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:com.twentyn.patentExtractor.Util.java

public static DocumentBuilderFactory mkDocBuilderFactory() throws ParserConfigurationException {
    /* Try to load the document.  Note that the factory must be configured within the context of a method call
     * for exception handling.  TODO: can we work around this w/ dependency injection? */

    // With help from http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setValidating(false);/*from   ww  w. j a v a2s  .c o  m*/
    docFactory.setNamespaceAware(true);
    docFactory.setFeature("http://xml.org/sax/features/namespaces", false);
    docFactory.setFeature("http://xml.org/sax/features/validation", false);
    docFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    docFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    return docFactory;
}

From source file:de.mpg.escidoc.services.tools.scripts.person_grants.Util.java

/**
 * Queries an eSciDoc instance/* ww  w . ja  v a2s.co m*/
 * 
 * @param url
 * @param query
 * @param adminUserName
 * @param adminPassword
 * @param frameworkUrl
 * @return
 */
public static Document queryFramework(String url, String query, String adminUserName, String adminPassword,
        String frameworkUrl) {
    try {
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactoryImpl.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        GetMethod getMethod = new GetMethod(url + "?query="
                + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle="
                + Base64.encode(
                        getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8")));
        System.out.println("Querying <" + url + "?query="
                + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle="
                + Base64.encode(
                        getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8")));
        client.executeMethod(getMethod);
        if (getMethod.getStatusCode() == 200) {
            document = documentBuilder.parse(getMethod.getResponseBodyAsStream());
        } else {
            System.out.println("Error querying: Status " + getMethod.getStatusCode() + "\n"
                    + getMethod.getResponseBodyAsString());
        }
        return document;
    } catch (Exception e) {
        try {
            System.out.println("Error querying Framework <" + url + "?query="
                    + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle="
                    + Base64.encode(
                            getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8"))
                    + ">");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        e.printStackTrace();
    }
    return null;
}

From source file:be.fedict.eid.applet.service.signer.odf.ODFUtil.java

/**
 * Return a new DOM Document Builder//from  w  ww . j a  v  a2s  .com
 * 
 * @return DOM Document Builder
 * @throws ParserConfigurationException
 */
public static DocumentBuilder getNewDocumentBuilder() throws ParserConfigurationException {
    LOG.debug("new DOM document builder");
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    return documentBuilderFactory.newDocumentBuilder();
}

From source file:filehandling.FilePreprocessor.java

public static List<FileData> extractMDFilesFromXMLEmbedding(byte[] bytes, String basename, String extension) {

    List<FileData> returnList = new ArrayList<FileData>();
    try {/*from   w w  w . j  a v a2 s .c  om*/
        FileUtils.writeByteArrayToFile(new File("/tmp/debugData/instreamBeforeExtraction.xml"), bytes);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder dBuilder = dbf.newDocumentBuilder();

        Document doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(bytes)));

        if (Master.DEBUG_LEVEL > Master.LOW) {
            System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
        }

        NodeList entryElements = doc.getElementsByTagNameNS("http://www.w3.org/2005/Atom", "entry");
        for (int i = 0; i < entryElements.getLength(); i++) {
            Element entryElement = (Element) entryElements.item(i);
            FileData fd = null;
            /*
             * First try to find a <link> element pointing to Metadata as
             * this should be included by default
             */
            if (fd == null) {
                NodeList linkElements = entryElement.getElementsByTagNameNS("http://www.w3.org/2005/Atom",
                        "link");
                String iso19139Link = null;
                String iso19139_2Link = null;
                for (int j = 0; j < linkElements.getLength(); j++) {
                    Element linkElement = (Element) linkElements.item(j);
                    String relAttrValue = linkElement.getAttribute("rel");
                    String typeAttributeValue = linkElement.getAttribute("type");
                    if (relAttrValue != null && relAttrValue.equals("alternate")
                            && typeAttributeValue != null) {
                        switch (typeAttributeValue) {
                        case "application/vnd.iso.19139+xml":
                            iso19139Link = linkElement.getAttribute("href");
                            break;
                        case "application/vnd.iso.19139-2+xml":
                            iso19139_2Link = linkElement.getAttribute("href");
                            break;
                        }
                    }
                }
                /* iso19139-2 gets priority */
                String url = iso19139_2Link != null ? iso19139_2Link : iso19139Link;
                if (url != null) {
                    try (InputStream is = FileFetcher.fetchFileFromUrl(url)) {
                        Document doc2 = dBuilder.parse(new InputSource(is));
                        fd = processMDList(doc2.getDocumentElement(), extension, url);
                    }
                }
            }
            /*
             * Fallback to finding Metadata embedded directly in <entry>.
             * There will be either MI_Metadata or MD_Metadata, not both
             */
            if (fd == null) {
                fd = processMDList(entryElement.getElementsByTagName("gmi:MI_Metadata").item(0), extension,
                        null);
            }
            if (fd == null) {
                fd = processMDList(entryElement.getElementsByTagName("gmd:MD_Metadata").item(0), extension,
                        null);
            }

            if (fd != null) {
                returnList.add(fd);
            }
        }
    } catch (Exception e) {
        // TODO: handle exception

        if (Master.DEBUG_LEVEL > Master.LOW)
            System.out.println(e.getLocalizedMessage());
        GUIrefs.displayAlert("Error in FilePreprocessor.extractMDFilesFromXMLEmbedding"
                + StringUtilities.escapeQuotes(e.getMessage()));
    }
    return returnList;
}

From source file:ch.entwine.weblounge.common.impl.util.TestUtils.java

/**
 * Parses the <code>HTTP</code> response body into a <code>DOM</code>
 * document./* w  ww .j ava2s  . c  om*/
 * 
 * @param response
 *          the response
 * @return the parsed xml
 * @throws Exception
 *           if parsing fails
 */
public static Document parseXMLResponse(HttpResponse response) throws Exception {
    String responseXml = EntityUtils.toString(response.getEntity(), "utf-8");
    responseXml = StringEscapeUtils.unescapeHtml(responseXml);

    // Depending on whether it's an HTML page, let's make sure we end up with a
    // valid DOM
    Header contentTypeHeader = response.getFirstHeader("Content-Type");
    String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;

    Document doc = null;
    if ("text/html".equals(contentType)) {
        Tidy tidy = new Tidy();
        tidy.setOnlyErrors(true);
        tidy.setOutputEncoding("utf-8");
        doc = tidy.parseDOM(IOUtils.toInputStream(responseXml, "utf-8"), null);
    } else {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(new ByteArrayInputStream(responseXml.getBytes("utf-8")));
    }
    return doc;
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.WsStream.java

/**
 * Performs JAX-WS service call using SOAP API.
 *
 * @param url/*from w  w  w. j av a2s.  c  om*/
 *            JAX-WS service URL
 * @param soapRequestData
 *            JAX-WS service request data: headers and body XML string
 * @return service response string
 * @throws Exception
 *             if exception occurs while performing JAX-WS service call
 */
protected static String callWebService(String url, String soapRequestData) throws Exception {
    if (StringUtils.isEmpty(url)) {
        LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME,
                "WsStream.cant.execute.request"), url);
        return null;
    }

    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME, "WsStream.invoking.request"),
            url, soapRequestData);

    Map<String, String> headers = new HashMap<>();
    // separate SOAP message header values from request body XML
    BufferedReader br = new BufferedReader(new StringReader(soapRequestData));
    StringBuilder sb = new StringBuilder();
    try {
        String line;
        while ((line = br.readLine()) != null) {
            if (line.trim().startsWith("<")) { // NON-NLS
                sb.append(line).append(Utils.NEW_LINE);
            } else {
                int bi = line.indexOf(':'); // NON-NLS
                if (bi >= 0) {
                    String hKey = line.substring(0, bi).trim();
                    String hValue = line.substring(bi + 1).trim();
                    headers.put(hKey, hValue);
                } else {
                    sb.append(line).append(Utils.NEW_LINE);
                }
            }
        }
    } finally {
        Utils.close(br);
    }

    soapRequestData = sb.toString();

    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME, "WsStream.invoking.request"),
            url, soapRequestData);

    // Create Request body XML document
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(soapRequestData)));

    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Create SOAP message and set request XML as body
    SOAPMessage soapRequest = MessageFactory.newInstance().createMessage();

    // SOAPPart part = soapRequest.getSOAPPart();
    // SOAPEnvelope envelope = part.getEnvelope();
    // envelope.addNamespaceDeclaration();

    if (!headers.isEmpty()) {
        MimeHeaders mimeHeaders = soapRequest.getMimeHeaders();

        for (Map.Entry<String, String> e : headers.entrySet()) {
            mimeHeaders.addHeader(e.getKey(), e.getValue());
        }
    }

    SOAPBody body = soapRequest.getSOAPBody();
    body.addDocument(doc);
    soapRequest.saveChanges();

    // Send SOAP Message to SOAP Server
    SOAPMessage soapResponse = soapConnection.call(soapRequest, url);

    ByteArrayOutputStream soapResponseBaos = new ByteArrayOutputStream();
    soapResponse.writeTo(soapResponseBaos);
    String soapResponseXml = soapResponseBaos.toString();

    return soapResponseXml;
}

From source file:Main.java

private static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilder documentBuilder;

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

    documentBuilderFactory.setValidating(false); // dtd isn't available; would be nice to attempt to validate
    documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilder = documentBuilderFactory.newDocumentBuilder();

    return documentBuilder;
}

From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private static void addOriginSigsRels(final String signatureZipEntryName, final ZipOutputStream zipOutputStream)
        throws ParserConfigurationException, IOException, TransformerException {
    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);

    final Document originSignRelsDocument = documentBuilderFactory.newDocumentBuilder().newDocument();

    final Element relationshipsElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
            "Relationships"); //$NON-NLS-1$
    relationshipsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", RELATIONSHIPS_SCHEMA); //$NON-NLS-1$
    originSignRelsDocument.appendChild(relationshipsElement);

    final Element relationshipElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
            "Relationship"); //$NON-NLS-1$
    final String relationshipId = "rel-" + UUID.randomUUID().toString(); //$NON-NLS-1$
    relationshipElement.setAttribute("Id", relationshipId); //$NON-NLS-1$
    relationshipElement.setAttribute("Type", //$NON-NLS-1$
            "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); //$NON-NLS-1$

    relationshipElement.setAttribute("Target", FilenameUtils.getName(signatureZipEntryName)); //$NON-NLS-1$
    relationshipsElement.appendChild(relationshipElement);

    zipOutputStream.putNextEntry(new ZipEntry("_xmlsignatures/_rels/origin.sigs.rels")); //$NON-NLS-1$
    writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false);
}

From source file:eu.stork.peps.test.simple.SSETestUtils.java

/**
 * Marshall./*from w ww .ja  v a  2  s  .  c om*/
 * 
 * @param samlToken the SAML token
 * 
 * @return the byte[]
 * 
 * @throws MarshallingException the marshalling exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws TransformerException the transformer exception
 */
public static byte[] marshall(final XMLObject samlToken)
        throws MarshallingException, ParserConfigurationException, TransformerException {

    final javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringComments(true);
    final javax.xml.parsers.DocumentBuilder docBuild = dbf.newDocumentBuilder();

    // Get the marshaller factory
    final MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory();

    // Get the Subject marshaller
    final Marshaller marshaller = marshallerFactory.getMarshaller(samlToken);

    final Document doc = docBuild.newDocument();

    // Marshall the SAML token
    marshaller.marshall(samlToken, doc);

    // Obtain a byte array representation of the marshalled SAML object
    final DOMSource domSource = new DOMSource(doc);
    final StringWriter writer = new StringWriter();
    final StreamResult result = new StreamResult(writer);
    final TransformerFactory transFact = TransformerFactory.newInstance();
    final Transformer transformer = transFact.newTransformer();
    transformer.transform(domSource, result);

    return writer.toString().getBytes();
}

From source file:dk.netarkivet.common.utils.XmlUtils.java

/**
 * Validate that the settings xml files conforms to the XSD.
 *
 * @param xsdFile Schema to check settings against.
 * @throws ArgumentNotValid if unable to validate the settings files
 * @throws IOFailure If unable to read the settings files and/or 
 * the xsd file./*from   w w w.j av a2 s.  c o  m*/
 */
public static void validateWithXSD(File xsdFile) {
    ArgumentNotValid.checkNotNull(xsdFile, "File xsdFile");
    List<File> settingsFiles = Settings.getSettingsFiles();
    for (File settingsFile : settingsFiles) {
        try {
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            builderFactory.setNamespaceAware(true);
            DocumentBuilder parser = builderFactory.newDocumentBuilder();
            org.w3c.dom.Document document = parser.parse(settingsFile);

            // create a SchemaFactory capable of understanding WXS schemas
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            // load a WXS schema, represented by a Schema instance
            Source schemaFile = new StreamSource(xsdFile);
            Schema schema = factory.newSchema(schemaFile);

            // create a Validator instance, which can be used to validate an
            // instance document
            Validator validator = schema.newValidator();

            // validate the DOM tree
            try {
                validator.validate(new DOMSource(document));
            } catch (SAXException e) {
                // instance document is invalid!
                final String msg = "Settings file '" + settingsFile + "' does not validate using '" + xsdFile
                        + "'";
                log.warn(msg, e);
                throw new ArgumentNotValid(msg, e);
            }
        } catch (IOException e) {
            throw new IOFailure("Error while validating: ", e);
        } catch (ParserConfigurationException e) {
            final String msg = "Error validating settings file '" + settingsFile + "'";
            log.warn(msg, e);
            throw new ArgumentNotValid(msg, e);
        } catch (SAXException e) {
            final String msg = "Error validating settings file '" + settingsFile + "'";
            log.warn(msg, e);
            throw new ArgumentNotValid(msg, e);
        }
    }
}