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:org.openengsb.core.test.AbstractOsgiMockServiceTest.java

/**
 * registers the service under the given interfaces and sets it's location in the root-context
 *//*from  w  w  w  .  j  a v a 2  s  .c o  m*/
protected void registerServiceAtRootLocation(Object service, String location, Class<?>... interfazes) {
    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put("location.root", new String[] { location });
    registerService(service, props, interfazes);
}

From source file:org.openengsb.core.test.AbstractOsgiMockServiceTest.java

/**
 * registers the service under the given interfaces, settint its "id"-property to the given id
 *//*from  w w w .  j  a v a  2s  .co  m*/
protected void registerService(Object service, String id, Class<?>... interfaces) {
    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(Constants.SERVICE_PID, id);
    registerService(service, props, interfaces);
}

From source file:org.openengsb.core.test.AbstractOsgiMockServiceTest.java

/**
 * registers the service under the given interfaces and sets its location-property accordingly:
 * location.context=location/*from  www.  j a  va 2s.  c  o m*/
 */
protected void registerServiceAtLocation(Object service, String location, String context,
        Class<?>... interfazes) {
    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put("location." + context, new String[] { location });
    registerService(service, props, interfazes);
}

From source file:org.ops4j.pax.runner.platform.internal.Activator.java

/**
 * Tracks platform builder services via a Service tracker.
 *//*  w ww .  j av a2s .  c om*/
private void trackPlatformBuilders() {
    m_serviceTracker = new ServiceTracker(m_bundleContext, PlatformBuilder.class.getName(), null) {
        /**
         * Create and register a new platform.
         *
         * @see ServiceTracker#addingService(org.osgi.framework.ServiceReference)
         */
        @Override
        public Object addingService(final ServiceReference serviceReference) {
            NullArgumentException.validateNotNull(serviceReference, "Service reference");
            LOGGER.debug("Platform builder available [" + serviceReference + "]");
            final PlatformBuilder platformBuilder = (PlatformBuilder) super.addingService(serviceReference);
            if (platformBuilder != null) {
                LOGGER.debug("Registering a platform for [" + platformBuilder + "]");
                // copy all properties
                final Dictionary<String, Object> props = new Hashtable<String, Object>();
                final String[] keys = serviceReference.getPropertyKeys();
                if (keys != null) {
                    for (String key : keys) {
                        props.put(key, serviceReference.getProperty(key));
                    }
                }
                try {
                    // create and register the platform
                    final Platform platform = createPlatform(platformBuilder);
                    final ServiceRegistration registration = m_bundleContext
                            .registerService(Platform.class.getName(), platform, props);
                    // and store it for clean up
                    m_registrations.put(serviceReference, registration);
                    if (platform instanceof PlatformImpl) {
                        m_platforms.put(serviceReference, (PlatformImpl) platform);
                    }
                    LOGGER.debug("Registred platform [" + platform + "]");
                } catch (Exception e) {
                    LOGGER.error("Could not register a platform for [" + serviceReference + "]", e);
                }
            }
            return platformBuilder;
        }

        /**
         * Unregister the platform corespronding to th ebuilder.
         *
         * @see ServiceTracker#removedService(org.osgi.framework.ServiceReference,Object)
         */
        @Override
        public void removedService(final ServiceReference serviceReference, final Object object) {
            LOGGER.debug("Platform builder removed [" + serviceReference + "]");
            if (!(object instanceof PlatformBuilder)) {
                throw new IllegalArgumentException("Invalid tracked object [" + object.getClass()
                        + "]. Expected an " + PlatformBuilder.class.getName());
            }
            super.removedService(serviceReference, object);
            final ServiceRegistration registration = m_registrations.get(serviceReference);
            if (registration != null) {
                registration.unregister();
                m_registrations.remove(serviceReference);
                LOGGER.debug("Unregistred platform for [" + object + "]");
            }
            m_platforms.remove(serviceReference);
        }
    };
    m_serviceTracker.open();
}

