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.eclipse.virgo.ide.bundlor.internal.core.BundlorProjectBuilder.java

/**
 * Generate a new or update the existing manifest.
 *
 * @throws IOException// www .  j  ava2  s  .c o m
 */
private BundleManifest generateManifest(IJavaProject javaProject, ReadablePartialManifest model,
        ManifestGenerator generator, Set<IResource> resources, boolean isFullBuild, boolean isTestManifest)
        throws JavaModelException, CoreException, IOException {

    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

    Set<String> folders = getSourceFolders(javaProject, root, isTestManifest);

    // Removed deleted resources
    for (IResource deletedResource : isTestManifest ? this.deletedTestResources : this.deletedSourceResources) {
        String path = deletedResource.getRawLocation().toString();
        for (String folder : folders) {
            if (path.startsWith(folder)) {
                path = path.substring(folder.length() + 1);
                if (model instanceof EntryScannerListener) {
                    ((EntryScannerListener) model).onBeginEntry(path);
                }
                ((EntryScannerListener) model).onEndEntry();
            }
        }
    }

    IResource templateResource = getProject().findMember("template.mf");

    ManifestContents templateManifest = createManifestFromPath(templateResource);

    // Test-Import-Package and Test-Import-Bundle -> Import-Package and
    // Import-Bundle
    if (isTestManifest) {
        templateManifest.getMainAttributes().remove(Constants.IMPORT_PACKAGE);
        templateManifest.getMainAttributes().remove(IHeaderConstants.IMPORT_BUNDLE);
        templateManifest.getMainAttributes().remove(IHeaderConstants.IMPORT_LIBRARY);

        if (templateManifest.getMainAttributes().containsKey(IHeaderConstants.TEST_IMPORT_BUNDLE)) {
            templateManifest.getMainAttributes().put(IHeaderConstants.IMPORT_BUNDLE,
                    templateManifest.getMainAttributes().get(IHeaderConstants.TEST_IMPORT_BUNDLE));
        }
        if (templateManifest.getMainAttributes().containsKey(IHeaderConstants.TEST_IMPORT_PACKAGE)) {
            templateManifest.getMainAttributes().put(Constants.IMPORT_PACKAGE,
                    templateManifest.getMainAttributes().get(IHeaderConstants.TEST_IMPORT_PACKAGE));
        }
        if (templateManifest.getMainAttributes().containsKey(IHeaderConstants.TEST_IMPORT_LIBRARY)) {
            templateManifest.getMainAttributes().put(IHeaderConstants.IMPORT_LIBRARY,
                    templateManifest.getMainAttributes().get(IHeaderConstants.TEST_IMPORT_LIBRARY));
        }
    } else {
        String importPackageHeader = templateManifest.getMainAttributes().get(Constants.IMPORT_PACKAGE);
        Dictionary<String, String> contents = new Hashtable<String, String>();
        if (importPackageHeader != null) {
            contents.put(Constants.IMPORT_PACKAGE, importPackageHeader);
        }
        this.templatePackageImports.addAll(
                BundleManifestFactory.createBundleManifest(contents).getImportPackage().getImportedPackages());
    }

    ManifestContents manifest = null;
    List<ClassPath> classpathEntries = new ArrayList<ClassPath>();
    StandardClassPathFactory factory = new StandardClassPathFactory();
    if (isFullBuild) {
        for (String folder : folders) {
            classpathEntries.add(factory.create(folder));
        }
    } else {
        for (String folder : folders) {
            classpathEntries.add(new FilteringClassPath(resources, folder));
        }
    }

    manifest = generator.generate(templateManifest,
            classpathEntries.toArray(new ClassPath[classpathEntries.size()]));
    return org.eclipse.virgo.bundlor.util.BundleManifestUtils.createBundleManifest(manifest);
}

From source file:net.solarnetwork.node.settings.ca.CASettingsService.java

@Override
public String addProviderFactoryInstance(String factoryUID) {
    synchronized (factories) {
        List<KeyValuePair> instanceKeys = settingDao.getSettings(getFactorySettingKey(factoryUID));
        int next = instanceKeys.size() + 1;
        // verify key doesn't exist
        boolean done = false;
        while (!done) {
            done = true;/*from w w w .j  a va  2 s . c  om*/
            for (KeyValuePair instanceKey : instanceKeys) {
                if (instanceKey.getKey().equals(String.valueOf(next))) {
                    done = false;
                    next++;
                }
            }
        }
        String newInstanceKey = String.valueOf(next);
        settingDao.storeSetting(getFactorySettingKey(factoryUID), newInstanceKey, newInstanceKey);
        try {
            Configuration conf = getConfiguration(factoryUID, newInstanceKey);
            @SuppressWarnings("unchecked")
            Dictionary<String, Object> props = conf.getProperties();
            if (props == null) {
                props = new Hashtable<String, Object>();
            }
            props.put(OSGI_PROPERTY_KEY_FACTORY_INSTANCE_KEY, newInstanceKey);
            conf.update(props);
            return newInstanceKey;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InvalidSyntaxException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:de.tum.in.bluetooth.discovery.BluetoothDeviceDiscovery.java

/**
 * Used to register a service per device discovered
 *
 * @param device// w w w . j  a v  a2  s . c  o m
 *            The found device
 */
private synchronized void register(RemoteDevice device) {
    final Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put("device.id", device.getBluetoothAddress());
    final String name = this.getDeviceName(device);

    if (name != null) {
        // Switch device to our own implementation
        device = new RemoteNamedDevice(device, name);
        props.put("device.name", name);
    } else if (this.m_ignoreUnnamedDevices) {
        LOGGER.warn("Ignoring device " + device.getBluetoothAddress() + " - discovery set to ignore "
                + "unnamed devices");
        return;
    }

    LOGGER.info("Registering new service for " + device.getBluetoothAddress() + " with properties " + props);

    // check autopairing
    if (!device.isAuthenticated()) {
        if (!this.pair(device)) {
            LOGGER.warn("Aborting registering for " + device.getBluetoothAddress());
            return;
        }
    }

    final ServiceRegistration<?> reg = this.m_context.registerService(RemoteDevice.class.getName(), device,
            props);
    this.m_devices.put(device, reg);

}

From source file:org.codice.ddf.ui.admin.api.ConfigurationAdmin.java

public Map<String, Object> enableConfiguration(String servicePid) throws IOException {
    if (StringUtils.isEmpty(servicePid)) {
        throw new IOException(
                "Service PID of Source to be disabled must be specified.  Service PID provided: " + servicePid);
    }/*from w w w  .  j ava  2s . c  o  m*/

    Configuration disabledConfig = configurationAdminExt.getConfiguration(servicePid);

    if (disabledConfig == null) {
        throw new IOException("No Source exists with the service PID: " + servicePid);
    }

    Dictionary<String, Object> properties = disabledConfig.getProperties();
    String disabledFactoryPid = (String) properties
            .get(org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID);
    if (!StringUtils.endsWith(disabledFactoryPid, DISABLED)) {
        throw new IOException("Source is already enabled.");
    }

    String enabledFactoryPid = StringUtils.removeEnd(disabledFactoryPid, DISABLED);
    properties.put(org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID, enabledFactoryPid);
    Configuration enabledConfiguration = configurationAdmin.createFactoryConfiguration(enabledFactoryPid, null);
    enabledConfiguration.update(properties);

    disabledConfig.delete();

    Map<String, Object> rval = new HashMap<>();
    rval.put(ORIGINAL_PID, servicePid);
    rval.put(ORIGINAL_FACTORY_PID, disabledFactoryPid);
    rval.put(NEW_PID, enabledConfiguration.getPid());
    rval.put(NEW_FACTORY_PID, enabledFactoryPid);
    return rval;
}

From source file:org.forgerock.openidm.provisioner.openicf.impl.OpenICFProvisionerServiceTest.java

@BeforeClass
public void setUp() throws Exception {
    // Start OpenICF Connector Server
    String openicfServerPort = IdentityServer.getInstance().getProperty("openicfServerPort", "8759");
    int port = 8759;// Integer.getInteger(openicfServerPort);
    System.setProperty(Log.LOGSPI_PROP, NoOpLogger.class.getName());

    connectorServer = new ConnectorServerImpl();
    connectorServer.setPort(port);/* ww w  . ja v a  2s  .com*/

    File root = new File(OpenICFProvisionerService.class.getResource("/").toURI());

    List<URL> bundleURLs = new ArrayList<URL>();

    File[] connectors = (new File(root, "/connectors/")).listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar");
        }
    });

    assertThat(connectors).isNotNull().overridingErrorMessage("You must copy the connectors first");

    for (File connector : connectors) {
        bundleURLs.add(connector.toURI().toURL());
    }

    // No Connectors were found!
    assertThat(bundleURLs.isEmpty()).isFalse();

    connectorServer.setBundleURLs(bundleURLs);
    connectorServer.setKeyHash("xOS4IeeE6eb/AhMbhxZEC37PgtE=");
    connectorServer.setIfAddress(InetAddress.getByName("127.0.0.1"));
    connectorServer.start();

    // Start ConnectorInfoProvider Service
    Dictionary<String, Object> properties = new Hashtable<String, Object>(3);
    properties.put(JSONEnhancedConfig.JSON_CONFIG_PROPERTY, CONFIGURATION_TEMPLATE);
    // mocking
    ComponentContext context = mock(ComponentContext.class);
    // stubbing
    when(context.getProperties()).thenReturn(properties);

    provider = Pair.of(new ConnectorInfoProviderService(), context);
    provider.getLeft().connectorFrameworkFactory = new ConnectorFrameworkFactory();
    provider.getLeft().bindEnhancedConfig(new JSONEnhancedConfig());
    provider.getLeft().activate(context);

    File[] configJsons = (new File(root, "/config/")).listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.startsWith("provisioner.openicf-");
        }
    });

    assertThat(configJsons).isNotNull().overridingErrorMessage("You must copy the configurations first");

    for (final File configJson : configJsons) {
        // Start OpenICFProvisionerService Service
        properties = new Hashtable<String, Object>(3);
        // properties.put(ComponentConstants.COMPONENT_ID, 42);
        // properties.put(ComponentConstants.COMPONENT_NAME,
        // getClass().getCanonicalName());
        properties.put(JSONEnhancedConfig.JSON_CONFIG_PROPERTY, FileUtil.readFile(configJson));

        context = mock(ComponentContext.class);
        // stubbing
        when(context.getProperties()).thenReturn(properties);

        OpenICFProvisionerService service = new OpenICFProvisionerService();

        service.bindConnectorInfoProvider(provider.getLeft());
        service.bindRouterRegistry(this);
        service.bindSyncFailureHandlerFactory(this);
        service.bindEnhancedConfig(new JSONEnhancedConfig());
        service.bindConnectionFactory(
                new IDMConnectionFactoryWrapper(Resources.newInternalConnectionFactory(router)));

        //set as NullActivityLogger to be the mock logger.
        service.setActivityLogger(NullActivityLogger.INSTANCE);

        // Attempt to activate the provisioner service up to 4 times, using ConnectorFacade#test to
        // validate proper initialization.  If the connector info manager is not be initialized, the
        // test fails because the connector cannot connect to the remote server.  In this test, it 
        // manifests as a timing issue owing to the flexibility in the provisioner service and the 
        // connector info provider supporting the ability for the connector server to come and go, as
        // managed by the health check thread (see ConnectorInfoProviderService#initialiseRemoteManager).
        // The test simply executes too fast for the health check thread to complete setup of the
        // connector info manager.
        for (int count = 0; count < 4; count++) {
            service.activate(context);
            try {
                service.getConnectorFacade().test();
                break;
            } catch (Exception e) {
                Thread.sleep(1000);
            }
        }

        systems.add(Pair.of(service, context));
    }
    // bind SystemObjectSetService dependencies in closure as the bind methods
    // are protected
    SystemObjectSetService systemObjectSetService = new SystemObjectSetService() {
        {
            bindConnectionFactory(
                    new IDMConnectionFactoryWrapper(Resources.newInternalConnectionFactory(router)));
            for (Pair<OpenICFProvisionerService, ComponentContext> pair : systems) {
                bindProvisionerService(pair.getLeft(), (Map) null);
            }
        }
    };

    router.addRoute(uriTemplate("system"), systemObjectSetService);

    connection = Resources.newInternalConnection(router);
}

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

