Java Code Examples for javax.xml.parsers.DocumentBuilderFactory

The following are top voted examples for showing how to use javax.xml.parsers.DocumentBuilderFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: jentrata-msh   File: XPathExecutor.java View source code Vote up 8 votes
/**
 * Creates a blank document.
 * 
 * @return a blank document.
 */
private static Node createDocument() {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        return db.newDocument();
    }
    catch (Exception e) {
        throw new RuntimeException("Cannot construct or configure document builder", e);
    }
}
 
Example 2
Project: jbosgi   File: DocumentBuilderTestCase.java View source code Vote up 6 votes
private void parse(DocumentBuilderFactory factory) throws Exception {
    factory.setNamespaceAware(true);
    factory.setValidating(false);

    DocumentBuilder domBuilder = factory.newDocumentBuilder();
    URL resURL = bundle.getResource("simple.xml");
    Document dom = domBuilder.parse(resURL.openStream());
    assertNotNull("Document not null", dom);

    Element root = dom.getDocumentElement();
    assertEquals("root", root.getLocalName());

    Node child = root.getFirstChild();
    assertEquals("child", child.getLocalName());
    assertEquals("content", child.getTextContent());
}
 
Example 3
Project: richfaces   File: XMLBody.java View source code Vote up 6 votes
/**
 * Load XML document and parse it into DOM.
 *
 * @param input
 * @throws ParsingException
 */
public void loadXML(InputStream input, boolean namespaceAware) throws ParsingException {
    try {
        // Create Document Builder Factory
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setIgnoringElementContentWhitespace(true);
        docFactory.setValidating(false);
        docFactory.setNamespaceAware(namespaceAware);
        // Create Document Builder
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        // docBuilder.
        // docBuilder.isValidating();

        // Disable loading of external Entityes
        docBuilder.setEntityResolver(new EntityResolver() {
            // Dummi resolver - alvays do nothing
            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                return new InputSource(new StringReader(""));
            }
        });

        // open and parse XML-file
        xmlDocument = docBuilder.parse(input);

        // Get Root xmlElement
        rootElement = xmlDocument.getDocumentElement();
    } catch (Exception e) {
        throw new ParsingException("Error load XML ", e);
    }
}
 
Example 4
Project: jlibs   File: DOMUtil.java View source code Vote up 6 votes
public static DocumentBuilder newDocumentBuilder(boolean nsAware, boolean validating, boolean coalescing, boolean ignoreComments) throws ParserConfigurationException{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(nsAware);
    factory.setValidating(validating);
    factory.setCoalescing(coalescing);
    factory.setIgnoringComments(ignoreComments);
    return factory.newDocumentBuilder();
}
 
Example 5
Project: eclipse-integration-commons   File: StsTestUtil.java View source code Vote up 6 votes
public static String canocalizeXml(String originalServerXml) throws Exception {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setExpandEntityReferences(false);

	DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
	Document document = builder.parse(new InputSource(new StringReader(originalServerXml)));
	document.normalize();

	TransformerFactory factory = TransformerFactory.newInstance();
	Transformer transformer = factory.newTransformer();
	StringWriter writer = new StringWriter();
	transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	transformer.transform(new DOMSource(document.getDocumentElement()), new StreamResult(writer));
	return writer.toString().replace("\\s+\\n", "\\n");
}
 
Example 6
Project: virgo.kernel   File: PlanReader.java View source code Vote up 6 votes
private DocumentBuilderFactory createDocumentBuilderFactory() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
    return factory;
}
 
Example 7
Project: JerseyTest   File: WadlResourceTest.java View source code Vote up 6 votes
/**
 * Test WADL generation
 */
