Example usage for org.apache.commons.configuration XMLConfiguration save

List of usage examples for org.apache.commons.configuration XMLConfiguration save

Introduction

In this page you can find the example usage for org.apache.commons.configuration XMLConfiguration save.

Prototype

public void save() throws ConfigurationException 

Source Link

Usage

From source file:com.xemantic.tadedon.configuration.ConfigurationsTest.java

/**
 * copying of XML properties does not work at the moment
 * @throws IOException/*from   ww  w .j a  v a2s  .co m*/
 * @throws ConfigurationException
 */
@Test
@Ignore
public void shouldCopyXmlPropertyWithoutComments() throws IOException, ConfigurationException {
    // given
    File confFile1 = new File("src/test/data/conf1.xml");
    File confFile2 = new File("src/test/data/conf2.xml");
    File confFile3 = new File("src/test/data/conf3.xml");
    File outConfFile = new File(testConfDir, "outConf.xml");
    Files.copy(confFile1, outConfFile);
    XMLConfiguration conf2 = new XMLConfiguration(confFile2);
    XMLConfiguration outConf = new XMLConfiguration(outConfFile);

    // when
    //Configurations.copyProperty("bar", conf2, outConf);
    outConf.save();

    // then
    assertThat(Files.equal(outConfFile, confFile3), is(true));
}

From source file:logica.EstacionMet.java

@Override
public Stack<PaqueteDatos> actualizar() {
    // Informacion para PaqueteDatos()
    Integer[] sensoresID = new Integer[redSensores.length];
    String[] tipo = new String[redSensores.length];
    String[] medicion = new String[redSensores.length];

    // Cargo el resumen de la estacion si es que existe.
    // Instancio el manejador de XML
    XMLConfiguration registro = new XMLConfiguration();
    registro.setFileName(String.format("resumenes/%d.xml", ID));

    try {/* w  w  w  . j  a v  a  2  s .  c o  m*/
        // Cargo si existe el registro
        registro.load();
    } catch (ConfigurationException ex) {
        // Si no existe, simplemente seteo el nombre del elemento base
        registro.setRootElementName("resumen");
        // Y creo el archivo
        try {
            registro.save();
        } catch (ConfigurationException ex1) {
            LOGGER.log(Level.SEVERE, null, ex1);
        }
    }

    // Datos de las sub-estaciones
    medidasPila = super.actualizar();

    // Busco y guardo las mediciones de los sensores.
    int largo = redSensores.length;
    for (int i = 0; i < largo; i++) {
        if (redSensores[i] != null) {
            sensoresID[i] = redSensores[i].getID();
            tipo[i] = redSensores[i].getClass().getSimpleName();
            medicion[i] = redSensores[i].getMedicion();
            resumenSave(registro, sensoresID[i], tipo[i], medicion[i]);
        }
    }

    // Agrego el los datos de esta estacion al final de los datos de las sub-estaciones
    medidasPila.push(new PaqueteDatos(ID, getHora(), sensoresID, tipo, medicion));

    return medidasPila;
}

From source file:de.nec.nle.siafu.control.Controller.java

/**
 * Create a config file with default values. This is used when the config
 * file doesn't exist in the first place.
 * /*from   w  ww  .  j  a  va  2 s  . co m*/
 * @return the newly created configuration file.
 */
private XMLConfiguration createDefaultConfigFile() {
    System.out.println("Creating a default configuration file at " + DEFAULT_CONFIG_FILE);
    XMLConfiguration newConfig = new XMLConfiguration();
    newConfig.setRootElementName("configuration");
    newConfig.setProperty("commandlistener.enable", true);
    newConfig.setProperty("commandlistener.tcpport", DEFAULT_PORT);
    newConfig.setProperty("ui.usegui", true);
    newConfig.setProperty("ui.speed", DEFAULT_UI_SPEED);
    newConfig.setProperty("ui.gradientcache.prefill", true);
    newConfig.setProperty("ui.gradientcache.size", DEFAULT_CACHE_SIZE);
    newConfig.setProperty("output.type", "null");
    newConfig.setProperty("output.csv.path",
            System.getProperty("user.home") + File.separator + "SiafuContext.csv");
    newConfig.setProperty("output.csv.interval", DEFAULT_CSV_INTERVAL);
    newConfig.setProperty("output.csv.keephistory", true);

    try {
        newConfig.setFileName(DEFAULT_CONFIG_FILE);
        newConfig.save();
    } catch (ConfigurationException e) {
        throw new RuntimeException("Can not create a default config file at " + DEFAULT_CONFIG_FILE, e);
    }

    return newConfig;
}

