Example usage for org.apache.commons.configuration Configuration getBoolean

List of usage examples for org.apache.commons.configuration Configuration getBoolean

Introduction

In this page you can find the example usage for org.apache.commons.configuration Configuration getBoolean.

Prototype

Boolean getBoolean(String key, Boolean defaultValue);

Source Link

Document

Get a Boolean associated with the given configuration key.

Usage

From source file:org.roda.wui.filter.OnOffFilter.java

/**
 * Init inner filter.//from  ww w  .ja  v  a2 s  . c o m
 *
 * @throws ServletException
 *           if some error occurs.
 */
private void initInnerFilter() throws ServletException {
    final Configuration rodaConfig = RodaCoreFactory.getRodaConfiguration();
    if (rodaConfig == null) {
        LOGGER.info("RODA configuration not available yet. Delaying init of {}.",
                this.webXmlFilterConfig.getInitParameter(PARAM_INNER_FILTER_CLASS));
    } else {
        final String innerFilterClass = this.webXmlFilterConfig.getInitParameter(PARAM_INNER_FILTER_CLASS);
        final String configPrefix = this.webXmlFilterConfig.getInitParameter(PARAM_CONFIG_PREFIX);
        if (rodaConfig.getBoolean(configPrefix + ".enabled", false)) {
            try {
                this.innerFilter = (Filter) Class.forName(innerFilterClass).newInstance();
                this.innerFilter.init(getFilterConfig());
                this.isOn = true;
            } catch (final InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                this.isOn = false;
                throw new ServletException("Error instantiating inner filter - " + e.getMessage(), e);
            }
        } else {
            this.isOn = false;
        }
    }
    LOGGER.info("{} is {}", getFilterConfig().getFilterName(), (this.isOn ? "ON" : "OFF"));
}

From source file:org.seedstack.business.internal.event.EventPlugin.java

@SuppressWarnings("unchecked")
@Override/*w w w  .ja va2s .c  o m*/
public InitState init(InitContext initContext) {
    Configuration eventConfiguration = initContext.dependency(ConfigurationProvider.class).getConfiguration()
            .subset(PREFIX);

    watchRepo = eventConfiguration.getBoolean("domain.watch", false);
    Collection<Class<?>> scannedEventHandlerClasses = initContext.scannedTypesBySpecification()
            .get(eventHandlerSpecification);

    for (Class<?> scannedEventHandlerClass : scannedEventHandlerClasses) {
        if (EventHandler.class.isAssignableFrom(scannedEventHandlerClass)) {
            eventHandlerClasses.add((Class<EventHandler>) scannedEventHandlerClass);
            Class<Event> typeParameterClass = (Class<Event>) TypeResolver
                    .resolveRawArguments(EventHandler.class, (Class<EventHandler>) scannedEventHandlerClass)[0];
            eventHandlersByEvent.put(typeParameterClass, (Class<EventHandler>) scannedEventHandlerClass);
        }
    }

    return InitState.INITIALIZED;
}

From source file:org.seedstack.jms.internal.JmsFactoryImpl.java