public void testGetWadl() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    initiateWebApplication(WidgetsResource.class, ExtraResource.class);
    WebResource r = resource("/application.wadl");

    File tmpFile = r.get(File.class);
    DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance();
    bf.setNamespaceAware(true);
    bf.setValidating(false);
    bf.setXIncludeAware(false);
    DocumentBuilder b = bf.newDocumentBuilder();
    Document d = b.parse(tmpFile);
    printSource(new DOMSource(d));
    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(new NSResolver("wadl", "http://research.sun.com/wadl/2006/10"));
    // check base URI
    String val = (String)xp.evaluate("/wadl:application/wadl:[email protected]", d, XPathConstants.STRING);
    assertEquals(val,BASE_URI.toString());
    // check total number of resources is 4
    val = (String)xp.evaluate("count(//wadl:resource)", d, XPathConstants.STRING);
    assertEquals(val,"4");
    // check only once resource with for {id}
    val = (String)xp.evaluate("count(//wadl:resource[@path='{id}'])", d, XPathConstants.STRING);
    assertEquals(val,"1");
    // check only once resource with for {id}/verbose
    val = (String)xp.evaluate("count(//wadl:resource[@path='{id}/verbose'])", d, XPathConstants.STRING);
    assertEquals(val,"1");
    // check only once resource with for widgets
    val = (String)xp.evaluate("count(//wadl:resource[@path='widgets'])", d, XPathConstants.STRING);
    assertEquals(val,"1");
    // check 3 methods for {id}
    val = (String)xp.evaluate("count(//wadl:resource[@path='{id}']/wadl:method)", d, XPathConstants.STRING);
    assertEquals(val,"3");
    // check 2 methods for widgets
    val = (String)xp.evaluate("count(//wadl:resource[@path='widgets']/wadl:method)", d, XPathConstants.STRING);
    assertEquals(val,"2");
    // check type of {id} is int
    val = (String)xp.evaluate("//wadl:resource[@path='{id}']/wadl:param[@name='id'][email protected]", d, XPathConstants.STRING);
    assertEquals(val,"xs:int");
    // check number of output representations is two
    val = (String)xp.evaluate("count(//wadl:resource[@path='widgets']/wadl:method[@name='GET']/wadl:response/wadl:representation)", d, XPathConstants.STRING);
    assertEquals(val,"2");
    // check number of output representations is one
    val = (String)xp.evaluate("count(//wadl:resource[@path='widgets']/wadl:method[@name='POST']/wadl:request/wadl:representation)", d, XPathConstants.STRING);
    assertEquals(val,"1");
    // check type of {id}/verbose is int
    val = (String)xp.evaluate("//wadl:resource[@path='{id}/verbose']/wadl:param[@name='id'][email protected]", d, XPathConstants.STRING);
    assertEquals(val,"xs:int");
}
 
Example 8
Project: viskell   File: HaskellCatalog.java View source code Vote up 6 votes
/**
 * Loads the given XML catalog into a document.
 * @param XMLPath The path to the XML file.
 * @param XSDPath The path to the XSD file.
 * @return The document for the XML file.
 */
protected static Document getDocument(final String XMLPath, final String XSDPath) {
    URL xmlFile = HaskellCatalog.class.getResource(XMLPath);
    URL schemaFile = HaskellCatalog.class.getResource(XSDPath);

    try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        SchemaFactory sFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

        dbFactory.setIgnoringElementContentWhitespace(true);
        dbFactory.setIgnoringComments(true);
        dbFactory.setSchema(sFactory.newSchema(schemaFile));

        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

        return dBuilder.parse(xmlFile.openStream());
    } catch (IOException | ParserConfigurationException | SAXException e) {
        throw new RuntimeException("could not read or parse catalog file", e);
    }
}
 
