Example usage for org.apache.commons.configuration HierarchicalConfiguration getString

List of usage examples for org.apache.commons.configuration HierarchicalConfiguration getString

Introduction

In this page you can find the example usage for org.apache.commons.configuration HierarchicalConfiguration getString.

Prototype

public String getString(String key) 

Source Link

Usage

From source file:org.apache.james.fetchmail.FetchMail.java

/**
 * Method configure parses and validates the Configuration data and creates
 * a new <code>ParsedConfiguration</code>, an <code>Account</code> for each
 * configured static account and a/*from  w w w.j  a va2s  .  c  o  m*/
 * <code>ParsedDynamicAccountParameters</code> for each dynamic account.
 *
 * @see org.apache.james.lifecycle.api.Configurable#configure(HierarchicalConfiguration)
 */
public void configure(HierarchicalConfiguration configuration) throws ConfigurationException {
    // Set any Session parameters passed in the Configuration
    setSessionParameters(configuration);

    // Create the ParsedConfiguration used in the delegation chain
    ParsedConfiguration parsedConfiguration = new ParsedConfiguration(configuration, logger, getLocalUsers(),
            getDNSService(), getDomainList(), getMailQueue());

    setParsedConfiguration(parsedConfiguration);

    // Setup the Accounts
    List<HierarchicalConfiguration> allAccounts = configuration.configurationsAt("accounts");
    if (allAccounts.size() < 1)
        throw new ConfigurationException("Missing <accounts> section.");
    if (allAccounts.size() > 1)
        throw new ConfigurationException("Too many <accounts> sections, there must be exactly one");
    HierarchicalConfiguration accounts = allAccounts.get(0);

    if (!accounts.getKeys().hasNext())
        throw new ConfigurationException("Missing <account> section.");

    int i = 0;
    // Create an Account for every configured account
    for (ConfigurationNode accountsChild : accounts.getRoot().getChildren()) {

        String accountsChildName = accountsChild.getName();

        List<HierarchicalConfiguration> accountsChildConfig = accounts.configurationsAt(accountsChildName);
        HierarchicalConfiguration conf = accountsChildConfig.get(i);

        if ("alllocal".equals(accountsChildName)) {
            // <allLocal> is dynamic, save the parameters for accounts to
            // be created when the task is triggered
            getParsedDynamicAccountParameters().add(new ParsedDynamicAccountParameters(i, conf));
            continue;
        }

        if ("account".equals(accountsChildName)) {
            // Create an Account for the named user and
            // add it to the list of static accounts
            getStaticAccounts().add(new Account(i, parsedConfiguration, conf.getString("[@user]"),
                    conf.getString("[@password]"), conf.getString("[@recipient]"),
                    conf.getBoolean("[@ignorercpt-header]"), conf.getString("[@customrcpt-header]", ""),
                    getSession()));
            continue;
        }

        throw new ConfigurationException("Illegal token: <" + accountsChildName + "> in <accounts>");
    }
    i++;
}

From source file:org.apache.james.fetchmail.FetchMail.java

/**
 * Propagate any Session parameters in the configuration to the Session.
 *
 * @param configuration The configuration containing the parameters
 * @throws ConfigurationException//from w w  w .  j  a v a 2  s  .c o m
 */
protected void setSessionParameters(HierarchicalConfiguration configuration) {

    if (configuration.getKeys("javaMailProperties.property").hasNext()) {
        Properties properties = getSession().getProperties();
        List<HierarchicalConfiguration> allProperties = configuration
                .configurationsAt("javaMailProperties.property");
        for (HierarchicalConfiguration propConf : allProperties) {
            properties.setProperty(propConf.getString("[@name]"), propConf.getString("[@value]"));
            if (logger.isDebugEnabled()) {
                StringBuilder messageBuffer = new StringBuilder("Set property name: ");
                messageBuffer.append(propConf.getString("[@name]"));
                messageBuffer.append(" to: ");
                messageBuffer.append(propConf.getString("[@value]"));
                logger.debug(messageBuffer.toString());
            }
        }
    }
}

From source file:org.apache.james.fetchmail.ParsedConfiguration.java

