List of usage examples for javax.xml.parsers SAXParser parse
public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException
From source file:org.apache.torque.generator.configuration.controller.ControlConfigurationXmlParser.java
/** * Reads the controller configuration out of a configurationProvider. * * @param configurationProvider the object for accessing the configuration, * not null.//from w w w .java 2s.c om * @param projectPaths the paths inside the configuration, not null. * @param configurationHandlers the available configuration handlers, * not null. * * @return the Controller configuration. * @throws ConfigurationException if an error in the configuration * is encountered. * @throws NullPointerException if an argument is null. */ public ControlConfiguration readControllerConfiguration(ConfigurationProvider configurationProvider, ProjectPaths projectPaths, ConfigurationHandlers configurationHandlers) throws ConfigurationException { InputStream controlConfigurationInputStream = configurationProvider.getControlConfigurationInputStream(); try { ControlConfiguration result = new ControlConfiguration(); try { SAXParser parser = saxFactory.newSAXParser(); InputSource is = new InputSource(controlConfigurationInputStream); parser.parse(is, new ControlConfigurationSaxHandler(result, configurationProvider, projectPaths, configurationHandlers)); } catch (SAXParseException e) { throw new ConfigurationException("Error parsing controller Configuration " + configurationProvider.getControlConfigurationLocation() + " at line " + e.getLineNumber() + " column " + e.getColumnNumber() + " : " + e.getMessage(), e); } catch (Exception e) { throw new ConfigurationException("Error parsing controller Configuration " + configurationProvider.getControlConfigurationLocation() + e.getMessage(), e); } return result; } finally { try { controlConfigurationInputStream.close(); } catch (IOException e) { log.warn("Could not close controlConfigurationInputStream", e); } } }
From source file:org.apache.torque.generator.configuration.outlet.OutletConfigurationXmlParser.java
/** * Reads a outlet configuration file and returns the outlets * and isolated mergepoint mappings which are configured in this file. * * @param outletConfigurationInputStream the stream containing the * outlet configuration.//from w ww .j av a2s .c o m * @param configurationProvider The access object for the configuration * files, not null. * @param projectPaths The paths of the surrounding project, not null. * @param configurationHandlers the handlers for reading the configuration, * not null. * * @return All the outlets and isolated mergepoint mappings * configured in the file. * @throws SAXException if an error occurs while parsing the configuration * file. * @throws IOException if the file cannot be read. * @throws ParserConfigurationException if a serious parser configuration * error occurs.. */ private OutletConfigFileContent readOutletConfig(InputStream outletConfigurationInputStream, ConfigurationProvider configurationProvider, ProjectPaths projectPaths, ConfigurationHandlers configurationHandlers) throws SAXException, IOException, ParserConfigurationException { SAXParser parser = saxFactory.newSAXParser(); OutletConfigurationSaxHandler saxHandler = new OutletConfigurationSaxHandler(configurationProvider, projectPaths, configurationHandlers); InputSource is = new InputSource(outletConfigurationInputStream); parser.parse(is, saxHandler); return new OutletConfigFileContent(saxHandler.getOutlets(), saxHandler.getMergepointMappings()); }
From source file:org.apereo.portal.tools.dbloader.HibernateDbLoader.java
protected ITableDataProvider loadTables(DbLoaderConfig configuration, Dialect dialect) throws ParserConfigurationException, SAXException, IOException { //Locate tables.xml final String tablesFileName = configuration.getTablesFile(); final Resource tablesFile = this.resourceLoader.getResource(tablesFileName); if (!tablesFile.exists()) { throw new IllegalArgumentException("Could not find tables file: " + tablesFile); }/* w w w .j av a2 s . c om*/ //Setup parser with custom handler to generate Table model and parse final SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); final TableXmlHandler dh = new TableXmlHandler(dialect); saxParser.parse(new InputSource(tablesFile.getInputStream()), dh); return dh; }
From source file:org.apereo.portal.tools.dbloader.HibernateDbLoader.java
protected void populateTables(DbLoaderConfig configuration, Map<String, Map<String, Integer>> tableColumnTypes) throws ParserConfigurationException, SAXException, IOException { //Locate tables.xml final String dataFileName = configuration.getDataFile(); final Resource dataFile = this.resourceLoader.getResource(dataFileName); if (!dataFile.exists()) { throw new IllegalArgumentException("Could not find data file: " + dataFile); }//from ww w . jav a2 s . c o m //Setup parser with custom handler to generate Table model and parse final SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); final DataXmlHandler dh = new DataXmlHandler(jdbcOperations, transactionOperations, tableColumnTypes); saxParser.parse(new InputSource(dataFile.getInputStream()), dh); }
From source file:org.attoparser.benchmark.AttoParserVSStandardSAXBenchmark.java
public static String standardSaxBenchmark(final String fileName, final int iterations) throws Exception { final SAXParserFactory parserFactory = SAXParserFactory.newInstance(); final SAXParser parser = parserFactory.newSAXParser(); /*/* w w w .j a va 2s.com*/ * WARMUP BEGIN */ System.out.println("Warming up phase for SAX STARTED"); for (int i = 0; i < 10000; i++) { InputStream is = null; Reader reader = null; try { is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); reader = new BufferedReader(new InputStreamReader(is, "ISO-8859-1")); final InputSource inputSource = new InputSource(reader); final BenchmarkStandardSaxContentHandler handler = new BenchmarkStandardSaxContentHandler(); parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler); parser.setProperty("http://xml.org/sax/properties/declaration-handler", handler); parser.parse(inputSource, handler); parser.reset(); handler.getEventCounter(); } finally { try { if (reader != null) reader.close(); } catch (final Exception ignored) { /* ignored */} try { if (is != null) is.close(); } catch (final Exception ignored) { /* ignored */} } } /* * WARMUP END */ System.out.println("Warming up phase for SAX FINISHED"); final StopWatch sw = new StopWatch(); boolean started = false; int eventCounter = 0; for (int i = 0; i < iterations; i++) { InputStream is = null; Reader reader = null; try { is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); reader = new BufferedReader(new InputStreamReader(is, "ISO-8859-1")); final InputSource inputSource = new InputSource(reader); final BenchmarkStandardSaxContentHandler handler = new BenchmarkStandardSaxContentHandler(); parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler); parser.setProperty("http://xml.org/sax/properties/declaration-handler", handler); if (started) { sw.resume(); } else { started = true; sw.start(); } parser.parse(inputSource, handler); parser.reset(); sw.suspend(); eventCounter = handler.getEventCounter(); } finally { try { if (reader != null) reader.close(); } catch (final Exception ignored) { /* ignored */} try { if (is != null) is.close(); } catch (final Exception ignored) { /* ignored */} } } sw.stop(); return "[" + eventCounter + "] " + sw.toString(); }
From source file:org.bigbluebutton.freeswitch.voice.freeswitch.actions.CheckIfConfIsRunningCommand.java
public void handleResponse(EslMessage response, ConferenceEventListener eventListener) { //Test for Known Conference String firstLine = response.getBodyLines().get(0); log.info("Check conference first line response: " + firstLine); //E.g. Conference 85115 not found if (!firstLine.startsWith("<?xml")) { log.info("INFO! Successfully ejected all users from conference {}.", room); return;/*from ww w . j a va2s .c o m*/ } XMLResponseConferenceListParser confXML = new XMLResponseConferenceListParser(); //get a factory SAXParserFactory spf = SAXParserFactory.newInstance(); try { //get a new instance of parser SAXParser sp = spf.newSAXParser(); //Hack turning body lines back into string then to ByteStream.... BLAH! String responseBody = StringUtils.join(response.getBodyLines(), "\n"); //http://mark.koli.ch/2009/02/resolving-orgxmlsaxsaxparseexception-content-is-not-allowed-in-prolog.html //This Sux! responseBody = responseBody.trim().replaceFirst("^([\\W]+)<", "<"); ByteArrayInputStream bs = new ByteArrayInputStream(responseBody.getBytes()); sp.parse(bs, confXML); Integer numUsers = confXML.getConferenceList().size(); if (numUsers > 0) { log.info("Check conference response: " + responseBody); log.warn("WARNING! Failed to eject all users from conf={},numUsers={}.", room, numUsers); for (ConferenceMember member : confXML.getConferenceList()) { if ("caller".equals(member.getMemberType())) { //Foreach found member in conference create a JoinedEvent String callerId = member.getCallerId(); String callerIdName = member.getCallerIdName(); String voiceUserId = callerIdName; String uuid = member.getUUID(); log.info("WARNING! User possibly stuck in conference. uuid=" + uuid + ",caller=" + callerIdName + ",callerId=" + callerId + ",conf=" + room); } else if ("recording_node".equals(member.getMemberType())) { } } } else { log.info("INFO! Successfully ejected all users from conference {}.", room); } } catch (SAXException se) { // System.out.println("Cannot parse repsonce. ", se); } catch (ParserConfigurationException pce) { // System.out.println("ParserConfigurationException. ", pce); } catch (IOException ie) { // System.out.println("Cannot parse repsonce. IO Exception. ", ie); } }
From source file:org.bigbluebutton.freeswitch.voice.freeswitch.actions.GetAllUsersCommand.java
public void handleResponse(EslMessage response, ConferenceEventListener eventListener) { //Test for Known Conference String firstLine = response.getBodyLines().get(0); //E.g. Conference 85115 not found if (!firstLine.startsWith("<?xml")) { // System.out.println("Not XML: [{}]", firstLine); return;/*from www .j a va 2 s .c o m*/ } XMLResponseConferenceListParser confXML = new XMLResponseConferenceListParser(); //get a factory SAXParserFactory spf = SAXParserFactory.newInstance(); try { //get a new instance of parser SAXParser sp = spf.newSAXParser(); //Hack turning body lines back into string then to ByteStream.... BLAH! String responseBody = StringUtils.join(response.getBodyLines(), "\n"); //http://mark.koli.ch/2009/02/resolving-orgxmlsaxsaxparseexception-content-is-not-allowed-in-prolog.html //This Sux! responseBody = responseBody.trim().replaceFirst("^([\\W]+)<", "<"); ByteArrayInputStream bs = new ByteArrayInputStream(responseBody.getBytes()); sp.parse(bs, confXML); //Maybe move this to XMLResponseConferenceListParser, sendConfrenceEvents ? VoiceUserJoinedEvent pj; for (ConferenceMember member : confXML.getConferenceList()) { //Foreach found member in conference create a JoinedEvent String callerId = member.getCallerId(); String callerIdName = member.getCallerIdName(); String voiceUserId = callerIdName; Matcher matcher = CALLERNAME_PATTERN.matcher(callerIdName); if (matcher.matches()) { voiceUserId = matcher.group(1).trim(); callerIdName = matcher.group(2).trim(); } pj = new VoiceUserJoinedEvent(voiceUserId, member.getId().toString(), confXML.getConferenceRoom(), callerId, callerIdName, member.getMuted(), member.getSpeaking(), null); eventListener.handleConferenceEvent(pj); } } catch (SAXException se) { // System.out.println("Cannot parse repsonce. ", se); } catch (ParserConfigurationException pce) { // System.out.println("ParserConfigurationException. ", pce); } catch (IOException ie) { // System.out.println("Cannot parse repsonce. IO Exception. ", ie); } }
From source file:org.biouno.drmaa_pbs.parser.NodeXmlParser.java
public List<Node> parse(String xml) throws ParseException { try {// ww w . j a v a 2 s . co m final SAXParserFactory factory = SAXParserFactory.newInstance(); final SAXParser saxParser = factory.newSAXParser(); final NodeXmlHandler handler = new NodeXmlHandler(); saxParser.parse(new CharSequenceInputStream(xml, Charset.defaultCharset()), handler); return handler.getNodes(); } catch (IOException ioe) { throw new ParseException(ioe); } catch (SAXException e) { throw new ParseException(e); } catch (ParserConfigurationException e) { throw new ParseException(e); } }
From source file:org.cerberus.crud.service.impl.ImportFileService.java
/** * Auxiliary method that parses an XML. Depending on the type, a different handler can be used, and different information is retrieved to the user * @param filecontent content to be parse * @param handlerType handler type that defines the type of information that should be retrieved * @return the content of the XML file that was parsed * @throws SAXException/*from www .j ava2s.c om*/ * @throws ParserConfigurationException * @throws IOException */ private Object parseXMLFile(InputStream xmlContent, XMLHandlerEnumType handlerType) throws SAXException, ParserConfigurationException, IOException { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); SAXParser saxParser = saxParserFactory.newSAXParser(); if (handlerType.ordinal() == XMLHandlerEnumType.TESTDATALIB_HANDLER.ordinal()) { XMLTestDataLibHandler handler = new XMLTestDataLibHandler(); saxParser.parse(xmlContent, handler); return handler.getDataFromFile(); // returns tha map that contains the data that we want to parse } return null; }
From source file:org.chiba.xml.xforms.connector.SchemaValidator.java
/** * validate the instance according to the schema specified on the model * * @return false if the instance is not valid *//*from www. jav a 2 s .c om*/ public boolean validateSchema(Model model, Node instance) throws XFormsException { boolean valid = true; String message; if (LOGGER.isDebugEnabled()) LOGGER.debug("SchemaValidator.validateSchema: validating instance"); //needed if we want to load schemas from Model + set it as "schemaLocation" attribute String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema"); if (schemas != null && !schemas.equals("")) { // valid=false; //add schemas to element //shouldn't it be done on a copy of the doc ? Element el = null; if (instance.getNodeType() == Node.ELEMENT_NODE) el = (Element) instance; else if (instance.getNodeType() == Node.DOCUMENT_NODE) el = ((Document) instance).getDocumentElement(); else { if (LOGGER.isDebugEnabled()) LOGGER.debug("instance node type is: " + instance.getNodeType()); } String prefix = NamespaceResolver.getPrefix(el, XMLSCHEMA_INSTANCE_NS); //test if with targetNamespace or not //if more than one schema : namespaces are mandatory ! (optional only for 1) StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false); String schemaLocations = null; String noNamespaceSchemaLocation = null; while (tokenizer.hasMoreElements()) { String token = (String) tokenizer.nextElement(); //check that it is an URL URI uri = null; try { uri = new java.net.URI(token); } catch (java.net.URISyntaxException ex) { if (LOGGER.isDebugEnabled()) LOGGER.debug(token + " is not an URI"); } if (uri != null) { String ns; try { ns = this.getSchemaNamespace(uri); if (ns != null && !ns.equals("")) { if (schemaLocations == null) schemaLocations = ns + " " + token; else schemaLocations = schemaLocations + " " + ns + " " + token; ///add the namespace declaration if it is not on the instance? //TODO: how to know with which prefix ? String nsPrefix = NamespaceResolver.getPrefix(el, ns); if (nsPrefix == null) { //namespace not declared ! LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token + " is not declared in instance: declaring it as default..."); el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns); } } else if (noNamespaceSchemaLocation == null) noNamespaceSchemaLocation = token; else { //we have more than one schema without namespace LOGGER.warn("SchemaValidator: There is more than one schema without namespace !"); } } catch (Exception ex) { LOGGER.warn( "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(), ex); //in case there was an exception: do nothing, do not set the schema } } } //write schemaLocations found if (schemaLocations != null && !schemaLocations.equals("")) el.setAttributeNS(XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation", schemaLocations); if (noNamespaceSchemaLocation != null) el.setAttributeNS(XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation", noNamespaceSchemaLocation); //save and parse the doc ValidationErrorHandler handler = null; File f; try { //save document f = File.createTempFile("instance", ".xml"); f.deleteOnExit(); TransformerFactory trFact = TransformerFactory.newInstance(); Transformer trans = trFact.newTransformer(); DOMSource source = new DOMSource(el); StreamResult result = new StreamResult(f); trans.transform(source, result); if (LOGGER.isDebugEnabled()) LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath()); //parse it with error handler to validate it handler = new ValidationErrorHandler(); SAXParserFactory parserFact = SAXParserFactory.newInstance(); parserFact.setValidating(true); parserFact.setNamespaceAware(true); SAXParser parser = parserFact.newSAXParser(); XMLReader reader = parser.getXMLReader(); //validation activated reader.setFeature("http://xml.org/sax/features/validation", true); //schema validation activated reader.setFeature("http://apache.org/xml/features/validation/schema", true); //used only to validate the schema, not the instance //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true); //validate only if there is a grammar reader.setFeature("http://apache.org/xml/features/validation/dynamic", true); parser.parse(f, handler); } catch (Exception ex) { LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex); //throw new XFormsException("XMLSchema validation failed. "+message); } //if no exception if (handler != null && handler.isValid()) valid = true; else { message = handler.getMessage(); //TODO: find a way to get the error message displayed throw new XFormsException("XMLSchema validation failed. " + message); } if (LOGGER.isDebugEnabled()) LOGGER.debug("Validator.validateSchema: result=" + valid); } return valid; }