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:io.swagger.assert4j.maven.RunMojo.java

private void readRecipeProperties() throws IOException {
    File recipeProperties = new File(recipeDirectory, "recipe.properties");
    if (properties == null) {
        properties = new HashMap();
    }/*from  w  w w  .  j  av  a  2  s .  c  o  m*/
    if (recipeProperties.exists()) {
        Properties props = new Properties();
        props.load(new FileInputStream(recipeProperties));
        getLog().debug("Read " + props.size() + " properties from recipe.properties");

        // override with properties in config section
        if (properties != null) {
            props.putAll(properties);
        }

        properties = props;
    }
}

From source file:org.sakaiproject.hierarchy.tool.vm.spring.VelocityView.java

/**
 * Set tool attributes to expose to the view, as attribute name / class name pairs.
 * An instance of the given class will be added to the Velocity context for each
 * rendering operation, under the given attribute name.
 * <p>For example, an instance of MathTool, which is part of the generic package
 * of Velocity Tools, can be bound under the attribute name "math", specifying the
 * fully qualified class name "org.apache.velocity.tools.generic.MathTool" as value.
 * <p>Note that VelocityView can only create simple generic tools or values, that is,
 * classes with a public default constructor and no further initialization needs.
 * This class does not do any further checks, to not introduce a required dependency
 * on a specific tools package.//from  www .  jav a 2  s . co  m
 * <p>For tools that are part of the view package of Velocity Tools, a special
 * Velocity context and a special init callback are needed. Use VelocityToolboxView
 * in such a case, or override <code>createVelocityContext</code> and
 * <code>initTool</code> accordingly.
 * <p>For a simple VelocityFormatter instance or special locale-aware instances
 * of DateTool/NumberTool, which are part of the generic package of Velocity Tools,
 * specify the "velocityFormatterAttribute", "dateToolAttribute" or
 * "numberToolAttribute" properties, respectively.
 * @param toolAttributes attribute names as keys, and tool class names as values
 * @see org.apache.velocity.tools.generic.MathTool
 * @see VelocityToolboxView
 * @see #createVelocityContext
 * @see #initTool
 * @see #setVelocityFormatterAttribute
 * @see #setDateToolAttribute
 * @see #setNumberToolAttribute
 */
public void setToolAttributes(Properties toolAttributes) {
    this.toolAttributes = new HashMap(toolAttributes.size());
    for (Enumeration attributeNames = toolAttributes.propertyNames(); attributeNames.hasMoreElements();) {
        String attributeName = (String) attributeNames.nextElement();
        String className = toolAttributes.getProperty(attributeName);
        Class toolClass = null;
        try {
            toolClass = ClassUtils.forName(className);
        } catch (ClassNotFoundException ex) {
            throw new IllegalArgumentException("Invalid definition for tool '" + attributeName
                    + "' - tool class not found: " + ex.getMessage());
        }
        this.toolAttributes.put(attributeName, toolClass);
    }
}

From source file:com.savy3.util.DBConfiguration.java

/** Returns a connection object to the DB.
 * @throws ClassNotFoundException//from www. ja  va 2 s  .com
 * @throws SQLException */