protected void configure(HierarchicalConfiguration conf) throws ConfigurationException {
    setHost(conf.getString("host"));

    setFetchTaskName(conf.getString("[@name]"));
    setJavaMailProviderName(conf.getString("javaMailProviderName"));
    setJavaMailFolderName(conf.getString("javaMailFolderName"));
    setRecurse(conf.getBoolean("recursesubfolders"));

    HierarchicalConfiguration recipientNotFound = conf.configurationAt("recipientnotfound");
    setDeferRecipientNotFound(recipientNotFound.getBoolean("[@defer]"));
    setRejectRecipientNotFound(recipientNotFound.getBoolean("[@reject]"));
    setLeaveRecipientNotFound(recipientNotFound.getBoolean("[@leaveonserver]"));
    setMarkRecipientNotFoundSeen(recipientNotFound.getBoolean("[@markseen]"));
    setDefaultDomainName(conf.getString("defaultdomain", "localhost"));

    setFetchAll(conf.getBoolean("fetchall"));

    HierarchicalConfiguration fetched = conf.configurationAt("fetched");
    setLeave(fetched.getBoolean("[@leaveonserver]"));
    setMarkSeen(fetched.getBoolean("[@markseen]"));

    HierarchicalConfiguration remoterecipient = conf.configurationAt("remoterecipient");
    setRejectRemoteRecipient(remoterecipient.getBoolean("[@reject]"));
    setLeaveRemoteRecipient(remoterecipient.getBoolean("[@leaveonserver]"));
    setMarkRemoteRecipientSeen(remoterecipient.getBoolean("[@markseen]"));

    HierarchicalConfiguration blacklist = conf.configurationAt("blacklist");
    setBlacklist(conf.getString("blacklist", ""));
    setRejectBlacklisted(blacklist.getBoolean("[@reject]"));
    setLeaveBlacklisted(blacklist.getBoolean("[@leaveonserver]"));
    setMarkBlacklistedSeen(blacklist.getBoolean("[@markseen]"));

    HierarchicalConfiguration userundefined = conf.configurationAt("userundefined");
    setRejectUserUndefined(userundefined.getBoolean("[@reject]"));
    setLeaveUserUndefined(userundefined.getBoolean("[@leaveonserver]"));
    setMarkUserUndefinedSeen(userundefined.getBoolean("[@markseen]"));

    HierarchicalConfiguration undeliverable = conf.configurationAt("undeliverable");
    setLeaveUndeliverable(undeliverable.getBoolean("[@leaveonserver]"));
    setMarkUndeliverableSeen(undeliverable.getBoolean("[@markseen]"));

    if (conf.getKeys("remotereceivedheader").hasNext()) {
        HierarchicalConfiguration remotereceivedheader = conf.configurationAt("remotereceivedheader");

        setRemoteReceivedHeaderIndex(remotereceivedheader.getInt("[@index]"));
        setRejectRemoteReceivedHeaderInvalid(remotereceivedheader.getBoolean("[@reject]"));
        setLeaveRemoteReceivedHeaderInvalid(remotereceivedheader.getBoolean("[@leaveonserver]"));
        setMarkRemoteReceivedHeaderInvalidSeen(remotereceivedheader.getBoolean("[@markseen]"));
    }//from w ww .  j a  v a  2s  .c  o m

    if (conf.getKeys("maxmessagesize").hasNext()) {
        HierarchicalConfiguration maxmessagesize = conf.configurationAt("maxmessagesize");

        setMaxMessageSizeLimit(maxmessagesize.getInt("[@limit]") * 1024);
        setRejectMaxMessageSizeExceeded(maxmessagesize.getBoolean("[@reject]"));
        setLeaveMaxMessageSizeExceeded(maxmessagesize.getBoolean("[@leaveonserver]"));
        setMarkMaxMessageSizeExceededSeen(maxmessagesize.getBoolean("[@markseen]"));
    }

    if (getLogger().isDebugEnabled()) {
        getLogger().info("Configured FetchMail fetch task " + getFetchTaskName());
    }
}

From source file:org.apache.james.http.jetty.JettyHttpServerFactory.java

private Configuration buildConfiguration(HierarchicalConfiguration serverConfig) {
    Builder builder = Configuration.builder();

    boolean randomPort = serverConfig.getBoolean("port[@random]", false);
    Integer port = serverConfig.getInteger("port[@fixed]", null);
    if (randomPort && port != null) {
        throw new ConfigurationException("Random port is not compatible with fixed port");
    }// w  ww. j av a 2  s.  c  o  m
    if (randomPort) {
        builder.randomPort();
    }
    if (port != null) {
        builder.port(port);
    }
    for (HierarchicalConfiguration mapping : serverConfig.configurationsAt("mappings.mapping")) {
        String classname = mapping.getString("servlet");
        Class<? extends Servlet> servletClass = findServlet(classname);
        builder.serve(mapping.getString("path")).with(servletClass);
    }
    for (HierarchicalConfiguration mapping : serverConfig.configurationsAt("filters.mapping")) {
        String classname = mapping.getString("filter");
        Class<? extends Filter> filterClass = findFilter(classname);
        builder.filter(mapping.getString("path")).with(filterClass);
    }
    return builder.build();
}

From source file:org.apache.james.mailetcontainer.lib.AbstractStateCompositeProcessor.java

@PostConstruct
public void init() throws Exception {
    List<HierarchicalConfiguration> processorConfs = config.configurationsAt("processor");
    for (HierarchicalConfiguration processorConf : processorConfs) {
        String processorName = processorConf.getString("[@state]");

        // if the "child" processor has no jmx config we just use the one of
        // the composite
        if (!processorConf.containsKey("[@enableJmx]")) {
            processorConf.addProperty("[@enableJmx]", enableJmx);
        }//from w  ww .j ava2 s.c o m
        processors.put(processorName, createMailProcessor(processorName, processorConf));
    }

    if (enableJmx) {
        this.jmxListener = new JMXStateCompositeProcessorListener(this);
        addListener(jmxListener);
    }

    // check if all needed processors are configured
    checkProcessors();
}

From source file:org.apache.james.mailetcontainer.lib.AbstractStateMailetProcessor.java

private void parseConfiguration() throws MessagingException, ConfigurationException {

    // load composite matchers if there are any
    Map<String, Matcher> compositeMatchers = new HashMap<String, Matcher>();
    loadCompositeMatchers(getState(), compositeMatchers, config.configurationsAt("matcher"));

    final List<HierarchicalConfiguration> mailetConfs = config.configurationsAt("mailet");

    // Loop through the mailet configuration, load
    // all of the matcher and mailets, and add
    // them to the processor.
    for (HierarchicalConfiguration c : mailetConfs) {
        // We need to set this because of correctly parsing comma
        String mailetClassName = c.getString("[@class]");
        String matcherName = c.getString("[@match]", null);
        String invertedMatcherName = c.getString("[@notmatch]", null);

        Mailet mailet;//from   w w  w  .  j  av  a 2 s. co  m
        Matcher matcher;

        try {

            if (matcherName != null && invertedMatcherName != null) {
                // if no matcher is configured throw an Exception
                throw new ConfigurationException("Please configure only match or nomatch per mailet");
            } else if (matcherName != null) {
                // try to load from compositeMatchers first
                matcher = compositeMatchers.get(matcherName);
                if (matcher == null) {
                    // no composite Matcher found, try to load it via
                    // MatcherLoader
                    matcher = matcherLoader.getMatcher(createMatcherConfig(matcherName));
                }
            } else if (invertedMatcherName != null) {
                // try to load from compositeMatchers first
                // matcherName is a known null value at this state
                matcher = compositeMatchers.get(matcherName);
                if (matcher == null) {
                    // no composite Matcher found, try to load it via
                    // MatcherLoader
                    matcher = matcherLoader.getMatcher(createMatcherConfig(invertedMatcherName));
                }
                matcher = new MatcherInverter(matcher);

            } else {
                // default matcher is All
                matcher = matcherLoader.getMatcher(createMatcherConfig("All"));
            }

            // The matcher itself should log that it's been inited.
            if (logger.isInfoEnabled()) {
                String infoBuffer = "Matcher " + matcherName + " instantiated.";
                logger.info(infoBuffer.toString());
            }
        } catch (MessagingException ex) {
            // **** Do better job printing out exception
            if (logger.isErrorEnabled()) {
                String errorBuffer = "Unable to init matcher " + matcherName + ": " + ex.toString();
                logger.error(errorBuffer.toString(), ex);
                if (ex.getNextException() != null) {
                    logger.error("Caused by nested exception: ", ex.getNextException());
                }
            }
            throw new ConfigurationException("Unable to init matcher " + matcherName, ex);
        }
        try {
            mailet = mailetLoader.getMailet(createMailetConfig(mailetClassName, c));
            if (logger.isInfoEnabled()) {
                String infoBuffer = "Mailet " + mailetClassName + " instantiated.";
                logger.info(infoBuffer.toString());
            }
        } catch (MessagingException ex) {
            // **** Do better job printing out exception
            if (logger.isErrorEnabled()) {
                String errorBuffer = "Unable to init mailet " + mailetClassName + ": " + ex.toString();
                logger.error(errorBuffer.toString(), ex);
                if (ex.getNextException() != null) {
                    logger.error("Caused by nested exception: ", ex.getNextException());
                }
            }
            throw new ConfigurationException("Unable to init mailet " + mailetClassName, ex);
        }

        if (matcher != null && mailet != null) {
            pairs.add(new MatcherMailetPair(matcher, mailet));
        } else {
            throw new ConfigurationException("Unable to load Mailet or Matcher");
        }
    }
}

From source file:org.apache.james.mailrepository.file.FileMailRepository.java

