Example usage for javax.xml.parsers DocumentBuilderFactory setNamespaceAware

List of usage examples for javax.xml.parsers DocumentBuilderFactory setNamespaceAware

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setNamespaceAware.

Prototype


public void setNamespaceAware(boolean awareness) 

Source Link

Document

Specifies that the parser produced by this code will provide support for XML namespaces.

Usage

From source file:eu.smartfp7.terrier.sensor.ParserUtility.java

public static EdgeNodeSnapShot parse(InputStream is) throws Exception {
    DocumentBuilderFactory xmlfact = DocumentBuilderFactory.newInstance();
    xmlfact.setNamespaceAware(true);
    Document document = xmlfact.newDocumentBuilder().parse(is);

    NamespaceContext ctx = new NamespaceContext() {

        @Override/*from   w  w  w . j  ava 2  s  .c  o  m*/
        public Iterator getPrefixes(String namespaceURI) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public String getNamespaceURI(String prefix) {

            String uri = null;

            /*
             *    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
            xmlns:smart="http://www.ait.gr/ait_web_site/faculty/apne/schema.xml#"
            xmlns:dc="http://purl.org/dc/elements/1.1/"
            xmlns:contact="http://www.w3.org/2000/10/swap/pim/contact#"
            xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
            xmlns:time="http://www.w3.org/2006/time#"
            xml:base="http://www.ait.gr/ait_web_site/faculty/apne/report.xml"
                    
            *
            */

            if (prefix.equals("rdf")) {
                uri = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
            }
            if (prefix.equals("smart")) {
                uri = "http://www.ait.gr/ait_web_site/faculty/apne/schema.xml#";
            }
            if (prefix.equals("dc")) {
                uri = "http://purl.org/dc/elements/1.1/#";
            }
            if (prefix.equals("geo")) {
                uri = "http://www.w3.org/2003/01/geo/wgs84_pos#";
            }
            if (prefix.equals("time")) {
                uri = "http://www.w3.org/2006/time#";
            }
            return uri;

        }
    };

    // find the node data

    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(ctx);

    String id = (String) xpath.compile("//smart:Node/@rdf:ID").evaluate(document, XPathConstants.STRING);
    String lat = (String) xpath.compile("//smart:Node/geo:lat/text()").evaluate(document,
            XPathConstants.STRING);
    String lon = (String) xpath.compile("//smart:Node/geo:long/text()").evaluate(document,
            XPathConstants.STRING);
    String fullName = (String) xpath.compile("//smart:Node/dc:fullName/text()").evaluate(document,
            XPathConstants.STRING);
    Node node = new Node(new Double(lat), new Double(lon), id, fullName);

    String time = (String) xpath.compile("//smart:Report/time:inXSDDateTime/text()").evaluate(document,
            XPathConstants.STRING);
    String reportId = (String) xpath.compile("//smart:Report/@rdf:ID").evaluate(document,
            XPathConstants.STRING);

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Calendar c = Calendar.getInstance();
    ;
    c.setTime(df.parse(time));

    String density = (String) xpath.compile("//smart:Crowd/smart:density/text()").evaluate(document,
            XPathConstants.STRING);
    String cameraGain = (String) xpath.compile("//smart:Crowd/smart:cameraGain/text()").evaluate(document,
            XPathConstants.STRING);

    NodeList list = (NodeList) xpath.compile("//smart:Crowd/smart:colour").evaluate(document,
            XPathConstants.NODESET);
    double[] colors = new double[list.getLength()];
    for (int i = 0; i < list.getLength(); i++) {
        org.w3c.dom.Node colorNode = list.item(i);
        String v = colorNode.getFirstChild().getTextContent();
        colors[i] = new Double(v);
    }

    CrowdReport crowdReport = new CrowdReport(reportId, new Double(density), new Double(cameraGain), colors);

    EdgeNodeSnapShot snapShot = new EdgeNodeSnapShot(node, id, c, crowdReport);

    return snapShot;
}

