Search in sources :

Example 6 with StrLookup

use of org.apache.commons.lang3.text.StrLookup in project tomee by apache.

the class Configuration method loadFromProperties.

public void loadFromProperties(final Properties config) {
    // filtering properties with system properties or themself
    final StrSubstitutor strSubstitutor = new StrSubstitutor(new StrLookup<String>() {

        @Override
        public String lookup(final String key) {
            final String property = System.getProperty(key);
            return property == null ? config.getProperty(key) : null;
        }
    });
    for (final String key : config.stringPropertyNames()) {
        final String val = config.getProperty(key);
        if (val == null || val.trim().isEmpty()) {
            continue;
        }
        final String newVal = strSubstitutor.replace(config.getProperty(key));
        if (!val.equals(newVal)) {
            config.setProperty(key, newVal);
        }
    }
    final String http = config.getProperty("http");
    if (http != null) {
        setHttpPort(Integer.parseInt(http));
    }
    final String https = config.getProperty("https");
    if (https != null) {
        setHttpsPort(Integer.parseInt(https));
    }
    final String stop = config.getProperty("stop");
    if (stop != null) {
        setStopPort(Integer.parseInt(stop));
    }
    final String host = config.getProperty("host");
    if (host != null) {
        setHost(host);
    }
    final String dir = config.getProperty("dir");
    if (dir != null) {
        setDir(dir);
    }
    final String serverXml = config.getProperty("serverXml");
    if (serverXml != null) {
        setServerXml(serverXml);
    }
    final String keepServerXmlAsThis = config.getProperty("keepServerXmlAsThis");
    if (keepServerXmlAsThis != null) {
        setKeepServerXmlAsThis(Boolean.parseBoolean(keepServerXmlAsThis));
    }
    final String quickSession = config.getProperty("quickSession");
    if (quickSession != null) {
        setQuickSession(Boolean.parseBoolean(quickSession));
    }
    final String skipHttp = config.getProperty("skipHttp");
    if (skipHttp != null) {
        setSkipHttp(Boolean.parseBoolean(skipHttp));
    }
    final String ssl = config.getProperty("ssl");
    if (ssl != null) {
        setSsl(Boolean.parseBoolean(ssl));
    }
    final String http2 = config.getProperty("http2");
    if (http2 != null) {
        setHttp2(Boolean.parseBoolean(http2));
    }
    final String deleteBaseOnStartup = config.getProperty("deleteBaseOnStartup");
    if (deleteBaseOnStartup != null) {
        setDeleteBaseOnStartup(Boolean.parseBoolean(deleteBaseOnStartup));
    }
    final String webResourceCached = config.getProperty("webResourceCached");
    if (webResourceCached != null) {
        setWebResourceCached(Boolean.parseBoolean(webResourceCached));
    }
    final String withEjbRemote = config.getProperty("withEjbRemote");
    if (withEjbRemote != null) {
        setWithEjbRemote(Boolean.parseBoolean(withEjbRemote));
    }
    final String deployOpenEjbApp = config.getProperty("deployOpenEjbApp");
    if (deployOpenEjbApp != null) {
        setDeployOpenEjbApp(Boolean.parseBoolean(deployOpenEjbApp));
    }
    final String keystoreFile = config.getProperty("keystoreFile");
    if (keystoreFile != null) {
        setKeystoreFile(keystoreFile);
    }
    final String keystorePass = config.getProperty("keystorePass");
    if (keystorePass != null) {
        setKeystorePass(keystorePass);
    }
    final String keystoreType = config.getProperty("keystoreType");
    if (keystoreType != null) {
        setKeystoreType(keystoreType);
    }
    final String clientAuth = config.getProperty("clientAuth");
    if (clientAuth != null) {
        setClientAuth(clientAuth);
    }
    final String keyAlias = config.getProperty("keyAlias");
    if (keyAlias != null) {
        setKeyAlias(keyAlias);
    }
    final String sslProtocol = config.getProperty("sslProtocol");
    if (sslProtocol != null) {
        setSslProtocol(sslProtocol);
    }
    final String webXml = config.getProperty("webXml");
    if (webXml != null) {
        setWebXml(webXml);
    }
    final String tempDir = config.getProperty("tempDir");
    if (tempDir != null) {
        setTempDir(tempDir);
    }
    final String customWebResources = config.getProperty("customWebResources");
    if (customWebResources != null) {
        setCustomWebResources(customWebResources);
    }
    final String classesFilterType = config.getProperty("classesFilter");
    if (classesFilterType != null) {
        try {
            setClassesFilter(Filter.class.cast(Thread.currentThread().getContextClassLoader().loadClass(classesFilterType).newInstance()));
        } catch (final InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            throw new IllegalArgumentException(e);
        }
    }
    final String conf = config.getProperty("conf");
    if (conf != null) {
        setConf(conf);
    }
    for (final String prop : config.stringPropertyNames()) {
        if (prop.startsWith("properties.")) {
            property(prop.substring("properties.".length()), config.getProperty(prop));
        } else if (prop.startsWith("users.")) {
            user(prop.substring("users.".length()), config.getProperty(prop));
        } else if (prop.startsWith("roles.")) {
            role(prop.substring("roles.".length()), config.getProperty(prop));
        } else if (prop.startsWith("connector.")) {
            // created in container
            property(prop, config.getProperty(prop));
        } else if (prop.equals("realm")) {
            final ObjectRecipe recipe = new ObjectRecipe(config.getProperty(prop));
            for (final String realmConfig : config.stringPropertyNames()) {
                if (realmConfig.startsWith("realm.")) {
                    recipe.setProperty(realmConfig.substring("realm.".length()), config.getProperty(realmConfig));
                }
            }
            setRealm(Realm.class.cast(recipe.create()));
        } else if (prop.equals("login")) {
            final ObjectRecipe recipe = new ObjectRecipe(LoginConfigBuilder.class.getName());
            for (final String nestedConfig : config.stringPropertyNames()) {
                if (nestedConfig.startsWith("login.")) {
                    recipe.setProperty(nestedConfig.substring("login.".length()), config.getProperty(nestedConfig));
                }
            }
            loginConfig(LoginConfigBuilder.class.cast(recipe.create()));
        } else if (prop.equals("securityConstraint")) {
            final ObjectRecipe recipe = new ObjectRecipe(SecurityConstaintBuilder.class.getName());
            for (final String nestedConfig : config.stringPropertyNames()) {
                if (nestedConfig.startsWith("securityConstraint.")) {
                    recipe.setProperty(nestedConfig.substring("securityConstraint.".length()), config.getProperty(nestedConfig));
                }
            }
            securityConstaint(SecurityConstaintBuilder.class.cast(recipe.create()));
        } else if (prop.equals("configurationCustomizer.")) {
            final String next = prop.substring("configurationCustomizer.".length());
            if (next.contains(".")) {
                continue;
            }
            final ObjectRecipe recipe = new ObjectRecipe(properties.getProperty(prop + ".class"));
            for (final String nestedConfig : config.stringPropertyNames()) {
                if (nestedConfig.startsWith(prop) && !prop.endsWith(".class")) {
                    recipe.setProperty(nestedConfig.substring(prop.length() + 1), config.getProperty(nestedConfig));
                }
            }
            addCustomizer(ConfigurationCustomizer.class.cast(recipe.create()));
        }
    }
}
Also used : StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) Filter(org.apache.xbean.finder.filter.Filter) Realm(org.apache.catalina.Realm)

