List of usage examples for javax.xml.parsers SAXParserFactory newSAXParser
public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;
From source file:org.atombeat.xquery.functions.util.RequestGetData.java
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { RequestModule myModule = (RequestModule) context.getModule(RequestModule.NAMESPACE_URI); // request object is read from global variable $request Variable var = myModule.resolveVariable(RequestModule.REQUEST_VAR); if (var == null || var.getValue() == null) throw new XPathException(this, "No request object found in the current XQuery context."); if (var.getValue().getItemType() != Type.JAVA_OBJECT) throw new XPathException(this, "Variable $request is not bound to an Java object."); JavaObjectValue value = (JavaObjectValue) var.getValue().itemAt(0); if (value.getObject() instanceof RequestWrapper) { RequestWrapper request = (RequestWrapper) value.getObject(); //if the content length is unknown, return if (request.getContentLength() == -1) { return Sequence.EMPTY_SEQUENCE; }/*from w w w . j a v a 2s. c om*/ //first, get the content of the request byte[] bufRequestData = null; try { InputStream is = request.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(request.getContentLength()); byte[] buf = new byte[256]; int l = 0; while ((l = is.read(buf)) > -1) { bos.write(buf, 0, l); } bufRequestData = bos.toByteArray(); } catch (IOException ioe) { throw new XPathException(this, "An IO exception ocurred: " + ioe.getMessage(), ioe); } //was there any POST content if (bufRequestData != null) { //determine if exists mime database considers this binary data String contentType = request.getContentType(); if (contentType != null) { //strip off any charset encoding info if (contentType.indexOf(";") > -1) contentType = contentType.substring(0, contentType.indexOf(";")); MimeType mimeType = MimeTable.getInstance().getContentType(contentType); //<atombeat> // this code will only encode the request data if the mimeType // is present in the mime table, and the mimeType is stated // as binary... // if(mimeType != null) // { // if(!mimeType.isXMLType()) // { // //binary data // return new Base64Binary(bufRequestData); // } // } // this code takes a more conservative position and assumes that // if the mime type is not present in the table, the request // data should be treated as binary, and should be encoded as // base 64... if (mimeType == null || !mimeType.isXMLType()) { return new Base64Binary(bufRequestData); } //</atombeat> } //try and parse as an XML documemnt, otherwise fallback to returning the data as a string context.pushDocumentContext(); try { //try and construct xml document from input stream, we use eXist's in-memory DOM implementation SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); //TODO : we should be able to cope with context.getBaseURI() InputSource src = new InputSource(new ByteArrayInputStream(bufRequestData)); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); MemTreeBuilder builder = context.getDocumentBuilder(); DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder, true); reader.setContentHandler(receiver); reader.parse(src); Document doc = receiver.getDocument(); return (NodeValue) doc.getDocumentElement(); } catch (ParserConfigurationException e) { //do nothing, we will default to trying to return a string below } catch (SAXException e) { //do nothing, we will default to trying to return a string below } catch (IOException e) { //do nothing, we will default to trying to return a string below } finally { context.popDocumentContext(); } //not a valid XML document, return a string representation of the document String encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } try { String s = new String(bufRequestData, encoding); return new StringValue(s); } catch (IOException e) { throw new XPathException(this, "An IO exception ocurred: " + e.getMessage(), e); } } else { //no post data return Sequence.EMPTY_SEQUENCE; } } else { throw new XPathException(this, "Variable $request is not bound to a Request object."); } }
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 v a2 s .c om*/ * 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.attoparser.benchmark.AttoParserVSStandardSAXBenchmark.java
private static String getSAXParserClassName() throws Exception { final SAXParserFactory parserFactory = SAXParserFactory.newInstance(); final SAXParser parser = parserFactory.newSAXParser(); return parser.getClass().getName(); }
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;// w w w .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); 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 ww w .j a v a 2s . com } 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 {/*from w w w . j a v a2s.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.browsermob.proxy.jetty.xml.XmlParser.java
/** * Construct/*from w ww . j a v a2 s.co m*/ */ public XmlParser() { try { SAXParserFactory factory = SAXParserFactory.newInstance(); boolean notValidating = Boolean.getBoolean("org.browsermob.proxy.jetty.xml.XmlParser.NotValidating"); factory.setValidating(!notValidating); _parser = factory.newSAXParser(); try { if (!notValidating) _parser.getXMLReader().setFeature("http://apache.org/xml/features/validation/schema", true); } catch (Exception e) { log.warn("Schema validation may not be supported"); log.debug("", e); notValidating = true; } _parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", !notValidating); _parser.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", !notValidating); _parser.getXMLReader().setFeature("http://xml.org/sax/features/namespace-prefixes", !notValidating); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); throw new Error(e.toString()); } }
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 w w w . jav a2 s . c o m * @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 w w w. ja va2 s . c o m 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; }
From source file:org.codehaus.enunciate.modules.xml.XMLDeploymentModule.java
/** * Pretty-prints the specified xml file. * * @param file The file to pretty-print. *///from www. j a va 2s. c o m protected void prettyPrint(File file) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); SAXParser parser = factory.newSAXParser(); File prettyFile = enunciate.createTempFile("enunciate", file.getName()); parser.parse(file, new PrettyPrinter(prettyFile)); if (file.delete()) { enunciate.copyFile(prettyFile, file); } else { warn("Unable to delete %s. Skipping pretty-print transformation....", file); } } catch (Exception e) { //fall through... skip pretty printing. warn("Unable to pretty-print %s (%s).", file, e.getMessage()); if (enunciate.isDebug()) { e.printStackTrace(System.err); } } }