public Connection getConnection() throws ClassNotFoundException, SQLException {
    Connection connection;

    Class.forName(conf.get(DBConfiguration.DRIVER_CLASS_PROPERTY));

    String username = conf.get(DBConfiguration.USERNAME_PROPERTY);
    String password = getPassword((JobConf) conf);
    String connectString = conf.get(DBConfiguration.URL_PROPERTY);
    String connectionParamsStr = conf.get(DBConfiguration.CONNECTION_PARAMS_PROPERTY);
    Properties connectionParams = propertiesFromString(connectionParamsStr);

    if (connectionParams != null && connectionParams.size() > 0) {
        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 {
        if (username == null) {
            connection = DriverManager.getConnection(connectString);
        } else {
            connection = DriverManager.getConnection(connectString, username, password);
        }
    }

    return connection;
}

From source file:org.apache.nifi.properties.NiFiPropertiesLoader.java

/**
 * Returns a {@link ProtectedNiFiProperties} instance loaded from the
 * serialized form in the file. Responsible for actually reading from disk
 * and deserializing the properties. Returns a protected instance to allow
 * for decryption operations.//from   w ww.ja  v  a  2 s  . c om
 *
 * @param file the file containing serialized properties
 * @return the ProtectedNiFiProperties instance
 */
ProtectedNiFiProperties readProtectedPropertiesFromDisk(File file) {
    if (file == null || !file.exists() || !file.canRead()) {
        String path = (file == null ? "missing file" : file.getAbsolutePath());
        logger.error("Cannot read from '{}' -- file is missing or not readable", path);
        throw new IllegalArgumentException("NiFi properties file missing or unreadable");
    }

    Properties rawProperties = new Properties();

    InputStream inStream = null;
    try {
        inStream = new BufferedInputStream(new FileInputStream(file));
        rawProperties.load(inStream);
        logger.info("Loaded {} properties from {}", rawProperties.size(), file.getAbsolutePath());

        ProtectedNiFiProperties protectedNiFiProperties = new ProtectedNiFiProperties(rawProperties);
        return protectedNiFiProperties;
    } catch (final Exception ex) {
        logger.error("Cannot load properties file due to " + ex.getLocalizedMessage());
        throw new RuntimeException("Cannot load properties file due to " + ex.getLocalizedMessage(), ex);
    } finally {
        if (null != inStream) {
            try {
                inStream.close();
            } catch (final Exception ex) {
                /**
                 * do nothing *
                 */
            }
        }
    }
}

From source file:org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver.java

/**
 * Load the specified NamespaceHandler mappings lazily.
 *///w  w  w.  java 2s.c o  m
private Map<String, Object> getHandlerMappings() {
    Map<String, Object> handlerMappings = this.handlerMappings;
    if (handlerMappings == null) {
        synchronized (this) {
            handlerMappings = this.handlerMappings;
            if (handlerMappings == null) {
                try {
                    Properties mappings = PropertiesLoaderUtils.loadAllProperties(this.handlerMappingsLocation,
                            this.classLoader);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Loaded NamespaceHandler mappings: " + mappings);
                    }
                    Map<String, Object> mappingsToUse = new ConcurrentHashMap<>(mappings.size());
                    CollectionUtils.mergePropertiesIntoMap(mappings, mappingsToUse);
                    handlerMappings = mappingsToUse;
                    this.handlerMappings = handlerMappings;
                } catch (IOException ex) {
                    throw new IllegalStateException("Unable to load NamespaceHandler mappings from location ["
                            + this.handlerMappingsLocation + "]", ex);
                }
            }
        }
    }
    return handlerMappings;
}

From source file:com.izforge.izpack.event.AntAction.java

private void addProperties(Project proj, Properties props) {
    if (proj == null) {
        return;/*w  w  w.  j  a v  a  2 s.  c  o  m*/
    }
    if (props.size() > 0) {
        for (Object o : props.keySet()) {
            String key = (String) o;
            proj.setProperty(key, props.getProperty(key));
        }
    }
}

From source file:de.innovationgate.webgate.api.jdbc.pool.DBCPConnectionProvider.java

