List of usage examples for org.xml.sax XMLReader parse
public void parse(String systemId) throws IOException, SAXException;
From source file:Examples.java
/** * Show the Transformer using SAX events in and DOM nodes out. *//* ww w . j av a 2s . c om*/ public static void exampleContentHandler2DOM(String sourceID, String xslID) throws TransformerException, TransformerConfigurationException, SAXException, IOException, ParserConfigurationException { TransformerFactory tfactory = TransformerFactory.newInstance(); // Make sure the transformer factory we obtained supports both // DOM and SAX. if (tfactory.getFeature(SAXSource.FEATURE) && tfactory.getFeature(DOMSource.FEATURE)) { // We can now safely cast to a SAXTransformerFactory. SAXTransformerFactory sfactory = (SAXTransformerFactory) tfactory; // Create an Document node as the root for the output. DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); org.w3c.dom.Document outNode = docBuilder.newDocument(); // Create a ContentHandler that can liston to SAX events // and transform the output to DOM nodes. TransformerHandler handler = sfactory.newTransformerHandler(new StreamSource(xslID)); handler.setResult(new DOMResult(outNode)); // Create a reader and set it's ContentHandler to be the // transformer. 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); reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); // Send the SAX events from the parser to the transformer, // and thus to the DOM tree. reader.parse(sourceID); // Serialize the node for diagnosis. exampleSerializeNode(outNode); } else { System.out.println( "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory"); } }
From source file:com.zegoggles.smssync.XOAuthConsumer.java
protected String getUsernameFromContacts() { final HttpClient httpClient = new DefaultHttpClient(); final String url = "https://www.google.com/m8/feeds/contacts/default/thin?max-results=1"; final StringBuilder email = new StringBuilder(); try {//from www.j a v a 2s .c o m HttpGet get = new HttpGet(sign(url)); HttpResponse resp = httpClient.execute(get); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(new DefaultHandler() { boolean inEmail; @Override public void startElement(String uri, String localName, String qName, Attributes atts) { inEmail = "email".equals(localName); } @Override public void characters(char[] c, int start, int length) { if (inEmail) { email.append(c, start, length); } } }); xr.parse(new InputSource(resp.getEntity().getContent())); return email.toString(); } catch (oauth.signpost.exception.OAuthException e) { Log.e(TAG, "error", e); return null; } catch (org.xml.sax.SAXException e) { Log.e(TAG, "error", e); return null; } catch (java.io.IOException e) { Log.e(TAG, "error", e); return null; } catch (javax.xml.parsers.ParserConfigurationException e) { Log.e(TAG, "error", e); return null; } }
From source file:com.travelguide.GuideActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); final String TAG = "Activity2"; String ln = getIntent().getExtras().getString("tag"); if ((ln.equals("Espaol")) || (ln.equals("Spanish"))) { TextView t1 = (TextView) findViewById(R.id.thanks); t1.setText("Gracias por usar mi aplicacin."); TextView t2 = (TextView) findViewById(R.id.link); t2.setText("Las ubicaciones de visitantes en el interior " + getIntent().getExtras().getString("com.travelguide.radius") + " millas para " + getIntent().getExtras().getString("com.travelguide.location")); } else {/* w w w.ja v a 2 s. c om*/ TextView t1 = (TextView) findViewById(R.id.thanks); t1.setText("Thanks for using my App."); TextView t2 = (TextView) findViewById(R.id.link); t2.setText( "Visitor locations found within " + getIntent().getExtras().getString("com.travelguide.radius") + " miles for " + getIntent().getExtras().getString("com.travelguide.location")); } String url = getIntent().getExtras().getString("com.travelguide.link"); Log.i(TAG, url); try { //***** Parsing the xml file***** SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); tgparse myXML_parser = new tgparse(); xr.setContentHandler(myXML_parser); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.replace(" ", "%20")); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); Log.i(TAG, "responseBody: " + responseBody); ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); Log.i(TAG, "parse complete"); TextView placename[]; TextView placeaddress[]; TextView placerating[]; tgxml data; data = tgparse.getXMLData(); placename = new TextView[data.getName().size()]; placeaddress = new TextView[data.getName().size()]; placerating = new TextView[data.getName().size()]; webview = (WebView) findViewById(R.id.myWebView); // webview.setBackgroundColor(0); // webview.setBackgroundResource(R.drawable.openbook); String stg1 = new String(); stg1 = "<html>"; for (int i = 1; i < (data.getName().size()); i++) { Log.i(TAG, " " + i); Log.i(TAG, "Name= " + data.getName().get(i)); Log.i(TAG, "Address= " + data.getAddress().get(i)); Log.i(TAG, "Rating= " + data.getRating().get(i)); placename[i] = new TextView(this); placename[i].setText("Name= " + data.getName().get(i)); placeaddress[i] = new TextView(this); placeaddress[i].setText("Address= " + data.getAddress().get(i)); placerating[i] = new TextView(this); placerating[i].setText("Rating= " + data.getRating().get(i)); if ((ln.equals("Espaol")) || (ln.equals("Spanish"))) { stg1 = stg1 + "Nombre: " + data.getName().get(i) + "<br>" + " Direccin: " + data.getAddress().get(i) + "<br>" + " clasificacin= " + data.getRating().get(i) + "<br>" + "<br>"; } else { stg1 = stg1 + "Name: " + data.getName().get(i) + "<br>" + " Address: " + data.getAddress().get(i) + "<br>" + " Rating= " + data.getRating().get(i) + "<br>" + "<br>"; } } stg1 = stg1 + "</html>"; webview.loadDataWithBaseURL(null, stg1, "text/html", "utf-8", "about:blank"); } catch (Exception e) { Log.i(TAG, "Exception caught", e); } }
From source file:org.energyos.espi.common.service.impl.ImportServiceImpl.java
@Override public void importData(InputStream stream, Long retailCustomerId) throws IOException, SAXException, ParserConfigurationException { // setup the parser JAXBContext context = marshaller.getJaxbContext(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true);/*from w ww . j a v a 2 s . com*/ XMLReader reader = factory.newSAXParser().getXMLReader(); // EntryProcessor processor = new EntryProcessor(resourceLinker, new // ResourceConverter(), resourceService); ATOMContentHandler atomContentHandler = new ATOMContentHandler(context, entryProcessorService); reader.setContentHandler(atomContentHandler); // do the parse/import try { reader.parse(new InputSource(stream)); } catch (SAXException e) { System.out.printf( "\nImportServiceImpl -- importData: SAXException\n Cause = %s\n Description = %s\n\n", e.getClass(), e.getMessage()); throw new SAXException(e.getMessage(), e); } catch (Exception e) { System.out.printf("\nImportServiceImpl -- importData:\n Cause = %s\n Description = %s\n\n", e.getClass(), e.getMessage()); e.printStackTrace(); } // context of the import used for linking things up // and establishing notifications // entries = atomContentHandler.getEntries(); minUpdated = atomContentHandler.getMinUpdated(); maxUpdated = atomContentHandler.getMaxUpdated(); // cleanup/end processing // 1 - associate to usage points to the right retail customer // 2 - make sure authorization/subscriptions have the right URIs // 3 - place the imported usagePoints in to the subscriptions // List<UsagePoint> usagePointList = new ArrayList<UsagePoint>(); // now perform any associations (to RetailCustomer) and stage the // Notifications (if any) RetailCustomer retailCustomer = null; if (retailCustomerId != null) { retailCustomer = retailCustomerService.findById(retailCustomerId); } Iterator<EntryType> its = entries.iterator(); while (its.hasNext()) { EntryType entry = its.next(); UsagePoint usagePoint = entry.getContent().getUsagePoint(); if (usagePoint != null) { // see if we already have a retail customer association RetailCustomer tempRc = usagePoint.getRetailCustomer(); if (tempRc != null) { // hook it to the retailCustomer if (!(tempRc.equals(retailCustomer))) { // we have a conflict in association meaning to Retail // Customers // TODO: resolve how to handle the conflict mentioned // above. // TODO: Only works for a single customer and not // multiple customers retailCustomer = tempRc; } } else { // associate the usagePoint with the Retail Customer if (retailCustomer != null) { usagePointService.associateByUUID(retailCustomer, usagePoint.getUUID()); } } usagePointList.add(usagePoint); } } // now if we have a retail customer, check for any subscriptions that // need associated if (retailCustomer != null) { Subscription subscription = null; // find and iterate across all relevant authorizations // List<Authorization> authorizationList = authorizationService .findAllByRetailCustomerId(retailCustomer.getId()); for (Authorization authorization : authorizationList) { try { subscription = subscriptionService.findByAuthorizationId(authorization.getId()); } catch (Exception e) { // an Authorization w/o an associated subscription breaks // the propagation chain System.out.printf("**** End of Notification Propagation Chain\n"); } if (subscription != null) { String resourceUri = authorization.getResourceURI(); // this is the first time this authorization has been in // effect. We must set up the appropriate resource links if (resourceUri == null) { ApplicationInformation applicationInformation = authorization.getApplicationInformation(); resourceUri = applicationInformation.getDataCustodianResourceEndpoint(); resourceUri = resourceUri + "/Batch/Subscription/" + subscription.getId(); authorization.setResourceURI(resourceUri); resourceService.merge(authorization); } // make sure the UsagePoint(s) we just imported are linked // up // with // the Subscription for (UsagePoint usagePoint : usagePointList) { boolean addNew = false; for (UsagePoint up : subscription.getUsagePoints()) { if (up.equals(usagePoint)) addNew = true; } if (addNew) subscriptionService.addUsagePoint(subscription, usagePoint); } } } } }
From source file:cm.aptoide.pt.Aptoide.java
private void parseXmlString(String file) { SAXParserFactory spf = SAXParserFactory.newInstance(); try {/*from w w w . ja v a 2 s . co m*/ keepScreenOn.acquire(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); NewServerRssHandler handler = new NewServerRssHandler(this); xr.setContentHandler(handler); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(file)); xr.parse(is); server_lst = handler.getNewSrvs(); get_apks = handler.getNewApks(); keepScreenOn.release(); } catch (IOException e) { } catch (SAXException e) { } catch (ParserConfigurationException e) { } }
From source file:com.penbase.dma.Dalyo.HTTPConnection.DmaHttpClient.java
/** * Gets the resources of an application/*from w ww . j av a 2 s .c om*/ */ public void getResource(String urlRequest) { if (mSendResource) { StringBuffer getResources = new StringBuffer("act=getresources"); getResources.append(urlRequest); byte[] bytes = sendPost(getResources.toString()); SAXParserFactory spFactory = SAXParserFactory.newInstance(); SAXParser saxParser; try { saxParser = spFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); EventsHandler eventsHandler = new EventsHandler(urlRequest); xmlReader.setContentHandler(eventsHandler); xmlReader.parse(new InputSource(new ByteArrayInputStream(bytes))); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Common.streamToFile(bytes, mResources_XML, false); } else { SAXParserFactory spFactory = SAXParserFactory.newInstance(); SAXParser saxParser; try { saxParser = spFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); EventsHandler eventsHandler = new EventsHandler(urlRequest); xmlReader.setContentHandler(eventsHandler); xmlReader.parse(new InputSource(new FileInputStream(new File(mResources_XML)))); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.amazonaws.eclipse.dynamodb.testtool.TestToolManager.java
/** * Parse a manifest file describing a list of test tool versions. * * @param file The file to parse.//from w w w .j a v a2s . c o m * @return The parsed list of versions. * @throws IOException on error. */ private List<TestToolVersion> parseManifest(final File file) throws IOException { FileInputStream stream = null; try { stream = new FileInputStream(file); BufferedReader buffer = new BufferedReader(new InputStreamReader(stream)); ManifestContentHandler handler = new ManifestContentHandler(); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.setErrorHandler(handler); reader.parse(new InputSource(buffer)); return handler.getResult(); } catch (SAXException exception) { throw new IOException("Error parsing DynamoDB Local manifest file", exception); } finally { if (stream != null) { stream.close(); } } }
From source file:com.mirth.connect.plugins.datatypes.edi.EDISerializer.java
@Override public String fromXML(String source) throws MessageSerializerException { XMLReader xr; try {//ww w. j a va2 s .co m xr = XMLReaderFactory.createXMLReader(); } catch (SAXException e) { throw new MessageSerializerException("Error converting XML to EDI", e, ErrorMessageBuilder .buildErrorMessage(this.getClass().getSimpleName(), "Error converting XML to EDI", e)); } EDIXMLHandler handler = new EDIXMLHandler(); xr.setContentHandler(handler); xr.setErrorHandler(handler); try { //Parse, but first replace all spaces between brackets. This fixes pretty-printed XML we might receive xr.parse(new InputSource(new StringReader( prettyPattern2.matcher(prettyPattern1.matcher(source).replaceAll("<$1>")).replaceAll("<$1>")))); } catch (Exception e) { throw new MessageSerializerException("Error converting XML to EDI", e, ErrorMessageBuilder .buildErrorMessage(this.getClass().getSimpleName(), "Error converting XML to EDI", e)); } return handler.getOutput().toString(); }
From source file:cm.aptoide.pt.Aptoide.java
private void getRemoteServLst(String file) { SAXParserFactory spf = SAXParserFactory.newInstance(); try {/*from ww w . ja v a 2s . com*/ keepScreenOn.acquire(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); NewServerRssHandler handler = new NewServerRssHandler(this); xr.setContentHandler(handler); InputStreamReader isr = new FileReader(new File(file)); InputSource is = new InputSource(isr); xr.parse(is); File xml_file = new File(file); xml_file.delete(); server_lst = handler.getNewSrvs(); get_apks = handler.getNewApks(); keepScreenOn.release(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } }