Java Code Examples for org.apache.commons.configuration2.HierarchicalConfiguration#getString()

The following examples show how to use org.apache.commons.configuration2.HierarchicalConfiguration#getString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GlobalRepoUpgradeOperation.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void doInit(final HierarchicalConfiguration<ImmutableNode> config) {
    overwrite = config.getBoolean(CONFIG_KEY_OVERWRITE, true);
    List<HierarchicalConfiguration<ImmutableNode>> fileMappings = config.configurationsAt(CONFIG_KEY_FILES);
    for (HierarchicalConfiguration<ImmutableNode> fileMapping : fileMappings) {
        String src = fileMapping.getString(CONFIG_KEY_SRC);
        String dest = fileMapping.getString(CONFIG_KEY_DEST);

        if (StringUtils.isEmpty(src)) {
            throw new IllegalStateException("'" + CONFIG_KEY_SRC + "' config key not specified");
        }
        if (StringUtils.isEmpty(dest)) {
            throw new IllegalStateException("'" + CONFIG_KEY_DEST + "' config key not specified");
        }

        files.put(loadResource(src), dest);
    }
}
 
Example 2
Source File: ConfigurationScriptJobResolver.java    From engine with GNU General Public License v3.0 6 votes vote down vote up
protected List<JobContext> getJobsUnderFolder(SiteContext siteContext, HierarchicalConfiguration jobFolderConfig) {
    List<JobContext> jobContexts = null;
    String folderPath = jobFolderConfig.getString(PATH_KEY);
    String cronExpression = jobFolderConfig.getString(CRON_EXPRESSION_KEY);
    ContentStoreService storeService = siteContext.getStoreService();
    Context context = siteContext.getContext();

    if (StringUtils.isNotEmpty(folderPath) && StringUtils.isNotEmpty(cronExpression)) {
        List<String> scriptPaths = ContentStoreUtils.findChildrenUrl(storeService, context, folderPath);
        if (CollectionUtils.isNotEmpty(scriptPaths)) {
            for (String scriptPath : scriptPaths) {
                if (scriptPath.endsWith(scriptSuffix)) {
                    if (jobContexts == null) {
                        jobContexts = new ArrayList<>();
                    }

                    jobContexts.add(SchedulingUtils.createJobContext(siteContext, scriptPath, cronExpression,
                                                                     disableVariableRestrictions? servletContext : null));
                }
            }
        }
    }

    return jobContexts;
}
 
Example 3
Source File: HttpProxyFilter.java    From engine with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("rawtypes, unchecked")
protected String getTargetUrl(SiteContext siteContext, String requestUri) {
    HierarchicalConfiguration proxyConfig = siteContext.getProxyConfig();

    if (proxyConfig == null) {
        throw new HttpProxyException("No proxy configuration found for site " + siteContext.getSiteName());
    }

    List<HierarchicalConfiguration> servers = proxyConfig.configurationsAt(CONFIG_KEY_SERVERS);
    for (HierarchicalConfiguration server : servers) {
        List<String> patterns = server.getList(String.class, CONFIG_KEY_PATTERNS);
        if (RegexUtils.matchesAny(requestUri, patterns)) {
            logger.debug("Found matching server {} for proxy request {}",
                    server.getString(CONFIG_KEY_ID), requestUri);
            return server.getString(CONFIG_KEY_URL);
        }
    }

    // should never happen (unless there is an issue with the config)
    throw new IllegalStateException("Invalid proxy configuration for site " + siteContext.getSiteName() +
            ", no matching server found for request " + requestUri);
}
 
Example 4
Source File: ConfigAwareAccessTokenIdResolver.java    From engine with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String getAccessTokenId() {
    String accessTokenId = null;
    HierarchicalConfiguration config = ConfigUtils.getCurrentConfig();

    if (config != null) {
        accessTokenId = config.getString(ACCESS_TOKEN_ID_KEY);
    }

    if (StringUtils.isNotEmpty(accessTokenId)) {
        return accessTokenId;
    } else {
        throw new ConfigurationException("Current config for site '" + SiteContext.getCurrent().getSiteName() +
                                        "' doesn't contain required property " + ACCESS_TOKEN_ID_KEY);
    }
}
 
Example 5
Source File: AbstractStateMailetProcessor.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(HierarchicalConfiguration<ImmutableNode> config) throws ConfigurationException {
    this.state = config.getString("[@state]", null);
    if (state == null) {
        throw new ConfigurationException("Processor state attribute must be configured");
    }
    if (state.equals(Mail.GHOST)) {
        throw new ConfigurationException("Processor state of " + Mail.GHOST + " is reserved for internal use, choose a different one");
    }

    this.enableJmx = config.getBoolean("[@enableJmx]", true);
    this.config = config;

}
 
