Example usage for org.springframework.beans.factory.config PropertiesFactoryBean getObject

List of usage examples for org.springframework.beans.factory.config PropertiesFactoryBean getObject

Introduction

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

Prototype

@Override
    @Nullable
    public final Properties getObject() throws IOException 

Source Link

Usage

From source file:org.springframework.batch.admin.web.server.JsonIntegrationTests.java

@Test
public void testListedResourcesWithGet() throws Exception {

    Map<String, String> params = new HashMap<String, String>();
    params.put("jobName", "job2");
    // These should be there if the previous test cases worked
    params.put("jobInstanceId", "0");
    params.put("jobExecutionId", "0");
    params.put("stepExecutionId", "0");

    RestTemplate template = new RestTemplate();

    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(/*from  w  ww.j  a v  a 2s.co m*/
            new ClassPathResource("/org/springframework/batch/admin/web/manager/json-resources.properties"));
    propertiesFactoryBean.afterPropertiesSet();
    Properties properties = propertiesFactoryBean.getObject();

    for (String path : properties.stringPropertyNames()) {
        if (!StringUtils.hasText(path) || !path.startsWith("GET")) {
            continue;
        }
        path = path.substring(path.indexOf("/"));
        ResponseEntity<String> result = template.exchange(serverRunning.getUrl() + path, HttpMethod.GET, null,
                String.class, params);
        JsonWrapper wrapper = new JsonWrapper(result.getBody());
        // System.err.println(wrapper);
        assertNotNull(wrapper);
    }
}

From source file:org.springframework.data.jdbc.config.oracle.PoolingDataSourceBeanDefinitionParser.java

protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    ResourceLoader rl = parserContext.getReaderContext().getResourceLoader();
    //attributes/*from  w  w  w  . j a v a2  s  .co  m*/
    String propertyFileLocation = element.getAttribute(PROPERTIES_LOCATION_ATTRIBUTE);
    String connectionPropertyFileLocation = element.getAttribute(PROPERTIES_LOCATION_ATTRIBUTE);

    String connectionPropertyPrefix = element.getAttribute(CONNECTION_PROPERTIES_PREFIX_ATTRIBUTE);
    String cachingPropertyPrefix = element.getAttribute(CONNECTON_CACHE_PROPERTIS_PREFIX_ATTRIBUTE);
    String url = element.getAttribute(URL_ATTRIBUTE);
    String username = element.getAttribute(USERNAME_ATTRIBUTE);
    String password = element.getAttribute(PASSWORD_ATTRIBUTE);
    String onsConfiguration = element.getAttribute(ONS_CONFIGURATION_ATTRIBUTE);
    String fastConnectionFailoverEnabled = element.getAttribute(FAST_CONNECTION_FAILOVER_ENABLED_ATTRIBUTE);
    String connectionCachingEnabled = element.getAttribute(CONNECTION_CACHING_ENABLED_ATTRIBUTE);

    boolean propertyFileProvided = false;

    Map<String, Object> providedProperties = new HashMap<String, Object>();

    // defaults
    if (!StringUtils.hasText(propertyFileLocation) && !StringUtils.hasText(connectionPropertyFileLocation)) {
        propertyFileLocation = DEFAULT_PROPERTY_FILE_LOCATION;
    }
    if (!StringUtils.hasText(connectionPropertyPrefix)) {
        connectionPropertyPrefix = DEFAULT_PROPERTY_PREFIX;
    }

    // look for property files
    if (StringUtils.hasText(propertyFileLocation)) {
        logger.debug("Using properties location: " + propertyFileLocation);
        String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(propertyFileLocation);
        Resource r = rl.getResource(resolvedLocation);
        logger.debug("Loading properties from resource: " + r);
        PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();
        factoryBean.setLocation(r);
        try {
            factoryBean.afterPropertiesSet();
            Properties resource = factoryBean.getObject();
            for (Map.Entry<Object, Object> entry : resource.entrySet()) {
                providedProperties.put((String) entry.getKey(), entry.getValue());
            }
            propertyFileProvided = true;
        } catch (FileNotFoundException e) {
            propertyFileProvided = false;
            if (propertyFileLocation.equals(DEFAULT_PROPERTY_FILE_LOCATION)) {
                logger.debug("Unable to find " + propertyFileLocation);
            } else {
                parserContext.getReaderContext()
                        .error("pooling-datasource defined with attribute '" + PROPERTIES_LOCATION_ATTRIBUTE
                                + "' but the property file was not found at location \"" + propertyFileLocation
                                + "\"", element);
            }
        } catch (IOException e) {
            logger.warn("Error loading " + propertyFileLocation + ": " + e.getMessage());
        }
    } else {
        propertyFileProvided = false;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Using provided properties: " + providedProperties);
    }

    if (connectionPropertyPrefix == null) {
        connectionPropertyPrefix = "";
    }
    if (connectionPropertyPrefix.length() > 0 && !connectionPropertyPrefix.endsWith(".")) {
        connectionPropertyPrefix = connectionPropertyPrefix + ".";
    }
    logger.debug("Using connection properties prefix: " + connectionPropertyPrefix);

    if (cachingPropertyPrefix == null) {
        cachingPropertyPrefix = "";
    }
    if (cachingPropertyPrefix.length() > 0 && !cachingPropertyPrefix.endsWith(".")) {
        cachingPropertyPrefix = cachingPropertyPrefix + ".";
    }
    logger.debug("Using caching properties prefix: " + cachingPropertyPrefix);

    if (!(StringUtils.hasText(connectionCachingEnabled) || providedProperties
            .containsKey(attributeToPropertyMap.get(CONNECTION_CACHING_ENABLED_ATTRIBUTE)))) {
        connectionCachingEnabled = DEFAULT_CONNECTION_CACHING_ENABLED;
    }

    setRequiredAttribute(builder, parserContext, element, providedProperties, connectionPropertyPrefix,
            propertyFileProvided, url, URL_ATTRIBUTE, "URL");
    setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, username, USERNAME_ATTRIBUTE);
    setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, password, PASSWORD_ATTRIBUTE);
    setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, connectionCachingEnabled,
            CONNECTION_CACHING_ENABLED_ATTRIBUTE);
    setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, fastConnectionFailoverEnabled,
            FAST_CONNECTION_FAILOVER_ENABLED_ATTRIBUTE);
    setOptionalAttribute(builder, providedProperties, connectionPropertyPrefix, onsConfiguration,
            ONS_CONFIGURATION_ATTRIBUTE);

    Properties providedConnectionProperties = new Properties();
    Properties providedCachingProperties = new Properties();
    for (String key : providedProperties.keySet()) {
        if (StringUtils.hasText(connectionPropertyPrefix) && key.startsWith(connectionPropertyPrefix)) {
            String newKey = key.substring(connectionPropertyPrefix.length());
            providedConnectionProperties.put(newKey, providedProperties.get(key));
        } else {
            if (StringUtils.hasText(cachingPropertyPrefix) && key.startsWith(cachingPropertyPrefix)) {
                String newKey = key.substring(cachingPropertyPrefix.length());
                providedCachingProperties.put(newKey, providedProperties.get(key));
            } else {
                providedConnectionProperties.put(key, providedProperties.get(key));
            }
        }
    }

    // look for connectionProperties
    Object connProperties = DomUtils.getChildElementValueByTagName(element,
            CONNECTION_PROPERTIES_CHILD_ELEMENT);
    if (connProperties != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Using connection-properties");
        }
        builder.addPropertyValue("connectionProperties", connProperties);
    } else {
        if (providedConnectionProperties.size() > 0) {
            if (logger.isDebugEnabled()) {
                logger.debug("Using provided connection properties: " + providedConnectionProperties);
            }
            builder.addPropertyValue("connectionProperties", providedConnectionProperties);
        }
    }

    // look for connectionCacheProperties
    Object cacheProperties = DomUtils.getChildElementValueByTagName(element,
            CONNECTION_CACHE_PROPERTIES_CHILD_ELEMENT);
    if (cacheProperties != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Using connection-cache-properties: [" + cacheProperties + "]");
        }
        builder.addPropertyValue("connectionCacheProperties", cacheProperties);
    } else {
        if (providedCachingProperties.size() > 0) {
            if (logger.isDebugEnabled()) {
                logger.debug("Using provided caching properties: " + providedCachingProperties);
            }
            builder.addPropertyValue("connectionCacheProperties", providedCachingProperties);
        }
    }

    builder.setRole(BeanDefinition.ROLE_SUPPORT);
}

From source file:org.springframework.integration.twitter.inbound.DirectMessageReceivingMessageSourceTests.java

