Java Code Examples for javax.xml.parsers.DocumentBuilder.setErrorHandler()

The following are Jave code examples for showing how to use setErrorHandler() of the javax.xml.parsers.DocumentBuilder class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: vexillo   File: FlagParser.java   Source Code and License Vote up 6 votes
public static Flag parse(String name, InputStream in) throws IOException {
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(true); // make sure the XML is valid
		factory.setExpandEntityReferences(false); // don't allow custom entities
		DocumentBuilder builder = factory.newDocumentBuilder();
		builder.setEntityResolver(new KVXXEntityResolver());
		builder.setErrorHandler(new KVXXErrorHandler(name));
		Document document = builder.parse(new InputSource(in));
		return parseDocument(document);
	} catch (ParserConfigurationException pce) {
		throw new IOException(pce);
	} catch (SAXException saxe) {
		throw new IOException(saxe);
	}
}
 
Example 2
Project: openjdk-jdk10   File: DocumentBuilderFactoryTest.java   Source Code and License Vote up 6 votes
/**
 * Test for the isIgnoringElementContentWhitespace and the
 * setIgnoringElementContentWhitespace. The xml file has all kinds of
 * whitespace,tab and newline characters, it uses the MyNSContentHandler
 * which does not invoke the characters callback when this
 * setIgnoringElementContentWhitespace is set to true.
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckElementContentWhitespace() throws Exception {
    String goldFile = GOLDEN_DIR + "dbfactory02GF.out";
    String outputFile = USER_DIR + "dbfactory02.out";
    MyErrorHandler eh = MyErrorHandler.newInstance();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    assertFalse(dbf.isIgnoringElementContentWhitespace());
    dbf.setIgnoringElementContentWhitespace(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(eh);
    Document doc = db.parse(new File(XML_DIR, "DocumentBuilderFactory06.xml"));
    assertFalse(eh.isErrorOccured());
    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer transformer = tfactory.newTransformer();
    SAXResult saxResult = new SAXResult();
    try(MyCHandler handler = MyCHandler.newInstance(new File(outputFile))) {
        saxResult.setHandler(handler);
        transformer.transform(domSource, saxResult);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 3
Project: jaffa-framework   File: DomParser.java   Source Code and License Vote up 6 votes
/** Parses the XML. It returns a Map.
 * @param uri The location of the content to be parsed.
 * @param validate if the XML is to be validated while parsing.
 * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested.
 * @throws SAXException If any parse errors occur.
 * @throws IOException If any IO errors occur.
 * @return The Map.
 */
public static Map parse(String uri, boolean validate)
throws ParserConfigurationException, SAXException, IOException {
    // Create a factory object for creating DOM parsers
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    
    // Specifies that the parser produced by this factory will validate documents as they are parsed.
    factory.setValidating(validate);
    
    // Now use the factory to create a DOM parser
    DocumentBuilder parser = factory.newDocumentBuilder();
    
    // Specifies the EntityResolver to resolve DTD used in XML documents
    parser.setEntityResolver(new DefaultEntityResolver());
    
    // Specifies the ErrorHandler to handle warning/error/fatalError conditions
    parser.setErrorHandler(new DefaultErrorHandler());
    
    Document document = parser.parse(uri);
    
    return parseXML(document);
}
 
Example 4
Project: openjdk-jdk10   File: UserController.java   Source Code and License Vote up 6 votes
/**
 * Checking Text content in XML file.
 * @see <a href="content/accountInfo.xml">accountInfo.xml</a>
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testMoreUserInfo() throws Exception {
    String xmlFile = XML_DIR + "accountInfo.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.parse(xmlFile);
    Element account = (Element)document
            .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0);
    String textContent = account.getTextContent();
    assertTrue(textContent.trim().regionMatches(0, "Rachel", 0, 6));
    assertEquals(textContent, "RachelGreen744");

    Attr accountID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID");
    assertTrue(accountID.getTextContent().trim().equals("1"));

    assertFalse(eh.isAnyError());
}
 
Example 5
Project: lams   File: StaticBasicParserPool.java   Source Code and License Vote up 6 votes
/**
 * Creates a new document builder.
 * 
 * @return newly created document builder
 * 
 * @throws XMLParserException thrown if their is a configuration error with the builder factory
 */