Example 6
Source File: AbstractContentTypeUpgradeOperation.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void doInit(final HierarchicalConfiguration<ImmutableNode> config) {
    super.doInit(config);
    includedContentTypes = config.getList(String.class, CONFIG_KEY_CONTENT_TYPES);
    formDefinitionXpath = config.getString(CONFIG_KEY_FORM_DEFINITION);
    int maxCacheItems = config.getInt(CONFIG_KEY_MAX_ITEMS, DEFAULT_MAX_ITEMS);
    cache = CacheBuilder
        .newBuilder()
        .maximumSize(maxCacheItems)
        .build();
}
 
Example 7
Source File: ConfigAwareAuthenticationSuccessHandler.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected String determineTargetUrl(final HttpServletRequest request, final HttpServletResponse response) {
    HierarchicalConfiguration config = ConfigUtils.getCurrentConfig();
    if (config != null) {
        return config.getString(LOGIN_DEFAULT_SUCCESS_URL_KEY, super.determineTargetUrl(request, response));
    }
    return super.determineTargetUrl(request, response);
}
 
Example 8
Source File: IndexerConfigurationBeanFactoryPostProcessor.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    ConfigurationProvider confProvider = beanFactory.getBean(ConfigurationProvider.class);
    try {
        HierarchicalConfiguration<ImmutableNode> config = confProvider.getConfiguration("indexer");
        String provider = config.getString("provider", "lazyIndex");

        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        String indexer = null;
        String reIndexer = null;
        if (provider.equalsIgnoreCase("lazyIndex")) {
            indexer = "lazyIndex";
            reIndexer = "fake-reindexer";
        } else if (provider.equalsIgnoreCase("elasticsearch")) {
            indexer = "elasticsearch-listener";
            reIndexer = "reindexer-impl";
        } else if (provider.equalsIgnoreCase("luceneIndex")) {
            indexer = "luceneIndex";
            reIndexer = "fake-reindexer";
        }

        if (indexer == null) {
            throw new ConfigurationException("Indexer provider " + provider + " not supported!");
        }
        registry.registerAlias(indexer, "indexer");
        registry.registerAlias(reIndexer, "reindexer");

    } catch (ConfigurationException e) {
        throw new FatalBeanException("Unable to config the indexer", e);
    }

}
 
Example 9
Source File: FacebookConnectionFactoryConfigParser.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ConnectionFactory<Facebook> parse(HierarchicalConfiguration config) throws ConfigurationException {
    String appId = config.getString(FACEBOOK_CONNECTION_FACTORY_APP_ID_KEY);
    String appSecret = config.getString(FACEBOOK_CONNECTION_FACTORY_APP_SECRET_KEY);

    if (StringUtils.isNotEmpty(appId) && StringUtils.isNotEmpty(appSecret)) {
        return createFacebookConnectionFactory(appId, appSecret);
    } else {
        return null;
    }
}
 
Example 10
Source File: AbstractHeadersAuthenticationFilter.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
protected String getTokenExpectedValue() {
    HierarchicalConfiguration config = ConfigUtils.getCurrentConfig();
    if (config != null && config.containsKey(HEADERS_TOKEN_CONFIG_KEY)) {
        return config.getString(HEADERS_TOKEN_CONFIG_KEY);
    }
    return defaultTokenValue;
}
 
Example 11
Source File: ReadOnlyLDAPGroupRestriction.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * Initialises an instance from the contents of a
 * <code>&lt;restriction&gt;<code> configuration XML
 * element.
 *
 * @param configuration The avalon configuration instance that encapsulates the
 *                      contents of the <code>&lt;restriction&gt;<code> XML element.
 * @throws org.apache.commons.configuration2.ex.ConfigurationException
 *          If an error occurs extracting values from the configuration
 *          element.
 */
public ReadOnlyLDAPGroupRestriction(HierarchicalConfiguration<ImmutableNode> configuration) {
    groupDNs = new ArrayList<>();

    if (configuration != null) {
        memberAttribute = configuration.getString("[@memberAttribute]");

        if (configuration.getKeys("group").hasNext()) {
            Collections.addAll(groupDNs, configuration.getStringArray("group"));
        }
    }
}
 
