/** * Uses a Vector of TransformerHandlers to pipe XML input document through a series of 1 or more * transformations. Called by {@link #pipeDocument}. * * @param vTHandler Vector of Transformation Handlers (1 per stylesheet). * @param source absolute URI to XML input * @param target absolute path to transformation output. */ public void usePipe(Vector vTHandler, String source, String target) throws TransformerException, TransformerConfigurationException, FileNotFoundException, IOException, SAXException, SAXNotRecognizedException { XMLReader reader = XMLReaderFactory.createXMLReader(); TransformerHandler tHFirst = (TransformerHandler) vTHandler.firstElement(); reader.setContentHandler(tHFirst); reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHFirst); for (int i = 1; i < vTHandler.size(); i++) { TransformerHandler tHFrom = (TransformerHandler) vTHandler.elementAt(i - 1); TransformerHandler tHTo = (TransformerHandler) vTHandler.elementAt(i); tHFrom.setResult(new SAXResult(tHTo)); } TransformerHandler tHLast = (TransformerHandler) vTHandler.lastElement(); Transformer trans = tHLast.getTransformer(); Properties outputProps = trans.getOutputProperties(); Serializer serializer = SerializerFactory.getSerializer(outputProps); FileOutputStream out = new FileOutputStream(target); try { serializer.setOutputStream(out); tHLast.setResult(new SAXResult(serializer.asContentHandler())); reader.parse(source); } finally { // Always clean up the FileOutputStream, // even if an exception was thrown in the try block if (out != null) out.close(); } }
static XMLReader createXMLReader() { try { return XMLReaderFactory.createXMLReader(); } catch (SAXException e) { // oops, lets try doing this (needed in 1.4) System.setProperty("org.xml.sax.driver", "org.apache.crimson.parser.XMLReaderImpl"); } try { // try once more return XMLReaderFactory.createXMLReader(); } catch (SAXException e) { throw new RuntimeException("Couldn't initialize a sax driver for the XMLReader"); } }
@Test public void testGeneratedFiles() throws SAXException, IOException { final File[] files = { new File("maps", "root-map-01.ditamap"), new File("topics", "target-topic-a.xml"), new File("topics", "target-topic-c.xml"), new File("topics", "xreffin-topic-1.xml"), new File("topics", "copy-to.xml"), }; final Map<File, File> copyto = new HashMap<File, File>(); copyto.put(new File("topics", "copy-to.xml"), new File("topics", "xreffin-topic-1.xml")); final TestHandler handler = new TestHandler(); final XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(handler); for (final File f : files) { InputStream in = null; try { in = new FileInputStream(new File(tmpDir, f.getPath())); handler.setSource( new File(inputDir, copyto.containsKey(f) ? copyto.get(f).getPath() : f.getPath())); parser.parse(new InputSource(in)); } finally { if (in != null) { in.close(); } } } }
@Test public void testParserHandling() throws Exception { final StringBuilder chars = new StringBuilder(); XMLReader r = XMLReaderFactory.createXMLReader(); r.setErrorHandler( new ErrorHandler() { public void warning(SAXParseException e) throws SAXException { throw e; } public void fatalError(SAXParseException e) throws SAXException { throw e; } public void error(SAXParseException e) throws SAXException { throw e; } }); r.setContentHandler( new DefaultHandler() { @Override public void characters(char[] ch, int start, int length) throws SAXException { chars.append(ch, start, length); } }); r.parse(new InputSource(new ByteArrayInputStream(utf8Xml))); assertThat(chars.toString()).isEqualTo(" \u0096 "); }
private Authentication getConnectionData(String stFile) { Authentication sr = null; try { // open the file and parse it to retrieve the four required information File file = new File(stFile); InputStream inputStream; inputStream = new FileInputStream(file); Reader reader = new InputStreamReader(inputStream, "ISO-8859-1"); InputSource is = new InputSource(reader); is.setEncoding("UTF-8"); XMLReader saxReader = XMLReaderFactory.createXMLReader(); sr = new Authentication(); saxReader.setContentHandler(sr); saxReader.parse(is); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sr; }
public void writeAsAttachment(Object obj, OutputStream out) throws IOException { try { if (obj instanceof StreamSource) { StreamSource source = (StreamSource) obj; InputSource inputSource = null; InputStream is = source.getInputStream(); Reader reader = source.getReader(); String systemId = source.getSystemId(); if (is != null) inputSource = new InputSource(is); else if (reader != null) inputSource = new InputSource(reader); else if (systemId != null) inputSource = new InputSource(systemId); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(_entityResolver); SAXSource saxSource = new SAXSource(xmlReader, inputSource); _transformer.transform(saxSource, new StreamResult(out)); } else _transformer.transform((Source) obj, new StreamResult(out)); } catch (TransformerException e) { IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } catch (SAXException saxe) { IOException ioe = new IOException(); ioe.initCause(saxe); throw ioe; } }
@Override public boolean execute(Property inputProperty, Node outputNode, Context context) throws Exception { Binary binaryValue = inputProperty.getBinary(); CheckArg.isNotNull(binaryValue, "binary"); if (!outputNode.isNew()) { outputNode = outputNode.addNode(XmlLexicon.DOCUMENT); } XmlSequencerHandler sequencingHandler = new XmlSequencerHandler(outputNode, scoping); // Create the reader ... XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(sequencingHandler); reader.setErrorHandler(sequencingHandler); // Ensure handler acting as entity resolver 2 reader.setProperty(DECL_HANDLER_FEATURE, sequencingHandler); // Ensure handler acting as lexical handler reader.setProperty(LEXICAL_HANDLER_FEATURE, sequencingHandler); // Ensure handler acting as entity resolver 2 setFeature(reader, ENTITY_RESOLVER_2_FEATURE, true); // Prevent loading of external DTDs setFeature(reader, LOAD_EXTERNAL_DTDS_FEATURE, false); // Prevent the resolving of DTD entities into fully-qualified URIS setFeature(reader, RESOLVE_DTD_URIS_FEATURE, false); // Parse XML document try (InputStream stream = binaryValue.getStream()) { reader.parse(new InputSource(stream)); } return true; }
private XMLReader createXMLReader() throws SAXException { XMLReader reader; try { reader = XMLReaderFactory.createXMLReader(); } catch (SAXException e) { reader = XMLReaderFactory.createXMLReader( System.getProperty("org.xml.sax.driver", "org.apache.crimson.parser.XMLReaderImpl")); } reader.setFeature("http://xml.org/sax/features/validation", true); GenericContentHandler handler = new GenericContentHandler(); reader.setContentHandler(handler); reader.setErrorHandler(handler); reader.setEntityResolver(new GenericEntityResolver()); return reader; }
/** Helper to create XSLT transformer for this instance */ private void initTransformer() { // build new transformer final InputStream xslin = getClass().getResourceAsStream("/org/olat/ims/resources/xsl/" + XSLFILENAME); // translate xsl with velocity final Context vcContext = new VelocityContext(); vcContext.put("t", pT); vcContext.put("staticPath", StaticMediaDispatcher.createStaticURIFor("")); String xslAsString = ""; try { xslAsString = slurp(xslin); } catch (final IOException e) { log.error("Could not convert xsl to string!", e); } final String replacedOutput = evaluateValue(xslAsString, vcContext); final TransformerFactory tfactory = TransformerFactory.newInstance(); XMLReader reader; try { reader = XMLReaderFactory.createXMLReader(); reader.setEntityResolver(er); final Source xsltsource = new SAXSource(reader, new InputSource(new StringReader(replacedOutput))); this.transformer = tfactory.newTransformer(xsltsource); } catch (final SAXException e) { throw new OLATRuntimeException("Could not initialize transformer!", e); } catch (final TransformerConfigurationException e) { throw new OLATRuntimeException("Could not initialize transformer (wrong config)!", e); } }
public List<Weapon> parseBySAX() throws SAXException, IOException { XMLReader reader = XMLReaderFactory.createXMLReader(); WeaponSaxHandler handler = new WeaponSaxHandler(); reader.setContentHandler(handler); reader.parse(new InputSource("resources/weaponMarket.xml")); return handler.getListWeapon(); }
@Test public void testImportExcel2007() throws Exception { long beginTime = System.currentTimeMillis(); String fileName = "D:\\Backup\\test.xlsx"; List<ExcelData> dataList = Lists.newArrayList(); OPCPackage pkg = OPCPackage.open(fileName); XSSFReader r = new XSSFReader(pkg); XMLReader parser = XMLReaderFactory.createXMLReader(); ContentHandler handler = new Excel2007SheetHandler(dataList); parser.setContentHandler(handler); Iterator<InputStream> sheets = r.getSheetsData(); while (sheets.hasNext()) { InputStream sheet = sheets.next(); InputSource sheetSource = new InputSource(sheet); parser.parse(sheetSource); sheet.close(); } // 把最后剩下的不足batchSize大小 if (dataList.size() > 0) { doBatchSave(dataList); } long endTime = System.currentTimeMillis(); log.info("耗时(秒):" + (endTime - beginTime) / 1000); }
public static void main(String[] args) { if (args.length <= 0) { System.out.println("Usage: java ExtractorDriver url"); return; } try { XMLReader parser = XMLReaderFactory.createXMLReader(); // Since this just writes onto the console, it's best // to use the system default encoding, which is what // we get by not specifying an explicit encoding here. Writer out = new OutputStreamWriter(System.out); ContentHandler handler = new TextExtractor(out); parser.setContentHandler(handler); // parser.parse("file:////c://myxml.xml"); parser.parse(args[0]); out.flush(); } catch (Exception e) { System.err.println(e); } }
public List<ExtensionInfo> parse() { List<ExtensionInfo> result = Lists.newArrayList(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); PluginXMLContentHandler handler = new PluginXMLContentHandler(); reader.setContentHandler(handler); for (URL u : getAllPluginResourceURLs()) { InputStream openStream = null; try { openStream = u.openStream(); reader.parse(new InputSource(openStream)); } catch (IOException e) { throw new RuntimeException(e); } finally { if (openStream != null) try { openStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } for (ExtensionPointHandler h : handler.getFinishedHandlers()) for (ExtensionInfo pi : h.getInfo()) result.add(pi); } catch (SAXException e) { throw new RuntimeException(e); } return result; }
@SuppressWarnings("unchecked") public static <T> T unmarshal(final InputStream in) throws IOException { final Unmarshaller unmarshaller = SardineUtil.createUnmarshaller(); try { final XMLReader reader = XMLReaderFactory.createXMLReader(); try { reader.setFeature("http://xml.org/sax/features/external-general-entities", Boolean.FALSE); } catch (final SAXException e) {; // Not all parsers will support this attribute } try { reader.setFeature("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE); } catch (final SAXException e) {; // Not all parsers will support this attribute } try { reader.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE); } catch (final SAXException e) {; // Not all parsers will support this attribute } try { reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); } catch (final SAXException e) {; // Not all parsers will support this attribute } return (T) unmarshaller.unmarshal(new SAXSource(reader, new InputSource(in))); } catch (final SAXException e) { throw new RuntimeException(e.getMessage(), e); } catch (final JAXBException e) { // Server does not return any valid WebDAV XML that matches our JAXB context final IOException failure = new IOException("Not a valid DAV response"); // Backward compatibility failure.initCause(e); throw failure; } }
public Design(String xmlFname) throws SAXException, IOException { FileInputStream fis = new FileInputStream(xmlFname); XMLReader rdr = XMLReaderFactory.createXMLReader(); rdr.setContentHandler(new MyContentHandler()); rdr.parse(new InputSource(fis)); fis.close(); }
/** Loads edits file, uses visitor to process all elements */ public void loadEdits() throws IOException { try { XMLReader xr = XMLReaderFactory.createXMLReader(); xr.setContentHandler(this); xr.setErrorHandler(this); xr.setDTDHandler(null); xr.parse(new InputSource(fileReader)); visitor.close(null); } catch (SAXParseException e) { System.out.println( "XML parsing error: " + "\n" + "Line: " + e.getLineNumber() + "\n" + "URI: " + e.getSystemId() + "\n" + "Message: " + e.getMessage()); visitor.close(e); throw new IOException(e.toString()); } catch (SAXException e) { visitor.close(e); throw new IOException(e.toString()); } catch (RuntimeException e) { visitor.close(e); throw e; } finally { fileReader.close(); } }
public static void main(String[] args) { try { // Creamos nuestro objeto libro vac�o Libro libro = new Libro(); // Creamos la factoria de parseadores por defecto XMLReader reader = XMLReaderFactory.createXMLReader(); // LibroXML libroleido = new LibroXML(libro); // A�adimos nuestro manejador al reader pasandole el objeto libro reader.setContentHandler(libroleido); // Procesamos el xml de ejemplo reader.parse(new InputSource(new FileInputStream("libros.xml"))); // System.out.println(libro.toString()); System.out.println(libroleido.getColeccionLibros()); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
static { try { xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://xml.org/sax/features/validation", false); if (false) { // FIXME AK: we need real handling for the normal case (HTML->FOP XML) EntityResolver resolver = new EntityResolver() { public InputSource resolveEntity(String arg0, String arg1) throws SAXException, IOException { log.info(arg0 + "::" + arg1); InputSource source = new InputSource( (new URL("file:///Volumes/Home/Desktop/dtd/xhtml1-transitional.dtd")) .openStream()); source.setSystemId(arg1); return source; } }; xmlReader.setEntityResolver(resolver); } } catch (SAXException e) { e.printStackTrace(); } }
protected List<NodeTypeDefinition> importFromXml(InputSource source) throws RepositoryException { XmlNodeTypeReader handler = new XmlNodeTypeReader(session); try { XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(handler); parser.parse(source); } catch (EnclosingSAXException ese) { Exception cause = ese.getException(); if (cause instanceof RepositoryException) { throw (RepositoryException) cause; } throw new RepositoryException(cause); } catch (SAXParseException se) { throw new InvalidSerializedDataException(se); } catch (SAXException se) { throw new RepositoryException(se); } catch (IOException ioe) { throw new RepositoryException(ioe); } catch (RuntimeException t) { throw t; } catch (Throwable t) { throw new RepositoryException(t); } return handler.getNodeTypeDefinitions(); }
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); } }
public static void main(String argv[]) { if (argv.length != 1) { System.err.println("Usage: java Validate [filename.xml | URLToFile]"); System.exit(1); } try { // get a parser XMLReader reader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); // request validation reader.setFeature("http://xml.org/sax/features/validation", true); reader.setFeature("http://apache.org/xml/features/validation/schema", true); reader.setErrorHandler(new Validate()); // associate an InputSource object with the file name or URL InputSource inputSource = new InputSource(argv[0]); // go ahead and parse reader.parse(inputSource); } catch (org.xml.sax.SAXException e) { System.out.println("Error in parsing " + e); valid = false; } catch (java.io.IOException e) { System.out.println("Error in I/O " + e); System.exit(0); } System.out.println("Valid Document is " + valid); }
private XMLReader createXMLReader() throws SAXException { XMLReader reader = queue.poll(); if (reader == null) { reader = XMLReaderFactory.createXMLReader(); } return reader; }
public WikiXMLParser(Reader reader, IArticleFilter filter) throws SAXException { super(); fArticleFilter = filter; fXMLReader = XMLReaderFactory.createXMLReader(); fXMLReader.setContentHandler(this); fXMLReader.setErrorHandler(this); fReader = reader; }
/** * Constructs the XML SAX parser. * * @param properties the JetS3t properties that will be applied when parsing XML documents. * @throws S3ServiceException */ public XmlResponsesSaxParser(Jets3tProperties properties) throws S3ServiceException { this.properties = properties; // Ensure we can load the XML Reader. try { xr = XMLReaderFactory.createXMLReader(); } catch (SAXException e) { // oops, lets try doing this (needed in 1.4) System.setProperty("org.xml.sax.driver", "org.apache.crimson.parser.XMLReaderImpl"); try { // Try once more... xr = XMLReaderFactory.createXMLReader(); } catch (SAXException e2) { throw new S3ServiceException("Couldn't initialize a sax driver for the XMLReader"); } } }
/** * Loads the configuration XML from the given string. * * @since 1.3 */ public static Configuration loadFromString(String config) throws IOException, SAXException { ConfigurationImpl cfg = new ConfigurationImpl(); XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(new ConfigHandler(cfg, null)); Reader reader = new StringReader(config); parser.parse(new InputSource(reader)); return cfg; }
public static Map<String, String> action( String action, String service, String url, Map<String, String> para) { try { StringBuffer req = new StringBuffer(); req.append( "<?xml version=\"1.0\"?>\r\n" + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" " + "SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "<SOAP-ENV:Body><m:" + action + " xmlns:m=\"" + service + "\">"); if (para != null && para.size() > 0) { Set<Map.Entry<String, String>> entrySet = para.entrySet(); for (Map.Entry<String, String> entry : entrySet) { String key = entry.getKey(); req.append("<" + key + ">" + entry.getValue() + "</" + key + ">"); } } req.append("</m:" + action + "></SOAP-ENV:Body></SOAP-ENV:Envelope>"); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("SOAPAction", service + "#" + action); conn.setRequestProperty("Content-Type", "text/xml"); conn.setRequestProperty("Connection", "Close"); conn.setDoOutput(true); byte[] bs = req.toString().getBytes(); conn.setRequestProperty("Content-Length", String.valueOf(bs.length)); conn.getOutputStream().write(bs); Map<String, String> result = new HashMap<String, String>(); XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(new ResultHandler(result)); if (conn.getResponseCode() == 500) { conn.disconnect(); return null; } else { parser.parse(new InputSource(conn.getInputStream())); conn.disconnect(); return result; } } catch (Exception e) { } return null; }
public ExpatReaderWrapper() throws SAXException { // initialize with an ExpatReader XMLReader reader = null; try { reader = XMLReaderFactory.createXMLReader("org.apache.harmony.xml.ExpatReader"); } catch (SAXException ex) { // expat reader is not available // fall back to the default XML reader try { reader = XMLReaderFactory.createXMLReader(); } catch (SAXException ex2) { // no default XML reader is set // fall back to xmlpull sax2 driver reader = XMLReaderFactory.createXMLReader("org.xmlpull.v1.sax2.Driver"); } } init(reader); }
public static void lerPeloSax() throws Exception { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); ProdutosHandler produtosHandler = new ProdutosHandler(); xmlReader.setContentHandler(produtosHandler); FileInputStream fileInputStream = new FileInputStream("src/venda.xml"); InputSource inputSource = new InputSource(fileInputStream); xmlReader.parse(inputSource); System.out.println(produtosHandler.getProdutos()); }
private static XMLReader getParser(TPENode root, ResultsCollector r) throws SAXException { if (!root.isRootNode()) { throw new RuntimeException("Provided root node is not a root node!"); } XMLReader parser = XMLReaderFactory.createXMLReader(); ContentHandler contentHandler = new StackEval(root, r); parser.setContentHandler(contentHandler); return parser; }
/** * Method to parse the XML input stream * * @throws TransactionCodesException if a problem is encountered parsing the XML stream */ public void parse() throws URLRolesXMLParserException { try { XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(this); parser.setErrorHandler(this); parser.parse(new InputSource(_xmlStream)); } catch (Exception e) { throw new URLRolesXMLParserException( "Exception caught parsing valid values XML stream: ", e, logger); } }