下面列出了怎么用org.apache.commons.lang.text.StrSubstitutor的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* This method selects a filepath of an appender.
*
* @param appender The appender name
* @param replaceVariables If true all variables(${var}) in the file path
* will be substituted
*
* @return The log file path
*/
public String getFile(String appender, boolean replaceVariables) {
String result = null;
Element elem = xml.getChild("appender", "name", appender);
if (elem != null) {
List childs = elem.getChildren("param");
Iterator children = childs.iterator();
while (children.hasNext()) {
Element child = (Element) children.next();
if (child.getAttributeValue("name").equals("File")) {
result = child.getAttributeValue("value");
}
}
if (replaceVariables) {
result = StrSubstitutor.replaceSystemProperties(result);
}
}
return result;
}
/**
*
* @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;
}
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());
}
@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;
}
@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.8;
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;
}
@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_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;
}
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;
}
}
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 void importLdif() throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("hostname", this.bindHost);
if (this.ldapSaslPrincipal != null) {
map.put("ldapSaslPrincipal", this.ldapSaslPrincipal);
}
// Find LDIF file on filesystem or classpath ( if it's like classpath:ldap/users.ldif )
InputStream is = FindFile.findFile(ldifFile);
if (is == null) {
throw new IllegalStateException("LDIF file not found on classpath or on file system. Location was: " + ldifFile);
}
final String ldifContent = StrSubstitutor.replace(StreamUtil.readString(is), map);
log.info("Content of LDIF: " + ldifContent);
final SchemaManager schemaManager = directoryService.getSchemaManager();
importLdifContent(directoryService, ldifContent);
}
/**
*
* @param propertyKeys the collection of the properties; if null will return all properties
* @return properties which contained in propertyKeys
*/
protected Properties getProperties(Collection<String> propertyKeys) {
Map<String, String> envMap = System.getenv();
StrSubstitutor sub = new StrSubstitutor(envMap);
Properties filteredProperties = new Properties();
for (Entry<Object, Object> entry : this.properties.entrySet()) {
if (propertyKeys == null || propertyKeys.contains(entry.getKey())) {
filteredProperties.put(entry.getKey(), sub.replace((String) entry.getValue()));
}
}
return filteredProperties;
}
public String resolve(Map<String, String> environmentVariables) throws UnresolvedPropertyException {
String evaluatedProperty = StrSubstitutor.replace(property, environmentVariables);
if(ENVIRONMENT_VARIABLE_PATTERN.matcher(evaluatedProperty).find()) {
throw new UnresolvedPropertyException(evaluatedProperty, propertyName);
}
return evaluatedProperty;
}
/**
* @param timeFormat example : "yyyy-MM-dd HH:mm:ss"
* */
public static String substitute(String str, String timeFormat) {
final SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
final String formatteddDate = sdf.format(new Date());
final Map valuesMap = new HashMap();
valuesMap.put("uuid", UUID.randomUUID().toString());
valuesMap.put("now", formatteddDate);
valuesMap.put(timeFormat, formatteddDate);
final StrSubstitutor sub = new StrSubstitutor(valuesMap);
return sub.replace(str);
}
/**
* @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 MCRConfiguration2#getString(String)}.
* If the property is not defined no 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(MCRConfiguration2.getPropertiesMap());
String expandedCommand = strSubstitutor.replace(command);
if (!expandedCommand.equals(command)) {
LOGGER.info("{} --> {}", command, expandedCommand);
}
return expandedCommand;
}
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);
}
private static Map<?, ?> getParameters(TestNGScenario scenario) {
Map<String, Object> methodParameters = scenario.getMetaData();
String description = scenario.getDescription();
if (isNotBlank(description) && JSONUtil.isValidJsonString(description)) {
Map<String, Object> paramsFromDesc = new JSONObject(description).toMap();
description =(String) paramsFromDesc.remove("description");
methodParameters.putAll(paramsFromDesc);
scenario.setDescription(description);
}
// highest priority test data overridden through property with test name prefix
String testParameters = getConfigParameters(scenario.getMethodName() + ".testdata");
if(isBlank(testParameters)){
//second priority overridden through property "global.testdata"
testParameters = getConfigParameters("global.testdata");
if(isBlank(testParameters)){
//default provided with test case
testParameters = new JSONObject(methodParameters).toString();
}
}
String cls = scenario.getConstructorOrMethod().getMethod().getDeclaringClass().getSimpleName();
String mtd = scenario.getMethodName();
testParameters = testParameters.replace("${class}", cls);
testParameters = testParameters.replace("${method}", mtd);
testParameters = StrSubstitutor.replace(testParameters, methodParameters);
testParameters = getBundle().getSubstitutor().replace(testParameters);
try {
return new JSONObject(testParameters).toMap();
} catch (JsonSyntaxException e) {
// old way of setting global data or testdata using key=value
return StringUtil.toMap(testParameters, true);
}
}
@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 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);
}
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 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 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;
}
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;
}
private String formatNameInternal(final Address address, final String format) {
if (address != null) {
final Map<String, String> values = new HashMap<>();
values.put("salutation", StringUtils.defaultString(address.getSalutation()));
values.put("firstname", StringUtils.defaultString(address.getFirstname()));
values.put("middlename", StringUtils.defaultString(address.getMiddlename()));
values.put("lastname", StringUtils.defaultString(address.getLastname()));
return new StrSubstitutor(values, "{{", "}}").replace(format);
}
return StringUtils.EMPTY;
}
private String formatNameInternal(final Customer customer, final String format) {
if (customer != null) {
final Map<String, String> values = new HashMap<>();
values.put("salutation", StringUtils.defaultString(customer.getSalutation()));
values.put("firstname", StringUtils.defaultString(customer.getFirstname()));
values.put("middlename", StringUtils.defaultString(customer.getMiddlename()));
values.put("lastname", StringUtils.defaultString(customer.getLastname()));
return new StrSubstitutor(values, "{{", "}}").replace(format);
}
return StringUtils.EMPTY;
}
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;
}
/**
* @param propertyKeys the collection of the properties; if null will return all properties
* @return properties which contained in propertyKeys
*/
protected Properties getProperties(Collection<String> propertyKeys) {
Map<String, String> envMap = System.getenv();
StrSubstitutor sub = new StrSubstitutor(envMap);
Properties filteredProperties = new Properties();
for (Entry<Object, Object> entry : this.properties.entrySet()) {
if (propertyKeys == null || propertyKeys.contains(entry.getKey())) {
filteredProperties.put(entry.getKey(), sub.replace((String) entry.getValue()));
}
}
return filteredProperties;
}
@Test
public void testStringSubstitution() throws MalformedURLException {
Map<String, String> subMap = new HashMap<>();
String afterChange = "afterChange";
subMap.put(SlrLatexTemplate.SLRVARIABLE_ABSTRACT, afterChange);
String dontChangeMeString = "dontChangeMe";
String oldString = "${" + SlrLatexTemplate.SLRVARIABLE_ABSTRACT + "}" + "," + dontChangeMeString;
StrSubstitutor sub = new StrSubstitutor(subMap);
String newString = sub.replace(oldString);
assertFalse(newString.contains(SlrLatexTemplate.SLRVARIABLE_ABSTRACT));
assertTrue(newString.contains(dontChangeMeString));
}