List of usage examples for org.xml.sax XMLReader parse
public void parse(String systemId) throws IOException, SAXException;
From source file:com.surveypanel.form.xml.ParserHelper.java
/** * Return a reader to parse content/*w ww . j av a 2 s .c o m*/ * @param path * @return */ protected static FormValuesHandler getReader(InputStream is) { FormValuesHandler formValuesHandler = new FormValuesHandler(); XMLReader parser = null; try { InputStreamReader inputStreamReader = new InputStreamReader(is, "UTF-8"); parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(formValuesHandler); parser.setErrorHandler(formValuesHandler); InputSource inputSource = new InputSource(inputStreamReader); parser.parse(inputSource); } catch (Exception e) { e.printStackTrace(); } return formValuesHandler; }
From source file:com.textocat.textokit.commons.io.axml.AXMLReader.java
/** * Populate the specified CAS by a text and annotations from the specified * input assuming that it is formatted as described above. * * @param in input Reader. It is a caller's responsibility to close this * reader instance.// ww w.j ava2 s . c o m * @param cas CAS * @throws IOException * @throws SAXException */ public static void read(Reader in, final CAS cas) throws IOException, SAXException { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); AXMLContentHandler contentHandler = new AXMLContentHandler(cas.getTypeSystem()); xmlReader.setContentHandler(contentHandler); InputSource inputSource = new InputSource(in); xmlReader.parse(inputSource); cas.setDocumentText(contentHandler.getText()); // from axml ID to CAS FS final Map<Annotation, FeatureStructure> mapped = Maps.newHashMap(); List<Runnable> delayedFeatureAssignments = Lists.newLinkedList(); // for (Annotation _anno : contentHandler.getAnnotations()) { String typeName = _anno.getType(); Type type = cas.getTypeSystem().getType(typeName); if (type == null) { throw new IllegalStateException(String.format("Unknown type: %s", typeName)); } final AnnotationFS anno = cas.createAnnotation(type, _anno.getBegin(), _anno.getEnd()); // set primitive features for (String featName : _anno.getFeatureNames()) { final Feature feat = type.getFeatureByBaseName(featName); if (feat == null) throw new IllegalStateException( String.format("%s does not have feature %s", type.getName(), featName)); if (feat.getRange().isPrimitive()) { String featValStr = _anno.getFeatureStringValue(featName); if (featValStr != null) { anno.setFeatureValueFromString(feat, featValStr); } } else { if (feat.getRange().isArray()) { final List<Annotation> srcFSes = _anno.getFeatureFSArrayValue(featName); delayedFeatureAssignments.add(new Runnable() { @Override public void run() { List<FeatureStructure> mappedFSes = Lists.transform(srcFSes, new Function<Annotation, FeatureStructure>() { @Override public FeatureStructure apply(Annotation srcFS) { FeatureStructure mappedFS = mapped.get(srcFS); if (mappedFS == null) throw new IllegalStateException(); return mappedFS; } }); anno.setFeatureValue(feat, FSCollectionFactory.createArrayFS(cas, mappedFSes)); } }); } else { final Annotation srcFS = _anno.getFeatureFSValue(featName); delayedFeatureAssignments.add(new Runnable() { @Override public void run() { FeatureStructure mappedFS = mapped.get(srcFS); if (mappedFS == null) throw new IllegalStateException(); anno.setFeatureValue(feat, mappedFS); } }); } } } cas.addFsToIndexes(anno); mapped.put(_anno, anno); } // PHASE II -- set FS and FSArray features for (Runnable r : delayedFeatureAssignments) { r.run(); } }
From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java
/** * Validates an XML document, capturing the messages into an XML document that includes * any @xtrc values pointing back into the original DOCX file from which the XML was * generated. The resulting document can be used to then annotate the original DOCX * file with messages bound to the original source paragraphs. * @param messageFile The file to hold the XML message log. * @param inputUrl The URL of the document to be validated. * @param catalogs List of entity resolution catalogs to be used by the parser (as for the Resolver class). * @return DOM document containing the log messages. Also saves the messages to the specified file. * @throws IOException//www . ja v a2 s . c o m * @throws ParserConfigurationException * @throws Exception * @throws SAXException * @throws FileNotFoundException */ public static Document validateXml(File messageFile, URL inputUrl, String[] catalogs) throws IOException, ParserConfigurationException, Exception, SAXException, FileNotFoundException { InputSource source = new InputSource(inputUrl.openStream()); Document logDoc = DomUtil.getNewDom(); XMLReader reader = SaxUtil.getXMLFormatLoggingXMLReader(log, logDoc, true, catalogs); reader.parse(source); InputStream logStream = DomUtil.serializeToInputStream(logDoc, "utf-8"); System.out.println("Creating message file \"" + messageFile.getAbsolutePath() + "\"..."); OutputStream fos = new FileOutputStream(messageFile); IOUtils.copy(logStream, fos); return logDoc; }
From source file:info.unyttig.helladroid.newzbin.NewzBinController.java
/** * Fetches a report from Newzbin based on a given id. * However if the report is already cached, its just fetched from the hashmap. * @param id//from w ww . j a v a2 s . c o m */ public static NewzBinReport getReportInfo(int id) { if (detailedReports.containsKey(id)) return detailedReports.get(id); String url = NBAPIURL + "reportinfo/"; HashMap<String, String> searchOptions = new HashMap<String, String>(); searchOptions.put("id", "" + id); try { HttpResponse response = doPost(url, searchOptions); checkReturnCode(response.getStatusLine().getStatusCode(), false); InputStream is = response.getEntity().getContent(); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); NewzBinDRHandler handler = new NewzBinDRHandler(); if (reports.containsKey(id)) handler.nbdr = reports.get(id); xr.setContentHandler(handler); xr.parse(new InputSource(is)); detailedReports.put(id, handler.getParsedData()); // Temp ArrayList<NewzBinReportComment> comments = handler.nbdr.getComments(); Log.i(LOG_NAME, "Comments size: " + comments.size()); Iterator<NewzBinReportComment> sd = comments.iterator(); while (sd.hasNext()) { NewzBinReportComment nrc = sd.next(); Log.i(LOG_NAME, nrc.toString()); } return handler.getParsedData(); } catch (ClientProtocolException e) { Log.e(LOG_NAME, "ClientProtocol thrown: ", e); } catch (IOException e) { Log.e(LOG_NAME, "IOException thrown: ", e); } catch (NewzBinPostReturnCodeException e) { Log.e(LOG_NAME, "POST ReturnCode error: " + e.toString()); } catch (ParserConfigurationException e) { Log.e(LOG_NAME, "ParserError thrown: ", e); } catch (SAXException e) { Log.e(LOG_NAME, "SAXError thrown: ", e); } return null; }
From source file:XMLUtilities.java
/** * Convenience method for parsing an XML file. This method will * wrap the resource in an InputSource and set the source's * systemId to "jedit.jar" (so the source should be able to * handle any external entities by itself). * * <p>SAX Errors are caught and are not propagated to the caller; * instead, an error message is printed to jEdit's activity * log. So, if you need custom error handling, <b>do not use * this method</b>.//w w w. j av a2 s .c o m * * <p>The given stream is closed before the method returns, * regardless whether there were errors or not.</p> * * @return true if any error occured during parsing, false if success. */ public static boolean parseXML(InputStream in, DefaultHandler handler) throws IOException { try { XMLReader parser = XMLReaderFactory.createXMLReader(); InputSource isrc = new InputSource(new BufferedInputStream(in)); isrc.setSystemId("jedit.jar"); parser.setContentHandler(handler); parser.setDTDHandler(handler); parser.setEntityResolver(handler); parser.setErrorHandler(handler); parser.parse(isrc); } catch (SAXParseException se) { int line = se.getLineNumber(); return true; } catch (SAXException e) { return true; } finally { try { if (in != null) in.close(); } catch (IOException io) { } } return false; }
From source file:net.ontopia.persistence.rdbms.DatabaseProjectReader.java
public static Project loadProject(InputSource isource) throws IOException, SAXException { ProjectHandler handler = new ProjectHandler(); XMLReader parser = DefaultXMLReaderFactory.createXMLReader(); parser.setContentHandler(handler);/*from w w w . j ava2s .c om*/ parser.parse(isource); return handler.project; }
From source file:net.ontopia.topicmaps.entry.XMLConfigSource.java
private static List<TopicMapSourceIF> readSources(InputSource inp_source, Map<String, String> environ) { ConfigHandler handler = new ConfigHandler(environ); try {// w w w . ja va2 s. c o m XMLReader parser = DefaultXMLReaderFactory.createXMLReader(); parser.setContentHandler(handler); parser.setErrorHandler(new Slf4jSaxErrorHandler(log)); parser.parse(inp_source); } catch (SAXParseException e) { String msg = "" + e.getSystemId() + ":" + e.getLineNumber() + ":" + e.getColumnNumber() + ": " + e.getMessage(); throw new OntopiaRuntimeException(msg, e); } catch (Exception e) { throw new OntopiaRuntimeException(e); } return handler.sources; }
From source file:com.puppycrawl.tools.checkstyle.XmlTreeWalker.java
/** * Static helper method to parses a Java source file. * * @param source// w w w . j ava 2s.co m * contains the contents of the file * @throws TokenStreamException * if lexing failed * @throws RecognitionException * if parsing failed * @return the root of the AST */ public static DetailAST parse(InputSource source, File file) throws IOException, XMLStreamException, SAXException { XMLReader reader = XMLReaderFactory.createXMLReader(); XmlContentHandler contentHandler = new XmlContentHandler(file); reader.setContentHandler(contentHandler); reader.parse(source); return contentHandler.getAST(); }
From source file:nl.b3p.kaartenbalie.service.ImageCollector.java
/** * * @param byteStream InputStream object in which the serviceexception is stored. * * @ return String with the given exception * * @throws IOException, SAXException/*from ww w . j a va2 s.co m*/ */ private static String getServiceException(InputStream byteStream) throws IOException, SAXException { Switcher s = new Switcher(); s.setElementHandler("ServiceException", new ServiceExceptionHandler()); XMLReader reader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); IgnoreEntityResolver r = new IgnoreEntityResolver(); reader.setEntityResolver(r); reader.setContentHandler(s); InputSource is = new InputSource(byteStream); is.setEncoding(KBConfiguration.CHARSET); reader.parse(is); return (String) stack.pop(); }
From source file:it.osm.gtfs.input.OSMParser.java
public static List<Relation> readOSMRelations(File file, Map<String, Stop> stopsWithOSMIndex) throws ParserConfigurationException, SAXException, IOException { NodeParser nodeParser;/* w w w . jav a 2 s. c o m*/ { XMLReader xr = XMLReaderFactory.createXMLReader(); nodeParser = new NodeParser(); xr.setContentHandler(nodeParser); xr.setErrorHandler(nodeParser); xr.parse(new InputSource(new FileReader(file))); } WayParser wayParser; { XMLReader xr = XMLReaderFactory.createXMLReader(); wayParser = new WayParser(nodeParser.result); xr.setContentHandler(wayParser); xr.setErrorHandler(wayParser); xr.parse(new InputSource(new FileReader(file))); } RelationParser relationParser; { XMLReader xr = XMLReaderFactory.createXMLReader(); relationParser = new RelationParser(stopsWithOSMIndex, wayParser.result); xr.setContentHandler(relationParser); xr.setErrorHandler(relationParser); xr.parse(new InputSource(new FileReader(file))); } if (relationParser.missingNodes.size() > 0 || relationParser.failedRelationIds.size() > 0) { System.err.println("Failed to parse some relations. Relations id: " + StringUtils.join(relationParser.failedRelationIds, ", ")); System.err.println("Failed to parse some relations. Missing nodes: " + StringUtils.join(relationParser.missingNodes, ", ")); } return relationParser.result; }