org.apache.commons.lang.text.StrSubstitutor#replace ( )源码实例Demo

下面列出了org.apache.commons.lang.text.StrSubstitutor#replace ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: slr-toolkit   文件: TemplateTUDSCR.java
@Override
public String fillDocument(String document, SlrProjectMetainformation metainformation, DataProvider dataProvider,
		Map<Term, String> mainDimensions) {
	Map<String, String> valuesMap = new HashMap<String, String>();
	valuesMap.put(SLRVARIABLE_TITLE, metainformation.getTitle());
	valuesMap.put(SLRVARIABLE_ABSTRACT, metainformation.getProjectAbstract());
	valuesMap.put(SLRVARIABLE_KEYWORDS, metainformation.getKeywords());
	valuesMap.put(SLRVARIABLE_AUTHORS, this.generateAuthorSection(metainformation));
	valuesMap.put(SLRVARIABLE_TAXONOMYDESCRIPTION, metainformation.getTaxonomyDescription());
	valuesMap.put(SLRVARIABLE_STATISTICS, this.generateStatistics(dataProvider));
	
	double imageToTextWidthFactor = 1;
	valuesMap.put(SLRVARIABLE_DIMENSIONCHARTS, this.generateDimensionCharts(mainDimensions, imageToTextWidthFactor));

	StrSubstitutor sub = new StrSubstitutor(valuesMap);
	String resolvedString = sub.replace(document);

	return resolvedString;
}
 
源代码2 项目: slr-toolkit   文件: TemplateIEEEconf.java
@Override
public String fillDocument(String document, SlrProjectMetainformation metainformation, DataProvider dataProvider,
		Map<Term, String> mainDimensions) {
	Map<String, String> valuesMap = new HashMap<String, String>();
	valuesMap.put(SLRVARIABLE_TITLE, metainformation.getTitle());
	valuesMap.put(SLRVARIABLE_ABSTRACT, metainformation.getProjectAbstract());
	valuesMap.put(SLRVARIABLE_KEYWORDS, metainformation.getKeywords());
	valuesMap.put(SLRVARIABLE_AUTHORS, this.generateAuthorSection(metainformation));
	valuesMap.put(SLRVARIABLE_STATISTICS, this.generateStatistics(dataProvider));
	valuesMap.put(SLRVARIABLE_TAXONOMYDESCRIPTION, metainformation.getTaxonomyDescription());
	
	double imageToTextWidthFactor = 0.4;
	valuesMap.put(SLRVARIABLE_DIMENSIONCHARTS, this.generateDimensionCharts(mainDimensions, imageToTextWidthFactor));

	StrSubstitutor sub = new StrSubstitutor(valuesMap);
	String resolvedString = sub.replace(document);

	return resolvedString;
}
 
源代码3 项目: usergrid   文件: EmailFlowIT.java
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 );
    }
}
 
源代码4 项目: qaf   文件: MetaDataScanner.java
/**
 * 
 * @param xmlTest
 * @param parameter
 * @return
 */
public static String getParameter(XmlTest xmlTest, String parameter) {
	String paramValue = "";

	boolean overrideUsingSystemProp = System.getProperties().containsKey(parameter);

	Map<String, String> context = xmlTest.getAllParameters();
	context.keySet().removeAll(System.getProperties().keySet());

	if (overrideUsingSystemProp) {
		paramValue = System.getProperty(parameter);
	} else if (context.containsKey(parameter)) {
		paramValue = context.get(parameter);
	} else if (getBundle().containsKey(parameter)) {
		try {
			// unresolved value
			paramValue = (String) getBundle().configurationAt(parameter).getRoot().getValue();
		} catch (Exception e) {
			paramValue = getBundle().getString(parameter, "");
		}
	}
	paramValue = StrSubstitutor.replace(paramValue, context);
	paramValue = getBundle().getSubstitutor().replace(paramValue);
	return paramValue;
}
 
