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

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

Introduction

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

Prototype

String getString(String key);

Source Link

Document

Get a string associated with the given configuration key.

Usage

From source file:de.shadowhunt.sonar.plugins.ignorecode.batch.IgnoreCoverageDecoratorTest.java

@Test
public void testDecorate() throws Exception {
    final java.io.File configFile = temporaryFolder.newFile("coverage.txt");
    final PrintWriter writer = new PrintWriter(configFile);
    writer.println("src/java/net/example/Foo.java;[1-20]");
    writer.close();//from  w w w .ja va  2s  . c  om

    final Configuration configuration = Mockito.mock(Configuration.class);
    Mockito.when(configuration.getString(IgnoreCoverageDecorator.CONFIG_FILE))
            .thenReturn(configFile.getAbsolutePath());

    final IgnoreCoverageDecorator decorator = new IgnoreCoverageDecorator(configuration);
    decorator.setModifyMeasures(Mockito.mock(ModifyMeasures.class));

    final org.sonar.api.resources.File file = org.sonar.api.resources.File
            .create("src/java/net/example/Foo.java");
    final DecoratorContext context = Mockito.mock(DecoratorContext.class);
    decorator.decorate(file, context);
}

From source file:de.shadowhunt.sonar.plugins.ignorecode.batch.IgnoreCoverageDecoratorTest.java

@Test
public void testDecorateNotMatchedResource() throws Exception {
    final java.io.File configFile = temporaryFolder.newFile("coverage.txt");
    final PrintWriter writer = new PrintWriter(configFile);
    writer.println("src/java/net/example/Foo.java;[1-20]");
    writer.close();/* w  w  w  .  j  a v  a2 s .c  o  m*/

    final Configuration configuration = Mockito.mock(Configuration.class);
    Mockito.when(configuration.getString(IgnoreCoverageDecorator.CONFIG_FILE))
            .thenReturn(configFile.getAbsolutePath());

    final IgnoreCoverageDecorator decorator = new IgnoreCoverageDecorator(configuration);
    decorator.setModifyMeasures(Mockito.mock(ModifyMeasures.class));

    final org.sonar.api.resources.File file = org.sonar.api.resources.File
            .create("src/java/net/example/Bar.java");
    final DecoratorContext context = Mockito.mock(DecoratorContext.class);
    decorator.decorate(file, context);
}

From source file:edu.kit.dama.rest.util.auth.AuthenticatorFactory.java

/**
 * Creates an instance of the configured authenticator defined in a
 * subsection of pConfig named 'authenticators'. The root node of the
 * section also contains the implementation class. Depending on the
 * implementation, there might be further child nodes containing specific
 * configuration values for the adapter implementation.
 *
 * @param <T> Adapter class implementing IConfigurableAdapter.
 * @param pConfig The configuration used to obtain the Authenticator.
 *
 * @return An instance of the created Authenticator implementation.
 *
 * @throws ConfigurationException if anything goes wrong (e.g. if the
 * provided adapter class was not found, instantiation or configuration
 * failed...)/*from  w ww .j  a  v  a  2  s .  c  o  m*/
 */
private <T extends IConfigurableAdapter> T createAuthenticatorInstance(Configuration pConfig)
        throws ConfigurationException {
    try {
        String adapterClass = pConfig.getString("[@class]");

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

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

        //create and configure instance
        Class clazz = Class.forName(adapterClass);
        Object inst = clazz.getConstructor().newInstance();
        ((T) inst).configure(pConfig);
        return (T) inst;
    } catch (ClassNotFoundException cnfe) {
        throw new ConfigurationException("Failed to locate adapter class for adapter 'Authenticator'", cnfe);
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException ie) {
        throw new ConfigurationException(
                "Failed to instantiate and configure adapter for adapter 'Authenticator'", ie);
    } catch (NoSuchMethodException nsme) {
        throw new ConfigurationException("Invalid adapter class for adapter 'Authenticator'", nsme);
    } catch (ClassCastException cce) {
        throw new ConfigurationException(
                "Adapter instance for adapter 'Authenticator' does not implement IConfigurableAdapter interface",
                cce);
    }
}

From source file:com.nesscomputing.quartz.NessQuartzModule.java

private void configureJob(final String jobName, final Configuration jobConfig) {
    try {//w w w .java2  s  . c om
        final String className = jobConfig.getString("class");
        Preconditions.checkState(className != null, "No class key found (but it existed earlier!");
        final Class<? extends Job> jobClass = Class.forName(className).asSubclass(Job.class);

        // Bind the class. if it needs to be a singleton, annotate accordingly. Do not add
        // in(Scopes.SINGLETON) here, because then it is not possible to undo that.
        bind(jobClass);

        final QuartzJobBinder binder = QuartzJobBinder.bindQuartzJob(binder(), jobClass);
        binder.name(jobName);

        if (jobConfig.containsKey("delay")) {
            binder.delay(parseDuration(jobConfig, "delay"));
        }

        if (jobConfig.containsKey("startTime")) {
            binder.startTime(parseStartTime(jobConfig, "startTime"), new TimeSpan("60s"));
        }

        if (jobConfig.containsKey("repeat")) {
            binder.repeat(parseDuration(jobConfig, "repeat"));
        }

        if (jobConfig.containsKey("group")) {
            binder.group(jobConfig.getString("group"));
        }

        if (jobConfig.containsKey("cronExpression")) {
            binder.cronExpression(jobConfig.getString("cronExpression"));
        }

        if (jobConfig.containsKey("enabled")) {
            binder.enabled(jobConfig.getBoolean("enabled"));
        } else {
            LOG.warn("Found job %s but no key for enabling!", jobName);
        }

        LOG.info("Registered %s", binder);
        binder.register();
    } catch (ClassCastException cce) {
        addError(cce);
    } catch (ClassNotFoundException cnfe) {
        addError(cnfe);
    }
}

