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

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

Introduction

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

Prototype

public void clearTree(String key) 

Source Link

Usage

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

/**
 * The Main Event.//from   w ww. j  a  v  a2s .c o  m
 * 
 * @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:org.glite.slcs.acl.impl.RemoveAccessControlRuleXMLOperation.java

protected void doProcessing(XMLConfiguration config) {

    if (LOG.isDebugEnabled())
        LOG.debug("remove AccessControlRule[id=" + ruleId_ + "]");

    // find index
    int i = 0;/*from w w w .j  av a2s .c  om*/
    String ruleKey = null;
    while (true) {
        String rulePrefix = "AccessControlRule(" + i + ")";
        i++;
        String ruleId = config.getString(rulePrefix + "[@id]");
        if (ruleId == null) {
            // no more rules
            break;
        } else {
            int id = Integer.parseInt(ruleId);
            if (id == ruleId_) {
                ruleKey = rulePrefix;
                break;
            }
        }
    }

    if (ruleKey != null) {
        LOG.debug("delete AccessControlRule[id=" + ruleId_ + "]");
        // clear property/tree
        config.clearTree(ruleKey);
        // save
        save(config);
        // success
        setStatus(true);

    } else {
        LOG.error("rule to delete not found: AccessControlRule[id=" + ruleId_ + "]");
    }

}

From source file:org.glite.slcs.acl.impl.ReplaceAccessControlRuleXMLOperation.java

protected void doProcessing(XMLConfiguration config) {

    if (LOG.isDebugEnabled())
        LOG.debug("replacing: " + rule_);

    // find index
    int i = 0;/* www . j  av a  2  s. co  m*/
    String ruleId = null;
    String ruleKey = null;
    while (true) {
        String rulePrefix = "AccessControlRule(" + i + ")";
        i++;
        // read current id
        ruleId = config.getString(rulePrefix + "[@id]");
        if (ruleId == null) {
            // no more rules
            break;
        }
        int id = -1;
        try {
            id = Integer.parseInt(ruleId);
        } catch (Exception e) {
            LOG.error(e);
        }
        if (id == rule_.getId()) {
            ruleKey = rulePrefix;
            // rule found
            break;
        }
    }

    if (ruleKey != null) {
        LOG.debug("replace AccessControlRule[" + ruleId + "]: " + rule_);
        // replace group
        config.setProperty(ruleKey + "[@group]", rule_.getGroupName());
        // clear all existing rule attributes
        config.clearTree(ruleKey + ".Attribute");
        // add new rule attributes
        List ruleAttributes = rule_.getAttributes();
        Iterator attributes = ruleAttributes.iterator();
        while (attributes.hasNext()) {
            Attribute attribute = (Attribute) attributes.next();
            config.addProperty(ruleKey + ".Attribute(-1)", attribute.getValue());
            config.addProperty(ruleKey + ".Attribute[@name]", attribute.getName());
        }
        // save the XML file
        save(config);
        // success
        setStatus(true);

    } else {
        LOG.error("rule to replace: " + rule_ + " not found!");
    }

}

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

