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:net.sf.navigator.util.PropertyMessageResources.java

/**
 * Load the messages associated with the specified Locale key.  For this
 * implementation, the <code>config</code> property should contain a fully
 * qualified package and resource name, separated by periods, of a series
 * of property resources to be loaded from the class loader that created
 * this PropertyMessageResources instance.  This is exactly the same name
 * format you would use when utilizing the
 * <code>java.util.PropertyResourceBundle</code> class.
 *
 * @param localeKey Locale key for the messages to be retrieved
 *//*from  w ww.  j a  va 2s .c o  m*/
protected synchronized void loadLocale(String localeKey) {

    if (log.isTraceEnabled()) {
        log.trace("loadLocale(" + localeKey + ")");
    }

    // Have we already attempted to load messages for this locale?
    if (locales.get(localeKey) != null) {
        return;
    }

    locales.put(localeKey, localeKey);

    // Set up to load the property resource for this locale key, if we can
    String name = config.replace('.', '/');
    if (localeKey.length() > 0) {
        name += "_" + localeKey;
    }

    name += ".properties";
    InputStream is = null;
    Properties props = new Properties();

    // Load the specified property resource
    if (log.isTraceEnabled()) {
        log.trace("  Loading resource '" + name + "'");
    }

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader == null) {
        classLoader = this.getClass().getClassLoader();
    }

    is = classLoader.getResourceAsStream(name);
    if (is != null) {
        try {
            props.load(is);

        } catch (IOException e) {
            log.error("loadLocale()", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                log.error("loadLocale()", e);
            }
        }
    }

    if (log.isTraceEnabled()) {
        log.trace("  Loading resource completed");
    }

    // Copy the corresponding values into our cache
    if (props.size() < 1) {
        return;
    }

    synchronized (messages) {
        Iterator names = props.keySet().iterator();
        while (names.hasNext()) {
            String key = (String) names.next();
            if (log.isTraceEnabled()) {
                log.trace("  Saving message key '" + messageKey(localeKey, key));
            }
            messages.put(messageKey(localeKey, key), props.getProperty(key));
        }
    }

}

From source file:com.aliyun.odps.conf.Configuration.java

/**
 *  {@link DataOutput}/*from  w w  w  .java  2s . c  o m*/
 */
@Override
public void write(DataOutput out) throws IOException {
    Properties props = getProps();
    WritableUtils.writeVInt(out, props.size());
    for (Map.Entry<Object, Object> item : props.entrySet()) {
        com.aliyun.odps.io.Text.writeString(out, (String) item.getKey());
        com.aliyun.odps.io.Text.writeString(out, (String) item.getValue());
    }
}

From source file:org.alfresco.reporting.action.executer.ReportContainerExecutor.java

/**
 * Execute the single report//from  w w  w  .j av a 2 s. co m
 * 
 * @param reportRef the actual report
 * @param targetDocumentRef the new documnt to store the report into
 * @param outputType the type of report to generate (pdf or Excel)
 */