From source file:com.connexta.arbitro.ctx.InputParser.java

/**
 * Tries to Parse the given output as a Context document.
 * //from  w  ww.  j  av a 2 s.c  o m
 * @param input the stream to parse
 * @param rootTag either "Request" or "Response"
 * 
 * @return the root node of the request/response
 * 
 * @throws ParsingException if a problem occurred parsing the document
 */
public static Node parseInput(InputStream input, String rootTag) throws ParsingException {
    NodeList nodes = null;

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);

        DocumentBuilder builder = null;

        // as of 1.2, we always are namespace aware
        factory.setNamespaceAware(true);

        if (ipReference == null) {
            // we're not validating
            factory.setValidating(false);

            builder = factory.newDocumentBuilder();
        } else {
            // we are validating
            factory.setValidating(true);

            factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
            factory.setAttribute(JAXP_SCHEMA_SOURCE, ipReference.schemaFile);

            builder = factory.newDocumentBuilder();
            builder.setErrorHandler(ipReference);
        }

        Document doc = builder.parse(input);
        nodes = doc.getElementsByTagName(rootTag);
    } catch (Exception e) {
        throw new ParsingException("Error tring to parse " + rootTag + "Type", e);
    }

    if (nodes.getLength() != 1)
        throw new ParsingException("Only one " + rootTag + "Type allowed " + "at the root of a Context doc");

    return nodes.item(0);
}

From source file:dk.statsbiblioteket.util.xml.DOM.java

/**
 * Parses a XML document from a stream to a DOM or return
 * {@code null} on error.//from   www.j av  a2  s. c o  m
 *
 * @param xmlStream      a stream containing an XML document.
 * @param namespaceAware if {@code true} the constructed DOM will reflect
 *                       the namespaces declared in the XML document
 * @return The document in a DOM or {@code null} in case of errors
 */
public static Document streamToDOM(InputStream xmlStream, boolean namespaceAware) {
    try {
        DocumentBuilderFactory dbFact = DocumentBuilderFactory.newInstance();
        dbFact.setNamespaceAware(namespaceAware);

        return dbFact.newDocumentBuilder().parse(xmlStream);
    } catch (IOException e) {
        log.warn("I/O error when parsing stream :" + e.getMessage(), e);
    } catch (SAXException e) {
        log.warn("Parse error when parsing stream :" + e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        log.warn("Parser configuration error when parsing XML stream: " + e.getMessage(), e);
    }
    return null;
}

From source file:org.eclipse.lyo.testsuite.server.util.OSLCUtils.java

public static Document createXMLDocFromResponseBody(String respBody)
        throws ParserConfigurationException, IOException, SAXException {
    //Create XML Doc out of response
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);//from w  w  w  .  ja v  a  2s  .c o  m
    // Don't load external DTD
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(respBody));
    return db.parse(is);
}

From source file:dk.statsbiblioteket.util.xml.DOM.java

/**
 * Parses an XML document from a String to a DOM.
 *
 * @param xmlString      a String containing an XML document.
 * @param namespaceAware if {@code true} the parsed DOM will reflect any
 *                       XML namespaces declared in the document
 * @return The document in a DOM or {@code null} on errors.
 *///w  w w.j a  v  a 2  s  . c  om
public static Document stringToDOM(String xmlString, boolean namespaceAware) {
    try {
        InputSource in = new InputSource();
        in.setCharacterStream(new StringReader(xmlString));

        DocumentBuilderFactory dbFact = DocumentBuilderFactory.newInstance();
        dbFact.setNamespaceAware(namespaceAware);

        return dbFact.newDocumentBuilder().parse(in);
    } catch (IOException e) {
        log.warn("I/O error when parsing XML :" + e.getMessage() + "\n" + xmlString, e);
    } catch (SAXException e) {
        log.warn("Parse error when parsing XML :" + e.getMessage() + "\n" + xmlString, e);
    } catch (ParserConfigurationException e) {
        log.warn("Parser configuration error when parsing XML :" + e.getMessage() + "\n" + xmlString, e);
    }
    return null;
}