protected DocumentBuilder createBuilder() throws XMLParserException {
    try {
        DocumentBuilder builder = builderFactory.newDocumentBuilder();

        if (entityResolver != null) {
            builder.setEntityResolver(entityResolver);
        }

        if (errorHandler != null) {
            builder.setErrorHandler(errorHandler);
        }

        return builder;
    } catch (ParserConfigurationException e) {
        log.error("Unable to create new document builder", e);
        throw new XMLParserException("Unable to create new document builder", e);
    }
}
 
Example 6
Project: openjdk-jdk10   File: Bug4972882.java   Source Code and License Vote up 6 votes
@Test
public void test1() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute(SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
    dbf.setAttribute(SCHEMA_SOURCE, Bug4972882.class.getResource("targetNS00101m2_stub.xsd").toExternalForm());

    DocumentBuilder builder = dbf.newDocumentBuilder();
    builder.setErrorHandler(new DraconianErrorHandler());

    try {
        builder.parse(Bug4972882.class.getResource("targetNS00101m2_stub.xml").toExternalForm());
        Assert.fail("failure expected");
    } catch (SAXException e) {
        Assert.assertTrue(e.getMessage().indexOf("sch-props-correct.2") != -1);
    }
}
 
Example 7
Project: openjdk-jdk10   File: AuctionController.java   Source Code and License Vote up 6 votes
/**
 * Check usage of TypeInfo interface introduced in DOM L3.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testGetTypeInfo() throws Exception {
    String xmlFile = XML_DIR + "accountInfo.xml";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    docBuilder.setErrorHandler(new MyErrorHandler());

    Document document = docBuilder.parse(xmlFile);
    Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0);
    TypeInfo typeInfo = userId.getSchemaTypeInfo();
    assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger"));
    assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI));

    Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0);
    TypeInfo roletypeInfo = role.getSchemaTypeInfo();
    assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell"));
    assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS));
}
 
Example 8
Project: jdk8u-jdk   File: XMLSignatureInput.java   Source Code and License Vote up 5 votes
void convertToNodes() throws CanonicalizationException,
    ParserConfigurationException, IOException, SAXException {
    if (dfactory == null) {
        dfactory = DocumentBuilderFactory.newInstance();
        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        dfactory.setValidating(false);
        dfactory.setNamespaceAware(true);
    }
    DocumentBuilder db = dfactory.newDocumentBuilder();
    // select all nodes, also the comments.
    try {
        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

        Document doc = db.parse(this.getOctetStream());
        this.subNode = doc;
    } catch (SAXException ex) {
        // if a not-wellformed nodeset exists, put a container around it...
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos.write("<container>".getBytes("UTF-8"));
        baos.write(this.getBytes());
        baos.write("</container>".getBytes("UTF-8"));

        byte result[] = baos.toByteArray();
        Document document = db.parse(new ByteArrayInputStream(result));
        this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
    } finally {
        if (this.inputOctetStreamProxy != null) {
            this.inputOctetStreamProxy.close();
        }
        this.inputOctetStreamProxy = null;
        this.bytes = null;
    }
}
 
Example 9
Project: aws-sdk-java-v2   File: XpathUtils.java   Source Code and License Vote up 5 votes
/**
 * This method closes the given input stream upon completion.
 */
public static Document documentFrom(InputStream is)
        throws SAXException, IOException, ParserConfigurationException {
    is = new NamespaceRemovingInputStream(is);
    // DocumentBuilderFactory is not thread safe
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    // ensure that parser writes error/warning messages to the logger
    // rather than stderr
    builder.setErrorHandler(ERROR_HANDLER);
    Document doc = builder.parse(is);
    is.close();
    return doc;
}
 
