Example usage for org.springframework.core.env PropertiesPropertySource PropertiesPropertySource

List of usage examples for org.springframework.core.env PropertiesPropertySource PropertiesPropertySource

Introduction

In this page you can find the example usage for org.springframework.core.env PropertiesPropertySource PropertiesPropertySource.

Prototype

protected PropertiesPropertySource(String name, Map<String, Object> source) 

Source Link

Usage

From source file:com.careerly.common.support.ReloadablePropertySourcesPlaceholderConfigurer.java

private void reload() throws IOException {
    logger.info("properties changed, reloading..");

    // Properties?
    Properties properties = super.mergeProperties();
    MutablePropertySources propertySources = new MutablePropertySources();
    propertySources.addLast(new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, properties));
    ConfigurablePropertyResolver propertyResolver = new PropertySourcesPropertyResolver(propertySources);
    // BeanFactory??removeEmbeddedValueResolver??Resolver?
    valueResolver.expire();//  w w w .ja v a 2 s.c o  m
    valueResolver = new PropertyStringValueResolver(propertyResolver);
    beanFactory.addEmbeddedValueResolver(valueResolver);

    // ??
    for (String beanName : beanNames) {
        Object bean = beanFactory.getBean(beanName);
        autowiredAnnotationBeanPostProcessor.processInjection(bean);
    }
}

From source file:ch.sdi.core.impl.cfg.ConfigUtils.java

/**
 * Tries to retrieve the named PropertySource from the environment. If not found it creates a
 * new one.//w  ww .  j a v  a  2 s .c om
 * <p>
 *
 * @param aEnv
 * @param aPropertySourceName
 * @return the embedded property map
 * @throws SdiException if the found property source is not instance of PropertiesPropertySource
 */
public static Map<String, Object> getOrCreatePropertySource(ConfigurableEnvironment aEnv,
        String aPropertySourceName) throws SdiException {
    MutablePropertySources mps = aEnv.getPropertySources();
    PropertySource<?> ps = mps.get(aPropertySourceName);
    PropertiesPropertySource pps = null;

    if (ps == null) {
        Properties props = new Properties();
        pps = new PropertiesPropertySource(aPropertySourceName, props);
        mps.addFirst(pps);
    } else {
        if (!(ps instanceof PropertiesPropertySource)) {
            throw new SdiException("Found property source is not instance of PropertiesPropertySource "
                    + " but: " + ps.getClass().getName(), SdiException.EXIT_CODE_CONFIG_ERROR);
        } // if !( ps instanceof PropertiesPropertySource )

        pps = (PropertiesPropertySource) ps;
    }

    Map<String, Object> map = pps.getSource();
    return map;
}

From source file:org.alfresco.bm.tools.BMTestRunner.java

/**
 * Execute the default test against the given MongoDB or an in-memory instance
 * /*from   ww  w  .j ava  2  s.co  m*/
 * @param mongoConfigHost           the MongoDB host to connect to for configuraton data or <tt>null</tt> to use an in-memory version
 * @param mongoTestHost             the MongoDB host to connect to for test data data or <tt>null</tt> to use the same database as the config
 * @param testProperties            any properties to specifically set for the test or <tt>null</tt> if there are none
 */
public void run(String mongoConfigHost, String mongoTestHost, Properties testProperties) throws Exception {
    // Secure the listeners against modification
    List<BMTestRunnerListener> listeners = new ArrayList<BMTestRunnerListener>(this.listeners);

    // If no MongoDB URL is provided, then we have to start one
    MongoDBForTestsFactory mongoDBForTestsFactory = null;
    ClassPathXmlApplicationContext ctx = null;
    try {
        // Ensure that required system properties are present
        System.setProperty(PROP_APP_CONTEXT_PATH, System.getProperty("user.dir"));
        System.setProperty(PROP_APP_DIR, System.getProperty("user.dir"));

        // Create a MongoDB for use if one has not been specified
        if (mongoConfigHost == null) {
            mongoDBForTestsFactory = new MongoDBForTestsFactory();
            String uriWithoutDB = mongoDBForTestsFactory.getMongoURIWithoutDB();
            mongoConfigHost = new MongoClientURI(uriWithoutDB).getHosts().get(0);
        }
        // Fill in the URI for the test MongoDB
        if (mongoTestHost == null) {
            mongoTestHost = mongoConfigHost;
        }

        // Fill in the properties required for the test
        Properties mongoProps = new Properties();
        mongoProps.put(PROP_MONGO_CONFIG_HOST, mongoConfigHost);

        // Construct the application context
        ctx = new ClassPathXmlApplicationContext(new String[] { PATH_APP_CONTEXT }, false);
        // Push cluster properties into the context (must be done AFTER setting parent context)
        ConfigurableEnvironment ctxEnv = ctx.getEnvironment();
        // Mongo properties come first
        ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("mongo-props", mongoProps));
        // Finally, system properties overrule them all
        ctxEnv.getPropertySources()
                .addFirst(new PropertiesPropertySource("system-props", System.getProperties()));

        // Kick it all off
        try {
            ctx.refresh();
        } catch (Exception e) {
            Throwable root = ExceptionUtils.getRootCause(e);
            if (root != null
                    && (root instanceof MongoSocketException || root instanceof UnknownHostException)) {
                // We deal with this specifically as it's a simple case of not finding the MongoDB
                logger.error("Set the configuration property '" + PROP_MONGO_CONFIG_HOST
                        + "' (<server>:<port>) as required.");
            } else {
                // Log application start failure because test frameworks might not do so nicely
                logger.error("Failed to start application.", e);
            }
            throw new RuntimeException("Failed to start application.", e);
        }

        // Get the test
        Test test = ctx.getBean(Test.class);
        String release = test.getRelease();
        Integer schema = test.getSchema();

        TestRestAPI api = ctx.getBean(TestRestAPI.class);

        // Create a new test
        TestDetails testDetails = new TestDetails();
        String testName = "BMTestRunner_" + System.currentTimeMillis();
        testDetails.setName(testName);
        testDetails.setDescription("Test created by BMTestRunner on " + new Date());
        testDetails.setRelease(release);
        testDetails.setSchema(schema);
        api.createTest(testDetails);

        // We need to tell the test which MongoDB to write data to
        PropSetBean propSet = new PropSetBean();
        propSet.setValue(mongoTestHost);
        propSet.setVersion(0);
        api.setTestProperty(testName, PROP_MONGO_TEST_HOST, propSet);

        // Now set any properties that have been explicitly passed in for the test
        if (testProperties != null) {
            for (Map.Entry<Object, Object> entry : testProperties.entrySet()) {
                String propKey = (String) entry.getKey();
                String propVal = (String) entry.getValue();

                propSet.setValue(propVal);
                propSet.setVersion(0);
                api.setTestProperty(testName, propKey, propSet);
            }
        }

        // Call listeners: the test has been created
        for (BMTestRunnerListener listener : listeners) {
            listener.testReady(ctx, testName);
        }

        // Create a new test run
        TestRunDetails testRunDetails = new TestRunDetails();
        String testRunName = "BMTestRunner_" + System.currentTimeMillis();
        testRunDetails.setName(testRunName);
        testRunDetails.setDescription("Test run created by BMTestRunner on " + new Date());
        api.createTestRun(testDetails.getName(), testRunDetails);

        // Call listeners: the test run has been created
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunReady(ctx, testName, testRunName);
        }

        // Get all the test run properties for logging
        String jsonTestRun = api.getTestRun(testName, testRunName);

        // Start the test run
        logger.info("Starting test run: " + testRunName + "\n" + jsonTestRun);
        TestRunSchedule testRunSchedule = new TestRunSchedule();
        testRunSchedule.setScheduled(System.currentTimeMillis());
        api.scheduleTestRun(testName, testRunName, testRunSchedule);

        // Call listeners: the test run has started
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunStarted(ctx, testName, testRunName);
        }

        // Wait for the test run to complete
        long timeInit = System.currentTimeMillis();
        long timeLastChange = -1L;
        String jsonLastChange = null;
        String testRunStateStr = api.getTestRunState(testName, testRunName);

        // Keep looking until the test run completes
        while (!TestRunState.COMPLETED.toString().equals(testRunStateStr)) {
            long now = System.currentTimeMillis();

            // Check that we have not exceeded the maximum time
            if (now - timeInit > maxTestTime) {
                throw new RuntimeException("Test run failed to complete in " + (int) maxTestTime / 1000 + "s.");
            }

            testRunStateStr = api.getTestRunState(testName, testRunName);

            if (TestRunState.SCHEDULED.toString().equals(testRunStateStr) && (now - timeInit) > 10000L) {
                throw new RuntimeException("Test run failed to start in 10s.");
            }

            // Check that there are updates to the test run
            String jsonNow = api.getTestRunSummary(testName, testRunName);
            if (jsonLastChange != null && jsonLastChange.equals(jsonNow)) {
                if ((now - timeLastChange) > 60000L) {
                    throw new RuntimeException("Test run has not been updated in the last 60s");
                }
            }
            // Store values for next iteration
            timeLastChange = now;
            jsonLastChange = jsonNow;

            synchronized (testRunStateStr) {
                try {
                    testRunStateStr.wait(1000L);
                } catch (InterruptedException e) {
                }
            }
        }
        // Call listeners: the test run has finished
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunFinished(ctx, testName, testRunName);
        }
    } finally {
        // Close the context
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                logger.error("Failed to shut down application context.", e);
            }
        }
        // Close the local Mongo instance
        if (mongoDBForTestsFactory != null) {
            try {
                mongoDBForTestsFactory.destroy();
            } catch (Exception e) {
                logger.error("Failed to stop in-memory MongoDB instance.", e);
            }
        }
    }
}