@Test
public void testAllRegistryInfo() throws Exception {
    List<Service> metatypes = new ArrayList<>();
    List<Configuration> configurations = new ArrayList<>();
    Dictionary<String, Object> props = new Hashtable<>();
    Dictionary<String, Object> propsDisabled = new Hashtable<>();

    metatypes.add(new ServiceImpl());

    props.put("key1", "value1");
    propsDisabled.put("key2", "value2");

    Configuration config = mock(Configuration.class);
    configurations.add(config);//w w  w  . ja va2 s. co m
    when(config.getPid()).thenReturn("myPid");
    when(config.getFactoryPid()).thenReturn("myFpid");
    when(config.getProperties()).thenReturn(props);

    Configuration configDisabled = mock(Configuration.class);
    configurations.add(configDisabled);
    when(configDisabled.getPid()).thenReturn("myPid_disabled");
    when(configDisabled.getFactoryPid()).thenReturn("myFpid_disabled");
    when(configDisabled.getProperties()).thenReturn(propsDisabled);

    when(helper.getMetatypes()).thenReturn(metatypes);
    when(helper.getConfigurations(any(Service.class))).thenReturn(configurations);
    when(helper.getName(any(Configuration.class))).thenReturn("name");
    when(helper.getBundleName(any(Configuration.class))).thenReturn("bundleName");
    when(helper.getBundleId(any(Configuration.class))).thenReturn(1234L);

    List<Service> updatedMetatypes = federationAdmin.allRegistryInfo();
    assertThat(updatedMetatypes.size(), is(1));
    ArrayList<Map<String, Object>> configs = (ArrayList<Map<String, Object>>) updatedMetatypes.get(0)
            .get("configurations");
    assertThat(configs.size(), is(2));
    Map<String, Object> activeConfig = configs.get(0);
    Map<String, Object> disabledConfig = configs.get(1);
    assertThat(activeConfig.get("name"), equalTo("name"));
    assertThat(activeConfig.get("id"), equalTo("myPid"));
    assertThat(activeConfig.get("fpid"), equalTo("myFpid"));
    assertThat(activeConfig.get("enabled"), equalTo(true));
    assertThat(((Map<String, Object>) activeConfig.get("properties")).get("key1"), equalTo("value1"));

    assertThat(disabledConfig.get("name"), equalTo("myPid_disabled"));
    assertThat(disabledConfig.get("id"), equalTo("myPid_disabled"));
    assertThat(disabledConfig.get("fpid"), equalTo("myFpid_disabled"));
    assertThat(disabledConfig.get("enabled"), equalTo(false));
    assertThat(((Map<String, Object>) disabledConfig.get("properties")).get("key2"), equalTo("value2"));
}