Example 12
Source File: ConfigAwareAccessDeniedHandler.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
public String getErrorPage() {
    HierarchicalConfiguration siteConfig = ConfigUtils.getCurrentConfig();
    if (siteConfig != null && siteConfig.containsKey(ACCESS_DENIED_ERROR_PAGE_URL_KEY)) {
        return siteConfig.getString(ACCESS_DENIED_ERROR_PAGE_URL_KEY);
    }
    return null;
}
 
Example 13
Source File: AbstractUpgradeOperation.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void init(final String sourceVersion, final String targetVersion,
                 final HierarchicalConfiguration<ImmutableNode> config) throws UpgradeException {
    this.currentVersion = sourceVersion;
    this.nextVersion = targetVersion;
    this.commitDetails = config.getString(CONFIG_KEY_COMMIT_DETAILS);

    try {
        doInit(config);
    } catch (ConfigurationException e) {
        throw new UpgradeException("Error initializing operation", e);
    }
}
 
Example 14
Source File: ConfigAwareSecurityMetadataSource.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Collection<ConfigAttribute> getAttributes(final Object object) throws IllegalArgumentException {
    Callback<SecurityMetadataSource> callback = () -> {
        HierarchicalConfiguration siteConfig = ConfigUtils.getCurrentConfig();
        if (siteConfig != null) {
            List<HierarchicalConfiguration> restrictionsConfig = siteConfig.configurationsAt(URL_RESTRICTION_KEY);
            if (CollectionUtils.isNotEmpty(restrictionsConfig)) {
                LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> map = new LinkedHashMap<>();
                for (HierarchicalConfiguration restrictionConfig : restrictionsConfig) {
                    String url = restrictionConfig.getString(URL_RESTRICTION_URL_KEY);
                    String expression = restrictionConfig.getString(URL_RESTRICTION_EXPRESSION_KEY);
                    if (StringUtils.isNotEmpty(url) && StringUtils.isNotEmpty(expression)) {
                        AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
                        map.put(matcher, singleton(new SecurityConfig(expression)));
                    }
                }
                return new ExpressionBasedFilterInvocationSecurityMetadataSource(map,
                    new DefaultWebSecurityExpressionHandler());
            }
        }
        return new DefaultFilterInvocationSecurityMetadataSource(new LinkedHashMap<>());
    };

    SiteContext siteContext = SiteContext.getCurrent();
    if (siteContext != null) {
        SecurityMetadataSource metadataSource =
            cacheTemplate.getObject(siteContext.getContext(), callback, URL_RESTRICTIONS_CACHE_KEY);

        return metadataSource.getAttributes(object);
    }
    return null;
}
 
Example 15
Source File: ScriptFilter.java    From engine with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected List<FilterMapping> getFilterMappings() {
    final SiteContext siteContext = SiteContext.getCurrent();
    if (siteContext != null) {
        Callback<List<FilterMapping>> callback = new Callback<List<FilterMapping>>() {

            @Override
            public List<FilterMapping> execute() {
                HierarchicalConfiguration config = ConfigUtils.getCurrentConfig();
                CachingAwareList<FilterMapping> mappings = new CachingAwareList<>();

                if (config != null) {
                    List<HierarchicalConfiguration> filtersConfig = config.configurationsAt(FILTER_KEY);
                    if (CollectionUtils.isNotEmpty(filtersConfig)) {
                        for (HierarchicalConfiguration filterConfig : filtersConfig) {
                            String scriptUrl = filterConfig.getString(SCRIPT_KEY);
                            String[] includes = filterConfig.getStringArray(INCLUDE_MAPPINGS_KEY);
                            String[] excludes = filterConfig.getStringArray(EXCLUDE_MAPPINGS_KEY);

                            if (StringUtils.isNotEmpty(scriptUrl) && ArrayUtils.isNotEmpty(includes)) {
                                ContentStoreService storeService = siteContext.getStoreService();
                                ScriptFactory scriptFactory = siteContext.getScriptFactory();

                                if (!storeService.exists(siteContext.getContext(), scriptUrl)) {
                                    throw new ConfigurationException("No filter script found at " + scriptUrl);
                                }

                                FilterMapping mapping = new FilterMapping();
                                mapping.script = scriptFactory.getScript(scriptUrl);
                                mapping.includes = includes;
                                mapping.excludes = excludes;

                                mappings.add(mapping);
                            }
                        }
                    }
                }

                return mappings;
            }

        };

        return cacheTemplate.getObject(siteContext.getContext(), callback, FILTER_MAPPINGS_CACHE_KEY);
    } else {
        return null;
    }
}
 
