List of usage examples for java.util Dictionary put
public abstract V put(K key, V value);
From source file:org.sakaiproject.nakamura.cluster.ClusterTrackingServiceImpl.java
/** * @param trackingCookie//from ww w . ja v a 2 s. com * @param remoteUser * @throws PingRemoteTrackingFailedException */ private void pingRemoteTracking(String trackingCookie, String remoteUser) throws PingRemoteTrackingFailedException { ClusterServer clusterServer = getServer(trackingCookie); if (clusterServer == null) { throw new PingRemoteTrackingFailedException("Server at " + trackingCookie + " not alive "); } // send over OSGi and then JMS over the OSGi2JMS Bridge Dictionary<String, Object> messageDict = new Hashtable<String, Object>(); messageDict.put(EVENT_FROM_SERVER, serverId); messageDict.put(EVENT_TO_SERVER, clusterServer.getServerId()); messageDict.put(EVENT_TRACKING_COOKIE, trackingCookie); messageDict.put(EVENT_USER, remoteUser); Event pingUserEvent = new Event(EVENT_PING_CLUSTER_USER + "/" + clusterServer.getServerId(), messageDict); eventAdmin.postEvent(pingUserEvent); }
From source file:org.eclipse.gemini.blueprint.compendium.internal.cm.ManagedServiceFactoryFactoryBean.java
private void registerService() { synchronized (monitor) { Dictionary props = new Hashtable(2); props.put(Constants.SERVICE_PID, factoryPid); configurationWatcher = bundleContext.registerService(ManagedServiceFactory.class.getName(), new ConfigurationWatcher(), props); }//from w w w. ja va2 s .c o m }
From source file:com.adobe.acs.commons.rewriter.impl.VersionedClientlibsTransformerFactory.java
@Activate @SuppressWarnings("squid:S1149") protected void activate(ComponentContext componentContext) { final BundleContext bundleContext = componentContext.getBundleContext(); final Dictionary<?, ?> props = componentContext.getProperties(); final int size = PropertiesUtil.toInteger(props.get(PROP_MD5_CACHE_SIZE), DEFAULT_MD5_CACHE_SIZE); this.md5Cache = CacheBuilder.newBuilder().recordStats().maximumSize(size).build(); this.disableVersioning = PropertiesUtil.toBoolean(props.get(PROP_DISABLE_VERSIONING), DEFAULT_DISABLE_VERSIONING); this.enforceMd5 = PropertiesUtil.toBoolean(props.get(PROP_ENFORCE_MD5), DEFAULT_ENFORCE_MD5); if (enforceMd5) { Dictionary<String, Object> filterProps = new Hashtable<String, Object>(); filterProps.put("sling.filter.scope", "REQUEST"); filterProps.put("service.ranking", Integer.valueOf(0)); filterReg = bundleContext.registerService(Filter.class.getName(), new BadMd5VersionedClientLibsFilter(), filterProps);/*from w w w. j a v a2 s. com*/ } }
From source file:org.codice.pubsub.stomp.SubscriptionQueryMessageListener.java
private boolean createSubscription(SearchQueryMessage queryMsg) { boolean success = false; String subscriptionId = queryMsg.getSubscriptionId(); //Build Query String cqlText = queryMsg.getQueryString(); if (StringUtils.isNotEmpty(cqlText)) { Filter filter = null;//from w w w.j a v a 2 s . co m try { filter = CQL.toFilter(cqlText); } catch (CQLException e) { LOGGER.error("Fatal error while trying to build CQL-based Filter from cqlText : " + cqlText); return success; } //Add CSW Record Mapper Filter Visitor for more CQL filtering options try { FilterVisitor f = new CswRecordMapperFilterVisitor(); filter = (Filter) filter.accept(f, null); } catch (UnsupportedOperationException ose) { try { throw new CswException(ose.getMessage(), CswConstants.INVALID_PARAMETER_VALUE, null); } catch (CswException e) { LOGGER.error(e.getMessage()); return success; } } if (catalogFramework != null && filter != null) { LOGGER.trace("Catalog Frameowork: " + catalogFramework.getVersion()); //Set creation and last modified date times Calendar now = Calendar.getInstance(); queryMsg.setCreationDate(now.getTimeInMillis()); queryMsg.setLastModifiedDate(now.getTimeInMillis()); //Starts this class in a thread ExecutorService executor = Executors.newFixedThreadPool(NUM_QUERY_SEND_THREADS); QueryAndSend qasInst = queryAndSend.newInstance(); qasInst.setEnterprise(DEFAULT_IS_ENTERPRISE); qasInst.setFilter(filter); qasInst.setSubscriptionId(subscriptionId); Callable worker = qasInst; executor.submit(worker); //Add to Subscription Map ObjectMapper mapper = new ObjectMapper(); String jsonMsg = null; try { jsonMsg = mapper.writeValueAsString(queryMsg); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage()); return success; } LOGGER.debug("Store Subscription: " + jsonMsg); Dictionary subMap = getSubscriptionMap(); subMap.put(subscriptionId, jsonMsg); setSubscriptionMap(subMap); //Set TTL (time to live) for subscription int ttlType = Calendar.MILLISECOND; String queryTtlType = queryMsg.getSubscriptionTtlType(); //If Query TTL Type is null, assume Milliseconds if (StringUtils.isBlank(queryTtlType)) { LOGGER.debug("Query TTL Type is null"); queryTtlType = TTL_TYPE_MILLISECONDS; } if (queryTtlType.equals(TTL_TYPE_MILLISECONDS)) { ttlType = Calendar.MILLISECOND; } else if (queryTtlType.equals(TTL_TYPE_SECONDS)) { ttlType = Calendar.SECOND; } else if (queryTtlType.equals(TTL_TYPE_MINUTES)) { ttlType = Calendar.MINUTE; } else if (queryTtlType.equals(TTL_TYPE_HOURS)) { ttlType = Calendar.HOUR; } else if (queryTtlType.equals(TTL_TYPE_MONTHS)) { ttlType = Calendar.MONTH; } else if (queryTtlType.equals(TTL_TYPE_YEARS)) { ttlType = Calendar.YEAR; } int queryTtl = queryMsg.getSubscriptionTtl(); LOGGER.debug("Query TTL: {}", queryTtl); if (queryTtl == -9 || queryTtl == 0) { //No TTL chosen; make it close to forever queryTtl = 9999; ttlType = Calendar.YEAR; } //Set TTL from creation time to TTL specified long creationTime = queryMsg.getCreationDate(); Calendar ttl = Calendar.getInstance(); ttl.setTimeInMillis(creationTime); ttl.add(ttlType, queryTtl); subscriptionTtlMap.put(subscriptionId, ttl); success = true; } else { LOGGER.trace("Catalog Framework or filter is NULL"); } } else { LOGGER.debug("Subscription ID is null: Subscription ID= {}", subscriptionId); } return success; }
From source file:org.opencastproject.kernel.rest.RestPublisher.java
/** * Creates a REST endpoint for the JAX-RS annotated service. * //from w w w.j a v a2 s .co m * @param ref * the osgi service reference * @param service * The service itself */ @SuppressWarnings("unchecked") protected void createEndpoint(ServiceReference ref, Object service) { RestServlet cxf = new RestServlet(); ServiceRegistration reg = null; String serviceType = (String) ref.getProperty(SERVICE_TYPE_PROPERTY); String servicePath = (String) ref.getProperty(SERVICE_PATH_PROPERTY); boolean jobProducer = Boolean.parseBoolean((String) ref.getProperty(SERVICE_JOBPRODUCER_PROPERTY)); try { Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put("contextId", RestConstants.HTTP_CONTEXT_ID); props.put("alias", servicePath); props.put(SERVICE_TYPE_PROPERTY, serviceType); props.put(SERVICE_PATH_PROPERTY, servicePath); props.put(SERVICE_JOBPRODUCER_PROPERTY, jobProducer); reg = componentContext.getBundleContext().registerService(Servlet.class.getName(), cxf, props); } catch (Exception e) { logger.info("Problem registering REST endpoint {} : {}", servicePath, e.getMessage()); return; } servletRegistrationMap.put(servicePath, reg); // Wait for the servlet to be initialized. Since the servlet is published via the whiteboard, this may happen // asynchronously while (!cxf.isInitialized()) { logger.debug("Waiting for the servlet at '{}' to be initialized", servicePath); try { Thread.sleep(100); } catch (InterruptedException e) { logger.warn("Interrupt while waiting for RestServlet initialization"); break; } } // Set up cxf Bus bus = cxf.getBus(); JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean(); factory.setBus(bus); factory.setProviders(providers); // Set the service class factory.setServiceClass(service.getClass()); factory.setResourceProvider(service.getClass(), new SingletonResourceProvider(service)); // Set the address to '/', which will force the use of the http service factory.setAddress("/"); // Use the cxf classloader itself to create the cxf server ClassLoader bundleClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader delegateClassLoader = JAXRSServerFactoryBean.class.getClassLoader(); try { Thread.currentThread().setContextClassLoader(delegateClassLoader); factory.create(); } finally { Thread.currentThread().setContextClassLoader(bundleClassLoader); } logger.info("Registered REST endpoint at " + servicePath); }
From source file:de.tum.in.socket.client.SocketClient.java
/** * Publishes asynchronous events for caching *//*from www.j av a2s . com*/ private void doBroadcastEventsForCaching(final String message) { LOGGER.debug("Publishing Event for caching wifi data..."); final Dictionary<String, Object> properties = new Hashtable<>(); properties.put("data", message); properties.put("timestamp", LocalDateTime.now()); final Event event = new Event(Events.DATA_CACHE, properties); this.m_eventAdmin.postEvent(event); LOGGER.debug("Publishing Event for caching wifi data...Done"); }
From source file:com.activecq.samples.replication.impl.ReverseReplicatorImpl.java
private void replicate(final Resource resource, final Event event) throws ReplicationException { if (resource == null) { return;/*from ww w.jav a 2s . c o m*/ } final ReplicationOptions replicationOptions = new ReplicationOptions(); final Session adminSession = resource.getResourceResolver().adaptTo(Session.class); final String revision = (String) resource.getResourceMetadata().get("resourceVersion"); if (revision != null) { replicationOptions.setRevision(revision); } replicationOptions.setFilter(DISTRIBUTE_AGENT_FILTER); replicationOptions.setSynchronous(sychronous); replicationOptions.setSuppressStatusUpdate(suppressStatusUpdate); replicationOptions.setSuppressVersions(supressVersioning); if (canReplicate(null, resource.getPath())) {//adminResourceResolver.adaptTo(User.class), resource.getPath())) { replicator.replicate(adminSession, getReplicationActionType(event), resource.getPath(), replicationOptions); } else { final String path = resource.getPath(); log.error((new StringBuilder()).append(adminSession.getUserID()) .append(" is not allowed to replicate this page/asset ").append(path) .append(". Issuing request for 'replication'").toString()); final Dictionary properties = new Hashtable<String, Object>(); properties.put("path", path); properties.put("replicationType", getReplicationActionType(event)); final Event activationEvent = new Event("com/day/cq/wcm/workflow/req/for/activation", properties); eventAdmin.sendEvent(activationEvent); } }
From source file:org.codice.ddf.registry.publication.manager.RegistryPublicationManagerTest.java
private Event getRegistryEvent(String topic, ArrayList<String> locations) { Dictionary<String, Object> eventProperties = new Hashtable<>(); Metacard mcard = getRegistryMetacard(DEFAULT_REGISTRY_ID); if (locations != null) { mcard.setAttribute(new AttributeImpl(RegistryObjectMetacardType.PUBLISHED_LOCATIONS, locations)); }//from www. jav a 2 s . c o m eventProperties.put(METACARD_PROPERTY, mcard); return new Event(topic, eventProperties); }
From source file:org.sakaiproject.nakamura.user.lite.servlet.LiteCreateSakaiGroupServlet.java
@Override protected void handleOperation(SlingHttpServletRequest request, HtmlResponse response, List<Modification> changes) throws AuthorizableExistsException, ClientPoolException, StorageClientException, AccessDeniedException { // KERN-432 dont allow anon users to access create group. if (User.ANON_USER.equals(request.getRemoteUser())) { response.setStatus(403, "AccessDenied"); return;//from w ww .j av a 2s. c o m } // check that the submitted parameter values have valid values. final String principalName = request.getParameter(SlingPostConstants.RP_NODE_NAME); if (principalName == null) { throw new IllegalArgumentException("Group name was not submitted"); } LiteNameSanitizer san = new LiteNameSanitizer(principalName, false); san.validate(); // check for allow create Group boolean allowCreateGroup = false; User currentUser = null; try { Session currentSession = StorageClientUtils .adaptToSession(request.getResourceResolver().adaptTo(javax.jcr.Session.class)); AuthorizableManager authorizableManager = currentSession.getAuthorizableManager(); currentUser = (User) authorizableManager.findAuthorizable(currentSession.getUserId()); if (currentUser.isAdmin()) { LOGGER.debug("User is an admin "); allowCreateGroup = true; } else { LOGGER.debug("Checking for membership of one of {} ", authorizedGroups); for (String groupName : currentUser.getPrincipals()) { if (authorizedGroups.contains(groupName)) { allowCreateGroup = true; break; } } // TODO: Implement Dynamic Group membership checks } } catch (Exception ex) { LOGGER.warn("Failed to determin if the user is an admin, assuming not. Cause: " + ex.getMessage()); allowCreateGroup = false; } if (!allowCreateGroup) { LOGGER.debug("User is not allowed to create groups "); response.setStatus(HttpServletResponse.SC_FORBIDDEN, "User is not allowed to create groups"); return; } Session session = getSession(); try { AuthorizableManager authorizableManager = session.getAuthorizableManager(); Authorizable authorizable = authorizableManager.findAuthorizable(principalName); if (authorizable != null) { // principal already exists! response.setStatus(400, "A principal already exists with the requested name: " + principalName); return; } else { if (authorizableManager.createGroup(principalName, principalName, null)) { Group group = (Group) authorizableManager.findAuthorizable(principalName); String groupPath = LiteAuthorizableResourceProvider.SYSTEM_USER_MANAGER_GROUP_PREFIX + group.getId(); Map<String, RequestProperty> reqProperties = collectContent(request, response, groupPath); response.setPath(groupPath); response.setLocation(groupPath); response.setParentLocation(LiteAuthorizableResourceProvider.SYSTEM_USER_MANAGER_GROUP_PATH); changes.add(Modification.onCreated(groupPath)); Map<String, Object> toSave = Maps.newLinkedHashMap(); // It is not allowed to touch the rep:group-managers property directly. String key = SYSTEM_USER_MANAGER_GROUP_PREFIX + principalName + "/"; reqProperties.remove(key + PROP_GROUP_MANAGERS); reqProperties.remove(key + PROP_GROUP_VIEWERS); // write content from form writeContent(session, group, reqProperties, changes, toSave); dumpToSave(toSave, "after write content"); // update the group memberships, although this uses session from the request, it // only // does so for finding authorizables, so its ok that we are using an admin session // here. updateGroupMembership(request, session, group, changes, toSave); dumpToSave(toSave, " after update group membership"); // TODO We should probably let the client decide whether the // current user belongs in the managers list or not. updateOwnership(request, group, new String[] { currentUser.getId() }, changes, toSave); dumpToSave(toSave, "before save"); saveAll(session, toSave); try { postProcessorService.process(group, session, ModificationType.CREATE, ParameterMap.extractParameters(request)); } catch (Exception e) { LOGGER.warn(e.getMessage(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } // Launch an OSGi event for creating a group. try { Dictionary<String, String> properties = new Hashtable<String, String>(); properties.put(UserConstants.EVENT_PROP_USERID, principalName); properties.put("path", principalName); EventUtils.sendOsgiEvent(properties, UserConstants.TOPIC_GROUP_CREATED, eventAdmin); } catch (Exception e) { // Trap all exception so we don't disrupt the normal behaviour. LOGGER.error("Failed to launch an OSGi event for creating a user.", e); } } else { throw new AuthorizableExistsException("Failed to create group, already exists "); } } } finally { ungetSession(session); } }
From source file:org.openengsb.core.services.internal.deployer.connector.ConnectorDeployerServiceTest.java
private void setupPersistence() { DummyConfigPersistenceService<ConnectorDescription> backend = new DummyConfigPersistenceService<ConnectorDescription>(); configPersistence = new DefaultConfigPersistenceService(backend); Dictionary<String, Object> props2 = new Hashtable<String, Object>(); props2.put("configuration.id", org.openengsb.core.api.Constants.CONFIG_CONNECTOR); registerService(configPersistence, props2, ConfigPersistenceService.class); }