From source file:edu.kit.dama.mdm.dataorganization.service.core.DataOrganizerFactory.java

/**
 * Creates an instance of the configured DataOrganizer defined in a
 * subsection of pConfig named 'dataOrganizerAdapter'. The root node of the
 * section also contains the implementation class. Depending on the
 * implementation, there might be further child nodes containing specific
 * configuration values for the adapter implementation.
 *
 * @param <T> Adapter class implementing IConfigurableAdapter.
 * @param pConfig The configuration used to obtain the DataOrganizerAdapter.
 *
 * @return An instance of the created DataOrganizer implementation.
 *
 * @throws ConfigurationException if anything goes wrong (e.g. if the
 * provided adapter class was not found, instantiation or configuration
 * failed...)/*from   w w  w  . j a v a  2s.  c o  m*/
 */
private <T extends IConfigurableAdapter> T createDataOrganizerAdapterInstance(Configuration pConfig)
        throws ConfigurationException {
    try {
        String adapterClass = pConfig.getString("dataOrganizerAdapter[@class]");

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

        Configuration customConfig = pConfig.subset("dataOrganizerAdapter");

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

        //create and configure instance
        Class clazz = Class.forName(adapterClass);
        Object inst = clazz.getConstructor().newInstance();
        if (customConfig != null && !customConfig.isEmpty()) {//try custom configuration
            ((T) inst).configure(customConfig);
        }
        return (T) inst;
    } catch (ClassNotFoundException cnfe) {
        throw new ConfigurationException("Failed to locate adapter class for adapter 'dataOrganizerAdapter'",
                cnfe);
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException ie) {
        throw new ConfigurationException(
                "Failed to instantiate and configure adapter for adapter 'dataOrganizerAdapter'", ie);
    } catch (NoSuchMethodException nsme) {
        throw new ConfigurationException("Invalid adapter class for adapter 'dataOrganizerAdapter'", nsme);
    } catch (ClassCastException cce) {
        throw new ConfigurationException(
                "Adapter instance for adapter 'dataOrganizerAdapter' does not implement IConfigurableAdapter interface",
                cce);
    }
}

From source file:com.boozallen.cognition.lens.LensAPI.java

/**
 * Helper method for creating the spark context from the given cognition configuration
 * @return a new configured spark context
 *//*w  ww  .  j  a v  a  2s.  c  o  m*/
public SparkContext createSparkContext() {
    SparkConf conf = new SparkConf();

    Configuration config = cognition.getProperties();

    conf.set("spark.serializer", KryoSerializer.class.getName());
    conf.setAppName(config.getString("app.name"));
    conf.setMaster(config.getString("master"));

    Iterator<String> iterator = config.getKeys("spark");
    while (iterator.hasNext()) {
        String key = iterator.next();
        conf.set(key, config.getString(key));
    }

    SparkContext sc = new SparkContext(conf);
    for (String jar : config.getStringArray("jars")) {
        sc.addJar(jar);
    }

    return sc;
}

From source file:com.boozallen.cognition.ingest.storm.bolt.geo.LocationResolverBolt.java

@Override
public void configure(Configuration conf) throws ConfigurationException {
    _luceneIndexDir = conf.getString(LUCENE_INDEX_DIR);
    _localIndexDir = conf.getString(LOCAL_INDEX_DIR);
    _textFields = conf.getList(TEXT_FIELDS);
    _pipClavinLocationPrefix = conf.getString(PIP_CLAVIN_LOCATION_PREFIX, "pip.clavinLocation_");
    _fieldName = conf.getString(FIELD_NAME, FIELD_NAME);
    _name = conf.getString(NAME, NAME);//from   www  .  ja va  2  s  . co  m
    _admin1Code = conf.getString(ADMIN1CODE, ADMIN1CODE);
    _admin2Code = conf.getString(ADMIN2CODE, ADMIN2CODE);
    _countryCode = conf.getString(COUNTRYCODE, COUNTRYCODE);
    _latitude = conf.getString(LATITUDE, LATITUDE);
    _longitude = conf.getString(LONGITUDE, LONGITUDE);
    _confidence = conf.getString(CONFIDENCE, CONFIDENCE);

    Configuration hadoopConfigSubset = conf.subset(HADOOP_CONFIG);
    for (Iterator<String> itr = hadoopConfigSubset.getKeys(); itr.hasNext();) {
        String key = itr.next();
        String value = hadoopConfigSubset.getString(key);
        hadoopConfig.put(key, value);
    }
}