private void executeReportExecuter(final ReportTemplate report, final NodeRef targetDocumentRef,
        final Properties keyValues) {
    logger.debug("enter executeReportExecuter");
    logger.debug("  reportRef        : " + report.getNodeRef());
    logger.debug("  reportName       : " + report.getName());
    logger.debug("  targetDocumentRef: " + targetDocumentRef);
    logger.debug("  outputType       : " + report.getOutputFormat());
    logger.debug("  parameters       : " + keyValues);

    Action action = actionService.createAction(ReportExecuter.NAME);
    action.setParameterValue(ReportExecuter.OUTPUT_TYPE, report.getOutputFormat());
    action.setParameterValue(ReportExecuter.TARGET_DOCUMENT, targetDocumentRef);

    if (keyValues.size() > 0) {
        action.setParameterValue(ReportExecuter.SEPARATOR, Constants.SEPARATOR);

        Enumeration keys = keyValues.keys();

        //Properties namespaces = reportingHelper.getNameSpacesShortToLong();
        /*
        Collection<String> nameSpaceKeys = namespaceService.getURIs();
        for (String myKey:nameSpaceKeys){
           String myValue = namespaceService.getNamespaceURI(myKey);
           logger.debug("Found value: "+ myValue+"  namespacekey: " + myKey);
        }
        */

        int i = 0;
        while (keys.hasMoreElements()) {
            i++;
            String key = (String) keys.nextElement();

            String pushString = key + Constants.SEPARATOR + keyValues.getProperty(key, "");

            logger.debug("Setting report parameter " + key + " = " + keyValues.getProperty(key, ""));

            if (i == 1)
                action.setParameterValue(ReportExecuter.PARAM_1, pushString);
            if (i == 2)
                action.setParameterValue(ReportExecuter.PARAM_2, pushString);
            if (i == 3)
                action.setParameterValue(ReportExecuter.PARAM_3, pushString);
            if (i == 4)
                action.setParameterValue(ReportExecuter.PARAM_4, pushString);

        } // end while key.hasMoreElements
    }

    actionService.executeAction(action, report.getNodeRef());
    logger.debug("Exit executeReportExecuter");
}

From source file:com.linkage.crm.csb.sign.DigitalSignUtil.java

/**
 * .//from  w w w. j a va2 s .c o m
 * @param code  5.:10.3 
 * @param xml xml.
 * @return true/false.
 * @throws IOException .
 */
public boolean verify(String xml, String key, String srcSysId) throws SignException {
    if (StringUtils.isEmpty(xml)) {
        throw new IllegalArgumentException("xml to be verified is null");
    }

    boolean result = false;
    ICAPSigner verifier = null;
    if (srcSysId == null || srcSysId.equals("")) {
        srcSysId = getSrcSysId(xml, key);
    }
    log.debug("srcSysId==" + srcSysId);
    if (srcSysId != null) {

        //SP.
        verifier = (ICAPSigner) verifierMap.get(srcSysId);

        if (verifier == null) {
            // srcSysIdpwd.
            Properties props = new Properties();
            String spConfigFile = null;
            try {
                System.out.println(this.servletContext.getRealPath(String.valueOf(File.separatorChar)));
                System.out.println(this.servletContext.getContextPath());
                configDir = this.servletContext.getRealPath(String.valueOf(File.separatorChar)) + "/META-INF";
                spConfigFile = configDir + File.separator + "keystore" + File.separator + srcSysId
                        + File.separator + "pwd";
                props.load(new FileInputStream(new File(spConfigFile)));
                log.debug("spConfigFile" + spConfigFile);
                log.debug("" + srcSysId + "." + props);
            } catch (Exception e) {
                throw new SignException(SignException.TYPE_VRF, "SP" + spConfigFile,
                        e);
            }
            String fileName = null, alias = null, password = null, certFileName = null;
            if (props != null && props.size() > 0) {
                fileName = props.getProperty("filename");
                alias = props.getProperty("alias");
                password = props.getProperty("password");
                certFileName = props.getProperty("certfile");

                log.debug("%%%%%%%%%%%%%%%%" + fileName + "===" + alias + "===" + password + "==="
                        + certFileName);
                {
                    verifier = new DefaultCAPSigner(password, alias,
                            configDir + File.separator + "keystore" + File.separator + srcSysId + File.separator
                                    + fileName, // 
                            configDir + File.separator + "keystore" + File.separator + srcSysId + File.separator
                                    + certFileName); // 

                    verifierMap.put(srcSysId, verifier);

                }
            } else {
                log.error(",srcSysId=" + srcSysId);
            }
        }
    }
    if (verifier != null) {
        result = verifier.verifyCAP(xml);
    } else {
        log.debug("SignException");
        throw new SignException(SignException.TYPE_VRF, "" + srcSysId + "",
                new NullPointerException("verifier for " + srcSysId + " is null"));
    }
    return result;
}