public void configure(Map propsMap) throws HibernateException {
    try {//from w  w w .  ja va  2 s . c o m
        log.debug("Configure DBCPConnectionProvider");
        Properties props = new Properties();
        props.putAll(propsMap);

        String jdbcUrl = (String) props.getProperty(Environment.URL);

        // DBCP properties used to create the BasicDataSource
        Properties dbcpProperties = new Properties();

        // DriverClass & url
        String jdbcDriverClass = props.getProperty(Environment.DRIVER);

        // Try to determine driver by jdbc-URL
        if (jdbcDriverClass == null) {
            Driver driver = DriverManager.getDriver(jdbcUrl);
            if (driver != null) {
                jdbcDriverClass = driver.getClass().getName();
            } else {
                throw new HibernateException("Driver class not available");
            }
        }

        dbcpProperties.put("driverClassName", jdbcDriverClass);
        dbcpProperties.put("url", jdbcUrl);

        // Username / password
        String username = props.getProperty(Environment.USER);
        if (username != null) {
            dbcpProperties.put("username", username);
        }

        String password = props.getProperty(Environment.PASS);
        if (password != null) {
            dbcpProperties.put("password", password);
        }

        // Isolation level
        String isolationLevel = props.getProperty(Environment.ISOLATION);
        if ((isolationLevel != null) && (isolationLevel.trim().length() > 0)) {
            dbcpProperties.put("defaultTransactionIsolation", isolationLevel);
        }

        // Turn off autocommit (unless autocommit property is set) 
        String autocommit = props.getProperty(AUTOCOMMIT);
        if ((autocommit != null) && (autocommit.trim().length() > 0)) {
            dbcpProperties.put("defaultAutoCommit", autocommit);
        } else {
            dbcpProperties.put("defaultAutoCommit", String.valueOf(Boolean.FALSE));
        }

        // Pool size
        String poolSize = props.getProperty(Environment.POOL_SIZE);
        if ((poolSize != null) && (poolSize.trim().length() > 0) && (Integer.parseInt(poolSize) > 0)) {
            dbcpProperties.put("maxActive", poolSize);
        }

        // Copy all "driver" properties into "connectionProperties"
        Properties driverProps = ConnectionProviderInitiator.getConnectionProperties(props);
        if (driverProps.size() > 0) {
            StringBuffer connectionProperties = new StringBuffer();
            for (Iterator iter = driverProps.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                String value = driverProps.getProperty(key);
                connectionProperties.append(key).append('=').append(value);
                if (iter.hasNext()) {
                    connectionProperties.append(';');
                }
            }
            dbcpProperties.put("connectionProperties", connectionProperties.toString());
        }

        // Copy all DBCP properties removing the prefix
        for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
            String key = String.valueOf(iter.next());
            if (key.startsWith(PREFIX)) {
                String property = key.substring(PREFIX.length());
                String value = props.getProperty(key);
                dbcpProperties.put(property, value);
            }
        }

        // Backward-compatibility
        if (props.getProperty(DBCP_PS_MAXACTIVE) != null) {
            dbcpProperties.put("poolPreparedStatements", String.valueOf(Boolean.TRUE));
            dbcpProperties.put("maxOpenPreparedStatements", props.getProperty(DBCP_PS_MAXACTIVE));
        }
        if (props.getProperty(DBCP_MAXACTIVE) != null) {
            dbcpProperties.put("maxTotal", props.getProperty(DBCP_MAXACTIVE));
        }
        if (props.getProperty(DBCP_MAXWAIT) != null) {
            dbcpProperties.put("maxWaitMillis", props.getProperty(DBCP_MAXWAIT));
        }

        // Some debug info
        if (log.isDebugEnabled()) {
            log.debug("Creating a DBCP BasicDataSource with the following DBCP factory properties:");
            StringWriter sw = new StringWriter();
            dbcpProperties.list(new PrintWriter(sw, true));
            log.debug(sw.toString());
        }

        String dbKey = (String) props.get("hibernate.dbcp.dbkey");
        String databaseServerId = (String) props.get("hibernate.dbcp.dbserver.id");

        // Enable DBCP2 JMX monitoring information
        if (dbKey != null) {
            dbcpProperties.put("jmxName",
                    JMX_DBCP2_DBPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(dbKey));
        } else if (databaseServerId != null) {
            String entityTitle = props.getProperty("hibernate.dbcp.dbserver.title");
            dbcpProperties.put("jmxName",
                    JMX_DBCP2_SERVERPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(entityTitle));
        }

        // Let the factory create the pool
        _ds = BasicDataSourceFactory.createDataSource(dbcpProperties);
        _ds.setLogExpiredConnections(false);

        // The BasicDataSource has lazy initialization
        // borrowing a connection will start the DataSource
        // and make sure it is configured correctly.
        Connection conn = _ds.getConnection();
        conn.close();

        // Create Legacy JMX monitoring information, provided by WGA
        if ("true".equals(props.getProperty("hibernate.dbcp.legacyJMX"))) {
            try {
                if (dbKey != null) {
                    _entityKey = dbKey;
                    _entityTitle = dbKey;
                    _jmxManager = new JmxManager(new DBCPPoolInformation(this),
                            new ObjectName(JMX_DBPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(dbKey)));
                } else if (databaseServerId != null) {
                    _server = true;
                    _entityKey = databaseServerId;
                    _entityTitle = (String) props.get("hibernate.dbcp.dbserver.title");
                    _jmxManager = new JmxManager(new DBCPPoolInformation(this), new ObjectName(
                            JMX_SERVERPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(_entityTitle)));
                }
            } catch (Throwable e) {
                log.error("Error enabling JMX metrics for connection pool", e);
            }
        }

    } catch (Exception e) {
        String message = "Could not create a DBCP pool";
        if (_ds != null) {
            try {
                _ds.close();
            } catch (Exception e2) {
                // ignore
            }
            _ds = null;
        }
        throw new HibernateException(message, e);
    }
    log.debug("Configure DBCPConnectionProvider complete");

}

From source file:com.github.dakusui.symfonion.CLI.java

