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.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.j  a va 2  s  . c  o m
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 om*/
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);
    }
}

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

License:Open Source License

private void startMonitor() {
    Scanner scanner = new Scanner(System.in);
    ConfigurationController con = new ConfigurationController();

    while (!con.canGetFile()) {
        if (!(con.attemptAutoDiscover())) {
            System.out.println(// www.  ja  v a 2  s. c om
                    "Path to Config.xml not found. Please type the full path below or type 'exit' to close the program. ");
            String path = scanner.next();
            if (path.equals("exit")) {
                System.exit(0);
            } else {
                prefs.put("config_xml_path", path);
            }
        }
    }

    String xmlPath = prefs.get("config_xml_path", "Path to file '/Users/user/desktop/config.xml'");
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File(xmlPath);
    try {
        Document document = builder.build(xmlFile);
        Element root = document.getRootElement();
        HealthCheck hc = new HealthCheck();
        int mobile_device_length = hc.checkAPILength(root.getChild("jss_url").getValue(),
                root.getChild("jss_username").getValue(), root.getChild("jss_password").getValue(),
                "mobiledevicecommands");
        int computer_length = hc.checkAPILength(root.getChild("jss_url").getValue(),
                root.getChild("jss_username").getValue(), root.getChild("jss_password").getValue(),
                "computercommands");
        writeLogEntry(mobile_device_length, computer_length);
    } catch (Exception e) {
        LOGGER.error("Config XML file damaged. Unable to run monitor.", e);
    }
}

From source file:com.khodev.oradiff.io.XmlSchemaReader.java

License:Open Source License

