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(Writer writer) throws ConfigurationException 

Source Link

Document

Saves the configuration to the specified writer.

Usage

From source file:com.seanmadden.fast.ldap.main.Main.java

/**
 * The Main Event./*  w  w  w.  ja v a  2  s  .c  om*/
 * 
 * @param args
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    BasicConfigurator.configure();
    log.debug("System initializing");
    try {
        Logger.getRootLogger().addAppender(
                new FileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), "log.log"));
    } catch (IOException e1) {
        log.error("Unable to open the log file..?");
    }

    /*
     * Initialize the configuration engine.
     */
    XMLConfiguration config = new XMLConfiguration();
    config.setListDelimiter('|');

    /*
     * Initialize the Command-Line parsing engine.
     */
    CommandLineParser parser = new PosixParser();
    Options opts = new Options();
    opts.addOption(OptionBuilder.withLongOpt("config-file").hasArg()
            .withDescription("The configuration file to load").withArgName("config.xml").create("c"));

    opts.addOption(OptionBuilder.withLongOpt("profile").hasArg().withDescription("The profile to use")
            .withArgName("Default").create("p"));

    opts.addOption(OptionBuilder.withLongOpt("password").hasArg().withDescription("Password to connect with")
            .withArgName("password").create("P"));

    opts.addOption(OptionBuilder.withLongOpt("debug").hasArg(false).create('d'));

    opts.addOption(OptionBuilder.withLongOpt("verbose").hasArg(false).create('v'));

    File configurationFile = new File("config.xml");

    try {
        // Parse the command-line options
        CommandLine cmds = parser.parse(opts, args);

        if (!cmds.hasOption('p')) {
            Logger.getRootLogger().addAppender(new GuiErrorAlerter(Level.ERROR));
        }

        Logger.getRootLogger().setLevel(Level.ERROR);
        if (cmds.hasOption('v')) {
            Logger.getRootLogger().setLevel(Level.INFO);
        }
        if (cmds.hasOption('d')) {
            Logger.getRootLogger().setLevel(Level.DEBUG);
        }

        log.debug("Enabling configuration file parsing");
        // The user has given us a file to parse.
        if (cmds.hasOption("c")) {
            configurationFile = new File(cmds.getOptionValue("c"));
        }
        log.debug("Config file: " + configurationFile);

        // Load the configuration file
        if (configurationFile.exists()) {
            config.load(configurationFile);
        } else {
            log.error("Cannot find config file");
        }

        /*
         * Convert the profiles into memory
         */
        Vector<ConnectionProfile> profs = new Vector<ConnectionProfile>();
        List<?> profList = config.configurationAt("Profiles").configurationsAt("Profile");
        for (Object p : profList) {
            SubnodeConfiguration profile = (SubnodeConfiguration) p;
            String name = profile.getString("[@name]");
            String auth = profile.getString("LdapAuthString");
            String server = profile.getString("LdapServerString");
            String group = profile.getString("LdapGroupsLocation");
            ConnectionProfile prof = new ConnectionProfile(name, server, auth, group);
            profs.add(prof);
        }
        ConnectionProfile prof = null;
        if (!cmds.hasOption('p')) {
            /*
             * Deploy the profile selector, to select a profile
             */
            ProfileSelector profSel = new ProfileSelector(profs);
            prof = profSel.getSelection();
            if (prof == null) {
                return;
            }
            /*
             * Empty the profiles and load a clean copy - then save it back
             * to the file
             */
            config.clearTree("Profiles");
            for (ConnectionProfile p : profSel.getProfiles()) {
                config.addProperty("Profiles.Profile(-1)[@name]", p.getName());
                config.addProperty("Profiles.Profile.LdapAuthString", p.getLdapAuthString());
                config.addProperty("Profiles.Profile.LdapServerString", p.getLdapServerString());
                config.addProperty("Profiles.Profile.LdapGroupsLocation", p.getLdapGroupsString());
            }
            config.save(configurationFile);
        } else {
            for (ConnectionProfile p : profs) {
                if (p.getName().equals(cmds.getOptionValue('p'))) {
                    prof = p;
                    break;
                }
            }
        }

        log.info("User selected " + prof);

        String password = "";
        if (cmds.hasOption('P')) {
            password = cmds.getOptionValue('P');
        } else {
            password = PasswordPrompter.promptForPassword("Password?");
        }

        if (password.equals("")) {
            return;
        }

        LdapInterface ldap = new LdapInterface(prof.getLdapServerString(), prof.getLdapAuthString(),
                prof.getLdapGroupsString(), password);

        /*
         * Gather options information from the configuration engine for the
         * specified report.
         */
        Hashtable<String, Hashtable<String, ReportOption>> reportDataStructure = new Hashtable<String, Hashtable<String, ReportOption>>();
        List<?> repConfig = config.configurationAt("Reports").configurationsAt("Report");
        for (Object p : repConfig) {
            SubnodeConfiguration repNode = (SubnodeConfiguration) p;

            // TODO Do something with the report profile.
            // Allowing the user to deploy "profiles" is a nice feature
            // String profile = repNode.getString("[@profile]");

            String reportName = repNode.getString("[@report]");
            Hashtable<String, ReportOption> reportOptions = new Hashtable<String, ReportOption>();
            reportDataStructure.put(reportName, reportOptions);
            // Loop through the options and add each to the table.
            for (Object o : repNode.configurationsAt("option")) {
                SubnodeConfiguration option = (SubnodeConfiguration) o;
                String name = option.getString("[@name]");
                String type = option.getString("[@type]");
                String value = option.getString("[@value]");

                ReportOption ro = new ReportOption();
                ro.setName(name);

                if (type.toLowerCase().equals("boolean")) {
                    ro.setBoolValue(Boolean.parseBoolean(value));
                } else if (type.toLowerCase().equals("integer")) {
                    ro.setIntValue(Integer.valueOf(value));
                } else {
                    // Assume a string type here then.
                    ro.setStrValue(value);
                }
                reportOptions.put(name, ro);
                log.debug(ro);
            }
        }
        System.out.println(reportDataStructure);

        /*
         * At this point, we now need to deploy the reports window to have
         * the user pick a report and select some happy options to allow
         * that report to work. Let's go.
         */
        /*
         * Deploy the Reports selector, to select a report
         */
        Reports.getInstance().setLdapConnection(ldap);
        ReportsWindow reports = new ReportsWindow(Reports.getInstance().getAllReports(), reportDataStructure);
        Report report = reports.getSelection();
        if (report == null) {
            return;
        }
        /*
         * Empty the profiles and load a clean copy - then save it back to
         * the file
         */
        config.clearTree("Reports");
        for (Report r : Reports.getInstance().getAllReports()) {
            config.addProperty("Reports.Report(-1)[@report]", r.getClass().getCanonicalName());
            config.addProperty("Reports.Report[@name]", "Standard");
            for (ReportOption ro : r.getOptions().values()) {
                config.addProperty("Reports.Report.option(-1)[@name]", ro.getName());
                config.addProperty("Reports.Report.option[@type]", ro.getType());
                config.addProperty("Reports.Report.option[@value]", ro.getStrValue());
            }
        }
        config.save(configurationFile);
        ProgressBar bar = new ProgressBar();
        bar.start();
        report.execute();
        ASCIIFormatter format = new ASCIIFormatter();
        ReportResult res = report.getResult();
        format.format(res, new File(res.getForName() + "_" + res.getReportName() + ".txt"));
        bar.stop();

        JOptionPane.showMessageDialog(null,
                "The report is at " + res.getForName() + "_" + res.getReportName() + ".txt", "Success",
                JOptionPane.INFORMATION_MESSAGE);

    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FAST Ldap Searcher", opts);
    } catch (ConfigurationException e) {
        e.printStackTrace();
        log.fatal("OH EM GEES!  Configuration errors.");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.dfki.av.sudplan.Configuration.java

/**
 * Save the configuration file {@code config/sudplan3D.xml} from the
 * resources to the the file {@code file}. Adding the additional properties
 * {@code sudplan3D.user.dir} and {@code sudplan3D.working.dir}.
 *
 * @param file the configuration {@link File}
 * @param userHomeDir the user home directory
 * @param workingDir the working directory
 *//* w w  w  . ja va 2 s.c o m*/
private static void installConfigFile(File file, String userHomeDir, String workingDir) {
    log.debug("Installing configuration to {}...", file.getAbsoluteFile());
    try {
        ClassLoader loader = Configuration.class.getClassLoader();
        URL url = loader.getResource("config/sudplan3D.xml");
        XMLConfiguration xmlInitialConfig = new XMLConfiguration(url);
        xmlInitialConfig.addProperty("sudplan3D.user.dir", userHomeDir);
        xmlInitialConfig.addProperty("sudplan3D.working.dir", workingDir);
        xmlInitialConfig.save(file);
    } catch (ConfigurationException ex) {
        log.error(ex.toString());
    }
}

From source file:com.intuit.tank.proxy.config.CommonsProxyConfiguration.java

public static boolean save(int port, boolean followRedirect, String outputFile,
        Set<ConfigInclusionExclusionRule> inclusions, Set<ConfigInclusionExclusionRule> exclusions,
        Set<ConfigInclusionExclusionRule> bodyInclusions, Set<ConfigInclusionExclusionRule> bodyExclusions,
        String fileName) {/*  w w w  .j  a v  a2s .  com*/

    ConfigurationNode node = getConfNode("recording-proxy-config", "", false);
    ConfigurationNode portNode = getConfNode("proxy-port", String.valueOf(port), false);
    ConfigurationNode followRedirectNode = getConfNode("follow-redirects", Boolean.toString(followRedirect),
            false);
    ConfigurationNode outputFileNode = getConfNode("output-file", outputFile, false);
    ConfigurationNode inclusionsNode = getConfNode("inclusions", "", false);
    ConfigurationNode exclusionsNode = getConfNode("exclusions", "", false);
    ConfigurationNode bodyInclusionsNode = getConfNode("body-inclusions", "", false);
    ConfigurationNode bodyExclusionsNode = getConfNode("body-exclusions", "", false);

    updateRuleParentNode(inclusions, inclusionsNode);
    updateRuleParentNode(exclusions, exclusionsNode);
    updateRuleParentNode(bodyInclusions, bodyInclusionsNode);
    updateRuleParentNode(bodyExclusions, bodyExclusionsNode);

    node.addChild(portNode);
    node.addChild(followRedirectNode);
    node.addChild(outputFileNode);
    node.addChild(inclusionsNode);
    node.addChild(exclusionsNode);
    node.addChild(bodyInclusionsNode);
    node.addChild(bodyExclusionsNode);

    HierarchicalConfiguration hc = new HierarchicalConfiguration();
    hc.setRootNode(node);
    XMLConfiguration xmlConfiguration = new XMLConfiguration(hc);
    xmlConfiguration.setRootNode(node);

    try {

        xmlConfiguration.save(new File(fileName));
    } catch (ConfigurationException e) {
        e.printStackTrace();
    }
    return true;

}

From source file:com.vmware.qe.framework.datadriven.utils.XMLUtil.java

public static void writeToXML(HierarchicalConfiguration config, String fileName) throws Exception {
    XMLConfiguration xmlConfiguration = new XMLConfiguration();
    xmlConfiguration.addNodes("test-data", config.getRootNode().getChildren());
    xmlConfiguration.save(fileName);
}

From source file:co.turnus.generic.AbstractConfigurable.java

protected void storeConfiguration(File file) {
    XMLConfiguration xml = new XMLConfiguration();
    xml.copy(configuration);/*  w  ww  .j  a  v  a  2s  .co  m*/
    try {
        xml.save(file);
    } catch (Exception e) {
        throw new TurnusRuntimeException("Error while storing the configuration to " + file.getAbsolutePath());
    }
}

From source file:com.oltpbenchmark.util.ResultUploader.java

public void writeBenchmarkConf(PrintStream os) throws ConfigurationException {
    XMLConfiguration outputConf = (XMLConfiguration) expConf.clone();
    for (String key : IGNORE_CONF) {
        outputConf.clearProperty(key);//from w  w  w. jav a  2s  .  com
    }
    outputConf.save(os);
}

From source file:com.jf.javafx.plugins.impl.PluginRepositoryImpl.java

private String getConfigInString(XMLConfiguration cfg) {
    StringWriter sw = new StringWriter();
    String result = "";
    try {//  w  ww  .  jav  a 2s .c o  m
        cfg.save(sw);
        result = sw.toString();
    } catch (ConfigurationException ex) {
        // do nothing
    }
    try {
        sw.close();
    } catch (IOException ex) {
        Logger.getLogger(PluginRepositoryImpl.class.getName()).log(Level.INFO, null, ex);
    }

    return result;
}

From source file:com.eyeq.pivot4j.ui.property.ConditionalPropertyTest.java

@Test
public void testSettingsManagement() throws ConfigurationException {
    XMLConfiguration configuration = new XMLConfiguration();
    configuration.setRootElementName("property");

    property.saveSettings(configuration);
    System.out.println("Saved configuration : ");
    configuration.save(System.out);
    ConditionalProperty property2 = new ConditionalProperty(new DefaultConditionFactory());
    property2.restoreSettings(configuration);

    assertThat("Property name has been changed.", property2.getName(), is(equalTo(property.getName())));
    assertThat("Default value has been changed.", property2.getDefaultValue(),
            is(equalTo(property.getDefaultValue())));

    RenderContext context = createDummyRenderContext();
    context.setColIndex(2);//from www . ja  v  a2 s .com
    context.setRowIndex(4);

    String result = property2.getValue(context);

    assertThat("Wrong property value.", result, is(equalTo("blue")));

    System.out.println("Saved configuration : ");
    configuration.save(System.out);
}

From source file:com.eyeq.pivot4j.state.StateSavingIT.java

@Test
public void testSaveModelSettings() throws ConfigurationException, IOException {
    PivotModel model = getPivotModel();// w w w  .  j  a v  a  2  s. c  o  m
    model.setMdx(getTestQuery());
    model.initialize();

    model.setSorting(true);
    model.setTopBottomCount(3);
    model.setSortCriteria(SortCriteria.BOTTOMCOUNT);

    CellSet cellSet = model.getCellSet();
    CellSetAxis axis = cellSet.getAxes().get(Axis.COLUMNS.axisOrdinal());

    model.sort(axis, axis.getPositions().get(0));

    String mdx = model.getCurrentMdx();

    XMLConfiguration configuration = new XMLConfiguration();
    configuration.setDelimiterParsingDisabled(true);

    model.saveSettings(configuration);

    Logger logger = LoggerFactory.getLogger(getClass());
    if (logger.isDebugEnabled()) {
        StringWriter writer = new StringWriter();
        configuration.save(writer);
        writer.flush();
        writer.close();

        logger.debug("Loading report content :" + System.getProperty("line.separator"));
        logger.debug(writer.getBuffer().toString());
    }

    PivotModel newModel = new PivotModelImpl(getDataSource());
    newModel.restoreSettings(configuration);

    newModel.getCellSet();

    String newMdx = newModel.getCurrentMdx();
    if (newMdx != null) {
        // Currently the parser treats every number as double value.
        // It's inevitable now and does not impact the result.
        newMdx = newMdx.replaceAll("3\\.0", "3");
    }

    assertThat("MDX has been changed after the state restoration", newMdx, is(equalTo(mdx)));
    assertThat("Property 'sorting' has been changed after the state restoration", newModel.isSorting(),
            is(true));
    assertThat("Property 'topBottomCount' has been changed after the state restoration",
            newModel.getTopBottomCount(), is(equalTo(3)));
    assertThat("Property 'sortMode' has been changed after the state restoration", newModel.getSortCriteria(),
            is(equalTo(SortCriteria.BOTTOMCOUNT)));
}

From source file:com.eyeq.pivot4j.ui.condition.NotConditionTest.java

@Test
public void testSettingsManagement() throws ConfigurationException {
    RenderContext context = createDummyRenderContext();

    NotCondition not = new NotCondition(conditionFactory);
    not.setSubCondition(TestCondition.FALSE);

    XMLConfiguration configuration = new XMLConfiguration();
    configuration.setRootElementName("condition");

    not.saveSettings(configuration);/* www .  j av a 2s  . c  om*/

    not = new NotCondition(conditionFactory);
    not.restoreSettings(configuration);

    assertThat("Sub condition should not be null.", not.getSubCondition(), is(notNullValue()));
    assertThat("'!false' should be true.", not.matches(context), is(true));

    System.out.println("Saved configuration : ");

    configuration.save(System.out);
}