下面列出了怎么用org.apache.commons.lang3.text.StrSubstitutor的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public ActionState execute(ActionContext context) {
String message = this.message;
if(message == null) {
message = context.getVariable(VAR_MESSAGE, String.class);
}
Logger logger = context.logger();
if(message == null) {
logger.warn("Unable to retrieve log message from context [{}]", context);
}
else if(logger.isInfoEnabled()) {
String logMessage = StrSubstitutor.replace(message, context.getVariables());
logger.info(logMessage);
}
return ActionState.IDLE;
}
@Override
public void execute(ActionContext context) {
String message = this.message;
if(message == null) {
message = context.getVariable(VAR_MESSAGE, String.class);
}
Logger logger = context.logger();
if(message == null) {
logger.warn("Unable to retrieve log message from context [{}]", context);
}
else if(logger.isInfoEnabled()) {
String logMessage = StrSubstitutor.replace(message, context.getVariables());
logger.info(logMessage);
}
}
public void onCreate(Map<String, Object> values) {
String name = (String) values.get(CreateRuleRequest.ATTR_NAME);
Map<String, Object> vars = new HashMap<String,Object>();
for(String key: values.keySet()) {
if(key.startsWith("var:")) {
vars.put(key.substring(4), values.get(key));
}
}
Oculus.showProgress(
template
.createRule(
placeId,
name,
StrSubstitutor.replace(template.getTemplate(), vars),
vars
)
.onFailure((e) -> result.setError(e))
.onSuccess((r) -> result.setValue(true)),
"Creating rule..."
);
}
public void onUpdate(Map<String, Object> values) {
Map<String, Object> vars = new HashMap<String,Object>();
for(String key: values.keySet()) {
if(key.startsWith("var:")) {
vars.put(key.substring(4), values.get(key));
}
}
Oculus.showProgress(result, "Updating rule...");
String templateId = (String) values.get(UpdateContextRequest.ATTR_TEMPLATE);
rule.setName((String) values.get(CreateRuleRequest.ATTR_NAME));
rule.setDescription(StrSubstitutor.replace(template.getTemplate(), vars));
rule
.commit()
.onFailure((e) -> result.setError(e))
.onSuccess((v) -> {
rule
.updateContext(vars, templateId)
.onFailure((e) -> result.setError(e))
.onSuccess((r) -> result.setValue(true))
;
})
;
}
@Override
public boolean incomingRequestPostProcessed(RequestDetails theRequestDetails, HttpServletRequest theRequest, HttpServletResponse theResponse) throws AuthenticationException {
log.trace("incomingRequestPostProcessed "+theRequest.getMethod());
Enumeration<String> headers = theRequest.getHeaderNames();
while (headers.hasMoreElements()) {
String header = headers.nextElement();
log.debug("Header = "+ header + "="+ theRequest.getHeader(header));
}
// Perform any string substitutions from the message format
StrLookup<?> lookup = new MyLookup(theRequest, theRequestDetails);
StrSubstitutor subs = new StrSubstitutor(lookup, "${", "}", '\\');
// Actually log the line
String myMessageFormat = "httpVerb[${requestVerb}] Source[${remoteAddr}] Operation[${operationType} ${idOrResourceName}] UA[${requestHeader.user-agent}] Params[${requestParameters}] RequestId[${requestHeader.x-request-id}] ForwardedFor[${requestHeader.x-forwarded-for}] ForwardedHost[${requestHeader.x-forwarded-host}] CorrelationId[] ProcessingTime[] ResponseCode[]";
String line = subs.replace(myMessageFormat);
log.info(line);
return true;
}
@Override
public void processingCompletedNormally(ServletRequestDetails theRequestDetails) {
// Perform any string substitutions from the message format
StrLookup<?> lookup = new MyLookup(theRequestDetails.getServletRequest(), theRequestDetails);
StrSubstitutor subs = new StrSubstitutor(lookup, "${", "}", '\\');
for (String header : theRequestDetails.getServletResponse().getHeaderNames()) {
log.debug("Header = " + header + "=" + theRequestDetails.getServletResponse().getHeader(header));
}
String myMessageFormat = "httpVerb[${requestVerb}] Source[${remoteAddr}] Operation[${operationType} ${idOrResourceName}] UA[${requestHeader.user-agent}] Params[${requestParameters}] RequestId[${requestHeader.x-request-id}] ForwardedFor[${requestHeader.x-forwarded-for}] ForwardedHost[${requestHeader.x-forwarded-host}] CorrelationId[${requestHeader.x-request-id}] ProcessingTime[${processingTimeMillis}]";
String line = subs.replace(myMessageFormat);
log.info(line+" ResponseCode["+theRequestDetails.getServletResponse().getStatus()+"]");
}
protected void createPullRequest(String baseBranch,String newBranch) throws IOException, GitAPIException, URISyntaxException {
GitHub github = RepairnatorConfig.getInstance().getGithub();
GHRepository originalRepository = github.getRepository(this.getInspector().getRepoSlug());
GHRepository ghForkedRepo = originalRepository.fork();
String base = baseBranch;
String head = ghForkedRepo.getOwnerName() + ":" + newBranch;
System.out.println("base: " + base + " head:" + head);
String travisURL = this.getInspector().getBuggyBuild() == null ? "" : Utils.getTravisUrl(this.getInspector().getBuggyBuild().getId(), this.getInspector().getRepoSlug());
Map<String, String> values = new HashMap<String, String>();
values.put("travisURL", travisURL);
values.put("tools", String.join(",", this.getConfig().getRepairTools()));
values.put("slug", this.getInspector().getRepoSlug());
if (prText == null) {
StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
this.prText = sub.replace(DEFAULT_TEXT_PR);
}
GHPullRequest pullRequest = originalRepository.createPullRequest(prTitle, head, base, this.prText);
String prURL = "https://github.com/" + this.getInspector().getRepoSlug() + "/pull/" + pullRequest.getNumber();
this.getLogger().info("Pull request created on: " + prURL);
this.getInspector().getJobStatus().addPRCreated(prURL);
}
public static <T> T loadConfigFromEnv(Class<T> configurationClass, final String path)
throws IOException
{
LOGGER.info("Parsing configuration file from {} ", path);
logProcessEnv();
final Path configPath = Paths.get(path);
final File file = configPath.toAbsolutePath().toFile();
final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
final StrSubstitutor sub = new StrSubstitutor(new StrLookup<Object>() {
@Override
public String lookup(String key) {
return System.getenv(key);
}
});
sub.setEnableSubstitutionInVariables(true);
final String conf = sub.replace(FileUtils.readFileToString(file));
return mapper.readValue(conf, configurationClass);
}
/**
* Given a url template, interpolate with keys and build the URI after adding query parameters
*
* <p>
* With url template: http://test.com/resource/(urn:${resourceId})/entities/(entity:${entityId}),
* keys: { "resourceId": 123, "entityId": 456 }, queryParams: { "locale": "en_US" }, the outpuT URI is:
* http://test.com/resource/(urn:123)/entities/(entity:456)?locale=en_US
* </p>
*
* @param urlTemplate url template
* @param keys data map to interpolate url template
* @param queryParams query parameters added to the url
* @return a uri
*/
public static URI buildURI(String urlTemplate, Map<String, String> keys, Map<String, String> queryParams) {
// Compute base url
String url = urlTemplate;
if (keys != null && keys.size() != 0) {
url = StrSubstitutor.replace(urlTemplate, keys);
}
try {
URIBuilder uriBuilder = new URIBuilder(url);
// Append query parameters
if (queryParams != null && queryParams.size() != 0) {
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
uriBuilder.addParameter(entry.getKey(), entry.getValue());
}
}
return uriBuilder.build();
} catch (URISyntaxException e) {
throw new RuntimeException("Fail to build uri", e);
}
}
/**
* Get the row count for a time range
*/
private int getCountForRange(TableCountProbingContext probingContext, StrSubstitutor sub,
Map<String, String> subValues, long startTime, long endTime) {
String startTimeStr = Utils.dateToString(new Date(startTime), SalesforceExtractor.SALESFORCE_TIMESTAMP_FORMAT);
String endTimeStr = Utils.dateToString(new Date(endTime), SalesforceExtractor.SALESFORCE_TIMESTAMP_FORMAT);
subValues.put("start", startTimeStr);
subValues.put("end", endTimeStr);
String query = sub.replace(PROBE_PARTITION_QUERY_TEMPLATE);
log.debug("Count query: " + query);
probingContext.probeCount++;
JsonArray records = getRecordsForQuery(probingContext.connector, query);
Iterator<JsonElement> elements = records.iterator();
JsonObject element = elements.next().getAsJsonObject();
return element.get("cnt").getAsInt();
}
/**
* Split a histogram bucket along the midpoint if it is larger than the bucket size limit.
*/
private void getHistogramRecursively(TableCountProbingContext probingContext, Histogram histogram, StrSubstitutor sub,
Map<String, String> values, int count, long startEpoch, long endEpoch) {
long midpointEpoch = startEpoch + (endEpoch - startEpoch) / 2;
// don't split further if small, above the probe limit, or less than 1 second difference between the midpoint and start
if (count <= probingContext.bucketSizeLimit
|| probingContext.probeCount > probingContext.probeLimit
|| (midpointEpoch - startEpoch < MIN_SPLIT_TIME_MILLIS)) {
histogram.add(new HistogramGroup(Utils.epochToDate(startEpoch, SECONDS_FORMAT), count));
return;
}
int countLeft = getCountForRange(probingContext, sub, values, startEpoch, midpointEpoch);
getHistogramRecursively(probingContext, histogram, sub, values, countLeft, startEpoch, midpointEpoch);
log.debug("Count {} for left partition {} to {}", countLeft, startEpoch, midpointEpoch);
int countRight = count - countLeft;
getHistogramRecursively(probingContext, histogram, sub, values, countRight, midpointEpoch, endEpoch);
log.debug("Count {} for right partition {} to {}", countRight, midpointEpoch, endEpoch);
}
/**
* Get a histogram for the time range by probing to break down large buckets. Use count instead of
* querying if it is non-negative.
*/
private Histogram getHistogramByProbing(TableCountProbingContext probingContext, int count, long startEpoch,
long endEpoch) {
Histogram histogram = new Histogram();
Map<String, String> values = new HashMap<>();
values.put("table", probingContext.entity);
values.put("column", probingContext.watermarkColumn);
values.put("greater", ">=");
values.put("less", "<");
StrSubstitutor sub = new StrSubstitutor(values);
getHistogramRecursively(probingContext, histogram, sub, values, count, startEpoch, endEpoch);
return histogram;
}
String substituteRelationships(String query, final Multimap<String, Object> valueMap) {
StrSubstitutor substitutor = new StrSubstitutor(new StrLookup<String>() {
@Override
public String lookup(String key) {
Collection<String> resolvedRelationshipTypes =
transform(valueMap.get(key), new Function<Object, String>() {
@Override
public String apply(Object input) {
if (input.toString().matches(".*(\\s).*")) {
throw new IllegalArgumentException(
"Cypher relationship templates must not contain spaces");
}
return curieUtil.getIri(input.toString()).orElse(input.toString());
}
});
return on("|").join(resolvedRelationshipTypes);
}
});
return substitutor.replace(query);
}
public static String applyLayout(Map<String, String> valuesMap, String templateName) throws IOException {
String templateString = "";
if (templates.containsKey(templateName)) {
templateString = templates.get(templateName);
} else {
// get the file
InputStream inputStream = Resources.class.getResourceAsStream("/templates/" + templateName);
// convert to string
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, Charset.defaultCharset());
templateString = writer.toString();
templates.put(templateName, templateString);
}
// substitution & return
StrSubstitutor sub = new StrSubstitutor(valuesMap);
return sub.replace(templateString);
}
@Override
public Resource getPluginFile(String siteId, String type, String name, String filename)
throws ContentNotFoundException {
String basePath = servicesConfig.getPluginFolderPattern(siteId);
if (StringUtils.isEmpty(basePath)) {
throw new IllegalStateException(
String.format("Site '%s' does not have an plugin folder pattern configured", siteId));
} else if (!StringUtils.contains(basePath, PLACEHOLDER_TYPE) ||
!StringUtils.contains(basePath, PLACEHOLDER_NAME)) {
throw new IllegalStateException(String.format(
"Plugin folder pattern for site '%s' does not contain all required placeholders", basePath));
}
Map<String, String> values = new HashMap<>();
values.put(PLACEHOLDER_TYPE, type);
values.put(PLACEHOLDER_NAME, name);
basePath = StrSubstitutor.replace(basePath, values);
String filePath = UrlUtils.concat(basePath, filename);
return contentService.getContentAsResource(siteId, filePath);
}
public static File newFile(String path) {
path = path.trim();
if (path.equals("~")) {
path = USER_HOME;
} else if (path.startsWith("~" + File.separator)) {
path = USER_HOME + path.substring(1);
}
path = new StrSubstitutor().replace(path);
return new File(path);
}
@Override
public String getOptional(String prop, String dft) {
String value = overrides.get(prop);
if (value != null)
return StrSubstitutor.replace(value, System.getenv());
else
return super.getOptional(prop, dft);
}
@Override
public String toString() {
return StrSubstitutor.replace(
delegate.getDescription(),
Collections.singletonMap(targetVariable, "all devices where " + selector.toString() + " and " + condition.toString())
);
}
@Override
public String toString() {
return StrSubstitutor.replace(
delegate.getDescription(),
Collections.singletonMap(targetVariable, "all devices where " + selector.toString())
);
}
public RuleDefinition create(UUID placeId, String name, Map<String, Object> variables) throws ValidationException {
RuleDefinition definition = new StatefulRuleDefinition();
definition.setName(name);
definition.setDescription(StrSubstitutor.replace(template, variables));
definition.setPlaceId(placeId);
definition.setRuleTemplate(getId());
definition.setVariables(variables);
return regenerate(definition);
}
@Override
public void write(Entry entry) throws IOException {
StrSubstitutor substitutor = new StrSubstitutor(new EntryLookup(entry), "${", "}", '\\');
boolean isProtocol = isProtocolMessage(entry);
String message = substitutor.replace(isProtocol ? protocolFormat : platformFormat) + "\n";
writer.write(message);
writer.flush();
}
/**
* Gets the policy knowledge base path URL.
*
* @param ruleParam the rule param
* @return the policy knowledge base path URL
*/
private static String getPolicyKnowledgeBasePathURL(Map<String,String> ruleParam){
String policyUrl = CommonUtils.getPropValue(PacmanSdkConstants.POLICY_URL_PATH);
Map<String, String> policyUrlMap = new HashMap<>();
policyUrlMap.put("RULE_ID", ruleParam.get(PacmanSdkConstants.RULE_ID));
policyUrl = StrSubstitutor.replace(policyUrl, policyUrlMap);
return policyUrl;
}
private String hello(String name) {
String configGreeting = ApplicationConfiguration.load(config()).getString("GREETING");
String greeting = configGreeting == null ? "Hello {name} from {hostname} with {version}" : configGreeting;
Map<String, String> values = new HashMap<String, String>();
values.put("name", name);
values.put("hostname", System.getenv().getOrDefault("HOSTNAME", "unknown"));
values.put("version", version);
return new StrSubstitutor(values, "{", "}").replace(greeting);
}
/**
* Formats the configured DN by replacing any properties it finds.
* @param dnPattern
* @param username
* @param request
*/
private String formatDn(String dnPattern, String username, ApiRequest request) {
Map<String, String> valuesMap = request.getHeaders().toMap();
valuesMap.put("username", username); //$NON-NLS-1$
StrSubstitutor sub = new StrSubstitutor(valuesMap);
return sub.replace(dnPattern);
}
@Override
public void initialize(Bootstrap<CassandraExecutorConfiguration> bootstrap) {
super.initialize(bootstrap);
bootstrap.addBundle(new Java8Bundle());
bootstrap.setConfigurationSourceProvider(
new SubstitutingSourceProvider(
bootstrap.getConfigurationSourceProvider(),
new StrSubstitutor(
new EnvironmentVariableLookup(false))));
}
private static void resolvePropertyReferences(Map<String, String> config) {
for (Map.Entry<String, String> entry : config.entrySet()) {
String entryValue = (String) ((Map.Entry) entry).getValue();
if (!StringUtils.isBlank(entryValue)) {
entry.setValue(StrSubstitutor.replace(entryValue, config));
}
}
}
/**
* Performs variable interpolation using the named arguments from an Action on a single String
*
* @param input The string possibly containing keys to be interpolated
* @param namedArgs The key/value pairs used for interpolation
* @param defaultArgs Default values for the named args, used if an interpolation key has no value given
*
* @return A copy of input with variable interpolation performed
*/
public static String interpolate(String input, final Map<String, String> namedArgs, final Map<String, String> defaultArgs) {
if (namedArgs == null || input == null) {
return input;
}
final Map<String, String> interpolationArgs = createFinalInterpolationMap(namedArgs, defaultArgs);
return StrSubstitutor.replace(input, interpolationArgs, PREFIX, SUFFIX);
}
@Before
public void before() {
when(confMgmt.getConfigurationValue(TenantConfigurationKey.POLLING_TIME_INTERVAL, String.class))
.thenReturn(TEST_POLLING_TIME_INTERVAL);
when(confMgmt.getConfigurationValue(TenantConfigurationKey.POLLING_OVERDUE_TIME_INTERVAL, String.class))
.thenReturn(TEST_POLLING_OVERDUE_TIME_INTERVAL);
substitutor = new StrSubstitutor(resolverUnderTest, StrSubstitutor.DEFAULT_PREFIX,
StrSubstitutor.DEFAULT_SUFFIX, StrSubstitutor.DEFAULT_ESCAPE);
}
@Test
@Description("Tests escape mechanism for placeholders (syntax is $${SOME_PLACEHOLDER}).")
public void handleEscapedPlaceholder() {
final String placeholder = "${OVERDUE_TS}";
final String escaptedPlaceholder = StrSubstitutor.DEFAULT_ESCAPE + placeholder;
final String testString = "lhs=lt=" + escaptedPlaceholder;
final String resolvedPlaceholders = substitutor.replace(testString);
assertThat("Escaped OVERDUE_TS should not be resolved!", resolvedPlaceholders, containsString(placeholder));
}
private String loadTemplate(final String path, final Map<String, String> values)
throws IOException {
final String string;
final ClassLoader loader = ManagedSetupConnection.class.getClassLoader();
try (final InputStream is = loader.getResourceAsStream(path)) {
if (is == null) {
throw new IOException("No such resource: " + path);
}
string = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
}
return new StrSubstitutor(values, "{{", "}}").replace(string);
}