From source file:de.suse.swamp.modules.actions.LoginActions.java

public void doLogoutuser(RunData data, Context context) throws Exception {
    User user = data.getUser();//from   w  w w.jav  a 2  s  .c  o  m

    if (!TurbineSecurity.isAnonymousUser(user)) {
        // Make sure that the user has really logged in...
        if (!user.hasLoggedIn()) {
            Logger.ERROR("Trying to logout a not-logged-in User! (" + user.getName() + ")");
            return;
        }
        user.setHasLoggedIn(Boolean.FALSE);
    }

    Configuration conf = Turbine.getConfiguration();
    data.setMessage(conf.getString(TurbineConstants.LOGOUT_MESSAGE));

    // This will cause the acl to be removed from the session in the Turbine servlet code.
    data.setACL(null);

    // Retrieve an anonymous user.
    data.setUser(TurbineSecurity.getAnonymousUser());

    // In the event that the current screen or related navigations
    // require acl info, we cannot wait for Turbine to handle
    // regenerating acl.
    data.getSession().removeAttribute(AccessControlList.SESSION_KEY);
    data.save();

    HttpSession session = data.getSession();
    session.invalidate();
    data.setUser(TurbineSecurity.getAnonymousUser());
    String loginScreen = Turbine.getConfiguration().getString("template.login");
    data.setScreenTemplate(loginScreen);
    Logger.LOG(user.getName() + " has logged out.");

    // Check for XML-Output for external scripts
    if (data.getParameters().containsKey("xmlresponse")
            && data.getParameters().get("xmlresponse").equals("true")) {
        ExternalActions.doSendXMLOutput(data, "0", "Your are logged out");
    }

}

From source file:com.appeligo.channelfeed.SendCaptionFiles.java

@Override
protected void openSources(Configuration provider) {
    int fileCount = provider.getList("files.file[@name]").size();

    for (int j = 0; j < fileCount; j++) {

        String fileName = provider.getString("files.file(" + j + ")[@name]");
        String callsign = provider.getString("files.file(" + j + ")[@callsign]");
        String loop = provider.getString("files.file(" + j + ")[@loop]");
        String autoAdvance = provider.getString("files.file(" + j + ")[@autoAdvance]");
        String advanceSeconds = provider.getString("files.file(" + j + ")[@advanceSeconds]");

        if ((autoAdvance != null) && (advanceSeconds != null)) {
            log.error("autoAdvance and advanceSeconds are mutually exclusive");
            continue;
        }/*w ww  .jav a 2  s.c  o m*/

        log.info("fileName=" + fileName + ", callsign=" + callsign + ", advanceSeconds=" + advanceSeconds);

        if (fileName == null || callsign == null) {
            //TODO: change to a logging call
            log.error("Invalid configuration in: " + identifyMe());
            log.error("    fileName=" + fileName + ", callsign=" + callsign);
            continue;
        }
        try {
            FileReaderThread fileThread = new FileReaderThread(
                    "File Captions " + getLineupID() + ", callsign " + callsign);

            fileThread.setEpgService(getEpgService());
            fileThread.setCcDocumentRoot(getCaptionDocumentRoot());
            fileThread.setCaptionFileName(fileName);
            if (advanceSeconds != null) {
                fileThread.setAdvanceSeconds(Integer.parseInt(advanceSeconds));
            } else if (autoAdvance != null) {
                fileThread.setAutoAdvance(Boolean.parseBoolean(autoAdvance));
            }
            if (loop != null) {
                fileThread.setLoop(Boolean.parseBoolean(loop));
            }

            Destinations destinations = setupDestinations();
            destinations.setCallsign(callsign);
            destinations.setSendXDS(false);
            destinations.setSendITV(false);
            destinations.setFileWriter(null);

            fileThread.setDestinations(destinations);

            destinations.connect();
            fileThread.start();

        } catch (MalformedURLException e1) {
            log.error("Exception on a channel", e1);
        } catch (NumberFormatException e1) {
            log.error("Exception on a channel", e1);
        } catch (IOException e1) {
            log.error("Exception on a channel", e1);
        }
    }
}

From source file:com.nesscomputing.config.TestPrefix.java

@Test
public void testSystemStillWins() {
    Assert.assertThat(cfg, is(notNullValue()));

    PropertiesConfiguration pc = new PropertiesConfiguration();
    pc.setProperty("prefix.of.three.string-null-value", "NULL");
    pc.setProperty("prefix.of.three.string-value", "another test value");

    PropertiesSaver ps = new PropertiesSaver("prefix.of.three.string-value");

    try {/*w w w .j av  a  2s .co  m*/
        System.setProperty("prefix.of.three.string-value", "system-value");

        Config c2 = Config.getOverriddenConfig(cfg, pc);

        final Configuration config = c2.getConfiguration("prefix.of.three");

        Assert.assertThat(config, is(notNullValue()));

        final String s_cfg2 = config.getString("string-value");
        Assert.assertThat(s_cfg2, is("system-value"));
    } finally {
        ps.apply();
    }
}