Example 10
Project: openjdk-jdk10   File: DocumentBuilderFactoryTest.java   Source Code and License Vote up 5 votes
/**
 * Test the setValidating. By default it is false, use a
 * document which is not valid. It should not throw a warning or an error.
 * The test passes in case the return value equals 1.
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckDocumentBuilderFactory16() throws Exception {
    MyErrorHandler eh = MyErrorHandler.newInstance();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(eh);
    db.parse(new File(XML_DIR, "DocumentBuilderFactory05.xml"));
    assertFalse(eh.isErrorOccured());
}
 
Example 11
Project: incubator-netbeans   File: ModuleLifecycleManager.java   Source Code and License Vote up 5 votes
private Document readModuleDocument(FileObject fo) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    parser.setEntityResolver(this);
    parser.setErrorHandler(this);
    InputStream is = fo.getInputStream();
    Document document = parser.parse(is);
    is.close();
    return document;
}
 
Example 12
Project: generator_mybatis   File: XmlCodeGenerationTest.java   Source Code and License Vote up 5 votes
@Test
public void testXmlParse() {
    ByteArrayInputStream is = new ByteArrayInputStream(
            generatedXmlFile.getFormattedContent().getBytes());
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new TestEntityResolver());
        builder.setErrorHandler(new TestErrorHandler());
        builder.parse(is);
    } catch (Exception e) {
        fail("Generated XML File " + generatedXmlFile.getFileName() + " will not parse");
    }
}
 
Example 13
Project: MybatisGeneatorUtil   File: XmlCodeGenerationTest.java   Source Code and License Vote up 5 votes
@Test
public void testXmlParse() {
    ByteArrayInputStream is = new ByteArrayInputStream(
            generatedXmlFile.getFormattedContent().getBytes());
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new TestEntityResolver());
        builder.setErrorHandler(new TestErrorHandler());
        builder.parse(is);
    } catch (Exception e) {
        fail("Generated XML File " + generatedXmlFile.getFileName() + " will not parse");
    }
}
 
Example 14
Project: openjdk-jdk10   File: UserController.java   Source Code and License Vote up 5 votes
/**
 * Checking when creating an XML document using DOM Level 2 validating
 * it without having a schema source or a schema location It must throw a
 * sax parse exception.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCreateNewUser() throws Exception {
    String resultFile = USER_DIR + "accountInfoOut.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.newDocument();

    Element account = document.createElementNS(PORTAL_ACCOUNT_NS, "acc:Account");
    Attr accountID = document.createAttributeNS(PORTAL_ACCOUNT_NS, "acc:accountID");
    account.setAttributeNode(accountID);

    account.appendChild(document.createElement("FirstName"));
    account.appendChild(document.createElementNS(PORTAL_ACCOUNT_NS, "acc:LastName"));
    account.appendChild(document.createElement("UserID"));

    DOMImplementationLS impl
            = (DOMImplementationLS) DOMImplementationRegistry
                    .newInstance().getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();
    LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
    try(FileOutputStream output = new FileOutputStream(resultFile)) {
        MyDOMOutput domOutput = new MyDOMOutput();
        domOutput.setByteStream(output);
        writer.write(account, domOutput);
        docBuilder.parse(resultFile);
    }
    assertTrue(eh.isAnyError());
}
 
Example 15
Project: lams   File: PersistenceUnitReader.java   Source Code and License Vote up 5 votes
/**
 * Validate the given stream and return a valid DOM document for parsing.
 */
protected Document buildDocument(ErrorHandler handler, InputStream stream)
		throws ParserConfigurationException, SAXException, IOException {

	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	dbf.setNamespaceAware(true);
	DocumentBuilder parser = dbf.newDocumentBuilder();
	parser.setErrorHandler(handler);
	return parser.parse(stream);
}
 
Example 16
Project: wisp   File: ConfigParser.java   Source Code and License Vote up 4 votes
/**
 * parse data
 *
 * @param xmlPath
 *
 * @return
 *
 * @throws Exception
 */
public static InitDbConfig parse(InputStream xmlPath) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");

    Document document = null;
    DocumentBuilder docBuilder = null;
    docBuilder = factory.newDocumentBuilder();
    DefaultHandler handler = new DefaultHandler();
    docBuilder.setEntityResolver(handler);
    docBuilder.setErrorHandler(handler);

    document = docBuilder.parse(xmlPath);

    List<String> schemaList = new ArrayList<>();
    List<String> dataList = new ArrayList<>();

    Element rootEl = document.getDocumentElement();
    NodeList children = rootEl.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (node instanceof Element) {
            Element element = (Element) node;

            if (elementNameMatch(element, "initialize-database")) {

                schemaList = parseSchemaList(element);

            } else if (elementNameMatch(element, "initialize-data")) {

                dataList = parseDataList(element);
            }

        }
    }

    InitDbConfig initDbConfig = new InitDbConfig();
    initDbConfig.setDataFileList(dataList);
    initDbConfig.setSchemaFileList(schemaList);

    return initDbConfig;
}
 