From source file:io.datalayer.conf.XmlConfigurationTest.java

/**
 * Tests setting an attribute on the root element.
 *//*w w w . jav a  2 s . com*/
@Test
public void testSetRootAttribute() throws ConfigurationException {
    conf.setProperty("[@test]", "true");
    assertEquals("Root attribute not set", "true", conf.getString("[@test]"));
    conf.save(testSaveConf);
    XMLConfiguration checkConf = new XMLConfiguration();
    checkConf.setFile(testSaveConf);
    checkSavedConfig(checkConf);
    assertTrue("Attribute not found after save", checkConf.containsKey("[@test]"));
    checkConf.setProperty("[@test]", "newValue");
    checkConf.save();
    conf = checkConf;
    checkConf = new XMLConfiguration();
    checkConf.setFile(testSaveConf);
    checkSavedConfig(checkConf);
    assertEquals("Attribute not modified after save", "newValue", checkConf.getString("[@test]"));
}

From source file:io.datalayer.conf.XmlConfigurationTest.java

/**
 * Tests the copy constructor./* www .j  av a2 s  .c o  m*/
 */
@Test
public void testInitCopy() throws ConfigurationException {
    XMLConfiguration copy = new XMLConfiguration(conf);
    assertEquals("value", copy.getProperty("element"));
    assertNull("Document was copied, too", copy.getDocument());
    ConfigurationNode root = copy.getRootNode();
    for (ConfigurationNode node : root.getChildren()) {
        assertNull("Reference was not cleared", node.getReference());
    }

    removeTestFile();
    copy.setFile(testSaveConf);
    copy.save();
    copy.clear();
    checkSavedConfig(copy);
}

From source file:logica.EstacionMet.java

/**
 * Encargado de actualizar y guardar la informacion de un sensor en los 
 * resumenes XML//  w w w .  j  a  v a  2  s.  c o m
 * 
 * @param registro El manejador de XML
 * @param sensorID El id del sensor cuyo resumen hay que actualizar
 * @param tipo El tipo de sensor cuyo resumen hay que actualizar
 * @param medicionS La medicion del sensor
 */