Example 16
Source File: ClusterNodeRegistrationImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
public void init() {
    logger.debug("Autoregister cluster if cluster node is configured");
    HierarchicalConfiguration<ImmutableNode> registrationData = getConfiguration();
    ClusterMember clusterMember = new ClusterMember();
    if (registrationData != null && !registrationData.isEmpty()) {
        try {
            logger.debug("Collect and populate data for cluster node registration");
            clusterMember.setLocalAddress(registrationData.getString(CLUSTER_MEMBER_LOCAL_ADDRESS));
            if (!isRegistered(clusterMember.getLocalAddress())) {
                Path path = Paths.get(studioConfiguration.getProperty(REPO_BASE_PATH),
                                      studioConfiguration.getProperty(SITES_REPOS_PATH));
                String authenticationType = registrationData.getString(CLUSTER_MEMBER_AUTHENTICATION_TYPE);
                String username = registrationData.getString(CLUSTER_MEMBER_USERNAME);
                String password = registrationData.getString(CLUSTER_MEMBER_PASSWORD);
                String token = registrationData.getString(CLUSTER_MEMBER_TOKEN);
                String privateKey = registrationData.getString(CLUSTER_MEMBER_PRIVATE_KEY);
                String gitUrl = studioConfiguration.getProperty(CLUSTERING_SYNC_URL_FORMAT);
                if (StringUtils.isEmpty(username)) {
                    gitUrl = gitUrl.replace("{username}@", "");
                } else {
                    gitUrl = gitUrl.replace("{username}", username);
                }
                gitUrl = gitUrl.replace("{localAddress}", clusterMember.getLocalAddress())
                               .replace("{absolutePath}", path.toAbsolutePath().normalize().toString())
                         + "/{siteId}";
                clusterMember.setGitUrl(gitUrl);
                clusterMember.setState(ClusterMember.State.ACTIVE);
                clusterMember.setGitRemoteName(getGitRemoteName(clusterMember));
                clusterMember.setGitAuthType(authenticationType.toLowerCase());
                clusterMember.setGitUsername(username);
                TextEncryptor encryptor = null;
                encryptor = new PbkAesTextEncryptor(studioConfiguration.getProperty(SECURITY_CIPHER_KEY),
                                                    studioConfiguration.getProperty(SECURITY_CIPHER_SALT));
                if (StringUtils.isEmpty(password)) {
                    clusterMember.setGitPassword(password);
                } else {
                    String hashedPassword = encryptor.encrypt(password);
                    clusterMember.setGitPassword(hashedPassword);
                }

                if (StringUtils.isEmpty(token)) {
                    clusterMember.setGitToken(token);
                } else {
                    String hashedToken = encryptor.encrypt(token);
                    clusterMember.setGitToken(hashedToken);
                }

                if (StringUtils.isEmpty(privateKey)) {
                    clusterMember.setGitPrivateKey(privateKey);
                } else {
                    String hashedPrivateKey = encryptor.encrypt(privateKey);
                    clusterMember.setGitPrivateKey(hashedPrivateKey);
                }

                logger.debug("Register cluster member");
                registerClusterNode(clusterMember);
            }
        } catch (CryptoException e) {
            logger.error("Failed to register cluster member");
        }
    }
}
 
Example 17
Source File: SMTPServer.java    From james-project with Apache License 2.0 4 votes vote down vote up
@Override
public void doConfigure(HierarchicalConfiguration<ImmutableNode> configuration) throws ConfigurationException {
    super.doConfigure(configuration);
    if (isEnabled()) {
        String authRequiredString = configuration.getString("authRequired", "false").trim().toLowerCase(Locale.US);
        if (authRequiredString.equals("true")) {
            authRequired = AUTH_REQUIRED;
        } else if (authRequiredString.equals("announce")) {
            authRequired = AUTH_ANNOUNCE;
        } else {
            authRequired = AUTH_DISABLED;
        }
        if (authRequired != AUTH_DISABLED) {
            LOGGER.info("This SMTP server requires authentication.");
        } else {
            LOGGER.info("This SMTP server does not require authentication.");
        }

        authorizedAddresses = configuration.getString("authorizedAddresses", null);
        if (authRequired == AUTH_DISABLED && authorizedAddresses == null) {
            /*
             * if SMTP AUTH is not required then we will use
             * authorizedAddresses to determine whether or not to relay
             * e-mail. Therefore if SMTP AUTH is not required, we will not
             * relay e-mail unless the sending IP address is authorized.
             * 
             * Since this is a change in behavior for James v2, create a
             * default authorizedAddresses network of 0.0.0.0/0, which
             * matches all possible addresses, thus preserving the current
             * behavior.
             * 
             * James v3 should require the <authorizedAddresses> element.
             */
            authorizedAddresses = "0.0.0.0/0.0.0.0";
        }

      
        if (authorizedNetworks != null) {
            LOGGER.info("Authorized addresses: {}", authorizedNetworks);
        }

        // get the message size limit from the conf file and multiply
        // by 1024, to put it in bytes
        maxMessageSize = configuration.getLong("maxmessagesize", maxMessageSize) * 1024;
        if (maxMessageSize > 0) {
            LOGGER.info("The maximum allowed message size is {} bytes.", maxMessageSize);
        } else {
            LOGGER.info("No maximum message size is enforced for this server.");
        }

        heloEhloEnforcement = configuration.getBoolean("heloEhloEnforcement", true);

        if (authRequiredString.equals("true")) {
            authRequired = AUTH_REQUIRED;
        }

        // get the smtpGreeting
        smtpGreeting = configuration.getString("smtpGreeting", null);

        addressBracketsEnforcement = configuration.getBoolean("addressBracketsEnforcement", true);

        verifyIdentity = configuration.getBoolean("verifyIdentity", true);

    }
}
 
