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:esg.node.core.AbstractDataNodeManager.java

public Properties getMatchingProperties(String regex) {
    log.trace("getting matching properties for [" + regex + "]");
    Properties matchProps = null;
    if ((matchProps = propCache.get(regex)) != null) {
        return matchProps;
    }// w ww.ja  v  a 2s.  com
    matchProps = new Properties();
    String key = null;
    for (Enumeration keys = props.propertyNames(); keys.hasMoreElements();) {
        key = (String) keys.nextElement();
        //log.trace("inspecting: "+key);
        try {
            if (key.matches(regex)) {
                //log.trace("matched: adding...");
                matchProps.put(key, props.getProperty(key));
            }
        } catch (PatternSyntaxException ex) {
            log.error(ex.getMessage(), ex);
            break;
        }
    }
    propCache.put(regex, matchProps);
    log.trace("[" + regex + "] => (" + matchProps.size() + " entries)");
    log.trace("propCache size = " + propCache.size());
    return matchProps;
}

From source file:org.eclipse.gemini.blueprint.test.AbstractDependencyManagerTests.java

/**
 * Returns the bundles that have to be installed as part of the test setup.
 * This method is preferred as the bundles are by their names rather then as
 * {@link Resource}s. It allows for a <em>declarative</em> approach for
 * specifying bundles as opposed to {@link #getTestBundles()} which provides
 * a programmatic one.//from   w ww .  j a  v  a  2  s  . c  o  m
 * 
 * <p/>This implementation reads a predefined properties file to determine
 * the bundles needed. If the configuration needs to be changed, consider
 * changing the configuration location.
 * 
 * @return an array of testing framework bundle identifiers
 * @see #getTestingFrameworkBundlesConfiguration()
 * @see #locateBundle(String)
 * 
 */
protected String[] getTestFrameworkBundlesNames() {
    // load properties file
    Properties props = PropertiesUtil.loadAndExpand(getTestingFrameworkBundlesConfiguration());

    if (props == null)
        throw new IllegalArgumentException(
                "cannot load default configuration from " + getTestingFrameworkBundlesConfiguration());

    boolean trace = logger.isTraceEnabled();

    if (trace)
        logger.trace("Loaded properties " + props);

    // pass properties to test instance running inside OSGi space
    System.getProperties().put(GEMINI_BLUEPRINT_VERSION_PROP_KEY, props.get(GEMINI_BLUEPRINT_VERSION_PROP_KEY));
    System.getProperties().put(SPRING_VERSION_PROP_KEY, props.get(SPRING_VERSION_PROP_KEY));

    Properties excluded = PropertiesUtil.filterKeysStartingWith(props, IGNORE);

    if (trace) {
        logger.trace("Excluded ignored properties " + excluded);
    }

    String[] bundles = props.keySet().toArray(new String[props.size()]);
    // sort the array (as the Properties file doesn't respect the order)
    //bundles = StringUtils.sortStringArray(bundles);

    if (logger.isDebugEnabled())
        logger.debug("Default framework bundles :" + ObjectUtils.nullSafeToString(bundles));

    return bundles;
}

From source file:com.alfaariss.oa.OAContextListener.java