private void resumenSave(XMLConfiguration registro, Integer sensorID, String tipo, String medicionS) {
    try {
        // Busco si ya hay algun registro del sensor.
        List<String> idsRegistro = registro.getList(String.format("estacion%d.sensor.id", ID));
        int index = -1;

        for (String id : idsRegistro) {
            if (Integer.valueOf(id).equals(sensorID)) {
                index = idsRegistro.indexOf(String.valueOf(sensorID));
                break;
            }
        }
        // Si ya hay, actualizo
        if (index != -1) {
            float medicion; // Medicion actual en float
            String nMedicionesS; // Numero de mediciones
            int nMediciones;
            String maximoS; // Valor maximo de las mediciones
            float maximo;
            String minimoS; // Valor minimo de las mediciones
            float minimo;
            String medioS; // Valor medio de las mediciones
            float medio;

            // Cargo los valores
            nMedicionesS = registro.getString(String.format("estacion%d.sensor(%d).mediciones", ID, index));
            maximoS = registro.getString(String.format("estacion%d.sensor(%d).maximo", ID, index));
            minimoS = registro.getString(String.format("estacion%d.sensor(%d).minimo", ID, index));
            medioS = registro.getString(String.format("estacion%d.sensor(%d).medio", ID, index));

            // Aumento en uno la cantidad de mediciones
            nMediciones = Integer.valueOf(nMedicionesS) + 1;
            registro.setProperty(String.format("estacion%d.sensor(%d).mediciones", ID, index),
                    String.valueOf(nMediciones));

            // Recalculo maximo y minimo
            medicion = Float.valueOf(medicionS.split(" ")[0]);
            maximo = Float.valueOf(maximoS.split(" ")[0]);
            minimo = Float.valueOf(minimoS.split(" ")[0]);

            if (medicion > maximo)
                registro.setProperty(String.format("estacion%d.sensor(%d).maximo", ID, index), medicionS);
            if (medicion < minimo)
                registro.setProperty(String.format("estacion%d.sensor(%d).minimo", ID, index), medicionS);

            // Recalculo el valor medio
            medio = Float.valueOf(medioS.split(" ")[0]);

            medio = (medio + medicion) / 2;
            registro.setProperty(String.format("estacion%d.sensor(%d).medio", ID, index),
                    String.valueOf(medio));
        } else { // Si no, creo y cargo los valores como iniciales
            index = idsRegistro.size();
            registro.addProperty(String.format("estacion%d.sensor(%d).id", ID, index), sensorID.toString());
            registro.addProperty(String.format("estacion%d.sensor(%d).tipo", ID, index), tipo);
            registro.addProperty(String.format("estacion%d.sensor(%d).maximo", ID, index), medicionS);
            registro.addProperty(String.format("estacion%d.sensor(%d).minimo", ID, index), medicionS);
            registro.addProperty(String.format("estacion%d.sensor(%d).medio", ID, index), medicionS);
            registro.addProperty(String.format("estacion%d.sensor(%d).mediciones", ID, index), "1");
        }

        registro.save();
    } catch (ConfigurationException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.juddi.v3.client.config.ClientConfig.java

/**
 * Attempts to save any changes made to the configuration back to disk
 * @throws ConfigurationException /*from   w w  w  . j  av a 2 s .  c  o  m*/
 */
public void saveConfig() throws ConfigurationException {

    XMLConfiguration saveConfiguration = new XMLConfiguration(configurationFile);
    Configuration cc = new CompositeConfiguration(saveConfiguration);
    Iterator<String> keys = this.config.getKeys();
    while (keys.hasNext()) {
        String key = keys.next();
        if (key.startsWith("client") || key.startsWith("config")) {
            cc.setProperty(key, config.getProperty(key));
        }
    }
    saveConfiguration.save();
}

From source file:org.jevis.commons.cli.ConfigurationHelper.java

/**
 * Create an new configuration skeleton/*from w  w w.j  av  a2s . com*/
 *
 * @param file
 * @throws ConfigurationException
 */
public void createConfigFile(File file) throws ConfigurationException {

    //TODO:  XPath expressions for a better implementation see http://www.code-thrill.com/2012/05/configuration-that-rocks-with-apache.html
    XMLConfiguration config = new XMLConfiguration(file);

    config.setProperty("jevis.datasource.class", "org.jevis.api.sql.JEVisDataSourceSQL");
    config.setProperty("jevis.datasource.host", "openjevis.org");
    config.setProperty("jevis.datasource.schema", "jevis");
    config.setProperty("jevis.datasource.port", "13306");
    config.setProperty("jevis.datasource.username", "jevis");
    config.setProperty("jevis.datasource.password", "jevistest");

    config.save();

}

From source file:org.parosproxy.paros.Constant.java

private void initializeFilesAndDirectories() {

    FileCopier copier = new FileCopier();
    File f = null;// w  ww  .  j  a  v a2 s.c om
    Logger log = null;

    // default to use application directory 'log'
    System.setProperty(SYSTEM_PAROS_USER_LOG, "log");

    // Set up the version from the manifest
    PROGRAM_VERSION = getVersionFromManifest();
    PROGRAM_TITLE = PROGRAM_NAME + " " + PROGRAM_VERSION;

    if (zapHome == null) {
        zapHome = getDefaultHomeDirectory(true);
    }

    zapHome = getAbsolutePath(zapHome);
    f = new File(zapHome);

    FILE_CONFIG = zapHome + FILE_CONFIG;
    FOLDER_SESSION = zapHome + FOLDER_SESSION;
    DBNAME_UNTITLED = zapHome + DBNAME_UNTITLED;
    ACCEPTED_LICENSE = zapHome + ACCEPTED_LICENSE;
    DIRBUSTER_CUSTOM_DIR = zapHome + DIRBUSTER_DIR;
    FUZZER_DIR = zapHome + FUZZER_DIR;
    FOLDER_LOCAL_PLUGIN = zapHome + FOLDER_LOCAL_PLUGIN;

    try {
        System.setProperty(SYSTEM_PAROS_USER_LOG, zapHome);

        if (!f.isDirectory()) {
            if (!f.mkdir()) {
                // ZAP: report failure to create directory
                System.out.println("Failed to create directory " + f.getAbsolutePath());
            }
        }

        // Setup the logging
        File logFile = new File(zapHome + "/log4j.properties");
        if (!logFile.exists()) {
            copier.copy(new File(zapInstall, "xml/log4j.properties"), logFile);
        }
        System.setProperty("log4j.configuration", logFile.getAbsolutePath());
        PropertyConfigurator.configure(logFile.getAbsolutePath());
        log = Logger.getLogger(Constant.class);

        f = new File(FILE_CONFIG);
        if (!f.isFile()) {
            File oldf;
            if (isDevBuild() || isDailyBuild()) {
                // try standard location
                oldf = new File(getDefaultHomeDirectory(false) + FILE_SEPARATOR + FILE_CONFIG_NAME);
            } else {
                // try old location
                oldf = new File(zapHome + FILE_SEPARATOR + "zap" + FILE_SEPARATOR + FILE_CONFIG_NAME);
            }

            if (oldf.exists() && Paths.get(zapHome).equals(Paths.get(getDefaultHomeDirectory(true)))) {
                // Dont copy old configs if they've specified a non std directory
                log.info("Copying defaults from " + oldf.getAbsolutePath() + " to " + FILE_CONFIG);
                copier.copy(oldf, f);

            } else {
                log.info("Copying defaults from " + getPathDefaultConfigFile() + " to " + FILE_CONFIG);
                copier.copy(getPathDefaultConfigFile().toFile(), f);
            }
        }

        f = new File(FOLDER_SESSION);
        if (!f.isDirectory()) {
            log.info("Creating directory " + FOLDER_SESSION);
            if (!f.mkdir()) {
                // ZAP: report failure to create directory
                System.out.println("Failed to create directory " + f.getAbsolutePath());
            }
        }
        f = new File(DIRBUSTER_CUSTOM_DIR);
        if (!f.isDirectory()) {
            log.info("Creating directory " + DIRBUSTER_CUSTOM_DIR);
            if (!f.mkdir()) {
                // ZAP: report failure to create directory
                System.out.println("Failed to create directory " + f.getAbsolutePath());
            }
        }
        f = new File(FUZZER_DIR);
        if (!f.isDirectory()) {
            log.info("Creating directory " + FUZZER_DIR);
            if (!f.mkdir()) {
                // ZAP: report failure to create directory
                System.out.println("Failed to create directory " + f.getAbsolutePath());
            }
        }
        f = new File(FOLDER_LOCAL_PLUGIN);
        if (!f.isDirectory()) {
            log.info("Creating directory " + FOLDER_LOCAL_PLUGIN);
            if (!f.mkdir()) {
                // ZAP: report failure to create directory
                System.out.println("Failed to create directory " + f.getAbsolutePath());
            }
        }

    } catch (Exception e) {
        System.err.println("Unable to initialize home directory! " + e.getMessage());
        e.printStackTrace(System.err);
        System.exit(1);
    }

    // Upgrade actions
    try {
        try {

            // ZAP: Changed to use ZapXmlConfiguration, to enforce the same character encoding when reading/writing configurations.
            XMLConfiguration config = new ZapXmlConfiguration(FILE_CONFIG);
            config.setAutoSave(false);

            long ver = config.getLong("version");

            if (ver == VERSION_TAG) {
                // Nothing to do
            } else if (isDevBuild() || isDailyBuild()) {
                // Nothing to do
            } else {
                // Backup the old one
                log.info("Backing up config file to " + FILE_CONFIG + ".bak");
                f = new File(FILE_CONFIG);
                try {
                    copier.copy(f, new File(FILE_CONFIG + ".bak"));
                } catch (IOException e) {
                    String msg = "Failed to backup config file " + FILE_CONFIG + " to " + FILE_CONFIG + ".bak "
                            + e.getMessage();
                    System.err.println(msg);
                    log.error(msg, e);
                }

                if (ver == V_PAROS_TAG) {
                    upgradeFrom1_1_0(config);
                    upgradeFrom1_2_0(config);
                }
                if (ver <= V_1_0_0_TAG) {
                    // Nothing to do
                }
                if (ver <= V_1_1_0_TAG) {
                    upgradeFrom1_1_0(config);
                }
                if (ver <= V_1_2_0_TAG) {
                    upgradeFrom1_2_0(config);
                }
                if (ver <= V_1_2_1_TAG) {
                    // Nothing to do
                }
                if (ver <= V_1_3_0_TAG) {
                    // Nothing to do
                }
                if (ver <= V_1_3_1_TAG) {
                    // Nothing to do
                }
                if (ver <= V_1_4_1_TAG) {
                    upgradeFrom1_4_1(config);
                }
                if (ver <= V_2_0_0_TAG) {
                    upgradeFrom2_0_0(config);
                }
                if (ver <= V_2_1_0_TAG) {
                    // Nothing to do
                }
                if (ver <= V_2_2_0_TAG) {
                    upgradeFrom2_2_0(config);
                }
                if (ver <= V_2_3_1_TAG) {
                    upgradeFrom2_3_1(config);
                }
                log.info("Upgraded from " + ver);

                // Update the version
                config.setProperty("version", VERSION_TAG);
                config.save();
            }

        } catch (ConfigurationException | ConversionException | NoSuchElementException e) {
            //  if there is any error in config file (eg config file not exist, corrupted),
            //  overwrite previous configuration file 
            // ZAP: changed to use the correct file
            copier.copy(getPathDefaultConfigFile().toFile(), new File(FILE_CONFIG));

        }
    } catch (Exception e) {
        System.err.println("Unable to upgrade config file " + FILE_CONFIG + " " + e.getMessage());
        e.printStackTrace(System.err);
        System.exit(1);
    }

    // ZAP: Init i18n
    String lang;
    Locale locale = Locale.ENGLISH;

    try {
        // Select the correct locale
        // ZAP: Changed to use ZapXmlConfiguration, to enforce the same character encoding when reading/writing configurations.
        XMLConfiguration config = new ZapXmlConfiguration(FILE_CONFIG);
        config.setAutoSave(false);

        lang = config.getString(OptionsParamView.LOCALE, OptionsParamView.DEFAULT_LOCALE);
        if (lang.length() == 0) {
            lang = OptionsParamView.DEFAULT_LOCALE;
        }

        String[] langArray = lang.split("_");
        locale = new Locale(langArray[0], langArray[1]);

    } catch (Exception e) {
        System.out.println("Failed to initialise locale " + e);
    }

    Locale.setDefault(locale);

    messages = new I18N(locale);
}

From source file:org.settings4j.helper.configuration.ConfigurationToConnectorAdapterTest.java

@Test
public void testAdapterXmlConfigWithDefaultDelimiter() throws Exception {
    final Settings4jRepository testSettings = createSimpleSettings4jConfig();

    // start test => create adapter and add to Settings4jRepository
    final XMLConfiguration configuration = addXmlConfiguration(//
            testSettings, "myXmlConfigConnector", "xmlConfigWithDefaultDelimiter.xml", "/");

    // configure some values
    configuration.setProperty(TEST_VALUE_KEY, "Hello Windows World");
    configuration.save();

    // validate result
    assertThat(testSettings.getSettings().getString(TEST_VALUE_KEY), is("Hello Windows World"));
    assertThat(testSettings.getSettings().getString("unknown/Value"), is(nullValue()));

}