Example usage for org.jdom2.input SAXBuilder build

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

Introduction

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

Prototype

@Override
public Document build(final String systemId) throws JDOMException, IOException 

Source Link

Document

This builds a document from the supplied URI.

Usage

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;/* ww  w  . j a  v a2  s  .c om*/
    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.kixeye.kixmpp.KixmppWebSocketCodec.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
    WebSocketFrame frame = (WebSocketFrame) msg;

    ByteBuf content = frame.retain().content();
    String frameString = content.toString(StandardCharsets.UTF_8);

    if (logger.isDebugEnabled()) {
        logger.debug("Received: [{}]", frameString);
    }/*ww w  .  j ava2 s .  c o  m*/

    if (frameString.startsWith("<?xml")) {
        frameString = frameString.replaceFirst("<\\?xml.*?\\?>", "");
    }

    if (frameString.startsWith("<stream:stream")) {
        out.add(new KixmppStreamStart(null, true));
    } else if (frameString.startsWith("</stream:stream")) {
        out.add(new KixmppStreamEnd());
    } else {

        SAXBuilder saxBuilder = new SAXBuilder(readerFactory);
        Document document = saxBuilder.build(new ByteBufInputStream(content));

        Element element = document.getRootElement();

        out.add(element);
    }

}

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 ww .j av a2s  .c  om

    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.medvision360.medrecord.basex.AbstractXmlConverter.java

License:Creative Commons License

protected Document toDocument(InputStream is, String encoding) throws IOException {
    SAXBuilder builder = new SAXBuilder();
    Document d;//from  w w  w.  j av  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   w ww.  jav a2s . c  om*/
    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$
}

From source file:com.move.in.nantes.cars.ParkingParser.java

private static List<Parking> parseXml() {
    List<Parking> listPakings = new ArrayList<Parking>();

    try {//  w  w w  .  j  ava 2s  . co  m
        SAXBuilder saxb = new SAXBuilder();
        File file = new File("WEB-INF/json/Parking.xml");

        Document doc = saxb.build(file);
        Element root = doc.getRootElement();
        List<Element> locations = root.getChildren("data").get(0).getChildren("element");

        for (int i = 0; i < locations.size(); i++) {
            Element elem = locations.get(i);

            if (elem.getChildText("CATEGORIE").equalsIgnoreCase("1001")) {

                String name = elem.getChild("geo").getChildText("name");

                Coordinates coordinates = getCoordinates(elem.getChildText("_l"));

                String postalCode = elem.getChildText("CODE_POSTAL");
                String city = elem.getChildText("COMMUNE");
                String address = elem.getChildText("ADRESSE");

                listPakings.add(new Parking(name, coordinates, postalCode, city, address));
            }
        }
    } catch (JDOMException ex) {
        Logger.getLogger(ParkingParser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ParkingParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return listPakings;
}

From source file:com.musala.cron.RefreshDbTask.java

License:Apache License

@Scheduled(fixedRate = 300000)
@Transactional//from  w w  w. j  a  v a2  s  .co  m
public void printMe() {
    logger.info("Cron task is started");

    for (Site rssFeedSite : siteService.findAll()) {
        logger.info("--------------> Reading information for site: " + rssFeedSite.getRssLink());
        SAXBuilder builder = new SAXBuilder();
        Document doc = null;

        try {
            doc = builder.build(new URL(rssFeedSite.getRssLink()));
            if (rssFeedSite.getLastVisitDateTag() != null) {
                Element root = doc.getRootElement();
                ElementFilter filter = new ElementFilter(rssFeedSite.getLastVisitDateTag());

                String currentLastVisitedDate = null;

                for (Element c : root.getDescendants(filter)) {
                    currentLastVisitedDate = c.getTextNormalize();
                }

                if (currentLastVisitedDate != null
                        && currentLastVisitedDate.equals(rssFeedSite.getLastVisitDate())) {
                    logger.info("--------------> Rss {} is not changed", rssFeedSite.getRssLink());
                } else {
                    logger.info("--------------> Rss {} is changed", rssFeedSite.getRssLink());
                    rssFeedSite.setLastVisitDate(currentLastVisitedDate);
                    subject.processRss(rssFeedSite);
                }
            }
        } catch (JDOMException | IOException e) {
            logger.warn("Error occurred during reading of rss", e);
        }
    }
}

From source file:com.novell.ldapchai.impl.edir.NmasResponseSet.java

License:Open Source License

static List<Challenge> parseNmasPolicyXML(final String str, final Locale locale)
        throws IOException, JDOMException {
    final List<Challenge> returnList = new ArrayList<Challenge>();

    final Reader xmlreader = new StringReader(str);
    final SAXBuilder builder = new SAXBuilder();
    final Document doc = builder.build(xmlreader);
    final boolean required = doc.getRootElement().getName().equals("RequiredQuestions");

    for (Iterator qIter = doc.getDescendants(new ElementFilter("Question")); qIter.hasNext();) {
        final Element loopQ = (Element) qIter.next();
        final int maxLength = StringHelper.convertStrToInt(loopQ.getAttributeValue("MaxLength"), 255);
        final int minLength = StringHelper.convertStrToInt(loopQ.getAttributeValue("MinLength"), 1);

        final String challengeText = readDisplayString(loopQ, locale);

        final Challenge challenge = new ChaiChallenge(required, challengeText, minLength, maxLength, true, 0,
                false);/* w w w.  ja va 2  s .c  o m*/
        returnList.add(challenge);
    }

    for (Iterator iter = doc.getDescendants(new ElementFilter("UserDefined")); iter.hasNext();) {
        final Element loopQ = (Element) iter.next();
        final int maxLength = StringHelper.convertStrToInt(loopQ.getAttributeValue("MaxLength"), 255);
        final int minLength = StringHelper.convertStrToInt(loopQ.getAttributeValue("MinLength"), 1);
        final Challenge challenge = new ChaiChallenge(required, null, minLength, maxLength, false, 0, false);
        returnList.add(challenge);
    }

    return returnList;
}

From source file:com.novell.ldapchai.impl.edir.NmasResponseSet.java

License:Open Source License

static ChallengeSet parseNmasUserResponseXML(final String str)
        throws IOException, JDOMException, ChaiValidationException {
    final List<Challenge> returnList = new ArrayList<Challenge>();

    final Reader xmlreader = new StringReader(str);
    final SAXBuilder builder = new SAXBuilder();
    final Document doc = builder.build(xmlreader);

    final Element rootElement = doc.getRootElement();
    final int minRandom = StringHelper.convertStrToInt(rootElement.getAttributeValue("RandomQuestions"), 0);

    final String guidValue;
    {/*w  ww  .j  av  a  2s . c om*/
        final Attribute guidAttribute = rootElement.getAttribute("GUID");
        guidValue = guidAttribute == null ? null : guidAttribute.getValue();
    }

    for (Iterator iter = doc.getDescendants(new ElementFilter("Challenge")); iter.hasNext();) {
        final Element loopQ = (Element) iter.next();
        final int maxLength = StringHelper.convertStrToInt(loopQ.getAttributeValue("MaxLength"), 255);
        final int minLength = StringHelper.convertStrToInt(loopQ.getAttributeValue("MinLength"), 2);
        final String defineStrValue = loopQ.getAttributeValue("Define");
        final boolean adminDefined = defineStrValue.equalsIgnoreCase("Admin");
        final String typeStrValue = loopQ.getAttributeValue("Type");
        final boolean required = typeStrValue.equalsIgnoreCase("Required");
        final String challengeText = loopQ.getText();

        final Challenge challenge = new ChaiChallenge(required, challengeText, minLength, maxLength,
                adminDefined, 0, false);
        returnList.add(challenge);
    }

    return new ChaiChallengeSet(returnList, minRandom, null, guidValue);
}