@Override
@SuppressWarnings("unchecked")
public ConnectionDefinition createConnectionDefinition(String connectionName, Configuration configuration,
        ConnectionFactory connectionFactory) {
    // Find connection factory if not given explicitly
    if (connectionFactory == null) {
        connectionFactory = connectionFactoryMap.get(configuration.getString("connection-factory"));

        if (connectionFactory == null) {
            throw SeedException.createNew(JmsErrorCodes.MISSING_CONNECTION_FACTORY).put("connectionName",
                    connectionName);//w ww .  j a v  a 2s  .  c o m
        }
    }

    // Create exception listener
    String exceptionListenerClassName = configuration.getString("exception-listener");
    Class<? extends ExceptionListener> exceptionListener = null;
    if (StringUtils.isNotBlank(exceptionListenerClassName)) {
        try {
            exceptionListener = (Class<? extends ExceptionListener>) Class.forName(exceptionListenerClassName);
        } catch (Exception e) {
            throw new PluginException(
                    "Unable to load JMS ExceptionListener class " + exceptionListenerClassName, e);
        }
    }

    // Create exception handler
    String exceptionHandlerClassName = configuration.getString("exception-handler");
    Class<? extends JmsExceptionHandler> exceptionHandler = null;
    if (StringUtils.isNotBlank(exceptionHandlerClassName)) {
        try {
            exceptionHandler = (Class<? extends JmsExceptionHandler>) Class.forName(exceptionHandlerClassName);
        } catch (Exception e) {
            throw SeedException.wrap(e, JmsErrorCodes.UNABLE_TO_LOAD_CLASS).put("exceptionHandler",
                    exceptionHandlerClassName);
        }
    }

    boolean jeeMode = configuration.getBoolean("jee-mode", false);
    boolean shouldSetClientId = configuration.getBoolean("set-client-id", !jeeMode);

    if (jeeMode && shouldSetClientId) {
        throw SeedException.createNew(JmsErrorCodes.CANNOT_SET_CLIENT_ID_IN_JEE_MODE)
                .put(JmsPlugin.ERROR_CONNECTION_NAME, connectionName);
    }

    return new ConnectionDefinition(connectionName, connectionFactory,
            configuration.getBoolean("managed-connection", true), jeeMode, shouldSetClientId,
            configuration.getString("client-id", applicationName + "-" + connectionName),
            configuration.getString("user"), configuration.getString("password"),
            configuration.getInt("reconnection-delay", DEFAULT_RECONNECTION_DELAY), exceptionListener,
            exceptionHandler);
}

From source file:org.seedstack.mqtt.internal.MqttPluginTest.java

/**
 * Test method for//  w w w  .  j a v  a  2  s  . co m
 * {@link org.seedstack.mqtt.internal.MqttPlugin#init(io.nuun.kernel.api.plugin.context.InitContext)}
 * .
 */
@Test
public void testInitWithPoolConfiguration(@Mocked final Configuration configuration,
        @SuppressWarnings("rawtypes") @Mocked final ArrayBlockingQueue queue,
        @Mocked final ThreadPoolExecutor threadPoolExecutor) {
    final String clientName = "clientOK1";
    final String[] clients = { clientName };
    final Collection<Class<?>> classes = new ArrayList<Class<?>>();
    MqttPlugin plugin = new MqttPlugin();
    new Expectations() {
        {
            application.getConfiguration();
            result = configuration;

            configuration.subset(anyString);
            result = configuration;

            configuration.getStringArray(CONNECTION_CLIENTS);
            result = clients;

            configuration.getString(BROKER_URI);
            result = "xx";

            configuration.getBoolean(POOL_ENABLED, Boolean.TRUE);
            result = Boolean.TRUE;

            specs.get(any);
            result = classes;

        }
    };

    new MockUp<MqttClient>() {
        @Mock
        public void $init(String serverURI, String clientId) throws MqttException {
        }

    };

    plugin.init(initContext);

    ConcurrentHashMap<String, MqttClientDefinition> defs = Deencapsulation.getField(plugin,
            "mqttClientDefinitions");
    Assertions.assertThat(defs).isNotEmpty();
    MqttClientDefinition clientDef = defs.get(clientName);
    Assertions.assertThat(clientDef.getPoolDefinition()).isNotNull();
    Assertions.assertThat(clientDef.getPoolDefinition().getThreadPoolExecutor()).isNotNull();
}

From source file:org.seedstack.mqtt.internal.MqttPoolDefinition.java

