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

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

Introduction

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

Prototype

private void load(InputSource source) throws ConfigurationException 

Source Link

Document

Loads a configuration file from the specified input source.

Usage

From source file:org.talend.mdm.commmon.util.core.EncryptUtil.java

public static void encyptXML(String location) {
    try {/*from   ww w .  j  a  v a  2s . c  om*/
        File file = new File(location);
        if (file.exists()) {
            XMLConfiguration config = new XMLConfiguration();
            config.setDelimiterParsingDisabled(true);
            config.load(file);
            List<Object> dataSources = config.getList("datasource.[@name]"); //$NON-NLS-1$
            int index = -1;
            for (int i = 0; i < dataSources.size(); i++) {
                if (dataSources.get(i).equals(dataSourceName)) {
                    index = i;
                    break;
                }
            }
            updated = false;
            if (index >= 0) {
                HierarchicalConfiguration sub = config.configurationAt("datasource(" + index + ")"); //$NON-NLS-1$//$NON-NLS-2$
                encryptByXpath(sub, "master.rdbms-configuration.connection-password"); //$NON-NLS-1$
                encryptByXpath(sub, "master.rdbms-configuration.init.connection-password"); //$NON-NLS-1$
                encryptByXpath(sub, "staging.rdbms-configuration.connection-password"); //$NON-NLS-1$
                encryptByXpath(sub, "staging.rdbms-configuration.init.connection-password"); //$NON-NLS-1$
                encryptByXpath(sub, "system.rdbms-configuration.connection-password"); //$NON-NLS-1$
                encryptByXpath(sub, "system.rdbms-configuration.init.connection-password"); //$NON-NLS-1$
            }
            if (updated) {
                config.save(file);
            }
        }
    } catch (Exception e) {
        LOGGER.error("Encrypt password in '" + location + "' error."); //$NON-NLS-1$ //$NON-NLS-2$
    }
}

From source file:org.talend.mdm.commmon.util.core.EncryptUtilTest.java

@Test
public void testEncypt() throws Exception {
    String path = getClass().getResource("mdm.conf").getFile();
    path = StringUtils.substringBefore(path, "mdm.conf");
    EncryptUtil.encrypt(path);/*from   w w  w  .  j  a  v  a2s  . co  m*/

    File confFile = new File(path + "mdm.conf");
    PropertiesConfiguration confConfig = new PropertiesConfiguration();
    confConfig.setDelimiterParsingDisabled(true);
    confConfig.load(confFile);
    assertEquals("aYfBEdcXYP3t9pofaispXA==,Encrypt", confConfig.getString(MDMConfiguration.ADMIN_PASSWORD));
    assertEquals("tKyTop7U6czAJKGTd9yWRA==,Encrypt", confConfig.getString(MDMConfiguration.TECHNICAL_PASSWORD));
    assertEquals("DlqU02M503JUOVBeup29+w==,Encrypt", confConfig.getString(EncryptUtil.ACTIVEMQ_PASSWORD));

    File tdscFile = new File(path + "tdsc-database.properties");
    PropertiesConfiguration tdscConfig = new PropertiesConfiguration();
    tdscConfig.setDelimiterParsingDisabled(true);
    tdscConfig.load(tdscFile);
    assertEquals("yzuBTeQahXQS7ts8Dh6zeQ==,Encrypt", tdscConfig.getString(EncryptUtil.TDSC_DATABASE_PASSWORD));

    File datasource = new File(path + "datasources.xml");
    XMLConfiguration config = new XMLConfiguration();
    config.setDelimiterParsingDisabled(true);
    config.load(datasource);

    HierarchicalConfiguration sub = config.configurationAt("datasource(0)");
    String password = sub.getString("master.rdbms-configuration.connection-password");
    assertEquals("sa", password);
    password = sub.getString("master.rdbms-configuration.init.connection-password");
    assertNull(password);

    sub = config.configurationAt("datasource(1)");
    password = sub.getString("master.rdbms-configuration.connection-password");
    assertEquals("+WNho+eyvY2IdYENFaoKIA==,Encrypt", password);
    password = sub.getString("master.rdbms-configuration.init.connection-password");
    assertEquals("+WNho+eyvY2IdYENFaoKIA==,Encrypt", password);

}

From source file:org.zaproxy.gradle.UpdateAddOnZapVersionsEntries.java

