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

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

Introduction

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

Prototype

Configuration subset(String prefix);

Source Link

Document

Return a decorator Configuration containing every key from the current Configuration that starts with the specified prefix.

Usage

From source file:net.sf.jclal.classifier.MulanClassifier.java

/**
 *
 * @param configuration The configuration of Mulan classifier.
 *
 *The XML labels supported are:/*from w w w.jav a 2  s  . c o  m*/
 *
 * <ul>
 * <li>
 * <b>classifier type= class</b>
 * <p>
 * Package:
 * </p>
 * mulan.classifier
 * <p>
 * Class: All
 * </p>
 * If the defined classifier is instance of
 * mulan.classifier.transformation, then a base-classifier must be
 * configured
 * <ul>
 * <li>
 * <b>base-classifier type= class</b>
 * All weka classifier are supported
 * </li>
 * </ul>
 * </li>
 * </ul>
 */
@Override
public void configure(Configuration configuration) {

    String classifierError = "classifier type= ";
    try {
        // classifier classname
        String classifierClassname = configuration.getString("classifier[@type]");
        classifierError += classifierClassname;
        // classifier class
        Class<? extends MultiLabelLearnerBase> classifierClass = (Class<? extends MultiLabelLearnerBase>) Class
                .forName(classifierClassname);

        MultiLabelLearnerBase multiLabelClassifier = null;

        // If the multi label learner is a problem transformation method
        // then a base classifier must be configured
        if (TransformationBasedMultiLabelLearner.class.isAssignableFrom(classifierClass)) {

            String baseError = "base-classifier type= ";
            try {

                Configuration conf = configuration.subset("classifier");

                // classifier classname
                String baseClassifier = conf.getString("base-classifier[@type]");
                baseError += baseClassifier;
                // classifier class
                Class<? extends Classifier> baseClassifierClass = (Class<? extends Classifier>) Class
                        .forName(baseClassifier);

                // classifier instance
                Classifier baseClassifierInstance = baseClassifierClass.newInstance();

                multiLabelClassifier = classifierClass.getConstructor(new Class<?>[] { Classifier.class })
                        .newInstance(baseClassifierInstance);

            } catch (IllegalArgumentException e) {
                throw new ConfigurationRuntimeException("\nIllegal base classifier: " + baseError, e);
            } catch (InvocationTargetException e) {
                throw new ConfigurationRuntimeException("\nIllegal base classifier: " + baseError, e);
            } catch (SecurityException e) {
                throw new ConfigurationRuntimeException("\nIllegal base classifier: " + baseError, e);
            } catch (NoSuchMethodException ex) {
                Logger.getLogger(MulanClassifier.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {
            multiLabelClassifier = classifierClass.newInstance();
        }
        // Add this classifier
        setClassifier(multiLabelClassifier);

    } catch (ClassNotFoundException e) {
        throw new ConfigurationRuntimeException("\nIllegal classifier classname: " + classifierError, e);
    } catch (InstantiationException e) {
        throw new ConfigurationRuntimeException("\nIllegal classifier classname: " + classifierError, e);
    } catch (IllegalAccessException e) {
        throw new ConfigurationRuntimeException("\nIllegal classifier classname: " + classifierError, e);
    }
}

From source file:com.knowbout.epg.processor.Parser.java

@SuppressWarnings("unchecked")

public Parser(Configuration config, File headendFile, File lineupFile, File stationFile, File programFile,
        File scheduleFile) {/*from  www .  ja va 2s .  c  o  m*/
    this.headendFile = headendFile;
    this.lineupFile = lineupFile;
    this.stationFile = stationFile;
    this.programFile = programFile;
    this.scheduleFile = scheduleFile;
    this.config = config;
    //Get the transaction count.  This can affect the performance a lot
    Configuration transactions = config.subset("transactions");
    headendTransaction = transactions.getInt("headends");
    lineupTransaction = transactions.getInt("lineups");
    stationTransaction = transactions.getInt("stations");
    programTransaction = transactions.getInt("programs");
    stationNames = new HashMap<String, String>();
    List<String> names = config.getList("stationNames.station", new ArrayList<String>());
    List<String> callSigns = config.getList("stationNames.station[@callSign]", new ArrayList<String>());
    for (int i = 0; i < callSigns.size() && i < names.size(); i++) {
        stationNames.put(callSigns.get(i), names.get(i));
    }
}

From source file:net.sf.jclal.activelearning.querystrategy.AbstractQueryStrategy.java

/**
 *
 * @param configuration The configuration object for the Abstract query
 * strategy./*w w w . j  ava 2s.  co m*/
 *The XML labels supported are:
 * <ul>
 * <li>
 * <b>maximal= boolean</b>
 * </li>
 * <li>
 * <b>wrapper-classifier type= class</b>
 * <p>
 * Package: net.sf.jclal.classifier</p>
 * <p>
 * Class: All
 * </p>
 * </li>
 * </ul>
 */
@Override
public void configure(Configuration configuration) {

    // Set max iteration
    boolean maximalT = configuration.getBoolean("maximal", isMaximal());
    setMaximal(maximalT);

    String wrapperError = "wrapper-classifier type= ";
    try {
        // classifier classname
        String classifierClassname = configuration.getString("wrapper-classifier[@type]");

        wrapperError += classifierClassname;
        // classifier class
        Class<? extends IClassifier> classifierClass = (Class<? extends IClassifier>) Class
                .forName(classifierClassname);
        // classifier instance
        IClassifier classifierTemp = classifierClass.newInstance();
        // Configure classifier (if necessary)
        if (classifierTemp instanceof IConfigure) {
            ((IConfigure) classifierTemp).configure(configuration.subset("wrapper-classifier"));
        }
        // Add this classifier to the query strategy
        setClassifier(classifierTemp);
    } catch (ClassNotFoundException e) {
        throw new ConfigurationRuntimeException("Illegal classifier classname: " + wrapperError, e);
    } catch (InstantiationException e) {
        throw new ConfigurationRuntimeException("Illegal classifier classname: " + wrapperError, e);
    } catch (IllegalAccessException e) {
        throw new ConfigurationRuntimeException("Illegal classifier classname: " + wrapperError, e);
    }
}

From source file:net.sf.jclal.activelearning.algorithm.ClassicalALAlgorithm.java

/**
 * Establishes the configuration of the scenario
 *
 * @param configuration// w  w w . j a  v  a  2s. c  o m
 *            The configuration object to use
 */
public void setScenarioConfiguration(Configuration configuration) {

    String scenarioError = "scenario type= ";
    // scenario
    try {
        // scenario classname
        String scenarioClassname = configuration.getString("scenario[@type]");

        scenarioError += scenarioClassname;
        // scenario class
        Class<? extends IScenario> scenarioClass = (Class<? extends IScenario>) Class
                .forName(scenarioClassname);
        // scenario instance
        IScenario scenario = scenarioClass.newInstance();
        // Configure scenario (if necessary)
        if (scenario instanceof IConfigure) {
            ((IConfigure) scenario).configure(configuration.subset("scenario"));
        }
        // Add this scenario to the algorithm
        setScenario(scenario);
    } catch (ClassNotFoundException e) {
        throw new ConfigurationRuntimeException("\nIllegal scenario classname: " + scenarioError, e);
    } catch (InstantiationException e) {
        throw new ConfigurationRuntimeException("\nIllegal scenario classname: " + scenarioError, e);
    } catch (IllegalAccessException e) {
        throw new ConfigurationRuntimeException("\nIllegal scenario classname: " + scenarioError, e);
    }
}

From source file:edu.kit.dama.staging.util.StagingConfigurationManager.java

/**
 * Creates an instance of one of the needed adapters. The type of the
 * instance is defined by the return value and by pAdapterId. Both
 * definitions must fit to avoid configuration exceptions.
 *
 * @param <T> Adapter class implementing IConfigurableAdapter.
 * @param pConfig The configuration used to obtain the adapter
 * configurations./*from w w w  .ja v  a  2  s.  c  o m*/
 * @param pAdapterId The ID of the adapter. Depending on the ID, all
 * properties are obtained and logging is performed.
 *
 * @return An instance of the created adapter which extends
 * IConfigurableAdapter.
 *
 * @throws ConfigurationException if anything goes wrong (e.g. T and
 * pAdapterId do not fit, no entry for pAdapterId was found, the provided
 * adapter class was not found, instantiation or configuration failed...).
 */
private <T extends IConfigurableAdapter> T createAdapterInstance(Configuration pConfig, String pAdapterId)
        throws ConfigurationException {
    try {
        String adapterClass = pConfig.getString("adapters." + pAdapterId + "[@class]");

        //check adapter class
        if (adapterClass == null || adapterClass.length() < 1) {
            throw new ConfigurationException(
                    "No valid adapter class attribute found for adapter '" + pAdapterId + "'");
        }

        String adapterTarget = pConfig.getString("adapters." + pAdapterId + "[@target]");
        Configuration customConfig = pConfig.subset("adapters." + pAdapterId);

        LOGGER.debug("Creating adapter instance for '{}'", pAdapterId);
        LOGGER.debug(" * Adapter class: '{}'", adapterClass);
        LOGGER.debug(" * Adapter target: '{}'", adapterTarget);

        //create and configure instance
        Class clazz = Class.forName(adapterClass);
        Object instance;
        if (adapterTarget == null || adapterTarget.length() < 1 || adapterTarget.equalsIgnoreCase("local")) {//no target provided...hopefully the adapter can be instantiated without a target
            instance = clazz.getConstructor().newInstance();
        } else {//target provided, use it for instantiation
            try {
                URL target = new URL(adapterTarget);
                instance = clazz.getConstructor(URL.class).newInstance(target);
            } catch (MalformedURLException mue) {
                throw new ConfigurationException(
                        "Provided adapter target '" + adapterTarget + "'is no valid URL", mue);
            }
        }
        if (customConfig != null && !customConfig.isEmpty()) {//try custom configuration
            ((T) instance).configure(customConfig);
        }
        return (T) instance;
    } catch (ClassNotFoundException cnfe) {
        throw new ConfigurationException("Failed to locate adapter class for ID '" + pAdapterId + "'", cnfe);
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException ie) {
        throw new ConfigurationException(
                "Failed to instantiate and configure adapter for ID '" + pAdapterId + "'", ie);
    } catch (NoSuchMethodException nsme) {
        throw new ConfigurationException("Invalid adapter class for ID '" + pAdapterId + "'", nsme);
    } catch (ClassCastException cce) {
        throw new ConfigurationException(
                "Adapter instance for ID '" + pAdapterId + "' does not implement adapter interface", cce);
    }
}

From source file:com.konakart.server.KKGWTServiceImpl.java

public void init(ServletConfig config) throws ServletException {
    // very important to call super.init() here
    super.init(config);

    if (config != null) {
        String startOwnEnginesParam = config.getInitParameter("startOwnEngines");
        if (log.isDebugEnabled()) {
            log.debug("startOwnEngines parameter = " + startOwnEnginesParam);
        }//ww  w . ja v  a2  s  .c o  m

        if (startOwnEnginesParam != null && startOwnEnginesParam.equalsIgnoreCase("FALSE")) {
            setStartOwnEngines(false);
        }
    } else {
        if (log.isInfoEnabled()) {
            log.info("Servlet config was null");
        }
    }

    if (isStartOwnEngines() == false) {
        if (log.isDebugEnabled()) {
            log.debug("No engines created in KKGWTServiceImpl()");
        }
        return;
    }

    if (log.isInfoEnabled()) {
        log.info("startOwnEngines undefined so we now create some engines...");
    }

    /*
     * This should only be used when debugging from Eclipse. Otherwise we use the instance of
     * the engine which is attached to the session.
     */
    synchronized (mutex) {
        if (kkConfig == null) {
            try {
                String configFile;
                /*
                 * Find the properties file which is guaranteed to return the full path name of
                 * the properties file or throw an exception. It can't send out an error message
                 * since Log4j hasn't been initialised yet. In this case the properties file
                 * should be called konakart_gwt.properties
                 */
                configFile = PropertyFileFinder.findProperties(propertiesFileName);
                Configuration conf = new PropertiesConfiguration(configFile);
                if (conf.isEmpty()) {
                    log.error("KKGWTServiceImpl() " + propertiesFileName + " contains no keys");
                    throw new KKException(
                            "The configuration file: " + propertiesFileName + " contains no keys");
                }

                // Look for properties that are in the "konakart.app" namespace.
                Configuration subConf = conf.subset("konakart.gwt");
                if (subConf == null || subConf.isEmpty()) {
                    log.error("The konakart.gwt section in the properties file is missing. "
                            + "You must add at least one property to resolve this problem. "
                            + "e.g. konakart.gwt.engineclass=com.konakart.app.KKEng");
                    return;
                }
                kkConfig = subConf;
            } catch (Exception e) {
                log.warn("KonakartGWTServer() an error has occured");
                // e.printStackTrace();
                throw new ServletException(getExceptionMessage(e));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("kkConfig not null");
            }
        }

        // Instantiate the engine
        try {
            if (kkConfig == null) {
                throw new KKException("No properties have been found for the application. "
                        + "Please ensure that the properties file " + propertiesFileName + " exists");
            }
            String engineClassName = kkConfig.getString("engineclass");
            System.out.println("KonakartGWTServer() Engine to be used by application is " + engineClassName);

            EngineConfigIf engConf = new EngineConfig();
            engConf.setStoreId("store1");
            engConf.setAppPropertiesFileName(konakart_app_propertiesFileName);
            engConf.setPropertiesFileName(konakart_eng_propertiesFileName);
            engConf.setMode(EngineConfig.MODE_SINGLE_STORE);

            if (log.isInfoEnabled()) {
                log.info("Kick off an engine as if by Struts");
            }
            getAppEngByName(engineClassName, engConf);

            debugAppEng = getAppEngByName(engineClassName);

            // while (debugAppEng.getOrderMgr().isMgrReady() == false)
            // {
            // if (log.isInfoEnabled())
            // {
            // log.info("Mgr is not ready");
            // }
            // Thread.sleep(1000);
            // }

            debugAppEng.getOrderMgr().setHostAndPort("localhost:8080");

            // debugAppEng.getCustomerMgr().login("root@localhost", "password");
            if (log.isInfoEnabled()) {
                log.info("KonakartGWTServer() Engine created successfully");
            }

        } catch (Exception e) {
            // e.printStackTrace();
            throw new ServletException(getExceptionMessage(e));
        }
    }
}

From source file:com.comcast.viper.flume2storm.location.StaticLocationService.java

/**
 * @param configuration/* w  ww.  j  av a  2s. com*/
 *          The configuration that contains the {@link ServiceProvider}
 * @param serialization
 *          The {@link ServiceProviderSerialization} to use
 * @throws F2SConfigurationException
 *           If the configuration is invalid
 */
public StaticLocationService(Configuration configuration, final ServiceProviderSerialization<SP> serialization)
        throws F2SConfigurationException {
    this.serialization = serialization;
    StaticLocationServiceConfiguration staticLocationServiceConfig = StaticLocationServiceConfiguration
            .from(configuration);

    String configLoaderClassName = staticLocationServiceConfig.getConfigurationLoaderClassName();
    ServiceProviderConfigurationLoader<SP> spLoader = null;
    try {
        @SuppressWarnings("unchecked")
        Class<? extends ServiceProviderConfigurationLoader<SP>> loaderFactoryClass = (Class<? extends ServiceProviderConfigurationLoader<SP>>) Class
                .forName(configLoaderClassName);
        spLoader = loaderFactoryClass.newInstance();
    } catch (Exception e) {
        throw new F2SConfigurationException("Failed to load ServiceProviderConfigurationLoader class", e);
    }
    assert spLoader != null;

    String spString = configuration.getString(StaticLocationServiceConfiguration.SERVICE_PROVIDER_LIST);
    LOG.trace("Service providers to load: {}", spString);
    if (spString == null)
        return;
    Configuration spConfig = configuration.subset(staticLocationServiceConfig.getServiceProviderBase());
    Builder<SP> spBuilders = ImmutableList.builder();
    for (String spName : StringUtils.split(spString,
            StaticLocationServiceConfiguration.SERVICE_PROVIDER_LIST_SEPARATOR)) {
        LOG.trace("Loading service provider: {}", spName);
        Configuration providerConfig = spConfig.subset(spName);
        SP serviceProvider = spLoader.load(providerConfig);
        if (serviceProvider != null) {
            LOG.debug("Loaded service provider {}: {}", spName, serviceProvider);
            spBuilders.add(serviceProvider);
        } else {
            LOG.error("Failed to load service provider identified with {}", spName);
        }
    }
    serviceProviderManager.set(spBuilders.build());
}

From source file:net.sf.jclal.activelearning.algorithm.AbstractALAlgorithm.java

/**
 *
 * @param configuration The configuration object
 * //from w ww .  ja  v a 2  s.co m
 * The XML labels supported are:
 * 
 * <ul>
 * <li><b>listener type = class:</b>
 * <p>
 * Adds the specified listener to receive algorithm events from this
 * algorithm.
 * </p>
 * <p>
 * Package: net.sf.jclal.listener</p>
 * <p>
 * Class: All</p>
 * </li>
 * </ul>
 */
@Override
public void configure(Configuration configuration) {
    // Number of defined listeners
    int numberOfListeners = configuration.getList("listener[@type]").size();
    // For each listener in list
    String listenerError;
    for (int i = 0; i < numberOfListeners; i++) {
        String header = "listener(" + i + ")";
        listenerError = "listener type= ";
        try {
            // Listener classname
            String listenerClassname = configuration.getString(header + "[@type]");
            listenerError += listenerClassname;
            // Listener class
            Class<? extends IAlgorithmListener> listenerClass = (Class<? extends IAlgorithmListener>) Class
                    .forName(listenerClassname);
            // Listener instance
            IAlgorithmListener listener = listenerClass.newInstance();
            // Configure listener (if necessary)
            if (listener instanceof IConfigure) {
                ((IConfigure) listener).configure(configuration.subset(header));
            }
            // Add this listener to the algorithm
            addListener(listener);
        } catch (ClassNotFoundException e) {
            throw new ConfigurationRuntimeException("\nIllegal listener classname: " + listenerError, e);
        } catch (InstantiationException e) {
            throw new ConfigurationRuntimeException("\nIllegal listener classname: " + listenerError, e);
        } catch (IllegalAccessException e) {
            throw new ConfigurationRuntimeException("\nIllegal listener classname: " + listenerError, e);
        }
    }
}

From source file:net.sf.jclal.classifier.WekaComitteClassifier.java

/**
 *
 * @param configuration The configuration of Weka committee classifier.
 *The XML labels supported are://from  w  w  w . j a  v a  2s  .c  om
 * <ul>
 * <li>
 * <b>classifier type= class</b>
 * <p>
 * More than one classifier tag can be specified 
 * 
 * Package:
 * weka.classifiers</p>
 * <p>
 * Class: All</p>
 * </li>
 * </ul>
 */
@Override
public void configure(Configuration configuration) {

    String classifierError = "classifier type= ";
    try {

        // Number of defined classifiers
        int numberOfClassifiers = configuration.getList("classifier[@type]").size();

        Classifier[] currentClassifiers = new Classifier[numberOfClassifiers];

        // For each classifier in list
        for (int i = 0; i < numberOfClassifiers; i++) {

            String header = "classifier(" + i + ")";

            // classifier classname
            String classifierClassname = configuration.getString(header + "[@type]");
            classifierError += classifierClassname;
            // classifier class
            Class<? extends Classifier> classifierClass = (Class<? extends Classifier>) Class
                    .forName(classifierClassname);

            // classifier instance
            Classifier currentClassifier = classifierClass.newInstance();

            // Configure classifier (if necessary)
            if (currentClassifier instanceof IConfigure) {
                ((IConfigure) currentClassifier).configure(configuration.subset(header));
            }

            currentClassifiers[i] = currentClassifier;

        }
        // Add this classifier to the strategy
        setClassifiers(currentClassifiers);

    } catch (ClassNotFoundException e) {
        throw new ConfigurationRuntimeException("\nIllegal classifier classname: " + classifierError, e);
    } catch (InstantiationException e) {
        throw new ConfigurationRuntimeException("\nIllegal classifier classname: " + classifierError, e);
    } catch (IllegalAccessException e) {
        throw new ConfigurationRuntimeException("\nIllegal classifier classname: " + classifierError, e);
    }
}

From source file:net.sf.jclal.evaluation.method.AbstractEvaluationMethod.java

/**
 * Set the sampling strategy/*from   w w w .  ja v  a 2  s.co m*/
 *
 * @param configuration The configuration to use
 */
public void setSamplingStrategyConfiguration(Configuration configuration) {

    String samplingError = "sampling-method type= ";
    try {

        // sampling classname
        String samplingClassname = configuration.getString("sampling-method[@type]");

        samplingError += samplingClassname;
        // sampling class
        Class<? extends ISampling> samplingClass = (Class<? extends ISampling>) Class
                .forName(samplingClassname);
        // sampling instance
        ISampling sampling = samplingClass.newInstance();
        // Configure sampling (if necessary)
        if (sampling instanceof IConfigure) {
            ((IConfigure) sampling).configure(configuration.subset("sampling-method"));
        }
        // Add this sampling to the algorithm
        setSamplingStrategy(sampling);
    } catch (ClassNotFoundException e) {
        throw new ConfigurationRuntimeException("\nIllegal ISampling classname: " + samplingError, e);
    } catch (InstantiationException e) {
        throw new ConfigurationRuntimeException("\nIllegal ISampling classname: " + samplingError, e);
    } catch (IllegalAccessException e) {
        throw new ConfigurationRuntimeException("\nIllegal ISampling classname: " + samplingError, e);
    }

}