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:net.cellar.hazelcast.HazelcastGroupManager.java

public void unRegisterGroup(Group group) {
    String groupName = group.getName();
    //1. Remove local node from group.
    group.getMembers().remove(getNode());
    listGroups().put(groupName, group);//from   ww w .ja va2 s  .  c om

    //2. Unregister group consumers
    if (consumerRegistrations != null && !consumerRegistrations.isEmpty()) {
        ServiceRegistration consumerRegistration = consumerRegistrations.get(groupName);
        if (consumerRegistration != null) {
            consumerRegistration.unregister();
            consumerRegistrations.remove(groupName);
        }

    }

    //3. Unregister group producers
    if (producerRegistrations != null && !producerRegistrations.isEmpty()) {
        ServiceRegistration producerRegistration = producerRegistrations.get(groupName);
        if (producerRegistration != null) {
            producerRegistration.unregister();
            producerRegistrations.remove(groupName);
        }
    }

    //Remove group from configuration
    try {
        Configuration configuration = configurationAdmin.getConfiguration(Configurations.NODE);
        Dictionary<String, String> properties = configuration.getProperties();
        String groups = properties.get(Configurations.GROUPS_KEY);
        if (groups == null || groups.isEmpty()) {
            groups = "";
        } else if (groups.contains(groupName)) {

            Set<String> groupNamesSet = convertStringToSet(groups);
            groupNamesSet.remove(groupName);
            groups = convertSetToString(groupNamesSet);

        }
        properties.put(Configurations.GROUPS_KEY, groups);
        configuration.update(properties);
    } catch (IOException e) {
        logger.error("Error reading group configuration {}", group);
    }
}

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

public ConfigurationStatus disableManagedServiceFactoryConfiguration(String servicePid,
        Configuration originalConfig) throws IOException {
    Dictionary<String, Object> properties = originalConfig.getProperties();
    String originalFactoryPid = (String) properties
            .get(org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID);
    if (originalFactoryPid == null) {
        throw new IOException("Configuration does not belong to a managed service factory.");
    }//from  w  w  w.j a  va2  s  . c  o m
    if (StringUtils.endsWith(originalFactoryPid, ConfigurationStatus.DISABLED_EXTENSION)) {
        throw new IOException("Configuration is already disabled.");
    }

    // Copy configuration from the original configuration and change its factory PID to end with
    // "disabled"
    Dictionary<String, Object> disabledProperties = copyConfigProperties(properties, originalFactoryPid);
    String disabledServiceFactoryPid = originalFactoryPid + ConfigurationStatus.DISABLED_EXTENSION;
    disabledProperties.put(org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID,
            disabledServiceFactoryPid);
    Configuration disabledConfig = configurationAdmin.createFactoryConfiguration(disabledServiceFactoryPid,
            null);
    disabledConfig.update(disabledProperties);

    // remove original configuration
    originalConfig.delete();
    return new ConfigurationStatusImpl(disabledServiceFactoryPid, disabledConfig.getPid(), originalFactoryPid,
            servicePid);
}

From source file:org.ops4j.pax.web.service.jetty.internal.JettyServerWrapper.java