private void upgradeFrom1_4_1(XMLConfiguration config) {
    // As the POST_FORM option for the spider has been updated from int to boolean, keep
    // compatibility for old versions
    if (!config.getProperty("spider.postform").toString().equals("0")) {
        config.setProperty("spider.postform", "true");
        config.setProperty("spider.processform", "true");
    } else {// ww w.  ja  va  2s  .  com
        config.setProperty("spider.postform", "false");
        config.setProperty("spider.processform", "false");
    }

    // Move the old session tokens to the new "httpsessions" hierarchy and 
    // delete the old "session" hierarchy as it's no longer used/needed.
    String[] tokens = config.getStringArray("session.tokens");
    for (int i = 0; i < tokens.length; ++i) {
        String elementBaseKey = "httpsessions.tokens.token(" + i + ").";

        config.setProperty(elementBaseKey + "name", tokens[i]);
        config.setProperty(elementBaseKey + "enabled", Boolean.TRUE);
    }
    config.clearTree("session");

    // Update the anti CSRF tokens elements/hierarchy.
    tokens = config.getStringArray("anticsrf.tokens");
    config.clearTree("anticsrf.tokens");
    for (int i = 0; i < tokens.length; ++i) {
        String elementBaseKey = "anticsrf.tokens.token(" + i + ").";

        config.setProperty(elementBaseKey + "name", tokens[i]);
        config.setProperty(elementBaseKey + "enabled", Boolean.TRUE);
    }

    // Update the invoke applications elements/hierarchy.
    List<Object[]> oldData = new ArrayList<>();
    for (int i = 0;; i++) {
        String baseKey = "invoke.A" + i + ".";
        String host = config.getString(baseKey + "name");
        if (host == null || "".equals(host)) {
            break;
        }

        Object[] data = new Object[6];
        data[0] = host;
        data[1] = config.getString(baseKey + "directory", "");
        data[2] = config.getString(baseKey + "command");
        data[3] = config.getString(baseKey + "parameters");
        data[4] = Boolean.valueOf(config.getBoolean(baseKey + "output", true));
        data[5] = Boolean.valueOf(config.getBoolean(baseKey + "note", false));
        oldData.add(data);
    }
    config.clearTree("invoke.A");
    for (int i = 0, size = oldData.size(); i < size; ++i) {
        String elementBaseKey = "invoke.apps.app(" + i + ").";
        Object[] data = oldData.get(i);

        config.setProperty(elementBaseKey + "name", data[0]);
        config.setProperty(elementBaseKey + "directory", data[1]);
        config.setProperty(elementBaseKey + "command", data[2]);
        config.setProperty(elementBaseKey + "parameters", data[3]);
        config.setProperty(elementBaseKey + "output", data[4]);
        config.setProperty(elementBaseKey + "note", data[5]);
        config.setProperty(elementBaseKey + "enabled", Boolean.TRUE);
    }

    // Update the authentication elements/hierarchy.
    oldData = new ArrayList<>();
    for (int i = 0;; i++) {
        String baseKey = "connection.auth.A" + i + ".";
        String host = config.getString(baseKey + "hostName");
        if (host == null || "".equals(host)) {
            break;
        }

        Object[] data = new Object[5];
        data[0] = host;
        data[1] = Integer.valueOf(config.getString(baseKey + "port", "80"));
        data[2] = config.getString(baseKey + "userName");
        data[3] = config.getString(baseKey + "password");
        data[4] = config.getString(baseKey + "realm");
        oldData.add(data);
    }
    config.clearTree("connection.auth.A");
    for (int i = 0, size = oldData.size(); i < size; ++i) {
        String elementBaseKey = "connection.auths.auth(" + i + ").";
        Object[] data = oldData.get(i);

        config.setProperty(elementBaseKey + "name", "Auth " + i);
        config.setProperty(elementBaseKey + "hostName", data[0]);
        config.setProperty(elementBaseKey + "port", data[1]);
        config.setProperty(elementBaseKey + "userName", data[2]);
        config.setProperty(elementBaseKey + "password", data[3]);
        config.setProperty(elementBaseKey + "realm", data[4]);
        config.setProperty(elementBaseKey + "enabled", Boolean.TRUE);
    }

    // Update the passive scan elements/hierarchy.
    String[] names = config.getStringArray("pscans.names");
    oldData = new ArrayList<>();
    for (String pscanName : names) {
        String baseKey = "pscans." + pscanName + ".";

        Object[] data = new Object[8];
        data[0] = pscanName;
        data[1] = config.getString(baseKey + "type");
        data[2] = config.getString(baseKey + "config");
        data[3] = config.getString(baseKey + "reqUrlRegex");
        data[4] = config.getString(baseKey + "reqHeadRegex");
        data[5] = config.getString(baseKey + "resHeadRegex");
        data[6] = config.getString(baseKey + "resBodyRegex");
        data[7] = Boolean.valueOf(config.getBoolean(baseKey + "enabled"));
        oldData.add(data);
    }
    config.clearTree("pscans.names");
    for (String pscanName : names) {
        config.clearTree("pscans." + pscanName);
    }
    for (int i = 0, size = oldData.size(); i < size; ++i) {
        String elementBaseKey = "pscans.autoTagScanners.scanner(" + i + ").";
        Object[] data = oldData.get(i);

        config.setProperty(elementBaseKey + "name", data[0]);
        config.setProperty(elementBaseKey + "type", data[1]);
        config.setProperty(elementBaseKey + "config", data[2]);
        config.setProperty(elementBaseKey + "reqUrlRegex", data[3]);
        config.setProperty(elementBaseKey + "reqHeadRegex", data[4]);
        config.setProperty(elementBaseKey + "resHeadRegex", data[5]);
        config.setProperty(elementBaseKey + "resBodyRegex", data[6]);
        config.setProperty(elementBaseKey + "enabled", data[7]);
    }
}

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

private void upgradeFrom2_0_0(XMLConfiguration config) {
    String forcedBrowseFile = config.getString("bruteforce.defaultFile", "");
    if (!"".equals(forcedBrowseFile)) {
        String absolutePath = "";
        // Try the 'local' dir first
        File f = new File(DIRBUSTER_CUSTOM_DIR + File.separator + forcedBrowseFile);
        if (!f.exists()) {
            f = new File(DIRBUSTER_DIR + File.separator + forcedBrowseFile);
        }/*from  www  .  ja va2s .co m*/
        if (f.exists()) {
            absolutePath = f.getAbsolutePath();
        }
        config.setProperty("bruteforce.defaultFile", absolutePath);
    }

    // Remove the manual request editor configurations that were incorrectly created.
    config.clearTree("nullrequest");
    config.clearTree("nullresponse");
}

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

private void upgradeFrom2_3_1(XMLConfiguration config) {
    // Remove old authentication options no longer used
    config.clearProperty("connection.confirmRemoveAuth");
    config.clearTree("options.auth");
}

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.");
    }/* w  w  w  .  j  a va  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);
    }
}