예제 #1
0
 public SpringUtils(AbstractResource conf, Properties properties) {
   this.context = new XmlBeanFactory(conf);
   if (properties != null) {
     PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
     cfg.setProperties(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;
    }
  }
	@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
  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);
	}
 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);
 }
 @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 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]);
	}
예제 #10
0
  @Override
  public void onStart() {
    Logger.debug("Spring Plugin Starting");

    String contextPath = app.configuration().getString(SPRING_CONTEXT_PATH);
    String namespaceAware = app.configuration().getString(SPRING_NAMESPACE_AWARE);
    String addPlayProperties = app.configuration().getString(SPRING_ADD_PLAY_PROPERTIES);

    URL url = null;
    if (contextPath != null) {
      Logger.debug("Loading application context: " + contextPath);
      url = app.classloader().getResource(contextPath);
    }
    if (url == null) {
      Logger.debug("Loading default application context: application-context.ml");
      url = app.classloader().getResource("application-context.xml");
    }
    if (url != null) {
      InputStream is = null;
      try {
        Logger.debug("Starting Spring application context from " + url.toExternalForm());
        applicationContext = new GenericApplicationContext();
        applicationContext.setClassLoader(Play.application().classloader());
        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
        if (!"false".equalsIgnoreCase(namespaceAware)) {
          Logger.debug("Application context is namespace aware");
          xmlReader.setNamespaceAware(true);
        } else {
          Logger.debug("Application context is NOT namespace aware");
        }
        xmlReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);

        // Load Play Configuration
        if (!"false".equalsIgnoreCase(addPlayProperties)) {
          Logger.debug("Adding PropertyPlaceholderConfigurer with Play properties");

          // Convert play's configuration to plain old java properties
          Properties properties = new Properties();
          Set<String> keys = app.configuration().keys();
          for (String key : keys) {
            try {
              String value = app.configuration().getString(key);
              properties.setProperty(key, value);
            } catch (Throwable t) {
              // Some config items are complex, so we'll just skip those for now.
            }
          }

          PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
          configurer.setProperties(properties);
          applicationContext.addBeanFactoryPostProcessor(configurer);
        } else {
          Logger.debug("PropertyPlaceholderConfigurer with Play properties NOT added");
        }

        is = url.openStream();
        xmlReader.loadBeanDefinitions(new InputSource(is));
        ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(app.classloader());
        try {
          applicationContext.refresh();
          // startDate = System.currentTimeMillis();
        } catch (BeanCreationException e) {
          Throwable ex = e.getCause();
          throw new RuntimeException("Unable to instantiate Spring application context", ex);
        } finally {
          Thread.currentThread().setContextClassLoader(originalClassLoader);
        }
      } catch (IOException e) {
        Logger.error("Can't load spring config file", e);
      } finally {
        if (is != null) {
          try {
            is.close();
          } catch (IOException e) {
            Logger.error("Can't close spring config file stream", e);
          }
        }
      }
    }
  }
 @Override
 public void setProperties(Properties properties) {
   // TODO Auto-generated method stub
   super.setProperties(properties);
 }
  @Test
  public void genericApplicationContext() throws Exception {
    GenericApplicationContext ac = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);

    ac.getBeanFactory()
        .registerScope(
            "myScope",
            new Scope() {
              public Object get(String name, ObjectFactory objectFactory) {
                return objectFactory.getObject();
              }

              public Object remove(String name) {
                return null;
              }

              public void registerDestructionCallback(String name, Runnable callback) {}

              public Object resolveContextualObject(String key) {
                if (key.equals("mySpecialAttr")) {
                  return "42";
                } else {
                  return null;
                }
              }

              public String getConversationId() {
                return null;
              }
            });

    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    Properties placeholders = new Properties();
    placeholders.setProperty("code", "123");
    ppc.setProperties(placeholders);
    ac.addBeanFactoryPostProcessor(ppc);

    GenericBeanDefinition bd0 = new GenericBeanDefinition();
    bd0.setBeanClass(TestBean.class);
    bd0.getPropertyValues().add("name", "myName");
    bd0.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "original"));
    ac.registerBeanDefinition("tb0", bd0);

    GenericBeanDefinition bd1 = new GenericBeanDefinition();
    bd1.setBeanClass(TestBean.class);
    bd1.setScope("myScope");
    bd1.getConstructorArgumentValues()
        .addGenericArgumentValue("XXX#{tb0.name}YYY#{mySpecialAttr}ZZZ");
    bd1.getConstructorArgumentValues().addGenericArgumentValue("#{mySpecialAttr}");
    ac.registerBeanDefinition("tb1", bd1);

    GenericBeanDefinition bd2 = new GenericBeanDefinition();
    bd2.setBeanClass(TestBean.class);
    bd2.setScope("myScope");
    bd2.getPropertyValues().add("name", "{ XXX#{tb0.name}YYY#{mySpecialAttr}ZZZ }");
    bd2.getPropertyValues().add("age", "#{mySpecialAttr}");
    bd2.getPropertyValues().add("country", "${code} #{systemProperties.country}");
    ac.registerBeanDefinition("tb2", bd2);

    GenericBeanDefinition bd3 = new GenericBeanDefinition();
    bd3.setBeanClass(ValueTestBean.class);
    bd3.setScope("myScope");
    ac.registerBeanDefinition("tb3", bd3);

    GenericBeanDefinition bd4 = new GenericBeanDefinition();
    bd4.setBeanClass(ConstructorValueTestBean.class);
    bd4.setScope("myScope");
    ac.registerBeanDefinition("tb4", bd4);

    GenericBeanDefinition bd5 = new GenericBeanDefinition();
    bd5.setBeanClass(MethodValueTestBean.class);
    bd5.setScope("myScope");
    ac.registerBeanDefinition("tb5", bd5);

    GenericBeanDefinition bd6 = new GenericBeanDefinition();
    bd6.setBeanClass(PropertyValueTestBean.class);
    bd6.setScope("myScope");
    ac.registerBeanDefinition("tb6", bd6);

    System.getProperties().put("country", "UK");
    try {
      ac.refresh();

      TestBean tb0 = ac.getBean("tb0", TestBean.class);

      TestBean tb1 = ac.getBean("tb1", TestBean.class);
      assertEquals("XXXmyNameYYY42ZZZ", tb1.getName());
      assertEquals(42, tb1.getAge());

      TestBean tb2 = ac.getBean("tb2", TestBean.class);
      assertEquals("{ XXXmyNameYYY42ZZZ }", tb2.getName());
      assertEquals(42, tb2.getAge());
      assertEquals("123 UK", tb2.getCountry());

      ValueTestBean tb3 = ac.getBean("tb3", ValueTestBean.class);
      assertEquals("XXXmyNameYYY42ZZZ", tb3.name);
      assertEquals(42, tb3.age);
      assertEquals("123 UK", tb3.country);
      assertEquals("123 UK", tb3.countryFactory.getObject());
      System.getProperties().put("country", "US");
      assertEquals("123 UK", tb3.country);
      assertEquals("123 US", tb3.countryFactory.getObject());
      System.getProperties().put("country", "UK");
      assertEquals("123 UK", tb3.country);
      assertEquals("123 UK", tb3.countryFactory.getObject());
      assertSame(tb0, tb3.tb);

      tb3 = (ValueTestBean) SerializationTestUtils.serializeAndDeserialize(tb3);
      assertEquals("123 UK", tb3.countryFactory.getObject());

      ConstructorValueTestBean tb4 = ac.getBean("tb4", ConstructorValueTestBean.class);
      assertEquals("XXXmyNameYYY42ZZZ", tb4.name);
      assertEquals(42, tb4.age);
      assertEquals("123 UK", tb4.country);
      assertSame(tb0, tb4.tb);

      MethodValueTestBean tb5 = ac.getBean("tb5", MethodValueTestBean.class);
      assertEquals("XXXmyNameYYY42ZZZ", tb5.name);
      assertEquals(42, tb5.age);
      assertEquals("123 UK", tb5.country);
      assertSame(tb0, tb5.tb);

      PropertyValueTestBean tb6 = ac.getBean("tb6", PropertyValueTestBean.class);
      assertEquals("XXXmyNameYYY42ZZZ", tb6.name);
      assertEquals(42, tb6.age);
      assertEquals("123 UK", tb6.country);
      assertSame(tb0, tb6.tb);
    } finally {
      System.getProperties().remove("country");
    }
  }