@SuppressWarnings("unchecked")
private HttpServiceContext addContext(final ContextModel model) {
    Bundle bundle = model.getBundle();//from  www .j a va 2 s .  co m
    BundleContext bundleContext = BundleUtils.getBundleContext(bundle);
    // scan for ServletContainerInitializers
    Set<Bundle> bundlesInClassSpace = ClassPathUtil.getBundlesInClassSpace(bundle, new HashSet<Bundle>());

    if (jettyBundle != null) {
        ClassPathUtil.getBundlesInClassSpace(jettyBundle, bundlesInClassSpace);
    }

    for (URL u : ClassPathUtil.findResources(bundlesInClassSpace, "/META-INF/services",
            "javax.servlet.ServletContainerInitializer", true)) {
        try {
            InputStream is = u.openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            // only the first line is read, it contains the name of the
            // class.
            String className = reader.readLine();
            LOG.info("will add {} to ServletContainerInitializers", className);

            if (className.endsWith("JasperInitializer")) {
                LOG.info("Skipt {}, because specialized handler will be present", className);
                continue;
            }

            Class<?> initializerClass;

            try {
                initializerClass = bundle.loadClass(className);
            } catch (ClassNotFoundException ignore) {
                initializerClass = jettyBundle.loadClass(className);
            }

            // add those to the model contained ones
            Map<ServletContainerInitializer, Set<Class<?>>> containerInitializers = model
                    .getContainerInitializers();

            ServletContainerInitializer initializer = (ServletContainerInitializer) initializerClass
                    .newInstance();

            if (containerInitializers == null) {
                containerInitializers = new HashMap<ServletContainerInitializer, Set<Class<?>>>();
                model.setContainerInitializers(containerInitializers);
            }

            Set<Class<?>> setOfClasses = new HashSet<Class<?>>();
            // scan for @HandlesTypes
            HandlesTypes handlesTypes = initializerClass.getAnnotation(HandlesTypes.class);
            if (handlesTypes != null) {
                Class<?>[] classes = handlesTypes.value();

                for (Class<?> klass : classes) {
                    boolean isAnnotation = klass.isAnnotation();
                    boolean isInteraface = klass.isInterface();

                    if (isAnnotation) {
                        try {
                            BundleAnnotationFinder baf = new BundleAnnotationFinder(
                                    packageAdminTracker.getService(), bundle);
                            List<Class<?>> annotatedClasses = baf
                                    .findAnnotatedClasses((Class<? extends Annotation>) klass);
                            setOfClasses.addAll(annotatedClasses);
                        } catch (Exception e) {
                            LOG.warn("Failed to find annotated classes for ServletContainerInitializer", e);
                        }
                    } else if (isInteraface) {
                        BundleAssignableClassFinder basf = new BundleAssignableClassFinder(
                                packageAdminTracker.getService(), new Class[] { klass }, bundle);
                        Set<String> interfaces = basf.find();
                        for (String interfaceName : interfaces) {
                            setOfClasses.add(bundle.loadClass(interfaceName));
                        }
                    } else {
                        // class
                        BundleAssignableClassFinder basf = new BundleAssignableClassFinder(
                                packageAdminTracker.getService(), new Class[] { klass }, bundle);
                        Set<String> classNames = basf.find();
                        for (String klassName : classNames) {
                            setOfClasses.add(bundle.loadClass(klassName));
                        }
                    }
                }
            }
            containerInitializers.put(initializer, setOfClasses);
            LOG.info("added ServletContainerInitializer: {}", className);
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException e) {
            LOG.warn(
                    "failed to parse and instantiate of javax.servlet.ServletContainerInitializer in classpath");
        }
    }

    HttpServiceContext context = new HttpServiceContext((HandlerContainer) getHandler(),
            model.getContextParams(), getContextAttributes(bundleContext), model.getContextName(),
            model.getHttpContext(), model.getAccessControllerContext(), model.getContainerInitializers(),
            model.getJettyWebXmlURL(), model.getVirtualHosts());
    context.setClassLoader(model.getClassLoader());
    Integer modelSessionTimeout = model.getSessionTimeout();
    if (modelSessionTimeout == null) {
        modelSessionTimeout = sessionTimeout;
    }
    String modelSessionCookie = model.getSessionCookie();
    if (modelSessionCookie == null) {
        modelSessionCookie = sessionCookie;
    }
    String modelSessionDomain = model.getSessionDomain();
    if (modelSessionDomain == null) {
        modelSessionDomain = sessionDomain;
    }
    String modelSessionPath = model.getSessionPath();
    if (modelSessionPath == null) {
        modelSessionPath = sessionPath;
    }
    String modelSessionUrl = model.getSessionUrl();
    if (modelSessionUrl == null) {
        modelSessionUrl = sessionUrl;
    }
    Boolean modelSessionCookieHttpOnly = model.getSessionCookieHttpOnly();
    if (modelSessionCookieHttpOnly == null) {
        modelSessionCookieHttpOnly = sessionCookieHttpOnly;
    }
    Boolean modelSessionSecure = model.getSessionCookieSecure();
    if (modelSessionSecure == null) {
        modelSessionSecure = sessionCookieSecure;
    }
    String workerName = model.getSessionWorkerName();
    if (workerName == null) {
        workerName = sessionWorkerName;
    }
    configureSessionManager(context, modelSessionTimeout, modelSessionCookie, modelSessionDomain,
            modelSessionPath, modelSessionUrl, modelSessionCookieHttpOnly, modelSessionSecure, workerName,
            lazyLoad, storeDirectory);

    if (model.getRealmName() != null && model.getAuthMethod() != null) {
        configureSecurity(context, model.getRealmName(), model.getAuthMethod(), model.getFormLoginPage(),
                model.getFormErrorPage());
    }

    configureJspConfigDescriptor(context, model);

    LOG.debug("Added servlet context: " + context);

    if (isStarted()) {
        try {
            LOG.debug("(Re)starting servlet contexts...");
            // start the server handler if not already started
            Handler serverHandler = getHandler();
            if (!serverHandler.isStarted() && !serverHandler.isStarting()) {
                serverHandler.start();
            }
            // if the server handler is a handler collection, seems like
            // jetty will not automatically
            // start inner handlers. So, force the start of the created
            // context
            if (!context.isStarted() && !context.isStarting()) {
                LOG.debug("Registering ServletContext as service. ");
                Dictionary<String, String> properties = new Hashtable<String, String>();
                properties.put("osgi.web.symbolicname", bundle.getSymbolicName());

                Dictionary<?, ?> headers = bundle.getHeaders();
                String version = (String) headers.get(Constants.BUNDLE_VERSION);
                if (version != null && version.length() > 0) {
                    properties.put("osgi.web.version", version);
                }

                // Context servletContext = context.getServletContext();
                String webContextPath = context.getContextPath();

                properties.put("osgi.web.contextpath", webContextPath);

                context.registerService(bundleContext, properties);
                LOG.debug("ServletContext registered as service. ");

            }
            // CHECKSTYLE:OFF
        } catch (Exception ignore) {
            LOG.error("Could not start the servlet context for http context [" + model.getHttpContext() + "]",
                    ignore);
            if (ignore instanceof MultiException) {
                LOG.error("MultiException found: ");
                MultiException mex = (MultiException) ignore;
                List<Throwable> throwables = mex.getThrowables();
                for (Throwable throwable : throwables) {
                    LOG.error(throwable.getMessage());
                }
            }
        }
        // CHECKSTYLE:ON
    }
    return context;
}