From source file:nl.nn.adapterframework.configuration.IbisContext.java

/**
 * Create Spring Bean factory. Parameter 'springContext' can be null.
 *
 * Create the Spring Bean Factory using the supplied <code>springContext</code>,
 * if not <code>null</code>.
 *
 * @param springContext Spring Context to create. If <code>null</code>,
 * use the default spring context./*  w  ww .  ja  v  a  2 s .  com*/
 * The spring context is loaded as a spring ClassPathResource from
 * the class path.
 *
 * @return The Spring XML Bean Factory.
 * @throws BeansException If the Factory can not be created.
 *
 */
private ApplicationContext createApplicationContext() throws BeansException {
    // Reading in Spring Context
    long start = System.currentTimeMillis();
    String springContext = "/springContext.xml";
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext();
    MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
    propertySources.remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
    propertySources.remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
    propertySources.addFirst(new PropertiesPropertySource("ibis", APP_CONSTANTS));
    applicationContext.setConfigLocation(springContext);
    applicationContext.refresh();
    log("startup " + springContext + " in " + (System.currentTimeMillis() - start) + " ms");
    return applicationContext;
}

From source file:org.alfresco.bm.api.v1.RestAPITest.java

@Before
public void setUp() throws Exception {
    gson = new Gson();

    // Create a mock DB to connect to
    mockDBFactory = new MongoDBForTestsFactory();
    mongoHost = mockDBFactory.getMongoHost();
    String database = mockDBFactory.getObject().getName();

    // Create an application context (don't start, yet)
    ctx = new ClassPathXmlApplicationContext(new String[] { PATH_APP_CONTEXT }, false);

    // Pass our properties to the new context
    Properties ctxProperties = new Properties();
    {/*  w ww  .  j  a  va2  s .  c  om*/
        ctxProperties.put(PROP_MONGO_CONFIG_HOST, mongoHost);
        ctxProperties.put(PROP_MONGO_CONFIG_DATABASE, database);
        ctxProperties.put(PROP_MONGO_TEST_DATABASE, MONGO_TEST_DATABASE);
        ctxProperties.put(PROP_APP_RELEASE, RELEASE);
        ctxProperties.put(PROP_APP_SCHEMA, "" + SCHEMA);
        ctxProperties.put(PROP_APP_INHERITANCE, "COMMON, TEST");
        ctxProperties.put(PROP_TEST_RUN_MONITOR_PERIOD, "" + 20000);
        ctxProperties.put(PROP_SYSTEM_CAPABILITIES, "Java");
        ctxProperties.put(PROP_APP_CONTEXT_PATH, "/");
        ctxProperties.put(PROP_APP_DIR, ".");
    }
    ConfigurableEnvironment ctxEnv = ctx.getEnvironment();
    ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("RestAPITest", ctxProperties));
    // Override all properties with system properties
    ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("system", System.getProperties()));
    // Start the context now
    ctx.refresh();

    // Get beans
    dao = ctx.getBean(MongoTestDAO.class);
    appDB = dao.getDb();
    TestServiceImpl testService = ctx.getBean(TestServiceImpl.class);
    LogService logService = ctx.getBean(LogService.class);
    this.testRunServicesCache = ctx.getBean(TestRunServicesCache.class);
    api = new TestRestAPI(dao, testService, logService, testRunServicesCache);
}