Example 17
Project: incubator-netbeans   File: ValidateNbinstTest.java   Source Code and License Vote up 4 votes
private void implNbinstHost(TestHandler handler) throws ParserConfigurationException, IOException, IllegalArgumentException, SAXException {
        FileObject libs = FileUtil.getConfigFile("org-netbeans-api-project-libraries/Libraries");                
        if (libs != null) {
            final List<FileObject> schemas = new ArrayList<FileObject>(3);
            schemas.add(null);
            final FileObject schema2 = FileUtil.getConfigFile("ProjectXMLCatalog/library-declaration/2.xsd");
            if (schema2 != null) {
                schemas.add(schema2);
            }
            final FileObject schema3 = FileUtil.getConfigFile("ProjectXMLCatalog/library-declaration/3.xsd");
            if (schema3 != null) {
                schemas.add(schema3);
            }
next:       for (FileObject lib : libs.getChildren()) {
                SAXException lastException = null;
                for (FileObject schema : schemas) {
                    lastException = null;
                    try {
                        final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        docBuilderFactory.setValidating(true);
                        if (schema != null) {
                            docBuilderFactory.setNamespaceAware(true);
                            docBuilderFactory.setAttribute(
                                "http://java.sun.com/xml/jaxp/properties/schemaLanguage",   //NOI18N
                                "http://www.w3.org/2001/XMLSchema");                        //NOI18N
                            docBuilderFactory.setAttribute(
                                "http://java.sun.com/xml/jaxp/properties/schemaSource",     //NOI18N
                                schema.toURI().toString());
                        }
                        final DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
                        builder.setErrorHandler(XMLUtil.defaultErrorHandler());
                        builder.setEntityResolver(EntityCatalog.getDefault());
                        Document doc = builder.parse(new InputSource(lib.toURL().toString()));
                        NodeList nl = doc.getElementsByTagName("resource");
                        for (int i = 0; i < nl.getLength(); i++) {
                            Element resource = (Element) nl.item(i);
                            validateNbinstURL(new URL(XMLUtil.findText(resource)), handler, lib);
                        }
                        continue next;
                    } catch (SAXException e) {
                        lastException = e;
                    }
                }
                throw lastException;
            }
        }
        for (FileObject f : NbCollections.iterable(FileUtil.getConfigRoot().getChildren(true))) {
            for (String attr : NbCollections.iterable(f.getAttributes())) {
                if (attr.equals("instanceCreate")) {
                    continue; // e.g. on Services/Hidden/org-netbeans-lib-jakarta_oro-antlibrary.instance prints stack trace
                }
                Object val = f.getAttribute(attr);
                if (val instanceof URL) {
                    validateNbinstURL((URL) val, handler, f);
                }
            }
        }
        assertNoErrors("No improper nbinst URLs", handler.errors());
    }
 
Example 18
Project: joai-project   File: XMLDoc.java   Source Code and License Vote up 4 votes
/**
 *  Reads and parses the XML from the given source.
 */		
private final void doParseDoc(
	InputSource xmlSource,
	boolean validating,			// does parser validate
	boolean namespaceAware,		// is parser namespace aware
	boolean expandEntities)		// expand Entity refs
throws XMLException
{
	this.doc = null;

	if (bugs >= 1)
		prtln("getXmlDoc: systemid: \"" + systemid + "\"");
	DocumentBuilderFactory factory = null;
	try {
		factory = DocumentBuilderFactory.newInstance();
	} catch (FactoryConfigurationError fce) {
		mkerror("factory config error: " + fce);
	}

	factory.setValidating(validating);
	factory.setNamespaceAware(namespaceAware);
	factory.setExpandEntityReferences(expandEntities); // expand Entity rfs

	factory.setCoalescing(true);	// convert CDATA nodes to Text nodes
	factory.setIgnoringElementContentWhitespace(true);

	DocumentBuilder bldr = null;
	try {
		bldr = factory.newDocumentBuilder();
	} catch (ParserConfigurationException pce) {
		mkerror("parser config exc: " + pce);
	}

	SimpleErrorHandler simpleErrorHandler
		= new SimpleErrorHandler(errors, warnings);
	bldr.setErrorHandler(simpleErrorHandler);

	try {
		doc = bldr.parse(xmlSource);
	} catch (IOException ioe) {
		mkerror("Could not read xml doc file \"" + systemid
			 + "\"  exc: " + ioe.getMessage());
	} catch (SAXException sxe) {
		mkerror("Could not parse xml doc file \"" + systemid
			 + "\"  exc: " + sxe.getMessage());
	}
	hasErrors = simpleErrorHandler.hasErrors();
	hasWarnings = simpleErrorHandler.hasWarnings();
	///try{
	///	xmlSource.getByteStream().close();
	///}catch(Throwable e){}
	///xmlSource = null;
}
 