From source file:org.energy_home.jemma.internal.device.zgd.StreamGobbler.java

private Dictionary getCurrentConfig() {
    Dictionary props = new Hashtable();
    props.put(PROP_ZGD_PORT, new String(this.zgdPort + ""));
    return props;
}

From source file:ch.entwine.weblounge.kernel.site.SiteDispatcherServiceImpl.java

/**
 * Adds a new site.//from   ww w.j a va 2  s  .c  o m
 * 
 * This method may be long-running and therefore is executed in its own
 * thread.
 * 
 * @param site
 *          the site
 */
private void addSite(final Site site) {
    Thread t = new Thread(new Runnable() {

        public void run() {

            Bundle siteBundle = siteManager.getSiteBundle(site);
            WebXml webXml = createWebXml(site, siteBundle);
            Properties initParameters = new Properties();

            // Prepare the init parameters
            // initParameters.put("load-on-startup", Integer.toString(1));
            initParameters.putAll(webXml.getContextParams());
            initParameters.putAll(jasperConfig);

            // Create the site URI
            String contextRoot = webXml.getContextParam(DispatcherConfiguration.WEBAPP_CONTEXT_ROOT,
                    DEFAULT_WEBAPP_CONTEXT_ROOT);
            String bundleURI = webXml.getContextParam(DispatcherConfiguration.BUNDLE_URI, site.getIdentifier());
            String siteContextURI = webXml.getContextParam(DispatcherConfiguration.BUNDLE_CONTEXT_ROOT_URI,
                    DEFAULT_BUNDLE_CONTEXT_ROOT_URI);
            String siteRoot = UrlUtils.concat(contextRoot, siteContextURI, bundleURI);

            // Prepare the Jasper work directory
            String scratchDirPath = PathUtils.concat(jasperConfig.get(OPT_JASPER_SCRATCHDIR),
                    site.getIdentifier());
            File scratchDir = new File(scratchDirPath);
            boolean jasperArtifactsExist = scratchDir.isDirectory() && scratchDir.list().length > 0;
            try {
                FileUtils.forceMkdir(scratchDir);
                logger.debug("Temporary jsp source files and classes go to {}", scratchDirPath);
            } catch (IOException e) {
                logger.warn("Unable to create jasper scratch directory at {}: {}", scratchDirPath,
                        e.getMessage());
            }

            try {
                // Create and register the site servlet
                SiteServlet siteServlet = new SiteServlet(site, siteBundle, environment);
                siteServlet.setSecurityService(securityService);
                Dictionary<String, String> servletRegistrationProperties = new Hashtable<String, String>();
                servletRegistrationProperties.put(Site.class.getName().toLowerCase(), site.getIdentifier());
                servletRegistrationProperties.put(SharedHttpContext.ALIAS, siteRoot);
                servletRegistrationProperties.put(SharedHttpContext.SERVLET_NAME, site.getIdentifier());
                servletRegistrationProperties.put(SharedHttpContext.CONTEXT_ID,
                        SharedHttpContext.WEBLOUNGE_CONTEXT_ID);
                servletRegistrationProperties.put(SharedHttpContext.INIT_PREFIX + OPT_JASPER_SCRATCHDIR,
                        scratchDirPath);
                ServiceRegistration servletRegistration = siteBundle.getBundleContext()
                        .registerService(Servlet.class.getName(), siteServlet, servletRegistrationProperties);
                servletRegistrations.put(site, servletRegistration);

                // We are using the Whiteboard pattern to register servlets. Wait for
                // the http service to pick up the servlet and initialize it
                synchronized (servletRegistrations) {
                    boolean warnedOnce = false;
                    while (!siteServlet.isInitialized()) {

                        if (!warnedOnce) {
                            logger.info("Waiting for site '{}' to be online", site.getIdentifier());
                            warnedOnce = true;
                        }

                        logger.debug("Waiting for http service to pick up {}", siteServlet);
                        servletRegistrations.wait(500);
                        if (shutdown) {
                            logger.info("Giving up waiting for registration of site '{}'");
                            servletRegistrations.remove(site);
                            return;
                        }
                    }
                }

                siteServlets.put(site, siteServlet);

                logger.info("Site '{}' is online and registered under site://{}", site, siteRoot);

                // Did we already miss the "siteStarted()" event? If so, we trigger it
                // for ourselves, so the modules are being started.
                site.addSiteListener(SiteDispatcherServiceImpl.this);
                if (site.isOnline()) {
                    siteStarted(site);
                }

                // Start the precompiler if requested
                if (precompile) {
                    String compilationKey = X_COMPILE_PREFIX + siteBundle.getBundleId();
                    Date compileDate = null;

                    boolean needsCompilation = true;

                    // Check if this site has been precompiled already
                    if (preferencesService != null) {
                        Preferences preferences = preferencesService.getSystemPreferences();
                        String compileDateString = preferences.get(compilationKey, null);
                        if (compileDateString != null) {
                            compileDate = WebloungeDateFormat.parseStatic(compileDateString);
                            needsCompilation = false;
                            logger.info("Site '{}' has already been precompiled on {}", site.getIdentifier(),
                                    compileDate);
                        }
                    } else {
                        logger.info(
                                "Precompilation status cannot be determined, consider deploying a preferences service implementation");
                    }

                    // Does the scratch dir exist?
                    if (!jasperArtifactsExist) {
                        needsCompilation = true;
                        logger.info("Precompiled artifacts for '{}' have been removed", site.getIdentifier());
                    }

                    // Let's do the work anyways
                    if (needsCompilation) {
                        Precompiler precompiler = new Precompiler(compilationKey, siteServlet, environment,
                                securityService, logCompileErrors);
                        precompilers.put(site, precompiler);
                        precompiler.precompile();
                    }
                }

                logger.debug("Site '{}' registered under site://{}", site, siteRoot);

            } catch (Throwable t) {
                logger.error("Error setting up site '{}' for http requests: {}",
                        new Object[] { site, t.getMessage() });
                logger.error(t.getMessage(), t);
            }

        }

    });
    t.setDaemon(true);
    t.start();
}