/**
 * Starts the engine before all servlets are initialized.
 * /*w  ww. j a v a2s  . com*/
 * Searches for the properties needed for the configuration in:
 * <code>[Servlet context dir]/WEB-INF/[PROPERTIES_FILENAME]</code>
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 */
@Override
public void contextInitialized(ServletContextEvent oServletContextEvent) {
    Properties pConfig = new Properties();
    try {
        _logger.info("Starting Asimba");

        Package pCurrent = OAContextListener.class.getPackage();

        String sSpecVersion = pCurrent.getSpecificationVersion();
        if (sSpecVersion != null)
            _logger.info("Specification-Version: " + sSpecVersion);

        String sImplVersion = pCurrent.getImplementationVersion();
        if (sImplVersion != null)
            _logger.info("Implementation-Version: " + sImplVersion);

        ServletContext oServletContext = oServletContextEvent.getServletContext();

        Enumeration enumContextAttribs = oServletContext.getInitParameterNames();
        while (enumContextAttribs.hasMoreElements()) {
            String sName = (String) enumContextAttribs.nextElement();
            pConfig.put(sName, oServletContext.getInitParameter(sName));
        }

        if (pConfig.size() > 0) {
            _logger.info("Using configuration items found in servlet context: " + pConfig);
        }

        // Add MountingPoint to PathTranslator
        PathTranslator.getInstance().addKey(MP_WEBAPP_ROOT, oServletContext.getRealPath(""));

        // Try to see whether there is a system property with the location of the properties file:
        String sPropertiesFilename = System.getProperty(PROPERTIES_FILENAME_PROPERTY);
        if (null != sPropertiesFilename && !"".equals(sPropertiesFilename)) {
            File fConfig = new File(sPropertiesFilename);
            if (fConfig.exists()) {
                _logger.info("Reading Asimba properties from " + fConfig.getAbsolutePath());
                pConfig.putAll(getProperties(fConfig));
            }
        }

        String sWebInf = oServletContext.getRealPath("WEB-INF");
        if (sWebInf != null) {
            _logger.info("Cannot find path in ServletContext for WEB-INF");
            StringBuffer sbConfigFile = new StringBuffer(sWebInf);
            if (!sbConfigFile.toString().endsWith(File.separator))
                sbConfigFile.append(File.separator);
            sbConfigFile.append(PROPERTIES_FILENAME);

            File fConfig = new File(sbConfigFile.toString());
            if (fConfig.exists()) {
                _logger.info("Updating configuration items with the items in file: " + fConfig.toString());
                pConfig.putAll(getProperties(fConfig));
            } else {
                _logger.info("No optional configuration properties (" + PROPERTIES_FILENAME
                        + ") file found at: " + fConfig.toString());
            }
        }
        //Search for PROPERTIES_FILENAME file in servlet context classloader classpath 
        //it looks first at this location: ./<context>/web-inf/classes/[PROPERTIES_FILENAME]
        //if previous location didn't contain PROPERTIES_FILENAME then checking: 
        //./tomcat/common/classes/PROPERTIES_FILENAME
        URL urlProperties = oServletContext.getClass().getClassLoader().getResource(PROPERTIES_FILENAME);
        if (urlProperties != null) {
            String sProperties = urlProperties.getFile();
            _logger.debug("Found '" + PROPERTIES_FILENAME + "' file in classpath: " + sProperties);
            File fProperties = new File(sProperties);
            if (fProperties != null && fProperties.exists()) {
                _logger.info("Updating configuration items with the items in file: "
                        + fProperties.getAbsolutePath());
                pConfig.putAll(getProperties(fProperties));
            } else
                _logger.info("Could not resolve: " + fProperties.getAbsolutePath());
        } else
            _logger.info("No optional '" + PROPERTIES_FILENAME
                    + "' configuration file found in servlet context classpath");

        if (!pConfig.containsKey("configuration.handler.filename")) {
            StringBuffer sbOAConfigFile = new StringBuffer(sWebInf);
            if (!sbOAConfigFile.toString().endsWith(File.separator))
                sbOAConfigFile.append(File.separator);
            sbOAConfigFile.append("conf");
            sbOAConfigFile.append(File.separator);
            sbOAConfigFile.append("asimba.xml");
            File fOAConfig = new File(sbOAConfigFile.toString());
            if (fOAConfig.exists()) {
                pConfig.put("configuration.handler.filename", sbOAConfigFile.toString());
                _logger.info(
                        "Setting 'configuration.handler.filename' configuration property with configuration file found at: "
                                + fOAConfig.toString());
            }
        }

        _oEngineLauncher.start(pConfig);

        _logger.info("Started Engine with OAContextListener");
    } catch (Exception e) {
        _logger.error("Can't start Engine with OAContextListener", e);

        _logger.debug("try stopping the server");
        _oEngineLauncher.stop();
    }

}

From source file:org.apache.directory.fortress.core.ldap.LdapDataProvider.java

/**
 * Given a collection of {@link java.util.Properties}, convert to raw data name-value format and load into ldap modification set in preparation for ldap add.
 *
 * @param props    contains {@link java.util.Properties} targeted for adding to ldap.
 * @param entry    contains ldap entry to push attrs into.
 * @param attrName contains the name of the ldap attribute to be added.
 * @param separator contains the char value used to separate name and value in ldap raw format.
 * @throws LdapException If we weren't able to add the properies into the entry
 *///from  ww  w  . j a  v  a 2  s. co  m
protected void loadProperties(Properties props, Entry entry, String attrName, char separator)
        throws LdapException {
    if ((props != null) && (props.size() > 0)) {
        Attribute attr = null;

        for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) {
            // This LDAP attr is stored as a name-value pair separated by a ':'.
            String key = (String) e.nextElement();
            String val = props.getProperty(key);
            String prop = key + separator + val;

            if (attr == null) {
                attr = new DefaultAttribute(attrName);
            } else {
                attr.add(prop);
            }
        }

        if (attr != null) {
            entry.add(attr);
        }
    }
}

From source file:org.wso2.carbon.bam.mediationstats.data.publisher.conf.RegistryPersistenceManager.java