public void analyze(CommandLine cmd) throws CLIException {
    if (cmd.hasOption('O')) {
        String optionName = "O";
        this.midiouts = initializeMidiPorts(cmd, optionName);
    }/*from ww  w .  j  a  v a2  s.c  o m*/
    if (cmd.hasOption('I')) {
        String optionName = "I";
        this.midiins = initializeMidiPorts(cmd, optionName);
    }
    if (cmd.hasOption('o')) {
        String sinkFilename = getSingleOptionValue(cmd, "o");
        if (sinkFilename == null) {
            String msg = composeErrMsg("Output filename is required by this option.", "o", null);
            throw new CLIException(msg);
        }
        this.sink = new File(sinkFilename);
    }
    if (cmd.hasOption("V") || cmd.hasOption("version")) {
        this.mode = Mode.VERSION;
    } else if (cmd.hasOption("h") || cmd.hasOption("help")) {
        this.mode = Mode.HELP;
    } else if (cmd.hasOption("l") || cmd.hasOption("list")) {
        this.mode = Mode.LIST;
    } else if (cmd.hasOption("p") || cmd.hasOption("play")) {
        this.mode = Mode.PLAY;
        String sourceFilename = getSingleOptionValue(cmd, "p");
        if (sourceFilename == null) {
            String msg = composeErrMsg("Input filename is required by this option.", "p", null);
            throw new CLIException(msg);
        }
        this.source = new File(sourceFilename);
    } else if (cmd.hasOption("c") || cmd.hasOption("compile")) {
        this.mode = Mode.COMPILE;
        String sourceFilename = getSingleOptionValue(cmd, "c");
        if (sourceFilename == null) {
            String msg = composeErrMsg("Input filename is required by this option.", "c", null);
            throw new CLIException(msg);
        }
        this.source = new File(sourceFilename);
    } else if (cmd.hasOption("r") || cmd.hasOption("route")) {
        this.mode = Mode.ROUTE;
        Properties props = cmd.getOptionProperties("r");
        if (props.size() != 1) {
            String msg = composeErrMsg("Route information is not given or specified multiple times.", "r",
                    "route");
            throw new CLIException(msg);
        }

        this.route = new Route(cmd.getOptionValues('r')[0], cmd.getOptionValues('r')[1]);
    } else {
        @SuppressWarnings("unchecked")
        List<String> leftovers = cmd.getArgList();
        if (leftovers.size() == 0) {
            this.mode = Mode.HELP;
        } else if (leftovers.size() == 1) {
            this.mode = Mode.PLAY;
            this.source = new File(leftovers.get(0));
        } else {
            String msg = composeErrMsg(
                    String.format("Unrecognized arguments:%s", leftovers.subList(2, leftovers.size())), "-",
                    null);
            throw new CLIException(msg);
        }
    }
}

From source file:net.sf.yal10n.analyzer.ExploratoryEncodingTest.java

/**
 * Test to load java properties files with a BOM.
 * @throws Exception any error/*from ww w  .j  av  a  2 s.co  m*/
 */
@Test
public void testPropertiesWithBOM() throws Exception {
    Properties properties = new Properties();
    InputStream in = ExploratoryEncodingTest.class.getResourceAsStream("/UTF8BOM.properties");

    // ------
    // need to skip 3 bytes, the BOM bytes
    // in.skip(3);
    // ------

    properties.load(new InputStreamReader(in, "UTF-8"));
    Assert.assertEquals(3, properties.size());

    // Assert.assertEquals("first key", properties.getProperty("testkey1"));
    // note: utf-8 bom read as first character
    Assert.assertEquals("first key", properties.getProperty("\ufefftestkey1"));

    Assert.assertEquals("second key", properties.getProperty("testkey2"));
    Assert.assertEquals("This file is encoded as UTF-8 with BOM .", properties.getProperty("description"));
}

From source file:org.jets3t.service.utils.signedurl.GatekeeperClientUtils.java

/**
 * Request permission from the Gatekeeper for a particular operation.
 *
 * @param operationType//from   w w  w .j av a2  s.c o  m
 * @param bucketName
 * @param objects
 * @param applicationPropertiesMap
 * @throws HttpException
 * @throws Exception
 */