From source file:org.jahia.bundles.extender.jahiamodules.Activator.java

/**
 * Registers the transformation services.
 *
 * @param context the OSGi bundle context object
 *//*from  w  ww.  j a v a 2s .c o m*/
private void registerUrlTransformers(BundleContext context) throws IOException {

    // register protocol handlers
    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(URLConstants.URL_HANDLER_PROTOCOL, URL_PROTOCOL_DX);
    props.put(Constants.SERVICE_DESCRIPTION,
            "URL stream protocol handler for DX modules that handles bundle storage and dependencies between modules");
    props.put(Constants.SERVICE_VENDOR, Jahia.VENDOR_NAME);
    serviceRegistrations
            .add(context.registerService(URLStreamHandlerService.class, new DxModuleURLStreamHandler(), props));
    props = new Hashtable<String, Object>();
    props.put(URLConstants.URL_HANDLER_PROTOCOL, URL_PROTOCOL_MODULE_DEPENDENCIES);
    props.put(Constants.SERVICE_DESCRIPTION,
            "URL stream protocol handler for DX modules that handles dependencies between them using OSGi capabilities");
    props.put(Constants.SERVICE_VENDOR, Jahia.VENDOR_NAME);
    serviceRegistrations.add(context.registerService(URLStreamHandlerService.class,
            new ModuleDependencyURLStreamHandler(), props));

    // register artifact listener and URL transformer
    props = new Hashtable<String, Object>();
    props.put(Constants.SERVICE_DESCRIPTION,
            "Artifact listener to perist the underlying bundle and transform its URL");
    props.put(Constants.SERVICE_VENDOR, Jahia.VENDOR_NAME);
    serviceRegistrations.add(context.registerService(
            new String[] { ArtifactUrlTransformer.class.getName(), ArtifactListener.class.getName() },
            new ModuleUrlTransformer(), null));
}