From source file:org.codice.ddf.registry.federationadmin.impl.FederationAdminTest.java

@Test
public void testRegistryStatusNoMatchingConfig() throws Exception {
    RegistryStore source = mock(RegistryStore.class);
    Configuration config = mock(Configuration.class);
    Dictionary<String, Object> props = new Hashtable<>();
    props.put("service.pid", "servicePid2");
    when(config.getProperties()).thenReturn(props);
    when(source.isAvailable()).thenReturn(true);
    when(helper.getRegistrySources()).thenReturn(Collections.singletonList(source));
    when(helper.getConfiguration(any(ConfiguredService.class))).thenReturn(config);
    assertThat(federationAdmin.registryStatus("servicePid"), is(false));
}

From source file:org.codice.ddf.registry.federationadmin.impl.FederationAdminTest.java

@Test
public void testRegistryStatus() throws Exception {
    RegistryStore source = mock(RegistryStore.class);
    Configuration config = mock(Configuration.class);
    Dictionary<String, Object> props = new Hashtable<>();
    props.put("service.pid", "servicePid");
    when(config.getProperties()).thenReturn(props);
    when(source.isAvailable()).thenReturn(true);
    when(helper.getRegistrySources()).thenReturn(Collections.singletonList(source));
    when(helper.getConfiguration(any(ConfiguredService.class))).thenReturn(config);
    assertThat(federationAdmin.registryStatus("servicePid"), is(true));
}

