Example usage for java.util Properties size

List of usage examples for java.util Properties size

Introduction

In this page you can find the example usage for java.util Properties size.

Prototype

@Override
    public int size() 

Source Link

Usage

From source file:org.webdavaccess.LocalFileSystemStorage.java

private Properties getPropertiesFor(String uri) {
    uri = normalize(uri);//from   w  w  w  .  j ava2 s.c  om
    File file = getPropertiesFile(uri);
    if (file == null || !file.exists()) {
        return null;
    }
    InputStream in = null;
    Properties persisted = new Properties();
    try {
        in = new FileInputStream(file);
        persisted.loadFromXML(in);
    } catch (Exception e) {
        log.warn("Failed to get properties from cache for " + uri);
        return null;
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Exception e) {
            }
    }
    Enumeration en = persisted.keys();
    Properties props = new Properties();
    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        if (isResourceProperty(uri, key)) {
            String newKey = getPropertyKey(uri, key);
            props.setProperty(newKey, persisted.getProperty(key));
        }
    }
    return (props.size() == 0) ? null : props;
}

From source file:org.intermine.sql.Database.java

/**
 * Configures a datasource from a Properties object
 *
 * @param props the properties for configuring the Database
 * @throws ClassNotFoundException if the class given in the properties file cannot be found
 * @throws IllegalArgumentException if the configuration properties are empty
 * @throws NullPointerException if props is null
 *///from   w ww.ja  v  a 2 s.  c om
protected void configure(Properties props) throws ClassNotFoundException {
    if (props == null) {
        throw new NullPointerException("Props cannot be null");
    }

    if (props.size() == 0) {
        throw new IllegalArgumentException("No configuration details");
    }

    Properties subProps = new Properties();

    for (Map.Entry<Object, Object> entry : props.entrySet()) {
        String propertyName = (String) entry.getKey();
        String propertyValue = (String) entry.getValue();
        Field field = null;

        // Get the first part of the string - this is the attribute we are taking about
        String attribute = propertyName;
        String subAttribute = "";
        int index = propertyName.indexOf(".");
        if (index != -1) {
            attribute = propertyName.substring(0, index);
            subAttribute = propertyName.substring(index + 1);
        }

        try {
            field = Database.class.getDeclaredField(attribute);
        } catch (Exception e) {
            LOG.warn("Ignoring field for Database: " + attribute);
            // Ignore this property - no such field
            continue;
        }

        if ("class".equals(subAttribute)) {
            // make a new instance of this class for this attribute
            Class<?> clazz = Class.forName(propertyValue.toString());
            Object obj;
            try {
                obj = clazz.newInstance();
            } catch (Exception e) {
                throw new ClassNotFoundException(
                        "Cannot instantiate class " + clazz.getName() + " " + e.getMessage());
            }
            // Set the field to this newly instantiated class
            try {
                field.set(this, obj);
            } catch (Exception e) {
                continue;
            }
        } else if ("".equals(subAttribute)) {
            // Set this attribute directly
            try {
                field.set(this, propertyValue);
            } catch (Exception e) {
                continue;
            }
        } else {
            // Set parameters on the attribute
            Method m = null;
            // Set this configuration parameter on the DataSource;
            try {
                // Strings first
                Object o = field.get(this);
                // Sometimes the class will not have been instantiated yet
                if (o == null) {
                    subProps.put(propertyName, propertyValue);
                    continue;
                }
                Class<?> clazz = o.getClass();
                m = clazz.getMethod("set" + StringUtil.capitalise(subAttribute), new Class[] { String.class });
                if (m != null) {
                    m.invoke(field.get(this), new Object[] { propertyValue });
                }
                // now integers
            } catch (Exception e) {
                // Don't do anything - either the method not found or cannot be invoked
            }
            try {
                if (m == null) {
                    m = field.get(this).getClass().getMethod("set" + StringUtil.capitalise(subAttribute),
                            new Class[] { int.class });
                    if (m != null) {
                        m.invoke(field.get(this), new Object[] { Integer.valueOf(propertyValue.toString()) });
                    }
                }
            } catch (Exception e) {
                // Don't do anything - either the method not found or cannot be invoked
            }
        }
        if (subProps.size() > 0) {
            configure(subProps);
        }
    }

}

From source file:com.dtolabs.rundeck.core.common.impl.URLFileUpdater.java

/**
 * Cache etag and last-modified header info for a response
 *///from w ww .j  a v  a2  s .co  m
