List of usage examples for java.util Dictionary put
public abstract V put(K key, V value);
From source file:org.paxle.gui.impl.servlets.LoginView.java
@Override public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) throws Exception { Template template = null;//w ww .j ava 2 s . co m try { // Get the session HttpSession session = request.getSession(true); boolean doRedirect = false; if (request.getParameter("doLogin") != null) { // getting user-name + password String userName = request.getParameter("login.username"); String password = request.getParameter("login.password"); if (password == null) password = ""; // getting the userAdmin service IServiceManager manager = (IServiceManager) context.get(IServiceManager.SERVICE_MANAGER); UserAdmin uAdmin = (UserAdmin) manager.getService(UserAdmin.class.getName()); // auth user final User user = this.guiAuthManager.authenticatedAs(request, userName, password); if (user != null) { // remember login state session.setAttribute("logon.isDone", Boolean.TRUE); // set user-data into the session session.setAttribute(HttpContext.AUTHENTICATION_TYPE, HttpServletRequest.FORM_AUTH); session.setAttribute(HttpContext.AUTHORIZATION, uAdmin.getAuthorization(user)); session.setAttribute(HttpContext.REMOTE_USER, user); // keep user-settings in sync with user-language settings CookieTool cookieTool = (CookieTool) context.get("cookieTool"); if (cookieTool.get("l10n") != null) { @SuppressWarnings("unchecked") Dictionary<String, Object> userProps = user.getProperties(); userProps.put(UserView.USER_LANGUAGE, cookieTool.get("l10n").getValue()); } doRedirect = true; } else { context.put("errorMsg", "Unable to login. Username or password is invalid"); } } else if (request.getParameter("doLogout") != null) { session.removeAttribute("logon.isDone"); session.removeAttribute(HttpContext.AUTHENTICATION_TYPE); session.removeAttribute(HttpContext.AUTHORIZATION); session.removeAttribute(HttpContext.REMOTE_USER); doRedirect = true; } if (doRedirect) { // redirect to target if (session.getAttribute("login.target") != null) { response.sendRedirect((String) session.getAttribute("login.target")); session.removeAttribute("login.target"); } else if (request.getParameter("login.target") != null) { response.sendRedirect((String) request.getParameter("login.target")); request.removeAttribute("login.target"); } else { response.sendRedirect("/"); } } else { template = this.getTemplate("/resources/templates/LoginView.vm"); } } catch (Exception e) { this.logger.error(String.format("Unexpected '%s': %s", e.getClass().getName(), e.getMessage()), e); throw e; } return template; }
From source file:org.apache.karaf.itests.MavenTest.java
@Test public void smartRetriesTest() throws Exception { karafTestSupport.bundleContext = bundleContext; final ConfigurationAdmin cm = karafTestSupport.getOsgiService(ConfigurationAdmin.class, 3000); updateSettings();/*from w w w .j ava 2 s.c o m*/ awaitMavenResolver(new Runnable() { @Override public void run() { try { org.osgi.service.cm.Configuration config = cm.getConfiguration("org.ops4j.pax.url.mvn", null); Dictionary<String, Object> props = config.getProperties(); props.put("org.ops4j.pax.url.mvn.globalChecksumPolicy", "ignore"); props.put("org.ops4j.pax.url.mvn.socket.readTimeout", "2000"); props.put("org.ops4j.pax.url.mvn.connection.retryCount", "0"); props.put("org.ops4j.pax.url.mvn.repositories", "http://localhost:1111/repository@id=r1," + "http://localhost:2222/repository@id=r2," + "http://localhost:3333/repository@id=r3"); config.update(props); } catch (Exception e) { fail(e.getMessage()); } } }); // grab modified resolver MavenResolver resolver = karafTestSupport.getOsgiService(MavenResolver.class, 15000); try { resolver.resolve("mvn:commons-universalis/commons-universalis/42"); fail("Should fail at first attempt"); } catch (IOException e) { File f = resolver.resolve("mvn:commons-universalis/commons-universalis/42", e); byte[] commonsUniversalis = FileUtils.readFileToByteArray(f); assertThat(commonsUniversalis.length, equalTo(1)); assertThat(commonsUniversalis[0], equalTo((byte) 0x42)); } }
From source file:com.eurodyn.qlack2.util.datasource.generic.Configurator.java
public void refresh() { try {//from w w w. j av a2 s . co m Object registeredDs; // Configure the database driver. Object dbDriver = Class.forName(getDriverClass()).newInstance(); // To configure the driver in a generic way, we use the // driverParametersMapping. String[] params = getDriverParametersMapping().split(","); for (String param : params) { param = param.trim(); String paramKey = param.trim().split("-")[0]; String paramValue = param.trim().split("-")[1]; String property = BeanUtils.getProperty(this, paramValue); BeanUtils.setProperty(dbDriver, paramKey, property); } if (datasourceType.equals("javax.sql.XADataSource")) { BasicManagedDataSource managedDs = new BasicManagedDataSource(); managedDs.setTransactionManager(transactionManager); managedDs.setXaDataSourceInstance((XADataSource) dbDriver); managedDs.setInitialSize(initialSize); managedDs.setMaxActive(maxActive); managedDs.setMaxIdle(maxIdle); managedDs.setMinIdle(minIdle); managedDs.setMaxWait(maxWait); managedDs.setValidationQuery(validationQuery); managedDs.setTestOnBorrow(testOnBorrow); managedDs.setRemoveAbandoned(removeAbandoned); managedDs.setRemoveAbandonedTimeout(removeAbandonedTimeout); registeredDs = managedDs; } else { registeredDs = dbDriver; } // If the service is already registered it should be unregistered first. for (ServiceRegistration<?> registration : serviceRegistrations) { registration.unregister(); } // Expose datasources using the driver configured above. // This bundle accepts multiple jndi names as a comma-separated list so we // expose as many services as the provided jndi names. String[] jndiNames = jndiName.split(","); for (String name : jndiNames) { Dictionary<String, String> registrationProperties = new Hashtable<String, String>(); registrationProperties.put("osgi.jndi.service.name", name); ServiceRegistration<?> registration = context.registerService(DataSource.class.getName(), registeredDs, registrationProperties); serviceRegistrations.add(registration); LOGGER.log(Level.CONFIG, "Registered Datasource for {0} under {1}.", new String[] { getDriverClass(), name }); } } catch (ClassNotFoundException e) { LOGGER.log(Level.SEVERE, MessageFormat.format("Could not find database driver {0}.", getDriverClass()), e); } catch (InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e) { LOGGER.log(Level.SEVERE, MessageFormat.format("Could not instantiate database driver {0}.", getDriverClass()), e); } }
From source file:org.eclipse.gemini.blueprint.extender.internal.support.NamespaceManager.java
/** * Registers the NamespacePlugins instance as an Osgi Resolver service *//*from w w w .j a va 2s. c o m*/ private void registerResolverServices() { if (log.isDebugEnabled()) { log.debug("Registering Spring NamespaceHandlerResolver and EntityResolver..."); } Bundle bnd = BundleUtils.getDMCoreBundle(context); Dictionary<String, Object> props = null; if (bnd != null) { props = new Hashtable<String, Object>(); props.put(BundleUtils.DM_CORE_ID, bnd.getBundleId()); props.put(BundleUtils.DM_CORE_TS, bnd.getLastModified()); } nsResolverRegistration = context.registerService(new String[] { NamespaceHandlerResolver.class.getName() }, this.namespacePlugins, props); enResolverRegistration = context.registerService(new String[] { EntityResolver.class.getName() }, this.namespacePlugins, props); }
From source file:com.adobe.acs.commons.wcm.impl.AemEnvironmentIndicatorFilter.java
@Activate @SuppressWarnings("squid:S1149") protected final void activate(ComponentContext ctx) { Dictionary<?, ?> config = ctx.getProperties(); color = PropertiesUtil.toString(config.get(PROP_COLOR), ""); cssOverride = PropertiesUtil.toString(config.get(PROP_CSS_OVERRIDE), ""); innerHTML = PropertiesUtil.toString(config.get(PROP_INNER_HTML), ""); innerHTML = new StrSubstitutor(StrLookup.systemPropertiesLookup()).replace(innerHTML); // Only write CSS variable if cssOverride or color is provided if (StringUtils.isNotBlank(cssOverride)) { css = cssOverride;// ww w . ja va 2s . com } else if (StringUtils.isNotBlank(color)) { css = createCss(color); } titlePrefix = xss.encodeForJSString(PropertiesUtil.toString(config.get(PROP_TITLE_PREFIX), "").toString()); if (StringUtils.isNotBlank(css) || StringUtils.isNotBlank(titlePrefix)) { Dictionary<String, String> filterProps = new Hashtable<String, String>(); filterProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_PATTERN, "/"); filterProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT, "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=*)"); filterRegistration = ctx.getBundleContext().registerService(Filter.class.getName(), this, filterProps); } excludedWCMModes = PropertiesUtil.toStringArray(config.get(PROP_EXCLUDED_WCMMODES), DEFAULT_EXCLUDED_WCMMODES); }
From source file:it.txt.ens.namespace.osgi.test.Activator.java
@Override public void start(BundleContext context) throws Exception { //retrieve the configuration admin service configAdminSR = context.getServiceReference(ConfigurationAdmin.class); if (configAdminSR == null) throw new Exception("No " + ConfigurationAdmin.class.getName() + " available"); ConfigurationAdmin configAdmin = context.getService(configAdminSR); config = configAdmin.createFactoryConfiguration(NamespaceInquirerMSF.PID, null); //load the configuration for this bundle File configFile = new File(DEFAULT_CONFIG_DIR + CONFIG_FILE); Dictionary<String, Object> properties = null; try {//from w w w . j av a 2 s . c om properties = Utils.loadConfiguration(DEFAULT_CONFIG_DIR + CONFIG_FILE); //add owner id String ownerID = String.valueOf(context.getBundle().getBundleId()); properties.put(NamespaceInquirerMSF.OWNER_ID, ownerID); config.update(properties); EqualsFilter ownerIDFilter = new EqualsFilter(NamespaceInquirerMSF.OWNER_ID, ownerID); Filter filter = context.createFilter(ownerIDFilter.encode()); NamespaceInquirerTracker tracker = new NamespaceInquirerTracker(context, filter); new Thread(tracker, "Namespace Inquirer Tracker").start(); } catch (Exception e) { LOGGER.log(Level.WARNING, MessageFormat.format( LOGGING_MESSAGES.getString("errorWhileReadingConfigFile"), configFile.getAbsolutePath()), e); } }
From source file:org.forgerock.openidm.router.RouteBuilder.java
public Dictionary<String, Object> buildServiceProperties() { if (routes.isEmpty()) { return null; }//from w w w .j a v a 2 s. c o m StringBuilder sb = new StringBuilder("Route group of {"); Dictionary<String, Object> properties = new Hashtable<String, Object>(5); properties.put(Constants.SERVICE_VENDOR, ServerConstants.SERVER_VENDOR_NAME); if (routes.size() == 1) { String template = routes.iterator().next().uriTemplate; sb.append(template); properties.put(ServerConstants.ROUTER_PREFIX, template); } else if (routes.size() > 1) { Object[] params = routes.toArray(); for (int i = 0; i < params.length; i++) { params[i] = ((RouteItem) params[i]).uriTemplate; if (i > 0) { sb.append(", "); } sb.append(params[i]); } properties.put(ServerConstants.ROUTER_PREFIX, params); } properties.put(Constants.SERVICE_DESCRIPTION, sb.append("}").toString()); return properties; }
From source file:org.apache.sling.replication.transport.impl.PollingTransportHandlerFactory.java
protected TransportHandler createTransportHandler(Map<String, ?> config, Dictionary<String, Object> props, TransportAuthenticationProvider transportAuthenticationProvider, ReplicationEndpoint[] endpoints, TransportEndpointStrategyType endpointStrategyType) { int pollItems = PropertiesUtil.toInteger(config.get(POLL_ITEMS), -1); props.put(POLL_ITEMS, pollItems); return new PollingTransportHandler(pollItems, (TransportAuthenticationProvider<Executor, Executor>) transportAuthenticationProvider, endpoints); }
From source file:org.openengsb.core.services.GenericSecurePortTest.java
@Before public void setupInfrastructure() throws Exception { System.setProperty("karaf.home", dataFolder.getRoot().getAbsolutePath()); FileKeySource fileKeySource = new FileKeySource("etc/keys", "RSA"); fileKeySource.init();/*from w ww. j a v a2s . c o m*/ serverPublicKey = fileKeySource.getPublicKey(); privateKeySource = fileKeySource; requestHandler = mock(RequestHandler.class); authManager = mock(AuthenticationDomain.class); when(authManager.authenticate(anyString(), any(Credentials.class))) .thenAnswer(new Answer<Authentication>() { @Override public Authentication answer(InvocationOnMock invocation) throws Throwable { String username = (String) invocation.getArguments()[0]; Credentials credentials = (Credentials) invocation.getArguments()[1]; return new Authentication(username, credentials); } }); setupSecurityManager(); when(requestHandler.handleCall(any(MethodCall.class))).thenAnswer(new Answer<MethodResult>() { @Override public MethodResult answer(InvocationOnMock invocation) throws Throwable { MethodCall call = (MethodCall) invocation.getArguments()[0]; return new MethodResult(call.getArgs()[0], call.getMetaData()); } }); FilterChainFactory<MethodCallMessage, MethodResultMessage> factory = new FilterChainFactory<MethodCallMessage, MethodResultMessage>( MethodCallMessage.class, MethodResultMessage.class); List<Object> filterFactories = new LinkedList<Object>(); filterFactories.add(MessageVerifierFilter.class); filterFactories.add(new MessageAuthenticatorFilterFactory(new DefaultOsgiUtilsService(bundleContext), new ShiroContext())); filterFactories.add(new RequestMapperFilter(requestHandler)); factory.setFilters(filterFactories); factory.create(); filterTop = factory; secureRequestHandler = getSecureRequestHandlerFilterChain(); Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put(Constants.PROVIDED_CLASSES_KEY, Password.class.getName()); props.put(Constants.DELEGATION_CONTEXT_KEY, org.openengsb.core.api.Constants.DELEGATION_CONTEXT_CREDENTIALS); registerService(new ClassProviderImpl(bundle, Sets.newHashSet(Password.class.getName())), props, ClassProvider.class); }
From source file:org.apache.ace.authentication.processor.password.PasswordAuthenticationProcessorTest.java
/** * Tests that updated does not throw an exception for a correct configuration. *//*from w w w . jav a2 s. co m*/ @Test(groups = { UNIT }) public void testUpdatedDoesAcceptCorrectProperties() throws ConfigurationException { final String keyUsername = "foo"; final String keyPassword = "bar"; Dictionary<String, Object> props = new Hashtable<>(); props.put(PROPERTY_KEY_USERNAME, keyUsername); props.put(PROPERTY_KEY_PASSWORD, keyPassword); props.put(PROPERTY_PASSWORD_HASHMETHOD, "sha1"); PasswordAuthenticationProcessor processor = new PasswordAuthenticationProcessor(); processor.updated(props); byte[] hashedPw = DigestUtils.sha("secret"); // Test whether we can use the new properties... User user = mock(User.class); when(user.getName()).thenReturn("bob"); when(user.hasCredential(eq(keyPassword), eq(hashedPw))).thenReturn(Boolean.TRUE); when(m_userAdmin.getUser(eq(keyUsername), eq("bob"))).thenReturn(user); User result = processor.authenticate(m_userAdmin, "bob", "secret"); assert result != null : "Expected a valid user to be returned!"; assert "bob".equals(user.getName()) : "Expected bob to be returned!"; }