Example 9
Project: jentrata-msh   File: PKISignatureImpl.java View source code Vote up 5 votes
void sign(String alias, char[] password, String keyStoreLocation,
        String algo, String digestAlgo, boolean signEnvelopeOnly)
            throws SignatureException {
    try {
        final SOAPPart soapPart = ebxmlMessage.getSOAPMessage().
            getSOAPPart();
        DocumentResult docResult = new DocumentResult();
        TransformerFactory.newInstance().newTransformer().
            transform(soapPart.getContent(), docResult);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        (new XMLWriter(baos)).write(docResult.getDocument());
        DocumentBuilderFactory factory = DocumentBuilderFactory.
            newInstance();
        factory.setNamespaceAware(true);
        // soapPartDocument is a DOM equivilance of soapPart
        final Document soapPartDocument = factory.newDocumentBuilder().
            parse(new ByteArrayInputStream(baos.toByteArray()));
        final String soapHeaderName = soapPart.getEnvelope().getHeader().
            getElementName().getLocalName();
        final Element soapHeader = (Element) soapPartDocument.
            getElementsByTagNameNS(NAMESPACE_URI_SOAP_ENVELOPE,
                                   soapHeaderName).item(0);
        ApacheXMLDSigner signature = new ApacheXMLDSigner();
        CompositeKeyStore ks = new CompositeKeyStore();
        ks.addKeyStoreFile(keyStoreLocation, null, password);
        PrivateKey pk = (PrivateKey) ks.getKey(alias, password);
        /* 
         * To reduce the complexity of the exception message,
         * the exception can be catch on the final catch block.
         *  
         try {
            pk = (PrivateKey) ks.getKey(alias, password);
            if(pk ==null){
            	String message ="Cannot retrieve key from keystore["+keyStoreLocation+"]" +"\n"+
            		"KeyStore Type: " + ks.getKeyStore().getType() +"\n"+
            		"Key Provider: " + ks.getKeyStore().getProvider().getInfo();
            	throw new NullPointerException(message);
            }
        }
        catch (Exception e) {
            String err = "Cannot get private key: " + alias + " - "
                + e.getMessage();
           logger.warn(err);
            throw new SignException(err);
        }*/

        if (algo != null) {
            if (!isAlgorithmMatchedWithKey(pk, algo)) {
                throw new SignException(
                        "Signing algorithm not matched with key algorithm, " +
                        "actual key algorithum:" + pk.getAlgorithm() +"\t" + "expect algorithum: " + algo 
                        );
            }
            if (digestAlgo == null) {
                signature.setEnvelope(soapPartDocument, algo);
            } else {
                signature.setEnvelope(soapPartDocument, algo, digestAlgo);
            }
        } else {
            String keyAlgo = getAlgorithmFromPrivateKey(pk);
            signature.setEnvelope(soapPartDocument, keyAlgo);
        }
        /*
        if (algo == null) {
            // use default algorithm, i.e. dsa-sha1
            signature.setEnvelope(soapPartDocument);
        }
        else {
            // use user-defined algorithm, only support dsa-sha1 and 
            // rsa-sha1
            if (digestAlgo == null) {
                signature.setEnvelope(soapPartDocument, algo);
            } else {
                signature.setEnvelope(soapPartDocument, algo, digestAlgo);
            }
        }
        */

        // important, if not, the transformation will fail
        soapHeader.appendChild(signature.getElement());

        if (!signEnvelopeOnly) {
            Iterator i = ebxmlMessage.getPayloadContainers();
            while (i.hasNext()) {
                PayloadContainer pc = (PayloadContainer) i.next();
                signature.addDocument(pc.getHref(), 
                    pc.getDataHandler().getInputStream(),
                    pc.getContentType());
            }
        }

        signature.sign(ks, alias, password);

        domToSoap(signature.getElement(), this);

        Iterator childElements = getChildElements
            (SignatureReference.SIGNATURE_REFERENCE);
        if (childElements.hasNext()) {
            while (childElements.hasNext()) {
                references.add(new SignatureReference(soapEnvelope,
                    (SOAPElement) childElements.next()));
            }
        }
        else {
            throw new SOAPValidationException(SOAPValidationException.
                SOAP_FAULT_CLIENT, "<" + NAMESPACE_PREFIX_DS + ":" +
                SignatureReference.SIGNATURE_REFERENCE +
                "> is not found in <" + NAMESPACE_PREFIX_DS + ":" +
                ELEMENT_SIGNATURE + ">!");
        }

        childElements = getChildElements(ELEMENT_SIGNATURE_VALUE);
        if (childElements.hasNext()) {
            signatureValue = ((SOAPElement) childElements.next()).
                getValue();
        }
        else {
            throw new SOAPValidationException(SOAPValidationException.
                SOAP_FAULT_CLIENT, "<" + NAMESPACE_PREFIX_DS + ":" +
                ELEMENT_SIGNATURE_VALUE + "> is not found in <" +
                NAMESPACE_PREFIX_DS + ":" + ELEMENT_SIGNATURE + ">!");
        }
    }
    catch (Exception e) {
        String err = ErrorMessages.getMessage
            (ErrorMessages.ERR_PKI_CANNOT_SIGN, e);
        err +=
        	"\n"+"Try to retreive key alias["+
        	alias+"] from keystore["+keyStoreLocation+"]";
        throw new SignatureException(err, e);
    }
}
 