/**
 * Loads configuration from Registry./*  ww  w .j a  v a  2  s.c  om*/
 */
public MediationStatConfig load(int tenantId) {

    MediationStatConfig mediationStatConfig = new MediationStatConfig();
    // First set it to defaults, but do not persist
    mediationStatConfig.setStatisticsReporterDisable(PublisherUtils.getStatisticsReporterDisable());
    mediationStatConfig.setEnableMediationStats(false);
    mediationStatConfig.setUrl(EMPTY_STRING);
    mediationStatConfig.setUserName(EMPTY_STRING);
    mediationStatConfig.setPassword(EMPTY_STRING);
    mediationStatConfig.setProperties(new Property[0]);

    // then load it from registry
    try {

        Registry registry = registryService.getConfigSystemRegistry(tenantId);

        String mediationStatsEnable = getConfigurationProperty(
                MediationDataPublisherConstants.ENABLE_MEDIATION_STATS, registry);
        String url = getConfigurationProperty(BAMDataPublisherConstants.BAM_URL, registry);
        String userName = getConfigurationProperty(BAMDataPublisherConstants.BAM_USER_NAME, registry);
        String password = getConfigurationProperty(BAMDataPublisherConstants.BAM_PASSWORD, registry);
        String streamName = getConfigurationProperty(BAMDataPublisherConstants.STREAM_NAME, registry);
        String version = getConfigurationProperty(BAMDataPublisherConstants.VERSION, registry);
        String description = getConfigurationProperty(BAMDataPublisherConstants.DESCRIPTION, registry);
        String nickName = getConfigurationProperty(BAMDataPublisherConstants.NICK_NAME, registry);

        Properties properties = getAllConfigProperties(
                MediationDataPublisherConstants.MEDIATION_STATISTICS_PROPERTIES_REG_PATH, registry);

        if (mediationStatsEnable != null && url != null && userName != null && password != null) {

            mediationStatConfig.setEnableMediationStats(Boolean.parseBoolean(mediationStatsEnable));
            mediationStatConfig.setUrl(url);
            mediationStatConfig.setUserName(userName);
            mediationStatConfig.setPassword(password);

            mediationStatConfig.setStreamName(streamName);
            mediationStatConfig.setVersion(version);
            mediationStatConfig.setDescription(description);
            mediationStatConfig.setNickName(nickName);

            if (properties != null) {
                List<Property> propertyDTOList = new ArrayList<Property>();
                String[] keys = properties.keySet().toArray(new String[properties.size()]);
                for (int i = keys.length - 1; i >= 0; i--) {
                    String key = keys[i];
                    Property propertyDTO = new Property();
                    propertyDTO.setKey(key);
                    propertyDTO.setValue(((List<String>) properties.get(key)).get(0));
                    propertyDTOList.add(propertyDTO);
                }

                mediationStatConfig
                        .setProperties(propertyDTOList.toArray(new Property[propertyDTOList.size()]));
            }

        }
        //            else {
        //                // Registry does not have eventing config
        //                update(mediationStatConfig, tenantId);
        //            }
    } catch (Exception e) {
        log.error("Coul not load values from registry", e);
    }
    return mediationStatConfig;
}

From source file:org.sakaiproject.component.impl.BasicConfigurationService.java

/**
 * INTERNAL/*from  w  w w .  ja  v  a  2s. c  o m*/
 * Adds a set of config items using the data from a set of properties
 * @param p the properties
 * @param source the source name
 */
protected void addProperties(Properties p, String source) {
    if (p != null) {
        if (source == null || "".equals(source)) {
            source = UNKNOWN;
        }
        M_log.info("Adding " + p.size() + " properties from " + source);
        for (Enumeration<Object> e = p.keys(); e.hasMoreElements(); /**/) {
            String name = (String) e.nextElement();
            String value = p.getProperty(name);
            // KNL-1361 - Add support for system-scoped properties
            if (name != null && name.endsWith(SAKAI_SYSTEM_PROPERTY_SUFFIX)
                    && name.length() > SAKAI_SYSTEM_PROPERTY_SUFFIX.length()) {
                name = name.substring(0, name.length() - SAKAI_SYSTEM_PROPERTY_SUFFIX.length());
                System.setProperty(name, value);
                M_log.info("Promoted to system property: " + name);
                continue;
            }
            ConfigItemImpl ci = new ConfigItemImpl(name, value, source);
            this.addConfigItem(ci, source);
        }
    }
}

From source file:org.opencastproject.scheduler.endpoint.SchedulerRestService.java