From source file:org.executequery.gui.browser.ConnectionPanel.java

/**
 * Sets the values of the current database connection
 * within the jdbc properties table./*  w  w  w.  j a  v  a 2  s  . c o  m*/
 */
private void setJdbcProperties() {
    advancedProperties = new String[20][2];
    Properties properties = databaseConnection.getJdbcProperties();
    if (properties == null || properties.size() == 0) {
        model.fireTableDataChanged();
        return;
    }

    int count = 0;
    for (Enumeration<?> i = properties.propertyNames(); i.hasMoreElements();) {
        String name = (String) i.nextElement();
        if (!name.equalsIgnoreCase("password")) {
            advancedProperties[count][0] = name;
            advancedProperties[count][1] = properties.getProperty(name);
            count++;
        }
    }
    model.fireTableDataChanged();
}

From source file:org.projectforge.web.admin.AdminPage.java

protected void checkI18nProperties() {
    log.info("Administration: check i18n properties.");
    checkAccess();/*from ww  w  .  j  a v a  2 s .c  o m*/
    final StringBuffer buf = new StringBuffer();
    final Properties props = new Properties();
    final Properties props_en = new Properties();
    final Properties props_de = new Properties();
    final Properties propsFound = new Properties();
    final ClassLoader cLoader = this.getClass().getClassLoader();
    try {
        load(props, "");
        load(props_en, "_en");
        load(props_de, "_de");
        final InputStream is = cLoader.getResourceAsStream(WebConstants.FILE_I18N_KEYS);
        propsFound.load(is);
    } catch (final IOException ex) {
        log.error("Could not load i18n properties: " + ex.getMessage(), ex);
        throw new RuntimeException(ex);
    }
    buf.append("Checking the differences between the " + PFUserContext.BUNDLE_NAME
            + " properties (default and _de)\n\n");
    buf.append("Found " + props.size() + " entries in default property file (en).\n\n");
    buf.append("Missing in _de:\n");
    buf.append("---------------\n");
    List<String> keys = new ArrayList<String>();
    for (final Object key : props.keySet()) {
        if (props_de.containsKey(key) == false) {
            keys.add(String.valueOf(key));
        }
    }
    Collections.sort(keys);
    for (final String key : keys) {
        buf.append(key + "=" + props.getProperty(key) + "\n");
    }
    buf.append("\n\nOnly in _de (not in _en):\n");
    buf.append("-------------------------\n");
    keys = new ArrayList<String>();
    for (final Object key : props_de.keySet()) {
        if (props.containsKey(key) == false) {
            keys.add(String.valueOf(key));
        }
    }
    Collections.sort(keys);
    for (final String key : keys) {
        buf.append(key + "=" + props_de.getProperty(key) + "\n");
    }
    if (WebConfiguration.isDevelopmentMode() == true) {
        buf.append("\n\nMaybe not defined but used (found in java, jsp or Wicket's html code):\n");
        buf.append("----------------------------------------------------------------------\n");
        keys = new ArrayList<String>();
        for (final Object key : propsFound.keySet()) {
            if (props.containsKey(key) == false && props_de.containsKey(key) == false
                    && props.containsKey(key) == false) {
                keys.add(String.valueOf(key) + "=" + propsFound.getProperty((String) key));
            }
        }
        Collections.sort(keys);
        for (final String key : keys) {
            buf.append(key + "\n");
        }
        buf.append(
                "\n\nExperimental (in progress): Maybe unused (not found in java, jsp or Wicket's html code):\n");
        buf.append(
                "----------------------------------------------------------------------------------------\n");
        final Set<String> all = new TreeSet<String>();
        CollectionUtils.addAll(all, props.keys());
        CollectionUtils.addAll(all, props_en.keys());
        CollectionUtils.addAll(all, props_de.keys());
        keys = new ArrayList<String>();
        for (final String key : all) {
            if (propsFound.containsKey(key) == false) {
                keys.add(String.valueOf(key));
            }
        }
        Collections.sort(keys);
        for (final String key : keys) {
            String value = props_de.getProperty(key);
            if (value == null) {
                value = props_en.getProperty(key);
            }
            if (value == null) {
                value = props.getProperty(key);
            }
            buf.append(key + "=" + value + "\n");
        }
    }
    final String result = buf.toString();
    final String filename = "projectforge_i18n_check" + DateHelper.getDateAsFilenameSuffix(new Date()) + ".txt";
    DownloadUtils.setDownloadTarget(result.getBytes(), filename);
}

