List of usage examples for org.xml.sax XMLReader parse
public void parse(String systemId) throws IOException, SAXException;
From source file:com.aurel.track.exchange.docx.importer.HTMLParser.java
private void parse(String fileName, Locale locale) { //get a factory localizedHeading = "berschrift";//LocalizeUtil.getLocalizedTextFromApplicationResources(HEADING_KEY, locale); SAXParserFactory spf = SAXParserFactory.newInstance(); try {//from www .ja v a2 s. com //get a new instance of parser SAXParser sp = spf.newSAXParser(); //spf.setValidating(true); XMLReader xmlReader = sp.getXMLReader(); xmlReader.setErrorHandler(new MyErrorHandler(System.err)); xmlReader.setContentHandler(this); //parse the file and also register this class for call backs //InputSource is=new InputSource(new StringReader(xml)); xmlReader.parse(convertToFileURL(fileName)); } catch (SAXException se) { LOGGER.error("Parsing the file " + fileName + " failed with " + se.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(se)); } catch (ParserConfigurationException pce) { LOGGER.error("Parsing the file " + fileName + " failed with " + pce.getMessage()); if (LOGGER.isDebugEnabled()) { LOGGER.error(ExceptionUtils.getStackTrace(pce)); } } catch (IOException ie) { LOGGER.error("Reading the file " + fileName + " failed with " + ie.getMessage()); LOGGER.error(ExceptionUtils.getStackTrace(ie)); } }
From source file:com.kdmanalytics.toif.adaptor.FindbugsAdaptor.java
/** * the xml produced form the tool is parsed by a sax parser and our own content handler. * //from w ww.ja v a 2s .c om * @throws ToifException */ @Override public ArrayList<Element> parse(java.io.File process, AdaptorOptions options, IFileResolver resolver, boolean[] validLines, boolean unknownCWE) throws ToifException { // InputStream inputStream = null; try { InputStream fis = null; String theString = ""; try { fis = new FileInputStream(process); StringWriter writer = new StringWriter(); IOUtils.copy(fis, writer, "UTF-8"); theString = writer.toString(); } finally { if (fis != null) fis.close(); } // inputStream = new ByteArrayInputStream(theString.getBytes(StandardCharsets.UTF_8)); // Thread stderr; final FindBugsParser parser = new FindBugsParser(getProperties(), resolver, getAdaptorName(), unknownCWE); // final ByteArrayOutputStream errStream = new ByteArrayOutputStream(); /* * The two streams could probably be merged with redirectErrorStream(), that was we would only * have to deal with one stream. */ // stderr = new Thread(new StreamGobbler(inputStream, errStream)); // // stderr.start(); // stderr.join(); // // final byte[] data = errStream.toByteArray(); // final ByteArrayInputStream in = new ByteArrayInputStream(data); final XMLReader rdr = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); rdr.setContentHandler(parser); rdr.parse(new InputSource(new StringReader(theString))); // return the elements gathered during the parse. ArrayList<Element> elements = parser.getElements(); return elements; } catch (final SAXException e) { final String msg = getAdaptorName() + ": Possibly the file the tool is run against is too large, the wrong kind of file, or not just one file."; LOG.error(msg, e); e.printStackTrace(); throw new ToifException(msg); } catch (final IOException e) { final String msg = getAdaptorName() + ": Possibly the file the tool is run against is too large, the wrong kind of file, or not just one file."; LOG.error(msg, e); throw new ToifException(msg); } // finally // { // if(inputStream != null) { // try { // inputStream.close(); // } // catch (IOException e) { // e.printStackTrace(); // } // } // } // catch (final InterruptedException e) { // final String msg = getAdaptorName() // + ": Possibly the file the tool is run against is too large, the wrong kind of file, or not // just one file."; // // LOG.error(msg, e); // throw new ToifException(msg); // // } }
From source file:com.prowidesoftware.swift.io.parser.MxParser.java
/** * Non-namespace aware parse.<br /> * Parses the complete message content into an {@link MxNode} tree structure. * The parser should be initialized with a valid source. * * @since 7.7/* w ww.j a v a 2 s . c o m*/ */ public MxNode parse() { Validate.notNull(buffer, "the source must be initialized"); try { final javax.xml.parsers.SAXParserFactory spf = javax.xml.parsers.SAXParserFactory.newInstance(); spf.setNamespaceAware(true); final javax.xml.parsers.SAXParser saxParser = spf.newSAXParser(); final MxNodeContentHandler contentHandler = new MxNodeContentHandler(); final org.xml.sax.XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new org.xml.sax.InputSource(new StringReader(this.buffer))); return contentHandler.getRootNode(); } catch (final Exception e) { log.log(Level.SEVERE, "Error parsing: ", e); } return null; }
From source file:com.typhoon.newsreader.engine.ChannelRefresh.java
public long syncDB(Handler h, long id, String rssurl) throws Exception { mHandler = h;/*ww w . j a va 2 s. c o m*/ mID = id; mRSSURL = rssurl; SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(this); xr.setErrorHandler(this); URL url = new URL(mRSSURL); URLConnection c = url.openConnection(); c.setRequestProperty("User-Agent", "Android/m3-rc37a"); xr.parse(new InputSource(c.getInputStream())); return mID; }
From source file:com.frostwire.gui.updates.UpdateMessageReader.java
public void readUpdateFile() { HttpURLConnection connection = null; InputSource src = null;//from w ww . jav a 2 s . c om try { String userAgent = "FrostWire/" + OSUtils.getOS() + "-" + OSUtils.getArchitecture() + "/" + FrostWireUtils.getFrostWireVersion(); connection = (HttpURLConnection) (new URL(getUpdateURL())).openConnection(); String url = getUpdateURL(); System.out.println("Reading update file from " + url); connection.setRequestProperty("User-Agent", userAgent); connection.setRequestProperty("Connection", "close"); connection.setReadTimeout(10000); // 10 secs timeout if (connection.getResponseCode() >= 400) { // invalid URL for sure connection.disconnect(); return; } src = new InputSource(connection.getInputStream()); XMLReader rdr = XMLReaderFactory .createXMLReader("com.sun.org.apache.xerces.internal.parsers.SAXParser"); rdr.setContentHandler(this); rdr.parse(src); connection.getInputStream().close(); connection.disconnect(); } catch (java.net.SocketTimeoutException e3) { System.out.println("UpdateMessageReadre.readUpdateFile() Socket Timeout Exeception " + e3.toString()); } catch (IOException e) { System.out.println("UpdateMessageReader.readUpdateFile() IO exception " + e.toString()); } catch (SAXException e2) { System.out.println("UpdateMessageReader.readUpdateFile() SAX exception " + e2.toString()); } }
From source file:com.sonicle.webtop.core.io.input.ExcelFileReader.java
public HashMap<String, String> listXlsxColumnNames(File file) throws IOException, FileReaderException { OPCPackage opc = null;// ww w. j a v a2 s.c om try { opc = OPCPackage.open(file, PackageAccess.READ); XSSFReader reader = new XSSFReader(opc); ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(opc); StylesTable styles = reader.getStylesTable(); XlsxColumnsHandler columnsHandler = null; XSSFReader.SheetIterator sit = (XSSFReader.SheetIterator) reader.getSheetsData(); while (sit.hasNext()) { InputStream is = null; try { is = sit.next(); if (StringUtils.equals(sit.getSheetName(), sheet)) { XMLReader xmlReader = SAXHelper.newXMLReader(); columnsHandler = new XlsxColumnsHandler(is, headersRow, firstDataRow, lastDataRow); ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, columnsHandler, fmt, false); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(is)); } } catch (SAXException | ParserConfigurationException ex) { throw new FileReaderException(ex, "Error processing file content"); } catch (NullPointerException ex) { // Thrown when stream is forcibly closed. Simply ignore this! } finally { IOUtils.closeQuietly(is); } if (columnsHandler != null) break; } return columnsHandler.columnNames; } catch (OpenXML4JException | SAXException ex) { throw new FileReaderException(ex, "Error opening file"); } finally { IOUtils.closeQuietly(opc); } }
From source file:com.sonicle.webtop.core.io.input.ExcelFileReader.java
public HashMap<String, Integer> listXlsxColumnIndexes(File file) throws IOException, FileReaderException { OPCPackage opc = null;//w w w . j a va 2s .co m try { opc = OPCPackage.open(file, PackageAccess.READ); XSSFReader reader = new XSSFReader(opc); ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(opc); StylesTable styles = reader.getStylesTable(); XlsxColumnsHandler columnsHandler = null; XSSFReader.SheetIterator sit = (XSSFReader.SheetIterator) reader.getSheetsData(); while (sit.hasNext()) { InputStream is = null; try { is = sit.next(); if (StringUtils.equals(sit.getSheetName(), sheet)) { XMLReader xmlReader = SAXHelper.newXMLReader(); columnsHandler = new XlsxColumnsHandler(is, headersRow, firstDataRow, lastDataRow); ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, columnsHandler, fmt, false); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(is)); } } catch (SAXException | ParserConfigurationException ex) { throw new FileReaderException(ex, "Error processing file content"); } catch (NullPointerException ex) { // Thrown when stream is forcibly closed. Simply ignore this! } finally { IOUtils.closeQuietly(is); } if (columnsHandler != null) break; } return columnsHandler.columnIndexes; } catch (OpenXML4JException | SAXException ex) { throw new FileReaderException(ex, "Error opening file"); } finally { IOUtils.closeQuietly(opc); } }
From source file:de.ks.idnadrev.expimp.xls.SingleSheetImport.java
@Override public Void call() throws Exception { try {/*from w ww. j a v a 2 s . co m*/ XMLReader parser = XMLReaderFactory.createXMLReader(); ImportSheetHandler importSheetHandler = new ImportSheetHandler(clazz, reader.getSharedStringsTable(), columnProvider, this::importEntity); parser.setContentHandler(importSheetHandler); InputSource inputSource = new InputSource(sheetStream); parser.parse(inputSource); } catch (SAXException | IOException | InvalidFormatException e) { result.generalError("Failed to parse sheet " + clazz.getName(), e); throw new RuntimeException(e); } finally { try { sheetStream.close(); } catch (IOException e) { result.generalError("Could not close sheet stream " + clazz.getName(), e); throw new RuntimeException(e); } return null; } }
From source file:org.apache.uima.ruta.resource.TreeWordList.java
public void readXML(InputStream stream, String encoding) throws IOException { try {/*from w w w .ja v a2 s. com*/ InputStream is = new BufferedInputStream(stream); // adds mark/reset support boolean isXml = MultiTreeWordListPersistence.isSniffedXmlContentType(is); if (!isXml) { // MTWL is encoded is = new ZipInputStream(is); ((ZipInputStream) is).getNextEntry(); // zip must contain a single entry } InputStreamReader streamReader = new InputStreamReader(is, encoding); this.root = new TextNode(); XMLEventHandler handler = new XMLEventHandler(root); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); // XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.setErrorHandler(handler); reader.parse(new InputSource(streamReader)); } catch (SAXParseException spe) { StringBuffer sb = new StringBuffer(spe.toString()); sb.append("\n Line number: " + spe.getLineNumber()); sb.append("\n Column number: " + spe.getColumnNumber()); sb.append("\n Public ID: " + spe.getPublicId()); sb.append("\n System ID: " + spe.getSystemId() + "\n"); System.out.println(sb.toString()); } catch (SAXException se) { System.out.println("loadDOM threw " + se); se.printStackTrace(System.out); } catch (ParserConfigurationException e) { e.printStackTrace(); } }
From source file:net.vivekiyer.GAL.ActiveSyncManager.java
/** * @param xml The XML to parse //from ww w .ja v a 2 s.c om * @param nodeName The Node to search for in the XML * @return List of strings found in the specified node * @throws Exception * * This method parses the an XML string and returns all values that were found * in the node specified in the request */ private String[] parseXML(String xml, String nodeName) throws Exception { // Our parser does not handle ampersands too well. Replace with & xml = xml.replaceAll("&", "&"); // Parse the XML ByteArrayInputStream xmlParseInputStream = new ByteArrayInputStream(xml.toString().getBytes()); XMLReader xr = XMLReaderFactory.createXMLReader(); XMLParser parser = new XMLParser(nodeName); xr.setContentHandler(parser); xr.parse(new InputSource(xmlParseInputStream)); return parser.getOutput(); }