@Override
protected void doConfigure(HierarchicalConfiguration config)
        throws org.apache.commons.configuration.ConfigurationException {
    super.doConfigure(config);
    destination = config.getString("[@destinationURL]");
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("FileMailRepository.destinationURL: " + destination);
    }//from  w w w  . jav  a  2 s .  c om
    fifo = config.getBoolean("[@FIFO]", false);
    cacheKeys = config.getBoolean("[@CACHEKEYS]", true);
    // ignore model
}

From source file:org.apache.james.mailrepository.file.MBoxMailRepository.java

public void configure(HierarchicalConfiguration configuration) throws ConfigurationException {
    /*//from   w w  w . j a v  a  2s.  c  o m
    The repository configuration
    */
    String destination;
    this.mList = null;
    BUFFERING = configuration.getBoolean("[@BUFFERING]", true);
    fifo = configuration.getBoolean("[@FIFO]", false);
    destination = configuration.getString("[@destinationURL]");
    if (destination.charAt(destination.length() - 1) == '/') {
        // Remove the trailing / as well as the protocol marker
        mboxFile = destination.substring("mbox://".length(), destination.lastIndexOf("/"));
    } else {
        mboxFile = destination.substring("mbox://".length());
    }

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("MBoxMailRepository.destinationURL: " + destination);
    }

    String checkType = configuration.getString("[@type]");
    if (!(checkType.equals("MAIL") || checkType.equals("SPOOL"))) {
        String exceptionString = "Attempt to configure MboxMailRepository as " + checkType;
        if (getLogger().isWarnEnabled()) {
            getLogger().warn(exceptionString);
        }
        throw new ConfigurationException(exceptionString);
    }
}

From source file:org.apache.james.mailrepository.jdbc.JDBCMailRepository.java

protected void doConfigure(HierarchicalConfiguration configuration) throws ConfigurationException {
    super.doConfigure(configuration);
    if (getLogger().isDebugEnabled()) {
        getLogger().debug(this.getClass().getName() + ".configure()");
    }/* ww  w  . ja  v  a 2  s .c  om*/
    destination = configuration.getString("[@destinationURL]");

    // normalize the destination, to simplify processing.
    if (!destination.endsWith("/")) {
        destination += "/";
    }
    // Parse the DestinationURL for the name of the datasource,
    // the table to use, and the (optional) repository Key.
    // Split on "/", starting after "db://"
    List<String> urlParams = new ArrayList<String>();
    int start = 5;
    if (destination.startsWith("dbfile")) {
        // this is dbfile:// instead of db://
        start += 4;
    }
    int end = destination.indexOf('/', start);
    while (end > -1) {
        urlParams.add(destination.substring(start, end));
        start = end + 1;
        end = destination.indexOf('/', start);
    }

    // Build SqlParameters and get datasource name from URL parameters
    if (urlParams.size() == 0) {
        String exceptionBuffer = "Malformed destinationURL - Must be of the format '"
                + "db://<data-source>[/<table>[/<repositoryName>]]'.  Was passed "
                + configuration.getString("[@destinationURL]");
        throw new ConfigurationException(exceptionBuffer);
    }
    if (urlParams.size() >= 1) {
        datasourceName = urlParams.get(0);
    }
    if (urlParams.size() >= 2) {
        tableName = urlParams.get(1);
    }
    if (urlParams.size() >= 3) {
        repositoryName = "";
        for (int i = 2; i < urlParams.size(); i++) {
            if (i >= 3) {
                repositoryName += '/';
            }
            repositoryName += urlParams.get(i);
        }
    }

    if (getLogger().isDebugEnabled()) {
        String logBuffer = "Parsed URL: table = '" + tableName + "', repositoryName = '" + repositoryName + "'";
        getLogger().debug(logBuffer);
    }

    inMemorySizeLimit = configuration.getInt("inMemorySizeLimit", 409600000);

    filestore = configuration.getString("filestore", null);
    sqlFileName = configuration.getString("sqlFile");

}

From source file:org.apache.james.mailrepository.memory.MemoryMailRepositoryStore.java

private void readConfigurationEntry(HierarchicalConfiguration repositoryConfiguration)
        throws ConfigurationException {
    String className = repositoryConfiguration.getString("[@class]");
    MailRepositoryProvider usedMailRepository = mailRepositories.stream()
            .filter(mailRepositoryProvider -> mailRepositoryProvider.canonicalName().equals(className))
            .findAny().orElseThrow(() -> new ConfigurationException(
                    "MailRepository " + className + " has not been registered"));
    for (String protocol : repositoryConfiguration.getStringArray("protocols.protocol")) {
        protocolToRepositoryProvider.put(new Protocol(protocol), usedMailRepository);
        registerRepositoryDefaultConfiguration(repositoryConfiguration, new Protocol(protocol));
    }/*ww  w .  j  a v  a2  s.  c o  m*/
}