Example usage for org.springframework.beans.factory.config PropertyPlaceholderConfigurer PropertyPlaceholderConfigurer

List of usage examples for org.springframework.beans.factory.config PropertyPlaceholderConfigurer PropertyPlaceholderConfigurer

Introduction

In this page you can find the example usage for org.springframework.beans.factory.config PropertyPlaceholderConfigurer PropertyPlaceholderConfigurer.

Prototype

PropertyPlaceholderConfigurer

Source Link

Usage

From source file:org.rivetlogic.export.components.XmlExtractRequestProcessor.java

private void initializeCMSCreds(Ticket ticketParam)
        throws IOException, AuthenticationFailure, CmaRuntimeException {

    // set up the bean factory
    if (beanFactory == null) {
        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");

        Resource resource = context.getResource("classpath:core/cma-cfg.properties");
        Properties properties = new Properties();
        properties.load(resource.getInputStream());

        configurer.setProperties(properties);

        context.addBeanFactoryPostProcessor(configurer);
        context.refresh();/*from  w  ww  . ja  v  a  2  s  .  c o  m*/

        beanFactory = context.getBeanFactory();
        authService = (AuthenticationService) beanFactory.getBean("authenticationService",
                AuthenticationServiceImpl.class);
    }

    // get a ticket
    if (this.ticket == null) {

        if (ticketParam != null) {
            this.ticket = ticketParam;

        } else {
            this.ticket = authService.authenticate(cmaUrl, cmaUsername, cmaPassword.toCharArray());
        }
    }

    try {
        authService.validate(ticket);
    } catch (InvalidTicketException e) {
        log.debug("ticket invalid, getting a new one.");
        ticket = authService.authenticate(cmaUrl, cmaUsername, cmaPassword.toCharArray());
    }
}

From source file:no.kantega.publishing.spring.OpenAksessContextLoaderListener.java

private void addConfigurationPropertyReplacer(ConfigurableWebApplicationContext wac,
        final Properties properties) {
    wac.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
            cfg.setProperties(properties);
            cfg.postProcessBeanFactory(beanFactory);
        }//  w w  w . ja va 2  s. c om
    });
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

private ApplicationContext loadContext(String[] configLocations, URLClassLoader cl, String contextDisplayName,
        Properties properties) throws Exception {
    ServletContext servletContext = ((ConfigurableWebApplicationContext) this._applicationContext)
            .getServletContext();//  ww w.  ja  v  a 2  s  .  co m
    //if plugin's classes have been loaded we can go on
    List<ClassPathXmlApplicationContext> ctxList = (List<ClassPathXmlApplicationContext>) servletContext
            .getAttribute("pluginsContextsList");
    if (ctxList == null) {
        ctxList = new ArrayList<ClassPathXmlApplicationContext>();
        servletContext.setAttribute("pluginsContextsList", ctxList);
    }
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    ClassPathXmlApplicationContext newContext = null;
    try {
        //create a new spring context with the classloader and the paths defined as parameter in pluginsInstallerContext.xml.
        //The new context is given the default webapplication context as its parent  
        Thread.currentThread().setContextClassLoader(cl);
        newContext = new ClassPathXmlApplicationContext();
        //ClassPathXmlApplicationContext newContext = new ClassPathXmlApplicationContext(configLocations, applicationContext);    
        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        configurer.setProperties(properties);
        newContext.addBeanFactoryPostProcessor(configurer);
        newContext.setClassLoader(cl);
        newContext.setParent(this._applicationContext);
        String[] configLocs = new String[] { "classpath:spring/restServerConfig.xml",
                "classpath:spring/baseSystemConfig.xml" };
        newContext.setConfigLocations(configLocs);
        newContext.refresh();
        BaseConfigManager baseConfigManager = (BaseConfigManager) ((ConfigurableWebApplicationContext) this._applicationContext)
                .getBean("BaseConfigManager");
        baseConfigManager.init();
        newContext.setConfigLocations(configLocations);
        newContext.refresh();
        newContext.setDisplayName(contextDisplayName);
        ClassPathXmlApplicationContext currentCtx = (ClassPathXmlApplicationContext) this
                .getStoredContext(contextDisplayName);
        if (currentCtx != null) {
            currentCtx.close();
            ctxList.remove(currentCtx);
        }
        ctxList.add(newContext);

    } catch (Exception e) {
        _logger.error("Unexpected error loading application context: " + e.getMessage());
        e.printStackTrace();
        throw e;
    } finally {
        Thread.currentThread().setContextClassLoader(currentClassLoader);
    }
    return newContext;
}

From source file:org.jumpmind.symmetric.ClientSymmetricEngine.java

@Override
protected void init() {
    try {/*from www.  j a va  2s.c o  m*/
        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;
    }
}

From source file:org.kuali.rice.krad.datadictionary.DataDictionary.java

/**
 * Invokes post processors and builds indexes for the beans contained in the dictionary
 *
 * @param allowConcurrentValidation - indicates whether the indexing should occur on a different thread
 * or the same thread//from w w w .j a v a 2 s  .  c  o  m
 */
public void performDictionaryPostProcessing(boolean allowConcurrentValidation) {
    LOG.info("Starting Data Dictionary Post Processing");

    timer.start("Spring Post Processing");
    PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
    propertyPlaceholderConfigurer.setProperties(ConfigContext.getCurrentContextConfig().getProperties());
    propertyPlaceholderConfigurer.postProcessBeanFactory(ddBeans);

    DictionaryBeanFactoryPostProcessor dictionaryBeanPostProcessor = new DictionaryBeanFactoryPostProcessor(
            DataDictionary.this, ddBeans);
    dictionaryBeanPostProcessor.postProcessBeanFactory();
    timer.stop();

    // post processes UIF beans for pulling out expressions within property values
    timer.start("UIF Post Processing");
    UifBeanFactoryPostProcessor factoryPostProcessor = new UifBeanFactoryPostProcessor();
    factoryPostProcessor.postProcessBeanFactory(ddBeans);
    timer.stop();

    timer.start("Instantiating DD Beans");
    ddBeans.preInstantiateSingletons();
    timer.stop();

    // Allow the DD to perform final post processing in a controlled order
    // Unlike the Spring post processor, we will only call for these operations on the
    // "top-level" beans and have them call post processing actions on embedded DD objects, if needed
    timer.start("DD Post Processing");
    for (DataObjectEntry entry : ddBeans.getBeansOfType(DataObjectEntry.class).values()) {
        entry.dataDictionaryPostProcessing();
    }
    for (DocumentEntry entry : ddBeans.getBeansOfType(DocumentEntry.class).values()) {
        entry.dataDictionaryPostProcessing();
    }
    timer.stop();

    timer.start("Data Dictionary Indexing");
    ddIndex.run();
    timer.stop();

    // the UIF defaulting must be done before the UIF indexing but after the main DD data object indexing
    timer.start("UIF Defaulting");
    generateMissingInquiryDefinitions();
    generateMissingLookupDefinitions();
    timer.stop();

    timer.start("UIF Indexing");
    uifIndex.run();
    timer.stop();

    LOG.info("Completed Data Dictionary Post Processing");
}

From source file:org.sakaiproject.util.SakaiProperties.java

/**
 * Dereferences property placeholders in the given {@link Properties}
 * in exactly the same way the {@link BeanFactoryPostProcessor}s in this
 * object perform their placeholder dereferencing. Unfortunately, this
 * process is not readily decoupled from the act of processing a
 * bean factory in the Spring libraries. Hence the reflection.
 * // w ww. j  a  v  a  2s .  c om
 * @param srcProperties a collection of name-value pairs
 * @return a new collection of properties. If <code>srcProperties</code>
 *   is <code>null</code>, returns null. If <code>srcProperties</code>
 *   is empty, returns a reference to same object.
 * @throws RuntimeException if any aspect of processing fails
 */
private Properties dereferenceProperties(Properties srcProperties) throws RuntimeException {
    if (srcProperties == null) {
        return null;
    }
    if (srcProperties.isEmpty()) {
        return srcProperties;
    }
    try {
        Properties parsedProperties = new Properties();
        PropertyPlaceholderConfigurer resolver = new PropertyPlaceholderConfigurer();
        resolver.setIgnoreUnresolvablePlaceholders(true);
        Method parseStringValue = resolver.getClass().getDeclaredMethod("parseStringValue", String.class,
                Properties.class, Set.class);
        parseStringValue.setAccessible(true);
        for (Map.Entry<Object, Object> propEntry : srcProperties.entrySet()) {
            String parsedPropValue = (String) parseStringValue.invoke(resolver, (String) propEntry.getValue(),
                    srcProperties, new HashSet<Object>());
            parsedProperties.setProperty((String) propEntry.getKey(), parsedPropValue);
        }
        return parsedProperties;
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException("Failed to dereference properties", e);
    }
}

From source file:org.springframework.context.expression.ApplicationContextExpressionTests.java

@Test
public void genericApplicationContext() throws Exception {
    GenericApplicationContext ac = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);

    ac.getBeanFactory().registerScope("myScope", new Scope() {
        @Override//from   w  w w  .j a v  a2s.c o m
        public Object get(String name, ObjectFactory<?> objectFactory) {
            return objectFactory.getObject();
        }

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

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

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

        @Override
        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.setBeanClassName("#{tb0.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.setBeanClassName("#{tb1.class.name}");
    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(42, tb3.ageFactory.getObject().intValue());
        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");
    }
}