@SuppressWarnings("unchecked")
@Test//from ww  w.j av a 2s.c  om
@Ignore
public void demoReceiveDm() throws Exception {
    PropertiesFactoryBean pf = new PropertiesFactoryBean();
    pf.setLocation(new ClassPathResource("sample.properties"));
    pf.afterPropertiesSet();
    Properties prop = pf.getObject();
    TwitterTemplate template = new TwitterTemplate(prop.getProperty("z_oleg.oauth.consumerKey"),
            prop.getProperty("z_oleg.oauth.consumerSecret"), prop.getProperty("z_oleg.oauth.accessToken"),
            prop.getProperty("z_oleg.oauth.accessTokenSecret"));
    DirectMessageReceivingMessageSource tSource = new DirectMessageReceivingMessageSource(template, "foo");
    tSource.afterPropertiesSet();
    for (int i = 0; i < 50; i++) {
        Message<DirectMessage> message = (Message<DirectMessage>) tSource.receive();
        if (message != null) {
            DirectMessage tweet = message.getPayload();
            logger.info(
                    tweet.getSender().getScreenName() + " - " + tweet.getText() + " - " + tweet.getCreatedAt());
        }
    }
}

From source file:org.springframework.integration.twitter.inbound.SearchReceivingMessageSourceTests.java

@SuppressWarnings("unchecked")
@Test/*from w ww.  j a v  a2 s.co  m*/
@Ignore
public void demoReceiveSearchResults() throws Exception {
    PropertiesFactoryBean pf = new PropertiesFactoryBean();
    pf.setLocation(new ClassPathResource("sample.properties"));
    pf.afterPropertiesSet();
    Properties prop = pf.getObject();
    TwitterTemplate template = new TwitterTemplate(prop.getProperty("z_oleg.oauth.consumerKey"),
            prop.getProperty("z_oleg.oauth.consumerSecret"), prop.getProperty("z_oleg.oauth.accessToken"),
            prop.getProperty("z_oleg.oauth.accessTokenSecret"));
    SearchReceivingMessageSource tSource = new SearchReceivingMessageSource(template, "foo");
    tSource.setQuery(SEARCH_QUERY);
    tSource.afterPropertiesSet();
    for (int i = 0; i < 50; i++) {
        Message<Tweet> message = (Message<Tweet>) tSource.receive();
        if (message != null) {
            Tweet tweet = message.getPayload();
            logger.info(tweet.getFromUser() + " - " + tweet.getText() + " - " + tweet.getCreatedAt());
        }
    }
}

From source file:org.springframework.integration.twitter.inbound.TimelineReceivingMessageSourceTests.java

@SuppressWarnings("unchecked")
@Test/*from  w  ww .j a v a  2 s  .c o  m*/
@Ignore
public void demoReceiveTimeline() throws Exception {
    PropertiesFactoryBean pf = new PropertiesFactoryBean();
    pf.setLocation(new ClassPathResource("sample.properties"));
    pf.afterPropertiesSet();
    Properties prop = pf.getObject();
    TwitterTemplate template = new TwitterTemplate(prop.getProperty("z_oleg.oauth.consumerKey"),
            prop.getProperty("z_oleg.oauth.consumerSecret"), prop.getProperty("z_oleg.oauth.accessToken"),
            prop.getProperty("z_oleg.oauth.accessTokenSecret"));
    TimelineReceivingMessageSource tSource = new TimelineReceivingMessageSource(template, "foo");
    tSource.afterPropertiesSet();
    for (int i = 0; i < 50; i++) {
        Message<Tweet> message = (Message<Tweet>) tSource.receive();
        if (message != null) {
            Tweet tweet = message.getPayload();
            logger.info(tweet.getFromUser() + " - " + tweet.getText() + " - " + tweet.getCreatedAt());
        }
    }
}

From source file:org.springframework.integration.twitter.oauth.ConsoleBasedAccessTokenInitialRequestProcessListener.java

public static void main(String[] args) throws Exception {
    File twitterProps = new File(SystemUtils.getUserHome(), "Desktop/twitter.properties");

    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(new FileSystemResource(twitterProps));
    propertiesFactoryBean.afterPropertiesSet();
    Properties props = propertiesFactoryBean.getObject();

    String key = StringUtils.trim(props.getProperty("twitter.oauth.consumerKey"));
    String secret = StringUtils.trim(props.getProperty("twitter.oauth.consumerSecret"));

    ConsoleBasedAccessTokenInitialRequestProcessListener consoleBasedAccessTokenInitialRequestProcessListener = new ConsoleBasedAccessTokenInitialRequestProcessListener();

    Twitter twitter = new TwitterFactory().getOAuthAuthorizedInstance(key, secret);

    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;/*from w  w  w . j  ava2s.  c  om*/
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    while (null == accessToken) {
        String pin = consoleBasedAccessTokenInitialRequestProcessListener
                .openUrlAndReturnPin(requestToken.getAuthorizationURL());

        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    }

    consoleBasedAccessTokenInitialRequestProcessListener.persistReturnedAccessToken(accessToken);

}