Example 18
Source File: LdapRepositoryConfiguration.java    From james-project with Apache License 2.0 4 votes vote down vote up
public static LdapRepositoryConfiguration from(HierarchicalConfiguration<ImmutableNode> configuration) throws ConfigurationException {
    String ldapHost = configuration.getString("[@ldapHost]", "");
    String principal = configuration.getString("[@principal]", "");
    String credentials = configuration.getString("[@credentials]", "");
    String userBase = configuration.getString("[@userBase]");
    String userIdAttribute = configuration.getString("[@userIdAttribute]");
    String userObjectClass = configuration.getString("[@userObjectClass]");
    // Default is to use connection pooling
    boolean useConnectionPool = configuration.getBoolean("[@useConnectionPool]", USE_CONNECTION_POOL);
    int connectionTimeout = configuration.getInt("[@connectionTimeout]", NO_CONNECTION_TIMEOUT);
    int readTimeout = configuration.getInt("[@readTimeout]", NO_READ_TIME_OUT);
    // Default maximum retries is 1, which allows an alternate connection to
    // be found in a multi-homed environment
    int maxRetries = configuration.getInt("[@maxRetries]", 1);
    boolean supportsVirtualHosting = configuration.getBoolean(SUPPORTS_VIRTUAL_HOSTING, !ENABLE_VIRTUAL_HOSTING);
    // Default retry start interval is 0 second
    long retryStartInterval = configuration.getLong("[@retryStartInterval]", 0);
    // Default maximum retry interval is 60 seconds
    long retryMaxInterval = configuration.getLong("[@retryMaxInterval]", 60);
    int scale = configuration.getInt("[@retryIntervalScale]", 1000); // seconds

    HierarchicalConfiguration<ImmutableNode> restrictionConfig = null;
    // Check if we have a restriction we can use
    // See JAMES-1204
    if (configuration.containsKey("restriction[@memberAttribute]")) {
        restrictionConfig = configuration.configurationAt("restriction");
    }
    ReadOnlyLDAPGroupRestriction restriction = new ReadOnlyLDAPGroupRestriction(restrictionConfig);

    //see if there is a filter argument
    String filter = configuration.getString("[@filter]");

    Optional<String> administratorId = Optional.ofNullable(configuration.getString("[@administratorId]"));

    return new LdapRepositoryConfiguration(
        ldapHost,
        principal,
        credentials,
        userBase,
        userIdAttribute,
        userObjectClass,
        useConnectionPool,
        connectionTimeout,
        readTimeout,
        maxRetries,
        supportsVirtualHosting,
        retryStartInterval,
        retryMaxInterval,
        scale,
        restriction,
        filter,
        administratorId);
}
 
Example 19
Source File: SiteAwareCORSFilter.java    From engine with GNU General Public License v3.0 4 votes vote down vote up
protected String getValue(String key, String defaultValue) {
    SiteContext siteContext = SiteContext.getCurrent();
    HierarchicalConfiguration corsConfig = siteContext.getConfig().configurationAt(CONFIG_KEY);
    return corsConfig.getString(key, defaultValue);
}
 
Example 20
Source File: DbScriptUpgradeOperation.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void doInit(final HierarchicalConfiguration<ImmutableNode> config) {
    fileName = config.getString(CONFIG_KEY_FILENAME);
    updateIntegrity = config.getBoolean(CONFIG_KEY_INTEGRITY, true);
}