private String getMessage(ApprovalStatusUpdateEvent event, IOrderApprovalMapping orderApproval, IUserAccount requester, IKiosk kiosk, IUserAccount updatedBy) { String message = getMessage(event.getStatus(), requester); Map<String, String> values = new HashMap<>(); values.put("approvalType", ApprovalUtils.getApprovalType(orderApproval.getApprovalType())); values.put("requestorName", requester.getFullName()); values.put("requestorPhone", requester.getMobilePhoneNumber()); values.put("eName", kiosk.getName()); values.put("eCity", kiosk.getCity()); values.put("orderId", event.getTypeId()); values.put("statusChangedTime", LocalDateUtil.format(event.getUpdatedAt(), requester.getLocale(), requester.getTimezone())); values.put("updatedBy", updatedBy.getFullName()); values.put("updatedByPhone", updatedBy.getMobilePhoneNumber()); StrSubstitutor sub = new StrSubstitutor(values); return sub.replace(message); }
public static void interpolate(File file) { String content; try { content = new String(Files.readAllBytes(file.toPath())); String replace = StrSubstitutor.replace(content, new ConfigurationMap( configuration())); Files.write(file.toPath(), replace.getBytes()); } catch (IOException e) { LOGGER.error( file + " interpolation error ", e); } }
/** * Notify user with "Edit stock inventories" right for the facility/program that * facility has stocked out of a product. * * @param stockCard StockCard for a product */ public void notifyStockEditors(StockCard stockCard) { Collection<UserDto> recipients = getEditors(stockCard); String subject = getMessage(EMAIL_ACTION_REQUIRED_SUBJECT); String content = getMessage(EMAIL_ACTION_REQUIRED_CONTENT); Map<String, String> valuesMap = getValuesMap(stockCard); StrSubstitutor sub = new StrSubstitutor(valuesMap); for (UserDto recipient : recipients) { if (recipient.getHomeFacilityId().equals(stockCard.getFacilityId()) && canBeNotified(recipient)) { valuesMap.put("username", recipient.getUsername()); notificationService.notify(recipient, sub.replace(subject), sub.replace(content)); } } }
@Override public String resolveJsonPaths(String jsonString, String scenarioState) { List<String> jsonPaths = getAllJsonPathTokens(jsonString); Map<String, String> paramMap = new HashMap<>(); jsonPaths.forEach(thisPath -> { try { paramMap.put(thisPath, JsonPath.read(scenarioState, thisPath)); } catch (Exception e) { throw new RuntimeException("\nJSON:" + jsonString + "\nPossibly comments in the JSON found or bad JSON path found: " + thisPath + ", Details: " + e); } }); StrSubstitutor sub = new StrSubstitutor(paramMap); return sub.replace(jsonString); }
protected String createStepWith(String stepName) { Map<String, String> parammap = new HashMap<>(); parammap.put("STEP.NAME", stepName); parammap.put("STEP.REQUEST", "{\n" + " \"customer\": {\n" + " \"firstName\": \"FIRST_NAME\"\n" + " }\n" + "}"); parammap.put("STEP.RESPONSE", "{\n" + " \"id\" : 10101\n" + "}"); StrSubstitutor sub = new StrSubstitutor(parammap); return sub.replace((new StepExecutionState()).getRequestResponseState()); }
protected void initHomeDir() { String homeDir = System.getProperty(DesktopAppContextLoader.HOME_DIR_SYS_PROP); if (StringUtils.isBlank(homeDir)) { homeDir = getDefaultHomeDir(); } homeDir = StrSubstitutor.replaceSystemProperties(homeDir); System.setProperty(DesktopAppContextLoader.HOME_DIR_SYS_PROP, homeDir); File file = new File(homeDir); if (!file.exists()) { boolean success = file.mkdirs(); if (!success) { System.out.println("Unable to create home dir: " + homeDir); System.exit(-1); } } if (!file.isDirectory()) { System.out.println("Invalid home dir: " + homeDir); System.exit(-1); } }
/** * Get the final filename of the generated .ass subtitle * * @return the name of the first subtitle */ private String getFileName() { String filename = this.userConfig.getFilename(); if (StringUtils.isEmpty(filename)) { filename = this.userConfig.getFirstSubtitle().getFileName(); filename = FilenameUtils.getBaseName(filename); } else { Map<String, String> substitutes = new HashMap<>(); String oneN = FilenameUtils.getBaseName(this.userConfig.getFirstSubtitle().getFileName()); String twoN = FilenameUtils.getBaseName(this.userConfig.getSecondSubtitle().getFileName()); substitutes.put("one", oneN); substitutes.put("two", twoN); substitutes.put("baseOne", StringUtils.substringBeforeLast(oneN, ".")); substitutes.put("baseTwo", StringUtils.substringBeforeLast(twoN, ".")); StrSubstitutor substitutor = new StrSubstitutor(substitutes); filename = substitutor.replace(filename); } return filename; }
@Override public Iterable<Record> serialize(Event event) { RecordKey key = new RecordKey(); Text value = new Text(); try { value.set(new String(event.getBody(), Charsets.UTF_8.name())); key.setHash(event.getHeaders().get(HEADER_TIMESTAMP).hashCode()); key.setType(event.getHeaders().get(HEADER_BATCH_TYPE)); key.setCodec(DFS_CODEC); key.setContainer(DFS_CONTAINER); key.setBatch(new StrSubstitutor(event.getHeaders(), "%{", "}").replace(DFS_BATCH_PATTERN)); key.setTimestamp(Long.parseLong(event.getHeaders().get(HEADER_TIMESTAMP))); key.setValid(true); } catch (Exception exception) { key.setValid(false); } return Collections.singletonList(new Record(key, value)); }
private void replaceProperties(Properties props) { StrSubstitutor substitutor = new StrSubstitutor(sqlProperties); // we must delete slash(it is added to the ${sql.url}) from connection string -> ${sql.url}/database if (props.getProperty(CONNECTION_URL_KEY) != null) { String connectionUrl = parseConnectionString(props.getProperty(CONNECTION_URL_KEY)); props.put(CONNECTION_URL_KEY, connectionUrl); } for (Map.Entry<Object, Object> entry : props.entrySet()) { if (entry.getValue() instanceof String) { String substituted = substitutor.replace(entry.getValue()); entry.setValue(substituted); } } }
private Function<File, GoArtifact> goArtifact(final UriConfig config, final Map<String, String> properties, final TaskExecutionContext context) { return new Function<File, GoArtifact>() { @Override public GoArtifact apply(File file) { GoArtifact artifact = new GoArtifact(file.getAbsolutePath(), artifactUri(file.getName())); artifact.properties(properties); return artifact; } private String artifactUri(String artifactName) { String uri = config.isFolder() ? config.uri() + "/" + artifactName : config.uri(); StrSubstitutor sub = new StrSubstitutor(context.environment().asMap()); return sub.replace(uri); } }; }
public static boolean impliesURI(String privilege, String request) { try { URI privilegeURI = new URI(new StrSubstitutor(System.getProperties()).replace(privilege)); URI requestURI = new URI(request); if (privilegeURI.getScheme() == null || privilegeURI.getPath() == null) { LOGGER.warn("Privilege URI " + request + " is not valid. Either no scheme or no path."); return false; } if (requestURI.getScheme() == null || requestURI.getPath() == null) { LOGGER.warn("Request URI " + request + " is not valid. Either no scheme or no path."); return false; } return PathUtils.impliesURI(privilegeURI, requestURI); } catch (URISyntaxException e) { LOGGER.warn("Request URI " + request + " is not a URI", e); return false; } }
/** * Loads the template with the specified name from the classloader and uses * it to templatize the properties using Apache Commons Lang's * StrSubstitutor and writes it to the response. * * @param res * the response to write to * @param template * the template file to load from the classpath * @param properties * the properties to templatize * @throws IOException */ private void renderBlock(HttpServletResponse res, String templateName, Map<String, String> properties) throws IOException { InputStream is = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); String template = null; try { is = getClass().getClassLoader().getResourceAsStream(templateName); if (is != null) { IOUtils.copy(is, baos); template = baos.toString(); } else { throw new IOException("Unable to load template " + templateName); } } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(baos); } StrSubstitutor sub = new StrSubstitutor(properties); res.getWriter().write(sub.replace(template)); }
private void testProperty( String propertyName, boolean containsSubstitution ) { String propertyValue = setup.get( 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 ); } }
private String getCommitMessage(final Project project) { String templateString = TemplateFileHandler.loadFile(project); Map<String, String> valuesMap = new HashMap<>(); String branchName = CommitMessage.extractBranchName(project); String[] branchParts = CommitMessage.splitBranchName(branchName); if (branchParts.length > 1) { valuesMap.put(Consts.TICKET, branchParts[1]); } valuesMap.put(Consts.SHORT_DESCRIPTION, ""); valuesMap.put(Consts.LONG_DESCRIPTION, ""); StrSubstitutor sub = new StrSubstitutor(valuesMap); return sub.replace(templateString); }
String getCommitMessage(Project project) { String templateString = TemplateFileHandler.loadFile(project); Map<String, String> valuesMap = new HashMap<>(); valuesMap.put(Consts.TICKET, getBranch()); valuesMap.put(Consts.SHORT_DESCRIPTION, panel.getShortDescription()); valuesMap.put(Consts.LONG_DESCRIPTION, getLongDescription(templateString)); StrSubstitutor sub = new StrSubstitutor(valuesMap); return sub.replace(templateString); }
/** @return the source for the generated file. */ public final String generate() { StrSubstitutor substitutor = new StrSubstitutor(templateValuesMap); String newFile = substitutor.replace(templateString); System.out.println(newFile); return newFile; }
/** * Expands variables in a command. * 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; }
/** * Expands all property place holders to actual values. For example * suppose you have a property defined as follows: root.dir=/usr/home * Expanding following ${root.dir}/somesubdir * will then give following result: /usr/home/somesubdir * * @param properties The properties, not null */ protected void expandPropertyValues(Properties properties) { for (Object key : properties.keySet()) { Object value = properties.get(key); try { String expandedValue = StrSubstitutor.replace(value, properties); properties.put(key, expandedValue); } catch (Exception e) { throw new UnitilsException("Unable to load unitils configuration. Could not expand property value for key: " + key + ", value " + value, e); } } }
@Override public String getTransformedMessage(FormatterData formatterData, String input) { final IJenkinsDescriptor jenkinsDescriptor = formatterData.getDataForType(IJenkinsDescriptor.class); if (jenkinsDescriptor != null) { final Map<String, String> vars = jenkinsDescriptor.getMasterEnvironmentVariables(); final StrSubstitutor strSubstitutor = new StrSubstitutor(vars); return strSubstitutor.replace(input); } else { return input; } }
@Override public String getTransformedMessage(FormatterData formatterData, String input) { final LocalVariables localVariables = formatterData.getDataForType(LocalVariables.class); if (localVariables != null) { final Map<String, String> vars = localVariables.getVariables(); final StrSubstitutor strSubstitutor = new StrSubstitutor(vars); return strSubstitutor.replace(input); } else { return input; } }
private String formatCommand(final String command, final Target target) { Map<Object, Object> valuesMap = new HashMap<>(); valuesMap.put("host", target.getHost()); valuesMap.put("module", target.getModule()); valuesMap.putAll(System.getProperties()); return new StrSubstitutor(valuesMap).replace(command); }
public String getResolvedScenarioState() { final String commaSeparatedStepResults = getAllStepsInStringList().stream() .map(i -> i) .collect(Collectors.joining(", ")); paramMap.put("STEP_REQUEST_RESPONSE_SECTION", commaSeparatedStepResults); return (new StrSubstitutor(paramMap)).replace(scenarioStateTemplate); }
@Test public void willHaveReqResp_resolved() throws Exception { Map<String, String> parammap = new HashMap<>(); parammap.put("STEP.NAME", "Step-1"); parammap.put("STEP.REQUEST", "{\n" + " \"customer\": {\n" + " \"firstName\": \"FIRST_NAME\"\n" + " }\n" + "}"); parammap.put("STEP.RESPONSE", "{\n" + " \"id\" : 10101\n" + "}"); StrSubstitutor sub = new StrSubstitutor(parammap); String resolvedString = sub.replace(stepExecutionState.getRequestResponseState()); JSONAssert.assertEquals(String.format("{%s}", resolvedString), "{\n" + " \"Step-1\": {\n" + " \"request\": {\n" + " \"customer\": {\n" + " \"firstName\": \"FIRST_NAME\"\n" + " }\n" + " },\n" + " \"response\": {\n" + " \"id\": 10101\n" + " }\n" + " }\n" + "}", true); }
private String handleInterpolation(String value) { StrSubstitutor substitutor = new StrSubstitutor(new StrLookup() { @Override public String lookup(String key) { String property = getSystemOrAppProperty(key); return property != null ? property : System.getProperty(key); } }); return substitutor.replace(value); }
private String getFormattedMessage(Message message) { String formattedMessage; if (messageFormat != null && messageFormat.length() > 0) { formattedMessage = StrSubstitutor.replace(messageFormat, message.getFields()); } else { formattedMessage = String.valueOf(message.getTimestamp()) + FIELD_SEPARATOR + message.getSource() + FIELD_SEPARATOR + message.getMessage(); } if (!formattedMessage.endsWith("\n")) { formattedMessage = formattedMessage.concat("\n"); } return formattedMessage; }
private String getFormattedPath(Message message) { String formattedPath = fileToWrite; if (fileToWrite.contains("${")) { formattedPath = StrSubstitutor.replace(formattedPath, message.getFields()); } if(fileToWrite.contains("%")) { formattedPath = String.format(formattedPath, message.getTimestamp().toDate()); } return formattedPath; }
/** * Parses a list of locations * @param params the current parameter map * @param locations a list of locations to parse * @throws IOException */ protected void parse(LinkedHashMap<String, Object> params, String[] locations) throws IOException { StrSubstitutor subs = new StrSubstitutor(new SystemPropertiesDelegatingStrLookup(params)); for (String location: locations) { parse(params, location, subs, 0); } }
@Override public JdbcUrl prepareConnectionUri(String connectionUrl) { String parsedConnection = StrSubstitutor.replace(parseConnectionString(connectionUrl), sqlProperties); try { return new JdbcUrl(parsedConnection); } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid connection url " + connectionUrl, e); } }
/** * * @param propertyKeys the collection of the properties; if null will return all properties * @return */ protected Properties getProperties(Collection<String> propertyKeys) { Map<String, String> envMap = System.getenv(); StrSubstitutor sub = new StrSubstitutor(envMap); Properties properties = new Properties(); for (Entry<Object, Object> entry : this.properties.entrySet()) { if (propertyKeys == null || propertyKeys.contains(entry.getKey())) { properties.put(entry.getKey(), sub.replace((String) entry.getValue())); } } return properties; }
public String getMetaAsString() { try (InputStream inputstream = resource.getInputStream()){ StrSubstitutor strSubstitutor = new StrSubstitutor(values, "%(", ")"); return strSubstitutor.replace(IOUtils.toString(inputstream)); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Read properties from filter file and substitute template place-holders. * * Typical output is to .../filter-dir/filter-name-no-extension/template-dir/template.name */ 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); } }
/** * Reads the {@link InputStream} and substitutes system properties. * * @return {@link Reader} */ private static Reader loadInputStream(InputStream propertiesStream) throws IOException { StringBuilder buff = new StringBuilder(); try (InputStreamReader isr = new InputStreamReader(propertiesStream, Charset.defaultCharset()); BufferedReader reader = new BufferedReader(isr)) { String line; while ((line = reader.readLine()) != null) { buff.append(line).append("\n"); } } return new StringReader(StrSubstitutor.replaceSystemProperties(buff.toString())); }
private static String buildUrl(String host, int port) { Map<String, String> valueMap = new HashMap<String, String>(); valueMap.put("HOST", host); valueMap.put("PORT", String.valueOf(port)); StrSubstitutor strSubstitutor = new StrSubstitutor(valueMap); return strSubstitutor.replace(JMX_URL); }
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); return sub.replace(temp); }
@Override public boolean handle(ApiRequest request) throws IOException { String id = request.getId(); if ( StringUtils.isBlank(id) ) { return false; } Account account = tokenManager.validateToken(id); if ( account == null ) { return false; } String url = getUrl(request); if ( url.contains("://localhost") ) { log.error("Don't use localhost to download the script, use the hostname or IP"); return false; } Map<String,String> tokens = new HashMap<String,String>(); tokens.put("CATTLE_URL", getUrl(request)); tokens.put("CATTLE_REGISTRATION_ACCESS_KEY", RegisterConstants.KIND_CREDENTIAL_REGISTRATION_TOKEN); tokens.put("CATTLE_REGISTRATION_SECRET_KEY", id); tokens.put("CATTLE_AGENT_IMAGE", IMAGE.get()); tokens.put("CATTLE_AGENT_IP", request.getClientIp()); String script = getScript(); if ( script == null ) { return false; } script = new StrSubstitutor(tokens).replace(script); request.getServletContext().getResponse().getOutputStream().write(script.getBytes("UTF-8")); return true; }
public String getConfigurationContent(String host, String confFileName) throws Exception { String fileContent = null; 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); }
public static String self(String pipelineName, String pipelineCounter, String stageName, String stageCounter) { return StrSubstitutor.replace("/api/stages/${pipeline_name}/${pipeline_counter}/${stage_name}/${stage_counter}", of( "pipeline_name", pipelineName, "pipeline_counter", pipelineCounter, "stage_name", stageName, "stage_counter", stageCounter)); }
public static String stageDetailTab(String pipelineName, int pipelineCounter, String stageName, int stageCounter) { return StrSubstitutor.replace("/pipelines/${pipeline_name}/${pipeline_counter}/${stage_name}/${stage_counter}", of( "pipeline_name", pipelineName, "pipeline_counter", pipelineCounter, "stage_name", stageName, "stage_counter", stageCounter)); }
@Activate @SuppressWarnings("squid:S1149") protected final void activate(ComponentContext ctx) { Dictionary<?, ?> config = ctx.getProperties(); color = PropertiesUtil.toString(config.get(PROP_COLOR), ""); cssOverride = PropertiesUtil.toString(config.get(PROP_CSS_OVERRIDE), ""); innerHTML = PropertiesUtil.toString(config.get(PROP_INNER_HTML), ""); innerHTML = new StrSubstitutor(StrLookup.systemPropertiesLookup()).replace(innerHTML); // Only write CSS variable if cssOverride or color is provided if (StringUtils.isNotBlank(cssOverride)) { css = cssOverride; } else if (StringUtils.isNotBlank(color)) { css = createCss(color); } titlePrefix = xss.encodeForJSString( PropertiesUtil.toString(config.get(PROP_TITLE_PREFIX), "").toString()); if (StringUtils.isNotBlank(css) || StringUtils.isNotBlank(titlePrefix)) { Dictionary<String, String> filterProps = new Hashtable<String, String>(); filterProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_PATTERN, "/"); filterProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT, "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=*)"); filterRegistration = ctx.getBundleContext().registerService(Filter.class.getName(), this, filterProps); } excludedWCMModes = PropertiesUtil.toStringArray(config.get(PROP_EXCLUDED_WCMMODES),DEFAULT_EXCLUDED_WCMMODES); }