List of usage examples for javax.xml.parsers SAXParserFactory newInstance
public static SAXParserFactory newInstance()
From source file:net.sf.jabref.importer.fetcher.OAI2Fetcher.java
/** * * * @param oai2Host//w ww.j a v a 2 s .com * the host to query without leading http:// and without trailing / * @param oai2Script * the relative location of the oai2 interface without leading * and trailing / * @param oai2Metadataprefix * the urlencoded metadataprefix * @param oai2Prefixidentifier * the urlencoded prefix identifier * @param waitTimeMs * Time to wait in milliseconds between query-requests. */ public OAI2Fetcher(String oai2Host, String oai2Script, String oai2Metadataprefix, String oai2Prefixidentifier, String oai2ArchiveName, long waitTimeMs) { this.oai2Host = oai2Host; this.oai2Script = oai2Script; this.oai2MetaDataPrefix = oai2Metadataprefix; this.oai2PrefixIdentifier = oai2Prefixidentifier; this.oai2ArchiveName = oai2ArchiveName; this.waitTime = waitTimeMs; try { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); saxParser = parserFactory.newSAXParser(); } catch (ParserConfigurationException | SAXException e) { LOGGER.error("Error creating SAXParser for OAI2Fetcher", e); } }
From source file:kmlvalidator.KmlValidatorServlet.java
/** * Handles POST requests for the servlet. *///from w w w . j a va2s .co m public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // Our response is always JSON. response.setContentType("application/json"); // Create the JSON response objects to be filled in later. JSONObject responseObj = new JSONObject(); JSONArray responseErrors = new JSONArray(); try { // Load XSD files here. Note that the Java runtime should be caching // these files. Object[] schemas = { new URL("http://schemas.opengis.net/kml/2.2.0/atom-author-link.xsd").openConnection() .getInputStream(), new URL("http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd").openConnection().getInputStream(), new URL("http://code.google.com/apis/kml/schema/kml22gx.xsd").openConnection() .getInputStream() }; // Create a SAX parser factory (not a DOM parser, we don't need the // overhead) and set it to validate and be namespace aware, for // we want to validate against multiple XSDs. SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // Create a SAX parser and prepare for XSD validation. SAXParser parser = parserFactory.newSAXParser(); parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); parser.setProperty(JAXP_SCHEMA_SOURCE, schemas); // Create a parser handler to trap errors during parse. KmlValidatorParserHandler parserHandler = new KmlValidatorParserHandler(); // Parse the KML and send all errors to our handler. parser.parse(request.getInputStream(), parserHandler); // Check our handler for validation results. if (parserHandler.getErrors().size() > 0) { // There were errors, enumerate through them and create JSON objects // for each one. for (KmlValidationError e : parserHandler.getErrors()) { JSONObject error = new JSONObject(); switch (e.getType()) { case KmlValidationError.VALIDATION_WARNING: error.put("type", "warning"); break; case KmlValidationError.VALIDATION_ERROR: error.put("type", "error"); break; case KmlValidationError.VALIDATION_FATAL_ERROR: error.put("type", "fatal_error"); break; default: error.put("type", "fatal_error"); } // fill in parse exception details SAXParseException innerException = e.getInnerException(); error.put("message", innerException.getMessage()); if (innerException.getLineNumber() >= 0) error.put("line", innerException.getLineNumber()); if (innerException.getColumnNumber() >= 0) error.put("column", innerException.getColumnNumber()); // add this error to the list responseErrors.add(error); } // The KML wasn't valid. responseObj.put("status", "invalid"); } else { // The KML is valid against the XSDs. responseObj.put("status", "valid"); } } catch (SAXException e) { // We should never get here due to regular parse errors. This error // must've been thrown by the schema factory. responseObj.put("status", "internal_error"); JSONObject error = new JSONObject(); error.put("type", "fatal_error"); error.put("message", "Internal error: " + e.getMessage()); responseErrors.add(error); } catch (ParserConfigurationException e) { // Internal error at this point. responseObj.put("status", "internal_error"); JSONObject error = new JSONObject(); error.put("type", "fatal_error"); error.put("message", "Internal parse error."); responseErrors.add(error); } // If there were errors, add them to the final response JSON object. if (responseErrors.size() > 0) { responseObj.put("errors", responseErrors); } // output the JSON object as the HTTP response and append a newline for // prettiness response.getWriter().print(responseObj); response.getWriter().println(); }
From source file:com.sshtools.daemon.configuration.ServerConfiguration.java
/** * * * @param in/*w ww . j a v a 2 s . com*/ * * @throws SAXException * @throws ParserConfigurationException * @throws IOException */ public void reload(InputStream in) throws SAXException, ParserConfigurationException, IOException { allowedSubsystems.clear(); serverHostKeys.clear(); allowedAuthentications.clear(); requiredAuthentications.clear(); commandPort = 12222; port = 22; listenAddress = "0.0.0.0"; maxConnections = 10; maxAuthentications = 5; terminalProvider = ""; authorizationFile = "authorization.xml"; userConfigDirectory = "%D/.ssh2"; authenticationBanner = ""; allowTcpForwarding = true; currentElement = null; SAXParserFactory saxFactory = SAXParserFactory.newInstance(); SAXParser saxParser = saxFactory.newSAXParser(); saxParser.parse(in, this); }
From source file:edu.psu.citeseerx.updates.external.metadata.DBLPMetadataUpdater.java
public void updateDBLP() { try {/*w ww. j a va 2s .c o m*/ // Get the SAX factory. SAXParserFactory factory = SAXParserFactory.newInstance(); // Neither we want validation nor namespaces. factory.setNamespaceAware(false); factory.setValidating(true); SAXParser parser = factory.newSAXParser(); parser.getXMLReader().setEntityResolver(new DBLPEntityResolver(DBLPDTDFile)); /*xmlReader.setFeature( "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);*/ parser.parse(DBLPDataFile, dblpHandler); } catch (ParserConfigurationException e) { logger.error("The underlaying parser doesn't support the " + "requested feature", e); } catch (SAXException e) { logger.error("Error", e); } catch (IOException e) { logger.error("A parsing error has occurred: " + DBLPDataFile, e); } }
From source file:org.openbmap.soapclient.CheckServerTask.java
@Override protected Object[] doInBackground(final String... params) { try {/* w w w. j a v a 2 s .co m*/ final Object[] result = new Object[2]; result[0] = ServerAnswer.UNKNOWN_ERROR; result[1] = "Uninitialized"; //check whether we have a connection to openbmap.org if (!isOnline()) { // if not, check whether connecting, if so wait Log.i(TAG, "No reply from server! Device might just been switched on, so wait a bit"); waitForConnect(); if (!isOnline()) { Log.i(TAG, "Waiting didn't help. Still no connection"); result[0] = ServerAnswer.NO_REPLY; result[1] = "No online connection!"; return result; } } final SAXParserFactory factory = SAXParserFactory.newInstance(); final DefaultHandler handler = new DefaultHandler() { private boolean versionElement = false; public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("ALLOWED")) { versionElement = true; } } public void endElement(final String uri, final String localName, final String qName) throws SAXException { // Log.d(TAG, "End Element :" + qName); } public void characters(final char[] ch, final int start, final int length) throws SAXException { if (versionElement) { serverVersion = new String(ch, start, length); versionElement = false; } } }; Log.i(TAG, "Verifying client version at" + Preferences.VERSION_CHECK_URL); // version file is opened as stream, thus preventing immediate timeout issues final URL url = new URL(Preferences.VERSION_CHECK_URL); final InputStream stream = url.openStream(); final SAXParser saxParser = factory.newSAXParser(); saxParser.parse(stream, handler); stream.close(); if (serverVersion.equals(params[0])) { Log.i(TAG, "Client version is up-to-date: " + params[0]); final boolean anonymousUpload = PreferenceManager.getDefaultSharedPreferences(mContext) .getBoolean(Preferences.KEY_ANONYMOUS_UPLOAD, false); if (!anonymousUpload && credentialsAccepted(params[1], params[2])) { result[0] = ServerAnswer.OK; result[1] = "Everything fine! You're using the most up-to-date version!"; } else if (!anonymousUpload && !credentialsAccepted(params[1], params[2])) { result[0] = ServerAnswer.BAD_PASSWORD; result[1] = "Server reports bad user or password!"; } else { result[0] = ServerAnswer.OK; result[1] = "Password validation skipped, anonymous upload!"; } return result; } else { Log.i(TAG, "Client version is outdated: server " + serverVersion + " client " + params[0]); result[0] = ServerAnswer.OUTDATED; result[1] = "New version available:" + serverVersion; return result; } } catch (final IOException e) { Log.e(TAG, "Error while checking version. Are you online?"); return new Object[] { ServerAnswer.NO_REPLY, "Couldn't contact server" }; } catch (final Exception e) { Log.e(TAG, "Error while checking version: " + e.toString(), e); return new Object[] { ServerAnswer.UNKNOWN_ERROR, "Error: " + e.toString() }; } }
From source file:net.sf.ehcache.config.Configurator.java
/** * Configures a bean from an XML file available as an URL. */// w ww . jav a 2 s. c o m public void configure(final Object bean, final URL url) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug("Configuring ehcache from URL: " + url); } final SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); final BeanHandler handler = new BeanHandler(bean); parser.parse(url.toExternalForm(), handler); }
From source file:sundroid.code.SundroidActivity.java
/** Called when the activity is first created. ***/ @Override// ww w . jav a 2 s .co 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:ch.cern.security.saml2.utils.xml.XMLUtils.java
/** * Creates a SamlVO instance with the minimum data for performing the SLO * /*from ww w. j av a 2s .c o m*/ * @param xmlLogoutRequest * @param isDebugEnabled * @return SamlVO instance * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ public static SamlVO parseXMLmessage(String xmlLogoutRequest, boolean isDebugEnabled) throws ParserConfigurationException, SAXException, IOException { // Parse the XML. SAX approach, we just need the ID attribute SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); // If we want to validate the doc we need to load the DTD // saxParserFactory.setValidating(true); // Get a SAXParser instance SAXParser saxParser = saxParserFactory.newSAXParser(); // Parse it XMLhandler xmLhandler = new XMLhandler(isDebugEnabled); saxParser.parse(new ByteArrayInputStream(xmlLogoutRequest.getBytes()), xmLhandler); // Return the SamlVO return xmLhandler.getSamlVO(); }
From source file:com.eventestimator.mvc.ContactCollectionController.java
@RequestMapping(value = "/json.j", method = RequestMethod.GET) protected ResponseEntity<Object> getContacts(Model model, HttpServletRequest request) throws Exception { HttpSession session = request.getSession(); String userName = (String) session.getAttribute("userName"); String accessToken = (String) session.getAttribute("accessToken"); String contactUrl = WS_URL_PREFIX + userName + "/contacts?access_token=" + accessToken; Feed contactSource = restTemplate.getForObject(contactUrl, Feed.class); List<Entry> contacts = contactSource.getEntries(); List<Contact> contactObjects = new ArrayList<Contact>(contacts.size()); for (Entry contact : contacts) { Link link = (Link) contact.getOtherLinks().get(0); String linkHref = link.getHref(); String contentXML = restTemplate.getForObject(WS_DOMAIN + linkHref + "?access_token=" + accessToken, String.class); // List<Content> contactContents = contactEntry.getBody().getContents(); // List<Content> contactContents = contactEntry.getContents(); //// ww w .j a v a2 s . c om // Content contactContent = contactContents.get(0); // String contentXML = contactContent.getValue(); final SAXParserFactory sax = SAXParserFactory.newInstance(); sax.setNamespaceAware(false); final XMLReader reader; try { reader = sax.newSAXParser().getXMLReader(); } catch (SAXException e) { throw new RuntimeException(e); } InputSource is = new InputSource(new StringReader(contentXML)); SAXSource source = new SAXSource(reader, is); JAXBContext context = JAXBContext.newInstance(ContactEntry.class); javax.xml.bind.Unmarshaller unmarshaller = context.createUnmarshaller(); JAXBElement<ContactEntry> contactEntry = (JAXBElement<ContactEntry>) unmarshaller.unmarshal(source, ContactEntry.class); Contact contactObject = contactEntry.getValue().getContent().getContact(); contactObjects.add(contactObject); } ResponseEntity<Object> response = new ResponseEntity<Object>(contactObjects, HttpStatus.OK); return response; }
From source file:iarnrodProducer.java
public static DefaultFeatureCollection parseXML(final SimpleFeatureBuilder builder) { // sft schema = "trainStatus:String,trainCode:String,publicMessage:String,direction:String,dtg:Date,*geom:Point:srid=4326" final DefaultFeatureCollection featureCollection = new DefaultFeatureCollection(); try {//from w w w . ja v a 2 s . c o m SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); DefaultHandler handler = new DefaultHandler() { StringBuilder textContent = new StringBuilder(); String tagName; double lat; double lon; String trainCode; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { tagName = qName; textContent.setLength(0); } public void endElement(String uri, String localName, String qName) throws SAXException { tagName = qName; String text = textContent.toString(); if (tagName == TRAIN_LAT) { lat = Double.parseDouble(text); } else if (tagName == TRAIN_LON) { lon = Double.parseDouble(text); } else if (tagName == TRAIN_STATUS) { builder.add(text); } else if (tagName == TRAIN_CODE) { trainCode = text; // use this as feature ID builder.add(text); } else if (tagName == PUBLIC_MESSAGE) { builder.add(text); } else if (tagName == DIRECTION) { builder.add(text); // add direction // this is the last field, so finish up builder.add(DateTime.now().toDate()); builder.add(WKTUtils$.MODULE$.read("POINT(" + (lon) + " " + (lat) + ")")); SimpleFeature feature = builder.buildFeature(trainCode); featureCollection.add(feature); } } public void characters(char ch[], int start, int length) throws SAXException { textContent.append(ch, start, length); } public void startDocument() throws SAXException { // System.out.println("document started"); } public void endDocument() throws SAXException { // System.out.println("document ended"); } }; //handler saxParser.parse(API_PATH, handler); return featureCollection; } catch (Exception e) { System.out.println("Parsing exception: " + e); System.out.println("exception"); return null; } }