@TaskAction
public void update() throws Exception {
    if (checksumAlgorithm.get().isEmpty()) {
        throw new IllegalArgumentException("The checksum algorithm must not be empty.");
    }//from w w w  .ja v a  2 s.  co  m

    if (fromFile.isPresent()) {
        if (fromUrl.isPresent()) {
            throw new IllegalArgumentException(
                    "Only one of the properties, URL or file, can be set at the same time.");
        }

        if (!downloadUrl.isPresent()) {
            throw new IllegalArgumentException("The download URL must be provided when specifying the file.");
        }
    } else if (!fromUrl.isPresent()) {
        throw new IllegalArgumentException("Either one of the properties, URL or file, must be set.");
    }

    if (downloadUrl.get().isEmpty()) {
        throw new IllegalArgumentException("The download URL must not be empty.");
    }

    try {
        URL url = new URL(downloadUrl.get());
        if (!HTTPS_SCHEME.equalsIgnoreCase(url.getProtocol())) {
            throw new IllegalArgumentException(
                    "The provided download URL does not use HTTPS scheme: " + url.getProtocol());
        }
    } catch (IOException e) {
        throw new IllegalArgumentException("Failed to parse the download URL: " + e.getMessage(), e);
    }

    Path addOn = getAddOn();
    String addOnId = extractAddOnId(addOn.getFileName().toString());
    AddOnEntry addOnEntry = new AddOnEntry(addOnId,
            new AddOnConfBuilder(addOn, downloadUrl.get(), checksumAlgorithm.get(), releaseDate.get()).build());

    for (File zapVersionsFile : into.getFiles()) {
        if (!Files.isRegularFile(zapVersionsFile.toPath())) {
            throw new IllegalArgumentException("The provided path is not a file: " + zapVersionsFile);
        }

        SortedSet<AddOnEntry> addOns = new TreeSet<>();
        XMLConfiguration zapVersionsXml = new CustomXmlConfiguration();
        zapVersionsXml.load(zapVersionsFile);
        Arrays.stream(zapVersionsXml.getStringArray(ADD_ON_ELEMENT)).filter(id -> !addOnId.equals(id))
                .forEach(id -> {
                    String key = ADD_ON_NODE_PREFIX + id;
                    addOns.add(new AddOnEntry(id, zapVersionsXml.configurationAt(key)));
                    zapVersionsXml.clearTree(key);
                });

        zapVersionsXml.clearTree(ADD_ON_ELEMENT);
        zapVersionsXml.clearTree(ADD_ON_NODE_PREFIX + addOnId);

        addOns.add(addOnEntry);

        addOns.forEach(e -> {
            zapVersionsXml.addProperty(ADD_ON_ELEMENT, e.getAddOnId());
            zapVersionsXml.addNodes(ADD_ON_NODE_PREFIX + e.getAddOnId(),
                    e.getData().getRootNode().getChildren());
        });
        zapVersionsXml.save(zapVersionsFile);
    }
}

From source file:org.zaproxy.gradle.UpdateDailyZapVersionsEntries.java

@TaskAction
public void update() throws Exception {
    File dailyRelease = from.get().getAsFile();
    if (!Files.isRegularFile(dailyRelease.toPath())) {
        throw new IllegalArgumentException(
                "The provided daily release does not exist or it's not a file: " + dailyRelease);
    }//from ww  w.  j a  va 2  s.c  om

    if (checksumAlgorithm.get().isEmpty()) {
        throw new IllegalArgumentException("The checksum algorithm must not be empty.");
    }

    if (baseDownloadUrl.get().isEmpty()) {
        throw new IllegalArgumentException("The base download URL must not be empty.");
    }

    String fileName = dailyRelease.getName();
    String dailyVersion = getDailyVersion(fileName);
    String hash = createChecksum(checksumAlgorithm.get(), dailyRelease);
    String size = String.valueOf(dailyRelease.length());
    String url = baseDownloadUrl.get() + dailyVersion.substring(2) + "/" + fileName;

    for (File zapVersionsFile : into.getFiles()) {
        if (!Files.isRegularFile(zapVersionsFile.toPath())) {
            throw new IllegalArgumentException("The provided path is not a file: " + zapVersionsFile);
        }

        XMLConfiguration zapVersionsXml = new CustomXmlConfiguration();
        zapVersionsXml.load(zapVersionsFile);
        zapVersionsXml.setProperty(DAILY_VERSION_ELEMENT, dailyVersion);
        zapVersionsXml.setProperty(DAILY_FILE_ELEMENT, fileName);
        zapVersionsXml.setProperty(DAILY_HASH_ELEMENT, hash);
        zapVersionsXml.setProperty(DAILY_SIZE_ELEMENT, size);
        zapVersionsXml.setProperty(DAILY_URL_ELEMENT, url);
        zapVersionsXml.save(zapVersionsFile);
    }
}