From source file:org.forgerock.openidm.repo.jdbc.impl.JDBCRepoService.java

/**
 * Initializes the JDBC Repository Service with the supplied configuration
 * // w ww  .  j a  v  a  2s  . c o  m
 * @param config            the configuration object
 * @param bundleContext     the bundle context
 * @throws InvalidException
 */
void init(JsonValue config, BundleContext bundleContext) throws InvalidException {
    try {
        String enabled = config.get("enabled").asString();
        if ("false".equals(enabled)) {
            logger.debug("JDBC repository not enabled");
            throw new RuntimeException("JDBC repository not enabled.");
        }

        JsonValue connectionConfig = config.get(CONFIG_CONNECTION).isNull() ? config
                : config.get(CONFIG_CONNECTION);

        maxTxRetry = connectionConfig.get("maxTxRetry").defaultTo(5).asInteger().intValue();

        // Data Source configuration
        jndiName = connectionConfig.get(CONFIG_JNDI_NAME).asString();
        String jtaName = connectionConfig.get(CONFIG_JTA_NAME).asString();
        if (jndiName != null && jndiName.trim().length() > 0) {
            // Get DB connection via JNDI
            logger.info("Using DB connection configured via Driver Manager");
            InitialContext ctx = null;
            try {
                ctx = new InitialContext();
            } catch (NamingException ex) {
                logger.warn("Getting JNDI initial context failed: " + ex.getMessage(), ex);
            }
            if (ctx == null) {
                throw new InvalidException(
                        "Current platform context does not support lookup of repository DB via JNDI. "
                                + " Configure DB initialization via direct " + CONFIG_DB_DRIVER
                                + " configuration instead.");
            }

            useDataSource = true;
            ds = (DataSource) ctx.lookup(jndiName); // e.g. "java:comp/env/jdbc/MySQLDB"
        } else if (!StringUtils.isBlank(jtaName)) {
            // e.g. osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/openidm)
            OsgiName lookupName = OsgiName.parse(jtaName);
            Object service = ServiceUtil.getService(bundleContext, lookupName, null, true);
            if (service instanceof DataSource) {
                useDataSource = true;
                ds = (DataSource) service;
            } else {
                throw new RuntimeException("DataSource can not be retrieved for: " + jtaName);
            }
        } else {
            // Get DB Connection via Driver Manager
            dbDriver = connectionConfig.get(CONFIG_DB_DRIVER).asString();
            if (dbDriver == null || dbDriver.trim().length() == 0) {
                throw new InvalidException(
                        "Either a JNDI name (" + CONFIG_JNDI_NAME + "), " + "or a DB driver lookup ("
                                + CONFIG_DB_DRIVER + ") needs to be configured to connect to a DB.");
            }
            dbUrl = connectionConfig.get(CONFIG_DB_URL).required().asString();
            user = connectionConfig.get(CONFIG_USER).required().asString();
            password = connectionConfig.get(CONFIG_PASSWORD).defaultTo("").asString();
            logger.info("Using DB connection configured via Driver Manager with Driver {} and URL", dbDriver,
                    dbUrl);
            try {
                Class.forName(dbDriver);
            } catch (ClassNotFoundException ex) {
                logger.error("Could not find configured database driver " + dbDriver + " to start repository ",
                        ex);
                throw new InvalidException(
                        "Could not find configured database driver " + dbDriver + " to start repository ", ex);
            }
            Boolean enableConnectionPool = connectionConfig.get("enableConnectionPool").defaultTo(Boolean.FALSE)
                    .asBoolean();
            if (null == sharedDataSource) {
                Dictionary<String, String> serviceParams = new Hashtable<String, String>(1);
                serviceParams.put("osgi.jndi.service.name", "jdbc/openidm");
                sharedDataSource = bundleContext.registerService(DataSource.class.getName(),
                        DataSourceFactory.newInstance(connectionConfig), serviceParams);
            }
            if (enableConnectionPool) {
                ds = DataSourceFactory.newInstance(connectionConfig);
                useDataSource = true;
                logger.info("DataSource connection pool enabled.");
            } else {
                logger.info("No DataSource connection pool enabled.");
            }
        }

        // Table handling configuration
        String dbSchemaName = connectionConfig.get(CONFIG_DB_SCHEMA).defaultTo(null).asString();
        JsonValue genericQueries = config.get("queries").get("genericTables");
        int maxBatchSize = connectionConfig.get(CONFIG_MAX_BATCH_SIZE).defaultTo(100).asInteger();

        tableHandlers = new HashMap<String, TableHandler>();
        //TODO Make safe the database type detection
        DatabaseType databaseType = DatabaseType.valueOf(
                connectionConfig.get(CONFIG_DB_TYPE).defaultTo(DatabaseType.ANSI_SQL99.name()).asString());

        JsonValue defaultMapping = config.get("resourceMapping").get("default");
        if (!defaultMapping.isNull()) {
            defaultTableHandler = getGenericTableHandler(databaseType, defaultMapping, dbSchemaName,
                    genericQueries, maxBatchSize);
            logger.debug("Using default table handler: {}", defaultTableHandler);
        } else {
            logger.warn("No default table handler configured");
        }

        // Default the configuration table for bootstrap
        JsonValue defaultTableProps = new JsonValue(new HashMap());
        defaultTableProps.put("mainTable", "configobjects");
        defaultTableProps.put("propertiesTable", "configobjectproperties");
        defaultTableProps.put("searchableDefault", Boolean.FALSE);
        GenericTableHandler defaultConfigHandler = getGenericTableHandler(databaseType, defaultTableProps,
                dbSchemaName, genericQueries, 1);
        tableHandlers.put("config", defaultConfigHandler);

        JsonValue genericMapping = config.get("resourceMapping").get("genericMapping");
        if (!genericMapping.isNull()) {
            for (String key : genericMapping.keys()) {
                JsonValue value = genericMapping.get(key);
                if (key.endsWith("/*")) {
                    // For matching purposes strip the wildcard at the end
                    key = key.substring(0, key.length() - 1);
                }
                TableHandler handler = getGenericTableHandler(databaseType, value, dbSchemaName, genericQueries,
                        maxBatchSize);

                tableHandlers.put(key, handler);
                logger.debug("For pattern {} added handler: {}", key, handler);
            }
        }

        JsonValue explicitQueries = config.get("queries").get("explicitTables");
        JsonValue explicitMapping = config.get("resourceMapping").get("explicitMapping");
        if (!explicitMapping.isNull()) {
            for (Object keyObj : explicitMapping.keys()) {
                JsonValue value = explicitMapping.get((String) keyObj);
                String key = (String) keyObj;
                if (key.endsWith("/*")) {
                    // For matching purposes strip the wildcard at the end
                    key = key.substring(0, key.length() - 1);
                }
                TableHandler handler = getMappedTableHandler(databaseType, value,
                        value.get("table").required().asString(),
                        value.get("objectToColumn").required().asMap(), dbSchemaName, explicitQueries,
                        maxBatchSize);

                tableHandlers.put(key, handler);
                logger.debug("For pattern {} added handler: {}", key, handler);
            }
        }

    } catch (RuntimeException ex) {
        logger.warn("Configuration invalid, can not start JDBC repository.", ex);
        throw new InvalidException("Configuration invalid, can not start JDBC repository.", ex);
    } catch (NamingException ex) {
        throw new InvalidException("Could not find configured jndiName " + jndiName + " to start repository ",
                ex);
    } catch (InternalServerErrorException ex) {
        throw new InvalidException("Could not initialize mapped table handler, can not start JDBC repository.",
                ex);
    }

    Connection testConn = null;
    try {
        // Check if we can get a connection
        testConn = getConnection();
        testConn.setAutoCommit(true); // Ensure we do not implicitly start transaction isolation
    } catch (Exception ex) {
        logger.warn("JDBC Repository start-up experienced a failure getting a DB connection: " + ex.getMessage()
                + ". If this is not temporary or resolved, Repository operation will be affected.", ex);
    } finally {
        if (testConn != null) {
            try {
                testConn.close();
            } catch (SQLException ex) {
                logger.warn("Failure during test connection close ", ex);
            }
        }
    }
}

