List of usage examples for javax.xml.parsers SAXParser getXMLReader
public abstract org.xml.sax.XMLReader getXMLReader() throws SAXException;
From source file:hu.sztaki.lpds.pgportal.services.dspace.LNIclient.java
/** * Completes the two-part operation started by startPut(), by * collecting status of the PUT operation and converting the * WebDAV URI of the newly-created resource back to a Handle, * which it returns.// www . j av a 2s . com * <p> * Any failure results in an exception. * * @return Handle of the newly-created DSpace resource. */ public String finishPut() throws InterruptedException, IOException, SAXException, SAXNotRecognizedException, ParserConfigurationException { if (lastPutThread != null) { lastPutThread.join(); lastPutThread = null; } Header loc = lastPut.getResponseHeader("Location"); lastStatus = lastPut.getStatusCode(); if (lastStatus < 100 || lastStatus >= 400) throw new IOException("PUT returned status = " + lastStatus + "; text=" + lastPut.getStatusText()); lastPut = null; if (loc != null) { String newURL = loc.getValue(); // do a quick PROPFIND to get the handle PropfindMethod pf = new PropfindMethod(newURL, propfindBody); pf.setDoAuthentication(true); client.executeMethod(pf); int pfStatus = pf.getStatusCode(); if (pfStatus < 200 || pfStatus >= 300) throw new IOException( "finishPut.propfind got status = " + pfStatus + "; text=" + pf.getStatusText()); // Maybe move all this crap to within Propfind class?? // so it can get the inputstream directly? SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); PropfindHandler handler = new PropfindHandler(); // XXX FIXME: should turn off validation here explicitly, but // it seems to be off by default. xr.setFeature("http://xml.org/sax/features/namespaces", true); xr.setContentHandler(handler); xr.setErrorHandler(handler); xr.parse(new InputSource(pf.getResponseBodyAsStream())); return handler.handle; } else throw new IOException("PUT response was missing a Location: header."); }
From source file:cm.aptoide.pt.Aptoide.java
private void getRemoteServLst(String file) { SAXParserFactory spf = SAXParserFactory.newInstance(); try {//from w ww.j a va 2 s . c o m 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(); } }
From source file:es.rczone.tutoriales.gmaps.MainActivity.java
private void cargarKML(String ruta) { try {//from w w w . j av a 2 s . c o 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:com.vkassin.mtrade.Common.java
public static String generalWebServiceCall(String urlStr, ContentHandler handler) { String errorMsg = ""; try {/* www . j a v a 2 s . c o m*/ URL url = new URL(urlStr); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setRequestProperty("User-Agent", "Android Application: aMTrade"); urlc.setRequestProperty("Connection", "close"); // urlc.setRequestProperty("Accept-Charset", "windows-1251"); // urlc.setRequestProperty("Accept-Charset", // "windows-1251,utf-8;q=0.7,*;q=0.7"); urlc.setRequestProperty("Accept-Charset", "utf-8"); urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds urlc.setDoInput(true); urlc.connect(); if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) { // Get a SAXParser from the SAXPArserFactory. SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); // Get the XMLReader of the SAXParser we created. XMLReader xr = sp.getXMLReader(); // Apply the handler to the XML-Reader xr.setContentHandler(handler); // Parse the XML-data from our URL. InputStream is = urlc.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(500); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } ByteArrayInputStream bais = new ByteArrayInputStream(baf.toByteArray()); // Reader isr = new InputStreamReader(bais, "windows-1251"); Reader isr = new InputStreamReader(bais, "utf-8"); InputSource ist = new InputSource(); // ist.setEncoding("UTF-8"); ist.setCharacterStream(isr); xr.parse(ist); // Parsing has finished. bis.close(); baf.clear(); bais.close(); is.close(); } urlc.disconnect(); } catch (SAXException e) { // All is OK :) } catch (MalformedURLException e) { Log.e(TAG, errorMsg = "MalformedURLException"); } catch (IOException e) { Log.e(TAG, errorMsg = "IOException"); } catch (ParserConfigurationException e) { Log.e(TAG, errorMsg = "ParserConfigurationException"); } catch (ArrayIndexOutOfBoundsException e) { Log.e(TAG, errorMsg = "ArrayIndexOutOfBoundsException"); } return errorMsg; }
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/* ww w . j a va 2s . com*/ */ 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:fr.paris.lutece.plugins.calendar.web.CalendarStyleSheetJspBean.java
/** * Use parsing for validate the modify xsl file * //from w ww . j av a 2s . co m * @param baXslSource The XSL source * @return the message exception when the validation is false */ private String isValid(byte[] baXslSource) { String strError = null; try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser analyzer = factory.newSAXParser(); InputSource is = new InputSource(new ByteArrayInputStream(baXslSource)); analyzer.getXMLReader().parse(is); } catch (Exception e) { strError = e.getMessage(); } return strError; }
From source file:de.tlabs.ssr.g1.client.XmlInputThread.java
@Override public void run() { Log.d(TAG, "(" + this.getId() + ") HELLO"); try {// w ww . j a va 2s . c om // create sax parser SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); // get an xml reader XMLReader xr = sp.getXMLReader(); // set up xml input source XMLChunkInputStream xmlChunkInputStream; synchronized (GlobalData.socketChannel) { xmlChunkInputStream = new XMLChunkInputStream(new ByteArrayBuffer(32 * 1024), GlobalData.socketChannel.socket().getInputStream()); } InputSource inputSource = new InputSource(xmlChunkInputStream); // create handler for scene description and assign it SceneDescrXMLHandler sceneDescrXMLHandler = new SceneDescrXMLHandler(GlobalData.audioScene); xr.setContentHandler(sceneDescrXMLHandler); // parse scene description //Log.d(TAG, "(" + this.getId() + ") parsing description..."); //xmlChunkInputStream.printToLog = true; while (xmlChunkInputStream.bufferNextChunk() && !sceneDescrXMLHandler.receivedSceneDescr()) { // parse and process xml input xr.parse(inputSource); } //xmlChunkInputStream.printToLog = false; // signal that scene description was parsed //Log.d(TAG, "(" + this.getId() + ") sending SCENEPARSED_OK_MSG"); GlobalData.sourcesMoverMsgHandler .sendMessage(GlobalData.sourcesMoverMsgHandler.obtainMessage(SourcesMover.SCENEPARSED_OK_MSG)); // create handler for scene updates and assign it SceneUpdateXMLHandler sceneUpdateXMLHandler = new SceneUpdateXMLHandler(GlobalData.audioScene); xr.setContentHandler(sceneUpdateXMLHandler); // parse scene updates Log.d(TAG, "(" + this.getId() + ") starting xml input loop..."); while (xmlChunkInputStream.bufferNextChunk()) { // parse and process xml input xr.parse(inputSource); // check if we should abort synchronized (abortFlag) { if (abortFlag == true) { break; } } } } catch (Exception e) { Log.d(TAG, "(" + this.getId() + ") Exception " + e.toString() + ": " + e.getMessage()); // check if this thread was aborted and/or stopped by a call to interrupt() if (Thread.interrupted() || abortFlag) { Log.d(TAG, "(" + this.getId() + ") interrupted/aborted"); } else { GlobalData.sourcesMoverMsgHandler.sendMessage(GlobalData.sourcesMoverMsgHandler .obtainMessage(SourcesMover.XMLINPUT_ERR_MSG, e.getMessage())); Log.d(TAG, "(" + this.getId() + ") sending XMLINPUT_ERR_MSG"); } } Log.d(TAG, "(" + this.getId() + ") GOOD BYE"); }
From source file:sundroid.code.SundroidActivity.java
/** Called when the activity is first created. ***/ @Override/*from w w w .j a v a2 s . c o m*/ public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); this.chk_usecelsius = (CheckBox) findViewById(R.id.chk_usecelsius); Button cmd_submit = (Button) findViewById(R.id.cmd_submit); cmd_submit.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { try { ///////////////// Code to get weather conditions for entered place /////////////////////////////////////////////////// String cityParamString = ((EditText) findViewById(R.id.edit_input)).getText().toString(); String queryString = "https://www.google.com/ig/api?weather=" + cityParamString; queryString = queryString.replace("#", ""); /* Parsing the xml file*/ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); GoogleWeatherHandler gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(queryString.replace(" ", "%20")); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); Log.d("Sundroid", "parse complete"); WeatherSet ws = gwh.getWeatherSet(); newupdateWeatherInfoView(R.id.weather_today, ws.getWeatherCurrentCondition(), " " + cityParamString, ""); ///////////////// Code to get weather conditions for entered place ends /////////////////////////////////////////////////// ///////////////// Code to get latitude and longitude using zipcode starts /////////////////////////////////////////////////// String latlng_querystring = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + cityParamString.replace(" ", "%20") + "&sensor=false"; URL url_latlng = new URL(latlng_querystring); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); xr = sp.getXMLReader(); xmlhandler_latlong xll = new xmlhandler_latlong(); xr.setContentHandler(xll); xr.parse(new InputSource(url_latlng.openStream())); Latitude_longitude ll = xll.getLatlng_resultset(); double selectedLat = ll.getLat_lng_pair().getLat(); double selectedLng = ll.getLat_lng_pair().getLon(); ///////////////// Code to get latitude and longitude using zipcode ends /////////////////////////////////////////////////// ///////////////// Code to get miles from text box & convert to meters for passing into the api link//////////////////////// EditText edt = (EditText) findViewById(R.id.edit_miles); float miles = Float.valueOf(edt.getText().toString()); float meters = (float) (miles * 1609.344); ///////////////// Code to get miles from text box & convert to meters for passing into the api link ends ///////////////// ///////////////// Code to pass lat,long and radius and get destinations from places api starts////////// ///////////////// URL queryString_1 = new URL("https://maps.googleapis.com/maps/api/place/search/xml?location=" + Double.toString(selectedLat) + "," + Double.toString(selectedLng) + "&radius=" + Float.toString(meters) + "&types=park|types=aquarium|types=point_of_interest|types=establishment|types=museum&sensor=false&key=AIzaSyDmP0SB1SDMkAJ1ebxowsOjpAyeyiwHKQU"); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); xr = sp.getXMLReader(); xmlhandler_places xhp = new xmlhandler_places(); xr.setContentHandler(xhp); xr.parse(new InputSource(queryString_1.openStream())); int arraysize = xhp.getVicinity_List().size(); String[] place = new String[25]; String[] place_name = new String[25]; Double[] lat_pt = new Double[25]; Double[] lng_pt = new Double[25]; int i; //Getting name and vicinity tags from the xml file// for (i = 0; i < arraysize; i++) { place[i] = xhp.getVicinity_List().get(i); place_name[i] = xhp.getPlacename_List().get(i); lat_pt[i] = xhp.getLatlist().get(i); lng_pt[i] = xhp.getLonglist().get(i); System.out.println("long -" + lng_pt[i]); place[i] = place[i].replace("#", ""); } ///////////////// Code to pass lat,long and radius and get destinations from places api ends////////// ///////////////// //////////////////////while loop for getting top 5 from the array//////////////////////////////////////////////// int count = 0; int while_ctr = 0; String str_weathercondition; str_weathercondition = ""; WeatherCurrentCondition reftemp; //Places to visit if none of places in the given radius are sunny/clear/partly cloudy String[] rainy_place = { "Indoor Mall", "Watch a Movie", "Go to a Restaurant", "Shopping!" }; double theDistance = 0; String str_dist = ""; while (count < 5) { //Checking if xml vicinity value is empty while (place[while_ctr] == null || place[while_ctr].length() < 2) { while_ctr = while_ctr + 1; } //First search for places that are sunny or clear if (while_ctr < i - 1) { queryString = "https://www.google.com/ig/api?weather=" + place[while_ctr]; System.out.println("In while loop - " + queryString); theDistance = (Math.sin(Math.toRadians(selectedLat)) * Math.sin(Math.toRadians(lat_pt[while_ctr])) + Math.cos(Math.toRadians(selectedLat)) * Math.cos(Math.toRadians(lat_pt[while_ctr])) * Math.cos(Math.toRadians(selectedLng - lng_pt[while_ctr]))); str_dist = new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09).intValue() + " miles"; System.out.println(str_dist); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); xr = sp.getXMLReader(); gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); httpclient = new DefaultHttpClient(); httpget = new HttpGet(queryString.replace(" ", "%20")); responseHandler = new BasicResponseHandler(); responseBody = httpclient.execute(httpget, responseHandler); is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); if (gwh.isIn_error_information()) { System.out.println("Error Info flag set"); } else { ws = gwh.getWeatherSet(); reftemp = ws.getWeatherCurrentCondition(); str_weathercondition = reftemp.getCondition(); // Check if the condition is sunny or partly cloudy if (str_weathercondition.equals("Sunny") || str_weathercondition.equals("Mostly Sunny") || str_weathercondition.equals("Clear")) { System.out.println("Sunny Loop"); // Increment the count ++count; // Disply the place on the widget if (count == 1) { newupdateWeatherInfoView(R.id.weather_1, reftemp, place_name[while_ctr], str_dist); } else if (count == 2) { newupdateWeatherInfoView(R.id.weather_2, reftemp, place_name[while_ctr], str_dist); } else if (count == 3) { newupdateWeatherInfoView(R.id.weather_3, reftemp, place_name[while_ctr], str_dist); } else if (count == 4) { newupdateWeatherInfoView(R.id.weather_4, reftemp, place_name[while_ctr], str_dist); } else if (count == 5) { newupdateWeatherInfoView(R.id.weather_5, reftemp, place_name[while_ctr], str_dist); } else { } } } } // If Five sunny places not found then search for partly cloudy places else if (while_ctr >= i && while_ctr < i * 2) { queryString = "https://www.google.com/ig/api?weather=" + place[while_ctr - i]; queryString = queryString.replace(" ", " "); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); // Get the XMLReader of the SAXParser we created. xr = sp.getXMLReader(); gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); // Use HTTPClient to deal with the URL httpclient = new DefaultHttpClient(); httpget = new HttpGet(queryString.replace(" ", "%20")); responseHandler = new BasicResponseHandler(); responseBody = httpclient.execute(httpget, responseHandler); is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); Log.d(DEBUG_TAG, "parse complete"); if (gwh.isIn_error_information()) { } else { ws = gwh.getWeatherSet(); reftemp = ws.getWeatherCurrentCondition(); str_weathercondition = reftemp.getCondition(); // Check if the condition is sunny or partly cloudy if (str_weathercondition.equals("Partly Cloudy")) { count = count + 1; // Display the place if (count == 1) { newupdateWeatherInfoView(R.id.weather_1, reftemp, place_name[while_ctr - i], str_dist); } else if (count == 2) { newupdateWeatherInfoView(R.id.weather_2, reftemp, place_name[while_ctr - i], str_dist); } else if (count == 3) { newupdateWeatherInfoView(R.id.weather_3, reftemp, place_name[while_ctr - i], str_dist); } else if (count == 4) { newupdateWeatherInfoView(R.id.weather_4, reftemp, place_name[while_ctr - i], str_dist); } else if (count == 5) { newupdateWeatherInfoView(R.id.weather_5, reftemp, place_name[while_ctr - i], str_dist); } else { } } } } //////////////////////////////// Give suggestions for a rainy day else { queryString = "https://www.google.com/ig/api?weather=" + cityParamString; queryString = queryString.replace("#", ""); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); // Get the XMLReader of the SAXParser we created. xr = sp.getXMLReader(); gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); httpclient = new DefaultHttpClient(); httpget = new HttpGet(queryString.replace(" ", "%20")); // create a response handler responseHandler = new BasicResponseHandler(); responseBody = httpclient.execute(httpget, responseHandler); is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); if (gwh.isIn_error_information()) { } else { ws = gwh.getWeatherSet(); reftemp = ws.getWeatherCurrentCondition(); str_weathercondition = reftemp.getCondition(); if (count == 0) { newupdateWeatherInfoView(R.id.weather_1, reftemp, rainy_place[0], ""); newupdateWeatherInfoView(R.id.weather_2, reftemp, rainy_place[1], ""); newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], ""); newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[3], ""); newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], ""); } else if (count == 1) { newupdateWeatherInfoView(R.id.weather_2, reftemp, rainy_place[1], ""); newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], ""); newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[3], ""); newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[0], ""); } else if (count == 2) { newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], ""); newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[0], ""); newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], ""); } else if (count == 3) { newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[0], ""); newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], ""); } else if (count == 4) { newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], ""); } else { } count = 5; } count = 5; } while_ctr++; } /////////////Closing the soft keypad//////////////// InputMethodManager iMethodMgr = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); iMethodMgr.hideSoftInputFromWindow(edt.getWindowToken(), 0); } catch (Exception e) { resetWeatherInfoViews(); Log.e(DEBUG_TAG, "WeatherQueryError", e); } } }); }
From source file:com.penbase.dma.Dalyo.HTTPConnection.DmaHttpClient.java
/** * Gets the resources of an application/*from w ww .j a v a2s . 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(); } } }