Example usage for java.util Dictionary put

List of usage examples for java.util Dictionary put

Introduction

In this page you can find the example usage for java.util Dictionary put.

Prototype

public abstract V put(K key, V value);

Source Link

Document

Maps the specified key to the specified value in this dictionary.

Usage

From source file:com.ibm.jaggr.core.impl.cache.CacheManagerImpl.java

/**
 * Starts up the cache. Attempts to de-serialize a previously serialized
 * cache from disk and starts the periodic serializer task.
 *
 * @param aggregator//from  w w w .ja v  a 2 s .c o  m
 *            the aggregator instance this cache manager belongs to
 * @param stamp
 *            a time stamp used to determine if the cache should be cleared.
 *            The cache should be cleared if the time stamp is later than
 *            the one associated with the cached resources.
 * @throws IOException
 */
public CacheManagerImpl(IAggregator aggregator, long stamp) throws IOException {

    _directory = new File(aggregator.getWorkingDirectory(), CACHEDIR_NAME);
    _aggregator = aggregator;
    // Make sure the cache directory exists
    if (!_directory.exists()) {
        if (!_directory.mkdirs()) {
            throw new IOException(MessageFormat.format(Messages.CacheManagerImpl_0,
                    new Object[] { _directory.getAbsoluteFile() }));
        }
    }
    // Attempt to de-serialize the cache from disk
    CacheImpl cache = null;
    try {
        File file = new File(_directory, CACHE_META_FILENAME);
        ObjectInputStream is = new ObjectInputStream(new FileInputStream(file));
        try {
            cache = (CacheImpl) is.readObject();
        } finally {
            try {
                is.close();
            } catch (Exception ignore) {
            }
        }
    } catch (FileNotFoundException e) {
        if (log.isLoggable(Level.INFO))
            log.log(Level.INFO, Messages.CacheManagerImpl_1);
    } catch (InvalidClassException e) {
        if (log.isLoggable(Level.INFO))
            log.log(Level.INFO, Messages.CacheManagerImpl_2);
        // one or more of the serializable classes has changed.  Delete the stale
        // cache files
    } catch (Exception e) {
        if (log.isLoggable(Level.SEVERE))
            log.log(Level.SEVERE, e.getMessage(), e);
    }
    if (cache != null) {
        _control = (CacheControl) cache.getControlObj();
    }
    if (_control != null) {
        // stamp == 0 means no overrides.  Need to check for this explicitly
        // in case the overrides directory has been removed.
        if (stamp == 0 && _control.initStamp == 0 || stamp != 0 && stamp <= _control.initStamp) {
            // Use AggregatorProxy so that getCacheManager will return non-null
            // if called from within setAggregator.  Need to do this because
            // IAggregator.getCacheManager() is unable to return this object
            // since it is still being constructed.
            cache.setAggregator(AggregatorProxy.newInstance(_aggregator, this));
            _cache.set(cache);
        }
    } else {
        _control = new CacheControl();
        _control.initStamp = stamp;
    }

    // Start up the periodic serializer task.  Serializes the cache every 10 minutes.
    // This is done so that we can recover from an unexpected shutdown
    aggregator.getExecutors().getScheduledExecutor().scheduleAtFixedRate(new Runnable() {
        public void run() {
            try {
                File file = new File(_directory, CACHE_META_FILENAME);
                // Synchronize on the cache object to keep the scheduled cache sync thread and
                // the thread processing servlet destroy from colliding.
                synchronized (cacheSerializerSyncObj) {
                    ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file));
                    try {
                        os.writeObject(_cache.get());
                    } finally {
                        try {
                            os.close();
                        } catch (Exception ignore) {
                        }
                    }
                }
            } catch (Exception e) {
                if (log.isLoggable(Level.SEVERE))
                    log.log(Level.SEVERE, e.getMessage(), e);
            }
        }
    }, 10, 10, TimeUnit.MINUTES);

    Dictionary<String, String> dict;

    if (_aggregator.getPlatformServices() != null) {
        dict = new Hashtable<String, String>();
        dict.put("name", aggregator.getName()); //$NON-NLS-1$
        _serviceRegistrations.add(_aggregator.getPlatformServices()
                .registerService(IShutdownListener.class.getName(), this, dict));

        dict = new Hashtable<String, String>();
        dict.put("name", aggregator.getName()); //$NON-NLS-1$
        _serviceRegistrations.add(
                _aggregator.getPlatformServices().registerService(IConfigListener.class.getName(), this, dict));

        dict = new Hashtable<String, String>();
        dict.put("name", aggregator.getName()); //$NON-NLS-1$
        _serviceRegistrations.add(_aggregator.getPlatformServices()
                .registerService(IDependenciesListener.class.getName(), this, dict));

        dict = new Hashtable<String, String>();
        dict.put("name", aggregator.getName()); //$NON-NLS-1$
        _serviceRegistrations.add(_aggregator.getPlatformServices()
                .registerService(IOptionsListener.class.getName(), this, dict));
    }

    optionsUpdated(aggregator.getOptions(), 1);
    configLoaded(aggregator.getConfig(), 1);
    dependenciesLoaded(aggregator.getDependencies(), 1);

    // Now invoke the listeners for objects that have already been initialized
    IOptions options = _aggregator.getOptions();
    if (options != null) {
        optionsUpdated(options, 1);
    }
    IConfig config = _aggregator.getConfig();
    if (config != null) {
        configLoaded(config, 1);
    }

    IDependencies deps = _aggregator.getDependencies();
    if (deps != null) {
        dependenciesLoaded(deps, 1);
    }
}