From source file:com.adobe.acs.commons.errorpagehandler.impl.ErrorPageHandlerImpl.java

@SuppressWarnings("squid:S1149")
private void configure(ComponentContext componentContext) {
    Dictionary<?, ?> config = componentContext.getProperties();
    final String legacyPrefix = "prop.";

    this.enabled = PropertiesUtil.toBoolean(config.get(PROP_ENABLED),
            PropertiesUtil.toBoolean(config.get(legacyPrefix + PROP_ENABLED), DEFAULT_ENABLED));

    this.vanityDispatchCheckEnabled = PropertiesUtil.toBoolean(config.get(PROP_VANITY_DISPATCH_ENABLED),
            PropertiesUtil.toBoolean(config.get(legacyPrefix + PROP_VANITY_DISPATCH_ENABLED),
                    DEFAULT_VANITY_DISPATCH_ENABLED));

    /** Error Pages **/

    this.systemErrorPagePath = PropertiesUtil.toString(config.get(PROP_ERROR_PAGE_PATH), PropertiesUtil
            .toString(config.get(legacyPrefix + PROP_ERROR_PAGE_PATH), DEFAULT_SYSTEM_ERROR_PAGE_PATH_DEFAULT));

    this.errorPageExtension = PropertiesUtil.toString(config.get(PROP_ERROR_PAGE_EXTENSION), PropertiesUtil
            .toString(config.get(legacyPrefix + PROP_ERROR_PAGE_EXTENSION), DEFAULT_ERROR_PAGE_EXTENSION));

    this.fallbackErrorName = PropertiesUtil.toString(config.get(PROP_FALLBACK_ERROR_NAME), PropertiesUtil
            .toString(config.get(legacyPrefix + PROP_FALLBACK_ERROR_NAME), DEFAULT_FALLBACK_ERROR_NAME));

    this.pathMap = configurePathMap(PropertiesUtil.toStringArray(config.get(PROP_SEARCH_PATHS),
            PropertiesUtil.toStringArray(config.get(legacyPrefix + PROP_SEARCH_PATHS), DEFAULT_SEARCH_PATHS)));

    /** Not Found Handling **/
    this.notFoundBehavior = PropertiesUtil.toString(config.get(PROP_NOT_FOUND_DEFAULT_BEHAVIOR),
            DEFAULT_NOT_FOUND_DEFAULT_BEHAVIOR);

    String[] tmpNotFoundExclusionPatterns = PropertiesUtil.toStringArray(
            config.get(PROP_NOT_FOUND_EXCLUSION_PATH_PATTERNS), DEFAULT_NOT_FOUND_EXCLUSION_PATH_PATTERNS);

    this.notFoundExclusionPatterns = new ArrayList<Pattern>();
    for (final String tmpPattern : tmpNotFoundExclusionPatterns) {
        this.notFoundExclusionPatterns.add(Pattern.compile(tmpPattern));
    }/*w  ww.  j av  a  2s .  c o m*/

    /** Error Page Cache **/

    int ttl = PropertiesUtil.toInteger(config.get(PROP_TTL),
            PropertiesUtil.toInteger(LEGACY_PROP_TTL, DEFAULT_TTL));

    boolean serveAuthenticatedFromCache = PropertiesUtil
            .toBoolean(config.get(PROP_SERVE_AUTHENTICATED_FROM_CACHE), PropertiesUtil.toBoolean(
                    LEGACY_PROP_SERVE_AUTHENTICATED_FROM_CACHE, DEFAULT_SERVE_AUTHENTICATED_FROM_CACHE));
    try {
        cache = new ErrorPageCacheImpl(ttl, serveAuthenticatedFromCache);

        Dictionary<String, Object> serviceProps = new Hashtable<String, Object>();
        serviceProps.put("jmx.objectname", "com.adobe.acs.commons:type=ErrorPageHandlerCache");

        cacheRegistration = componentContext.getBundleContext().registerService(DynamicMBean.class.getName(),
                cache, serviceProps);
    } catch (NotCompliantMBeanException e) {
        log.error("Unable to create cache", e);
    }

    /** Error Images **/

    this.errorImagesEnabled = PropertiesUtil.toBoolean(config.get(PROP_ERROR_IMAGES_ENABLED),
            DEFAULT_ERROR_IMAGES_ENABLED);

    this.errorImagePath = PropertiesUtil.toString(config.get(PROP_ERROR_IMAGE_PATH), DEFAULT_ERROR_IMAGE_PATH);

    // Absolute path
    if (StringUtils.startsWith(this.errorImagePath, "/")) {
        ResourceResolver serviceResourceResolver = null;
        try {
            Map<String, Object> authInfo = Collections.singletonMap(ResourceResolverFactory.SUBSERVICE,
                    (Object) SERVICE_NAME);
            serviceResourceResolver = resourceResolverFactory.getServiceResourceResolver(authInfo);
            final Resource resource = serviceResourceResolver.resolve(this.errorImagePath);

            if (resource != null && resource.isResourceType(JcrConstants.NT_FILE)) {
                final PathInfo pathInfo = new PathInfo(this.errorImagePath);

                if (!StringUtils.equals("img", pathInfo.getSelectorString())
                        || StringUtils.isBlank(pathInfo.getExtension())) {

                    log.warn("Absolute Error Image Path paths to nt:files should have '.img.XXX' "
                            + "selector.extension");
                }
            }
        } catch (LoginException e) {
            log.error("Could not get admin resource resolver to inspect validity of absolute errorImagePath");
        } finally {
            if (serviceResourceResolver != null) {
                serviceResourceResolver.close();
            }
        }
    }

    this.errorImageExtensions = PropertiesUtil.toStringArray(config.get(PROP_ERROR_IMAGE_EXTENSIONS),
            DEFAULT_ERROR_IMAGE_EXTENSIONS);

    for (int i = 0; i < errorImageExtensions.length; i++) {
        this.errorImageExtensions[i] = StringUtils.lowerCase(errorImageExtensions[i], Locale.ENGLISH);
    }

    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);

    pw.println();
    pw.printf("Enabled: %s", this.enabled).println();
    pw.printf("System Error Page Path: %s", this.systemErrorPagePath).println();
    pw.printf("Error Page Extension: %s", this.errorPageExtension).println();
    pw.printf("Fallback Error Page Name: %s", this.fallbackErrorName).println();

    pw.printf("Resource Not Found - Behavior: %s", this.notFoundBehavior).println();
    pw.printf("Resource Not Found - Exclusion Path Patterns %s", Arrays.toString(tmpNotFoundExclusionPatterns))
            .println();

    pw.printf("Cache - TTL: %s", ttl).println();
    pw.printf("Cache - Serve Authenticated: %s", serveAuthenticatedFromCache).println();

    pw.printf("Error Images - Enabled: %s", this.errorImagesEnabled).println();
    pw.printf("Error Images - Path: %s", this.errorImagePath).println();
    pw.printf("Error Images - Extensions: %s", Arrays.toString(this.errorImageExtensions)).println();

    log.debug(sw.toString());
}

