/** * Parse the content given {@link org.xml.sax.InputSource} * as XML using the specified * {@link org.xml.sax.helpers.DefaultHandler}. * * @param is The InputSource containing the content to be parsed. * @param dh The SAX DefaultHandler to use. * * @throws IllegalArgumentException If the <code>InputSource</code> object * is <code>null</code>. * @throws IOException If any IO errors occur. * @throws SAXException If any SAX errors occur during processing. * * @see org.xml.sax.DocumentHandler */ public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException { if (is == null) { throw new IllegalArgumentException("InputSource cannot be null"); } XMLReader reader = this.getXMLReader(); if (dh != null) { reader.setContentHandler(dh); reader.setEntityResolver(dh); reader.setErrorHandler(dh); reader.setDTDHandler(dh); } reader.parse(is); }
@Override public InputSource resolveEntity(String pid, String sid) throws SAXException { String publicURL = (String) dtdMap.get(pid); if (publicURL != null) { if (validate) { publicURL = getClass().getClassLoader().getResource(publicURL).toExternalForm(); return new InputSource(publicURL); } else { return new InputSource(new ByteArrayInputStream(new byte[0])); } } return new InputSource(sid); }
@Override public InputStream resolveEntity(String publicId, String systemId, String baseUri, String namespace) { InputSource is = resolveEntity(publicId, systemId); if (is != null && !is.isEmpty()) { try { return new URL(is.getSystemId()).openStream(); } catch (IOException ex) { //considered as no mapping. } } GroupEntry.ResolveType resolveType = ((CatalogImpl) catalog).getResolve(); switch (resolveType) { case IGNORE: return null; case STRICT: CatalogMessages.reportError(CatalogMessages.ERR_NO_MATCH, new Object[]{publicId, systemId}); } //no action, allow the parser to continue return null; }
/** * parse the XML content and verify the provisioningUsername and * provisioningPassword have been exported as expected * * @param xmlString * @throws Exception */ private void verifyXmlForUserAndPwd(String xmlString) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader( xmlString))); assertEquals(1, document.getChildNodes().getLength()); Element root = document.getDocumentElement(); assertEquals("tns:TechnicalServices", root.getNodeName()); List<?> productNodes = XMLConverter.getNodeList(root.getChildNodes(), "tns:TechnicalService"); assertEquals(1, productNodes.size()); Element e = (Element) productNodes.get(0); assertEquals(PROVISIONING_USER_NAME, e.getAttribute("provisioningUsername")); assertEquals(PROVISIONING_PASSWORD, e.getAttribute("provisioningPassword")); }
/** * Unit test for TemplatesHandler setter/getter. * * @throws Exception If any errors occur. */ @Test public void testcase13() throws Exception { String outputFile = USER_DIR + "saxtf013.out"; String goldFile = GOLDEN_DIR + "saxtf013GF.out"; try(FileInputStream fis = new FileInputStream(XML_FILE)) { // The transformer will use a SAX parser as it's reader. XMLReader reader = XMLReaderFactory.createXMLReader(); SAXTransformerFactory saxTFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); TemplatesHandler thandler = saxTFactory.newTemplatesHandler(); // I have put this as it was complaining about systemid thandler.setSystemId("file:///" + USER_DIR); reader.setContentHandler(thandler); reader.parse(XSLT_FILE); XMLFilter filter = saxTFactory.newXMLFilter(thandler.getTemplates()); filter.setParent(reader); filter.setContentHandler(new MyContentHandler(outputFile)); filter.parse(new InputSource(fis)); } assertTrue(compareWithGold(goldFile, outputFile)); }
/** * Attempt to obtain a SAX InputSource object from a Source * object. * * @param source Must be a non-null Source reference. * * @return An InputSource, or null if Source can not be converted. */ public static InputSource sourceToInputSource(Source source) { if (source instanceof SAXSource) { return ((SAXSource) source).getInputSource(); } else if (source instanceof StreamSource) { StreamSource ss = (StreamSource) source; InputSource isource = new InputSource(ss.getSystemId()); isource.setByteStream(ss.getInputStream()); isource.setCharacterStream(ss.getReader()); isource.setPublicId(ss.getPublicId()); return isource; } else { return null; } }
public void parse(InputStream xml, OutputStream finf, String workingDirectory) throws Exception { StAXDocumentSerializer documentSerializer = new StAXDocumentSerializer(); documentSerializer.setOutputStream(finf); SAX2StAXWriter saxTostax = new SAX2StAXWriter(documentSerializer); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setNamespaceAware(true); SAXParser saxParser = saxParserFactory.newSAXParser(); XMLReader reader = saxParser.getXMLReader(); reader.setProperty("http://xml.org/sax/properties/lexical-handler", saxTostax); reader.setContentHandler(saxTostax); if (workingDirectory != null) { reader.setEntityResolver(createRelativePathResolver(workingDirectory)); } reader.parse(new InputSource(xml)); xml.close(); finf.close(); }
public void parse(InputSource input) throws IOException, SAXException { try { InputStream s = input.getByteStream(); if (s == null) { String systemId = input.getSystemId(); if (systemId == null) { throw new SAXException(CommonResourceBundle.getInstance().getString("message.inputSource")); } parse(systemId); } else { parse(s); } } catch (FastInfosetException e) { logger.log(Level.FINE, "parsing error", e); throw new SAXException(e); } }
/** * Decodeer een object. * @param configuration configuratie * @param clazz te decoderen object * @param reader reader om XML van de lezen * @param <T> type van het object * @return het gedecodeerde object * @throws ConfigurationException bij configuratie problemen (annoties op de klassen) * @throws DecodeException bij decodeer problemen */ public static <T> T decode(final Configuration configuration, final Class<T> clazz, final Reader reader) throws XmlException { final Context context = new Context(); final Configuration theConfiguration = configuration == null ? DEFAULT_CONFIGURATION : configuration; ConfigurationHelper.setConfiguration(context, theConfiguration); final Root<T> item = theConfiguration.getModelFor(clazz); // Jaxp first final Document document; try { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); final DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(new InputSource(reader)); } catch (ParserConfigurationException | SAXException | IOException e) { throw new DecodeException(context.getElementStack(), e); } return item.decode(context, document); }
/** * Format xml string. * * @param uglyXml the ugly xml * @return the string */ public static String formatXml(String uglyXml) { try { String xmlHeader= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(uglyXml)); final Document document = db.parse(is); OutputFormat format = new OutputFormat(document); format.setLineWidth(65); format.setIndenting(true); format.setIndent(2); Writer out = new StringWriter(); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(document); return out.toString().replace(xmlHeader,""); } catch (Exception e) { return ""; } }
public void testCDATA() throws Exception { Document doc = XMLUtil.createDocument("root", null, null, null); Element e = doc.createElement("sometag"); doc.getDocumentElement().appendChild(e); String cdataContent = "!&<>*\n[[]]"; CDATASection cdata = doc.createCDATASection(cdataContent); e.appendChild(cdata); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLUtil.write(doc, baos, "UTF-8"); String data = baos.toString("UTF-8").replace("\r\n", "\n"); assertTrue("Can't find CDATA section", data.indexOf("<![CDATA[" + cdataContent + "]]>") != -1); // parse the data back to DOM Document doc2 = XMLUtil.parse(new InputSource(new ByteArrayInputStream(baos.toByteArray())), false, false, null, null); NodeList nl = doc2.getElementsByTagName("sometag"); assertEquals("Wrong number of <sometag/> elements", 1, nl.getLength()); nl = nl.item(0).getChildNodes(); assertEquals("Wrong number of <sometag/> child elements", 1, nl.getLength()); Node child = nl.item(0); assertTrue("Expecting CDATASection node", child instanceof CDATASection); assertEquals("Wrong CDATASection content", cdataContent, ((CDATASection) child).getNodeValue()); }
private String retrieveValueByXpath(String xml, DocumentBuilder builder, XPathExpression expr) { try { Document document = builder .parse(new InputSource(new StringReader(xml))); NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET); if (nodes == null || nodes.item(0) == null || nodes.item(0).getFirstChild() == null) { return null; } return nodes.item(0).getFirstChild().getNodeValue(); } catch (SAXException | XPathExpressionException | IOException e) { e.printStackTrace(); } return null; }
public void verifyClusterInfoXML(String xml) throws JSONException, Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); Document dom = db.parse(is); NodeList nodes = dom.getElementsByTagName("clusterInfo"); assertEquals("incorrect number of elements", 1, nodes.getLength()); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); verifyClusterGeneric(WebServicesTestUtils.getXmlLong(element, "id"), WebServicesTestUtils.getXmlLong(element, "startedOn"), WebServicesTestUtils.getXmlString(element, "state"), WebServicesTestUtils.getXmlString(element, "haState"), WebServicesTestUtils.getXmlString(element, "hadoopVersionBuiltOn"), WebServicesTestUtils.getXmlString(element, "hadoopBuildVersion"), WebServicesTestUtils.getXmlString(element, "hadoopVersion"), WebServicesTestUtils.getXmlString(element, "resourceManagerVersionBuiltOn"), WebServicesTestUtils.getXmlString(element, "resourceManagerBuildVersion"), WebServicesTestUtils.getXmlString(element, "resourceManagerVersion")); } }
static void validateAgainstAUDTDs(InputSource input, final Path updaterJar, final Task task) throws IOException, SAXException { XMLUtil.parse(input, true, false, XMLUtil.rethrowHandler(), new EntityResolver() { ClassLoader loader = new AntClassLoader(task.getProject(), updaterJar); public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { String remote = "http://www.netbeans.org/dtds/"; if (systemId.startsWith(remote)) { String rsrc = "org/netbeans/updater/resources/" + systemId.substring(remote.length()); URL u = loader.getResource(rsrc); if (u != null) { return new InputSource(u.toString()); } else { task.log(rsrc + " not found in " + updaterJar, Project.MSG_WARN); } } return null; } }); }
public static void close(InputSource inputSource) { if (inputSource == null) { // Nothing to do return; } InputStream is = inputSource.getByteStream(); if (is != null) { try { is.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } }
/** startParse() is a simple API which tells the IncrementalSAXSource * to begin reading a document. * * @throws SAXException is parse thread is already in progress * or parsing can not be started. * */ public void startParse(InputSource source) throws SAXException { if (fIncrementalParser==null) throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_STARTPARSE_NEEDS_SAXPARSER, null)); //"startParse needs a non-null SAXParser."); if (fParseInProgress) throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_STARTPARSE_WHILE_PARSING, null)); //"startParse may not be called while parsing."); boolean ok=false; try { ok = parseSomeSetup(source); } catch(Exception ex) { throw new SAXException(ex); } if(!ok) throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_COULD_NOT_INIT_PARSER, null)); //"could not initialize parser with"); }
/** * Method canonicalize * * @param inputBytes * @return the c14n bytes. * * @throws CanonicalizationException * @throws java.io.IOException * @throws javax.xml.parsers.ParserConfigurationException * @throws org.xml.sax.SAXException */ public byte[] engineCanonicalize(byte[] inputBytes) throws javax.xml.parsers.ParserConfigurationException, java.io.IOException, org.xml.sax.SAXException, CanonicalizationException { java.io.InputStream bais = new ByteArrayInputStream(inputBytes); InputSource in = new InputSource(bais); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); // needs to validate for ID attribute normalization dfactory.setNamespaceAware(true); DocumentBuilder db = dfactory.newDocumentBuilder(); Document document = db.parse(in); return this.engineCanonicalizeSubTree(document); }
/** * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, * java.lang.String) */ @Override public InputSource resolveEntity(final String publicId, final String systemId) throws SAXException { if( entityResolver != null ) { try { return entityResolver.resolveEntity(publicId, systemId); } catch( SAXException se ) { throw se; } catch( IOException ioe ) { throw new SAXException("I/O error has occurred - " + ioe, ioe); //$NON-NLS-1$ } } log.warn("ignoring publicId=" + publicId //$NON-NLS-1$ + " and systemId=" + systemId); //$NON-NLS-1$ return null; }
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { log("publicId: " + publicId + " systemId: " + systemId, Project.MSG_VERBOSE); int idx = systemId.lastIndexOf('/'); String last = systemId.substring(idx + 1); if (localDTDs.contains(last)) { log("Resolved to embedded DTD"); InputSource is = new InputSource(Arch.class.getResourceAsStream(last)); is.setSystemId(systemId); return is; } else { log("Not resolved"); return null; } }
/** * 遍历工作簿中所有的电子表格 * * @param filename * @throws Exception */ public void process(InputStream stream) throws Exception { OPCPackage pkg = OPCPackage.open(stream); XSSFReader r = new XSSFReader(pkg); SharedStringsTable sst = r.getSharedStringsTable(); XMLReader parser = fetchSheetParser(sst); Iterator<InputStream> sheets = r.getSheetsData(); while (sheets.hasNext()) { curRow = 0; sheetIndex++; InputStream sheet = sheets.next(); InputSource sheetSource = new InputSource(sheet); parser.parse(sheetSource); sheet.close(); } }
@DataProvider(name = "supportLSResourceResolver1") public Object[][] supportLSResourceResolver1() throws Exception { URI catalogFile = getClass().getResource("CatalogSupport.xml").toURI(); URI catalogFileUri = getClass().getResource("CatalogSupport_uri.xml").toURI(); /* * val_test.xml has a reference to system.dtd and val_test.xsd */ SAXSource ss = new SAXSource(new InputSource(xml_val_test)); ss.setSystemId(xml_val_test_id); return new Object[][]{ {catalogFile, ss}, {catalogFileUri, ss}, }; }
@Test public void testThatFilesAreTheSameAfterMerge() throws Exception { DefaultXmlFormatter xmlFormatter = new DefaultXmlFormatter(); Properties p = new Properties(); p.setProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE, "true"); CommentGenerator commentGenerator = new DefaultCommentGenerator(); commentGenerator.addConfigurationProperties(p); Document document = new Document(XmlConstants.MYBATIS3_MAPPER_PUBLIC_ID, XmlConstants.MYBATIS3_MAPPER_SYSTEM_ID); document.setRootElement(getSqlMapElement(commentGenerator)); GeneratedXmlFile generatedFile1 = new GeneratedXmlFile(document, "TestMapper.xml", "org.mybatis.test", "src", true, xmlFormatter); InputSource is1 = new InputSource(new StringReader(generatedFile1.getFormattedContent())); GeneratedXmlFile generatedFile2 = new GeneratedXmlFile(document, "TestMapper.xml", "org.mybatis.test", "src", true, xmlFormatter); InputSource is2 = new InputSource(new StringReader(generatedFile2.getFormattedContent())); String mergedSource = XmlFileMergerJaxp.getMergedSource(is1, is2, "TestMapper.xml"); assertEquals(generatedFile1.getFormattedContent(), mergedSource); }
public void testSpaceInPath() throws Exception { Catalog catalog = new Catalog(); URL locationURL = getClass().getResource("data/catalog.xml"); String location = locationURL.toExternalForm(); catalog.setLocation(location); catalog.refresh(); String s0 = catalog.resolvePublic("-//NetBeans//IZ53710//EN"); new URL(s0).openStream(); String s1 = catalog.resolvePublic("-//NetBeans//IZ53710 1//EN"); new URL(s1).openStream(); String s2 = catalog.resolvePublic("-//NetBeans//IZ53710 2//EN"); // new URL(s2).openStream(); String s3 = catalog.resolvePublic("-//NetBeans//IZ53710 3//EN"); new URL(s3).openStream(); InputSource in1 = catalog.resolveEntity("-//NetBeans//IZ53710 1//EN", null); InputSource in2 = catalog.resolveEntity("-//NetBeans//IZ53710 2//EN", null); InputSource in3 = catalog.resolveEntity("-//NetBeans//IZ53710 3//EN", null); System.err.println("Done"); }
@Test public void test() { try { FileInputStream fis = new FileInputStream(getClass().getResource("bug6690015.xml").getFile()); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(fis)); Element root = doc.getDocumentElement(); NodeList textnodes = root.getElementsByTagName("text"); int len = textnodes.getLength(); int index = 0; int attindex = 0; int attrlen = 0; NamedNodeMap attrs = null; while (index < len) { Element te = (Element) textnodes.item(index); attrs = te.getAttributes(); attrlen = attrs.getLength(); attindex = 0; Node node = null; while (attindex < attrlen) { node = attrs.item(attindex); System.out.println("attr: " + node.getNodeName() + " is shown holding value: " + node.getNodeValue()); attindex++; } index++; System.out.println("-------------"); } fis.close(); } catch (Exception e) { Assert.fail("Exception: " + e.getMessage()); } }
void doOneTestIteration() throws Exception { Source src = new StreamSource(new StringReader(xml)); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); SAXSource xsdSource = new SAXSource(new InputSource(new ByteArrayInputStream(xsd.getBytes()))); Schema schema = schemaFactory.newSchema(xsdSource); Validator v = schema.newValidator(); v.validate(src); }
/** * Test for evaluate(InputSource source,QName returnType) return a node list * if returnType is NodeList. * * @throws Exception If any errors occur. */ @Test public void testCheckXPathExpression31() throws Exception { try (InputStream is = Files.newInputStream(XML_PATH)) { NodeList nodeList = (NodeList) xpath.compile(EXPRESSION_NAME_A). evaluate(new InputSource(is), NODESET); assertEquals(((Attr) nodeList.item(0)).getValue(), "6"); } }
/** * Method to process the KalturaMetadata object (and the XML it contains) into a list of field strings * @param metadata kaltura metadata object * @return List of field strings */ private List<String> convertKalturaMetadataToFieldsList(KalturaMetadata metadata) { List<String> fields = new ArrayList<String>(); // if metadata exists for object if (metadata != null && StringUtils.isNotEmpty(metadata.xml)) { // check for malformed beginning of XML String metadataXml = metadata.xml; if (StringUtils.startsWithIgnoreCase(metadataXml, "xml=")){ metadataXml = metadataXml.replaceAll("xml=", ""); } // ensure XML begins with the <?xml tag int lastIndex = StringUtils.lastIndexOf(metadataXml, "<?xml"); if(lastIndex > 0){ metadataXml = StringUtils.substring(metadataXml, lastIndex); } // set the metadata's XML to the updated string metadata.xml = metadataXml; try { Document metadataDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(metadata.xml))); org.w3c.dom.Element root = metadataDoc.getDocumentElement(); NodeList childNodes = root.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node node = childNodes.item(i); if (node instanceof org.w3c.dom.Element) { fields.add(node.getTextContent()); } } } catch (Exception e) { throw new RuntimeException("Error processing metadata fields for kaltura metadata object (" + metadata.objectId + ") :: " + e + ", xml="+metadata.xml, e); } } return fields; }
/** * Resolves the given resource and adapts the <code>LSInput</code> * returned into an <code>InputSource</code>. */ public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId) throws SAXException, IOException { if (fEntityResolver != null) { LSInput lsInput = fEntityResolver.resolveResource(XML_TYPE, null, publicId, systemId, baseURI); if (lsInput != null) { final String pubId = lsInput.getPublicId(); final String sysId = lsInput.getSystemId(); final String baseSystemId = lsInput.getBaseURI(); final Reader charStream = lsInput.getCharacterStream(); final InputStream byteStream = lsInput.getByteStream(); final String data = lsInput.getStringData(); final String encoding = lsInput.getEncoding(); /** * An LSParser looks at inputs specified in LSInput in * the following order: characterStream, byteStream, * stringData, systemId, publicId. For consistency * with the DOM Level 3 Load and Save Recommendation * use the same lookup order here. */ InputSource inputSource = new InputSource(); inputSource.setPublicId(pubId); inputSource.setSystemId((baseSystemId != null) ? resolveSystemId(systemId, baseSystemId) : systemId); if (charStream != null) { inputSource.setCharacterStream(charStream); } else if (byteStream != null) { inputSource.setByteStream(byteStream); } else if (data != null && data.length() != 0) { inputSource.setCharacterStream(new StringReader(data)); } inputSource.setEncoding(encoding); return inputSource; } } return null; }
@Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId != null) { return new InputSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.dtd")); } return null; }
/** * @return InputSource, a callie SHOULD set systemId if available */ public static InputSource documentToInputSource (Document doc) { String text = documentToString (doc); Reader reader = new StringReader (text); InputSource in = new InputSource ("StringReader"); // NOI18N in.setCharacterStream (reader); return in; }
/** * Parse the content of the specified file using this Digester. Returns * the root element from the object stack (if any). * * @param file File containing the XML data to be parsed * * @exception IOException if an input/output error occurs * @exception SAXException if a parsing exception occurs */ public Object parse(File file) throws IOException, SAXException { configure(); InputSource input = new InputSource(new FileInputStream(file)); input.setSystemId("file://" + file.getAbsolutePath()); getXMLReader().parse(input); return (root); }
public void canonicalize(String inName, String outName) { try (//FileOutputStream outStream = new FileOutputStream(outName); FileInputStream inputStream = new FileInputStream(inName);) { JDK15XML1_0Parser parser = new JDK15XML1_0Parser(); parser.parse(new InputSource(inputStream)); success("test passed"); } catch (Exception e) { fail(e.getMessage()); } }
/** * Parses the document. * @param provider an implementation of the XMLProvider interface * @param source a SAX input source * @param context a parsing context * @param rootParser the root parser to start with; if null, * a root parser will be derived based on the rootClass * requested in the constructor. * @return an object that is the result of parsing. */ public Object parse( XMLProvider provider, InputSource source, ParseContext context, NodeParser rootParser) throws IOException, SAXException { if ((_rootClass == null) && (rootParser == null)) throw new NullPointerException(_LOG.getMessage( "NULL_ROOTCLASS_ROOTPARSER")); if (provider == null) provider = new JaxpXMLProvider(); ParseContextWrapper wrappedContext = new ParseContextWrapper(context, _manager, provider); Handler handler = new Handler(wrappedContext, rootParser); XMLReader reader = provider.getXMLReader(); // Force these two features to be set the way we want. // These are the default values, but we'd crash and burn // if they're wrong. reader.setFeature("http://xml.org/sax/features/namespaces", true); reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); reader.setContentHandler(handler); reader.setErrorHandler(handler); if (getEntityResolver() != null) reader.setEntityResolver(getEntityResolver()); reader.parse(source); return handler.getRoot(); }
/** Returns a XML parser. The same parser can be returned assuming that config files * are parser sequentially. * * @return XML parser with set content handler, errror handler * and entity resolver. */ public XMLReader getXMLParser (DefaultHandler h) throws SAXException { if (parser == null) { // get non validating, not namespace aware parser parser = XMLUtil.createXMLReader(); parser.setEntityResolver(new EntityResolver () { /** Implementation of entity resolver. Points to the local DTD * for our public ID */ public InputSource resolveEntity (String publicId, String systemId) throws SAXException { if (ModeParser.INSTANCE_DTD_ID_1_0.equals(publicId) || ModeParser.INSTANCE_DTD_ID_1_1.equals(publicId) || ModeParser.INSTANCE_DTD_ID_1_2.equals(publicId) || ModeParser.INSTANCE_DTD_ID_2_0.equals(publicId) || ModeParser.INSTANCE_DTD_ID_2_1.equals(publicId) || ModeParser.INSTANCE_DTD_ID_2_2.equals(publicId) || ModeParser.INSTANCE_DTD_ID_2_3.equals(publicId) || GroupParser.INSTANCE_DTD_ID_2_0.equals(publicId) || TCGroupParser.INSTANCE_DTD_ID_2_0.equals(publicId) || TCRefParser.INSTANCE_DTD_ID_1_0.equals(publicId) || TCRefParser.INSTANCE_DTD_ID_2_0.equals(publicId) || TCRefParser.INSTANCE_DTD_ID_2_1.equals(publicId) || TCRefParser.INSTANCE_DTD_ID_2_2.equals(publicId) || WindowManagerParser.INSTANCE_DTD_ID_1_0.equals(publicId) || WindowManagerParser.INSTANCE_DTD_ID_1_1.equals(publicId) || WindowManagerParser.INSTANCE_DTD_ID_2_0.equals(publicId) || WindowManagerParser.INSTANCE_DTD_ID_2_1.equals(publicId)) { InputStream is = new ByteArrayInputStream(new byte[0]); return new InputSource(is); } return null; // i.e. follow advice of systemID } }); } parser.setContentHandler(h); parser.setErrorHandler(h); return parser; }
/** * Test with an invalid XML file, parser should throw SAXException. * * @param saxparser a SAXParser instance. * @throws Exception If any errors occur. */ @Test(expectedExceptions = SAXException.class, dataProvider = "parser-provider") public void testParse29(SAXParser saxparser) throws Exception { try (FileInputStream instream = new FileInputStream( new File(XML_DIR, "invalid.xml"))) { saxparser.parse(new InputSource(instream), new DefaultHandler()); } }
private void prettyPrint(StringWriter writer) throws TransformerException, IOException, SAXException, ParserConfigurationException, XPathExpressionException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); InputSource is = new InputSource(new InputStreamReader( new ByteArrayInputStream(writer.toString().getBytes()))); Document original = dBuilder.parse(is); removeWhitespace(original); moreThanMeetsTheEye().transform(new DOMSource(original), getDestination()); }
/** * Parses as a DOM the IFile passed in argument .. * * @param file to parse * @return parsed Document */ private Document parseXslFile(IFile file) throws Exception { Document doc; doc = XMLUtils.getDefaultDocumentBuilder().parse(new InputSource(file.getContents())); return doc; }
@Override public InputSource resolveEntity(String publicID, String systemID) throws IOException, SAXException { // avoid HTTP traffic to unicode.org if (systemID.startsWith(CLDRConverter.SPPL_LDML_DTD_SYSTEM_ID)) { return new InputSource((new File(CLDRConverter.LOCAL_SPPL_LDML_DTD)).toURI().toString()); } return null; }
private NodeList unpackXML(String xml, String targetTag) throws Exception { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource source = new InputSource(); source.setCharacterStream(new StringReader(xml)); Document doc = db.parse(source); NodeList nodeList = doc.getElementsByTagName(targetTag); return nodeList; } catch (Exception e) { log.error(e); log.error(e.getStackTrace()); throw (e); } }
private void processEntry(final ZipInputStream zis, final ZipEntry ze, final ContentHandlerFactory handlerFactory) { ContentHandler handler = handlerFactory.createContentHandler(); try { // if (CODE2ASM.equals(command)) { // read bytecode and process it // // with TraceClassVisitor // ClassReader cr = new ClassReader(readEntry(zis, ze)); // cr.accept(new TraceClassVisitor(null, new PrintWriter(os)), // false); // } boolean singleInputDocument = inRepresentation == SINGLE_XML; if (inRepresentation == BYTECODE) { // read bytecode and process it // with handler ClassReader cr = new ClassReader(readEntry(zis, ze)); cr.accept(new SAXClassAdapter(handler, singleInputDocument), 0); } else { // read XML and process it with handler XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource( singleInputDocument ? (InputStream) new ProtectedInputStream( zis) : new ByteArrayInputStream(readEntry(zis, ze)))); } } catch (Exception ex) { update(ze.getName(), 0); update(ex, 0); } }