下面列出了org.apache.commons.lang.text.StrSubstitutor#replace ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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;
}
@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;
}
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 );
}
}
/**
*
* @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;
}
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;
}
@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);
}
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 );
}
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;
}
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;
}
@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);
}
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);
}
@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);
}
private String getContent(String template, Map<String, Object> dataMap) {
return StrSubstitutor.replace(template, dataMap);
}
/**
* 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);
}
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());
}
@Override
public String format(Object value, Map<String, Object> context) {
value = StrSubstitutor.replace(value, context);
value = ConfigurationManager.getBundle().getSubstitutor().replace(value);
return value+"formatted";
}
@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);
}
@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);
}
public String getResolvedStep() {
StrSubstitutor sub = new StrSubstitutor(paramMap);
return sub.replace(requestResponseState);
}