From source file:com.ibm.jaggr.core.impl.modulebuilder.javascript.JavaScriptModuleBuilder.java

@Override
public void initialize(IAggregator aggregator, IAggregatorExtension extension, IExtensionRegistrar registrar) {
    Dictionary<String, String> props;
    props = new Hashtable<String, String>();
    props.put("name", aggregator.getName()); //$NON-NLS-1$
    registrations/*from  w w w .  j  a v  a2 s  . c om*/
            .add(aggregator.getPlatformServices().registerService(ILayerListener.class.getName(), this, props));
    props = new Hashtable<String, String>();
    props.put("name", aggregator.getName()); //$NON-NLS-1$
    registrations.add(
            aggregator.getPlatformServices().registerService(IShutdownListener.class.getName(), this, props));
}

From source file:org.paxle.tools.ieporter.cm.impl.ConfigurationIEPorter.java

@SuppressWarnings("unchecked")
public Dictionary<String, Object> importConfiguration(Document doc) {
    if (doc == null)
        return null;

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    try {// w ww . jav  a  2  s  .c om
        Element configElement = doc.getDocumentElement();

        // getting the service-pid
        Element pidElement = (Element) configElement.getElementsByTagName(Constants.SERVICE_PID).item(0);
        props.put(Constants.SERVICE_PID, pidElement.getFirstChild().getNodeValue());

        // loop through all properties
        Element propsElement = (Element) configElement.getElementsByTagName(ELEM_PROPERTIES).item(0);
        NodeList propsList = propsElement.getElementsByTagName(ELEM_PROPERTY);

        for (int i = 0; i < propsList.getLength(); i++) {
            Element propertyElement = (Element) propsList.item(i);

            Object value = null;
            String key = propertyElement.getAttributes().getNamedItem(ATTRIBUTE_PROPERTY_KEY).getNodeValue();
            String type = propertyElement.getAttributes().getNamedItem(ATTRIB_PROPERTY_TYPE).getNodeValue();

            if (type.endsWith("[]") || type.equals(Vector.class.getSimpleName())) {
                Element valueElements = (Element) propertyElement.getElementsByTagName(ELEM_VALUES).item(0);
                NodeList valueElementList = valueElements.getElementsByTagName(ELEM_VALUE);

                if (type.endsWith("[]")) {
                    // get type class
                    Class clazz = NAMELOOKUP.get(type.substring(0, type.length() - 2));

                    // create a new array
                    value = Array.newInstance(clazz, valueElementList.getLength());
                } else {
                    // create a new vector
                    value = new Vector();
                }

                // append all values to the array/vector
                for (int j = 0; j < valueElementList.getLength(); j++) {
                    Element valueElement = (Element) valueElementList.item(j);
                    Object valueObj = this.valueOf(type, valueElement);

                    if (type.endsWith("[]")) {
                        Array.set(value, j, valueObj);
                    } else {
                        ((Vector<Object>) value).add(valueObj);
                    }
                }
            } else {
                Element valueElement = (Element) propertyElement.getElementsByTagName(ELEM_VALUE).item(0);

                // get concrete value
                value = this.valueOf(type, valueElement);
            }

            // add value
            props.put(key, value);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return props;
}

From source file:org.apache.sling.resourceresolver.impl.ResourceResolverFactoryActivator.java

/**
 * Try to register the factory.//from  www  .ja  v a 2  s  .  c  o m
 */
private void registerFactory(final ComponentContext localContext) {
    final FactoryRegistration local = new FactoryRegistration();

    if (localContext != null) {
        // activate and register factory
        final Dictionary<String, Object> serviceProps = new Hashtable<String, Object>();
        serviceProps.put(Constants.SERVICE_VENDOR, localContext.getProperties().get(Constants.SERVICE_VENDOR));
        serviceProps.put(Constants.SERVICE_DESCRIPTION,
                localContext.getProperties().get(Constants.SERVICE_DESCRIPTION));

        local.commonFactory = new CommonResourceResolverFactoryImpl(this);
        local.commonFactory.activate(localContext.getBundleContext());
        local.factoryRegistration = localContext.getBundleContext()
                .registerService(ResourceResolverFactory.class.getName(), new ServiceFactory() {

                    @Override
                    public Object getService(final Bundle bundle, final ServiceRegistration registration) {
                        if (ResourceResolverFactoryActivator.this.componentContext == null) {
                            return null;
                        }
                        final ResourceResolverFactoryImpl r = new ResourceResolverFactoryImpl(
                                local.commonFactory, bundle,
                                ResourceResolverFactoryActivator.this.serviceUserMapper);
                        return r;
                    }

                    @Override
                    public void ungetService(final Bundle bundle, final ServiceRegistration registration,
                            final Object service) {
                        // nothing to do
                    }
                }, serviceProps);

        local.runtimeRegistration = localContext.getBundleContext()
                .registerService(RuntimeService.class.getName(), this.getRuntimeService(), null);

        this.factoryRegistration = local;
    }
}

From source file:org.codice.ddf.admin.core.impl.ConfigurationAdminImpl.java

private List<Metatype> addMetaTypeNamesToMap(final Map<String, ObjectClassDefinition> objectClassDefinitions,
        final String filterSpec, final String type) {
    Filter filter = null;/*from  ww w  .  ja  va 2  s.com*/
    if (filterSpec != null) {
        try {
            filter = getBundleContext().createFilter(filterSpec);
        } catch (InvalidSyntaxException ignore) {
            // don't care
        }
    }

    List<Metatype> metatypeList = new ArrayList<>();
    for (Entry<String, ObjectClassDefinition> ociEntry : objectClassDefinitions.entrySet()) {
        final String pid = ociEntry.getKey();
        final ObjectClassDefinition ocd = ociEntry.getValue();
        if (filter == null) {
            AttributeDefinition[] defs = ocd.getAttributeDefinitions(ObjectClassDefinition.ALL);
            metatypeList.add(new MetatypeImpl(pid, ocd.getName(), createMetatypeMap(defs)));
        } else {
            final Dictionary<String, String> props = new Hashtable<>();
            props.put(type, pid);
            if (filter.match(props)) {
                AttributeDefinition[] defs = ocd.getAttributeDefinitions(ObjectClassDefinition.ALL);
                metatypeList.add(new MetatypeImpl(pid, ocd.getName(), createMetatypeMap(defs)));
            }
        }
    }
    return metatypeList;
}

From source file:org.codice.ddf.ui.admin.api.ConfigurationAdmin.java

/**
 * @see ConfigurationAdminMBean#updateForLocation(java.lang.String, java.lang.String,
 * java.util.Map)/*from w ww . jav  a  2s .c  om*/
 */
public void updateForLocation(final String pid, String location, Map<String, Object> configurationTable)
        throws IOException {
    if (pid == null || pid.length() < 1) {
        throw loggedException("Argument pid cannot be null or empty");
    }
    if (configurationTable == null) {
        throw loggedException("Argument configurationTable cannot be null");
    }

    Configuration config = configurationAdmin.getConfiguration(pid, location);

    final List<Map<String, Object>> metatype = findMetatypeForConfig(config);
    List<Map.Entry<String, Object>> configEntries = new ArrayList<>();

    CollectionUtils.addAll(configEntries, configurationTable.entrySet().iterator());

    if (metatype == null) {
        throw loggedException("Could not find metatype for " + pid);
    }
    // now we have to filter each property based on its cardinality
    CollectionUtils.transform(configEntries, new CardinalityTransformer(metatype, pid));

    Dictionary<String, Object> configurationProperties = new Hashtable<>();
    for (Map.Entry<String, Object> configEntry : configEntries) {
        configurationProperties.put(configEntry.getKey(), configEntry.getValue());
    }
    config.update(configurationProperties);
}

From source file:ddf.catalog.definition.impl.DefinitionParser.java

@SuppressWarnings("squid:S1149" /* Confined by underlying contract */)
private List<Callable<Boolean>> parseMetacardTypes(Changeset changeset,
        List<Outer.MetacardType> incomingMetacardTypes) {
    List<Callable<Boolean>> staged = new ArrayList<>();
    BundleContext context = getBundleContext();
    List<MetacardType> stagedTypes = new ArrayList<>();

    for (Outer.MetacardType metacardType : incomingMetacardTypes) {
        Set<AttributeDescriptor> attributeDescriptors = new HashSet<>(
                MetacardImpl.BASIC_METACARD.getAttributeDescriptors());
        Set<String> requiredAttributes = new HashSet<>();

        Set<AttributeDescriptor> extendedAttributes = Optional.of(metacardType).map(omt -> omt.extendsTypes)
                .orElse(Collections.emptyList()).stream().flatMap(getSpecifiedTypes(stagedTypes))
                .collect(Collectors.toSet());

        attributeDescriptors.addAll(extendedAttributes);

        Optional.ofNullable(metacardType.attributes).orElse(Collections.emptyMap())
                .forEach((attributeName, attribute) -> processAttribute(metacardType, attributeDescriptors,
                        requiredAttributes, attributeName, attribute));

        if (!requiredAttributes.isEmpty()) {
            final MetacardValidator validator = new RequiredAttributesMetacardValidator(metacardType.type,
                    requiredAttributes);
            staged.add(() -> {/*from   www.j av  a  2 s  . co m*/
                ServiceRegistration<MetacardValidator> registration = context
                        .registerService(MetacardValidator.class, validator, null);
                changeset.metacardValidatorServices.add(registration);
                return registration != null;
            });
        }

        Dictionary<String, Object> properties = new DictionaryMap<>();
        properties.put(NAME_PROPERTY, metacardType.type);
        MetacardType type = new MetacardTypeImpl(metacardType.type, attributeDescriptors);
        stagedTypes.add(type);
        staged.add(() -> {
            ServiceRegistration<MetacardType> registration = context.registerService(MetacardType.class, type,
                    properties);
            changeset.metacardTypeServices.add(registration);
            return registration != null;
        });
    }
    return staged;
}

From source file:org.apache.servicemix.jbi.deployer.impl.Deployer.java

public ServiceAssemblyImpl registerServiceAssembly(Bundle bundle, ServiceAssemblyDesc serviceAssemblyDesc,
        List<ServiceUnitImpl> sus) throws Exception {
    // Now create the SA and initialize it
    Preferences prefs = preferencesService
            .getUserPreferences(serviceAssemblyDesc.getIdentification().getName());
    ServiceAssemblyImpl sa = new ServiceAssemblyImpl(bundle, serviceAssemblyDesc, sus, prefs, endpointListener,
            autoStart);/*  w w  w.  j  av  a2  s  .  c  o m*/
    sa.setShutdownTimeout(shutdownTimeout);
    sa.setListenerRegistry(listenerRegistry);
    sa.init();
    serviceAssemblies.put(sa.getName(), sa);
    // populate props from the component meta-data
    Dictionary<String, String> props = new Hashtable<String, String>();
    props.put(NAME, serviceAssemblyDesc.getIdentification().getName());
    // register the service assembly in the OSGi registry
    LOGGER.debug("Registering JBI service assembly");
    registerService(bundle, ServiceAssembly.class.getName(), sa, props);
    getManagementStrategy().manageObject(sa);
    return sa;
}

From source file:org.apache.servicemix.jbi.deployer.impl.Deployer.java

public ComponentImpl registerComponent(Bundle bundle, ComponentDesc componentDesc,
        javax.jbi.component.Component innerComponent, SharedLibrary[] sharedLibraries) throws Exception {
    String name = componentDesc.getIdentification().getName();
    Preferences prefs = preferencesService.getUserPreferences(name);
    ComponentImpl component = new ComponentImpl(bundle, componentDesc, innerComponent, prefs, autoStart,
            sharedLibraries);//www.java2  s.  c  o  m
    component.setListenerRegistry(listenerRegistry);
    // populate props from the component meta-data
    Dictionary<String, String> props = new Hashtable<String, String>();
    props.put(NAME, name);
    props.put(TYPE, componentDesc.getType());
    for (SharedLibrary lib : sharedLibraries) {
        ((SharedLibraryImpl) lib).addComponent(component);
    }
    components.put(name, component);
    // register the component in the OSGi registry
    LOGGER.debug("Registering JBI component");
    registerService(bundle, new String[] { Component.class.getName(), ComponentWrapper.class.getName() },
            component, props);
    // Now, register the inner component
    if (!wrappedComponents.containsKey(name)) {
        registerService(bundle, javax.jbi.component.Component.class.getName(), innerComponent, props);
    }
    getManagementStrategy().manageObject(component);
    return component;
}

From source file:org.codice.ddf.admin.core.impl.ConfigurationAdminImpl.java

public ConfigurationStatus enableManagedServiceFactoryConfiguration(String servicePid,
        Configuration disabledConfig) throws IOException {
    Dictionary<String, Object> properties = disabledConfig.getProperties();
    String disabledFactoryPid = (String) properties
            .get(org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID);
    if (disabledFactoryPid == null) {
        throw new IOException("Configuration does not belong to a managed service factory.");
    }/*from  w ww  .ja v  a 2s.  co m*/
    if (!StringUtils.endsWith(disabledFactoryPid, ConfigurationStatus.DISABLED_EXTENSION)) {
        throw new IOException("Configuration is already enabled.");
    }

    String enabledFactoryPid = StringUtils.removeEnd(disabledFactoryPid,
            ConfigurationStatus.DISABLED_EXTENSION);
    Dictionary<String, Object> enabledProperties = copyConfigProperties(properties, enabledFactoryPid);
    enabledProperties.put(org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID, enabledFactoryPid);
    Configuration enabledConfiguration = configurationAdmin.createFactoryConfiguration(enabledFactoryPid, null);
    enabledConfiguration.update(enabledProperties);

    disabledConfig.delete();

    return new ConfigurationStatusImpl(enabledFactoryPid, enabledConfiguration.getPid(), disabledFactoryPid,
            servicePid);
}