Example usage for org.jdom2 Document getRootElement

List of usage examples for org.jdom2 Document getRootElement

Introduction

In this page you can find the example usage for org.jdom2 Document getRootElement.

Prototype

public Element getRootElement() 

Source Link

Document

This will return the root Element for this Document

Usage

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

License:Open Source License

private boolean privateBuild(String schemaFileName, Document document, boolean topLevel) throws Exception {
    int schemaFileNamesIdx = 0;

    String attributeValue;//ww  w.j a  v a 2 s  .  c  o  m
    XSDElement thisDocRoot;

    // get the root element of the XML - this should be <schema>, or we wont process the document 

    Element xsdRoot = document.getRootElement();
    String elementName = xsdRoot.getName();

    if (elementName.equals(SCHEMA) == false) {
        throw new Exception("The root element of the XML document is not <" + SCHEMA + ">");
    }

    id = xsdRoot.getAttributeValue(XSDSchema.ID_ATT);
    targetNamespace = xsdRoot.getAttributeValue(XSDSchema.TARGNAMSP_ATT);

    try {
        cache.pushNamespaces(schemaFileName);
    } catch (Exception ex) {
        log.fatal("Exception caching namespaces: " + ex.toString());
        return (false);
    }

    /** Go through the document and find any include or import elements... **/

    for (Element element : xsdRoot.getChildren()) {
        elementName = element.getName();

        if (elementName.equals(IMPORT) || elementName.equals(INCLUDE)) {
            attributeValue = element.getAttributeValue(SCHEMALOC_ATT);
            if (cache.schemaCached(attributeValue) == true) {
                log.debug("Schema already cached... ignoring");
                continue;
            }

            log.debug(elementName + " schema [" + attributeValue + "]");

            String importSchemaName = null;

            /* If the schema is relative to the current schema then work out the absolute name... */

            if (attributeValue.startsWith("..") == true) {

                String[] currentSchemaPath = ((String) schemaFileNames.get(schemaFileNamesIdx))
                        .split("[/\\\\]");
                String[] importSchemaFile = attributeValue.split("[/\\\\]");
                int idx = 0;
                int n = 0;
                StringBuffer realImportName = new StringBuffer();

                while (importSchemaFile[n].equals("..")) {
                    idx++;
                    n++;
                }

                for (n = 0; n < (currentSchemaPath.length - 1) - idx; n++) {
                    realImportName.append(currentSchemaPath[n]);
                    realImportName.append(File.separator);
                }

                for (n = idx; n < importSchemaFile.length; n++) {
                    realImportName.append(importSchemaFile[n]);
                    if (n < importSchemaFile.length - 1) {
                        realImportName.append(File.separator);
                    }
                }

                importSchemaName = realImportName.toString();
            } else { /* schema in current directory... */

                File sf = new File((String) schemaFileNames.get(schemaFileNamesIdx));
                String dirName = sf.getParent();
                importSchemaName = dirName + File.separator + attributeValue;
            }

            Document doc = builder.build(new FileReader(importSchemaName));

            schemaFileNames.add(importSchemaName);
            schemaFileNamesIdx++;

            cache.putSchema(attributeValue, document);
            privateBuild(importSchemaName, doc, false);

            schemaFileNames.remove(schemaFileNamesIdx);
            schemaFileNamesIdx--;
        }

    }

    // do it twice... so that all predefined types are picked up, no matter what order they are defined in...
    // @todo I know it is clunky, and when I get time I will make it scan for types (and imports etc!) first then build the definition.....

    for (int x = 0; x < 2; x++) {

        /** iterate all of the child elements of schema **/

        for (Element element : xsdRoot.getChildren()) {
            elementName = element.getName();
            log.debug("" + indent + ": " + "Element <" + elementName + ">");

            if (elementName.equals(ELEMENT)) {
                thisDocRoot = new XSDElement(indent);
                if (thisDocRoot.build(element, cache, "") != true) {
                    log.fatal("Error processing the schema");
                    return (false);
                }

                if (topLevel == true) {
                    topLevelElements.put(elementName, thisDocRoot);
                }
            } else if (elementName.equals(SIMPLETYPE)) {
            } else if (elementName.equals(COMPLEXTYPE)) {
                XSDElementTypeComplex complexType = new XSDElementTypeComplex(indent);
                if (complexType.build(element, cache, "") != true) {
                    log.fatal("Error building a complex type");
                    throw new Exception("Error building a complex type");
                }
                log.debug("Adding type <" + complexType.getName() + "> to type cache");
                cache.putType(complexType.getName(), complexType);

                if (topLevel == true) {
                    topLevelTypes.put(complexType.getName(), complexType);
                }

            } else if (elementName.equals(GROUP)) {
                XSDGroupType group = new XSDElementGroup(indent);
                if (group.build(element, cache, "") != true) {
                    log.fatal("Error building a group");
                    return (false);
                }
            } else if (elementName.equals(ATTRIBUTEGROUP)) {
                XSDAttributeGroup attGroup = new XSDAttributeGroup();
                if (attGroup.build(element, cache, "") != true) {
                    log.warn("Error building an attribute group");
                    continue;
                }
            } else if (elementName.equals(ATTRIBUTE)) {
                XSDAttribute attribute = new XSDAttribute();
                if (attribute.build(element, cache, "") != true) {
                    log.warn("Error building an attribute object");
                    continue;
                }
            } else if (elementName.equals(IMPORT) || elementName.equals(INCLUDE)) {
                // do nothing - these have already been processed...
            } else {
                log.debug("" + indent + ": " + "Unexpected element <" + elementName + "> found and ignored");
            }
        } // end for all child elements of the schema root

    }

    cache.popNamespaces();

    return (true);

}

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

License:Open Source License

