Beispiel #1
0
 @Bean
 public static PropertyPlaceholderConfigurer propertyConfigurer() throws IOException {
   PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
   props.setLocations(new Resource[] {new ClassPathResource("environment.properties")});
   props.setSearchSystemEnvironment(true);
   props.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
   return props;
 }
Beispiel #2
0
 public SpringUtils(AbstractResource conf, AbstractResource properties) {
   this.context = new XmlBeanFactory(conf);
   if (properties != null) {
     PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
     cfg.setLocation(properties);
     cfg.postProcessBeanFactory(context);
   }
 }
  @Override
  protected void init() {
    try {
      LogSummaryAppenderUtils.registerLogSummaryAppender();

      super.init();

      this.dataSource = platform.getDataSource();

      PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
      configurer.setProperties(parameterService.getAllParameters());

      ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(springContext);
      ctx.addBeanFactoryPostProcessor(configurer);

      List<String> extensionLocations = new ArrayList<String>();
      extensionLocations.add("classpath:/symmetric-ext-points.xml");
      if (registerEngine) {
        extensionLocations.add("classpath:/symmetric-jmx.xml");
      }

      String xml = parameterService.getString(ParameterConstants.EXTENSIONS_XML);
      File file = new File(parameterService.getTempDirectory(), "extension.xml");
      FileUtils.deleteQuietly(file);
      if (isNotBlank(xml)) {
        try {
          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          factory.setValidating(false);
          factory.setNamespaceAware(true);
          DocumentBuilder builder = factory.newDocumentBuilder();
          // the "parse" method also validates XML, will throw an exception if misformatted
          builder.parse(new InputSource(new StringReader(xml)));
          FileUtils.write(file, xml, false);
          extensionLocations.add("file:" + file.getAbsolutePath());
        } catch (Exception e) {
          log.error("Invalid " + ParameterConstants.EXTENSIONS_XML + " parameter.");
        }
      }

      try {
        ctx.setConfigLocations(extensionLocations.toArray(new String[extensionLocations.size()]));
        ctx.refresh();

        this.springContext = ctx;

        ((ClientExtensionService) this.extensionService).setSpringContext(springContext);
        this.extensionService.refresh();
      } catch (Exception ex) {
        log.error(
            "Failed to initialize the extension points.  Please fix the problem and restart the server.",
            ex);
      }
    } catch (RuntimeException ex) {
      destroy();
      throw ex;
    }
  }
 @Bean
 public static PropertyPlaceholderConfigurer securityPropertyPlaceholderConfigurer() {
   PropertyPlaceholderConfigurer propertyPlaceholderConfigurer =
       new PropertyPlaceholderConfigurer();
   propertyPlaceholderConfigurer.setLocation(
       new ClassPathResource("application-security.properties"));
   propertyPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
   return propertyPlaceholderConfigurer;
 }
	@Test
	public void testExtendedResourceInjectionWithOverriding() {
		DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
		CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
		bpp.setBeanFactory(bf);
		bf.addBeanPostProcessor(bpp);
		bf.registerResolvableDependency(BeanFactory.class, bf);

		PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
		Properties props = new Properties();
		props.setProperty("tb", "testBean3");
		ppc.setProperties(props);
		ppc.postProcessBeanFactory(bf);

		RootBeanDefinition annotatedBd = new RootBeanDefinition(ExtendedResourceInjectionBean.class);
		TestBean tb5 = new TestBean();
		annotatedBd.getPropertyValues().add("testBean2", tb5);
		bf.registerBeanDefinition("annotatedBean", annotatedBd);
		bf.registerBeanDefinition("annotatedBean2", new RootBeanDefinition(NamedResourceInjectionBean.class));
		TestBean tb = new TestBean();
		bf.registerSingleton("testBean", tb);
		TestBean tb2 = new TestBean();
		bf.registerSingleton("testBean2", tb2);
		TestBean tb3 = new TestBean();
		bf.registerSingleton("testBean3", tb3);
		TestBean tb4 = new TestBean();
		bf.registerSingleton("testBean4", tb4);
		NestedTestBean tb6 = new NestedTestBean();
		bf.registerSingleton("xy", tb6);

		ExtendedResourceInjectionBean bean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
		assertTrue(bean.initCalled);
		assertTrue(bean.init2Called);
		assertSame(tb, bean.getTestBean());
		assertSame(tb5, bean.getTestBean2());
		assertSame(tb4, bean.getTestBean3());
		assertSame(tb3, bean.getTestBean4());
		assertSame(tb6, bean.testBean5);
		assertSame(tb6, bean.testBean6);
		assertSame(bf, bean.beanFactory);

		try {
			bf.getBean("annotatedBean2");
		}
		catch (BeanCreationException ex) {
			assertTrue(ex.getRootCause() instanceof NoSuchBeanDefinitionException);
			NoSuchBeanDefinitionException innerEx = (NoSuchBeanDefinitionException) ex.getRootCause();
			assertEquals("testBean9", innerEx.getBeanName());
		}

		bf.destroySingletons();
		assertTrue(bean.destroyCalled);
		assertTrue(bean.destroy2Called);
	}
 @Bean
 PropertyPlaceholderConfigurer configurer() {
   PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
   configurer.setFileEncoding("utf-8");
   configurer.setSystemPropertiesMode(
       PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
   configurer.setLocations(
       new org.springframework.core.io.Resource[] {
         new ClassPathResource("config_test.properties", SpringFeatureTest.class),
         new ClassPathResource("config.properties")
       });
   return configurer;
 }
  @Bean
  public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() throws IOException {

    List<Resource> resources = loadPropertyResource();

    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    Properties props = propertyFactory();

    configurer.setProperties(props);
    configurer.setSystemPropertiesMode(
        PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);
    return configurer;
  }
	@Test
	public void testExtendedResourceInjection() {
		DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
		CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
		bpp.setBeanFactory(bf);
		bf.addBeanPostProcessor(bpp);
		bf.registerResolvableDependency(BeanFactory.class, bf);

		PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
		Properties props = new Properties();
		props.setProperty("tb", "testBean3");
		ppc.setProperties(props);
		ppc.postProcessBeanFactory(bf);

		bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ExtendedResourceInjectionBean.class));
		bf.registerBeanDefinition("annotatedBean2", new RootBeanDefinition(NamedResourceInjectionBean.class));
		bf.registerBeanDefinition("annotatedBean3", new RootBeanDefinition(ConvertedResourceInjectionBean.class));
		TestBean tb = new TestBean();
		bf.registerSingleton("testBean", tb);
		TestBean tb2 = new TestBean();
		bf.registerSingleton("testBean2", tb2);
		TestBean tb3 = new TestBean();
		bf.registerSingleton("testBean3", tb3);
		TestBean tb4 = new TestBean();
		bf.registerSingleton("testBean4", tb4);
		NestedTestBean tb6 = new NestedTestBean();
		bf.registerSingleton("value", "5");
		bf.registerSingleton("xy", tb6);
		bf.registerAlias("xy", "testBean9");

		ExtendedResourceInjectionBean bean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
		assertTrue(bean.initCalled);
		assertTrue(bean.init2Called);
		assertSame(tb, bean.getTestBean());
		assertSame(tb2, bean.getTestBean2());
		assertSame(tb4, bean.getTestBean3());
		assertSame(tb3, bean.getTestBean4());
		assertSame(tb6, bean.testBean5);
		assertSame(tb6, bean.testBean6);
		assertSame(bf, bean.beanFactory);

		NamedResourceInjectionBean bean2 = (NamedResourceInjectionBean) bf.getBean("annotatedBean2");
		assertSame(tb6, bean2.testBean);

		ConvertedResourceInjectionBean bean3 = (ConvertedResourceInjectionBean) bf.getBean("annotatedBean3");
		assertSame(5, bean3.value);

		bf.destroySingletons();
		assertTrue(bean.destroyCalled);
		assertTrue(bean.destroy2Called);
	}
  @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);
  }
 @Override
 protected void processProperties(
     ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
     throws BeansException {
   this.properties = props;
   super.processProperties(beanFactoryToProcess, this.properties);
 }
 @Override
 protected void loadProperties(Properties props) throws IOException {
   try {
     super.loadProperties(props);
   } catch (IOException ex) {
     logger.warn(ex.getMessage() + ", will use default configuration.");
   }
 }
 @SuppressWarnings("static-access")
 @Override
 protected void processProperties(
     ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
     throws BeansException {
   if (!props.isEmpty()) {
     this.props = props;
   }
   super.processProperties(beanFactoryToProcess, props);
 }
 protected void initPropertiesPlaceHolder(
     ConfigurableApplicationContext context, AcServiceConfig serviceConfig) {
   // prepare properties from service config
   Properties prop = new Properties();
   for (String key : serviceConfig.getKeys()) {
     // NOTE: use data from service property (preferences + default)
     prop.setProperty(key, serviceConfig.getProperty(key));
   }
   // TODO (other better way) other core reserved properties
   prop.setProperty(
       "ac.context.sessionId",
       String.valueOf(serviceConfig.getCoreContext().getSession().getSessionId()));
   prop.setProperty(
       "ac.context.profileId",
       String.valueOf(serviceConfig.getCoreContext().getSession().getProfile().getProfileId()));
   PropertyPlaceholderConfigurer propConfig = new PropertyPlaceholderConfigurer();
   propConfig.setProperties(prop);
   context.addBeanFactoryPostProcessor(propConfig);
 }
 @Override
 protected void processProperties(
     ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
     throws BeansException {
   String env = System.getProperty("ENV_MODE");
   logger.info("ENV_MODE is " + env);
   Properties appConfig = PropertiesHolder.INSTANCE.getAppConfig();
   mergeProperties(props, appConfig);
   super.processProperties(beanFactoryToProcess, appConfig);
 }
 protected void processProperties(
     ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
     throws BeansException {
   super.processProperties(beanFactoryToProcess, props);
   resolvedProps = new HashMap<String, String>();
   for (Object key : props.keySet()) {
     String keyStr = key.toString();
     resolvedProps.put(keyStr, resolvePlaceholder(keyStr, props));
   }
 }
 protected void processProperties(
     ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
     throws BeansException {
   Iterator<String> keys = AppConstants.config.getKeys();
   while (keys.hasNext()) {
     String key = keys.next();
     String value = AppConstants.config.getString(key);
     props.put(key, value);
   }
   super.processProperties(beanFactoryToProcess, props);
 }
 @Before
 public void createSpringContext() {
   try {
     log.info("creating spring context");
     PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
     Properties properties = new Properties();
     properties.setProperty("temp.dir", TMPDIR);
     configurer.setProperties(properties);
     ctx = new ClassPathXmlApplicationContext();
     ctx.addBeanFactoryPostProcessor(configurer);
     // ctx.setConfigLocation(
     // "org/drools/container/spring/beans/persistence/beansVarPersistence.xml" );
     ctx.setConfigLocation(
         "org/drools/container/spring/beans/persistence/beansVarPersistence_Env.xml");
     ctx.refresh();
   } catch (Exception e) {
     log.error("can't create spring context", e);
     throw new RuntimeException(e);
   }
 }
 public void init() {
   File file = new File(CASSANDRA_CONFIG_FILE);
   try {
     InputStream input = new FileInputStream(file);
     Resource location = new InputStreamResource(input);
     super.setLocation(location);
   } catch (IOException e) {
     System.out.println("cass file:" + file.getAbsolutePath() + "\n");
     e.printStackTrace();
   }
 }
  protected void processProperties(
      ConfigurableListableBeanFactory beanFactory, java.util.Properties props)
      throws BeansException {

    super.processProperties(beanFactory, props);
    for (Object key : props.keySet()) {
      String keyStr = key.toString();
      String value = props.getProperty(keyStr);
      ConstantBusiKeys.GLOBAL_CONFIG_PROPERTIES.put(keyStr, value);
    }
  }
  @Override
  protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
      throws BeansException {
    super.processProperties(beanFactory, props);

    propertiesMap = new HashMap<String, String>();
    for (Object key : props.keySet()) {
      String keyStr = key.toString();
      String valueStr = resolvePlaceholder(keyStr, props, springSystemPropertiesMode);
      propertiesMap.put(keyStr, valueStr);
    }
  }
  public final void loadNode() {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();

    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    configurer.setProperties(props);

    context.addBeanFactoryPostProcessor(configurer);
    context.setConfigLocation("net\\dfs\\remote\\filestorage\\spring-client.xml");
    context.refresh();
    context.start();

    /*		FileLocationTrackerImpl hash = new FileLocationTrackerImpl();
    		hash.removeAll();
    */
    log.info("Client Started");

    FileReceiverSupport receiveFile = (FileReceiverSupport) context.getBean("receiveFile");

    receiveFile.connectJavaSpace();
    receiveFile.retrieveFile();
  }
	@Test
	public void testResourceInjectionWithResolvableDependencyType() {
		DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
		CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor();
		bpp.setBeanFactory(bf);
		bf.addBeanPostProcessor(bpp);
		RootBeanDefinition abd = new RootBeanDefinition(ExtendedResourceInjectionBean.class);
		abd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
		bf.registerBeanDefinition("annotatedBean", abd);
		RootBeanDefinition tbd = new RootBeanDefinition(TestBean.class);
		tbd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
		bf.registerBeanDefinition("testBean4", tbd);

		bf.registerResolvableDependency(BeanFactory.class, bf);
		bf.registerResolvableDependency(INestedTestBean.class, new ObjectFactory<Object>() {
			@Override
			public Object getObject() throws BeansException {
				return new NestedTestBean();
			}
		});

		PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
		Properties props = new Properties();
		props.setProperty("tb", "testBean4");
		ppc.setProperties(props);
		ppc.postProcessBeanFactory(bf);

		ExtendedResourceInjectionBean bean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
		INestedTestBean tb = bean.getTestBean6();
		assertNotNull(tb);

		ExtendedResourceInjectionBean anotherBean = (ExtendedResourceInjectionBean) bf.getBean("annotatedBean");
		assertNotSame(anotherBean, bean);
		assertNotSame(anotherBean.getTestBean6(), tb);

		String[] depBeans = bf.getDependenciesForBean("annotatedBean");
		assertEquals(1, depBeans.length);
		assertEquals("testBean4", depBeans[0]);
	}
  @Override
  protected void loadProperties(Properties props) throws IOException {
    Resource location = null;
    if (StringUtils.isNotEmpty(systemPropertyName)) {
      String propertyFilePath = System.getProperties().getProperty(systemPropertyName);
      if (StringUtils.isNotBlank(propertyFilePath)) {
        location = new FileSystemResource(propertyFilePath);
      } else {
        location = new ClassPathResource(defaultPropertiesFileLocation);
      }
    }

    setLocation(location);
    super.loadProperties(props);
  }
  @Override
  protected void loadProperties(Properties props) throws IOException {
    Resource location = null;
    if (StringUtils.isNotEmpty(propertyFileName)) {
      String configFilepath = Env.getEnvInstance().getConfigFilePath();
      if (!propertyFileName.startsWith("/")) {
        configFilepath = configFilepath + "/";
      }

      location = new FileSystemResource(configFilepath + propertyFileName);
    }

    setLocation(location);
    super.loadProperties(props);
  }
 @Override
 protected void loadProperties(Properties props) throws IOException {
   // perform standard property resource file loading
   super.loadProperties(props);
   // put the properties into the Rice configuration context
   ConfigContext.getCurrentContextConfig().putProperties(props);
   // load the Rice properties
   if (LOG.isDebugEnabled()) {
     Config config = ConfigContext.getCurrentContextConfig();
     if (config != null) {
       LOG.debug("Replacing parameters in Spring using config:\r\n" + config);
       ConfigLogger.logConfig(config);
     }
   }
 }
  /**
   * Overridden to fill the location with the path from the {@link #propertyLocationSystemProperty}
   *
   * @param props propeties instance to fill
   * @throws IOException
   */
  @Override
  protected void loadProperties(Properties props) throws IOException {
    Resource location = null;
    String webAppContextUrl = null;
    try {
      BasicService basicService = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
      String codeBase = basicService.getCodeBase().toExternalForm();
      System.out.println("codeBase=[" + codeBase + "]");
      if (!codeBase.endsWith("/")) {
        codeBase += "/";
      }
      int webAppContextUrlLength = codeBase.lastIndexOf("applications");
      webAppContextUrl = codeBase.substring(0, webAppContextUrlLength) + "config/";
      System.out.println("webAppContextUrl=[" + webAppContextUrl + "]");
    } catch (Exception e) {
      // TODO logging
      e.printStackTrace();
    }
    location = appContext.getResource("url:" + webAppContextUrl);

    setLocation(location);
    super.loadProperties(props);
  }
  @Override
  public void afterPropertiesSet() throws Exception {
    File properties =
        new File(
            config
                .getConfiguration(EmbeddedBrokerConfiguration.EMBEDDED_BROKER_PROPERTIES_KEY)
                .toString());
    if (!properties.isAbsolute() && !properties.isFile()) {
      // try to resolve as absolute
      properties = new File(JMSConfiguration.getConfigPathDir(), properties.getPath());
      if (!properties.isFile()) {
        // copy the defaults
        IOUtils.copy(defaults.getFile(), properties);
      }
    }
    final Resource res = new FileSystemResource(properties);
    super.setLocation(res);

    // make sure the activemq.base is set to a valuable default
    final Properties props = new Properties();
    props.setProperty("activemq.base", (String) config.getConfiguration("CLUSTER_CONFIG_DIR"));
    props.setProperty("instanceName", (String) config.getConfiguration("instanceName"));
    setProperties(props);
  }
 @Override
 public void setSystemPropertiesMode(int systemPropertiesMode) {
   super.setSystemPropertiesMode(systemPropertiesMode);
   springSystemPropertiesMode = systemPropertiesMode;
 }
 @Bean
 public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
   PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
   ppc.setLocation(new ClassPathResource("/persistence.properties"));
   return ppc;
 }
 @Bean
 public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
   PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
   ppc.setLocation(new ClassPathResource("/Chat-WebSocket_Backbone.properties"));
   return ppc;
 }