List of usage examples for org.xml.sax XMLReader parse
public void parse(String systemId) throws IOException, SAXException;
From source file:com.mirth.connect.plugins.datatypes.hl7v2.ER7Serializer.java
/** * Returns an ER7-encoded HL7 message given an XML-encoded HL7 message. * /*from www .j a v a2s . c o m*/ * @param source * a XML-encoded HL7 message. * @return */ @Override public String fromXML(String source) throws MessageSerializerException { try { if (deserializationProperties.isUseStrictParser()) { return deserializationPipeParser.encode(deserializationXmlParser.parse(source)); } else { /* * The delimiters below need to come from the XML somehow. The * ER7 handler should take care of it TODO: Ensure you get these * elements from the XML */ String fieldSeparator = getNodeValue(source, "<MSH.1>", "</MSH.1>"); if (StringUtils.isEmpty(fieldSeparator)) { fieldSeparator = "|"; } String componentSeparator = "^"; String repetitionSeparator = "~"; String subcomponentSeparator = "&"; String escapeCharacter = "\\"; /* * Our delimiters usually look like this: * <MSH.2>^~\&</MSH.2> We need to decode XML entities */ String separators = ampersandPattern.matcher(getNodeValue(source, "<MSH.2>", "</MSH.2>")) .replaceAll("&"); if (separators.length() == 4) { // usually ^ componentSeparator = separators.substring(0, 1); // usually ~ repetitionSeparator = separators.substring(1, 2); // usually \ escapeCharacter = separators.substring(2, 3); // usually & subcomponentSeparator = separators.substring(3, 4); } XMLEncodedHL7Handler handler = new XMLEncodedHL7Handler(deserializationSegmentDelimiter, fieldSeparator, componentSeparator, repetitionSeparator, escapeCharacter, subcomponentSeparator, true); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.setErrorHandler(handler); /* * Parse, but first replace all spaces between brackets. This * fixes pretty-printed XML we might receive. */ reader.parse(new InputSource(new StringReader(prettyPattern2 .matcher(prettyPattern1.matcher(source).replaceAll("<$1>")).replaceAll("<$1>")))); return handler.getOutput().toString(); } } catch (Exception e) { throw new MessageSerializerException("Error converting XML to ER7", e, ErrorMessageBuilder .buildErrorMessage(this.getClass().getSimpleName(), "Error converting XML to ER7", e)); } }
From source file:Examples.java
/** * Show the Transformer using SAX events in and SAX events out. *//*ww w .j a va 2 s .co m*/ public static void exampleContentHandlerToContentHandler(String sourceID, String xslID) throws TransformerException, TransformerConfigurationException, SAXException, IOException { TransformerFactory tfactory = TransformerFactory.newInstance(); // Does this factory support SAX features? if (tfactory.getFeature(SAXSource.FEATURE)) { // If so, we can safely cast. SAXTransformerFactory stfactory = ((SAXTransformerFactory) tfactory); // A TransformerHandler is a ContentHandler that will listen for // SAX events, and transform them to the result. TransformerHandler handler = stfactory.newTransformerHandler(new StreamSource(xslID)); // Set the result handling to be a serialization to System.out. Result result = new SAXResult(new ExampleContentHandler()); handler.setResult(result); // Create a reader, and set it's content handler to be the TransformerHandler. XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2) { } if (reader == null) reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); // It's a good idea for the parser to send lexical events. // The TransformerHandler is also a LexicalHandler. reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); // Parse the source XML, and send the parse events to the TransformerHandler. reader.parse(sourceID); } else { System.out.println( "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory"); } }
From source file:SAXTreeViewer.java
/** * <p>This handles building the Swing UI tree.</p> * * @param treeModel Swing component to build upon. * @param base tree node to build on.// w w w . ja v a2s. c o m * @param xmlURI URI to build XML document from. * @throws <code>IOException</code> - when reading the XML URI fails. * @throws <code>SAXException</code> - when errors in parsing occur. */ public void buildTree(DefaultTreeModel treeModel, DefaultMutableTreeNode base, String xmlURI) throws IOException, SAXException { // Create instances needed for parsing XMLReader reader = XMLReaderFactory.createXMLReader(vendorParserClass); ContentHandler jTreeContentHandler = new JTreeContentHandler(treeModel, base); ErrorHandler jTreeErrorHandler = new JTreeErrorHandler(); // Register content handler reader.setContentHandler(jTreeContentHandler); // Register error handler reader.setErrorHandler(jTreeErrorHandler); // Parse InputSource inputSource = new InputSource(xmlURI); reader.parse(inputSource); }
From source file:com.cyberway.issue.crawler.settings.XMLSettingsHandler.java
/** Read the CrawlerSettings object from a specific file. * * @param settings the settings object to be updated with data from the * persistent storage./*w ww . j a v a2 s .c o m*/ * @param f the file to read from. * @return the updated settings object or null if there was no data for this * in the persistent storage. */ protected final CrawlerSettings readSettingsObject(CrawlerSettings settings, File f) { CrawlerSettings result = null; try { InputStream is = null; if (!f.exists()) { // Perhaps the file we're looking for is on the CLASSPATH. // DON'T look on the CLASSPATH for 'settings.xml' files. The // look for 'settings.xml' files happens frequently. Not looking // on classpath for 'settings.xml' is an optimization based on // ASSUMPTION that there will never be a 'settings.xml' saved // on classpath. if (!f.getName().startsWith(settingsFilename)) { is = XMLSettingsHandler.class.getResourceAsStream(f.getPath()); } } else { is = new FileInputStream(f); } if (is != null) { XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); InputStream file = new BufferedInputStream(is); parser.setContentHandler(new CrawlSettingsSAXHandler(settings)); InputSource source = new InputSource(file); source.setSystemId(f.toURL().toExternalForm()); parser.parse(source); result = settings; } } catch (SAXParseException e) { logger.warning(e.getMessage() + " in '" + e.getSystemId() + "', line: " + e.getLineNumber() + ", column: " + e.getColumnNumber()); } catch (SAXException e) { logger.warning(e.getMessage() + ": " + e.getException().getMessage()); } catch (ParserConfigurationException e) { logger.warning(e.getMessage() + ": " + e.getCause().getMessage()); } catch (FactoryConfigurationError e) { logger.warning(e.getMessage() + ": " + e.getException().getMessage()); } catch (IOException e) { logger.warning("Could not access file '" + f.getAbsolutePath() + "': " + e.getMessage()); } return result; }
From source file:se.lu.nateko.edca.svc.DescribeFeatureType.java
/** * Parses an XML response from a DescribeFeatureType request and stores the layer * attribute names and their data types in a GeographyLayer object. * @param xmlResponse A reader wrapped around an InputStream containing the XML response from a DescribeFeatureType request. *//* w w w.ja v a 2s.c om*/ protected boolean parseXMLResponse(Reader xmlResponse) { // Log.d(TAG, "parseXMLResponse(Reader) called."); try { SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory. spfactory.setValidating(false); // Tell the factory not to make validating parsers. SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser. XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler. XMLEventHandler xmlEventHandler = new XMLEventHandler(); xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use. xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls. InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader. xmlReader.parse(source); // Start parsing the XML. } catch (Exception e) { Log.e(TAG, e.toString()); return false; } return true; }
From source file:com.determinato.feeddroid.parser.RssParser.java
/** * Persists RSS item to the database./*from w w w . ja va 2 s . c om*/ * @param id item ID * @param folderId ID of containing folder * @param rssurl URL of RSS feed * @return long containing ID of inserted item * @throws Exception */ public long syncDb(long id, long folderId, String rssurl) throws Exception { mId = id; mFolderId = folderId; mRssUrl = rssurl; SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(this); reader.setErrorHandler(this); URL url = new URL(mRssUrl); URLConnection c = url.openConnection(); // TODO: Is this a known user agent, or do I need to come up with my own? c.setRequestProperty("User-Agent", "Android/m3-rc37a"); try { BufferedReader bufReader = new BufferedReader(new InputStreamReader(c.getInputStream()), 65535); reader.parse(new InputSource(bufReader)); } catch (NullPointerException e) { Log.e(TAG, Log.getStackTraceString(e)); Log.e(TAG, "Failed to load URL" + url.toString()); } return mId; }
From source file:org.gege.caldavsyncadapter.caldav.CaldavFacade.java
private void parseXML(HttpResponse response, ContentHandler contentHandler) throws IOException, CaldavProtocolException { InputStream is = response.getEntity().getContent(); /*BufferedReader bReader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String Content = "";//from w w w . jav a 2 s.c o m String Line = bReader.readLine(); while (Line != null) { Content += Line; Line = bReader.readLine(); }*/ SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(contentHandler); reader.parse(new InputSource(is)); } catch (ParserConfigurationException e) { throw new AssertionError("ParserConfigurationException " + e.getMessage()); } catch (IllegalStateException e) { throw new CaldavProtocolException(e.getMessage()); } catch (SAXException e) { throw new CaldavProtocolException(e.getMessage()); } }
From source file:es.rczone.tutoriales.gmaps.MainActivity.java
private void cargarKML(String ruta) { try {/*www . jav a2s .co m*/ InputStream is_kml = getResources().getAssets().open(ruta); // create the factory SAXParserFactory factory = SAXParserFactory.newInstance(); // create a parser SAXParser parser; parser = factory.newSAXParser(); // create the reader (scanner) XMLReader xmlreader = parser.getXMLReader(); // instantiate our handler NavigationSaxHandler navSaxHandler = new NavigationSaxHandler(); // assign our handler xmlreader.setContentHandler(navSaxHandler); // get our data via the url class InputSource is = new InputSource(is_kml); // perform the synchronous parse xmlreader.parse(is); // get the results - should be a fully populated RSSFeed instance, or null on error NavigationDataSet ds = navSaxHandler.getParsedData(); Placemark place = ds.getPlacemarks().get(0); ArrayList<String> lista_coordenadas = place.getCoordinates(); LatLng locationToCamera = null; for (String coordenadas : lista_coordenadas) { locationToCamera = draw(coordenadas); } CameraPosition camPos = new CameraPosition.Builder().target(locationToCamera) //Centramos el mapa en Madrid .zoom(9) //Establecemos el zoom en 19 .build(); CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos); map.animateCamera(camUpd3); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.castor.jaxb.CastorUnmarshallerTest.java
/** * Tests the {@link CastorUnmarshaller#getUnmarshallerHandler()} method. * * @throws Exception if any error occurs during test *///from w w w . ja v a 2s . c om @Test public void testGetUnmarshallHandler() throws Exception { UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler(); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); xmlReader.setContentHandler(unmarshallerHandler); xmlReader.parse(new InputSource(new StringReader(INPUT_XML))); Entity entity = (Entity) unmarshallerHandler.getResult(); testEntity(entity); }