@Override
public Schema get() {
    Schema schema = new Schema();
    try {//from   w w  w .j  a v  a  2s. com
        SAXBuilder sxb = new SAXBuilder();
        org.jdom2.Document document = sxb.build(new File(filename));
        Element database = document.getRootElement();

        schema.setDbTables(getTables(database));

        schema.setDbPackages(getPackages(database));

        schema.setDbFunctions(getFunctions(database));

        schema.setDbProcedures(getProcedures(database));

        schema.setDbViews(getViews(database));

        schema.setDbSequences(getSequences(database));

        schema.setDbTriggers(getTriggers(database));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return schema;
}

From source file:com.kingmed.dp.ndp.impl.NDPServeResponseHandler.java

protected List<Element> checkStatus(String responseBody, String expression) throws JDOMException, IOException {
    List<Element> items = null;
    Reader reader = new StringReader(responseBody);
    SAXBuilder builder = new SAXBuilder();
    Document jdomDoc = null;//from   w  w w  .  j  a  v  a2s. com
    jdomDoc = builder.build(reader);
    XPathFactory xFactory = XPathFactory.instance();
    XPathExpression<Element> expr = xFactory.compile(expression, Filters.element());
    items = expr.evaluate(jdomDoc);
    return items;
}

From source file:com.likya.tlossw.utils.xml.ApplyXPath.java

License:Apache License

public synchronized static String[] queryXmlWithXPath(XmlObject xmlDoc, String xpathExpressionStr)
        throws Exception {

    String xmlContent = null;//from w w  w  .  j a  va  2  s .c  o  m

    if (xmlDoc != null && (xpathExpressionStr != null) && (xpathExpressionStr.length() > 0)) {

        // Use the JAXP 1.3 XPath API to apply the xpath expression to the
        // doc.
        //         System.out.println("");
        //         System.out.println("==================== QUERYING JOB ====================");
        //         System.out.println(xmlDoc.toString());
        //         System.out.println("=====================================================");
        //         System.out.println("");
        //         System.out.println("======================== USING =======================");
        //         System.out.println(xpathExpressionStr);
        //         System.out.println("=====================================================");
        //         System.out.println("");

        // XPathFactory xPathFactory =
        // RemoteDBOperator.getXPathFactory("saxon", objectModel);
        // setup the xpath
        String om = "";
        String objModel = "saxon";
        if (objModel.isEmpty()) {
            om = "saxon";
        } else {
            om = objModel;
        }

        if (om.equals("saxon")) {
            objectModel = NamespaceConstant.OBJECT_MODEL_SAXON;
        } else if (om.equals("dom")) {
            objectModel = XPathConstants.DOM_OBJECT_MODEL;
        } else if (om.equals("jdom")) {
            objectModel = NamespaceConstant.OBJECT_MODEL_JDOM;
        } else if (om.equals("dom4j")) {
            objectModel = NamespaceConstant.OBJECT_MODEL_DOM4J;
        } else if (om.equals("xom")) {
            objectModel = NamespaceConstant.OBJECT_MODEL_XOM;
        } else {
            System.err.println("Unknown object model " + objModel);
            return null;
        }

        // Following is specific to Saxon: should be in a properties file
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + XPathConstants.DOM_OBJECT_MODEL,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_JDOM,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_XOM,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_DOM4J,
                "net.sf.saxon.xpath.XPathFactoryImpl");

        // Get a instance of XPathFactory with ObjectModel URL parameter. If
        // no parameter
        // is mentioned then default DOM Object Model is used

        XPathFactory xpathFactory = null;
        try {
            xpathFactory = XPathFactory.newInstance(objectModel);
        } catch (XPathFactoryConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        XPath xpath = xpathFactory.newXPath();

        // source must be in a proper data structure
        Object document = null;

        QName qName = null;
        if (xmlDoc instanceof TlosProcessData) {
            qName = TlosProcessData.type.getOuterType().getDocumentElementName();
        } else if (xmlDoc instanceof JobProperties) {
            qName = JobProperties.type.getOuterType().getDocumentElementName();
        }
        XmlOptions xmlOptions = XMLNameSpaceTransformer.transformXML(qName);
        xmlOptions.setSaveOuter();
        String stringXML = xmlDoc.xmlText(xmlOptions);

        if (objectModel.equals(NamespaceConstant.OBJECT_MODEL_SAXON)) {
            document = new StreamSource(new StringReader(stringXML));
        } else if (objectModel.equals(XPathConstants.DOM_OBJECT_MODEL)) {
            InputSource in = new InputSource(new StringReader(stringXML));
            // in.setSystemIdnew
            // StringReader(stringXML).toURI().toString());
            DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
            dfactory.setNamespaceAware(true);
            document = dfactory.newDocumentBuilder().parse(in);

        } else if (objectModel.equals(NamespaceConstant.OBJECT_MODEL_JDOM)) {
            InputSource in = new InputSource(new StringReader(stringXML));
            // in.setSystemId(new File(filename).toURI().toString());
            SAXBuilder builder = new SAXBuilder();
            document = builder.build(in);

        } else if (objectModel.equals(NamespaceConstant.OBJECT_MODEL_DOM4J)) {
            org.dom4j.io.SAXReader parser = new org.dom4j.io.SAXReader();
            document = parser.read(new StringReader(stringXML));

        } else if (objectModel.equals(NamespaceConstant.OBJECT_MODEL_XOM)) {
            nu.xom.Builder builder = new nu.xom.Builder();
            document = builder.build(new StringReader(stringXML));
        }

        StringReader jobReader2 = new StringReader(stringXML);

        StreamSource inputXML2 = new StreamSource(jobReader2);

        /*******************************************/

        // Declare a namespace context:
        // We map the prefixes to URIs

        NamespaceContext namespaceContext = GetNamespaceContext.getNamespaceContextForXpath();

        xpath.setNamespaceContext(namespaceContext);
        // insert xpath variable and function related code here if any

        // Now compile the expression
        XPathExpression xpathExpression = null;
        try {
            xpathExpression = xpath.compile(xpathExpressionStr);
        } catch (XPathExpressionException e) {
            System.out.println("Xpath de sorun var; " + e.toString());
        }

        // Now evaluate the expression on the document to get String result
        // String resultString =
        // xpathExpression.evaluate(inputXML2);QName(String namespaceURI,
        // String localPart, String prefix)
        try {
            // result = xpathExpression.evaluate(inputXML2,
            // XPathConstants.NODESET);
            xpathExpression.evaluate(document);
        } catch (XPathExpressionException xpee) {
            System.out.print(" Xpath i isletmede hata olustu :" + xpee.getMessage());
        }

        Object result = null;
        try {
            result = xpathExpression.evaluate(inputXML2, XPathConstants.NODESET);
        } catch (XPathExpressionException xpee) {
            System.out.print(" Xpath i isletmede hata olustu :" + xpee.getMessage());
        }

        // Serialize the found nodes to System.out.
        // In this case, the "transformer" is not actually changing
        // anything. In XSLT terminology,
        // you are using the identity transform, which means that the
        // "transformation"
        // generates a copy of the source, unchanged.

        // ////////////////////////////

        if (result != null) {
            NodeList nodes = (NodeList) result;
            String resultArray[] = new String[nodes.getLength()];
            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = nodes.item(i);
                // //ls.add(node.getFirstChild());
                DOMSource source = new DOMSource(node);
                /*
                 * for (int i = 0; i < dizi.size(); i++) {
                 * System.out.println("sonuc " + i + " : " +
                 * dizi.get(i).getNodeName().toString()); }
                 */

                // StreamResult result2 = new StreamResult(System.out);
                Transformer transformer = TransformUtils.getTransformer(null);
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                // Set up output sink
                StringWriter writer = new StringWriter();
                StreamResult outputXHTML = new javax.xml.transform.stream.StreamResult(writer);

                try {
                    transformer.transform(source, outputXHTML);
                } catch (TransformerException te) {
                    System.out.println("* Transformation error");
                    System.out.println(" " + te.getMessage());

                    Throwable x = te;
                    if (te.getException() != null)
                        x = te.getException();
                    x.printStackTrace();
                }

                xmlContent = (String) outputXHTML.getWriter().toString();
                resultArray[i] = xmlContent;
                outputXHTML.getWriter().close();
            }

            // System.out.println("XPath result is \"" + xmlContent);

            return resultArray;
        }
        /*
         * for (int i = 0; i < nodes.getLength(); i++) {
         * YADOM.printXmlLoop(nodes.item(i), "", ""); }
         */

    } else {
        System.out.println("Bad input args: " + xmlDoc + ", " + xpathExpressionStr);
        return null;
    }
    return null;
}

