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

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

Introduction

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

Prototype

public void setLocation(Resource location) 

Source Link

Document

Set a location of a properties file to be loaded.

Usage

From source file:org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration.java

/**
 * The {@link MessageSourceAccessor} to provide messages for {@link ResourceDescription}s being rendered.
 * /*w ww .  j a v a2 s. c  o  m*/
 * @return
 */
@Bean
public MessageSourceAccessor resourceDescriptionMessageSourceAccessor() {

    try {

        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("rest-default-messages.properties"));
        propertiesFactoryBean.afterPropertiesSet();

        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:rest-messages");
        messageSource.setCommonMessages(propertiesFactoryBean.getObject());
        messageSource.setDefaultEncoding("UTF-8");

        return new MessageSourceAccessor(messageSource);

    } catch (Exception o_O) {
        throw new BeanCreationException("resourceDescriptionMessageSourceAccessor", "", o_O);
    }
}

From source file:org.rifidi.edge.api.service.appmanager.FilePropertyResolver.java

private Properties getProperties(UrlResource resource) throws IOException {
    PropertiesFactoryBean appPropertiesFactoryBean = new PropertiesFactoryBean();
    appPropertiesFactoryBean.setLocation(resource);
    appPropertiesFactoryBean.afterPropertiesSet();
    return (Properties) appPropertiesFactoryBean.getObject();
}

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(
            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;
        }//from ww w .j a  v a2 s .c  o  m
        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//ww w  . j a va2 s  . c om
    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// www . ja  v  a  2s  .  c  o  m
@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//  w  w  w .  j a  v a 2  s  .  c o 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 2s .  com*/
@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;/* w  w w  .j  a  v  a 2s  . c  o m*/
    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);

}