From source file:org.openengsb.core.test.AbstractOsgiMockServiceTest.java

@SuppressWarnings("unchecked")
private ServiceRegistration<?> registerServiceInBundlecontext(String[] clazzes, final Object service,
        Dictionary<String, Object> dict) {
    dict.put(Constants.OBJECTCLASS, clazzes);
    final ServiceReference<?> serviceReference = putService(service, dict);
    ServiceRegistration<?> result = mock(ServiceRegistration.class);

    // unregistering removes the service from both maps
    doAnswer(new Answer<Void>() {
        @Override//w w  w.j  av  a  2 s . c  om
        public Void answer(InvocationOnMock invocation) throws Throwable {
            synchronized (services) {
                services.remove(serviceReference);
            }
            synchronized (serviceReferences) {

                Dictionary<String, Object> props = serviceReferences.remove(serviceReference);
                updateServiceListeners(ServiceEvent.UNREGISTERING, serviceReference, props);
                return null;
            }
        }
    }).when(result).unregister();

    // when properties are replaced, place a copy of the new properties-dictionary in the
    // serviceReferences-map (that overwrites the old dictionary)
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Dictionary<String, Object> arg = (Dictionary<String, Object>) invocation.getArguments()[0];
            Dictionary<String, Object> newDict = new Hashtable<String, Object>();
            Enumeration<String> keys = arg.keys();
            while (keys.hasMoreElements()) {
                String next = keys.nextElement();
                newDict.put(next, arg.get(next));
            }
            synchronized (serviceReferences) {
                serviceReferences.put(serviceReference, newDict);
            }
            return null;
        }
    }).when(result).setProperties(any(Dictionary.class));

    when(result.getReference()).thenAnswer(new ValueAnswer<ServiceReference<?>>(serviceReference));
    updateServiceListeners(ServiceEvent.REGISTERED, serviceReference, dict);
    return result;
}

From source file:org.wisdom.framework.jpa.PersistenceUnitComponent.java

/**
 * Starts the unit. It creates the entity manager factory and entity manager, as well as the repository and crud
 * services.//ww w.  jav  a2s  .  co  m
 */
@Validate
public void start() {
    try {
        Map<String, Object> map = new HashMap<>();
        for (Persistence.PersistenceUnit.Properties.Property p : persistenceUnitXml.getProperties()
                .getProperty()) {
            map.put(p.getName(), p.getValue());
        }

        if (isOpenJPA()) {
            map.put("openjpa.ManagedRuntime",
                    "invocation(TransactionManagerMethod=org.wisdom.framework.jpa.accessor"
                            + ".TransactionManagerAccessor.get)");
        }

        // This is not going to work with OpenJPA because the current version of OpenJPA requires an old version
        // of javax.validation. The wisdom one is too recent.
        map.put("javax.persistence.validation.factory", validator);

        Dictionary<String, Object> properties = new Hashtable<>();
        properties.put(UNIT_NAME_PROP, persistenceUnitXml.getName());
        properties.put(UNIT_VERSION_PROP, sourceBundle.bundle.getVersion());
        properties.put(UNIT_PROVIDER_PROP, provider.getClass().getName());
        List<String> entities = persistenceUnitXml.getClazz();
        properties.put(UNIT_ENTITIES_PROP, entities.toArray(new String[entities.size()]));
        properties.put(UNIT_TRANSACTION_PROP, getTransactionType().toString());

        // If the unit set the transaction to RESOURCE_LOCAL, no JTA involved.
        if (persistenceUnitXml
                .getTransactionType() == org.wisdom.framework.jpa.model.PersistenceUnitTransactionType.RESOURCE_LOCAL) {
            entityManagerFactory = provider.createContainerEntityManagerFactory(this, map);
            emfRegistration = bundleContext.registerService(EntityManagerFactory.class, entityManagerFactory,
                    properties);

            entityManager = entityManagerFactory.createEntityManager();
            emRegistration = bundleContext.registerService(EntityManager.class, entityManager, properties);

            repository = new JPARepository(persistenceUnitXml, entityManager, entityManagerFactory,
                    transactionManager, sourceBundle.bundle.getBundleContext());
        } else {
            // JTA
            entityManagerFactory = provider.createContainerEntityManagerFactory(this, map);
            entityManager = new TransactionalEntityManager(transactionManager, entityManagerFactory, this);
            emRegistration = bundleContext.registerService(EntityManager.class, entityManager, properties);
            emfRegistration = bundleContext.registerService(EntityManagerFactory.class, entityManagerFactory,
                    properties);
            repository = new JPARepository(persistenceUnitXml, entityManager, entityManagerFactory,
                    transactionManager, sourceBundle.bundle.getBundleContext());
        }
    } catch (Exception e) {
        LOGGER.error("Error while initializing the JPA services for unit {}", persistenceUnitXml.getName(), e);
    }

}

