List of usage examples for javax.xml.parsers SAXParserFactory newSAXParser
public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;
From source file:com.cloudera.recordbreaker.analyzer.XMLSchemaDescriptor.java
void computeSchema() throws IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = null;//from www. java 2 s . c o m // Unfortunately, validation is often not possible factory.setValidating(false); try { // The XMLProcessor builds up a tree of tags XMLProcessor xp = new XMLProcessor(); parser = factory.newSAXParser(); parser.parse(dd.getRawBytes(), xp); // Grab the root tag this.rootTag = xp.getRoot(); // Once the tree is built, we: // a) Find the correct repetition node (and throws out 'bad' repeats) // b) Flatten hierarchies of subfields into a single layer, so it's suitable // for relational-style handling // c) Build an overall schema object that can summarize every expected // object, even if the objects' individual schemas differ somewhat this.rootTag.completeTree(); } catch (SAXException saxe) { throw new IOException(saxe.toString()); } catch (ParserConfigurationException pcee) { throw new IOException(pcee.toString()); } }
From source file:net.sbbi.upnp.messages.ActionMessage.java
/** * Executes the message and retuns the UPNP device response, according to the UPNP specs, * this method could take up to 30 secs to process ( time allowed for a device to respond to a request ) * @return a response object containing the UPNP parsed response * @throws IOException if some IOException occurs during message send and reception process * @throws UPNPResponseException if an UPNP error message is returned from the server * or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message ) *//*from w w w .jav a 2s . c o m*/ public ActionResponse service() throws IOException, UPNPResponseException { ActionResponse rtrVal = null; UPNPResponseException upnpEx = null; IOException ioEx = null; StringBuffer body = new StringBuffer(256); body.append("<?xml version=\"1.0\"?>\r\n"); body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\""); body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"); body.append("<s:Body>"); body.append("<u:").append(serviceAction.getName()).append(" xmlns:u=\"").append(service.getServiceType()) .append("\">"); if (serviceAction.getInputActionArguments() != null) { // this action requires params so we just set them... for (Iterator itr = inputParameters.iterator(); itr.hasNext();) { InputParamContainer container = (InputParamContainer) itr.next(); body.append("<").append(container.name).append(">").append(container.value); body.append("</").append(container.name).append(">"); } } body.append("</u:").append(serviceAction.getName()).append(">"); body.append("</s:Body>"); body.append("</s:Envelope>"); if (log.isDebugEnabled()) log.debug("POST prepared for URL " + service.getControlURL()); URL url = new URL(service.getControlURL().toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); HttpURLConnection.setFollowRedirects(false); //conn.setConnectTimeout( 30000 ); conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort()); conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\""); conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length())); conn.setRequestProperty("SOAPACTION", "\"" + service.getServiceType() + "#" + serviceAction.getName() + "\""); OutputStream out = conn.getOutputStream(); out.write(body.toString().getBytes()); out.flush(); out.close(); conn.connect(); InputStream input = null; if (log.isDebugEnabled()) log.debug("executing query :\n" + body); try { input = conn.getInputStream(); } catch (IOException ex) { // java can throw an exception if he error code is 500 or 404 or something else than 200 // but the device sends 500 error message with content that is required // this content is accessible with the getErrorStream input = conn.getErrorStream(); } if (input != null) { int response = conn.getResponseCode(); String responseBody = getResponseBody(input); if (log.isDebugEnabled()) log.debug("received response :\n" + responseBody); SAXParserFactory saxParFact = SAXParserFactory.newInstance(); saxParFact.setValidating(false); saxParFact.setNamespaceAware(true); ActionMessageResponseParser msgParser = new ActionMessageResponseParser(serviceAction); StringReader stringReader = new StringReader(responseBody); InputSource src = new InputSource(stringReader); try { SAXParser parser = saxParFact.newSAXParser(); parser.parse(src, msgParser); } catch (ParserConfigurationException confEx) { // should never happen // we throw a runtimeException to notify the env problem throw new RuntimeException( "ParserConfigurationException during SAX parser creation, please check your env settings:" + confEx.getMessage()); } catch (SAXException saxEx) { // kind of tricky but better than nothing.. upnpEx = new UPNPResponseException(899, saxEx.getMessage()); } finally { try { input.close(); } catch (IOException ex) { // ignore } } if (upnpEx == null) { if (response == HttpURLConnection.HTTP_OK) { rtrVal = msgParser.getActionResponse(); } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) { upnpEx = msgParser.getUPNPResponseException(); } else { ioEx = new IOException("Unexpected server HTTP response:" + response); } } } try { out.close(); } catch (IOException ex) { // ignore } conn.disconnect(); if (upnpEx != null) { throw upnpEx; } if (rtrVal == null && ioEx == null) { ioEx = new IOException("Unable to receive a response from the UPNP device"); } if (ioEx != null) { throw ioEx; } return rtrVal; }
From source file:de.uzk.hki.da.convert.PublishXSLTConversionStrategy.java
/** * Creates the xml source./*from w ww .j a v a 2 s . c o m*/ * * @param file the file * @return the source */ private Source createXMLSource(File file) { // disable validation in order to prevent url resolution of DTDs etc. SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(false); try { spf.setFeature("http://xml.org/sax/features/validation", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); spf.setFeature("http://xml.org/sax/features/external-general-entities", false); spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); } catch (Exception e) { logger.warn(e.getMessage()); } XMLReader reader; try { reader = spf.newSAXParser().getXMLReader(); } catch (Exception e) { throw new IllegalStateException("Unable to create SAXParser", e); } return new SAXSource(reader, new InputSource(file.getAbsolutePath())); }
From source file:com.larvalabs.svgandroid.SVGParser.java
private static SVG parse(InputStream in, Integer searchColor, Integer replaceColor, boolean whiteMode) throws SVGParseException { // Util.debug("Parsing SVG..."); SVGHandler svgHandler = null;/*from ww w. j a va 2 s .c o m*/ try { // long start = System.currentTimeMillis(); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); final Picture picture = new Picture(); svgHandler = new SVGHandler(picture); svgHandler.setColorSwap(searchColor, replaceColor); svgHandler.setWhiteMode(whiteMode); CopyInputStream cin = new CopyInputStream(in); IDHandler idHandler = new IDHandler(); xr.setContentHandler(idHandler); xr.parse(new InputSource(cin.getCopy())); svgHandler.idXml = idHandler.idXml; xr.setContentHandler(svgHandler); xr.parse(new InputSource(cin.getCopy())); // Util.debug("Parsing complete in " + (System.currentTimeMillis() - start) + " millis."); SVG result = new SVG(picture, svgHandler.bounds); // Skip bounds if it was an empty pic if (!Float.isInfinite(svgHandler.limits.top)) { result.setLimits(svgHandler.limits); } return result; } catch (Exception e) { //for (String s : handler.parsed.toString().replace(">", ">\n").split("\n")) // Log.d(TAG, "Parsed: " + s); throw new SVGParseException(e); } }
From source file:de.uzk.hki.da.cli.Cli.java
/** * Copies the files listed in a SIP list to a single directory * /*ww w. j av a2 s. c o m*/ * @param fileListFile The SIP list file * @return The path to the directory containing the files */ private String copySipListContentToFolder(File sipListFile) { CliProgressManager progressManager = new CliProgressManager(); String tempFolderName = getTempFolderName(); XMLReader xmlReader = null; SAXParserFactory spf = SAXParserFactory.newInstance(); try { xmlReader = spf.newSAXParser().getXMLReader(); } catch (Exception e) { logger.error("Failed to create SAX parser", e); System.out.println("Fehler beim Einlesen der SIP-Liste: SAX-Parser konnte nicht erstellt werden."); return ""; } xmlReader.setErrorHandler(new ErrorHandler() { @Override public void error(SAXParseException e) throws SAXException { throw new SAXException("Beim Einlesen der SIP-Liste ist ein Fehler aufgetreten.", e); } @Override public void fatalError(SAXParseException e) throws SAXException { throw new SAXException("Beim Einlesen der SIP-Liste ist ein schwerer Fehler aufgetreten.", e); } @Override public void warning(SAXParseException e) throws SAXException { logger.warn("Warning while parsing siplist", e); System.out.println("\nWarnung:\n" + e.getMessage()); } }); InputStream inputStream; try { inputStream = new FileInputStream(sipListFile); Reader reader = new InputStreamReader(inputStream, "UTF-8"); Builder parser = new Builder(xmlReader); Document doc = parser.build(reader); reader.close(); Element root = doc.getRootElement(); Elements sipElements = root.getChildElements("sip"); long files = 0; for (int i = 0; i < sipElements.size(); i++) { Elements fileElements = sipElements.get(i).getChildElements("file"); if (fileElements != null) files += fileElements.size(); } progressManager.setTotalSize(files); for (int i = 0; i < sipElements.size(); i++) { Element sipElement = sipElements.get(i); String sipName = sipElement.getAttributeValue("name"); File tempDirectory = new File(tempFolderName + File.separator + sipName); if (tempDirectory.exists()) { FolderUtils.deleteQuietlySafe(new File(tempFolderName)); System.out.println("\nDie SIP-Liste enthlt mehrere SIPs mit dem Namen " + sipName + ". " + "Bitte vergeben Sie fr jedes SIP einen eigenen Namen."); return ""; } tempDirectory.mkdirs(); Elements fileElements = sipElement.getChildElements("file"); for (int j = 0; j < fileElements.size(); j++) { Element fileElement = fileElements.get(j); String filepath = fileElement.getValue(); File file = new File(filepath); if (!file.exists()) { logger.error("File " + file.getAbsolutePath() + " is referenced in siplist, " + "but does not exist"); System.out.println("\nDie in der SIP-Liste angegebene Datei " + file.getAbsolutePath() + " existiert nicht."); FolderUtils.deleteQuietlySafe(new File(tempFolderName)); return ""; } try { if (file.isDirectory()) FileUtils.copyDirectoryToDirectory(file, tempDirectory); else FileUtils.copyFileToDirectory(file, tempDirectory); progressManager.copyFilesFromListProgress(); } catch (IOException e) { logger.error("Failed to copy file " + file.getAbsolutePath() + " to folder " + tempDirectory.getAbsolutePath(), e); System.out.println("\nDie in der SIP-Liste angegebene Datei " + file.getAbsolutePath() + " konnte nicht kopiert werden."); FolderUtils.deleteQuietlySafe(new File(tempFolderName)); return ""; } } } } catch (Exception e) { logger.error("Failed to read siplist " + sipListFile.getAbsolutePath(), e); System.out.println("\nBeim Lesen der SIP-Liste ist ein Fehler aufgetreten. "); return ""; } return (new File(tempFolderName).getAbsolutePath()); }
From source file:com.flipzu.flipzu.FlipInterface.java
private List<BroadcastDataSet> sendRequest(String url, String data) throws IOException { DefaultHttpClient hc = new DefaultHttpClient(); ResponseHandler<String> res = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); }//from w w w .ja v a2 s . c o m HttpEntity entity = response.getEntity(); return entity == null ? null : EntityUtils.toString(entity, "UTF-8"); } }; HttpPost postMethod = new HttpPost(url); postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); if (data != null) { StringEntity tmp = null; try { tmp = new StringEntity(data, "UTF-8"); } catch (UnsupportedEncodingException e) { debug.logE(TAG, "sendRequest ERROR", e.getCause()); return null; } postMethod.setEntity(tmp); } String response = hc.execute(postMethod, res); SAXParserFactory spf = SAXParserFactory.newInstance(); try { SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); TimelineHandler myTimelineHandler = new TimelineHandler(); xr.setContentHandler(myTimelineHandler); InputSource inputSource = new InputSource(); inputSource.setEncoding("UTF-8"); inputSource.setCharacterStream(new StringReader(response)); xr.parse(inputSource); List<BroadcastDataSet> parsedDataSet = myTimelineHandler.getParsedData(); return parsedDataSet; } catch (ParserConfigurationException e) { return null; } catch (SAXException e) { return null; } }
From source file:com.xmobileapp.rockplayer.LastFmEventImporter.java
/********************************* * /*from w w w . ja v a2s .c om*/ * Get Artist Events * @throws SAXException * @throws ParserConfigurationException * *********************************/ public void getArtistEvents() throws SAXException, ParserConfigurationException { /* * Initialize Artist Cursor */ artistCursor = ((RockPlayer) context).contentResolver.query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, ((RockPlayer) context).ARTIST_COLS, // we should minimize the number of columns null, // all albums null, // parameters to the previous parameter - which is null also null // sort order, SQLite-like ); /* * Declare & Initialize some vars */ String artistName = null; String artistNameFiltered = null; String artistConcertFileName = null; SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); SAXParser saxParser = saxParserFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); XMLArtistEventHandler xmlHandler = new XMLArtistEventHandler(); xmlHandler.myLocation = this.myLocation; xmlReader.setContentHandler(xmlHandler); /* * Set Distance Limit */ xmlHandler.MAX_DISTANCE = this.concertRadius; /* * Loop through the artists */ artistCursor.moveToFirst(); for (int i = 0; i < artistCursor.getCount(); i++) { /* * Get artist name */ artistName = artistCursor.getString(artistCursor.getColumnIndex(MediaStore.Audio.Artists.ARTIST)); if (artistName.equals("<unknown>")) { artistCursor.moveToNext(); continue; } artistNameFiltered = filterString(artistName); artistConcertFileName = ((RockPlayer) context).FILEX_CONCERT_PATH + validateFileName(artistName); /* * UI feedback */ Bundle data = new Bundle(); data.putString("info", artistName); Message msg = new Message(); msg.setData(data); ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg); /* * If we dont have yet or info is too old, update the concert info of this artist */ if (hasConcertInfo(artistName) == false || concertInfoNeedsUpdate(artistName) == true) { Log.i("INET", "Getting concert info from LastFM"); if (hasConcertInfo(artistName) == false) Log.i("INET", "Because there is no concert info yet"); if (concertInfoNeedsUpdate(artistName) == true) Log.i("INET", "Because Info is too old"); File artistConcertFile = new File(artistConcertFileName); if (!artistConcertFile.exists()) { try { artistConcertFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } URL lastFmApiRequest; try { lastFmApiRequest = new URL( this.LAST_FM_API_URL + "&artist=" + URLEncoder.encode(artistNameFiltered)); BufferedInputStream bufferedURLStream = new BufferedInputStream(lastFmApiRequest.openStream()); BufferedOutputStream bufferedFileWriter = new BufferedOutputStream( new FileOutputStream(artistConcertFile)); byte[] buf = new byte[1024]; int len; while ((len = bufferedURLStream.read(buf)) >= 0) bufferedFileWriter.write(buf, 0, len); bufferedURLStream.close(); bufferedFileWriter.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /* * get event list from cached XML files */ File artistConcertFile = new File(artistConcertFileName); if (artistConcertFile.exists() && artistConcertFile.length() > 0) { try { BufferedReader xmlFileReader = new BufferedReader( new InputStreamReader(new FileInputStream(artistConcertFile))); xmlHandler.resetList(); xmlHandler.artist = artistName; xmlReader.parse(new InputSource(xmlFileReader)); insertListInListByDate(xmlHandler.artistEventList); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } artistCursor.moveToNext(); } /* * Debug */ ArtistEvent artistEventDebug = null; if (!artistEventList.isEmpty()) { artistEventList.getFirst(); ListIterator<ArtistEvent> listIterator = artistEventList.listIterator(0); for (artistEventDebug = listIterator.next(); listIterator .hasNext() == true; artistEventDebug = listIterator.next()) { if (artistEventDebug != null) Log.i("DBG", artistEventDebug.date + " " + artistEventDebug.city); // Log.i("DBG", artistEventDebug.date+" "+artistEventDebug.city+" "+artistEventDebug.artist); else Log.i("DBG", "NULL"); } } /* * Update Adapter */ eventLinkedListAdapter = new EventLinkedListAdapter(context, R.layout.eventlist_item, artistEventList); if (eventLinkedListAdapter == null) Log.i("NULL", "NULL"); ((RockPlayer) context).updateEventListHandler.sendEmptyMessage(0); /* * Give feedback to the user */ Bundle data = new Bundle(); Message msg = new Message(); data.putString("info", "Done!"); msg.setData(data); ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg); }
From source file:nl.armatiek.xslweb.configuration.WebApp.java
public XsltExecutable tryTemplatesCache(String transformationPath, ErrorListener errorListener) throws Exception { String key = FilenameUtils.normalize(transformationPath); XsltExecutable templates = templatesCache.get(key); if (templates == null) { logger.info("Compiling and caching stylesheet \"" + transformationPath + "\" ..."); try {/*from w w w. j a v a 2s. com*/ SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setXIncludeAware(true); spf.setValidating(false); SAXParser parser = spf.newSAXParser(); XMLReader reader = parser.getXMLReader(); Source source = new SAXSource(reader, new InputSource(transformationPath)); XsltCompiler comp = processor.newXsltCompiler(); comp.setErrorListener(errorListener); templates = comp.compile(source); } catch (Exception e) { logger.error("Could not compile stylesheet \"" + transformationPath + "\"", e); throw e; } if (!developmentMode) { templatesCache.put(key, templates); } } return templates; }
From source file:com.flipzu.flipzu.FlipInterface.java
public FlipUser getUser(String username, String token) throws IOException { String data = "username=" + username + "&access_token=" + token; String url = WSServer + "/api/get_user.xml"; debug.logV(TAG, "getUser for username " + username); DefaultHttpClient hc = new DefaultHttpClient(); ResponseHandler<String> res = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); }//from w w w .j av a 2 s . c o m HttpEntity entity = response.getEntity(); return entity == null ? null : EntityUtils.toString(entity, "UTF-8"); } }; HttpPost postMethod = new HttpPost(url); postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); if (data != null) { StringEntity tmp = null; try { tmp = new StringEntity(data, "UTF-8"); } catch (UnsupportedEncodingException e) { debug.logE(TAG, "getUser ERROR", e.getCause()); return null; } postMethod.setEntity(tmp); } String response = hc.execute(postMethod, res); SAXParserFactory spf = SAXParserFactory.newInstance(); try { SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); UserHandler myUserHandler = new UserHandler(); xr.setContentHandler(myUserHandler); InputSource inputSource = new InputSource(); inputSource.setEncoding("UTF-8"); inputSource.setCharacterStream(new StringReader(response)); xr.parse(inputSource); FlipUser parsedData = myUserHandler.getParsedData(); return parsedData; } catch (ParserConfigurationException e) { return null; } catch (SAXException e) { return null; } }
From source file:com.flipzu.flipzu.FlipInterface.java
private FlipUser setFollowUnfollow(String username, String token, boolean follow) throws IOException { String data = "username=" + username + "&access_token=" + token; String url;/*from ww w . j a va 2 s .c om*/ if (follow) { url = WSServer + "/api/set_follow.xml"; } else { url = WSServer + "/api/set_unfollow.xml"; } debug.logV(TAG, "setFollow for username " + username); DefaultHttpClient hc = new DefaultHttpClient(); ResponseHandler<String> res = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } HttpEntity entity = response.getEntity(); return entity == null ? null : EntityUtils.toString(entity, "UTF-8"); } }; HttpPost postMethod = new HttpPost(url); postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); if (data != null) { StringEntity tmp = null; try { tmp = new StringEntity(data, "UTF-8"); } catch (UnsupportedEncodingException e) { debug.logE(TAG, "getUser ERROR", e.getCause()); return null; } postMethod.setEntity(tmp); } String response = hc.execute(postMethod, res); SAXParserFactory spf = SAXParserFactory.newInstance(); try { SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); UserHandler myUserHandler = new UserHandler(); xr.setContentHandler(myUserHandler); InputSource inputSource = new InputSource(); inputSource.setEncoding("UTF-8"); inputSource.setCharacterStream(new StringReader(response)); xr.parse(inputSource); FlipUser parsedData = myUserHandler.getParsedData(); return parsedData; } catch (ParserConfigurationException e) { return null; } catch (SAXException e) { return null; } }