From source file:org.alfresco.bm.test.TestRun.java

/**
 * Called to ensure that the application context is started.
 * <p/>//from  ww w.ja v a  2s  .com
 * Note that we only pull out the test and test run names at this point so that we don't end up
 * using stale data.
 */
private synchronized void start() {
    DBObject runObj = getRunObj(true);
    if (runObj == null) {
        // Nothing much we can do here
        return;
    }

    // Check the application context
    if (testRunCtx != null) {
        // There is nothing to do, the context is already available
        return;
    }

    // INFO logging as this is a critical part of the whole application
    if (logger.isInfoEnabled()) {
        logger.info("Starting test run application context: " + runObj);
    }

    ObjectId testObjId = (ObjectId) runObj.get(FIELD_TEST);
    ObjectId runObjId = (ObjectId) runObj.get(FIELD_ID);
    String run = (String) runObj.get(FIELD_NAME);
    // We need to build the test run FQN out of the test run details
    DBObject testObj = testDAO.getTest(testObjId, false);
    if (testObj == null) {
        logger.warn("The test associated with the test run has been removed: " + runObj);
        logger.warn("The test run will be stopped and deleted: " + id);
        stop();
        testDAO.deleteTestRun(id);
        return;
    }
    String test = (String) testObj.get(FIELD_NAME);
    String release = (String) testObj.get(FIELD_RELEASE);
    Integer schema = (Integer) testObj.get(FIELD_SCHEMA);
    String testRunFqn = test + "." + run;

    // Extract the current properties for the run
    Set<String> propsToMask = new HashSet<String>(7);
    Properties testRunProps = new Properties();
    {
        testRunProps.put(PROP_DRIVER_ID, driverId);
        testRunProps.put(PROP_TEST, test);
        testRunProps.put(PROP_TEST_RUN, run);
        testRunProps.put(PROP_TEST_RUN_ID, id.toString());
        testRunProps.put(PROP_TEST_RUN_FQN, testRunFqn);

        BasicDBList propObjs = (BasicDBList) runObj.get(FIELD_PROPERTIES);
        for (Object obj : propObjs) {
            DBObject propObj = (DBObject) obj;
            String propName = (String) propObj.get(FIELD_NAME);
            String propDef = (String) propObj.get(FIELD_DEFAULT);
            String propValue = (String) propObj.get(FIELD_VALUE);
            if (propValue == null) {
                propValue = propDef;
            }
            testRunProps.put(propName, propValue);
            // Check on the masking for later reporting
            boolean mask = Boolean.parseBoolean((String) propObj.get(FIELD_MASK));
            if (mask) {
                propsToMask.add(propName);
            }
        }
    }

    // Create the child application context WITHOUT AUTOSTART
    // TODO: This is hard coded to "config/spring/test-context.xml".  It should be one of the
    //       test definition properties and have the same as default.
    ClassPathXmlApplicationContext testRunCtx = new ClassPathXmlApplicationContext(
            new String[] { PATH_TEST_CONTEXT }, false);
    // When running stand-alone, there might not be a parent context
    if (parentCtx != null) {
        testRunCtx.setParent(parentCtx);
    }
    // Push cluster properties into the context (must be done AFTER setting parent context)
    ConfigurableEnvironment ctxEnv = testRunCtx.getEnvironment();
    ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("run-props", testRunProps));
    ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("system-props", System.getProperties()));

    // Complete logging of what is going to be used for the test
    if (logger.isInfoEnabled()) {
        String nl = "\n";
        StringBuilder sb = new StringBuilder(1024);
        sb.append("Test run application context starting: ").append(nl).append("   Run ID:       ").append(id)
                .append(nl).append("   Test Name:    ").append(test).append(nl).append("   Run Name:     ")
                .append(run).append(nl).append("   Driver ID:    ").append(driverId).append(nl)
                .append("   Release:      ").append(release).append(nl).append("   Schema:       ")
                .append(schema).append(nl).append("   Test Run Properties:   ").append(nl);
        for (Object propNameObj : testRunProps.keySet()) {
            String propName = (String) propNameObj;
            String propValue = testRunProps.getProperty(propName);
            if (propsToMask.contains(propName) || propName.toLowerCase().contains("username")
                    || propName.toLowerCase().contains("password")) {
                propValue = MASK;
            }
            sb.append("      ").append(propName).append("=").append(propValue).append(nl);
        }
        sb.append("   System Properties:   ").append(nl);
        for (Object propNameObj : System.getProperties().keySet()) {
            String propName = (String) propNameObj;
            String propValue = System.getProperty(propName);
            if (propsToMask.contains(propName) || propName.toLowerCase().contains("username")
                    || propName.toLowerCase().contains("password")) {
                propValue = MASK;
            }
            sb.append("      ").append(propName).append("=").append(propValue).append(nl);
        }
        logger.info(sb);
    }

    // Now refresh (to load beans) and start
    try {
        this.testRunCtx = testRunCtx;
        // 2015-08-04 fkbecker: store definitions first - for refresh() or start() may fail, too. 
        this.test = test;
        this.run = run;
        this.release = release;
        this.schema = schema;

        testRunCtx.refresh();
        testRunCtx.start();

        // Make sure that the required components are present and of the correct type
        // There may be multiple beans of the type, so we have to use the specific bean name.
        @SuppressWarnings("unused")
        CompletionEstimator estimator = (CompletionEstimator) testRunCtx.getBean("completionEstimator");
        @SuppressWarnings("unused")
        EventProcessor startEventProcessor = (EventProcessor) testRunCtx.getBean("event.start");

        // Register the driver with the test run
        testDAO.addTestRunDriver(runObjId, driverId);

        // Log the successful startup
        logService.log(driverId, test, run, LogLevel.INFO,
                "Successful startup of test run '" + testRunFqn + "'.");
    } catch (Exception e) {
        /*
        Throwable root = ExceptionUtils.getRootCause(e);
        if (root != null && (root instanceof MongoException || root instanceof IOException))
        {
        // 2015-08-04 fkbecker IOException also thrown by FTP file service if host not reachable ...
        // FIXME 
                
        String msg1 = "Failed to start test run application '" + testRunFqn + "': " + e.getCause().getMessage();
        //String msg2 = "Set the test run property '" + PROP_MONGO_TEST_HOST + "' (<server>:<port>) as required.";
        // We deal with this specifically as it's a simple case of not finding the MongoDB
        logger.error(msg1);
        //logger.error(msg2);
        logService.log(driverId, test, run, LogLevel.ERROR, msg1);
        //logService.log(driverId, test, run, LogLevel.ERROR, msg2);
        }
        else
        {*/
        String stack = ExceptionUtils.getStackTrace(e);
        logger.error("Failed to start test run application '" + testRunFqn + "': ", e);
        String error = "Failed to start test run application '" + testRunFqn + ". \r\n" + stack;
        logService.log(driverId, test, run, LogLevel.ERROR, error);
        //}
        stop();
    }
}

