当前位置: 首页>>代码示例>>Java>>正文


Java StrSubstitutor类代码示例

本文整理汇总了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;
}
 
开发者ID:nhsconnect,项目名称:careconnect-reference-implementation,代码行数:21,代码来源:ServerInterceptor.java

示例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()+"]");
}
 
开发者ID:nhsconnect,项目名称:careconnect-reference-implementation,代码行数:17,代码来源:ServerInterceptor.java

示例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);
}
 
开发者ID:mesosphere,项目名称:dcos-commons,代码行数:20,代码来源:YAMLConfigurationLoader.java

示例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 "";
}
 
开发者ID:CognitiveJ,项目名称:wssimulator,代码行数:18,代码来源:BaseHandler.java

示例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;
}
 
开发者ID:BadgeUp,项目名称:badgeup-sponge-client,代码行数:21,代码来源:CommandAward.java

示例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));
    }
}
 
开发者ID:prestodb,项目名称:tempto,代码行数:24,代码来源:ConfigurationVariableResolver.java

示例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()]);
}
 
开发者ID:arquillian,项目名称:arquillian-cube-q,代码行数:19,代码来源:BlockPortSimianArmyChaosScript.java

示例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;
}
 
开发者ID:Predictia,项目名称:gfs-reader,代码行数:19,代码来源:Locations.java

示例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);
}
 
开发者ID:outbrain,项目名称:Aletheia,代码行数:19,代码来源:AletheiaConfig.java

示例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;
}
 
开发者ID:lightblue-platform,项目名称:lightblue-rest,代码行数:26,代码来源:QueryTemplateUtils.java

示例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");
        }
    }
}
 
开发者ID:regis-leray,项目名称:html-diff,代码行数:17,代码来源:DiffBuilder.java

示例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);
  }
}
 
开发者ID:apache,项目名称:incubator-gobblin,代码行数:35,代码来源:HttpUtils.java

示例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();
}
 
开发者ID:apache,项目名称:incubator-gobblin,代码行数:23,代码来源:SalesforceSource.java

示例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);
}
 
开发者ID:apache,项目名称:incubator-gobblin,代码行数:26,代码来源:SalesforceSource.java

示例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;
}
 
开发者ID:apache,项目名称:incubator-gobblin,代码行数:20,代码来源:SalesforceSource.java


注:本文中的org.apache.commons.lang3.text.StrSubstitutor类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。