Example 7 with StrLookup

use of org.apache.commons.lang3.text.StrLookup in project stanbol by apache.

the class KiWiRepositoryService method activate.

@Activate
protected final void activate(ComponentContext context) throws ConfigurationException, RepositoryException {
    log.info("activate KiWi repository ...");
    if (context == null || context.getProperties() == null) {
        throw new IllegalStateException("No valid" + ComponentContext.class + " parsed in activate!");
    }
    //copy the read-only configuration as we might need to change it before
    //adding it to the registered service
    final Dictionary<String, Object> config = copyConfig(context);
    final BundleContext bc = context.getBundleContext();
    //we want to substitute variables used in the dbURL with configuration, 
    //framework and system properties
    StrSubstitutor strSubstitutor = new StrSubstitutor(new StrLookup<Object>() {

        @Override
        public String lookup(String key) {
            Object val = config.get(key);
            if (val == null) {
                val = bc.getProperty(key);
            }
            return val.toString();
        }
    });
    String name = (String) config.get(REPOSITORY_ID);
    if (StringUtils.isBlank(name)) {
        throw new ConfigurationException(REPOSITORY_ID, "The parsed Repository ID MUST NOT be NULL nor blank!");
    } else {
        log.debug(" - name: {}", name);
    }
    KiWiDialect dialect;
    String db_type;
    if (StringUtils.equalsIgnoreCase("postgres", (String) config.get(DB_DIALECT))) {
        dialect = new PostgreSQLDialect();
        db_type = "postgresql";
    } else if (StringUtils.equalsIgnoreCase("mysql", (String) config.get(DB_DIALECT))) {
        dialect = new MySQLDialect();
        db_type = "mysql";
    } else if (StringUtils.equalsIgnoreCase("h2", (String) config.get(DB_DIALECT))) {
        dialect = new H2Dialect();
        db_type = "h2";
    } else {
        throw new ConfigurationException(DB_DIALECT, "No valid database dialect was given");
    }
    log.debug(" - dialect: {}", dialect);
    String db_url = (String) config.get(DB_URL);
    if (StringUtils.isBlank(db_url)) {
        //build the db url from parameters
        String db_host = (String) config.get(DB_HOST);
        if (StringUtils.isBlank(db_host)) {
            db_host = DEFAULT_DB_HOST;
        }
        log.debug(" - db host: {}", db_host);
        String db_name = (String) config.get(DB_NAME);
        if (StringUtils.isBlank(db_name)) {
            db_name = DEFAULT_DB_NAME;
        }
        log.debug(" - db name:  {}", name);
        int db_port;
        Object value = config.get(DB_PORT);
        if (value instanceof Number) {
            db_port = ((Number) value).intValue();
        } else if (value != null && !StringUtils.isBlank(value.toString())) {
            db_port = Integer.parseInt(value.toString());
        } else {
            db_port = DEFAULT_DB_PORT;
        }
        log.debug(" - db port: {}", db_port);
        String db_opts = (String) config.get(DB_OPTS);
        log.debug(" - db options: {}", db_opts);
        StringBuilder dbUrlBuilder = new StringBuilder("jdbc:").append(db_type);
        if (dialect instanceof H2Dialect) {
            //H2 uses a file path and not a host so we do not need the ://
            dbUrlBuilder.append(':').append(db_host);
        } else {
            dbUrlBuilder.append("://").append(db_host);
        }
        if (db_port > 0) {
            dbUrlBuilder.append(':').append(db_port);
        }
        if (!StringUtils.isBlank(db_name)) {
            dbUrlBuilder.append('/').append(db_name);
        }
        if (!StringUtils.isBlank(db_opts)) {
            dbUrlBuilder.append(db_opts);
        }
        dbUrl = strSubstitutor.replace(dbUrlBuilder);
    } else if (!db_url.startsWith("jdbc:")) {
        throw new ConfigurationException(DB_URL, "Database URLs are expected to start with " + "'jdbc:' (parsed: '" + db_url + "')!");
    } else {
        dbUrl = strSubstitutor.replace(db_url);
    }
    String db_user = (String) config.get(DB_USER);
    if (StringUtils.isBlank(db_user)) {
        db_user = DEFAULT_DB_USER;
    } else {
        db_user = strSubstitutor.replace(db_user);
    }
    log.debug(" - db user: {}", db_user);
    String db_pass = (String) config.get(DB_PASS);
    if (StringUtils.isBlank(db_pass)) {
        log.debug(" - db pwd is set to default");
        db_pass = DEFAULT_DB_PASS;
    } else {
        log.debug(" - db pwd is set to parsed value");
    }
    KiWiConfiguration configuration = new KiWiConfiguration("Marmotta KiWi", dbUrl, db_user, db_pass, dialect);
    //parse cluster options
    String cluster = (String) config.get(CLUSTER);
    if (!StringUtils.isBlank(cluster)) {
        log.debug(" - cluster: {}", cluster);
        configuration.setClustered(true);
        configuration.setClusterName(cluster);
        String clusterAddress = (String) config.get(CLUSTER_ADDRESS);
        if (!StringUtils.isBlank(clusterAddress)) {
            configuration.setClusterAddress(strSubstitutor.replace(clusterAddress));
        }
        log.debug(" - cluster address: {}", configuration.getClusterAddress());
        Object clusterPort = config.get(CLUSTER_PORT);
        if (clusterPort instanceof Number) {
            int port = ((Number) clusterPort).intValue();
            if (port > 0) {
                configuration.setClusterPort(port);
            }
        //else use default
        } else if (clusterPort != null) {
            try {
                int port = Integer.parseInt(strSubstitutor.replace(clusterPort));
                if (port > 0) {
                    configuration.setClusterPort(port);
                }
            } catch (NumberFormatException e) {
                throw new ConfigurationException(CLUSTER_PORT, "Unable to parse " + "Cluster Port from configured value '" + clusterPort + "'!", e);
            }
        }
        log.debug(" - cluster port ({})", configuration.getClusterPort());
        String cachingBackend = (String) config.get(CACHING_BACKEND);
        if (StringUtils.isBlank(cachingBackend)) {
            configuration.setCachingBackend(CachingBackends.valueOf(DEFAULT_CACHING_BACKEND));
        } else {
            try {
                configuration.setCachingBackend(CachingBackends.valueOf(strSubstitutor.replace(cachingBackend)));
            } catch (IllegalArgumentException e) {
                throw new ConfigurationException(CACHING_BACKEND, "Unsupported CachingBackend '" + cachingBackend + "' (supported: " + Arrays.toString(CachingBackends.values()) + ")!", e);
            }
        }
        log.debug(" - caching Backend: {}", configuration.getCachingBackend());
        String cacheMode = (String) config.get(CACHE_MODE);
        if (StringUtils.isBlank(cacheMode)) {
            cacheMode = DEFAULT_CACHE_MODE;
        }
        try {
            configuration.setCacheMode(CacheMode.valueOf(strSubstitutor.replace(cacheMode)));
        } catch (IllegalArgumentException e) {
            throw new ConfigurationException(CACHE_MODE, "Unsupported CacheMode '" + cacheMode + "' (supported: " + Arrays.toString(CacheMode.values()) + ")!");
        }
        log.debug(" - cache mode: {}", configuration.getCacheMode());
    } else {
        // not clustered
        log.debug(" - no cluster configured");
        configuration.setClustered(false);
    }
    log.info(" ... initialise KiWi repository: {}", dbUrl);
    KiWiStore store = new KiWiStore(configuration);
    repository = new SailRepository(new KiWiSparqlSail(store));
    repository.initialize();
    //set the repository type property to KiWiStore
    config.put(SAIL_IMPL, KiWiStore.class.getName());
    repoRegistration = context.getBundleContext().registerService(Repository.class.getName(), repository, config);
    log.info("  - successfully registered KiWi Repository {}", name);
}
Also used : KiWiSparqlSail(org.apache.marmotta.kiwi.sparql.sail.KiWiSparqlSail) H2Dialect(org.apache.marmotta.kiwi.persistence.h2.H2Dialect) SailRepository(org.openrdf.repository.sail.SailRepository) KiWiStore(org.apache.marmotta.kiwi.sail.KiWiStore) KiWiDialect(org.apache.marmotta.kiwi.persistence.KiWiDialect) StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor) MySQLDialect(org.apache.marmotta.kiwi.persistence.mysql.MySQLDialect) PostgreSQLDialect(org.apache.marmotta.kiwi.persistence.pgsql.PostgreSQLDialect) ConfigurationException(org.osgi.service.cm.ConfigurationException) KiWiConfiguration(org.apache.marmotta.kiwi.config.KiWiConfiguration) BundleContext(org.osgi.framework.BundleContext) Activate(org.apache.felix.scr.annotations.Activate)