From source file:com.datos.vfs.provider.sftp.SftpClientFactory.java

/**
 * Creates a new connection to the server.
 *
 * @param hostname The name of the host to connect to.
 * @param port The port to use.//  ww  w .j ava2 s  .  c  o m
 * @param username The user's id.
 * @param password The user's password.
 * @param fileSystemOptions The FileSystem options.
 * @return A Session.
 * @throws FileSystemException if an error occurs.
 */
public static Session createConnection(final String hostname, final int port, final char[] username,
        final char[] password, final FileSystemOptions fileSystemOptions) throws FileSystemException {
    final JSch jsch = new JSch();

    File sshDir = null;

    // new style - user passed
    final SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance();
    final File knownHostsFile = builder.getKnownHosts(fileSystemOptions);
    final IdentityInfo[] identities = builder.getIdentityInfo(fileSystemOptions);
    final IdentityRepositoryFactory repositoryFactory = builder.getIdentityRepositoryFactory(fileSystemOptions);

    sshDir = findSshDir();

    setKnownHosts(jsch, sshDir, knownHostsFile);

    if (repositoryFactory != null) {
        jsch.setIdentityRepository(repositoryFactory.create(jsch));
    }

    addIdentities(jsch, sshDir, identities);

    Session session;
    try {
        session = jsch.getSession(new String(username), hostname, port);
        if (password != null) {
            session.setPassword(new String(password));
        }

        final Integer timeout = builder.getTimeout(fileSystemOptions);
        if (timeout != null) {
            session.setTimeout(timeout.intValue());
        }

        final UserInfo userInfo = builder.getUserInfo(fileSystemOptions);
        if (userInfo != null) {
            session.setUserInfo(userInfo);
        }

        final Properties config = new Properties();

        // set StrictHostKeyChecking property
        final String strictHostKeyChecking = builder.getStrictHostKeyChecking(fileSystemOptions);
        if (strictHostKeyChecking != null) {
            config.setProperty("StrictHostKeyChecking", strictHostKeyChecking);
        }
        // set PreferredAuthentications property
        final String preferredAuthentications = builder.getPreferredAuthentications(fileSystemOptions);
        if (preferredAuthentications != null) {
            config.setProperty("PreferredAuthentications", preferredAuthentications);
        }

        // set compression property
        final String compression = builder.getCompression(fileSystemOptions);
        if (compression != null) {
            config.setProperty("compression.s2c", compression);
            config.setProperty("compression.c2s", compression);
        }

        final String proxyHost = builder.getProxyHost(fileSystemOptions);
        if (proxyHost != null) {
            final int proxyPort = builder.getProxyPort(fileSystemOptions);
            final SftpFileSystemConfigBuilder.ProxyType proxyType = builder.getProxyType(fileSystemOptions);
            Proxy proxy = null;
            if (SftpFileSystemConfigBuilder.PROXY_HTTP.equals(proxyType)) {
                proxy = createProxyHTTP(proxyHost, proxyPort);
            } else if (SftpFileSystemConfigBuilder.PROXY_SOCKS5.equals(proxyType)) {
                proxy = createProxySOCKS5(proxyHost, proxyPort);
            } else if (SftpFileSystemConfigBuilder.PROXY_STREAM.equals(proxyType)) {
                proxy = createStreamProxy(proxyHost, proxyPort, fileSystemOptions, builder);
            }

            if (proxy != null) {
                session.setProxy(proxy);
            }
        }

        // set properties for the session
        if (config.size() > 0) {
            session.setConfig(config);
        }
        session.setDaemonThread(true);
        session.connect();
    } catch (final Exception exc) {
        throw new FileSystemException("vfs.provider.sftp/connect.error", exc, hostname);
    }

    return session;
}