From source file:org.paxle.core.impl.RuntimeSettings.java

public Dictionary<?, ?> getCurrentIniSettings() {
    final Dictionary<String, Object> props = new Hashtable<String, Object>();
    final List<String> iniSettings = readSettings();

    final StringBuilder sb = new StringBuilder();
    final HashSet<OptEntry> opts = new HashSet<OptEntry>(OPTIONS);
    outer: for (final String opt : iniSettings) {
        final Iterator<OptEntry> it = opts.iterator();
        while (it.hasNext()) {
            final OptEntry e = it.next();
            if (opt.startsWith(e.fixOpt)) {
                props.put(e.getPid(), e.getValue(opt, true));
                it.remove();//from   w w w  . j a va2s . co m
                continue outer;
            }
        }
        if (sb.length() > 0)
            sb.append(OPT_OTHER_SPLIT);
        sb.append(opt);
    }
    for (final OptEntry e : opts)
        props.put(e.getPid(), e.getValue(null, true));
    if (sb.length() > 0)
        props.put(CM_OTHER_ENTRY.getPid(), sb.toString());

    return props;
}

From source file:org.apache.felix.webconsole.internal.servlet.OsgiManager.java

private Dictionary toStringConfig(Dictionary config) {
    Dictionary stringConfig = new Hashtable();
    for (Enumeration ke = config.keys(); ke.hasMoreElements();) {
        Object key = ke.nextElement();
        stringConfig.put(key.toString(), String.valueOf(config.get(key)));
    }/*from www  . j  a v a  2s. c  om*/
    return stringConfig;
}

From source file:org.codice.ddf.registry.federationadmin.impl.FederationAdminTest.java

@Test
public void testHandleEventDelete() throws Exception {
    performCreateEvent();// w  ww. ja v  a2 s. c  o m
    Dictionary<String, Object> eventProperties = new Hashtable<>();
    eventProperties.put("ddf.catalog.event.metacard", mcard);
    Event event = new Event("ddf/catalog/event/DELETED", eventProperties);
    federationAdmin.handleEvent(event);

    setupDefaultFilterProps();

    List<Map<String, Object>> result = (List<Map<String, Object>>) federationAdmin.allRegistryMetacardsSummary()
            .get("nodes");
    assertThat(result.size(), is(0));
}