From source file:org.openengsb.core.test.AbstractOsgiMockServiceTest.java

/**
 * creates a DomainProvider with for the given interface and name. This creates a mock of {@link DomainProvider}
 * where all String-methods return the name again.
 *
 * Also the service is registered with the mocked service-registry with the given name as domain-value
 *//*w w w  . j  a  v a 2 s  .c om*/
protected DomainProvider createDomainProviderMock(final Class<? extends Domain> interfaze, String name) {
    DomainProvider domainProviderMock = mock(DomainProvider.class);
    LocalizableString testDomainLocalizedStringMock = mock(LocalizableString.class);
    when(testDomainLocalizedStringMock.getString(Mockito.<Locale>any())).thenReturn(name);
    when(domainProviderMock.getId()).thenReturn(name);
    when(domainProviderMock.getName()).thenReturn(testDomainLocalizedStringMock);
    when(domainProviderMock.getDescription()).thenReturn(testDomainLocalizedStringMock);
    when(domainProviderMock.getDomainInterface()).thenAnswer(new Answer<Class<? extends Domain>>() {
        @Override
        public Class<? extends Domain> answer(InvocationOnMock invocation) {
            return interfaze;
        }
    });
    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(org.openengsb.core.api.Constants.DOMAIN_KEY, name);
    registerService(domainProviderMock, props, DomainProvider.class);
    return domainProviderMock;
}

From source file:org.openengsb.core.test.AbstractOsgiMockServiceTest.java

/**
 * creates a ConnectorProvider with for the given connectorType and domains. This creates a mock of
 * {@link ConnectorProvider} that returns a descriptor-mock when calling {@link ConnectorProvider#getDescriptor()}
 * Also the service is registered with the mocked service-registry
 *///from   w  w w.  j  av a 2s. com
protected ConnectorProvider createConnectorProviderMock(String connectorType, String... domains) {
    ConnectorProvider connectorProvider = mock(ConnectorProvider.class);
    when(connectorProvider.getId()).thenReturn(connectorType);

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(org.openengsb.core.api.Constants.CONNECTOR_KEY, connectorType);
    props.put(org.openengsb.core.api.Constants.DOMAIN_KEY, domains);
    registerService(connectorProvider, props, ConnectorProvider.class);

    ServiceDescriptor descriptor = mock(ServiceDescriptor.class);
    when(descriptor.getId()).thenReturn(connectorType);
    LocalizableString name = mockLocalizeableString("service.name");
    when(descriptor.getName()).thenReturn(name);
    LocalizableString desc = mockLocalizeableString("service.description");
    when(descriptor.getDescription()).thenReturn(desc);
    when(connectorProvider.getDescriptor()).thenReturn(descriptor);
    return connectorProvider;
}

From source file:ddf.test.itests.catalog.TestFtp.java