Aggregations

StrSubstitutor (org.apache.commons.lang3.text.StrSubstitutor)7 StrLookup (org.apache.commons.lang3.text.StrLookup)5 Test (org.junit.Test)3 IOException (java.io.IOException)1 Realm (org.apache.catalina.Realm)1 Activate (org.apache.felix.scr.annotations.Activate)1 KiWiConfiguration (org.apache.marmotta.kiwi.config.KiWiConfiguration)1 KiWiDialect (org.apache.marmotta.kiwi.persistence.KiWiDialect)1 H2Dialect (org.apache.marmotta.kiwi.persistence.h2.H2Dialect)1 MySQLDialect (org.apache.marmotta.kiwi.persistence.mysql.MySQLDialect)1 PostgreSQLDialect (org.apache.marmotta.kiwi.persistence.pgsql.PostgreSQLDialect)1 KiWiStore (org.apache.marmotta.kiwi.sail.KiWiStore)1 KiWiSparqlSail (org.apache.marmotta.kiwi.sparql.sail.KiWiSparqlSail)1 Filter (org.apache.xbean.finder.filter.Filter)1 ObjectRecipe (org.apache.xbean.recipe.ObjectRecipe)1 SailRepository (org.openrdf.repository.sail.SailRepository)1 BundleContext (org.osgi.framework.BundleContext)1 ConfigurationException (org.osgi.service.cm.ConfigurationException)1