List of usage examples for javax.xml.parsers SAXParserFactory newInstance
public static SAXParserFactory newInstance()
From source file:ca.nines.ise.util.XMLDriver.java
/** * Construct a driver.//from w w w . ja v a 2 s. co m * * @throws ParserConfigurationException * @throws TransformerConfigurationException * @throws SAXException * @throws TransformerException */ public XMLDriver() throws ParserConfigurationException, TransformerConfigurationException, SAXException, TransformerException { docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); nullTransformer = TransformerFactory.newInstance().newTransformer(); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setNamespaceAware(true); SAXParser saxParser = saxParserFactory.newSAXParser(); xmlReader = saxParser.getXMLReader(); }
From source file:com.jkoolcloud.tnt4j.streams.configure.sax.StreamsConfigSAXParser.java
/** * Reads the configuration and invokes the (SAX-based) parser to parse the configuration file contents. * * @param config/*from w w w . j a v a 2s . co m*/ * input stream to get configuration data from * @param validate * flag indicating whether to validate configuration XML against XSD schema * @return streams configuration data * @throws ParserConfigurationException * if there is an inconsistency in the configuration * @throws SAXException * if there was an error parsing the configuration * @throws IOException * if there is an error reading the configuration data */ public static StreamsConfigData parse(InputStream config, boolean validate) throws ParserConfigurationException, SAXException, IOException { if (validate) { config = config.markSupported() ? config : new ByteArrayInputStream(IOUtils.toByteArray(config)); Map<OpLevel, List<SAXParseException>> validationErrors = validate(config); if (MapUtils.isNotEmpty(validationErrors)) { for (Map.Entry<OpLevel, List<SAXParseException>> vee : validationErrors.entrySet()) { for (SAXParseException ve : vee.getValue()) { LOGGER.log(OpLevel.WARNING, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "StreamsConfigSAXParser.xml.validation.error"), ve.getLineNumber(), ve.getColumnNumber(), vee.getKey(), ve.getLocalizedMessage()); } } } } Properties p = Utils.loadPropertiesResource("sax.properties"); // NON-NLS SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); ConfigParserHandler hndlr = null; try { String handlerClassName = p.getProperty(HANDLER_PROP_KEY, ConfigParserHandler.class.getName()); if (StringUtils.isNotEmpty(handlerClassName)) { hndlr = (ConfigParserHandler) Utils.createInstance(handlerClassName); } } catch (Exception exc) { } if (hndlr == null) { hndlr = new ConfigParserHandler(); } parser.parse(config, hndlr); return hndlr.getStreamsConfigData(); }
From source file:com.inferiorhumanorgans.WayToGo.Agency.BART.Route.RouteTask.java
@Override protected Void doInBackground(BARTAgency... someAgencies) { super.doInBackground(someAgencies); Log.i(LOG_NAME, "Trying to get BART route list."); InputStream content = null;//from w w w .j a v a2s .c o m ClientConnectionManager connman = new ThreadSafeClientConnManager(params, registry); DefaultHttpClient hc = new DefaultHttpClient(connman, params); Log.i(LOG_NAME, "Fetching from: " + BART_URL + BARTAgency.API_KEY); HttpGet getRequest = new HttpGet(BART_URL + BARTAgency.API_KEY); try { content = hc.execute(getRequest).getEntity().getContent(); } catch (ClientProtocolException ex) { Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex); } Log.i(LOG_NAME, "Put the station list in the background."); try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(dataHandler); xr.parse(new InputSource(content)); } catch (ParserConfigurationException pce) { Log.e(LOG_NAME + " SAX XML", "sax parse error", pce); } catch (AbortXMLParsingException abrt) { Log.i(LOG_NAME + " AsyncXML", "Cancelled!!!!!"); } catch (SAXException se) { Log.e(LOG_NAME + " SAX XML", "sax error", se); } catch (IOException ioe) { Log.e(LOG_NAME + " SAX XML", "sax parse io error", ioe); } Log.i(LOG_NAME + " SAX XML", "Done parsing BART station XML"); return null; }
From source file:my.mavenproject10.FileuploadController.java
@RequestMapping(method = RequestMethod.POST) ModelAndView upload(HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); String fileName = ""; int size = 0; ArrayList<String> result = new ArrayList<String>(); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {/*w w w . j a va 2 s .co m*/ List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); fileName = item.getName(); System.out.println("file name " + item.getName()); JAXBContext jc = JAXBContext.newInstance(CustomersType.class); SAXParserFactory spf = SAXParserFactory.newInstance(); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); InputSource inputSource = new InputSource( new InputStreamReader(item.getInputStream(), "UTF-8")); SAXSource source = new SAXSource(xmlReader, inputSource); Unmarshaller unmarshaller = jc.createUnmarshaller(); CustomersType data2 = (CustomersType) unmarshaller.unmarshal(source); //System.out.println("size " + data2.getCustomer().size()); size = data2.getCustomer().size(); for (CustomerType customer : data2.getCustomer()) { System.out.println(customer.toString()); } // double summ = 0.0; HashMap<Integer, Float> ordersMap = new HashMap<Integer, Float>(); for (CustomerType customer : data2.getCustomer()) { for (OrderType orderType : customer.getOrders().getOrder()) { Float summPerOrder = 0.0f; //System.out.println(orderType); for (PositionType positionType : orderType.getPositions().getPosition()) { //System.out.println(positionType); summPerOrder += positionType.getCount() * positionType.getPrice(); summ += positionType.getCount() * positionType.getPrice(); } ordersMap.put(orderType.getId(), summPerOrder); } } summ = new BigDecimal(summ).setScale(2, RoundingMode.UP).doubleValue(); System.out.println(" " + summ); result.add(" " + summ); // HashMap<Integer, Float> customersMap = new HashMap<Integer, Float>(); for (CustomerType customer : data2.getCustomer()) { Float summPerCust = 0.0f; customersMap.put(customer.getId(), summPerCust); for (OrderType orderType : customer.getOrders().getOrder()) { for (PositionType positionType : orderType.getPositions().getPosition()) { summPerCust += positionType.getCount() * positionType.getPrice(); } } //System.out.println(customer.getId() + " orders " + summPerCust); customersMap.put(customer.getId(), summPerCust); } TreeMap sortedMap = sortByValue(customersMap); System.out.println(" " + sortedMap.keySet().toArray()[0] + " : " + sortedMap.get(sortedMap.firstKey())); result.add(" " + sortedMap.keySet().toArray()[0] + " : " + sortedMap.get(sortedMap.firstKey())); // TreeMap sortedMapOrders = sortByValue(ordersMap); System.out.println(" " + sortedMapOrders.keySet().toArray()[0] + " : " + sortedMapOrders.get(sortedMapOrders.firstKey())); result.add(" " + sortedMapOrders.keySet().toArray()[0] + " : " + sortedMapOrders.get(sortedMapOrders.firstKey())); // System.out.println(" " + sortedMapOrders.keySet().toArray()[sortedMapOrders.keySet().toArray().length - 1] + " : " + sortedMapOrders.get(sortedMapOrders.lastKey())); result.add(" " + sortedMapOrders.keySet().toArray()[sortedMapOrders.keySet().toArray().length - 1] + " : " + sortedMapOrders.get(sortedMapOrders.lastKey())); // System.out.println(" " + sortedMapOrders.size()); result.add(" " + sortedMapOrders.size()); // ArrayList<Float> floats = new ArrayList<Float>(sortedMapOrders.values()); Float summAvg = 0.0f; Float avg = 0.0f; for (Float f : floats) { summAvg += f; } avg = new BigDecimal(summAvg / floats.size()).setScale(2, RoundingMode.UP).floatValue(); System.out.println(" " + avg); result.add(" " + avg); } } catch (FileUploadException e) { System.out.println("FileUploadException:- " + e.getMessage()); } catch (JAXBException ex) { //Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } } ModelAndView modelAndView = new ModelAndView("fileuploadsuccess"); modelAndView.addObject("files", result); modelAndView.addObject("name", fileName); modelAndView.addObject("size", size); return modelAndView; }
From source file:com.dhenton9000.excel.ExcelParser.java
public SheetResults parse(InputStream inputStream) throws Exception { OPCPackage pkg = OPCPackage.open(inputStream); XSSFReader reader = new XSSFReader(pkg); this.sst = reader.getSharedStringsTable(); SAXParserFactory saxFactory = SAXParserFactory.newInstance(); SAXParser saxParser = saxFactory.newSAXParser(); XMLReader parser = saxParser.getXMLReader(); parser.setContentHandler(this); // There should only be one sheet final Iterator<InputStream> it = reader.getSheetsData(); final InputStream sheet = it.next(); final InputSource sheetSource = new InputSource(sheet); parser.parse(sheetSource);/*w ww.ja v a2s . c o m*/ sheet.close(); return getSheetResults(); }
From source file:net.sf.firemox.xml.XmlParser.java
/** * Constructor.//from ww w .ja v a 2 s . c o m * * @param validation * validation flag. * @throws SAXException */ public XmlParser(boolean validation) throws SAXException { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(validation); parser = factory.newSAXParser(); if (validation) { parser.setProperty(JAXP_SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI); parser.setProperty(JAXP_SCHEMA_SOURCE, MToolKit.getFile(MP_XML_SCHEMA)); } } catch (Exception e) { throw new SAXException(e.toString()); } }
From source file:com.inferiorhumanorgans.WayToGo.Agency.NextBus.RouteConfig.RouteConfigXMLTask.java
@Override protected Void doInBackground(final NextBusAgency... someAgencies) { super.doInBackground(someAgencies); final String ourNBName = theAgency.getNextBusName(); Log.i(LOG_NAME, "Trying to get the route config for " + ourNBName + "."); Log.i(LOG_NAME, "Fetching from: " + NB_URL_BASE + ourNBName); InputStream ourInputStream = null; ClientConnectionManager ourConnectionManager = new ThreadSafeClientConnManager(params, registry); DefaultHttpClient ourHttpClient = new DefaultHttpClient(ourConnectionManager, params); final HttpGet getRequest = new HttpGet(NB_URL_BASE + Uri.encode(ourNBName)); try {//from w ww . j a v a 2 s . c o m ourInputStream = ourHttpClient.execute(getRequest).getEntity().getContent(); } catch (ClientProtocolException ex) { Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex); } Log.i(LOG_NAME, "Done with the route config for " + ourNBName + "."); try { SAXParserFactory ourParserFactory = SAXParserFactory.newInstance(); SAXParser ourParser = ourParserFactory.newSAXParser(); XMLReader xr = ourParser.getXMLReader(); RouteConfigXMLHandler ourDataHandler = new RouteConfigXMLHandler(this); xr.setContentHandler(ourDataHandler); xr.parse(new InputSource(ourInputStream)); } catch (ParserConfigurationException pce) { Log.e(LOG_NAME + "SAX XML", "sax parse error", pce); } catch (AbortXMLParsingException abrt) { Log.i(LOG_NAME + "AsyncXML", "Cancelled!!!!!"); } catch (SAXException se) { Log.e(LOG_NAME + "SAX XML", "sax error", se); } catch (IOException ioe) { Log.e(LOG_NAME + "SAX XML", "sax parse io error", ioe); } Log.i(LOG_NAME + "SAX XML", "Done parsing XML for " + ourNBName); return null; }
From source file:com.opensymphony.xwork.util.DomHelper.java
/** * Creates a W3C Document that remembers the location of each element in * the source file. The location of element nodes can then be retrieved * using the {@link #getLocationObject(Element)} method. * * @param inputSource the inputSource to read the document from * @param dtdMappings a map of DTD names and public ids *///w w w. j av a2 s . c o m public static Document parse(InputSource inputSource, Map dtdMappings) { SAXParserFactory factory = null; String parserProp = System.getProperty("xwork.saxParserFactory"); if (parserProp != null) { try { Class clazz = ObjectFactory.getObjectFactory().getClassInstance(parserProp); factory = (SAXParserFactory) clazz.newInstance(); } catch (ClassNotFoundException e) { LOG.error("Unable to load saxParserFactory set by system property 'xwork.saxParserFactory': " + parserProp, e); } catch (Exception e) { LOG.error("Unable to load saxParserFactory set by system property 'xwork.saxParserFactory': " + parserProp, e); } } if (factory == null) { factory = SAXParserFactory.newInstance(); } factory.setValidating((dtdMappings != null)); factory.setNamespaceAware(true); SAXParser parser = null; try { parser = factory.newSAXParser(); } catch (Exception ex) { throw new XworkException("Unable to create SAX parser", ex); } DOMBuilder builder = new DOMBuilder(); // Enhance the sax stream with location information ContentHandler locationHandler = new LocationAttributes.Pipe(builder); try { parser.parse(inputSource, new StartHandler(locationHandler, dtdMappings)); } catch (Exception ex) { throw new XworkException(ex); } return builder.getDocument(); }
From source file:com.inferiorhumanorgans.WayToGo.Agency.NextBus.RouteList.RouteListXMLTask.java
@Override protected Void doInBackground(final NextBusAgency... someAgencies) { Assert.assertEquals(1, someAgencies.length); super.doInBackground(someAgencies); String theNBName = theAgency.getNextBusName(); Log.i(LOG_NAME, "Trying to get the route list for " + theNBName + "."); InputStream content = null;//from w w w . j a va 2 s . c o m ClientConnectionManager connman = new ThreadSafeClientConnManager(params, registry); DefaultHttpClient hc = new DefaultHttpClient(connman, params); String theNBURL = "http://webservices.nextbus.com/service/publicXMLFeed?command=routeList&a="; theNBURL += Uri.encode(theNBName); Log.i(LOG_NAME, "Fetching from: " + theNBURL); HttpGet getRequest = new HttpGet(theNBURL); try { content = hc.execute(getRequest).getEntity().getContent(); } catch (ClientProtocolException ex) { Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex); this.cancel(true); return null; } try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(theDataHandler); xr.parse(new InputSource(content)); } catch (ParserConfigurationException pce) { Log.e(LOG_NAME + " SAX XML", "sax parse error", pce); } catch (AbortXMLParsingException abrt) { Log.i(LOG_NAME + " AsyncXML", "Cancelled!!!!!"); } catch (SAXException se) { Log.e(LOG_NAME + " SAX XML", "sax error", se); } catch (IOException ioe) { Log.e(LOG_NAME + " SAX XML", "sax parse io error", ioe); } //Log.i(LOG_NAME + " SAX XML", "Done parsing XML for " + theNBName); return null; }
From source file:Util.java
/** * Creates an XMLReader with default feature set. Note that all Cayenne internal XML * parsers should probably use XMLReader obtained via this method for consistency * sake, and can customize feature sets as needed. *//*from w w w .j a v a2 s . c o m*/ public static XMLReader createXmlReader() throws SAXException, ParserConfigurationException { SAXParserFactory spf = SAXParserFactory.newInstance(); // Create a JAXP SAXParser SAXParser saxParser = spf.newSAXParser(); // Get the encapsulated SAX XMLReader XMLReader reader = saxParser.getXMLReader(); // set default features reader.setFeature("http://xml.org/sax/features/namespaces", true); return reader; }