Example usage for org.apache.commons.configuration ConfigurationUtils toString

List of usage examples for org.apache.commons.configuration ConfigurationUtils toString

Introduction

In this page you can find the example usage for org.apache.commons.configuration ConfigurationUtils toString.

Prototype

public static String toString(Configuration configuration) 

Source Link

Document

Get a string representation of the key/value mappings of a configuration.

Usage

From source file:net.sf.mpaxs.spi.server.DrmaaComputeHostLauncher.java

/**
 * Submits a new ComputeHost to the GridEngine.
 * Settings from the Settings class are used and converted to <code>Configuration</code>.
 *
 * @param cfg the configuration to use/*from  w  w w  . jav a2 s  .  c o m*/
 * @see net.sf.mpaxs.spi.computeHost.Settings
 */
@Override
public void startComputeHost(Configuration cfg) {
    String drmaaImplementation = SessionFactory.getFactory().getSession().getDrmaaImplementation();
    System.out.println("Drmaa Implementation: " + drmaaImplementation);
    File configLocation = new File(cfg.getString(ConfigurationKeys.KEY_COMPUTE_HOST_WORKING_DIR),
            "computeHost.properties");
    try {
        PropertiesConfiguration pc = new PropertiesConfiguration(configLocation);
        ConfigurationUtils.copy(cfg, pc);
        pc.save();
    } catch (ConfigurationException ex) {
        Logger.getLogger(DrmaaComputeHostLauncher.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<String> arguments = new ArrayList<String>();
    arguments.add("-cp");
    arguments.add(cfg.getString(ConfigurationKeys.KEY_PATH_TO_COMPUTEHOST_JAR));
    arguments.add(cfg.getString(ConfigurationKeys.KEY_COMPUTE_HOST_MAIN_CLASS));
    arguments.add("-c");
    try {
        arguments.add(configLocation.toURI().toURL().toString());
    } catch (MalformedURLException ex) {
        Logger.getLogger(DrmaaComputeHostLauncher.class.getName()).log(Level.SEVERE, null, ex);
    }
    Logger.getLogger(this.getClass().getName()).log(Level.INFO, "ComputeHost configuration: {0}",
            ConfigurationUtils.toString(cfg));
    try {
        SessionFactory factory = SessionFactory.getFactory();
        Session session = factory.getSession();
        Logger.getLogger(this.getClass().getName()).log(Level.INFO,
                "DRM System: {0} Implementation: {1} Version: {2}", new Object[] { session.getDrmSystem(),
                        session.getDrmaaImplementation(), session.getVersion() });
        session.init("");
        JobTemplate jt = session.createJobTemplate();
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Remote command: {0}",
                cfg.getString(ConfigurationKeys.KEY_PATH_TO_JAVA));
        jt.setRemoteCommand(cfg.getString(ConfigurationKeys.KEY_PATH_TO_JAVA));
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Working dir: {0}",
                cfg.getString(ConfigurationKeys.KEY_COMPUTE_HOST_WORKING_DIR));
        jt.setWorkingDirectory(cfg.getString(ConfigurationKeys.KEY_COMPUTE_HOST_WORKING_DIR));
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Arguments: {0}", arguments);
        jt.setArgs(arguments);
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Error path: {0}",
                cfg.getString(ConfigurationKeys.KEY_ERROR_FILE));
        jt.setErrorPath(":" + cfg.getString(ConfigurationKeys.KEY_ERROR_FILE));
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Output path: {0}",
                cfg.getString(ConfigurationKeys.KEY_OUTPUT_FILE));
        jt.setOutputPath(":" + cfg.getString(ConfigurationKeys.KEY_OUTPUT_FILE));
        jt.setNativeSpecification(cfg.getString(ConfigurationKeys.KEY_NATIVE_SPEC, ""));
        jt.setJobName("mpaxs-chost");
        session.runJob(jt);
        session.deleteJobTemplate(jt);
        session.exit();
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Session started!");
    } catch (DrmaaException ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:net.sf.mpaxs.spi.server.MpaxsImpl.java

@Override
public void startMasterServer(Configuration config, Container c) {
    if (master != null) {
        throw new IllegalStateException("Master server was already started!");
    }/*ww  w  .  j a v  a2s  .  com*/
    if (config == null) {
        System.out.println("Configuration is null, starting master with default parameters!");
        startMasterServer();
        return;
    }
    try {
        File f = File.createTempFile(UUID.randomUUID().toString(), ".properties");
        PropertiesConfiguration pc;
        try {
            pc = new PropertiesConfiguration(f);
            ConfigurationUtils.copy(config, pc);
            pc.save(f);
            System.out.println(ConfigurationUtils.toString(pc));
            master = StartUp.start(f.getAbsolutePath(), c);
        } catch (ConfigurationException ex) {
            Logger.getLogger(MpaxsImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (IOException ex) {
        Logger.getLogger(MpaxsImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.comcast.viper.flume2storm.sink.StormSink.java

/**
 * @see org.apache.flume.conf.Configurable#configure(org.apache.flume.Context)
 *//*from   ww w  . java2 s .  c  o  m*/
@Override
public void configure(final Context context) {
    Preconditions.checkNotNull(context);
    if (sinkCounter == null) {
        sinkCounter = new SinkCounter(getName());
    }
    try {
        Configuration mapConfiguration = new MapConfiguration(context.getParameters());
        LOG.debug("Storm-sink configuration:\n{}", ConfigurationUtils.toString(mapConfiguration));
        configuration = StormSinkConfiguration.from(mapConfiguration);
        Class<? extends ConnectionParametersFactory<CP>> connectionParametersFactoryClass = (Class<? extends ConnectionParametersFactory<CP>>) Class
                .forName(configuration.getConnectionParametersFactoryClassName());
        this.connectionParametersFactory = connectionParametersFactoryClass.newInstance();
        Class<? extends EventSenderFactory<CP>> eventSenderFactoryClass = (Class<? extends EventSenderFactory<CP>>) Class
                .forName(configuration.getEventSenderFactoryClassName());
        this.eventSenderFactory = eventSenderFactoryClass.newInstance();
        Class<? extends LocationServiceFactory<SP>> locationServiceFactoryClass = (Class<? extends LocationServiceFactory<SP>>) Class
                .forName(configuration.getLocationServiceFactoryClassName());
        this.locationServiceFactory = locationServiceFactoryClass.newInstance();
        Class<? extends ServiceProviderSerialization<SP>> serviceProviderSerializationClass = (Class<? extends ServiceProviderSerialization<SP>>) Class
                .forName(configuration.getServiceProviderSerializationClassName());
        this.serviceProviderSerialization = serviceProviderSerializationClass.newInstance();
    } catch (Exception e) {
        LOG.error("Failed to configure Storm sink: " + e.getMessage(), e);
    }
}

From source file:cross.datastructures.pipeline.ResultAwareCommandPipeline.java

/**
 *
 * @param workflow/*from   w ww.ja  v  a2s .c  om*/
 * @return
 */
protected PropertiesConfiguration getHashes(IWorkflow workflow) {
    File hashesFile = getHashesFile(workflow);
    if (hashes == null) {
        try {
            hashes = new PropertiesConfiguration(hashesFile);
            hashes.setAutoSave(true);
            hashes.setReloadingStrategy(new FileChangedReloadingStrategy());
            log.debug("Hashes: {}", ConfigurationUtils.toString(hashes));
            return hashes;
        } catch (ConfigurationException ex) {
            log.error("Could not load configuration at " + hashesFile, ex);
            throw new ExitVmException(ex);
        }
    } else {
        return hashes;
    }
}

From source file:com.vmware.qe.framework.datadriven.config.DDConfig.java

/**
 * Uses the current configuration data passed in as argument and does the following: <br>
 * 1. Look for config.properties file on class path and load it if present.<br>
 * 2. Look for config.path in CLI params. If present, load it and overwrite any existing
 * properties.<br>//from  ww  w  . j  a va2s  .co m
 * 3. Overwrite existing data with whatever was specified via cli. <br>
 * 
 * @param testData test configuration data
 * @return processed test configuration data
 */
private synchronized Configuration prepareData(Configuration testData) {
    Configuration resultData = null;
    // step 1. config.properties on classpath
    URL cfgFile = this.getClass().getResource(DD_CONFIG_FILE_NAME);
    if (cfgFile != null) {
        log.info("Loading Configuration File: {}", cfgFile);
        resultData = getConfigFileData(cfgFile.getFile());
    } else {
        log.warn("Config file not found! " + DD_CONFIG_FILE_NAME);
    }
    if (resultData != null) {
        log.debug("Loaded data from " + DD_CONFIG_FILE_NAME + " on classpath");
    }
    // step 2. config file specified on cli
    if (testData.containsKey(TESTINPUT_CONFIG_PATH)) {
        String filePath = testData.getString(TESTINPUT_CONFIG_PATH);
        if (checkFilePath(filePath)) {
            Configuration tmpData = getConfigFileData(filePath);
            resultData = overrideConfigProperties(resultData, tmpData);
            log.debug("Loaded data from config file '{}'", filePath);
        }
    }
    log.debug("Overriding using properties specified via commandline arguments");
    resultData = overrideConfigProperties(resultData, testData);
    if (resultData == null) {
        String error = "Configuration data can not be null. Please specify test "
                + "configuration information via config file on classpath or filesystem or via cli";
        log.error(error);
        throw new DDException(error);
    }
    log.debug("DDConfig: {}", ConfigurationUtils.toString(resultData));
    return resultData;
}

From source file:io.fluo.core.client.FluoAdminImpl.java

@Override
public void updateSharedConfig() {

    logger.info("Setting up observers using app config: {}",
            ConfigurationUtils.toString(config.subset(FluoConfiguration.APP_PREFIX)));

    Map<Column, ObserverConfiguration> colObservers = new HashMap<>();
    Map<Column, ObserverConfiguration> weakObservers = new HashMap<>();
    for (ObserverConfiguration observerConfig : config.getObserverConfig()) {

        Observer observer;/*  w  w  w.  j a v  a  2 s  . co m*/
        try {
            observer = Class.forName(observerConfig.getClassName()).asSubclass(Observer.class).newInstance();
        } catch (ClassNotFoundException e1) {
            throw new FluoException("Observer class '" + observerConfig.getClassName()
                    + "' was not found.  Check for class name misspellings or failure to include the observer jar.",
                    e1);
        } catch (InstantiationException | IllegalAccessException e2) {
            throw new FluoException(
                    "Observer class '" + observerConfig.getClassName() + "' could not be created.", e2);
        }

        logger.info("Setting up observer {} using params {}.", observer.getClass().getSimpleName(),
                observerConfig.getParameters());
        try {
            observer.init(new ObserverContext(config.subset(FluoConfiguration.APP_PREFIX),
                    observerConfig.getParameters()));
        } catch (Exception e) {
            throw new FluoException("Observer '" + observerConfig.getClassName() + "' could not be initialized",
                    e);
        }

        ObservedColumn observedCol = observer.getObservedColumn();
        if (observedCol.getType() == NotificationType.STRONG)
            colObservers.put(observedCol.getColumn(), observerConfig);
        else
            weakObservers.put(observedCol.getColumn(), observerConfig);
    }

    Properties sharedProps = new Properties();
    Iterator<String> iter = config.getKeys();
    while (iter.hasNext()) {
        String key = iter.next();
        if (key.equals(FluoConfiguration.TRANSACTION_ROLLBACK_TIME_PROP)) {
            sharedProps.setProperty(key, Long.toString(config.getLong(key)));
        } else if (key.startsWith(FluoConfiguration.APP_PREFIX)) {
            sharedProps.setProperty(key, config.getProperty(key).toString());
        }
    }

    try {
        CuratorFramework curator = getFluoCurator();
        Operations.updateObservers(curator, colObservers, weakObservers);
        Operations.updateSharedConfig(curator, sharedProps);
    } catch (Exception e) {
        throw new FluoException("Failed to update shared configuration in Zookeeper", e);
    }
}

From source file:it.unimi.dsi.util.Properties.java

public String toString() {
    return ConfigurationUtils.toString(this);
}

From source file:cross.datastructures.pipeline.ResultAwareCommandPipeline.java

/**
 *
 * @param workflow//from  w ww.ja  v  a2s  .  c o m
 * @param cmd
 */
@Override
protected void runFragmentCommand(IWorkflow workflow, IFragmentCommand cmd) {
    try {
        beforeCommand(cmd);
        TupleND<IFileFragment> results;
        if (!isUpToDate(getTmp(), cmd)) {
            if (getWorkflow().getOutputDirectory(cmd).exists()
                    && getWorkflow().getOutputDirectory(cmd).listFiles().length > 0) {
                log.info("Deleting invalid results for {} below {}", cmd,
                        getWorkflow().getOutputDirectory(cmd));
                try {
                    FileUtils.deleteDirectory(getWorkflow().getOutputDirectory(cmd));
                } catch (IOException ex) {
                    log.warn("Caught IO Exception while trying to delete workflow output directory at "
                            + getWorkflow().getOutputDirectory());
                    throw new RuntimeException(ex);
                }
            }
            long start = System.nanoTime();
            results = cmd.apply(getTmp());
            storeCommandRuntime(start, System.nanoTime(), cmd, getWorkflow());
        } else {
            log.info("Skipping, everything up to date!");
            File outputDir = getWorkflow().getOutputDirectory(cmd);
            Collection<File> inputFiles = FileUtils.listFiles(outputDir,
                    new String[] { "cdf", "CDF", "nc", "NC" }, false);
            TupleND<IFileFragment> inputFragments = new TupleND<>();
            for (File f : inputFiles) {
                inputFragments.add(getWorkflow().getFactory().getFileFragmentFactory().create(f));
            }
            log.debug("Setting file fragments {} as next input!", inputFragments);
            results = inputFragments;
        }
        updateHashes(getTmp(), cmd);
        setTmp(results);
        log.debug("Hashes: {}", ConfigurationUtils.toString(getHashes()));
    } finally {
        afterCommand(cmd);
    }
}

From source file:org.ambraproject.configuration.ConfigurationStore.java

/**
 * Load/Reload the configuration from the factory config url.
 *
 * @param configURL URL to the config file for ConfigurationFactory
 * @throws ConfigurationException when the config factory configuration has an error
 *//*w  w w  .j a v  a2 s  .c om*/
public void loadConfiguration(URL configURL) throws ConfigurationException {
    root = new CombinedConfiguration(new OverrideCombiner());

    // System properties override everything
    root.addConfiguration(new SystemConfiguration());

    // Load from ambra.configuration -- /etc/... (optional)
    if (configURL != null) {
        try {
            root.addConfiguration(getConfigurationFromUrl(configURL));
            log.info("Added URL '" + configURL + "'");
        } catch (ConfigurationException ce) {
            if (!(ce.getCause() instanceof FileNotFoundException))
                throw ce;
            log.info("Unable to open '" + configURL + "'");
        }
    }

    // Add ambra.configuration.overrides (if defined)
    String overrides = System.getProperty(OVERRIDES_URL);
    if (overrides != null) {
        try {
            root.addConfiguration(getConfigurationFromUrl(new URL(overrides)));
            log.info("Added override URL '" + overrides + "'");
        } catch (MalformedURLException mue) {
            // Must not be a URL, so it must be a resource
            addResources(root, overrides);
        }
    }

    CombinedConfiguration defaults = new CombinedConfiguration(new UnionCombiner());
    // Add defaults.xml from classpath
    addResources(defaults, DEFAULTS_RESOURCE);
    // Add journal.xml from journals/journal-name/configuration/journal.xml
    addJournalResources(root, defaults, JOURNAL_DIRECTORY);
    root.addConfiguration(defaults);

    // Add global-defaults.xml (presumably found in this jar)
    addResources(root, GLOBAL_DEFAULTS_RESOURCE);

    if (log.isDebugEnabled())
        log.debug("Configuration dump: " + System.getProperty("line.separator")
                + ConfigurationUtils.toString(root));

    /**
     * This prefix is needed by the AmbraIdGenerator to create prefixes for object IDs.
     * Because of the way the AmbraIdGenerator class is created by hibernate, passing in values
     * is very difficult.  If a better method is discovered... by all means use that.  Until that time
     * I've created a system level property to store this prefix.
     */
    String objectIDPrefix = root.getString("ambra.platform.guid-prefix");

    if (objectIDPrefix == null) {
        throw new RuntimeException(
                "ambra.platform.guid-prefix node is not found in the defined configuration file.");
    }

    System.setProperty(SYSTEM_OBJECT_ID_PREFIX, objectIDPrefix);
}

From source file:org.apache.fluo.api.config.SimpleConfiguration.java

@Override
public String toString() {
    return ConfigurationUtils.toString(internalConfig);
}