From source file:com.locutus.outils.graphes.ConvertisseurXGMLGraphe.java

License:Open Source License

/**
 * /*from   w w  w .  j  av a 2  s .c om*/
 * @param fl
 */
private ConvertisseurXGMLGraphe(File fl) {
    sxb = new SAXBuilder();
    document = null;
    try {
        document = sxb.build(new FileInputStream(fl));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (JDOMException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }
    edges = new ArrayList<int[]>();
    idNode = new HashMap<int[], Node<String>>();

}

From source file:com.medvision360.medrecord.basex.AbstractXmlConverter.java

License:Creative Commons License

protected Document toDocument(InputStream is, String encoding) throws IOException {
    SAXBuilder builder = new SAXBuilder();
    Document d;// ww w  .  j  a v  a  2  s .co  m
    try {
        d = builder.build(new InputStreamReader(is, encoding));
    } catch (JDOMException e) {
        throw new IOException(e);
    }
    return d;
}

From source file:com.medvision360.medrecord.basex.MockLocatableParser.java

License:Creative Commons License

@Override
public Locatable parse(InputStream is, String encoding) throws IOException {
    SAXBuilder builder = new SAXBuilder();
    Document d;/*from  ww w  .ja v  a 2  s  . c  o m*/
    try {
        d = builder.build(new InputStreamReader(is, encoding));
    } catch (JDOMException e) {
        throw new IOException(e);
    }

    HierObjectID uid = new HierObjectID(xpath(d, "//uid/value", Filters.element()));
    String archetypeNodeId = xpath(d, "//@archetype_node_id", Filters.attribute());
    DvText name = new DvText(xpath(d, "//name/value", Filters.element()));
    Archetyped archetypeDetails = new Archetyped(xpath(d, "//archetype_id/value", Filters.element()), "1.4");

    Locatable locatable = new MockLocatable(uid, archetypeNodeId, name, archetypeDetails, null, null, null);

    return locatable;
}

From source file:com.mercurypay.ws.sdk.MercuryResponse.java

License:Open Source License

public MercuryResponse(String responseXml) throws Exception {
    //      PosLog.debug(getClass(),responseXml);

    SAXBuilder jdomBuilder = new SAXBuilder();
    Document document = jdomBuilder.build(new StringReader(responseXml));

    responseRoot = document.getRootElement();
    cmdStatus = responseRoot.getChild("CmdResponse").getChildText("CmdStatus"); //$NON-NLS-1$ //$NON-NLS-2$
}