/**
 * Updates an existing event in the database. The event-id has to be stored in the database already. Will return OK,
 * if the event was found and could be updated.
 * // w w w. j a  v a2 s .  com
 * @param eventID
 *          id of event to be updated
 * 
 * @param catalogs
 *          serialized DC representing event
 * @return
 */
@PUT
@Path("{id:[0-9]+}")
@RestQuery(name = "updaterecordings", description = "Updates Dublin Core of specified event", returnDescription = "Status OK is returned if event was successfully updated, NOT FOUND if specified event does not exist or BAD REQUEST if data is missing or invalid", pathParameters = {
        @RestParameter(name = "id", description = "ID of event to be updated", isRequired = true, type = Type.STRING) }, restParameters = {
                @RestParameter(name = "dublincore", isRequired = false, description = "Updated Dublin Core for event", type = Type.TEXT),
                @RestParameter(name = "agentparameters", isRequired = false, description = "Updated Capture Agent properties", type = Type.TEXT),
                @RestParameter(name = "wfproperties", isRequired = false, description = "Workflow configuration properties", type = Type.TEXT) }, reponses = {
                        @RestResponse(responseCode = HttpServletResponse.SC_OK, description = "Event was successfully updated"),
                        @RestResponse(responseCode = HttpServletResponse.SC_NOT_FOUND, description = "Event with specified ID does not exist"),
                        @RestResponse(responseCode = HttpServletResponse.SC_FORBIDDEN, description = "Event with specified ID cannot be updated"),
                        @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "Data is missing or invalid") })
public Response updateEvent(@PathParam("id") String eventID, @FormParam("dublincore") String dublinCoreXml,
        @FormParam("agentparameters") String agentParameters,
        @FormParam("wfproperties") String workflowProperties) {

    // Update CA properties from dublin core (event.title, etc)
    Long id;
    try {
        id = Long.parseLong(eventID);
    } catch (Exception e) {
        logger.warn("Invalid eventID (non-numerical): {}", eventID);
        return Response.status(Status.BAD_REQUEST).build();
    }

    DublinCoreCatalog eventCatalog = null;
    if (StringUtils.isNotBlank(dublinCoreXml)) {
        try {
            logger.debug("DublinCore catalog found.");
            eventCatalog = parseDublinCore(dublinCoreXml);
            logger.debug(eventCatalog.toXmlString());
        } catch (Exception e) {
            logger.warn("Could not parse Dublin core catalog: {}", e);
            return Response.status(Status.BAD_REQUEST).build();
        }
    }

    Properties caProperties = null;
    if (StringUtils.isNotBlank(agentParameters)) {
        try {
            caProperties = parseProperties(agentParameters);
            if (caProperties.size() == 0)
                logger.info(
                        "Empty form param 'agentparameters'. This resets all CA parameters. Please make sure this is intended behaviour.");

        } catch (Exception e) {
            logger.warn("Could not parse capture agent properties: {}", agentParameters);
            return Response.status(Status.BAD_REQUEST).build();
        }
    }

    Map<String, String> wfProperties = new HashMap<String, String>();
    if (StringUtils.isNotBlank(workflowProperties)) {
        try {
            Properties prop = parseProperties(workflowProperties);
            wfProperties.putAll((Map) prop);
        } catch (IOException e) {
            logger.warn("Could not parse workflow configuration properties: {}", workflowProperties);
            return Response.status(Status.BAD_REQUEST).build();
        }
    }

    try {
        if (eventCatalog != null)
            service.updateEvent(id, eventCatalog, wfProperties);

        if (caProperties != null)
            service.updateCaptureAgentMetadata(caProperties, tuple(id, eventCatalog));

        return Response.ok().build();
    } catch (SchedulerException e) {
        logger.warn("{}", e.getMessage());
        //TODO: send the reason message in response body
        return Response.status(Status.FORBIDDEN).build();
    } catch (NotFoundException e) {
        logger.warn("Event with id '{}' does not exist.", id);
        return Response.status(Status.NOT_FOUND).build();
    } catch (Exception e) {
        logger.warn("Unable to update event with id '{}': {}", id, e);
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.apache.jxtadoop.conf.Configuration.java

public void write(DataOutput out) throws IOException {
    Properties props = getProps();
    WritableUtils.writeVInt(out, props.size());
    for (Map.Entry<Object, Object> item : props.entrySet()) {
        org.apache.jxtadoop.io.Text.writeString(out, (String) item.getKey());
        org.apache.jxtadoop.io.Text.writeString(out, (String) item.getValue());
    }//  ww  w . j a  v a2s .co  m
}

From source file:org.apache.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
 */// ww w  . j a v  a 2 s. 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.npower.dm.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. ja  v  a 2s.c  om
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<Object> 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));
        }
    }

}