public GatekeeperMessage requestActionThroughGatekeeper(String operationType, String bucketName,
        S3Object[] objects, Map applicationPropertiesMap) throws HttpException, Exception {
    /*
     *  Build Gatekeeper request.
     */
    GatekeeperMessage gatekeeperMessage = new GatekeeperMessage();
    gatekeeperMessage.addApplicationProperties(applicationPropertiesMap);
    gatekeeperMessage.addApplicationProperty(GatekeeperMessage.PROPERTY_CLIENT_VERSION_ID,
            userAgentDescription);

    // If a prior failure has occurred, add information about this failure.
    if (priorFailureException != null) {
        gatekeeperMessage.addApplicationProperty(GatekeeperMessage.PROPERTY_PRIOR_FAILURE_MESSAGE,
                priorFailureException.getMessage());
        // Now reset the prior failure variable.
        priorFailureException = null;
    }

    // Add all S3 objects as candiates for PUT signing.
    for (int i = 0; i < objects.length; i++) {
        SignatureRequest signatureRequest = new SignatureRequest(operationType, objects[i].getKey());
        signatureRequest.setObjectMetadata(objects[i].getMetadataMap());
        signatureRequest.setBucketName(bucketName);

        gatekeeperMessage.addSignatureRequest(signatureRequest);
    }

    /*
     *  Build HttpClient POST message.
     */

    // Add all properties/parameters to credentials POST request.
    HttpPost postMethod = new HttpPost(gatekeeperUrl);
    Properties properties = gatekeeperMessage.encodeToProperties();
    Iterator<Map.Entry<Object, Object>> propsIter = properties.entrySet().iterator();
    List<NameValuePair> parameters = new ArrayList<NameValuePair>(properties.size());
    while (propsIter.hasNext()) {
        Map.Entry<Object, Object> entry = propsIter.next();
        String fieldName = (String) entry.getKey();
        String fieldValue = (String) entry.getValue();
        parameters.add(new BasicNameValuePair(fieldName, fieldValue));
    }
    postMethod.setEntity(new UrlEncodedFormEntity(parameters));

    // Create Http Client if necessary, and include User Agent information.
    if (httpClientGatekeeper == null) {
        httpClientGatekeeper = initHttpConnection();
    }

    // Try to detect any necessary proxy configurations.
    try {
        HttpHost proxyHost = PluginProxyUtil.detectProxy(new URL(gatekeeperUrl));
        if (proxyHost != null) {
            httpClientGatekeeper.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        }
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.debug("No proxy detected");
        }
    }

    // Perform Gateway request.
    if (log.isDebugEnabled()) {
        log.debug("Contacting Gatekeeper at: " + gatekeeperUrl);
    }
    HttpResponse response = null;
    try {
        response = httpClientGatekeeper.execute(postMethod);
        int responseCode = response.getStatusLine().getStatusCode();
        String contentType = response.getFirstHeader("Content-Type").getValue();
        if (responseCode == 200) {
            InputStream responseInputStream = null;

            Header encodingHeader = response.getFirstHeader("Content-Encoding");
            if (encodingHeader != null && "gzip".equalsIgnoreCase(encodingHeader.getValue())) {
                if (log.isDebugEnabled()) {
                    log.debug("Inflating gzip-encoded response");
                }
                responseInputStream = new GZIPInputStream(response.getEntity().getContent());
            } else {
                responseInputStream = response.getEntity().getContent();
            }

            if (responseInputStream == null) {
                throw new IOException("No response input stream available from Gatekeeper");
            }

            Properties responseProperties = new Properties();
            try {
                responseProperties.load(responseInputStream);
            } finally {
                responseInputStream.close();
            }

            GatekeeperMessage gatekeeperResponseMessage = GatekeeperMessage
                    .decodeFromProperties(responseProperties);

            // Check for Gatekeeper Error Code in response.
            String gatekeeperErrorCode = gatekeeperResponseMessage.getApplicationProperties()
                    .getProperty(GatekeeperMessage.APP_PROPERTY_GATEKEEPER_ERROR_CODE);
            if (gatekeeperErrorCode != null) {
                if (log.isWarnEnabled()) {
                    log.warn("Received Gatekeeper error code: " + gatekeeperErrorCode);
                }
            }

            return gatekeeperResponseMessage;
        } else {
            if (log.isDebugEnabled()) {
                log.debug("The Gatekeeper did not permit a request. Response code: " + responseCode
                        + ", Response content type: " + contentType);
            }
            throw new IOException("The Gatekeeper did not permit your request");
        }
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new Exception("Gatekeeper did not respond", e);
    } finally {
        try {
            EntityUtils.consume(response.getEntity());
        } catch (Exception ee) {
            // ignore
        }
    }
}