Example usage for org.jdom2.input SAXBuilder SAXBuilder

List of usage examples for org.jdom2.input SAXBuilder SAXBuilder

Introduction

In this page you can find the example usage for org.jdom2.input SAXBuilder SAXBuilder.

Prototype

public SAXBuilder() 

Source Link

Document

Creates a new JAXP-based SAXBuilder.

Usage

From source file:com.googlecode.mipnp.extension.rhythmbox.RhythmboxExtension.java

License:Open Source License

@ExtensionMethod(ExtensionMethodType.LOAD)
public void loadExtension() throws ClassNotFoundException {
    this.db = DB_FILE;
    this.builder = new SAXBuilder();
}

From source file:com.googlesource.gerrit.plugins.manifest.ManifestXml.java

License:Apache License

public ManifestXml(String xml) throws IOException, ParserConfigurationException, SAXException, JDOMException {
    // Insert a unique identifier for entity definitions to prevent them from
    // getting expanded during the parse
    genReplacementText(xml);// ww  w  . ja v a2  s  . c o  m
    xml = xml.replaceAll("&([^;]*);", replacementText + "$1;");

    SAXBuilder builder = new SAXBuilder();
    builder.setSAXHandlerFactory(new SAXHandlerFactory() {
        @Override
        public SAXHandler createSAXHandler(JDOMFactory jdomFactory) {
            return new SAXHandler() {
                @Override
                public void attributeDecl(String eName, String aName, String type, String valueDefault,
                        String value) {
                    dtdAttributes.add(new DTDAttribute(eName, aName, type, valueDefault, value));
                    super.attributeDecl(eName, aName, type, valueDefault, value);
                }
            };
        }
    });
    builder.setExpandEntities(false);
    doc = builder.build(new InputSource(new StringReader(xml)));
}

From source file:com.htm.utils.Utilities.java

License:Open Source License