private void cacheResponseInfo(final httpClientInteraction method, final File cacheFile) {
    //write cache data to file if present
    Properties newprops = new Properties();

    if (null != method.getResponseHeader(LAST_MODIFIED)) {
        newprops.setProperty(LAST_MODIFIED, method.getResponseHeader(LAST_MODIFIED).getValue());
    }
    if (null != method.getResponseHeader(E_TAG)) {
        newprops.setProperty(E_TAG, method.getResponseHeader(E_TAG).getValue());
    }
    if (null != method.getResponseHeader(CONTENT_TYPE)) {
        newprops.setProperty(CONTENT_TYPE, method.getResponseHeader(CONTENT_TYPE).getValue());
    }
    if (newprops.size() > 0) {
        try {
            final FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
            try {
                newprops.store(fileOutputStream, "URLFileUpdater cache data for URL: " + url);
            } finally {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            logger.debug("Failed to write cache header info to file: " + cacheFile + ", " + e.getMessage(), e);
        }
    } else if (cacheFile.exists()) {
        if (!cacheFile.delete()) {
            logger.warn("Unable to delete cachefile: " + cacheFile.getAbsolutePath());
        }
    }
}

From source file:org.apache.sqoop.manager.SqlManager.java

/**
 * Create a connection to the database; usually used only from within
 * getConnection(), which enforces a singleton guarantee around the
 * Connection object./*from  ww  w.jav  a 2 s  . c  o m*/
 */
protected Connection makeConnection() throws SQLException {

    Connection connection;
    String driverClass = getDriverClass();

    try {
        Class.forName(driverClass);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException("Could not load db driver class: " + driverClass);
    }

    String username = options.getUsername();
    String password = options.getPassword();
    String connectString = options.getConnectString();
    Properties connectionParams = options.getConnectionParams();
    if (connectionParams != null && connectionParams.size() > 0) {
        LOG.debug(
                "User specified connection params. " + "Using properties specific API for making connection.");

        Properties props = new Properties();
        if (username != null) {
            props.put("user", username);
        }

        if (password != null) {
            props.put("password", password);
        }

        props.putAll(connectionParams);
        connection = DriverManager.getConnection(connectString, props);
    } else {
        LOG.debug("No connection paramenters specified. " + "Using regular API for making connection.");
        if (username == null) {
            connection = DriverManager.getConnection(connectString);
        } else {
            connection = DriverManager.getConnection(connectString, username, password);
        }
    }

    // We only use this for metadata queries. Loosest semantics are okay.
    connection.setTransactionIsolation(getMetadataIsolationLevel());
    connection.setAutoCommit(false);

    return connection;
}

From source file:org.sonar.batch.scan.DefaultProjectBootstrapperTest.java

@Test
public void shouldMergeParentProperties() {
    Properties parentProps = new Properties();
    parentProps.setProperty("toBeMergeProps", "fooParent");
    parentProps.setProperty("existingChildProp", "barParent");
    parentProps.setProperty("sonar.modules", "mod1,mod2");
    parentProps.setProperty("sonar.projectDescription", "Desc from Parent");
    parentProps.setProperty("mod1.sonar.projectDescription", "Desc for Mod1");
    parentProps.setProperty("mod2.sonar.projectkey", "Key for Mod2");

    Properties childProps = new Properties();
    childProps.setProperty("existingChildProp", "barChild");
    childProps.setProperty("otherProp", "tutuChild");

    DefaultProjectBootstrapper.mergeParentProperties(childProps, parentProps);

    assertThat(childProps.size()).isEqualTo(3);
    assertThat(childProps.getProperty("toBeMergeProps")).isEqualTo("fooParent");
    assertThat(childProps.getProperty("existingChildProp")).isEqualTo("barChild");
    assertThat(childProps.getProperty("otherProp")).isEqualTo("tutuChild");
    assertThat(childProps.getProperty("sonar.modules")).isNull();
    assertThat(childProps.getProperty("sonar.projectDescription")).isNull();
    assertThat(childProps.getProperty("mod1.sonar.projectDescription")).isNull();
    assertThat(childProps.getProperty("mod2.sonar.projectkey")).isNull();
}

From source file:org.flywaydb.test.junit.FlywayHelperFactory.java

/**
 * Create a new flyway instance and call {@link Flyway#configure(java.util.Properties)}  with
 * content of file <i>flyway.properties</i>.
 *
 * @return the flyway instance//from   www.ja va  2 s. c om
 */
public synchronized Flyway createFlyway() {

    if (flyway == null) {
        logger.info("Create a new flyway instance.");
        Flyway toReturn = new Flyway();
        setFlyway(toReturn);

        // now use the flyway properties
        Properties configuredProperties = getFlywayProperties();

        if (configuredProperties == null) {
            // try to search flyway.properties in classpath
            configuredProperties = new Properties();
            setFlywayProperties(configuredProperties);

            ClassPathResource classPathResource = new ClassPathResource("flyway.properties");

            InputStream inputStream = null;

            try {
                inputStream = classPathResource.getInputStream();
                configuredProperties.load(inputStream);
                inputStream.close();
            } catch (IOException e) {
                logger.error("Can not load flyway.properties.", e);
            }

            logger.info(String.format("Load flyway.properties with %d entries.", configuredProperties.size()));
        } else {
            logger.info(String.format("Used preconfigured flyway.properties with %d entries.",
                    configuredProperties.size()));
        }

        toReturn.configure(getFlywayProperties());
    }

    return flyway;
}

From source file:org.apache.sqoop.manager.OracleManager.java

/**
 * Create a connection to the database; usually used only from within
 * getConnection(), which enforces a singleton guarantee around the
 * Connection object.//from   w  w  w  . j  a  v a 2s.  c o m
 *
 * Oracle-specific driver uses READ_COMMITTED which is the weakest
 * semantics Oracle supports.
 */
protected Connection makeConnection() throws SQLException {

    Connection connection;
    String driverClass = getDriverClass();

    try {
        Class.forName(driverClass);
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException("Could not load db driver class: " + driverClass);
    }

    String username = options.getUsername();
    String password = options.getPassword();
    String connectStr = options.getConnectString();

    connection = CACHE.getConnection(connectStr, username);
    if (null == connection) {
        // Couldn't pull one from the cache. Get a new one.
        LOG.debug("Creating a new connection for " + connectStr + ", using username: " + username);
        Properties connectionParams = options.getConnectionParams();
        if (connectionParams != null && connectionParams.size() > 0) {
            LOG.debug("User specified connection params. "
                    + "Using properties specific API for making connection.");

            Properties props = new Properties();
            if (username != null) {
                props.put("user", username);
            }

            if (password != null) {
                props.put("password", password);
            }

            props.putAll(connectionParams);
            connection = DriverManager.getConnection(connectStr, props);
        } else {
            LOG.debug("No connection paramenters specified. " + "Using regular API for making connection.");
            if (username == null) {
                connection = DriverManager.getConnection(connectStr);
            } else {
                connection = DriverManager.getConnection(connectStr, username, password);
            }
        }
    }

    // We only use this for metadata queries. Loosest semantics are okay.
    connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

    // Setting session time zone
    setSessionTimeZone(connection);

    return connection;
}

From source file:org.rhq.server.control.command.AbstractInstall.java

private String[] toArray(Properties properties) {
    String[] array = new String[properties.size() * 2];
    int i = 0;/*from   w w  w.j  av a  2 s .c o  m*/
    for (Object key : properties.keySet()) {
        array[i++] = "--" + (String) key;
        array[i++] = properties.getProperty((String) key);
    }
    return array;
}

From source file:org.fuin.utils4j.Utils4JTest.java

/**
 * @testng.test//from w w w .j  a v a  2 s  .c o  m
 */
public final void testLoadPropertiesFile() throws IOException {
    final Properties props = Utils4J.loadProperties(TEST_PROPERTIES_FILE);
    Assert.assertEquals(3, props.size());
    Assert.assertEquals("1", props.get("one"));
    Assert.assertEquals("2", props.get("two"));
    Assert.assertEquals("3", props.get("three"));
}

From source file:cn.newgxu.lab.core.config.SpringBeans.java

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource(dataSource());
    entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter());

    Properties properties = new Properties();
    properties.setProperty("hibernate.hbm2ddl.auto", "none");
    //      properties.setProperty("hibernate.hbm2ddl.auto", "update");
    entityManagerFactoryBean.setJpaProperties(properties);

    properties.clear();/*from   ww  w  .  ja  v  a2  s .c o m*/
    InputStream in = null;
    try {
        in = this.getClass().getResourceAsStream("/config/entityPackages.properties");
        properties.load(in);
    } catch (IOException e) {
        L.error("?EntityManagerFactory", e);
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            L.error("wtf!", e);
        }
    }
    String[] entityPackages = new String[properties.size()];
    int i = 0;
    for (Object pkg : properties.keySet()) {
        entityPackages[i++] = properties.getProperty(pkg.toString());
    }
    entityManagerFactoryBean.setPackagesToScan(entityPackages);
    return entityManagerFactoryBean;
}