Example 19
Project: openjdk-jdk10   File: UserController.java   Source Code and License Vote up 4 votes
/**
 * This will check if adoptNode works will adoptNode from
 * @see <a href="content/userInfo.xml">userInfo.xml</a>
 * @see <a href="content/accountInfo.xml">accountInfo.xml</a>. This is
 * adopting a node from the XML file which is validated by a DTD and
 * into an XML file which is validated by the schema This covers Row 5
 * for the table
 * http://javaweb.sfbay/~jsuttor/JSR206/jsr-206-html/ch03s05.html. Filed
 * bug 4893745 because there was a difference in behavior.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCreateUserAccount() throws Exception {
    String userXmlFile = XML_DIR + "userInfo.xml";
    String accountXmlFile = XML_DIR + "accountInfo.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.parse(userXmlFile);
    Element user = (Element) document.getElementsByTagName("FirstName").item(0);
    // Set schema after parsing userInfo.xml. Otherwise it will conflict
    // with DTD validation.
    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    DocumentBuilder docBuilder1 = dbf.newDocumentBuilder();
    docBuilder1.setErrorHandler(eh);
    Document accDocument = docBuilder1.parse(accountXmlFile);

    Element firstName = (Element) accDocument
            .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0);
    Element adoptedAccount = (Element) accDocument.adoptNode(user);

    Element parent = (Element) firstName.getParentNode();
    parent.replaceChild(adoptedAccount, firstName);

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();

    MyDOMOutput mydomoutput = new MyDOMOutput();
    mydomoutput.setByteStream(System.out);

    writer.write(document, mydomoutput);
    writer.write(accDocument, mydomoutput);

    assertFalse(eh.isAnyError());
}
 
Example 20
Project: jaffa-framework   File: PatternGenerator.java   Source Code and License Vote up 4 votes
/**
 * Create source files based on the contents of an XML file
 * @param tempFileName the temporary file to be parsed, whose contents will
 *                     determine which files get created.
 * @param context contains information needed for processing, including
 *                information from WebMacro.properties and PatternGenerator
 *                properties.
 * @throws PatternGeneratorException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws WebMacroException
 * @throws SourceDecomposerException
 */
private void generateSourceFiles(String tempFileName, Context context)
        throws PatternGeneratorException, ParserConfigurationException,
               SAXException, IOException, WebMacroException,
               SourceDecomposerException {
    // parse the tempFileName.. Force XML validation
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    DocumentBuilder parser = factory.newDocumentBuilder();
    parser.setEntityResolver(new DefaultEntityResolver());
    parser.setErrorHandler(new DefaultErrorHandler());
    Document document = parser.parse(tempFileName);

    // check for Prerequisites
    // @todo : this currently only supports java files..
    // Need to enhance this logic to support other files too !!
    String preReqErrLog = null;
    Node preReq = document.getElementsByTagName(XML_PREREQUESITES).item(0);
    NodeList classes = preReq.getChildNodes();
    if (classes != null) {
        for (int i = 0; i < classes.getLength(); i++) {
            Node clazz = classes.item(i);
            if (clazz.getNodeType() == Node.ELEMENT_NODE) {
                String requiredClassName = XmlHelper.getTextTrim(clazz);
                try {
                    Class.forName(requiredClassName);
                } catch (ClassNotFoundException e) {
                    if (preReqErrLog == null) {
                        preReqErrLog = "";
                    }
                    preReqErrLog += "Error: PreRequesite Class " +
                                    requiredClassName + " not found\n";
                }
            }
        }
    }
    if (preReqErrLog != null) {
        writeMessage(m_auditFile, preReqErrLog, true);
        throw new PatternGeneratorException(preReqErrLog);
    }
    processComponents(context, document);
}