public static Document getXMLFromString(String xml) {

    if (xml == null) {
        return null;
    }/*from ww  w . ja  v  a2 s . c  o  m*/

    SAXBuilder builder = new SAXBuilder();
    try {
        return builder.build(new StringReader(xml));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:com.init.octo.schema.XSDSchema.java

License:Open Source License

/**
 * Constructor/*from  w  w w.  j  a v a  2s .c om*/
 */

public XSDSchema(Properties properties, int indent) {
    this.cache = new XSDCache();
    this.log = Logger.getLogger(XSDSchema.class.getName());
    this.root = null;
    this.indent = indent;
    this.schemaDefined = false;
    this.builder = new SAXBuilder();
}

From source file:com.init.octo.XMLtoSQL.java

License:Open Source License

public void setInputXML(String inxml) throws JDOMException, IOException {
    // convert the XML into a jdom structure...
    SAXBuilder xmlReader = new SAXBuilder();
    xmlInput = xmlReader.build(new ByteArrayInputStream(inxml.getBytes()));
}

From source file:com.init.octo.XMLtoSQL.java

License:Open Source License

public Element setScript(String script) throws JDOMException, IOException, ParseException {
    Element scriptRoot = null;//from  w w  w. java 2s .  c o  m

    if (getFileType(script).equals("application/xml")) {
        SAXBuilder xmlReader = new SAXBuilder();
        Document doc = xmlReader.build(new ByteArrayInputStream(script.getBytes()));
        scriptRoot = doc.getRootElement();
    } else {
        XMLtoSQLScript parser = new XMLtoSQLScript(new StringReader(script));
        //         parser.parseUpdateScript();
        scriptRoot = parser.getParsedDocumentRoot();
    }

    return scriptRoot;
}

From source file:com.jamfsoftware.jss.healthcheck.controller.ConfigurationController.java

License:Open Source License

/**
 * Constructor that optionally loads the XML file.
 *///from   w w w.j  av  a 2  s. c om
public ConfigurationController(boolean shouldLoadXML) {
    if (shouldLoadXML) {
        this.configurationPath = this.prefs.get("configurationPath",
                "Path to file '/Users/user/desktop/config.xml'");
        if (isCustomConfigurationPath() && canGetFile()) {
            try {
                SAXBuilder builder = new SAXBuilder();
                File xmlFile = new File(this.configurationPath);
                Document document = builder.build(xmlFile);
                this.root = document.getRootElement();
            } catch (Exception e) {
                LOGGER.error("", e);
            }
        }
    }
}

From source file:com.jamfsoftware.jss.healthcheck.controller.ConfigurationController.java

License:Open Source License

private boolean canGetFile(File file) {
    if (file.exists()) {
        SAXBuilder builder = new SAXBuilder();
        try {/*from   w w w . j  a  va  2  s  .  co  m*/
            Document document = builder.build(file);
            Element root = document.getRootElement();
            root.getChild("jss_url").getValue();
            return true;
        } catch (Exception e) {
            LOGGER.error("", e);
        }
    }

    return false;
}

From source file:com.jamfsoftware.jss.healthcheck.HealthCheck.java

License:Open Source License

/**
 * Hit a given API Object, parse the XML returned, then add the results
 * to the JSON String. Also handles parsing of the JSS Summary.
 * @param Object An API Object as a String
 * @param url JSS URL//from   w  ww.  j  a  v a2  s  .  c  o m
 * @param username JSS Username
 * @param password JSS Password
 * @param jsonString The running JSON String
 */
public void APIObject(String Object, String url, String username, String password, JSONBuilder jsonString) {
    HTTPController api = new HTTPController(username, password);
    //Create XML Object Parser
    SAXBuilder sb = new SAXBuilder();
    //Build the JSON
    try {
        //Send an API GET and store the returned String.
        String result = "";
        //Create a new XML element.
        Document doc = null;
        //If it's not the Summary Object, build the XML doc from the result of the API call.
        if (!Object.equals("summarydata")) {
            try {
                result = replaceSpecChars(api.doGet(url + "/JSSResource/" + Object));
                doc = sb.build(new ByteArrayInputStream(result.getBytes("UTF-8")));
            } catch (Exception e) {
                System.out.println("Unable to parse XML document for object: " + Object);
            }
            //Add the JSS Summary items to the JSON
        } else {
            System.out.println("Parsing JSS Summary..");
            //Do all of the summary checks
            jsonString.addObject("password_strength");
            String[] password_info = this.summary.getPasswordInformation();
            jsonString.addElement("uppercase?", password_info[0]);
            jsonString.addElement("lowercase?", password_info[1]);
            jsonString.addElement("number?", password_info[2]);
            jsonString.addFinalElement("spec_chars?", password_info[3]);
            jsonString.closeObject();

            String[] change_info = this.summary.getChangeManagementInfo();
            jsonString.addObject("changemanagment");
            jsonString.addElement("isusinglogfile", change_info[0]);
            jsonString.addFinalElement("logpath", change_info[1]);
            jsonString.closeObject();

            String[] tomcat_info = this.summary.getTomcatCert();
            jsonString.addObject("tomcat");
            jsonString.addElement("ssl_cert_issuer", tomcat_info[0]);
            jsonString.addFinalElement("cert_expires", tomcat_info[1]);
            jsonString.closeObject();

            jsonString.addObject("logflushing");
            jsonString.addFinalElement("log_flush_time", this.summary.getLogFlushingInfo());
            jsonString.closeObject();

            String[] push_cert_info = this.summary.getPushCertInfo();
            jsonString.addObject("push_cert_expirations");
            jsonString.addElement("mdm_push_cert", push_cert_info[0]);
            jsonString.addFinalElement("push_proxy", push_cert_info[1]);
            jsonString.closeObject();

            jsonString.addObject("loginlogouthooks");
            jsonString.addFinalElement("is_configured", this.summary.loginLogoutHooksEnabled().toString());
            jsonString.closeObject();

            try {
                String[] device_table_counts = this.summary.getTableRowCounts().split(",");
                jsonString.addObject("device_row_counts");
                jsonString.addElement("computers", device_table_counts[0]);
                jsonString.addElement("computers_denormalized", device_table_counts[1]);
                jsonString.addElement("mobile_devices", device_table_counts[2]);
                jsonString.addFinalElement("mobile_devices_denormalized", device_table_counts[3]);
                jsonString.closeObject();
            } catch (Exception e) {
                System.out.println("Unable to parse table row counts from the JSS Summary.");
            }
        }
        if (Object.equals("activationcode")) {
            List<Element> activationcode = doc.getRootElement().getChildren();
            jsonString.addObject("activationcode");
            jsonString.addElement("expires", this.summary.getActivationCodeExpiration());
            jsonString.addFinalElement("code", activationcode.get(1).getValue());
            jsonString.closeObject();
        } else if (Object.equals("computercheckin")) {
            List<Element> computercheckin = doc.getRootElement().getChildren();
            jsonString.addObject("computercheckin");
            jsonString.addFinalElement("frequency", computercheckin.get(0).getValue());
            jsonString.closeObject();
            //Get all of the LDAP servers and parse each one. Can take awhile if a lot of LDAP servers.
        } else if (Object.equals("ldapservers")) {

            List<Element> ldapservers = doc.getRootElement().getChildren();
            //Get all of the computer group IDS
            ArrayList<String> ldap_servers = parseMultipleObjects(ldapservers);
            jsonString.addArrayObject("ldapservers");
            for (int l = 0; l < ldap_servers.size(); l++) {
                String ldap_info = api.doGet(url + "/JSSResource/ldapservers/id/" + ldap_servers.get(l));
                Document account_as_xml = sb.build(new ByteArrayInputStream(ldap_info.getBytes("UTF-8")));
                List<Element> serv = account_as_xml.getRootElement().getChildren();
                jsonString.openArrayObject();
                jsonString.addElement("id", serv.get(0).getContent().get(0).getValue());
                jsonString.addElement("name", serv.get(0).getContent().get(1).getValue());
                jsonString.addElement("type", serv.get(0).getContent().get(3).getValue());
                jsonString.addFinalElement("address", serv.get(0).getContent().get(2).getValue());
                jsonString.closeObject();
            }
            if (ldap_servers.size() > 0) {
                //Remove a comma from the last element
                jsonString.removeComma();
            }
            jsonString.closeArrayObject();
        } else if (Object.equals("gsxconnection")) {
            List<Element> gsxconnection = doc.getRootElement().getChildren();
            jsonString.addObject("gsxconnection");
            if (gsxconnection.get(0).getValue().equals("true")) {
                jsonString.addElement("status", "enabled");
                jsonString.addFinalElement("uri", gsxconnection.get(5).getValue());
            } else {
                jsonString.addFinalElement("status", "disabled");
            }
            jsonString.closeObject();
        } else if (Object.equals("managedpreferenceprofiles")) {
            List<Element> managedpreferenceprofiles = doc.getRootElement().getChildren();
            jsonString.addObject("managedpreferenceprofiles");
            if (!(managedpreferenceprofiles.get(0).getValue().equals("0"))) {
                jsonString.addFinalElement("status", "enabled");
            } else {
                jsonString.addFinalElement("status", "disabled");
            }
            jsonString.closeObject();
            //Method to parse the group info, since they all follow the same format.
            //Gets all of the groups by ID, then parses each one. Can take awhile if the JSS contains a lot of groups.
        } else if (Object.equals("computergroups") || Object.equals("mobiledevicegroups")
                || Object.equals("usergroups")) {
            parseGroupObjects(Object, url, username, password, jsonString);
        } else
        //Looping through the VPP Accounts and checking the token expire date. Can take awhile if a lot of VPP accounts.
        if (Object.equals("vppaccounts")) {
            List<Element> vpp_accounts = doc.getRootElement().getChildren();
            //Get all of the vpp_account IDS
            ArrayList<String> vpp_account_ids = parseMultipleObjects(vpp_accounts);
            //Get the current date
            Date date = new Date();
            jsonString.addArrayObject("vppaccounts");
            //Loop through all of the IDS and get individual account information
            for (int a = 0; a < vpp_account_ids.size(); a++) {
                String account_info = api.doGet(url + "/JSSResource/vppaccounts/id/" + vpp_account_ids.get(a));
                Document account_as_xml = sb.build(new ByteArrayInputStream(account_info.getBytes("UTF-8")));
                List<Element> acc = account_as_xml.getRootElement().getChildren();
                //Get the exp date
                String exp_date = acc.get(5).getContent().get(0).getValue();
                jsonString.openArrayObject();
                jsonString.addElement("id", acc.get(0).getContent().get(0).getValue());
                jsonString.addElement("name", acc.get(1).getContent().get(0).getValue());
                jsonString.addFinalElement("days_until_expire",
                        Long.toString(calculateDays(dateFormat.format(date), exp_date)));
                jsonString.closeObject();
            }
            if (vpp_accounts.size() > 1) {
                jsonString.removeComma();
            }
            jsonString.closeArrayObject();
            //Get each script by ID and then parse each one
            //Can take a while if the JSS contains a lot of scripts.
        } else if (Object.equals("scripts")) {
            List<Element> scripts = doc.getRootElement().getChildren();
            ArrayList<String> script_ids = parseMultipleObjects(scripts);
            ArrayList<String> scripts_needing_update = new ArrayList<>();
            //Get all of the scripts
            jsonString.addArrayObject("scripts_needing_update");
            for (int s = 0; s < script_ids.size(); s++) {
                String script_info = api.doGet(url + "/JSSResource/scripts/id/" + script_ids.get(s));
                Document script_as_xml = sb.build(new ByteArrayInputStream(script_info.getBytes("UTF-8")));
                List<Element> script = script_as_xml.getRootElement().getChildren();
                //Get the script name and the actual content of the script
                String script_name = "";
                if (script.size() > 0) {
                    script_name = script.get(1).getContent().get(0).getValue();
                }
                String script_code = "";
                //Check to make the script actually has contents
                if (script.size() >= 10) {
                    if (script.get(9).getContent().size() > 0) {
                        script_code = script.get(9).getContent().get(0).getValue();
                    }
                }
                //Check for the old binary location, if it is present, add it to an arraylist.
                if (script_code.toLowerCase().contains("/usr/sbin/jamf")
                        || script_code.toLowerCase().contains("rm -rf")
                        || script_code.toLowerCase().contains("jamf recon")) {
                    scripts_needing_update.add(script_name);
                }
            }

            //Check if there are any scripts that use the old location
            if (scripts_needing_update.size() > 0) {
                for (int s = 0; s < scripts_needing_update.size(); s++) {
                    jsonString.openArrayObject();
                    jsonString.addFinalElement("name", scripts_needing_update.get(s));
                    jsonString.closeObject();
                }
                jsonString.removeComma();
            }

            jsonString.closeArrayObject();
            //Get each printer by ID and then parse each one individually.
            //Can take a while if a lot of printers are present.
        } else if (Object.equals("printers")) {
            List<Element> printers = doc.getRootElement().getChildren();
            ArrayList<String> printer_ids = parseMultipleObjects(printers);
            jsonString.addArrayObject("printer_warnings");
            int xerox_count = 0;
            for (int p = 0; p < printer_ids.size(); p++) {
                String printer_info = api.doGet(url + "/JSSResource/printers/id/" + printer_ids.get(p));
                Document printer_as_xml = sb.build(new ByteArrayInputStream(printer_info.getBytes("UTF-8")));
                List<Element> printer = printer_as_xml.getRootElement().getChildren();
                if (printer.get(6).getContent().size() != 0) {
                    String printer_model = printer.get(6).getContent().get(0).getValue();
                    //Warn of large Xerox drivers.
                    if (printer_model.toLowerCase().contains("xerox")) {
                        xerox_count++;
                        jsonString.openArrayObject();
                        jsonString.addFinalElement("model", printer_model);
                        jsonString.closeObject();
                    }
                }
            }
            if (xerox_count > 0) {
                jsonString.removeComma();
            }
            jsonString.closeArrayObject();
            //Check the count of several JSS items.
        } else if (Object.equals("computerextensionattributes")) {
            parseObjectCount(Object, url, username, password, jsonString);
        } else if (Object.equals("mobiledeviceextensionattributes")) {
            parseObjectCount(Object, url, username, password, jsonString);
        } else if (Object.equals("computerconfigurations")) {
            parseObjectCount(Object, url, username, password, jsonString);
        } else if (Object.equals("networksegments")) {
            parseObjectCount(Object, url, username, password, jsonString);
            //Get every policy by ID and then parse each one.
            //Can take a while if a lot of policies are present.
        } else if (Object.equals("policies")) {
            List<Element> policies = doc.getRootElement().getChildren();
            ArrayList<String> policy_ids = parseMultipleObjects(policies);
            jsonString.addArrayObject("policies_with_issues");
            int issue_policy_count = 0;
            for (int p = 0; p < policy_ids.size(); p++) {
                String policy_info = api.doGet(url + "/JSSResource/policies/id/" + policy_ids.get(p));
                Document policy_info_as_xml = sb.build(new ByteArrayInputStream(policy_info.getBytes("UTF-8")));
                List<Element> policy = policy_info_as_xml.getRootElement().getChildren();
                //A policy that ongoing and updates inventory AND  is triggered on a checkin
                if ((policy.get(9).getContent().get(0).getValue().equals("true"))
                        && (policy.get(0).getContent().get(11).getValue().equals("Ongoing")
                                && policy.get(0).getContent().get(4).getValue().equals("true"))) {
                    jsonString.openArrayObject();
                    jsonString.addElement("name", policy.get(0).getContent().get(1).getValue());
                    jsonString.addElement("ongoing",
                            Boolean.toString(policy.get(9).getContent().get(0).getValue().equals("true")
                                    && policy.get(0).getContent().get(11).getValue().equals("Ongoing")));
                    jsonString.addFinalElement("checkin_trigger",
                            Boolean.toString(policy.get(0).getContent().get(4).getValue().equals("true")));
                    jsonString.closeObject();
                    issue_policy_count++;
                }
            }
            if (issue_policy_count > 0) {
                jsonString.removeComma();
            }
            jsonString.closeArrayObject();
            //List the SMTP Server.
        } else if (Object.equals("smtpserver")) {
            List<Element> smtp_server = doc.getRootElement().getChildren();
            jsonString.addObject("smtpserver");
            if (smtp_server.get(10).getContent().size() > 0) {
                jsonString.addElement("server", smtp_server.get(1).getContent().get(0).getValue());
                jsonString.addFinalElement("sender_email", smtp_server.get(10).getContent().get(0).getValue());
            }
            jsonString.closeFinalObject();
        }
        //Catch all API Call errors and print the error.
    } catch (Exception e) {
        //Should still close JSON objects
        if (Object.equals("activationcode") || Object.equals("computercheckin")
                || Object.equals("gsxconnection") || Object.equals("managedpreferenceprofiles")) {
            jsonString.closeObject();
        } else if (Object.equals("ldapservers") || Object.equals("vppaccounts") || Object.equals("printers")
                || Object.equals("scripts") || Object.equals("policies")) {
            jsonString.closeArrayObject();
        } else if (Object.equals("smtpserver")) {
            jsonString.closeFinalObject();
        }
        System.out.println("Error making API call: " + e);
        e.printStackTrace();
    }
    //System.out.println(jsonString.returnJSON());
}

From source file:com.jamfsoftware.jss.healthcheck.HealthCheck.java

License:Open Source License

/**
 * Checks the length of an object in the JSS via the API.
 * @param url JSS URL.//from  w w w .ja  va  2s . c om
 * @param username JSS Username.
 * @param password JSS Password.
 * @param object JSS API Object.
 * @return size of the API Object.
 */
public int checkAPILength(String url, String username, String password, String object) {
    try {
        HTTPController api = new HTTPController(username, password);
        SAXBuilder sb = new SAXBuilder();
        String result = api.doGet(url + "/JSSResource/" + object);
        Document doc = sb.build(new ByteArrayInputStream(result.getBytes("UTF-8")));
        List<Element> returned = doc.getRootElement().getChildren();
        return returned.size() - 1;
    } catch (Exception e) {
        System.out.println("Error making API Call: " + e);
        e.printStackTrace();
        return 0;
    }
}