源代码5 项目: qaf   文件: BDDDefinitionHelper.java
public static String replaceParams(String stepCall, Map<String, Object> context) {
	stepCall = convertPrameter(stepCall);
	//don't resolve quoted parameters.
	stepCall = stepCall.replace("\"${", "\"<%{").replace("'${", "'<%{");
	//qaf#321 
	StrLookup lookup = new StrLookup() {
		public String lookup(String var) {

			Object prop = context.get(var);
			if(prop==null) {
				prop = getBundle().getSubstitutor().getVariableResolver().lookup(var);
			}
			return (prop != null) ? JSONUtil.toString(prop) : null;
		}
	};		
	StrSubstitutor interpol = new StrSubstitutor(lookup);
	stepCall = interpol.replace(stepCall);
	
	stepCall = stepCall.replace( "\"<%{","\"${").replace( "'<%{","'${");
	return stepCall;
}
 
源代码6 项目: zerocode   文件: StepExecutionStateTest.java
@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);
}
 
源代码7 项目: usergrid   文件: SwaggerServlet.java
public String loadTempate( String template ) {
    String templateString = readClasspathFileAsString( template );
    Map<String, String> valuesMap = new HashMap<String, String>();
    String basePath = properties != null ? properties.getProperty( "usergrid.api.url.base", SWAGGER_BASE_PATH ) :
                      SWAGGER_BASE_PATH;
    valuesMap.put( "basePath", basePath );
    StrSubstitutor sub = new StrSubstitutor( valuesMap );
    return sub.replace( templateString );
}
 
源代码8 项目: govpay   文件: CustomIuv.java
public String buildPrefix(Applicazione applicazione, String prefix, Map<String, String> values) {
	if(prefix == null) return "";
	
	StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
	String result = sub.replace(prefix);

	return result;
}
 
源代码9 项目: ankush   文件: GangliaDeployer.java
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);
}
 
private String resolvePropertyValue(String spec, MessageContext msgCtxt) {
    if (spec.indexOf('{') > -1 && spec.indexOf('}')>-1) {
        // Replace ALL curly-braced items in the spec string with
        // the value of the corresponding context variable.
        TemplateString ts = new TemplateString(spec);
        Map<String,String> valuesMap = new HashMap<String,String>();
        for (String s : ts.variableNames) {
            valuesMap.put(s, (String) msgCtxt.getVariable(s));
        }
        StrSubstitutor sub = new StrSubstitutor(valuesMap);
        String resolvedString = sub.replace(ts.template);
        return resolvedString;
    }
    return spec;
}
 
源代码11 项目: zerocode   文件: CalculatorTest.java
@Test
void testParamResolver() {
    String WelcomeMessage="Hello ${firstName} ${lastName}!";
    Map<String, String> valuesMap = new HashMap<>();
    valuesMap.put("firstName", "Peter");
    valuesMap.put("lastName", "Osi");
    StrSubstitutor sub = new StrSubstitutor(valuesMap);
    String message = sub.replace(WelcomeMessage);
    assertEquals("Hello Peter Osi!", message);
}
 
源代码12 项目: zerocode   文件: TokenUtils.java
public static String resolveKnownTokens(String requestJsonOrAnyString) {
    Map<String, Object> paramMap = new HashMap<>();

    final List<String> testCaseTokens = getTestCaseTokens(requestJsonOrAnyString);
    testCaseTokens.stream().distinct().forEach(runTimeToken -> {
        populateParamMap(paramMap, runTimeToken);
    });

    StrSubstitutor sub = new StrSubstitutor(paramMap);

    return sub.replace(requestJsonOrAnyString);
}
 