From source file:com.janoz.usenet.searchers.impl.NewzbinConnectorTest.java

@Test
public void testSearch() throws Exception {
    Capture<HttpPost> postCapture = recordHttpExecute(recordSearchResponse(), SEARCH_SPECIALCHARS);
    replay(clientMock, entityMock);/*  ww w.  j  a v  a  2 s  . c o  m*/

    List<NZB> results = subject.search("The query", null, 100, 1000, null, null);

    verify(clientMock, entityMock);
    // nzb
    assertSpecialCharSearchResult(results);

    String request = getRequestContent(postCapture);
    Properties params = extractUrlencodedParams(request);
    //credentials
    assertEquals("USER", params.getProperty("username"));
    assertEquals("PASS", params.getProperty("password"));
    //search
    assertEquals("The+query", params.getProperty("query"));
    assertEquals("100", params.getProperty("u_post_larger_than"));
    assertEquals("1000", params.getProperty("u_post_smaller_than"));
    //default
    assertEquals("1", params.getProperty("u_completions"));
    assertEquals("p", params.getProperty("fpn"));
    assertEquals("ps_edit_date", params.getProperty("sort"));
    assertEquals("desc", params.getProperty("order"));
    assertEquals("0", params.getProperty("retention"));

    assertEquals(10, params.size());
}

From source file:org.apache.solr.handler.admin.CoreAdminCreateDiscoverTest.java

@Test
public void testCreateSavesRegProps() throws Exception {

    setupCore(coreNormal, true);/* w  w w. j a va2  s .c o  m*/

    // create a new core (using CoreAdminHandler) w/ properties
    // Just to be sure it's NOT written to the core.properties file
    File workDir = new File(solrHomeDirectory, coreNormal);
    File data = new File(workDir, "data");

    SolrQueryResponse resp = new SolrQueryResponse();
    admin.handleRequestBody(req(CoreAdminParams.ACTION, CoreAdminParams.CoreAdminAction.CREATE.toString(),
            CoreAdminParams.NAME, coreNormal, CoreAdminParams.INSTANCE_DIR, workDir.getAbsolutePath(),
            CoreAdminParams.CONFIG, "solrconfig_ren.xml", CoreAdminParams.SCHEMA, "schema_ren.xml",
            CoreAdminParams.DATA_DIR, data.getAbsolutePath()), resp);
    assertNull("Exception on create", resp.getException());

    // verify props are in persisted file
    Properties props = new Properties();
    File propFile = new File(solrHomeDirectory, coreNormal + "/" + CorePropertiesLocator.PROPERTIES_FILENAME);
    FileInputStream is = new FileInputStream(propFile);
    try {
        props.load(new InputStreamReader(is, StandardCharsets.UTF_8));
    } finally {
        org.apache.commons.io.IOUtils.closeQuietly(is);
    }

    assertEquals("Unexpected value preserved in properties file " + propFile.getAbsolutePath(),
            props.getProperty(CoreAdminParams.NAME), coreNormal);

    assertEquals("Unexpected value preserved in properties file " + propFile.getAbsolutePath(),
            props.getProperty(CoreAdminParams.CONFIG), "solrconfig_ren.xml");

    assertEquals("Unexpected value preserved in properties file " + propFile.getAbsolutePath(),
            props.getProperty(CoreAdminParams.SCHEMA), "schema_ren.xml");

    assertEquals("Unexpected value preserved in properties file " + propFile.getAbsolutePath(),
            props.getProperty(CoreAdminParams.DATA_DIR), data.getAbsolutePath());

    assertEquals(props.size(), 4);

    //checkOnlyKnown(propFile);
    // For the other 3 vars, we couldn't get past creating the core if dereferencing didn't work correctly.

    // Should have segments in the directory pointed to by the ${DATA_TEST}.
    File test = new File(data, "index");
    assertTrue("Should have found index dir at " + test.getAbsolutePath(), test.exists());
}