From source file:be.e_contract.dssp.client.SignResponseVerifier.java

/**
 * Checks the signature on the SignResponse browser POST message.
 * /* ww  w.  j  a  v a2 s .co m*/
 * @param signResponseMessage
 *            the SignResponse message.
 * @param session
 *            the session object.
 * @return the verification result object.
 * @throws JAXBException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws MarshalException
 * @throws XMLSignatureException
 * @throws Base64DecodingException
 * @throws UserCancelException
 * @throws ClientRuntimeException
 * @throws SubjectNotAuthorizedException
 */
public static SignResponseVerificationResult checkSignResponse(String signResponseMessage,
        DigitalSignatureServiceSession session) throws JAXBException, ParserConfigurationException,
        SAXException, IOException, MarshalException, XMLSignatureException, Base64DecodingException,
        UserCancelException, ClientRuntimeException, SubjectNotAuthorizedException {
    if (null == session) {
        throw new IllegalArgumentException("missing session");
    }

    byte[] decodedSignResponseMessage;
    try {
        decodedSignResponseMessage = Base64.decode(signResponseMessage);
    } catch (Base64DecodingException e) {
        throw new SecurityException("no Base64");
    }
    // JAXB parsing
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.dss.async.ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.wsa.ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    SignResponse signResponse;
    try {
        signResponse = (SignResponse) unmarshaller
                .unmarshal(new ByteArrayInputStream(decodedSignResponseMessage));
    } catch (UnmarshalException e) {
        throw new SecurityException("no valid SignResponse XML");
    }

    // DOM parsing
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    InputStream signResponseInputStream = new ByteArrayInputStream(decodedSignResponseMessage);
    Document signResponseDocument = documentBuilder.parse(signResponseInputStream);

    // signature verification
    NodeList signatureNodeList = signResponseDocument
            .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature");
    if (signatureNodeList.getLength() != 1) {
        throw new SecurityException("requires 1 ds:Signature element");
    }
    Element signatureElement = (Element) signatureNodeList.item(0);
    SecurityTokenKeySelector keySelector = new SecurityTokenKeySelector(session.getKey());
    DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    boolean validSignature = xmlSignature.validate(domValidateContext);
    if (false == validSignature) {
        throw new SecurityException("invalid ds:Signature");
    }

    // verify content
    String responseId = null;
    RelatesToType relatesTo = null;
    AttributedURIType to = null;
    TimestampType timestamp = null;
    String signerIdentity = null;
    AnyType optionalOutputs = signResponse.getOptionalOutputs();
    List<Object> optionalOutputsList = optionalOutputs.getAny();
    for (Object optionalOutputObject : optionalOutputsList) {
        LOG.debug("optional output object type: " + optionalOutputObject.getClass().getName());
        if (optionalOutputObject instanceof JAXBElement) {
            JAXBElement optionalOutputElement = (JAXBElement) optionalOutputObject;
            LOG.debug("optional output name: " + optionalOutputElement.getName());
            LOG.debug("optional output value type: " + optionalOutputElement.getValue().getClass().getName());
            if (RESPONSE_ID_QNAME.equals(optionalOutputElement.getName())) {
                responseId = (String) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof RelatesToType) {
                relatesTo = (RelatesToType) optionalOutputElement.getValue();
            } else if (TO_QNAME.equals(optionalOutputElement.getName())) {
                to = (AttributedURIType) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof TimestampType) {
                timestamp = (TimestampType) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof NameIdentifierType) {
                NameIdentifierType nameIdentifier = (NameIdentifierType) optionalOutputElement.getValue();
                signerIdentity = nameIdentifier.getValue();
            }
        }
    }

    Result result = signResponse.getResult();
    LOG.debug("result major: " + result.getResultMajor());
    LOG.debug("result minor: " + result.getResultMinor());
    if (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(result.getResultMajor())) {
        if (DigitalSignatureServiceConstants.USER_CANCEL_RESULT_MINOR.equals(result.getResultMinor())) {
            throw new UserCancelException();
        }
        if (DigitalSignatureServiceConstants.CLIENT_RUNTIME_RESULT_MINOR.equals(result.getResultMinor())) {
            throw new ClientRuntimeException();
        }
        if (DigitalSignatureServiceConstants.SUBJECT_NOT_AUTHORIZED_RESULT_MINOR
                .equals(result.getResultMinor())) {
            throw new SubjectNotAuthorizedException(signerIdentity);
        }
    }
    if (false == DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR.equals(result.getResultMajor())) {
        throw new SecurityException("invalid dss:ResultMajor");
    }

    if (null == responseId) {
        throw new SecurityException("missing async:ResponseID");
    }
    if (false == responseId.equals(session.getResponseId())) {
        throw new SecurityException("invalid async:ResponseID");
    }

    if (null == relatesTo) {
        throw new SecurityException("missing wsa:RelatesTo");
    }
    if (false == session.getInResponseTo().equals(relatesTo.getValue())) {
        throw new SecurityException("invalid wsa:RelatesTo");
    }

    if (null == to) {
        throw new SecurityException("missing wsa:To");
    }
    if (false == session.getDestination().equals(to.getValue())) {
        throw new SecurityException("invalid wsa:To");
    }

    if (null == timestamp) {
        throw new SecurityException("missing wsu:Timestamp");
    }
    AttributedDateTime expires = timestamp.getExpires();
    if (null == expires) {
        throw new SecurityException("missing wsu:Timestamp/wsu:Expires");
    }
    DateTime expiresDateTime = new DateTime(expires.getValue());
    DateTime now = new DateTime();
    if (now.isAfter(expiresDateTime)) {
        throw new SecurityException("wsu:Timestamp expired");
    }

    session.setSignResponseVerified(true);

    SignResponseVerificationResult signResponseVerificationResult = new SignResponseVerificationResult(
            signerIdentity);
    return signResponseVerificationResult;
}

