List of usage examples for java.util Dictionary put
public abstract V put(K key, V value);
From source file:org.apache.sling.servlets.resolver.internal.SlingServletResolver.java
private Dictionary<String, Object> createServiceProperties(final ServiceReference reference, final ServletResourceProvider provider, final String root) { final Dictionary<String, Object> params = new Hashtable<String, Object>(); params.put(ResourceProvider.PROPERTY_ROOT, root); params.put(Constants.SERVICE_DESCRIPTION, "ServletResourceProvider for Servlets at " + Arrays.asList(provider.getServletPaths())); // inherit service ranking Object rank = reference.getProperty(Constants.SERVICE_RANKING); if (rank instanceof Integer) { params.put(Constants.SERVICE_RANKING, rank); }/*from w w w. ja v a2s. co m*/ return params; }
From source file:org.apache.sling.servlets.resolver.internal.SlingServletResolver.java
/** * Activate this component./*from w w w. ja va 2s . c o m*/ */ @SuppressWarnings("unchecked") protected void activate(final ComponentContext context) throws LoginException { // from configuration if available final Dictionary<?, ?> properties = context.getProperties(); Object servletRoot = properties.get(PROP_SERVLET_ROOT); if (servletRoot == null) { servletRoot = DEFAULT_SERVLET_ROOT; } final Collection<ServiceReference> refs; synchronized (this.pendingServlets) { refs = new ArrayList<ServiceReference>(pendingServlets); pendingServlets.clear(); this.sharedScriptResolver = resourceResolverFactory .getAdministrativeResourceResolver(this.createAuthenticationInfo(context.getProperties())); this.searchPaths = this.sharedScriptResolver.getSearchPath(); servletResourceProviderFactory = new ServletResourceProviderFactory(servletRoot, this.searchPaths); // register servlets immediately from now on this.context = context; } createAllServlets(refs); // execution paths this.executionPaths = OsgiUtil.toStringArray(properties.get(PROP_PATHS), DEFAULT_PATHS); if (this.executionPaths != null) { // if we find a string combination that basically allows all paths, // we simply set the array to null if (this.executionPaths.length == 0) { this.executionPaths = null; } else { boolean hasRoot = false; for (int i = 0; i < this.executionPaths.length; i++) { final String path = this.executionPaths[i]; if (path == null || path.length() == 0 || path.equals("/")) { hasRoot = true; break; } } if (hasRoot) { this.executionPaths = null; } } } this.defaultExtensions = OsgiUtil.toStringArray(properties.get(PROP_DEFAULT_EXTENSIONS), DEFAULT_DEFAULT_EXTENSIONS); // create cache - if a cache size is configured this.cacheSize = OsgiUtil.toInteger(properties.get(PROP_CACHE_SIZE), DEFAULT_CACHE_SIZE); if (this.cacheSize > 5) { this.cache = new ConcurrentHashMap<AbstractResourceCollector, Servlet>(cacheSize); this.logCacheSizeWarning = true; } else { this.cacheSize = 0; } // setup default servlet this.getDefaultServlet(); // and finally register as event listener this.eventHandlerReg = context.getBundleContext().registerService(EventHandler.class.getName(), this, properties); this.plugin = new ServletResolverWebConsolePlugin(context.getBundleContext()); if (this.cacheSize > 0) { try { Dictionary<String, String> mbeanProps = new Hashtable<String, String>(); mbeanProps.put("jmx.objectname", "org.apache.sling:type=servletResolver,service=SlingServletResolverCache"); ServletResolverCacheMBeanImpl mbean = new ServletResolverCacheMBeanImpl(); mbeanRegistration = context.getBundleContext() .registerService(SlingServletResolverCacheMBean.class.getName(), mbean, mbeanProps); } catch (Throwable t) { LOGGER.debug("Unable to register mbean"); } } }
From source file:org.codice.ddf.spatial.ogc.csw.catalog.source.CswSource.java
private void registerMetacardTypes() { List<String> contentTypesNames = getContentTypeNames(); if (!contentTypesNames.isEmpty()) { Dictionary<String, Object> metacardTypeProperties = new Hashtable<String, Object>(); metacardTypeProperties.put(Metacard.CONTENT_TYPE, contentTypesNames.toArray(new String[contentTypesNames.size()])); CswRecordMetacardType cswRecordMetacardType = new CswRecordMetacardType(cswSourceConfiguration.getId()); LOGGER.debug("{}: CSW Record Metacard Type hash code: {}", cswSourceConfiguration.getId(), cswRecordMetacardType.hashCode()); LOGGER.debug("{}: Registering CSW Record Metacard Type {} with content types: {}", cswSourceConfiguration.getId(), cswRecordMetacardType.getClass().getName(), contentTypesNames); ServiceRegistration<?> registeredMetacardType = context.registerService(MetacardType.class.getName(), cswRecordMetacardType, metacardTypeProperties); registeredMetacardTypes.add(registeredMetacardType); } else {//from w w w . ja va 2s.c o m LOGGER.debug( "{}: There are no metadata content types to register for CSW Record Metacard Type {}. Not registering CSW Record Metacard Type {}.", cswSourceConfiguration.getId(), CswRecordMetacardType.class.getName(), CswRecordMetacardType.class.getName()); } }
From source file:ch.trustserv.soundbox.plugins.portals.jamendoplugin.JamendoPlugin.java
/** * * @param searchString//w w w . jav a2s . c om * @return */ @Override public Object searchSong(final String searchString) { URI link = null; try { link = new URI("http://api.jamendo.com/get2/id+name+album_name+" + "artist_name+duration/track/json/track_album+album_artist" + "?order=searchweight_desc&n=all&searchquery=" + searchString.replaceAll(" ", "%20")); } catch (URISyntaxException ex) { Logger.getLogger(JamendoPlugin.class.getName()).log(Level.SEVERE, null, ex); } HttpGet get = new HttpGet(link); HttpClient client = new DefaultHttpClient(); Dictionary l = new Hashtable<>(); ArrayList songArrayList = new ArrayList(); JSONParser parser = new JSONParser(); Object obj = null; try { HttpEntity entity = client.execute(get).getEntity(); String entityAsString = EntityUtils.toString(entity); entity.getContent().close(); if (entityAsString.isEmpty()) // something went wrong... { return null; } obj = parser.parse(entityAsString); } catch (IOException | IllegalStateException | ParseException | org.json.simple.parser.ParseException ex) { Logger.getLogger(JamendoPlugin.class.getName()).log(Level.SEVERE, null, ex); } JSONArray songs = (JSONArray) obj; Iterator iter = songs.iterator(); JSONObject rawSong = null; while (iter.hasNext()) { try { rawSong = (JSONObject) parser.parse(iter.next().toString()); } catch (org.json.simple.parser.ParseException ex) { Logger.getLogger(JamendoPlugin.class.getName()).log(Level.SEVERE, null, ex); } JamendoSong song = new JamendoSong(rawSong); songArrayList.add(song); } l.put("songList", songArrayList); l.put("portalName", "Jamendo"); ServiceReference ref = cx.getServiceReference(EventAdmin.class.getName()); if (ref != null) { EventAdmin eventAdmin = (EventAdmin) cx.getService(ref); Event reportGeneratedEvent = new Event(FOUNDSONG, l); eventAdmin.sendEvent(reportGeneratedEvent); } return null; }
From source file:org.opencastproject.capture.impl.CaptureAgentImpl.java
/** * Callback from the OSGi container once this service is started. This is where we register our shell commands. * /* www . j ava 2 s . c o m*/ * @param ctx * the component context */ public void activate(ComponentContext ctx) { logger.info("Starting CaptureAgentImpl."); confidence = Boolean.valueOf(configService.getItem(CaptureParameters.CAPTURE_CONFIDENCE_ENABLE)); if (ctx != null) { // Setup the shell commands Dictionary<String, Object> commands = new Hashtable<String, Object>(); commands.put(CommandProcessor.COMMAND_SCOPE, "capture"); commands.put(CommandProcessor.COMMAND_FUNCTION, new String[] { "status", "start", "stop", "ingest", "reset", "capture" }); logger.info("Registering capture agent osgi shell commands"); ctx.getBundleContext().registerService(CaptureAgentShellCommands.class.getName(), new CaptureAgentShellCommands(this), commands); this.context = ctx; } else { logger.warn("Bundle context is null, so this is probably a test." + " If you see this message from Felix please post a bug!"); } setAgentState(AgentState.IDLE); if (configService != null && ctx != null) { configService.setItem("org.opencastproject.server.url", ctx.getBundleContext().getProperty("org.opencastproject.server.url")); } else if (configService == null) { logger.warn("Config service was null, unable to set local server url!"); } else if (ctx == null) { logger.warn("Context was null, unable to set local server url!"); } }
From source file:it.txt.ens.client.subscriber.printer.osgi.Activator.java
@Override public void start(final BundleContext context) throws Exception { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO,/*from w w w. jav a 2 s. c o m*/ "[ENS Subscriber - Event printer example] Bundle ID: " + context.getBundle().getBundleId()); } //retrieve the configuration admin service ServiceReference<ConfigurationAdmin> configAdminSR = context.getServiceReference(ConfigurationAdmin.class); if (configAdminSR == null) throw new Exception("No " + ConfigurationAdmin.class.getName() + " available"); ConfigurationAdmin configAdmin = context.getService(configAdminSR); File currentPropertiesFile; Properties currentProperties; Configuration config; FileInputStream stream = null; Dictionary<String, Object> configuration; int i = 1; while ((currentPropertiesFile = new File(DEFAULT_CONFIG_DIR + String.format(PROPERTY_NAME_FORMAT, i++))) .exists()) { currentProperties = new Properties(); try { stream = new FileInputStream(currentPropertiesFile); currentProperties.load(stream); config = configAdmin.createFactoryConfiguration( RegisteredServices.SUBSCRIBER_MANAGED_SERVICE_FACTORY_PID, null); } catch (IOException e) { LOGGER.log(Level.WARNING, MessageFormat.format(LOGGING_MESSAGES.getString("errorWhileReadingPropertiesFile"), currentPropertiesFile.getAbsolutePath()), e); continue; } finally { if (stream != null) try { stream.close(); } catch (Exception e) { } } configuration = MapConverter.convert(currentProperties); configuration.put(it.txt.ens.client.subscriber.osgi.FilterAttributes.SUBSCRIBER_OWNER_KEY, (Long) context.getBundle().getBundleId()); configuration.put(it.txt.ens.client.subscriber.osgi.FilterAttributes.SUBSCRIBER_IMPLEMENTATION_KEY, SUBSCRIBER_IMPLEMENTATION_ID); config.update(configuration); Object patternOBJ = configuration.get(ENSResourceFactory.PATTERN); String pattern; String namespace; if (patternOBJ == null) { Object resourceOBJ = configuration.get(ENSResourceFactory.URI); if (resourceOBJ == null) throw new ConfigurationException(ENSResourceFactory.URI, "Missing property"); else { ServiceReference<ENSResourceFactory> resourceFactorySR = context .getServiceReference(ENSResourceFactory.class); ENSResourceFactory resourceFactory = context.getService(resourceFactorySR); ENSResource resource; try { resource = resourceFactory.create(new URI(resourceOBJ.toString())); pattern = resource.getPattern(); namespace = resource.getNamespace(); } catch (IllegalArgumentException e) { throw new ConfigurationException(ENSResourceFactory.URI, e.getMessage(), e); } catch (URIParseException e) { throw new ConfigurationException(ENSResourceFactory.URI, e.getMessage(), e); } catch (URISyntaxException e) { throw new ConfigurationException(ENSResourceFactory.URI, e.getMessage(), e); } context.ungetService(resourceFactorySR); } } else { pattern = (String) patternOBJ; namespace = (String) configuration.get(ENSResourceFactory.NAMESPACE); } //this doesn't work because the escape doesn't work // EqualsFilter implementationFilter = new EqualsFilter( // it.txt.ens.client.subscriber.osgi.FilterAttributes.SUBSCRIBER_IMPLEMENTATION_KEY, // LdapEncoder.filterEncode(SUBSCRIBER_IMPLEMENTATION_ID)); // EqualsFilter ownershipFilter = new EqualsFilter( // it.txt.ens.client.subscriber.osgi.FilterAttributes.SUBSCRIBER_OWNER_KEY, // (int) context.getBundle().getBundleId()); // EqualsFilter patternFilter = new EqualsFilter(ENSResourceFactory.PATTERN,LdapEncoder.filterEncode(pattern)); // AndFilter filter = new AndFilter().and(implementationFilter).and(ownershipFilter).and(patternFilter); // Filter osgiFilter = FrameworkUtil.createFilter(filter.toString()); try { filters.put(new SubscriberFilter(SUBSCRIBER_IMPLEMENTATION_ID, context.getBundle().getBundleId(), namespace, pattern)); // } catch (InvalidSyntaxException e) { // throw new ConfigurationException(null, "An error occurred while tracking subscription services using filter " + // osgiFilter.toString(), e); } catch (InterruptedException e) { continue; } } tracker = new ConfiguredSubscriberTracker(context); tracker.start(); }
From source file:org.apache.felix.webconsole.internal.compendium.ConfigManager.java
private String applyConfiguration(HttpServletRequest comingRequest, ConfigurationAdmin ca, String pid) throws IOException { if (comingRequest.getParameter("delete") != null) { // only delete if the PID is not our place holder if (!SAVED_PID.equals(pid)) { // TODO: should log this here !! Configuration config = ca.getConfiguration(pid, null); config.delete();/*from www . jav a2s. c om*/ } return comingRequest.getHeader("Referer"); } String factoryPid = comingRequest.getParameter(ConfigManager.factoryPID); Configuration tempConfig = null; String propertyList = comingRequest.getParameter("propertylist"); if (propertyList == null) { String propertiesString = comingRequest.getParameter("properties"); if (propertiesString != null) { byte[] propBytes = propertiesString.getBytes("ISO-8859-1"); ByteArrayInputStream bin = new ByteArrayInputStream(propBytes); Properties props = new Properties(); props.load(bin); tempConfig = getConfiguration(ca, pid, factoryPid); tempConfig.update(props); } } else { tempConfig = getConfiguration(ca, pid, factoryPid); Dictionary propsBook = tempConfig.getProperties(); if (propsBook == null) { propsBook = new Hashtable(); } Map attrDefMap = this.getAttributeDefinitionMap(tempConfig, null); if (attrDefMap != null) { StringTokenizer propTokens = new StringTokenizer(propertyList, ","); while (propTokens.hasMoreTokens()) { String propName = propTokens.nextToken(); AttributeDefinition currAttrDef = (AttributeDefinition) attrDefMap.get(propName); if (currAttrDef == null || (currAttrDef.getCardinality() == 0 && currAttrDef.getType() == AttributeDefinition.STRING)) { String currPropName = comingRequest.getParameter(propName); if (currPropName != null) { propsBook.put(propName, currPropName); } } else if (currAttrDef.getCardinality() == 0) { // scalar of non-string String curProp = comingRequest.getParameter(propName); if (curProp != null) { try { propsBook.put(propName, this.getType(currAttrDef.getType(), curProp)); } catch (NumberFormatException nfe) { // don't care } } } else { // array or vector of any type Vector tempVec = new Vector(); String[] properties = comingRequest.getParameterValues(propName); if (properties != null) { for (int i = 0; i < properties.length; i++) { try { tempVec.add(this.getType(currAttrDef.getType(), properties[i])); } catch (NumberFormatException nfe) { // don't care } } } // but ensure size int maxSize = Math.abs(currAttrDef.getCardinality()); if (tempVec.size() > maxSize) { tempVec.setSize(maxSize); } if (currAttrDef.getCardinality() < 0) { // keep the vector propsBook.put(propName, tempVec); } else { // convert to an array propsBook.put(propName, this.getArray(currAttrDef.getType(), tempVec)); } } } } tempConfig.update(propsBook); } // redirect to the new configuration (if existing) return (tempConfig != null) ? tempConfig.getPid() : ""; }
From source file:ch.entwine.weblounge.common.impl.scheduler.QuartzJob.java
/** * Initializes this job from an XML node that was generated using * {@link #toXml()}.//from w ww . jav a 2 s .c o m * * @param context * the job node * @param xpathProcessor * xpath processor to use * @throws IllegalStateException * if the job cannot be parsed * @see #toXml() */ @SuppressWarnings("unchecked") public static Job fromXml(Node config, XPath xPathProcessor) throws IllegalStateException { CronJobTrigger jobTrigger = null; Dictionary<String, Object> ctx = new Hashtable<String, Object>(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // Main attributes String identifier = XPathHelper.valueOf(config, "@id", xPathProcessor); // Implementation class String className = XPathHelper.valueOf(config, "m:class", xPathProcessor); Class<? extends JobWorker> c; try { c = (Class<? extends JobWorker>) classLoader.loadClass(className); c.newInstance(); // Create an instance just to make sure we catch any errors right here } catch (ClassNotFoundException e) { throw new IllegalStateException( "Implementation " + className + " for job '" + identifier + "' not found", e); } catch (InstantiationException e) { throw new IllegalStateException( "Error instantiating impelementation " + className + " for job '" + identifier + "'", e); } catch (IllegalAccessException e) { throw new IllegalStateException( "Access violation instantiating implementation " + className + " for job '" + identifier + "'", e); } catch (Throwable t) { throw new IllegalStateException( "Error loading implementation " + className + " for job '" + identifier + "'", t); } // Read execution schedule String schedule = XPathHelper.valueOf(config, "m:schedule", xPathProcessor); if (schedule == null) throw new IllegalStateException("No schedule has been defined for job '" + identifier + "'"); jobTrigger = new CronJobTrigger(schedule); // Read options Node nodes = XPathHelper.select(config, "m:options", xPathProcessor); OptionsHelper options = OptionsHelper.fromXml(nodes, xPathProcessor); for (Map.Entry<String, Map<Environment, List<String>>> entry : options.getOptions().entrySet()) { String key = entry.getKey(); Map<Environment, List<String>> environments = entry.getValue(); for (Environment environment : environments.keySet()) { List<String> values = environments.get(environment); if (values.size() == 1) ctx.put(key, values.get(0)); else ctx.put(key, values.toArray(new String[values.size()])); } } // Did we find something? QuartzJob job = new QuartzJob(identifier, c, ctx, jobTrigger); job.options = options; // name String name = XPathHelper.valueOf(config, "m:name", xPathProcessor); job.setName(name); return job; }
From source file:org.codice.ddf.admin.core.impl.AdminConsoleService.java
/** * @see AdminConsoleServiceMBean#updateForLocation(java.lang.String, java.lang.String, * java.util.Map)//www . jav a 2 s . c om */ public void updateForLocation(final String pid, String location, Map<String, Object> configurationTable) throws IOException { if (pid == null || pid.length() < 1) { throw loggedException(ILLEGAL_PID_MESSAGE); } if (configurationTable == null) { throw loggedException(ILLEGAL_TABLE_MESSAGE); } final Configuration config = configurationAdmin.getConfiguration(pid, location); if (isPermittedToViewService(config.getPid())) { final Metatype metatype = configurationAdminImpl.findMetatypeForConfig(config); if (metatype == null) { throw loggedException("Could not find metatype for " + pid); } final List<Map.Entry<String, Object>> configEntries = new ArrayList<>(); CollectionUtils.addAll(configEntries, configurationTable.entrySet().iterator()); CollectionUtils.transform(configEntries, new CardinalityTransformer(metatype.getAttributeDefinitions(), pid)); final Dictionary<String, Object> configProperties = config.getProperties(); final Dictionary<String, Object> newConfigProperties = (configProperties != null) ? configProperties : new Hashtable<>(); // If the configuration entry is a password, and its updated configuration value is // "password", do not update the password. for (Map.Entry<String, Object> configEntry : configEntries) { final String configEntryKey = configEntry.getKey(); Object configEntryValue = sanitizeUIConfiguration(pid, configEntryKey, configEntry.getValue()); if (configEntryValue.equals("password")) { for (Map<String, Object> metatypeProperties : metatype.getAttributeDefinitions()) { if (metatypeProperties.get("id").equals(configEntry.getKey()) && AttributeDefinition.PASSWORD == (Integer) metatypeProperties.get("type") && configProperties != null) { configEntryValue = configProperties.get(configEntryKey); break; } } } newConfigProperties.put(configEntryKey, configEntryValue); } config.update(newConfigProperties); } }