源代码13 项目: zerocode   文件: FieldTypeConversionUtilsTest.java
@Test
public void testSubstituted_incorrectTypeException() throws IOException {
    String originalJson = "{\n" +
            "    \"found\": true,\n" +
            "    \"currentAddress\":{\n" +
            "      \"line1\": \"address line1\",  \n" +
            "      \"line2\": \"address line2\"  \n" +
            "    },\n" +
            "    \"results\": [\n" +
            "        {\n" +
            "            \"id\": 1,\n" +
            "            \"name\": \"Foo\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"id\": 2.35,\n" +
            "            \"name\": \"Bar\",\n" +
            "            \"isActive\": false\n" +
            "        }\n" +
            "    ]\n" +
            "}";

    String jsonViaPath = "{\n" +
            "    \"found\": \"(boolean)${$.found}\",\n" +
            "    \"currentAddress\":{\n" +
            "      \"line1\": \"address line1\",\n" +
            "      \"line2\": \"address line2\"\n" +
            "    }," +
            "    \"results\": [\n" +
            "        {\n" +
            "            \"id\": \"(int)${$.results[0].id}\",\n" +
            "            \"name\": \"Foo - ${$.results[0].id} - ${$.found}\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"id\": \"(float)${$.results[1].id}\",\n" +
            "            \"name\": \"Bar - ${$.results[1].id}\",\n" +
            "            \"isActive\": \"(int)${$.results[1].isActive}\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";

    List<String> tokens = new ArrayList<>();
    tokens.add("$.found");
    tokens.add("$.results[0].id");
    tokens.add("$.results[1].id");
    tokens.add("$.results[1].isActive");

    Map<String, Object> paramMap = new HashMap<>();

    tokens.forEach(thisPath -> {
        Object pathValue = JsonPath.read(originalJson, thisPath);
        paramMap.put(thisPath, pathValue);
    });

    StrSubstitutor sub = new StrSubstitutor(paramMap);
    String resolvedJson = sub.replace(jsonViaPath);

    Map<String, Object> stepMap = mapper.readValue(resolvedJson, new TypeReference<Map<String, Object>>() {
    });

    expectedException.expectMessage("Can not convert '(int)false");
    expectedException.expect(RuntimeException.class);
    digTypeCast(stepMap);
}
 
源代码14 项目: flash-waimai   文件: MessageService.java
private String getContent(String template, Map<String, Object> dataMap) {
    return StrSubstitutor.replace(template, dataMap);
}
 
源代码15 项目: pacbot   文件: S3AccessLogsRule.java
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam
 * 
 ************** Following are the Rule Parameters********* <br><br>
 *
 *ruleKey : check-for-s3-access-logs<br><br>
 *
 *esS3PubAccessIssueUrl : Enter the S3 Public Access ES issue URL <br><br>
 *
 *s3PublicAccessRuleId : Enter the ruleId which is s3 with public access with read\write<br><br>
 * 
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */

public RuleResult execute(final Map<String, String> ruleParam,Map<String, String> resourceAttributes) {
	logger.debug("========S3AccessLogsRule started=========");
	Annotation annotation = null;
	String esS3PubAccessIssueUrl = null;
	List<LinkedHashMap<String, Object>> issueList = new ArrayList<>();
	LinkedHashMap<String, Object> issue = new LinkedHashMap<>();
	String s3Bucket = ruleParam.get(PacmanRuleConstants.RESOURCE_ID);
	String destinationBucketForAutoFix = ruleParam.get(PacmanRuleConstants.DESTINATION_BUCKET_AUTOFIX);
	String accessLogsEnabledRegions = ruleParam.get(PacmanRuleConstants.ACCESSLOGS_ENABLED_REGIONS);
	String splitter = ruleParam.get(PacmanSdkConstants.SPLITTER_CHAR);
	String region = resourceAttributes.get(PacmanRuleConstants.REGION_ATTR);
	String accountId = resourceAttributes.get(PacmanRuleConstants.ACCOUNTID);
	String targetType = resourceAttributes.get(PacmanRuleConstants.ENTITY_TYPE);
	String isLoggingEnabled = resourceAttributes.get(PacmanRuleConstants.IS_S3_ACCESS_LOGS_ENABLED);

	String description = targetType+ " has not enabled the server access logs for " + s3Bucket;
	String s3PublicAccessRuleId = ruleParam.get(PacmanRuleConstants.S3_PUBLIC_ACCESS_RULE_ID);
       Map<String, String> data = new HashMap<>();
       data.put("ACCOUNT_ID", accountId);
       data.put("REGION", region);
       destinationBucketForAutoFix = StrSubstitutor.replace(destinationBucketForAutoFix, data);

	String pacmanHost = PacmanUtils.getPacmanHost(PacmanRuleConstants.ES_URI);
	logger.debug("========pacmanHost {}  =========", pacmanHost);

	if (!StringUtils.isNullOrEmpty(pacmanHost)) {
		esS3PubAccessIssueUrl = ruleParam.get(PacmanRuleConstants.ES_S3_PUBLIC_ACCESS_ISSUE_URL);
		esS3PubAccessIssueUrl = pacmanHost + esS3PubAccessIssueUrl;
	}

	MDC.put("executionId", ruleParam.get("executionId"));
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID));

	if (!PacmanUtils.doesAllHaveValue(esS3PubAccessIssueUrl,s3PublicAccessRuleId,destinationBucketForAutoFix,accessLogsEnabledRegions,splitter)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}
	try {

		Map<String, Object> mustFilter = new HashMap<>();
		mustFilter.put(PacmanRuleConstants.RESOURCE_ID, s3Bucket);
		mustFilter.put(PacmanRuleConstants.RULE_ID, s3PublicAccessRuleId);
		mustFilter.put(PacmanRuleConstants.ACCOUNTID, accountId);
		mustFilter.put(PacmanRuleConstants.REGION_ATTR, region);
		HashMultimap<String, Object> shouldFilter = HashMultimap.create();
		Map<String, Object> mustTermsFilter = new HashMap<>();
		shouldFilter.put(PacmanSdkConstants.ISSUE_STATUS_KEY,PacmanSdkConstants.STATUS_OPEN);
		shouldFilter.put(PacmanSdkConstants.ISSUE_STATUS_KEY,PacmanRuleConstants.STATUS_EXEMPTED);

		Set<String> resourceSet = PacmanUtils.getValueFromElasticSearchAsSet(esS3PubAccessIssueUrl,mustFilter, shouldFilter, mustTermsFilter,"_resourceid", null);
			logger.debug("======issueDetails : {}", resourceSet);	
		
			logger.debug("======isLoggingEnabled : {}", Boolean.parseBoolean(isLoggingEnabled));	
		
		if (resourceSet.isEmpty() && !Boolean.parseBoolean(isLoggingEnabled)) {
			String destinationBucketName = resourceAttributes.get(PacmanRuleConstants.DESTINATION_BUCKET_NAME);
			String logFilePrefix = resourceAttributes.get(PacmanRuleConstants.LOG_FILE_PREFIX);
			annotation = Annotation.buildAnnotation(ruleParam,Annotation.Type.ISSUE);
			annotation.put(PacmanSdkConstants.DESCRIPTION, description);
			annotation.put(PacmanRuleConstants.SEVERITY,ruleParam.get(PacmanRuleConstants.SEVERITY));
			annotation.put(PacmanRuleConstants.CATEGORY,ruleParam.get(PacmanRuleConstants.CATEGORY));
			destinationBucketForAutoFix = destinationBucketForAutoFix.replace("ACCOUNT_ID", accountId);
			destinationBucketForAutoFix = destinationBucketForAutoFix.replace("REGION", region);
			annotation.put(PacmanRuleConstants.DESTINATION_BUCKET_AUTOFIX,destinationBucketForAutoFix);
			annotation.put(PacmanRuleConstants.ACCESSLOGS_ENABLED_REGIONS,accessLogsEnabledRegions);
			annotation.put(PacmanSdkConstants.SPLITTER_CHAR,splitter);
			issue.put(PacmanRuleConstants.VIOLATION_REASON, description);
			issue.put(PacmanRuleConstants.IS_S3_ACCESS_LOGS_ENABLED, isLoggingEnabled);
			issue.put(PacmanRuleConstants.DESTINATION_BUCKET_NAME, destinationBucketName);
			issue.put(PacmanRuleConstants.LOG_FILE_PREFIX, logFilePrefix);
			issueList.add(issue);
			annotation.put("issueDetails", issueList.toString());
			logger.debug("========S3AccessLogsRule ended with an annotation {} : =========",annotation);
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
		}
	} catch (Exception e) {
		logger.error(e.getMessage());
		throw new RuleExecutionFailedExeption(e.getMessage());
	}
	logger.debug("========S3AccessLogsRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
源代码16 项目: kylin   文件: KylinConfigBase.java
protected String getOptional(String prop, String dft) {

        final String property = System.getProperty(prop);
        return property != null ? StrSubstitutor.replace(property, System.getenv())
                : StrSubstitutor.replace(properties.getProperty(prop, dft), System.getenv());
    }
 
源代码17 项目: qaf   文件: TestArgFormatter.java
@Override
public String format(Object value, Map<String, Object> context) {
	value = StrSubstitutor.replace(value, context);
	value = ConfigurationManager.getBundle().getSubstitutor().replace(value);
	return value+"formatted";
}
 
源代码18 项目: zerocode   文件: ZeroCodeAssertionsProcessorImpl.java
@Override
public String resolveKnownTokensAndProperties(String requestJsonOrAnyString) {
    Map<String, Object> paramMap = new HashMap<>();

    final List<String> testCaseTokens = getTestCaseTokens(requestJsonOrAnyString);

    testCaseTokens.forEach(runTimeToken -> {
        populateParamMap(paramMap, runTimeToken);

        if (isPropertyKey(runTimeToken)) {
            paramMap.put(runTimeToken, properties.get(runTimeToken));
        }

    });

    StrSubstitutor sub = new StrSubstitutor(paramMap);

    return sub.replace(requestJsonOrAnyString);
}
 
源代码19 项目: zerocode   文件: ZeroCodeAssertionsProcessorImpl.java
@Override
public String resolveJsonPaths(String jsonString, String scenarioState) {
    List<String> jsonPaths = getAllJsonPathTokens(jsonString);
    Map<String, String> paramMap = new HashMap<>();
    final String LEAF_VAL_REGEX = "\\$[.](.*)\\$VALUE\\[\\d\\]";

    jsonPaths.forEach(thisPath -> {
        try {

            if (thisPath.endsWith(RAW_BODY)) {
                /**
                 * In case the rawBody is used anywhere in the steps as $.step_name.response.rawBody,
                 * then it must be escaped as the content was not a simple JSON string to be able
                 * to convert to json. Hence without throwing exception, treat as string content.
                 *
                 * Use escapeJava, do not use escapeJavaScript, as escapeJavaScript also escapes single quotes
                 * which in turn throws Jackson Exception
                 */
                String escapedString = escapeJava(JsonPath.read(scenarioState, thisPath));
                paramMap.put(thisPath, escapedString);

            } else if (thisPath.matches(LEAF_VAL_REGEX) || thisPath.endsWith($VALUE)) {

                resolveLeafOnlyNodeValue(scenarioState, paramMap, thisPath);

            } else {
                Object jsonPathValue = JsonPath.read(scenarioState, thisPath);
                if (isPathValueJson(jsonPathValue)) {
                    final String jsonAsString = mapper.writeValueAsString(jsonPathValue);
                    String escapedJsonString = escapeJava(jsonAsString);
                    paramMap.put(thisPath, escapedJsonString);

                } else {

                    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 + ",\nDetails: " + e);
        }
    });

    StrSubstitutor sub = new StrSubstitutor(paramMap);

    return sub.replace(jsonString);
}
 
源代码20 项目: zerocode   文件: StepExecutionState.java
public String getResolvedStep() {
    StrSubstitutor sub = new StrSubstitutor(paramMap);
    return sub.replace(requestResponseState);
}
 
 同类方法