本文整理汇总了Java中org.apache.commons.lang3.text.StrSubstitutor类的典型用法代码示例。如果您正苦于以下问题:Java StrSubstitutor类的具体用法?Java StrSubstitutor怎么用?Java StrSubstitutor使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
StrSubstitutor类属于org.apache.commons.lang3.text包,在下文中一共展示了StrSubstitutor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: incomingRequestPostProcessed
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
@Override
public boolean incomingRequestPostProcessed(RequestDetails theRequestDetails, HttpServletRequest theRequest, HttpServletResponse theResponse) throws AuthenticationException {
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;
}
示例2: processingCompletedNormally
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
@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()+"]");
}
示例3: loadConfigFromEnv
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
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);
}
示例4: processRequest
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
@NotNull
public final Object processRequest(@NotNull Request request, @NotNull Response response) {
final Map<String, String> params = buildParameterValues(request);
LOG.info("request body:{}", request.body());
//find the correct simulation to use
WSSimulation wsSimulation = loadSimulation(request);
if (wsSimulation != null) {
wsSimulation.wsSimulationContext.simulationInvoked(request.body());
latencyCheck(wsSimulation);
LOG.info("returning with status code:{}", wsSimulation.responseCode);
response.status(wsSimulation.responseCode);
if (StringUtils.isNotEmpty(wsSimulation.response))
return new StrSubstitutor(params).replace(loadResponse(wsSimulation));
}
return "";
}
示例5: awardPlayer
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
@Override
public boolean awardPlayer(Player player) {
Optional<String> commandTemplateOpt = Util.safeGetString(this.data, "command");
if (!commandTemplateOpt.isPresent()) {
this.plugin.getLogger().error("No command specified. Aborting.");
return false;
}
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("playerName", player.getName());
valuesMap.put("playerId", player.getUniqueId().toString());
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String command = sub.replace(commandTemplateOpt.get());
this.plugin.getLogger().info("Executing command award as console: " + command);
CommandResult result = Sponge.getCommandManager().process(Sponge.getServer().getConsole(), command);
return result.getSuccessCount().orElse(0) > 0;
}
示例6: resolveConfigurationEntry
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
private Pair<String, Object> resolveConfigurationEntry(Configuration configuration, String prefix, StrSubstitutor strSubstitutor)
{
Optional<Object> optionalValue = configuration.get(prefix);
if (optionalValue.isPresent()) {
Object value = optionalValue.get();
if (value instanceof String) {
return Pair.of(prefix, strSubstitutor.replace(value));
}
else if (value instanceof List) {
List<String> resolvedList = new ArrayList<String>();
for (String entry : (List<String>) value) {
resolvedList.add(strSubstitutor.replace(entry));
}
return Pair.of(prefix, resolvedList);
}
else {
return Pair.of(prefix, value);
}
}
else {
return Pair.of(prefix, resolveVariables(configuration.getSubconfiguration(prefix), strSubstitutor));
}
}
示例7: postProcessScript
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
@Override
public String[] postProcessScript(String[] chaosScriptsContent) {
final List<String> commands = new ArrayList<>();
for (Integer port : ports) {
Map<String, Object> params = new HashMap<>();
params.put("port", port);
StrSubstitutor substitutor = new StrSubstitutor(params);
for (String chaosScriptContent : chaosScriptsContent) {
commands.add(substitutor.replace(chaosScriptContent));
}
}
return commands.toArray(new String[commands.size()]);
}
示例8: getLocations
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
public static List<String> getLocations(int maximumLocationAgeInDays){
List<String> locations = new ArrayList<String>();
DateTime minDate = new DateTime().withZone(DateTimeZone.UTC).minusDays(maximumLocationAgeInDays);
for(int daysDiff = 0; daysDiff < maximumLocationAgeInDays + 1; daysDiff++){
for(int hour : HOURS){
DateTime time = new DateTime().withZone(DateTimeZone.UTC).withMillisOfDay(0).minusDays(daysDiff).withHourOfDay(hour);
if(time.isBeforeNow() && time.isAfter(minDate)){
Map<String, String> valuesMap = new HashMap<String, String>();
valuesMap.put("date", DATE_FORMATTER.print(time));
valuesMap.put("hour", HOUR_FORMATTER.print(time));
StrSubstitutor substitutor = new StrSubstitutor(valuesMap);
String url = DODSNetcdfFile.canonicalURL(substitutor.replace(BASE_LOCATION));
locations.add(url);
}
}
}
return locations;
}
示例9: resolve
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
private String resolve(final String configurationWithPlaceholders, final Properties placeholderValues)
throws IOException {
return new StrSubstitutor(
new StrLookup<String>() {
@Override
public String lookup(final String key) {
Preconditions.checkNotNull(placeholderValues.getProperty(key),
"placeholder: \"${%s}\" was not assigned",
key);
return placeholderValues.getProperty(key);
}
},
"${",
"}",
'#')
.replace(configurationWithPlaceholders);
}
示例10: buildQueryFieldTemplate
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
private static String buildQueryFieldTemplate(String q) {
String sq;
String template = null;
String[] split = q.split(":");
Map<String, String> map = new HashMap<>();
map.put("field", split[0]);
String value = null;
String[] comma = split[1].split(",");
if (comma.length > 1) {
template = FIELD_Q_IN_TMPL;
value = "\"" + StringUtils.join(comma, "\",\"") + "\"";
} else {
template = FIELD_Q_EQ_TMPL;
value = split[1];
}
map.put("value", value);
StrSubstitutor sub = new StrSubstitutor(map);
sq = sub.replace(template);
return sq;
}
示例11: build
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
@Override
protected void build(BufferedWriter writer, SideBySideView view) throws IOException {
Map<String, String> variables = buildVariables(view);
final List<String> lines = templateLoader.loadTemplateAsLines(TemplateLoader.MAIN_TEMPLATE);
final StrSubstitutor sub = new StrSubstitutor(variables, prefix, suffix);
for (String line : lines) {
if(line.contains(getRowsVariable())){
rowBuilder.build(writer, view);
}else {
String content = sub.replace(line);
writer.write(content);
writer.write("\n");
}
}
}
示例12: buildURI
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
/**
* 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);
}
}
示例13: getCountForRange
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
/**
* 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();
}
示例14: getHistogramRecursively
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
/**
* 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);
}
示例15: getHistogramByProbing
import org.apache.commons.lang3.text.StrSubstitutor; //导入依赖的package包/类
/**
* 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;
}