Java 类org.apache.commons.lang3.text.StrSubstitutor 实例源码

项目:careconnect-reference-implementation    文件:ServerInterceptor.java   
@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;
}
项目:careconnect-reference-implementation    文件:ServerInterceptor.java   
@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()+"]");
}
项目:dcos-commons    文件:YAMLConfigurationLoader.java   
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);
}
项目:wssimulator    文件:BaseHandler.java   
@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 "";
}
项目:badgeup-sponge-client    文件:CommandAward.java   
@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;
}
项目:tempto    文件:ConfigurationVariableResolver.java   
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));
    }
}
项目:arquillian-cube-q    文件:BlockPortSimianArmyChaosScript.java   
@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()]);
}
项目:gfs-reader    文件:Locations.java   
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;
}
项目:Aletheia    文件:AletheiaConfig.java   
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);
}
项目:lightblue-rest    文件:QueryTemplateUtils.java   
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;
}
项目:html-diff    文件:DiffBuilder.java   
@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");
        }
    }
}
项目:incubator-gobblin    文件:HttpUtils.java   
/**
 * 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);
  }
}
项目:incubator-gobblin    文件:SalesforceSource.java   
/**
 * 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();
}
项目:incubator-gobblin    文件:SalesforceSource.java   
/**
 * 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);
}
项目:incubator-gobblin    文件:SalesforceSource.java   
/**
 * 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;
}
项目:SciGraph    文件:CypherUtil.java   
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);
}
项目:appstatus    文件:HtmlUtils.java   
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);
}
项目:jmxeval    文件:Element.java   
/**
 * Construct with the execution context.
 *
 * @param context Execution context
 */
protected Element(final Context context) {
  this.context = context;

  // Initialise string substituter for token replacement in variables
  this.substitutor = new StrSubstitutor(new StrLookup<String>() {
    @Override
    public String lookup(final String key) {
      final Object value = context.getVar(key);
      if (value == null) {
        return null;
      } else {
        return String.valueOf(value);
      }
    }
  });
  this.substitutor.setEnableSubstitutionInVariables(true);
}
项目:product-as    文件:ApplicationServerConfigurationTest.java   
private static AppServerClassLoading prepareClassLoaderEnv() {
    AppServerClassLoading classloadingEnvironments = new AppServerClassLoading();

    AppServerClassLoading.Environment cxf = new AppServerClassLoading.Environment();
    cxf.setName(TestConstants.CXF_ENV_NAME);
    cxf.setClasspath(TestConstants.CXF_ENV_CLASSPATH);
    AppServerClassLoading.Environment jaxrs = new AppServerClassLoading.Environment();
    jaxrs.setName(TestConstants.JAXRS_ENV_NAME);
    jaxrs.setClasspath(TestConstants.JAXRS_ENV_CLASSPATH);

    List<AppServerClassLoading.Environment> envList = new ArrayList<>();
    envList.add(cxf);
    envList.add(jaxrs);

    envList
            .forEach(environment -> environment.setClasspath(string_sub.replace(environment.getClasspath())));
    envList
            .forEach(environment -> environment.
                    setClasspath(StrSubstitutor.replaceSystemProperties(environment.getClasspath())));

    AppServerClassLoading.Environments environments = new AppServerClassLoading.Environments();
    environments.setEnvironments(envList);
    classloadingEnvironments.setEnvironments(environments);

    return classloadingEnvironments;
}
项目:product-as    文件:WebappClassLoaderContext.java   
private static List<String> generateClasspath(String classPath) throws FileNotFoundException {
    List<String> urlStr = new ArrayList<>();
    String realClassPath = StrSubstitutor.replaceSystemProperties(classPath);
    File classPathUrl = new File(realClassPath);

    if (!classPathUrl.exists()) {
        throw new FileNotFoundException("The classpath: " + realClassPath + " does not exist.");
    }

    if (classPathUrl.isFile()) {
        urlStr.add(classPathUrl.toURI().toString());
        return urlStr;
    }

    FileUtils.listFiles(classPathUrl, new String[] { "jar" }, false)
            .forEach((file) -> urlStr.add(file.toURI().toString()));

    return urlStr;
}
项目:product-as    文件:ServerConfigurationUtils.java   
private static AppServerClassLoading prepareClassLoaderEnv() {
    AppServerClassLoading classloadingEnvironments = new AppServerClassLoading();

    AppServerClassLoading.Environment cxf = new AppServerClassLoading.Environment();
    cxf.setName(Constants.CXF_ENV_NAME);
    cxf.setClasspath(Constants.CXF_ENV_CLASSPATH);

    List<AppServerClassLoading.Environment> envList = new ArrayList<>();
    envList.add(cxf);

    envList
            .forEach(environment -> environment.setClasspath(STRING_SUB.replace(environment.getClasspath())));
    envList
            .forEach(environment -> environment.
                    setClasspath(StrSubstitutor.replaceSystemProperties(environment.getClasspath())));

    AppServerClassLoading.Environments environments = new AppServerClassLoading.Environments();
    environments.setEnvironments(envList);
    classloadingEnvironments.setEnvironments(environments);

    return classloadingEnvironments;
}
项目:arquillian-cube    文件:IOUtil.java   
public static String replacePlaceholdersWithWhiteSpace(final String templateContent,
    final Map<String, String> values) {
    StrSubstitutor sub = new StrSubstitutor(values);
    sub.setVariableResolver(new StrLookup<Object>() {
        @Override
        public String lookup(String key) {
            if (values == null) {
                return "";
            }
            Object obj = values.get(key);
            if (obj == null) {
                return "";
            }
            return obj.toString();
        }
    });
    return sub.replace(templateContent);
}
项目:pinot    文件:AnomalyResource.java   
@GET
@Path("/external-dashboard-url/{mergedAnomalyId}")
public String getExternalDashboardUrlForMergedAnomaly(@NotNull @PathParam("mergedAnomalyId") Long mergedAnomalyId)
    throws Exception {

  MergedAnomalyResultDTO mergedAnomalyResultDTO = mergedAnomalyResultDAO.findById(mergedAnomalyId);
  String metric = mergedAnomalyResultDTO.getMetric();
  String dataset = mergedAnomalyResultDTO.getCollection();
  Long startTime = mergedAnomalyResultDTO.getStartTime();
  Long endTime = mergedAnomalyResultDTO.getEndTime();
  MetricConfigDTO metricConfigDTO = metricConfigDAO.findByMetricAndDataset(metric, dataset);

  Map<String, String> context = new HashMap<>();
  context.put(MetricConfigBean.URL_TEMPLATE_START_TIME, String.valueOf(startTime));
  context.put(MetricConfigBean.URL_TEMPLATE_END_TIME, String.valueOf(endTime));
  StrSubstitutor strSubstitutor = new StrSubstitutor(context);
  Map<String, String> urlTemplates = metricConfigDTO.getExtSourceLinkInfo();
  for (Entry<String, String> entry : urlTemplates.entrySet()) {
    String sourceName = entry.getKey();
    String urlTemplate = entry.getValue();
    String extSourceUrl = strSubstitutor.replace(urlTemplate);
    urlTemplates.put(sourceName, extSourceUrl);
  }
  return new JSONObject(urlTemplates).toString();
}
项目:timbuctoo    文件:Utils.java   
public static String replaceVariableReferences(final Evaluator evaluator, final String body,
                                               final ResultRecorder resultRecorder) {
  if (body == null) {
    return null;
  }
  StrSubstitutor sub = new StrSubstitutor(new StrLookup<Object>() {
    @Override
    public String lookup(String name) {
      try {
        Object value = evaluator.evaluate(name);
        if (value == null) {
          return "";
        } else {
          return value.toString();
        }
      } catch (Exception e) {
        resultRecorder.record(Result.FAILURE);
        return "<span class=\"failure\">" + e.toString() + "</span>";
      }
    }
  }, "$(", ")", '\\');

  return sub.replace(body);
}
项目:memory-graph    文件:ConfigurationUtils.java   
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));
        }
    }
}
项目:kubernetes-lab    文件:HelloworldVerticle.java   
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);
}
项目:trust-java    文件:VerificationUtils.java   
private static String updateEvalExpression(Map<String, String> testResults,
                                           String evalExpression) {
    if(collectionIsNotEmpty(testResults) &&
            StringUtils.
                    isNotBlank(
                            evalExpression)) {
        return new StrSubstitutor(testResults).
                replace(evalExpression);
    }

    return evalExpression;
}
项目:logger-spring-boot    文件:LoggerMsgFormatter.java   
public String warnBefore(ProceedingJoinPoint joinPoint, Loggable loggable, long nano) {
    Map<String, Object> values = new HashMap<>();
    values.put(METHDO_VALUE, methodName(joinPoint));
    values.put(ARGS_VALUE, methodArgs(joinPoint, loggable));
    values.put(DURATION_VALUE, durationString(nano));
    values.put(WARN_DURATION_VALUE, warnDuration(loggable));
    return StrSubstitutor.replace(formats.getWarnBefore(), values);
}
项目:logger-spring-boot    文件:LoggerMsgFormatter.java   
public String warnAfter(ProceedingJoinPoint joinPoint, Loggable loggable, Object result, long nano) {
    Map<String, Object> values = new HashMap<>();
    values.put(METHDO_VALUE, methodName(joinPoint));
    values.put(ARGS_VALUE, methodArgs(joinPoint, loggable));
    values.put(DURATION_VALUE, durationString(nano));
    values.put(WARN_DURATION_VALUE, warnDuration(loggable));
    values.put(RESULT_VALUE, methodResults(result, loggable));
    return StrSubstitutor.replace(formats.getWarnAfter(), values);
}
项目:logger-spring-boot    文件:LoggerMsgFormatter.java   
public String after(ProceedingJoinPoint joinPoint, Loggable loggable, Object result, long nano) {
    Map<String, Object> values = new HashMap<>();
    values.put(METHDO_VALUE, methodName(joinPoint));
    values.put(ARGS_VALUE, methodArgs(joinPoint, loggable));
    values.put(DURATION_VALUE, durationString(nano));
    values.put(RESULT_VALUE, methodResults(result, loggable));
    return StrSubstitutor.replace(formats.getAfter(), values);
}
项目:logger-spring-boot    文件:LoggerMsgFormatter.java   
public String error(ProceedingJoinPoint joinPoint, Loggable loggable, Object returnVal, long nano,
                    Throwable err) {
    Map<String, Object> values = new HashMap<>();
    values.put(METHDO_VALUE, methodName(joinPoint));
    values.put(ARGS_VALUE, methodArgs(joinPoint, loggable));
    values.put(DURATION_VALUE, durationString(nano));
    values.put(ERROR_CLASS_VALUE, errClass(err));
    values.put(ERROR_MSG_VALUE, errMsg(err));
    values.put(ERROR_SOURCE_CLASS_VALUE, errSourceClass(err));
    values.put(ERROR_LINE_VALUE, errLine(err));
    return StrSubstitutor.replace(formats.getError(), values);
}
项目:satisfy    文件:SessionVariablesUtils.java   
public static String substituteVariableByValue(String templateString) {
    Map<String, String> vars = findPropsThatMatchVars(templateString);
    for (Object key : getCurrentSession().keySet()) {
        if (key instanceof String) {
            Object val = getCurrentSession().get(key);
            if (val instanceof String) {
                vars.put((String) key, (String) val);
            }
        }
    }
    StrSubstitutor sub = new StrSubstitutor(vars);
    return sub.replace(templateString);
}
项目:solr-cmd-utils    文件:StandardReader.java   
public String getProperty(String name, String defaultValue) {
    String value = (String) reader.getProperty().get(name);
    if(value != null) {
        StrSubstitutor strSubstitutor = new StrSubstitutor(variables);
        value = strSubstitutor.replace(value);
        return value;
    }
    return defaultValue;
}
项目:solr-cmd-utils    文件:AbstractFilter.java   
public String getProperty(String name, String defaultValue) {
    if(filter.getProperty() == null) {
        return defaultValue;
    }
    String value = (String) filter.getProperty().get(name);
    if(value != null) {
        StrSubstitutor strSubstitutor = new StrSubstitutor(variables);
        value = strSubstitutor.replace(value);
        return value;
    }
    return defaultValue;
}
项目:solr-cmd-utils    文件:AbstractReader.java   
public String getProperty(String name, String defaultValue) {
    String value = (String) reader.getProperty().get(name);
    if(value != null) {
        StrSubstitutor strSubstitutor = new StrSubstitutor(variables);
        value = strSubstitutor.replace(value);
        return value;
    }
    return defaultValue;
}
项目:solr-cmd-utils    文件:SolrCompareFilter.java   
SearchResult query(Document document, SolrUrl solrUrl, SolrClient solrClient) {
    SolrQuery solrQuery = new SolrQuery();

    Map<String, String> valueMap = new HashMap<String, String>();
    String queryString = document.getFieldValue("query");
    valueMap.put("query", queryString);

    StrSubstitutor strSubstitutor = new StrSubstitutor(valueMap);
    for(Map<String, String> map : solrUrl.getQuery()) {
        for(String key: map.keySet()) {
            String value = map.get(key);
            value = strSubstitutor.replace(value);
            solrQuery.add(key, value);
        }
    }
    SearchResult searchResult = new SearchResult();
    try {
        QueryResponse response = solrClient.query(solrQuery);

        searchResult.setResponseTime(response.getQTime());
        searchResult.setNumFound(response.getResults().getNumFound());
        searchResult.setQuery(queryString);

        Iterator<SolrDocument> resultIterator = response.getResults().iterator();
        int position = 0;
        while(resultIterator.hasNext()) {
            SolrDocument solrDocument = resultIterator.next();
            String id = (String) solrDocument.getFieldValue("id");
            Result result = new Result(id,position++);
            searchResult.getResultList().add(result);
        }
    } catch (Exception e) {
        if(failOnError) {
            throw new RuntimeException(e);
        } else {
            searchResult.setValid(false);
            searchResult.setErrorMessage(e.getMessage());
        }

    }
    return searchResult;
}
项目:photometric-data-retriever    文件:PhotometricDataProcessStarter.java   
@Override
public Process run() throws IOException {
    if (!readyToRun)
        throw new IllegalStateException("Plugin must be prepared first by preparePlugin() method.");

    String[] commandSplit = command.trim().split(" ");
    for (int i = 0; i < commandSplit.length; i++) {
        commandSplit[i] = StrSubstitutor.replace(commandSplit[i], parameters);
    }
    logger.debug("Starting process by command '{}'", (Object) commandSplit);
    return Runtime.getRuntime().exec(commandSplit);
}
项目:mqtt-camunda-bpm    文件:MqttThrowingEvent.java   
public static String replaceVariables(DelegateExecution execution, String topicPattern) {

        if (topicPattern.contains("${")) {
            StrSubstitutor substitutor = new StrSubstitutor(execution.getVariables());
            return substitutor.replace(topicPattern);
        } else {
            return topicPattern;
        }

    }
项目:apiman-test    文件:PolicyLoader.java   
private void storeBean(String definitionId, String config, List<NewPolicyBean> policies) {
    config = StrSubstitutor.replace(config, System.getProperties());
    config = StrSubstitutor.replace(config, SuiteProperties.getProperties());
    config = StrSubstitutor.replace(config, params);

    NewPolicyBean bean = new NewPolicyBean();
    bean.setDefinitionId(definitionId);
    bean.setConfiguration(config);

    policies.add(bean);
}
项目:the-deploy-master    文件:HelloworldVerticle.java   
private String hello(String name) {
    String greeting = "Hello {name} from {hostname} with {version}";
    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);
}