From source file:Main.java

private static Document generate() throws ParserConfigurationException {

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(false);
    documentBuilderFactory.setValidating(false);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();

    return document;
}

From source file:de.ingrid.interfaces.csw.domain.encoding.impl.XMLEncoding.java

protected static Document extractFromDocument(Node node) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Node copy = node.cloneNode(true);
    Node adopted = doc.adoptNode(copy);
    doc.appendChild(adopted);//from w w  w  .  java2  s  . c o  m
    return doc;
}

From source file:kenh.xscript.ScriptUtils.java

/**
 * Get xScript instance./*from  w ww.j  a  va2 s  .  c om*/
 * @param url
 * @param env
 * @return
 * @throws UnsupportedScriptException
 */
public static final Element getInstance(URL url, Environment env) throws UnsupportedScriptException {

    if (url == null)
        return null;

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        factory.setIgnoringElementContentWhitespace(true);

        InputStream in = url.openStream();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(in);
        return getInstance(doc, env);
    } catch (UnsupportedScriptException e) {
        throw e;
    } catch (Exception e) {
        throw new UnsupportedScriptException(null, e);
    }
}

From source file:kenh.xscript.ScriptUtils.java

/**
 * Get xScript instance./*w w  w .jav a2 s . c o  m*/
 * @param file
 * @param env
 * @return
 * @throws UnsupportedScriptException
 */
public static final Element getInstance(File file, Environment env) throws UnsupportedScriptException {

    if (file == null || !file.exists())
        return null;

    if (env == null)
        env = new Environment();

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new FileInputStream(file));
        String home = file.getCanonicalFile().getParent();
        if (env != null) {
            if (!env.containsVariable(Constant.VARIABLE_HOME))
                env.setPublicVariable(Constant.VARIABLE_HOME, home, false);
        }
        return getInstance(doc, env);
    } catch (UnsupportedScriptException e) {
        throw e;
    } catch (Exception e) {
        throw new UnsupportedScriptException(null, e);
    }
}