From source file:org.zaproxy.zap.model.Vulnerabilities.java

private static synchronized void init() {
    if (vulns == null) {
        // Read them in from the file
        XMLConfiguration config;
        try {/*from   w w w  .jav  a2s  .c o m*/
            File f = new File(Constant.getInstance().VULNS_CONFIG);
            config = new XMLConfiguration();
            config.setDelimiterParsingDisabled(true);
            config.load(f);
        } catch (ConfigurationException e) {
            logger.error(e.getMessage(), e);
            initEmpty();
            return;
        }

        String[] test;
        try {
            test = config.getStringArray("vuln_items");
        } catch (ConversionException e) {
            logger.error(e.getMessage(), e);
            initEmpty();
            return;
        }
        final int numberOfVulns = test.length;

        List<Vulnerability> tempVulns = new ArrayList<>(numberOfVulns);
        idToVuln = new HashMap<>(Math.max((int) (numberOfVulns / 0.75) + 1, 16));

        String name;
        List<String> references;

        for (String item : test) {
            name = "vuln_item_" + item;
            try {
                references = new ArrayList<>(Arrays.asList(config.getStringArray(name + ".reference")));
            } catch (ConversionException e) {
                logger.error(e.getMessage(), e);
                references = new ArrayList<>(0);
            }

            Vulnerability v = new Vulnerability(item, config.getString(name + ".alert"),
                    config.getString(name + ".desc"), config.getString(name + ".solution"), references);
            tempVulns.add(v);
            idToVuln.put(item, v);
        }

        vulns = Collections.unmodifiableList(tempVulns);
    }
}

From source file:pl.otros.logview.gui.LogViewMainFrame.java

private static XMLConfiguration getConfiguration(String file) {
    XMLConfiguration commonConfiguration = new XMLConfiguration();
    File commonConfigurationFile = new File(file);
    // load common configuration
    if (commonConfigurationFile.exists()) {
        LOGGER.info("Loading common configuration from " + commonConfigurationFile.getAbsolutePath());
        try {//ww w  .  j a  v  a2 s.c om
            commonConfiguration.load(commonConfigurationFile);
        } catch (ConfigurationException e) {
            LOGGER.severe("Can't load configuration, creating new " + e.getMessage());
        }
    } else {
        LOGGER.info("Common configuration file do not exist");
    }
    // load user specific configuration
    if (!AllPluginables.USER_CONFIGURATION_DIRECTORY.exists()) {
        LOGGER.info("Creating user specific OtrosLogViewer configuration directory "
                + AllPluginables.USER_CONFIGURATION_DIRECTORY.getAbsolutePath());
        AllPluginables.USER_CONFIGURATION_DIRECTORY.mkdirs();
        AllPluginables.USER_FILTER.mkdirs();
        AllPluginables.USER_LOG_IMPORTERS.mkdirs();
        AllPluginables.USER_MARKERS.mkdirs();
        AllPluginables.USER_MESSAGE_FORMATTER_COLORZIERS.mkdirs();
    }
    XMLConfiguration userConfiguration = new XMLConfiguration();
    File userConfigurationFile = new File(AllPluginables.USER_CONFIGURATION_DIRECTORY + File.separator + file);
    userConfiguration.setFile(userConfigurationFile);
    if (userConfigurationFile.exists()) {
        try {
            userConfiguration.load();
        } catch (ConfigurationException e) {
            LOGGER.severe(String.format("Can't load user configuration from %s: %s",
                    userConfigurationFile.getAbsolutePath(), e.getMessage()));
        }
    }
    Iterator<?> keys = commonConfiguration.getKeys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        if (!userConfiguration.containsKey(key)) {
            userConfiguration.setProperty(key, commonConfiguration.getProperty(key));
        }
    }
    userConfiguration.setAutoSave(true);
    return userConfiguration;
}

From source file:put.semantic.fcanew.ui.EntryImpl.java