private void fillMandatoryChildren(XSDElement element, String parentSpec, Document doc) {
    for (XSDElement el : element.getChildren()) {
        String path = parentSpec + "." + el.getName();
        if (el.isMandatory()) {
            addMandatoryElementToDocument(el, path, doc.getRootElement());
        }//from  w  w w  .  j  a va2s  .  c  o  m
        fillMandatoryChildren(el, path, doc);
    }

    /** Add any mandatory attributes... **/
    List<XSDAttributeType> attList = element.getAttributeList();

    if (attList != null) {
        for (XSDAttributeType att : attList) {
            if (((XSDAttribute) att).isMandatory()) {
                addMandatoryElementToDocument(element, parentSpec + ".@" + att.getName(), doc.getRootElement());
            }
        }
    }

}

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

License:Open Source License

public Element setScript(String script) throws JDOMException, IOException, ParseException {
    Element scriptRoot = null;// ww w. j  a  v  a 2s .  c  om

    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.izforge.izpack.util.xmlmerge.merge.DefaultXmlMerge.java

License:Open Source License

/**
 * Performs the actual merge./*  w w  w.j ava 2  s . c  o m*/
 *
 * @param docs The documents to merge. The first doc is assumed to be the original one to apply patches against.
 * @return The merged result document
 * @throws AbstractXmlMergeException If an error occurred during the merge
 */
private Document doMerge(Document[] docs) throws AbstractXmlMergeException {
    Document originalDoc = docs[0];
    Element origRootElement = originalDoc.getRootElement();

    for (int i = 1; i < docs.length; i++) {
        Element comparedRootElement = docs[i].getRootElement();

        Document output = new Document();
        if (originalDoc.getDocType() != null) {
            output.setDocType((DocType) originalDoc.getDocType().clone());
        }
        output.setRootElement(new Element("root"));
        Element outputRootElement = output.getRootElement();

        m_rootMergeAction.perform(origRootElement, comparedRootElement, outputRootElement);

        Element root = (Element) outputRootElement.getChildren().get(0);
        root.detach();

        sortRootChildrenRecursive(root);

        originalDoc.setRootElement(root);
    }

    return originalDoc;
}

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

License:Open Source License

/**
 * Constructor that optionally loads the XML file.
 *///from   w  ww  .  ja v  a  2 s.co m
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  v  a 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// w w w  .  j a  v  a 2  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./*w w w  . ja v a 2s .co m*/
 * @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;
    }
}

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

License:Open Source License

/**
 * Method that counts the elements in a JSS and writes to the JSON string.
 *///from w  w  w.  ja va  2s .c om
public void parseObjectCount(String Object, String url, String username, String password,
        JSONBuilder jsonString) {
    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> objects = doc.getRootElement().getChildren();
        int count = parseMultipleObjects(objects).size();

        jsonString.addObject(Object);
        jsonString.addFinalElement("count", Integer.toString(count));
        jsonString.closeObject();
    } catch (Exception e) {
        e.printStackTrace();
        System.out.print(e);
    }

}

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

License:Open Source License

/**
 * This method gets all of the Computer, Mobile or User Smart Groups
 * by ID, then tallies the Criteria and Nested counts.
 * Adds problem groups to the JSON String.
 *//*from w w w  .jav  a2 s.  c o m*/
public void parseGroupObjects(String Object, String url, String username, String password,
        JSONBuilder jsonString) {
    ConfigurationController con = new ConfigurationController(true);
    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> groups = doc.getRootElement().getChildren();
        //Get all of the computer group IDS
        ArrayList<String> group_ids = parseMultipleObjects(groups);
        jsonString.addArrayObject(Object);
        int problems_added = 0;
        for (int c = 0; c < group_ids.size(); c++) {
            String group_info = api.doGet(url + "/JSSResource/" + Object + "/id/" + group_ids.get(c));
            Document account_as_xml = sb.build(new ByteArrayInputStream(group_info.getBytes("UTF-8")));
            List<Element> group = account_as_xml.getRootElement().getChildren();

            String name = group.get(1).getContent().get(0).getValue();
            int nested_groups_count = 0;
            int crit_count = 0;

            //Criteria has a different XML index value in each object for some reason.
            if (Object.equals("computergroups")) {
                crit_count = Integer.parseInt(group.get(4).getContent().get(0).getValue());
            } else if (Object.equals("mobiledevicegroups")) {
                crit_count = Integer.parseInt(group.get(3).getContent().get(0).getValue());
            } else {
                crit_count = Integer.parseInt(group.get(5).getContent().get(0).getValue());
            }
            //Loop through all of the Crit and check for nested groups.
            for (int cri = 1; cri < group.get(4).getContent().size(); cri++) {
                String value = group.get(4).getContent().get(1).getValue();
                if (value.contains("Computer Group") || value.contains("Mobile Device Group")
                        || value.contains("User Group")) {
                    nested_groups_count++;
                }
            }
            //Should only add problem groups
            if (nested_groups_count != 0 || crit_count > Integer
                    .parseInt(con.getValue("configurations,smart_groups", "criteria_count")[0])) {
                jsonString.openArrayObject();
                jsonString.addElement("id", group.get(0).getContent().get(0).getValue());
                jsonString.addElement("name", name);
                jsonString.addElement("nested_groups_count", Integer.toString(nested_groups_count));
                jsonString.addFinalElement("criteria_count", Integer.toString(crit_count));
                jsonString.closeObject();
                problems_added++;
            }
        }
        if (problems_added > 0) {
            //Need to remove the comma off of the final object in the group object
            jsonString.removeComma();
        }
        jsonString.closeArrayObject();
        //Print an error making the the group api call.
    } catch (Exception e) {
        jsonString.closeArrayObject();
        e.printStackTrace();
        System.out.println("Error with group: " + e);
    }
}