List of usage examples for org.xml.sax XMLReader parse
public void parse(String systemId) throws IOException, SAXException;
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 ww .ja v a2s . co 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;/* w ww . jav a 2s. 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; } }
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 a 2s . 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.daphne.es.showcase.excel.service.ExcelDataService.java
@Async public void importExcel2007(final User user, final InputStream is) { ExcelDataService proxy = ((ExcelDataService) AopContext.currentProxy()); BufferedInputStream bis = null; try {/*w ww.j ava 2 s. c o m*/ long beginTime = System.currentTimeMillis(); List<ExcelData> dataList = Lists.newArrayList(); bis = new BufferedInputStream(is); OPCPackage pkg = OPCPackage.open(bis); XSSFReader r = new XSSFReader(pkg); XMLReader parser = XMLReaderFactory.createXMLReader(); ContentHandler handler = new Excel2007ImportSheetHandler(proxy, dataList, batchSize); parser.setContentHandler(handler); Iterator<InputStream> sheets = r.getSheetsData(); while (sheets.hasNext()) { InputStream sheet = null; try { sheet = sheets.next(); InputSource sheetSource = new InputSource(sheet); parser.parse(sheetSource); } catch (Exception e) { throw e; } finally { IOUtils.closeQuietly(sheet); } } //??batchSize? if (dataList.size() > 0) { proxy.doBatchSave(dataList); } long endTime = System.currentTimeMillis(); Map<String, Object> context = Maps.newHashMap(); context.put("seconds", (endTime - beginTime) / 1000); notificationApi.notify(user.getId(), "excelImportSuccess", context); } catch (Exception e) { log.error("excel import error", e); Map<String, Object> context = Maps.newHashMap(); context.put("error", e.getMessage()); notificationApi.notify(user.getId(), "excelImportError", context); } finally { IOUtils.closeQuietly(bis); } }
From source file:edu.wisc.my.portlets.dmp.tools.XmlMenuPublisher.java
/** * Publishes all the menus in the XML specified by the URL. * // w w w .j a va 2s . c o m * @param xmlSourceUrl URL to the menu XML. */ public void publishMenus(URL xmlSourceUrl) { LOG.info("Publishing menus from: " + xmlSourceUrl); try { //The XMLReader will read in the XML document final XMLReader reader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); try { reader.setFeature("http://apache.org/xml/features/validation/dynamic", true); reader.setFeature("http://apache.org/xml/features/validation/schema", true); final URL menuSchema = this.getClass().getResource("/menu.xsd"); if (menuSchema == null) { throw new MissingResourceException("Could not load menu schema. '/menu.xsd'", this.getClass().getName(), "/menu.xsd"); } reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", menuSchema.toString()); } catch (SAXNotRecognizedException snre) { LOG.warn("Could not enable XSD validation", snre); } catch (SAXNotSupportedException xnse) { LOG.warn("Could not enable XSD validation", xnse); } final MenuItemGeneratingHandler handler = new MenuItemGeneratingHandler(); reader.setContentHandler(handler); reader.parse(new InputSource(xmlSourceUrl.openStream())); final Map menus = handler.getMenus(); final BeanFactory factory = this.getFactory(); final MenuDao dao = (MenuDao) factory.getBean("menuDao", MenuDao.class); for (final Iterator nameItr = menus.entrySet().iterator(); nameItr.hasNext();) { final Map.Entry entry = (Map.Entry) nameItr.next(); final String menuName = (String) entry.getKey(); final MenuItem rootItem = (MenuItem) entry.getValue(); LOG.info("Publishing menu='" + menuName + "' item='" + rootItem + "'"); dao.storeMenu(menuName, rootItem); } LOG.info("Published menus from: " + xmlSourceUrl); } catch (IOException ioe) { LOG.error("Error publishing menus", ioe); } catch (SAXException saxe) { LOG.error("Error publishing menus", saxe); } }
From source file:org.apache.cxf.cwiki.SiteExporter.java
private String updateContentLinks(AbstractPage page, String content, String id, String divCls) throws Exception { XMLReader parser = createTagSoupParser(); StringWriter w = new StringWriter(); parser.setContentHandler(createContentHandler(page, w, id, divCls)); parser.parse(new InputSource(new StringReader(content))); content = w.toString();/*from w ww . java2 s. com*/ if (content.indexOf("html>") != -1) { content = content.substring("<html><body>".length()); content = content.substring(0, content.lastIndexOf("</body></html>")); } int idx = content.indexOf('>'); if (idx != -1 && content.substring(idx + 1).startsWith("<p></p>")) { //new confluence tends to stick an empty paragraph at the beginning for some pages (like Banner) //that causes major formatting issues. Strip it. content = content.substring(0, idx + 1) + content.substring(idx + 8); } return content; }
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;//ww w . j a v a 2 s . com 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:com.mirth.connect.model.converters.NCPDPSerializer.java
@Override public String fromXML(String source) throws SerializerException { /*/* ww w . jav a 2s .co m*/ * Need to determine the version by looking at the raw message. * The transaction header will contain the version ("51" for 5.1 and * "D0" for D.0) */ String version = "D0"; if (source.indexOf("D0") == -1) { version = "51"; } else if (source.indexOf("51") == -1) { version = "D0"; } else if (source.indexOf("51") < source.indexOf("D0")) { version = "51"; } try { XMLReader reader = XMLReaderFactory.createXMLReader(); NCPDPXMLHandler handler = new NCPDPXMLHandler(segmentDelimeter, groupDelimeter, fieldDelimeter, version); reader.setContentHandler(handler); if (useStrictValidation) { reader.setFeature("http://xml.org/sax/features/validation", true); reader.setFeature("http://apache.org/xml/features/validation/schema", true); reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "ncpdp" + version + ".xsd"); reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp" + version + ".xsd"); } /* * Parse, but first replace all spaces between brackets. This fixes * pretty-printed XML we might receive */ reader.parse(new InputSource(new StringReader(source.replaceAll(">\\s+<", "><")))); return handler.getOutput().toString(); } catch (Exception e) { throw new SerializerException("Error converting XML to NCPDP message.", e); } }
From source file:com.silverpeas.importExport.control.ImportExport.java
/** * Mthode retournant l'arbre des objets mapps sur le fichier xml pass en paramtre. * * @param xmlFileName le fichier xml interprt par Castor * @return Un objet SilverPeasExchangeType contenant le mapping d'un fichier XML Castor * @throws ImportExportException// w ww . j a v a2s . c om */ SilverPeasExchangeType loadSilverpeasExchange(String xmlFileName) throws ImportExportException { SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_ENTER_METHOD", "xmlFileName = " + xmlFileName); try { InputSource xmlInputSource = new InputSource(xmlFileName); String xsdPublicId = settings.getString("xsdPublicId"); String xsdSystemId = settings.getString("xsdDefaultSystemId"); // Load and parse default XML schema for import/export SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema", "com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory", null); Schema schema = schemaFactory.newSchema(new StreamSource(xsdSystemId)); // Create an XML parser for loading XML import file SAXParserFactory factory = SAXParserFactory .newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null); factory.setValidating(false); factory.setNamespaceAware(true); factory.setSchema(schema); SAXParser parser = factory.newSAXParser(); // First try to determine to load the XML file using the default // XML-Schema ImportExportErrorHandler errorHandler = new ImportExportErrorHandler(); XMLReader xmlReader = parser.getXMLReader(); xmlReader.setErrorHandler(errorHandler); try { xmlReader.parse(xmlInputSource); } catch (SAXException ex) { SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_PARAM_VALUE", (new StringBuilder("XML File ")).append(xmlFileName) .append(" is not valid according to default schema").toString()); // If case the default schema is not the one specified by the // XML import file, try to get the right XML-schema and // namespace (this is done by parsing without validation) ImportExportNamespaceHandler nsHandler = new ImportExportNamespaceHandler(); factory.setSchema(null); parser = factory.newSAXParser(); xmlReader = parser.getXMLReader(); xmlReader.setContentHandler(nsHandler); xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); xmlReader.parse(xmlInputSource); // If OK, extract the name and location of the schema String nsSpec = nsHandler.getNsSpec(); if (nsSpec == null || xsdPublicId.equals(nsSpec)) { throw ex; } String nsVersion = extractUriNameIndex(nsSpec); if (nsVersion.length() == 0) { throw ex; } String altXsdSystemId = settings.getStringWithParam("xsdSystemId", nsVersion); if ((altXsdSystemId == null) || (altXsdSystemId.equals(xsdSystemId))) { throw ex; } SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_PARAM_VALUE", (new StringBuilder("Trying again using schema specification located at ")) .append(altXsdSystemId).toString()); // Try again to load, parse and validate the XML import file, // using the new schema specification schema = schemaFactory.newSchema(new StreamSource(altXsdSystemId)); factory.setSchema(schema); parser = factory.newSAXParser(); xmlReader = parser.getXMLReader(); xmlReader.setErrorHandler(errorHandler); xmlReader.parse(xmlInputSource); } SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_PARAM_VALUE", "XML Validation complete"); // Mapping file for Castor String mappingDir = settings.getString("mappingDir"); String mappingFileName = settings.getString("importExportMapping"); String mappingFile = mappingDir + mappingFileName; Mapping mapping = new Mapping(); // Load mapping and instantiate a Unmarshaller mapping.loadMapping(mappingFile); Unmarshaller unmar = new Unmarshaller(SilverPeasExchangeType.class); unmar.setMapping(mapping); unmar.setValidation(false); // Unmarshall the process model SilverPeasExchangeType silverpeasExchange = (SilverPeasExchangeType) unmar.unmarshal(xmlInputSource); SilverTrace.debug("importExport", "ImportExportSessionController.loadSilverpeasExchange", "root.MSG_GEN_PARAM_VALUE", "Unmarshalling complete"); return silverpeasExchange; } catch (MappingException me) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_LOADING_XML_MAPPING_FAILED", "XML Filename " + xmlFileName + ": " + me.getLocalizedMessage(), me); } catch (MarshalException me) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_UNMARSHALLING_FAILED", "XML Filename " + xmlFileName + ": " + me.getLocalizedMessage(), me); } catch (ValidationException ve) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + ve.getLocalizedMessage(), ve); } catch (IOException ioe) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_LOADING_XML_MAPPING_FAILED", "XML Filename " + xmlFileName + ": " + ioe.getLocalizedMessage(), ioe); } catch (ParserConfigurationException ex) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + ex.getLocalizedMessage(), ex); } catch (SAXNotRecognizedException snre) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + snre.getLocalizedMessage(), snre); } catch (SAXNotSupportedException snse) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + snse.getLocalizedMessage(), snse); } catch (SAXException se) { throw new ImportExportException("ImportExport.loadSilverpeasExchange", "importExport.EX_PARSING_FAILED", "XML Filename " + xmlFileName + ": " + se.getLocalizedMessage(), se); } }
From source file:com.pontecultural.flashcards.ReadSpreadsheet.java
public void run() { try {//from w w w . j av a2s. c o m // This class is used to upload a zip file via // the web (ie,fileData). To test it, the file is // give to it directly via odsFile. One of // which must be defined. assertFalse(odsFile == null && fileData == null); XMLReader reader = null; final String ZIP_CONTENT = "content.xml"; // Open office files are zipped. // Walk through it and find "content.xml" ZipInputStream zin = null; try { if (fileData != null) { zin = new ZipInputStream(new BufferedInputStream(fileData.getInputStream())); } else { zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(odsFile))); } ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { if (entry.getName().equals(ZIP_CONTENT)) { break; } } SAXParserFactory spf = SAXParserFactory.newInstance(); //spf.setValidating(validate); SAXParser parser = spf.newSAXParser(); reader = parser.getXMLReader(); // reader.setErrorHandler(new MyErrorHandler()); reader.setContentHandler(this); // reader.parse(new InputSource(zf.getInputStream(entry))); reader.parse(new InputSource(zin)); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXParseException spe) { spe.printStackTrace(); } catch (SAXException se) { se.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (zin != null) zin.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } }