@Override
  protected void processProperties(
      ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
      throws BeansException {
    /*
     * 覆盖父类的方法,截取解析到的参数值,放入自定义的map中,供外部调用。
     */

    // build the properties we need
    Map<String, String> tempProps = new HashMap<String, String>(props.size());
    PropertyPlaceholderHelper helper =
        new PropertyPlaceholderHelper(DEFAULT_PLACEHOLDER_PREFIX, DEFAULT_PLACEHOLDER_SUFFIX);
    for (Object keyObj : props.keySet()) {
      String key = String.valueOf(keyObj);
      String value = props.getProperty(key);
      if (StringUtils.hasText(value) && value.startsWith(SECRET_PREFIX)) {
        try {
          String tmp = CryptoUtil.decryptApi(value.substring(SECRET_PREFIX.length()));
          value = tmp;
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      value = helper.replacePlaceholders(value, props);
      tempProps.put(key, value);
      props.setProperty(key, value);
    }
    // 这个map只读
    this.resolvedProps = Collections.unmodifiableMap(tempProps);
    PropsUtil.setProperties(resolvedProps);

    // 必须放在后面执行, 否则在xml配置属性的时候会不可用
    super.processProperties(beanFactoryToProcess, props);
  }
  @Test(expected = IllegalArgumentException.class)
  public void testUnresolvedPlaceholderAsError() {
    String text = "foo=${foo},bar=${bar}";
    Properties props = new Properties();
    props.setProperty("foo", "bar");

    PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}", null, false);
    assertEquals("foo=bar,bar=${bar}", helper.replacePlaceholders(text, props));
  }
 /**
  * @param templateResourcePath
  * @param templateProperties
  * @return
  */
 private String replaceValuesAndGetTemplateValue(
     String templateResourcePath, Properties templateProperties, RestResponse response) {
   InputStream gradleInitTemplateStream = null;
   try {
     gradleInitTemplateStream = getClass().getResourceAsStream(templateResourcePath);
     String gradleTemplate = IOUtils.toString(gradleInitTemplateStream);
     PropertyPlaceholderHelper propertyPlaceholderHelper =
         new PropertyPlaceholderHelper("${", "}");
     return propertyPlaceholderHelper.replacePlaceholders(gradleTemplate, templateProperties);
   } catch (IOException e) {
     String errorMessage = "An error occurred while preparing the Gradle Init Script template: ";
     response.error(errorMessage + e.getMessage());
     log.error(errorMessage, e);
   } finally {
     IOUtils.closeQuietly(gradleInitTemplateStream);
   }
   return "";
 }
  /**
   * Utility method for extracting the Proxy Headers for a request.
   *
   * <p>The configuration option '{key}.proxyHeaders' is used to specify a multi-valued list of HTTP
   * headers to add to the outbound request to '{key}.uri'.
   *
   * <p>Example:
   *
   * <pre>
   * someservice.proxyHeaders=On-Behalf-Of: {wiscedupvi},Some-Other-Header: staticvalue
   * </pre>
   *
   * Implementers can specify either static values ('Some-Other-Header: staticvalue') or use
   * placeholders to relay {@link HttpServletRequest#getAttribute(String)} values ('On-Behalf-Of:
   * {wiscedupvi}')
   *
   * @param env
   * @param resourceKey
   * @param request
   * @return a potentially empty, but never null, {@link Multimap} of HTTP headers to add to the
   *     outbound HTTP request.
   */
  public static Multimap<String, String> getProxyHeaders(
      Environment env, String resourceKey, final HttpServletRequest request) {
    Multimap<String, String> headers = ArrayListMultimap.create();
    String proxyHeadersValue = env.getProperty(resourceKey + ".proxyHeaders");
    if (proxyHeadersValue != null) {
      String[] proxyHeaders = StringUtils.split(proxyHeadersValue, ",");
      for (String proxyHeader : proxyHeaders) {
        String[] tokens = StringUtils.trim(proxyHeader).split(":");
        if (tokens.length == 2) {
          PropertyPlaceholderHelper helper =
              new PropertyPlaceholderHelper(START_PLACEHOLDER, END_PLACEHOLDER);
          String value =
              helper.replacePlaceholders(
                  tokens[1],
                  new PropertyPlaceholderHelper.PlaceholderResolver() {
                    @Override
                    public String resolvePlaceholder(String placeholderName) {
                      Object attribute = request.getAttribute(placeholderName);
                      if (attribute != null && attribute instanceof String) {
                        return (String) attribute;
                      }
                      logger.warn(
                          "configuration error: could not resolve placeholder for attribute {} as it's not a String, it's a {}",
                          placeholderName,
                          attribute != null ? attribute.getClass() : null);
                      return null;
                    }
                  });

          value = StringUtils.trim(value);
          if (value != null
              && !value.startsWith(START_PLACEHOLDER)
              && !value.endsWith(END_PLACEHOLDER)) {
            headers.put(tokens[0], value);
          }
        } else {
          logger.warn("configuration error: can't split {} on ':', ignoring", proxyHeader);
        }
      }
    }
    return headers;
  }
示例#5
0
 /**
  * 计算带占位符的表达式值,如:http://${server.url}/api
  *
  * @param key 参数
  * @return 参数值
  */
 public static String getPlaceholder(String key) {
   Assert.notNull(key, "Argument 'key' must not be null.");
   return HELPER.replacePlaceholders(key, RESOLVER);
 }