List of usage examples for org.xml.sax SAXException toString
public String toString()
From source file:com.esri.gpt.server.csw.provider3.GetRecordsProvider.java
/** * Builds an ogc:Filter node from HTTP GET parameters. * @param namespace the namespace parameter values * @param constraintFilter the constraint parameter value * @throws Exception if a processing exception occurs *//*from w ww . j a v a 2 s . c om*/ protected Node buildFilterNode(String[] namespace, String constraintFilter) throws Exception { // TODO GetRecordsDomBuilder had a different pattern?? // parse namespaces // pattern: namespace=xmlns(ogc=http://www.opengis.net/ogc),xmlns(gml=http://www.opengis.net/gml)... StringBuilder nsBuffer = new StringBuilder(); boolean hasCswUri = false; boolean hasCswPfx = false; String cswPfx = ""; List<String[]> parseNamespace = parseNamespace(namespace); for (String[] ns : parseNamespace) { String nsUri = ns[0]; String nsPfx = ns[1]; if (nsUri.equals(CswNamespaces.CSW_30.URI_CSW())) { hasCswUri = true; if (!nsPfx.isEmpty()) { hasCswPfx = true; cswPfx = nsPfx; } } if (nsPfx.isEmpty()) { nsBuffer.append(" xmlns=\"").append(nsUri).append("\""); } else { nsBuffer.append(" xmlns:").append(nsPfx).append("=\"").append(nsUri).append("\""); } } // use ogc as the default namespace if no namespace parameter was supplied if (nsBuffer.length() == 0) { nsBuffer.append(" xmlns=\"http://www.opengis.net/ogc\""); } // build the constraint XML StringBuilder sbXml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); if (hasCswUri && hasCswPfx) { cswPfx = cswPfx + ":"; } else if (hasCswUri) { cswPfx = ""; } else { cswPfx = "csw:"; nsBuffer.append(" xmlns:csw=\"http://www.opengis.net/cat/csw/3.0\""); } sbXml.append("\r\n<").append(cswPfx).append("Constraint"); if (nsBuffer.length() > 0) { sbXml.append(" ").append(nsBuffer); } sbXml.append(">"); sbXml.append("\r\n").append(constraintFilter); sbXml.append("\r\n</").append(cswPfx).append("Constraint>"); // make the dom, find the ogc:Filter node try { Document dom = DomUtil.makeDomFromString(sbXml.toString(), true); CswNamespaces ns = CswNamespaces.CSW_30; XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(ns.makeNamespaceContext()); Node ndFilter = null; Node ndConstraint = (Node) xpath.evaluate("csw:Constraint", dom, XPathConstants.NODE); if (ndConstraint != null) { ndFilter = (Node) xpath.evaluate("ogc:Filter", ndConstraint, XPathConstants.NODE); ; } if (ndFilter == null) { String msg = "The supplied constraint was not a valid ogc:Filter."; throw new OwsException(OwsException.OWSCODE_NoApplicableCode, "constraint", msg); } else { return ndFilter; } } catch (SAXException e) { String msg = "The supplied namespace/constraint pairs were not well-formed xml: "; msg += " " + e.toString(); throw new OwsException(OwsException.OWSCODE_NoApplicableCode, "constraint", msg); } }
From source file:biz.taoconsulting.oxf.processor.converter.FromPdfConverter.java
private void extractFromPDF(InputStream inputStream, XMLReceiver xmlReceiver, String scope) { logger.info("Extract from PDF started"); // Write the header information of the PDF PDDocument doc = null;//from w ww . j a v a2 s . c o m try { xmlReceiver.startDocument(); logger.info("Start document completed"); // Some variables for our PDF processing doc = getPDFdocument(inputStream, xmlReceiver); // PDF // Document if (doc == null) { xmlReceiver.startElement("", TAG_ROOT, TAG_ROOT, null); addErrorTagToOutput(xmlReceiver, "No PDF Information could be extracted"); xmlReceiver.endElement("", TAG_ROOT, TAG_ROOT); return; //No processing on empty documents } } catch (SAXException e) { logger.error(e); } // Get a handle on all pages in the PDF. Needed for page lookup try { logger.info("Try to get handle on all pages array"); this.allPages = doc.getDocumentCatalog().getAllPages(); logger.info("Got handle to allPages in PDF"); } catch (Exception e) { logger.error(e); addErrorTagToOutput(xmlReceiver, e.toString()); this.allPages = null; } try { // Get the document information logger.info("Ready to retrieve basic PDF information"); PDDocumentInformation docInfo = getDocumentInformation(doc, xmlReceiver); AttributesImpl atts = new AttributesImpl(); // Capture the number of pages addPageCountAttribute(atts, doc); // Now add some document Info addDocInfoAttributes(atts, docInfo); // Start the PDF Document logger.info("writing the root element PDFDocument"); xmlReceiver.startElement("", TAG_ROOT, TAG_ROOT, atts); logger.info("PDFDocument tag succesful opened"); //Pull the Meta data from the PDF Document atts = new AttributesImpl(); logger.info("PDFMetadata Element start"); xmlReceiver.startElement("", TAG_META, TAG_META, atts); extractMetaDataFromPDF(xmlReceiver, doc); xmlReceiver.endElement("", TAG_META, TAG_META); logger.info("PDFMetadata Element end"); // Get the PDF Content based on the selection in config if (scope.equals(SCOPE_PAGES)) { //PDF page by page logger.info("Will extract pages"); extractPagesFromPDF(xmlReceiver, doc); } else if (scope.equals(SCOPE_METADATA)) { logger.info("No action bejond meta data"); // No further action required since it was meta data only! } else if (scope.equals(SCOPE_BOOKMARKPAGES)) { // Try bookmarks then pages logger.info("Will extract bookmarks first then pages"); if (!extractOutlineFromPDF(xmlReceiver, doc, scope)) { logger.info("No outline found, using pages"); extractPagesFromPDF(xmlReceiver, doc); } } else { // PDF in outlines - default logger.info("Will extract: " + scope); extractOutlineFromPDF(xmlReceiver, doc, scope); } //If we got here it worked logger.info("Writing end element " + TAG_ROOT); xmlReceiver.endElement("", TAG_ROOT, TAG_ROOT); logger.info("About to close PDFDocument and SaxDocument"); xmlReceiver.endDocument(); doc.close(); // We finish it once we are done logger.info("Closed PDF and XML"); } catch (IOException e) { logger.error(e); addErrorTagToOutput(xmlReceiver, e.toString()); } catch (SAXException e) { logger.error(e); addErrorTagToOutput(xmlReceiver, e.toString()); } }
From source file:org.apache.cocoon.forms.util.DomHelper.java
/** * Returns the content of the given Element as an object implementing the * XMLizable interface. Practically speaking, the implementation uses the * {@link SaxBuffer} class. The XMLizable object will be a standalone blurb * of SAX events, not producing start/endDocument calls and containing all * necessary namespace declarations.// ww w . j av a2 s . c o m */ public static XMLizable compileElementContent(Element element) { // Remove location information LocationAttributes.remove(element, true); SaxBuffer saxBuffer = new SaxBuffer(); DOMStreamer domStreamer = new DOMStreamer(); domStreamer.setContentHandler(saxBuffer); NodeList childNodes = element.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { try { domStreamer.stream(childNodes.item(i)); } catch (SAXException e) { // It's unlikely that an exception will occur here, // so use a runtime exception throw new RuntimeException("Error in DomHelper.compileElementContent: " + e.toString()); } } return saxBuffer; }
From source file:org.apache.cocoon.woody.util.DomHelper.java
/** * Returns the content of the given Element as an object implementing the * XMLizable interface. Practically speaking, the implementation uses the * {@link SaxBuffer} class. The XMLizable object will be a standalone blurb * of SAX events, not producing start/endDocument calls and containing all * necessary namespace declarations./*from www . j av a 2 s . c o m*/ */ public static XMLizable compileElementContent(Element element) { SaxBuffer saxBuffer = new SaxBuffer(); DOMStreamer domStreamer = new DOMStreamer(); domStreamer.setContentHandler(saxBuffer); NodeList childNodes = element.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { try { domStreamer.stream(childNodes.item(i)); } catch (SAXException e) { // It's unlikely that an exception will occur here, // so use a runtime exception throw new RuntimeException("Error in DomHelper.compileElementContent: " + e.toString()); } } return saxBuffer; }
From source file:org.cerberus.crud.service.impl.ImportFileService.java
@Override public AnswerItem importAndValidateXMLFromInputStream(InputStream filecontent, InputStream schemaContent, XMLHandlerEnumType handlerType) { AnswerItem answer = new AnswerItem(); MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK); msg.setDescription(/* ww w .j a v a 2s. c o m*/ msg.getDescription().replace("%ITEM%", "Test Data Library").replace("%OPERATION%", "Import")); if (schemaContent != null) { try { //InputStream data = new BufferedInputStream(filecontent); String textContent = IOUtils.toString(filecontent); Source source = new StreamSource(IOUtils.toInputStream(textContent)); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source sourceschema = new StreamSource(schemaContent); Schema schema = factory.newSchema(sourceschema); Validator validator = schema.newValidator(); //is valid validator.validate(source); //document is valid, then proceed to load the data answer.setItem(parseXMLFile(IOUtils.toInputStream(textContent), handlerType)); } catch (SAXException ex) { MyLogger.log(ImportFileService.class.getName(), Level.ERROR, "Unable to parse XML: " + ex.toString()); msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_IMPORT_ERROR_FORMAT); msg.setDescription( msg.getDescription().replace("%ITEM%", "Test Data Library").replace("%FORMAT%", "XML")); } catch (ParserConfigurationException ex) { MyLogger.log(ImportFileService.class.getName(), Level.ERROR, "Unable to parse XML: " + ex.toString()); msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED); msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", "Unable to parse the XML document. Please try again later.")); } catch (IOException ex) { MyLogger.log(ImportFileService.class.getName(), Level.ERROR, "Unable to parse XML: " + ex.toString()); msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED); msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", "Unable to verify if the XML document is valid. Please try again later.")); } } answer.setResultMessage(msg); return answer; }
From source file:org.jboss.bpm.console.server.util.DOMUtils.java
/** Parse the given XML stream and return the root Element *///from w ww. j a v a 2 s . c o m public static Element parse(InputStream xmlStream) throws IOException { try { return getDocumentBuilder().parse(xmlStream).getDocumentElement(); } catch (SAXException se) { throw new IOException(se.toString()); } finally { xmlStream.close(); } }
From source file:org.jboss.bpm.console.server.util.DOMUtils.java
/** Parse the given input source and return the root Element *///from w ww. java 2 s . c om public static Element parse(InputSource source) throws IOException { try { return getDocumentBuilder().parse(source).getDocumentElement(); } catch (SAXException se) { throw new IOException(se.toString()); } finally { InputStream is = source.getByteStream(); if (is != null) { is.close(); } Reader r = source.getCharacterStream(); if (r != null) { r.close(); } } }
From source file:org.jts.protocolvalidator.DefinitionFinder.java
private static String getFileID(File file) throws Exception { Document doc = null;/*from ww w .j a v a2 s . c o m*/ DocumentBuilder db = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); String id = ""; try { db = dbf.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException pce) { Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE, "Exception while configuring parser: " + pce.toString(), pce); throw new CodeGeneratorException("Exception while configuring parser: " + pce.getMessage()); } // see if the file can be parsed try { doc = db.parse(file); } catch (final IOException ioe) { Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE, "Unable to read file" + file.getName() + " \n " + ioe.toString(), ioe); } catch (final SAXException saxe) { Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE, "Unable to parse file" + file.getName() + " \n " + saxe.toString(), saxe); } // getting the id from the file Element root = doc.getDocumentElement(); if (root.getAttribute("xmlns").equals("urn:jaus:jsidl:1.0")) { id = root.getAttribute("id"); } return id; }
From source file:org.jts.protocolvalidator.DefinitionFinder.java
/** * Filter jsidl files and place in a Map with associated id. * @param fileList list of JSIDL XML files *//*from ww w . j a v a 2 s . c o m*/ private void populateIDMap(List<File> fileList, String schemaPath) throws Exception { Document doc = null; DocumentBuilder db = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); String id = ""; try { db = dbf.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException pce) { Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE, "Exception while configuring parser: " + pce.toString(), pce); throw new CodeGeneratorException("Exception while configuring parser: " + pce.getMessage()); } // store the path/id for each path in the list for (int ii = 0; ii < fileList.size(); ii++) { File file = fileList.get(ii); final String fileName = file.getPath(); // see if the file can be parsed try { doc = db.parse(file); } catch (final IOException ioe) { Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE, "Unable to read file" + fileName + " \n " + ioe.toString(), ioe); continue; // weaken import to allow bad files in target dir } catch (final SAXException saxe) { Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE, "Unable to parse file" + fileName + " \n " + saxe.toString(), saxe); continue; // weaken import to allow bad files in target dir } // getting the id from the file Element root = doc.getDocumentElement(); if (root.getAttribute("xmlns").equals("urn:jaus:jsidl:1.0")) { JSIDLReader reader = new JSIDLReader(fileName, schemaPath); Object rootObj = reader.getRootElement(); if (rootObj instanceof ServiceDef) { serviceDefMap.put(((ServiceDef) rootObj).getId(), ((ServiceDef) rootObj)); serviceSet.getServiceDef().add(((ServiceDef) rootObj)); } else if (rootObj instanceof DeclaredTypeSet) { typeSetMap.put(((DeclaredTypeSet) rootObj).getId(), ((DeclaredTypeSet) rootObj)); serviceSet.getDeclaredTypeSet().add(((DeclaredTypeSet) rootObj)); } else if (rootObj instanceof DeclaredConstSet) { constSetMap.put(((DeclaredConstSet) rootObj).getId(), ((DeclaredConstSet) rootObj)); serviceSet.getDeclaredConstSet().add(((DeclaredConstSet) rootObj)); } } } }
From source file:org.jts.protocolvalidator.FileFinder.java
/** * Filter jsidl files and place in a Map with associated id. * @param fileList list of JSIDL XML files *//*from w w w . j ava 2s. com*/ private void populateIDMap(List<File> fileList) throws Exception { fileMap = new HashMap(); reverseFileMap = new HashMap(); processedFileMap = new HashMap(); Document doc = null; DocumentBuilder db = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); String id = ""; try { db = dbf.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException pce) { Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE, "Exception while configuring parser: " + pce.toString(), pce); throw new Exception("Exception while configuring parser: " + pce.getMessage()); } // store the path/id for each path in the list for (int ii = 0; ii < fileList.size(); ii++) { File file = fileList.get(ii); final String fileName = file.getPath(); // see if the file can be parsed try { doc = db.parse(file); } catch (final IOException ioe) { Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE, "Unable to read file" + fileName + " \n " + ioe.toString(), ioe); continue; // weaken import to allow bad files in target dir } catch (final SAXException saxe) { Logger.getLogger(JTSFileWriter.class.getName()).log(Level.SEVERE, "Unable to parse file" + fileName + " \n " + saxe.toString(), saxe); continue; // weaken import to allow bad files in target dir } // getting the id from the file Element root = doc.getDocumentElement(); id = root.getAttribute("id"); if (root.getAttribute("xmlns").equals("urn:jaus:jsidl:1.0") && !id.isEmpty()) { fileMap.put(fileName, root.getAttribute("id")); reverseFileMap.put(root.getAttribute("id"), fileName); } } }