Example 10
Project: fiji   File: ReconstructTranslator.java View source code Vote up 5 votes
public boolean process()
{
    if (ready)
    {
        File[] sectionFiles;
        xmlBuilder = new StringBuilder();
        sectionDocuments.clear();

        /*
        Collect all Reconstruct section files.
        For instance, we might have a series file Reconstruct.ser
        In this case, projectName should be "Reconstruct" and we want to collect files like
        Reconstruct.1
        Reconstruct.2 ...
        Reconstruct.199
        Reconstruct.200
        */
        sectionFiles = inputFile.getParentFile().listFiles(
                new FilenameFilter()
                {
                    public boolean accept(File dir, String name)
                    {
                        return name.matches(projectName + ".[0-9]*$");
                    }
                }
        );

        try
        {
            //Read and parse all of the files (series and sections)
            final DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;

            // DTDs aren't commonly included with Reconstruct projects, so ignore them.
            builderFactory.setValidating(false);
            builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            builder = builderFactory.newDocumentBuilder();

            serDoc = builder.parse(inputFile);

            for (File f : sectionFiles)
            {
                log("Opening file " + f.getAbsolutePath());
                lastFile = f;
                addSection(sectionDocuments, builder, f);
            }

            //Sort section files by index.
            Collections.sort(sectionDocuments, new Utils.ReconstructSectionIndexComparator());

            //Need the pre-transform stack height in order to translate the Reconstruct
            //image transforms into TrakEM2 transforms. The coordinate systems are almost
            //as different as possible, for a 2D euclidean space.
            preTransPatchSize = Utils.getReconstructStackSize(sectionDocuments);
            defaultMag = Utils.getMedianMag(sectionDocuments);

            /*
            Reconstruct : TrakEM2
            Contour (closed) : area_list
            Contour (open) : profile_list
            Z-Trace : polyline

            Contours are stores in section files, whereas Z-Traces are stored in the
            series file.

            area_lists and polylines go in the trakem layer set definition, whereas
            profiles are stored directly in the layers.

            All of this is to say, that we need to collect all of the contours and ztraces
            ahead of time, and link them to their respective sections/layers.
            */

            collectContoursAndSections(sectionDocuments);
            collectZTraces(serDoc);

            xmlBuilder.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
            appendDTD(xmlBuilder);
            xmlBuilder.append("<trakem2>\n");
            appendProject(xmlBuilder);
            appendLayerSet(xmlBuilder);
            appendDisplay(xmlBuilder);
            xmlBuilder.append("</trakem2>\n");

            clearMemory();

            return true;
        }
        catch (SAXParseException spe)
        {
            String fid = lastFile == null ? "" : " in " + lastFile.getName();
            errorMessage = "Error while parsing XML" + fid + " at line " + spe.getLineNumber() +
                    ", column " + spe.getColumnNumber() + "\n";
            errorMessage += Utils.stackTraceToString(spe);

            clearMemory();
            
            return false;
        }
        catch (Exception e)
        {
            clearMemory();
            e.printStackTrace();
            errorMessage = Utils.stackTraceToString(e);
            return false;
        }
    }
    else
    {
        return false;
    }
}