From source file:org.alfresco.bm.test.TestRunServicesCache.java

/**
 * Create an application context holding the services for the given test run
 *//*from  w  w  w .  ja  va 2 s . com*/
private ClassPathXmlApplicationContext createContext(String test, String run) {
    String testRunFqn = test + "." + run;
    DBObject runObj;
    try {
        runObj = dao.getTestRun(test, run, true);
    } catch (ObjectNotFoundException e1) {
        logger.error("Test '" + test + "." + run + "' not found.", e1);
        return null;
    }

    // Dig the properties out of the test run
    Properties testRunProps = new Properties();
    {
        testRunProps.put(PROP_TEST_RUN_FQN, testRunFqn);

        BasicDBList propObjs = (BasicDBList) runObj.get(FIELD_PROPERTIES);
        for (Object obj : propObjs) {
            DBObject propObj = (DBObject) obj;
            String propName = (String) propObj.get(FIELD_NAME);
            String propDef = (String) propObj.get(FIELD_DEFAULT);
            String propValue = (String) propObj.get(FIELD_VALUE);
            if (propValue == null) {
                propValue = propDef;
            }
            testRunProps.put(propName, propValue);
        }
    }
    // Construct the properties
    ClassPathXmlApplicationContext testRunCtx = new ClassPathXmlApplicationContext(
            new String[] { PATH_TEST_SERVICES_CONTEXT }, false);
    ConfigurableEnvironment ctxEnv = testRunCtx.getEnvironment();
    ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("run-props", testRunProps));
    // Bind to shutdown
    testRunCtx.registerShutdownHook();

    // Attempt to start the context
    try {
        testRunCtx.refresh();
        testRunCtx.start();
        // Make sure that the required components are present
        testRunCtx.getBean(EventService.class);
        testRunCtx.getBean(ResultService.class);
        testRunCtx.getBean(SessionService.class);
    } catch (Exception e) {
        Throwable root = ExceptionUtils.getRootCause(e);
        if (root != null && root instanceof MongoSocketException) {
            // We deal with this specifically as it's a simple case of not finding the MongoDB
            logger.error("Failed to start test run services context '" + testRunFqn + "': "
                    + e.getCause().getMessage());
            logger.error(
                    "Set the test run property '" + PROP_MONGO_TEST_HOST + "' (<server>:<port>) as required.");
        } else if (root != null && root instanceof UnknownHostException) {
            // We deal with this specifically as it's a simple case of not finding the MongoDB
            logger.error("Failed to start test run services context '" + testRunFqn + "': "
                    + e.getCause().getCause().getMessage());
            logger.error(
                    "Set the test run property '" + PROP_MONGO_TEST_HOST + "' (<server>:<port>) as required.");
        } else {
            logger.error("Failed to start test run services context '" + testRunFqn + "': ", e);
        }
        testRunCtx = null;
    }
    // Done
    if (testRunCtx == null) {
        logger.warn("Failed to start test run services context: " + testRunFqn);
    } else if (logger.isDebugEnabled()) {
        logger.debug("Started test run services context: " + testRunFqn);
    }
    return testRunCtx;
}

From source file:org.codehaus.groovy.grails.commons.env.GrailsEnvironment.java

public GrailsEnvironment(GrailsApplication grailsApplication) {
    this.grailsApplication = grailsApplication;
    getPropertySources().addFirst(new GrailsConfigPropertySource());
    getPropertySources().addFirst(new PropertiesPropertySource("systemProperties", System.getProperties()));

}