/**
 * Sets the clientAuth configuration in catalog-ftp feature.
 *
 * <p>An FTPS client without a certificate is used to indicate when the clientAuth configuration
 * has taken effect at the FTP server level. - When the clientAuth is set to "want", this FTPS
 * client without a certificate should be able to connect to the FTP server and successfully
 * complete the SSL handshake. - When the clientAuth is set to "need", this FTPS client without a
 * certificate should be able to connect to the FTP server but fail to complete the SSL handshake.
 *
 * <p>SocketException and FTPConnectionClosedException are thrown when the client cannot connect
 * to the server or the connection was closed unexpectedly. These exceptions are thrown when the
 * server is being updated. SSLException is thrown only after a client has successfully connected
 * and when the SSL handshake between the client and server fails.
 *
 * @throws Exception/*from  ww  w . ja va 2  s .co m*/
 */
private void setClientAuthConfiguration(String clientAuth) throws Exception {
    Configuration config = getAdminConfig().getConfiguration("ddf.catalog.ftp.FtpServerManager");
    config.setBundleLocation("mvn:ddf.catalog/ftp/" + System.getProperty("ddf.version"));
    Dictionary properties = new Hashtable<>();
    properties.put(CLIENT_AUTH_PROPERTY_KEY, clientAuth);
    config.update(properties);

    // wait until the clientAuth configuration has taken effect at the FTP server level
    switch (clientAuth) {
    case WANT:
        expect("SSL handshake to succeed with FTPS client without certificate because clientAuth = \"want\"")
                .within(SET_CLIENT_AUTH_TIMEOUT_SEC, TimeUnit.SECONDS).until(() -> {
                    FTPSClient client = null;
                    try {
                        client = createSecureClient(false);
                        disconnectClient(client);
                        return true;
                    } catch (SSLException e) {
                        // SSL handshake failed
                        return false;
                    } catch (SocketException | FTPConnectionClosedException e) {
                        // connection failed
                        return false;
                    }
                });
        break;
    case NEED:
        expect("SSL handshake to fail with FTPS client without certificate because clientAuth = \"need\"")
                .within(SET_CLIENT_AUTH_TIMEOUT_SEC, TimeUnit.SECONDS).until(() -> {
                    FTPSClient client = null;
                    try {
                        client = createSecureClient(false);
                        disconnectClient(client);
                        return false;
                    } catch (SSLException e) {
                        // SSL handshake failed
                        return true;
                    } catch (SocketException | FTPConnectionClosedException e) {
                        // connection failed
                        return false;
                    }
                });
    }
}

From source file:com.ibm.jaggr.core.impl.options.OptionsImpl.java

public OptionsImpl(boolean loadFromPropertiesFile, IAggregator aggregator) {
    this.aggregator = aggregator;
    this.registrationName = aggregator != null ? aggregator.getName() : ""; //$NON-NLS-1$
    defaultOptions = new Properties(initDefaultOptions());
    if (loadFromPropertiesFile) {
        setProps(loadProps(defaultOptions));
    } else {/*w  w w . ja v  a  2  s. c  o  m*/
        setProps(defaultOptions);
    }

    // Create the properties file if necessary
    tryCreatePropsFile();

    serviceRegistrations = new LinkedList<IServiceRegistration>();
    if (aggregator != null) {
        // Register properties file changed service listener
        Dictionary<String, String> dict = new Hashtable<String, String>();
        dict.put("name", registrationName); //$NON-NLS-1$
        dict.put("propsFileName", getPropsFile().getAbsolutePath()); //$NON-NLS-1$
        serviceRegistrations
                .add(aggregator.getPlatformServices().registerService(OptionsImpl.class.getName(), this, dict));

        // Register shutdown listener
        dict = new Hashtable<String, String>();
        dict.put("name", registrationName); //$NON-NLS-1$
        serviceRegistrations.add(aggregator.getPlatformServices()
                .registerService(IShutdownListener.class.getName(), this, dict));
    }
}