From source file:org.apache.solr.handler.admin.CoreAdminCreateDiscoverTest.java

@Test
public void testCreateSavesSysProps() throws Exception {

    setupCore(coreSysProps, true);// ww w.j  a v a  2 s .com

    // create a new core (using CoreAdminHandler) w/ properties
    // Just to be sure it's NOT written to the core.properties file
    File workDir = new File(solrHomeDirectory, coreSysProps);
    System.setProperty("INSTDIR_TEST", workDir.getAbsolutePath());
    System.setProperty("CONFIG_TEST", "solrconfig_ren.xml");
    System.setProperty("SCHEMA_TEST", "schema_ren.xml");

    File dataDir = new File(workDir.getAbsolutePath(), "data_diff");
    System.setProperty("DATA_TEST", "data_diff");

    SolrQueryResponse resp = new SolrQueryResponse();
    admin.handleRequestBody(req(CoreAdminParams.ACTION, CoreAdminParams.CoreAdminAction.CREATE.toString(),
            CoreAdminParams.NAME, coreSysProps, CoreAdminParams.INSTANCE_DIR, "${INSTDIR_TEST}",
            CoreAdminParams.CONFIG, "${CONFIG_TEST}", CoreAdminParams.SCHEMA, "${SCHEMA_TEST}",
            CoreAdminParams.DATA_DIR, "${DATA_TEST}"), resp);
    assertNull("Exception on create", resp.getException());

    // verify props are in persisted file

    Properties props = new Properties();
    File propFile = new File(solrHomeDirectory, coreSysProps + "/" + CorePropertiesLocator.PROPERTIES_FILENAME);
    FileInputStream is = new FileInputStream(propFile);
    try {
        props.load(new InputStreamReader(is, StandardCharsets.UTF_8));
    } finally {
        org.apache.commons.io.IOUtils.closeQuietly(is);
    }

    assertEquals("Unexpected value preserved in properties file " + propFile.getAbsolutePath(),
            props.getProperty(CoreAdminParams.NAME), coreSysProps);

    assertEquals("Unexpected value preserved in properties file " + propFile.getAbsolutePath(),
            props.getProperty(CoreAdminParams.CONFIG), "${CONFIG_TEST}");

    assertEquals("Unexpected value preserved in properties file " + propFile.getAbsolutePath(),
            props.getProperty(CoreAdminParams.SCHEMA), "${SCHEMA_TEST}");

    assertEquals("Unexpected value preserved in properties file " + propFile.getAbsolutePath(),
            props.getProperty(CoreAdminParams.DATA_DIR), "${DATA_TEST}");

    assertEquals(props.size(), 4);
    //checkOnlyKnown(propFile);

    // Now assert that certain values are properly dereferenced in the process of creating the core, see
    // SOLR-4982. Really, we should be able to just verify that the index files exist.

    // Should NOT be a datadir named ${DATA_TEST} (literal).
    File badDir = new File(workDir, "${DATA_TEST}");
    assertFalse("Should have substituted the sys var, found file " + badDir.getAbsolutePath(), badDir.exists());

    // For the other 3 vars, we couldn't get past creating the core if dereferencing didn't work correctly.

    // Should have segments in the directory pointed to by the ${DATA_TEST}.
    File test = new File(dataDir, "index");
    assertTrue("Should have found index dir at " + test.getAbsolutePath(), test.exists());
}