public void load(File f) {
    try {/* w  ww  .j  a v a 2s  .c  o  m*/
        XMLConfiguration c = new XMLConfiguration();
        c.setDelimiterParsingDisabled(true);
        c.load(f);
        endpoint = c.getString("mappings.endpoint");
        prefixes = c.getString("mappings.prefixes");
        for (HierarchicalConfiguration m : c.configurationsAt("mappings.mapping")) {
            String attr = m.getString("attribute");
            for (EntryImpl e : entries) {
                if (attr.equals(e.getAttribute().toString())) {
                    e.setPattern(m.getString("pattern"));
                }
            }
        }
        tableModel.fireTableDataChanged();
    } catch (ConfigurationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:simpleserver.config.DTDEntityResolver.java

@Override
public void load() {
    if (isDefault) {
        return; // should not be called in default config!
    }/*w w  w  .  ja  v a  2 s .c  om*/

    XMLConfiguration confbuff = null;

    try {
        // load stored config
        loadsuccess = true;
        InputStream stream = new FileInputStream(getFile());
        confbuff = initConf(true);
        confbuff.load(stream);

        if (!loadsuccess) {
            loadsuccess = true;
            System.out.println("Trying to load permissions.xml ignoring DTD warnings...");
            stream = new FileInputStream(getFile());
            confbuff = initConf(false);
            confbuff.load(stream);
        }

        config = confbuff; // No problems loading -> set loaded config as real
        // config
        checkNewCommands(); // append new commands found in default to current
        // config
    }

    catch (FileNotFoundException e) {
        System.out.println("Trying to convert old configuration files...");
        if (new ConfToXml().convertFiles()) {
            server.kits.load();
            load();

        } else {
            System.out.println(getFilename() + " is missing.  Loading defaults.");
            loadDefaults();
            save();
        }
    }

    catch (ConfigurationException e) {
        System.out.println("[SimpleServer] " + e);
        System.out.println("[SimpleServer] Failed to load " + getFilename());

        if (config != null) {
            System.out.println("[SimpleServer] Warning:   permission.xml NOT reloaded!");
            System.out.println("               Saving now will overwrite your changes!");
        }

        loadsuccess = false;
    }
}

From source file:uk.ac.ebi.arrayexpress.app.ApplicationPreferences.java

private void load() {
    // todo: what to do if file is not there? must be a clear error message + shutdown
    InputStream prefsStream = null;
    try {/*from www  . java2s .  c o  m*/
        XMLConfiguration.setDefaultListDelimiter('\uffff');
        XMLConfiguration xmlConfig = new XMLConfiguration();

        //try to get system property file
        String filename = System.getProperty("biosamples.preferences.file");
        URL prefsURL;
        if (filename != null) {
            logger.info("Got value of system property biosamples.preferences.file " + filename);
            File prefsFile = new File(filename);
            prefsURL = prefsFile.toURI().toURL();
        } else {
            logger.info("Falling back to /WEB-INF/classes/" + prefsFileName + ".xml");
            prefsURL = Application.getInstance().getResource("/WEB-INF/classes/" + prefsFileName + ".xml");
        }

        prefsStream = prefsURL.openStream();
        xmlConfig.load(prefsStream);

        prefs = xmlConfig;
    } catch (Exception x) {
        logger.error("Caught an exception:", x);
    } finally {
        if (null != prefsStream) {
            try {
                prefsStream.close();
            } catch (IOException x) {
                logger.error("Caught an exception:", x);
            }
        }
    }
}

From source file:uk.ac.ebi.atlas.trader.ConfigurationTrader.java

private XMLConfiguration getXmlConfiguration(String pathTemplate, String experimentAccession,
        boolean splitOnComma) {
    Path path = Paths.get(MessageFormat.format(pathTemplate, experimentAccession));

    File file = path.toFile();/*from ww  w  . j ava  2s . c o m*/

    if (!file.exists()) {
        throw new IllegalStateException("Configuration file " + path.toString() + " does not exist");
    }

    try {
        XMLConfiguration xmlConfiguration = new XMLConfiguration();
        if (!splitOnComma) {
            xmlConfiguration.setDelimiterParsingDisabled(true);
        }
        xmlConfiguration.load(path.toFile());
        return xmlConfiguration;
    } catch (ConfigurationException cex) {
        LOGGER.error(cex.getMessage(), cex);
        throw new IllegalStateException("Cannot read configuration from path " + path.toString(), cex);
    }

}