public MqttPoolDefinition(Configuration configuration) {
    this.available = configuration.getBoolean(POOL_ENABLED, Boolean.TRUE);
    if (this.available) {
        int coreSize = configuration.getInt(POOL_CORE_SIZE, DEFAULT_CORE_SIZE);
        int maxSize = configuration.getInt(POOL_MAX_SIZE, DEFAULT_MAX_SIZE);
        int queueSize = configuration.getInt(POOL_QUEUE_SIZE, DEFAULT_QUEUE_SIZE);
        int keepAlive = configuration.getInt(POOL_KEEP_ALIVE, DEFAULT_KEEP_ALIVE);
        this.threadPoolExecutor = new ThreadPoolExecutor(coreSize, maxSize, keepAlive, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(queueSize));
    }/*from   ww  w  .  j a  v a 2 s . c  o  m*/
}

From source file:org.seedstack.seed.core.internal.application.ApplicationPlugin.java

@Override
public InitState init(InitContext initContext) {
    ApplicationDiagnosticCollector applicationDiagnosticCollector = new ApplicationDiagnosticCollector();
    ((CorePlugin) initContext.pluginsRequired().iterator().next())
            .registerDiagnosticCollector("org.seedstack.seed.core.application", applicationDiagnosticCollector);

    Set<String> allConfigurationResources = Sets.newHashSet();

    for (String propertiesResource : initContext.mapResourcesByRegex().get(PROPERTIES_REGEX)) {
        if (propertiesResource.startsWith(CONFIGURATION_LOCATION)) {
            allConfigurationResources.add(propertiesResource);
        }/*from   w  w  w  .ja va2s  . c o m*/
    }

    for (String propsResource : initContext.mapResourcesByRegex().get(PROPS_REGEX)) {
        if (propsResource.startsWith(CONFIGURATION_LOCATION)) {
            allConfigurationResources.add(propsResource);
        }
    }

    Map<String, Class<? extends StrLookup>> configurationLookups = new HashMap<String, Class<? extends StrLookup>>();

    for (Class<?> candidate : initContext.scannedClassesByAnnotationClass().get(ConfigurationLookup.class)) {
        ConfigurationLookup configurationLookup = candidate.getAnnotation(ConfigurationLookup.class);
        if (StrLookup.class.isAssignableFrom(candidate) && configurationLookup != null
                && !configurationLookup.value().isEmpty()) {
            configurationLookups.put(configurationLookup.value(), candidate.asSubclass(StrLookup.class));
            LOGGER.trace("Detected configuration lookup {}", configurationLookup.value());
        }
    }

    for (String configurationResource : allConfigurationResources) {
        boolean isOverrideResource = configurationResource.endsWith(".override.properties")
                || configurationResource.endsWith(".override.props");

        try {
            Enumeration<URL> urlEnumeration = classLoader.getResources(configurationResource);
            while (urlEnumeration.hasMoreElements()) {
                URL url = urlEnumeration.nextElement();
                InputStream resourceAsStream = null;

                try {
                    resourceAsStream = url.openStream();

                    if (isOverrideResource) {
                        LOGGER.debug("Adding {} to configuration override", url.toExternalForm());
                        propsOverride.load(resourceAsStream);
                    } else {
                        LOGGER.debug("Adding {} to configuration", url.toExternalForm());
                        props.load(resourceAsStream);
                    }
                } finally {
                    if (resourceAsStream != null) {
                        try { // NOSONAR
                            resourceAsStream.close();
                        } catch (IOException e) {
                            LOGGER.warn("Unable to close configuration resource " + configurationResource, e);
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw SeedException.wrap(e, ApplicationErrorCode.UNABLE_TO_LOAD_CONFIGURATION_RESOURCE)
                    .put("resource", configurationResource);
        }
    }

    // Determine configuration profile
    String[] profiles = getStringArray(System.getProperty("org.seedstack.seed.profiles"));
    if (profiles == null || profiles.length == 0) {
        LOGGER.info("No configuration profile selected");
        applicationDiagnosticCollector.setActiveProfiles("");
    } else {
        String activeProfiles = Arrays.toString(profiles);
        LOGGER.info("Active configuration profile(s): {}", activeProfiles);
        applicationDiagnosticCollector.setActiveProfiles(activeProfiles);
    }

    // Build configuration
    Configuration configuration = buildConfiguration(props, propsOverride, configurationLookups, profiles);
    applicationDiagnosticCollector.setConfiguration(configuration);
    Configuration coreConfiguration = configuration.subset(CorePlugin.CORE_PLUGIN_PREFIX);

    String appId = coreConfiguration.getString("application-id");
    if (appId == null || appId.isEmpty()) {
        throw SeedException.createNew(ApplicationErrorCode.MISSING_APPLICATION_IDENTIFIER).put("property",
                CorePlugin.CORE_PLUGIN_PREFIX + ".application-id");
    }

    String appName = coreConfiguration.getString("application-name");
    if (appName == null) {
        appName = appId;
    }

    String appVersion = coreConfiguration.getString("application-version");
    if (appVersion == null) {
        appVersion = "0.0.0";
    }

    LOGGER.info("Application info: '{}' / '{}' / '{}'", appId, appName, appVersion);
    applicationDiagnosticCollector.setApplicationId(appId);
    applicationDiagnosticCollector.setApplicationName(appName);
    applicationDiagnosticCollector.setApplicationVersion(appVersion);

    String seedStorage = coreConfiguration.getString("storage");
    File seedDirectory;
    if (seedStorage == null) {
        seedDirectory = new File(new File(getUserHome(), ".seed"), appId);
    } else {
        seedDirectory = new File(seedStorage);
    }

    if (!seedDirectory.exists() && !seedDirectory.mkdirs()) {
        throw SeedException.createNew(ApplicationErrorCode.UNABLE_TO_CREATE_STORAGE_DIRECTORY).put("path",
                seedDirectory.getAbsolutePath());
    }

    if (!seedDirectory.isDirectory()) {
        throw SeedException.createNew(ApplicationErrorCode.STORAGE_PATH_IS_NOT_A_DIRECTORY).put("path",
                seedDirectory.getAbsolutePath());
    }

    if (!seedDirectory.canWrite()) {
        throw SeedException.createNew(ApplicationErrorCode.STORAGE_DIRECTORY_IS_NOT_WRITABLE).put("path",
                seedDirectory.getAbsolutePath());
    }

    LOGGER.debug("Application storage location is {}", seedDirectory.getAbsolutePath());
    applicationDiagnosticCollector.setStorageLocation(seedDirectory.getAbsolutePath());

    if (coreConfiguration.getBoolean("redirect-jul", true)) {
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();

        LOGGER.debug(
                "Java logging to SLF4J redirection enabled, if you're using logback be sure to have a LevelChangePropagator in your configuration");
    }

    this.application = new ApplicationImpl(appName, appId, appVersion, seedDirectory, configuration);

    return InitState.INITIALIZED;
}

From source file:org.seedstack.seed.shell.internal.ShellPlugin.java

@Override
public InitState init(InitContext initContext) {
    ApplicationPlugin applicationPlugin = (ApplicationPlugin) initContext.pluginsRequired().iterator().next();
    org.apache.commons.configuration.Configuration shellConfiguration = applicationPlugin.getApplication()
            .getConfiguration().subset(ShellPlugin.SHELL_PLUGIN_CONFIGURATION_PREFIX);

    // No need to go further if shell is not enabled
    if (!shellConfiguration.getBoolean("enabled", false)) {
        LOGGER.info("Shell support is present in the classpath but not enabled");
        return InitState.INITIALIZED;
    }//  w  ww.  j  a v a  2 s.  c o m

    port = shellConfiguration.getInt("port", SHELL_DEFAULT_PORT);
    sshServer = SshServer.setUpDefaultServer();
    sshServer.setPort(port);

    String keyType = shellConfiguration.getString("key.type", "generated");
    if ("generated".equals(keyType)) {
        File storage;
        try {
            storage = applicationPlugin.getApplication().getStorageLocation("shell");
        } catch (IOException e) {
            throw new PluginException("Unable to acces storage location for context shell", e);
        }
        sshServer.setKeyPairProvider(
                new SimpleGeneratorHostKeyProvider(new File(storage, "generate-key.ser").getAbsolutePath()));
    } else if ("file".equals(keyType)) {
        sshServer.setKeyPairProvider(
                new FileKeyPairProvider(new String[] { shellConfiguration.getString("key.location") }));
    } else if ("resource".equals(keyType)) {
        sshServer.setKeyPairProvider(
                new ResourceKeyPairProvider(new String[] { shellConfiguration.getString("key.location") }));
    }
    sshServer.setShellFactory(new Factory<Command>() {
        @Override
        public Command create() {
            return shellFactory.createInteractiveShell();
        }
    });

    sshServer.setCommandFactory(new CommandFactory() {
        @Override
        public Command createCommand(String command) {
            return shellFactory.createNonInteractiveShell(command);
        }
    });

    return InitState.INITIALIZED;
}

From source file:org.seedstack.seed.web.internal.WebCorsPlugin.java

@Override
public InitState init(InitContext initContext) {
    if (this.servletContext == null) {
        LOGGER.info("No servlet context detected, web support disabled");
        return InitState.INITIALIZED;
    }//from w  w  w  . jav  a 2  s. co  m

    ApplicationPlugin applicationPlugin = (ApplicationPlugin) initContext.pluginsRequired().iterator().next();
    Configuration webConfiguration = applicationPlugin.getApplication().getConfiguration()
            .subset(WebPlugin.WEB_PLUGIN_PREFIX);

    boolean corsEnabled = webConfiguration.getBoolean("cors.enabled", false);
    Map<String, String> corsParameters = new HashMap<String, String>();
    String corsMapping;
    if (corsEnabled) {
        corsMapping = webConfiguration.getString("cors.url-mapping", "/*");

        Properties corsProperties = SeedConfigurationUtils.buildPropertiesFromConfiguration(webConfiguration,
                "cors.property");
        for (Object key : corsProperties.keySet()) {
            corsParameters.put("cors." + key.toString(), corsProperties.getProperty(key.toString()));
        }

        webCorsModule = new WebCorsModule(corsMapping, corsParameters);
        LOGGER.info("CORS support enabled on {}", corsMapping);
    }

    return InitState.INITIALIZED;
}

From source file:org.seedstack.seed.web.internal.WebPlugin.java

@SuppressWarnings("unchecked")
@Override//ww  w.j  av  a2s  .  co  m
public InitState init(InitContext initContext) {
    if (servletContext == null) {
        LOGGER.info("No servlet context detected, web support disabled");
        return InitState.INITIALIZED;
    }

    WebDiagnosticCollector webDiagnosticCollector = new WebDiagnosticCollector(servletContext);
    ApplicationPlugin applicationPlugin = null;
    for (Plugin plugin : initContext.pluginsRequired()) {
        if (plugin instanceof ApplicationPlugin) {
            applicationPlugin = (ApplicationPlugin) plugin;
        } else if (plugin instanceof CorePlugin) {
            ((CorePlugin) plugin).registerDiagnosticCollector(WEB_PLUGIN_PREFIX, webDiagnosticCollector);
        }
    }

    if (applicationPlugin == null) {
        throw SeedException.createNew(WebErrorCode.PLUGIN_NOT_FOUND).put("plugin", "application");
    }

    Configuration webConfiguration = applicationPlugin.getApplication().getConfiguration()
            .subset(WebPlugin.WEB_PLUGIN_PREFIX);
    Map<Class<? extends Annotation>, Collection<Class<?>>> scannedClassesByAnnotationClass = initContext
            .scannedClassesByAnnotationClass();

    Collection<Class<?>> list = scannedClassesByAnnotationClass.get(WebServlet.class);
    List<ConfiguredServlet> servlets = new ArrayList<ConfiguredServlet>();
    for (Class<?> candidate : list) {
        if (Servlet.class.isAssignableFrom(candidate)) {
            WebServlet annotation = candidate.getAnnotation(WebServlet.class);

            ConfiguredServlet configuredServlet = new ConfiguredServlet();
            configuredServlet.setName(annotation.name());

            Map<String, String> initParams = new HashMap<String, String>();
            for (WebInitParam initParam : annotation.initParams()) {
                initParams.put(initParam.name(), initParam.value());
            }
            configuredServlet.setInitParams(initParams);

            configuredServlet.setUrlPatterns(annotation.value());

            configuredServlet.setClazz((Class<? extends HttpServlet>) candidate);

            servlets.add(configuredServlet);
            LOGGER.debug("Serving {} with {}", Arrays.toString(configuredServlet.getUrlPatterns()),
                    configuredServlet.getClazz().getCanonicalName());
        }
    }

    List<ConfiguredFilter> filters = new ArrayList<ConfiguredFilter>();
    for (Class<?> candidate : scannedClassesByAnnotationClass.get(WebFilter.class)) {
        if (Filter.class.isAssignableFrom(candidate)) {
            WebFilter annotation = candidate.getAnnotation(WebFilter.class);

            ConfiguredFilter configuredFilter = new ConfiguredFilter();
            configuredFilter.setName(annotation.filterName());

            Map<String, String> initParams = new HashMap<String, String>();
            for (WebInitParam initParam : annotation.initParams()) {
                initParams.put(initParam.name(), initParam.value());
            }
            configuredFilter.setInitParams(initParams);

            configuredFilter.setUrlPatterns(annotation.value());

            configuredFilter.setClazz((Class<? extends Filter>) candidate);

            filters.add(configuredFilter);
            LOGGER.debug("Filtering {} through {}", Arrays.toString(configuredFilter.getUrlPatterns()),
                    configuredFilter.getClazz().getCanonicalName());
        }
    }

    boolean resourcesEnabled = webConfiguration.getBoolean("resources.enabled", true);
    String resourcesPrefix = null;
    if (resourcesEnabled) {
        resourcesPrefix = webConfiguration.getString("resources.path", "/resources");
        LOGGER.info("Static resources served on {}", resourcesPrefix);
    }

    boolean requestDiagnosticEnabled = webConfiguration.getBoolean("request-diagnostic.enabled", false);
    if (requestDiagnosticEnabled) {
        LOGGER.info("Per-request diagnostic enabled");
    }

    webModule = new WebModule(requestDiagnosticEnabled, servlets, filters, resourcesEnabled, resourcesPrefix,
            additionalModules);

    return InitState.INITIALIZED;
}

From source file:org.seedstack.seed.web.internal.WebResourceResolverImpl.java

@Inject
WebResourceResolverImpl(final Application application, final Injector injector,
        @Named("SeedWebResourcesPath") final String resourcePath) {
    Configuration configuration = application.getConfiguration();
    this.injector = injector;
    this.resourcePath = resourcePath;
    this.classpathLocation = "META-INF/resources" + resourcePath;
    this.classLoader = SeedReflectionUtils.findMostCompleteClassLoader(WebResourceResolverImpl.class);
    this.docrootLocation = resourcePath;
    this.mimetypesFileTypeMap = new MimetypesFileTypeMap();
    this.serveMinifiedResources = configuration
            .getBoolean(WebPlugin.WEB_PLUGIN_PREFIX + ".resources.minification-support", true);
    this.serveGzippedResources = configuration
            .getBoolean(WebPlugin.WEB_PLUGIN_PREFIX + ".resources.gzip-support", true);
    this.onTheFlyGzipping = configuration.getBoolean(WebPlugin.WEB_PLUGIN_PREFIX + ".resources.gzip-on-the-fly",
            true);//from ww w  . j a v  a2s. c om
}