From source file:org.codice.ddf.ui.admin.api.ConfigurationAdminTest.java

/**
 * Tests the {@link ConfigurationAdmin#disableConfiguration(String)} method
 * for the case where the source is already disabled
 *
 * @throws Exception/*www  .j  a v  a 2 s  .  c o m*/
 */
@Test(expected = Exception.class)
public void testDisableConfigurationsAlreadyDisabled() throws Exception {
    org.osgi.service.cm.ConfigurationAdmin testConfigAdmin = mock(org.osgi.service.cm.ConfigurationAdmin.class);
    ConfigurationAdmin configAdmin = new ConfigurationAdmin(testConfigAdmin);

    Configuration testConfig = mock(Configuration.class);
    Configuration testFactoryConfig = mock(Configuration.class);
    Dictionary<String, Object> testProperties = new Hashtable<>();

    testProperties.put(org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID, TEST_FACT_PID_DISABLED);

    when(testConfigAdmin.listConfigurations('(' + Constants.SERVICE_PID + '=' + TEST_PID + ')'))
            .thenReturn(new Configuration[] { testConfig });
    when(testConfig.getProperties()).thenReturn(testProperties);
    when(testFactoryConfig.getPid()).thenReturn(TEST_FACT_PID_DISABLED);

    configAdmin.disableConfiguration(TEST_PID);
}