List of usage examples for org.xml.sax SAXException getMessage
public String getMessage()
From source file:com.graphhopper.util.InstructionListTest.java
public void verifyGPX(String gpx) { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = null;/* w w w. ja va 2s . com*/ try { Source schemaFile = new StreamSource(getClass().getResourceAsStream("gpx-schema.xsd")); schema = schemaFactory.newSchema(schemaFile); // using more schemas: http://stackoverflow.com/q/1094893/194609 } catch (SAXException e1) { throw new IllegalStateException( "There was a problem with the schema supplied for validation. Message:" + e1.getMessage()); } Validator validator = schema.newValidator(); try { validator.validate(new StreamSource(new StringReader(gpx))); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:net.ontopia.topicmaps.xml.TMXMLReader.java
@Override public void importInto(TopicMapIF topicmap) throws IOException { // Check that store is ok TopicMapStoreIF store = topicmap.getStore(); if (store == null) throw new IOException("Topic map not connected to a store."); XMLReader parser;// w w w .j av a2s. co m try { parser = DefaultXMLReaderFactory.createXMLReader(); } catch (SAXException e) { throw new IOException("Problems occurred when creating SAX2 XMLReader: " + e.getMessage()); } // Register content handlers ContentHandler handler = new TMXMLContentHandler(topicmap, base_address); if (validate) handler = new ValidatingContentHandler(handler, getTMXMLSchema(), true); parser.setContentHandler(handler); // Parse input source try { parser.parse(source); } catch (SAXException e) { if (e.getException() instanceof IOException) throw (IOException) e.getException(); throw new OntopiaRuntimeException(e); //throw new IOException("XML related problem: " + e.toString()); } }
From source file:net.sf.joost.trax.TransformerImpl.java
/** * Transforms a xml-source : SAXSource, DOMSource, StreamSource to SAXResult, * DOMResult and StreamResult//from w w w .j a v a 2 s . c o m * * @param xmlSource A <code>Source</code> * @param result A <code>Result</code> * @throws TransformerException */ public void transform(Source xmlSource, Result result) throws TransformerException { StxEmitter out = null; SAXSource saxSource = null; // should be synchronized synchronized (reentryGuard) { if (DEBUG) log.debug("perform transformation from " + "xml-source(SAXSource, DOMSource, StreamSource) " + "to SAXResult, DOMResult or StreamResult"); try { // init StxEmitter out = TrAXHelper.initStxEmitter(result, processor, null); out.setSystemId(result.getSystemId()); this.processor.setContentHandler(out); this.processor.setLexicalHandler(out); // register ErrorListener if (this.errorListener != null) { this.processor.setErrorListener(errorListener); } // construct from source a SAXSource saxSource = TrAXHelper.getSAXSource(xmlSource, errorListener); InputSource isource = saxSource.getInputSource(); if (isource != null) { if (DEBUG) log.debug("perform transformation"); if (saxSource.getXMLReader() != null) { // should not be an DOMSource if (xmlSource instanceof SAXSource) { XMLReader xmlReader = ((SAXSource) xmlSource).getXMLReader(); /** * URIs for Identifying Feature Flags and Properties : * There is no fixed set of features or properties * available for SAX2, except for two features that all XML * parsers must support. Implementors are free to define * new features and properties as needed, using URIs to * identify them. * * All XML readers are required to recognize the * "http://xml.org/sax/features/namespaces" and the * "http://xml.org/sax/features/namespace-prefixes" * features (at least to get the feature values, if not set * them) and to support a true value for the namespaces * property and a false value for the namespace-prefixes * property. These requirements ensure that all SAX2 XML * readers can provide the minimal required Namespace * support for higher-level specs such as RDF, XSL, XML * Schemas, and XLink. XML readers are not required to * recognize or support any other features or any * properties. * * For the complete list of standard SAX2 features and * properties, see the {@link org.xml.sax} Package * Description. */ if (xmlReader != null) { try { // set the required // "http://xml.org/sax/features/namespaces" Feature xmlReader.setFeature(FEAT_NS, true); // set the required // "http://xml.org/sax/features/namespace-prefixes" // Feature xmlReader.setFeature(FEAT_NSPREFIX, false); // maybe there would be other features } catch (SAXException sE) { getErrorListener().warning(new TransformerException(sE.getMessage(), sE)); } } } // set the the SAXSource as the parent of the STX-Processor this.processor.setParent(saxSource.getXMLReader()); } // perform transformation this.processor.parse(isource); } else { TransformerException tE = new TransformerException( "InputSource is null - could not perform transformation"); getErrorListener().fatalError(tE); } // perform result performResults(result, out); } catch (SAXException ex) { TransformerException tE; Exception emb = ex.getException(); if (emb instanceof TransformerException) { tE = (TransformerException) emb; } else { tE = new TransformerException(ex.getMessage(), ex); } getErrorListener().fatalError(tE); } catch (IOException ex) { // will this ever happen? getErrorListener().fatalError(new TransformerException(ex.getMessage(), ex)); } } }
From source file:de.escidoc.core.common.util.security.helper.InvocationParser.java
/** * Gets the {@link StringAttribute} for the provided values. * * @param arguments The arguments of the method call. * @param isArray Flag that indicates that the given arguments parameter is an array (<code>true</code>) * or not (<code>false</code>). * @param index The index of the current object. * @param invocationMapping The {@link InvocationMapping} to get the value for. * @return Returns a {@link StringAttribute} with the value for the invocation mapping. * @throws MissingMethodParameterException * Thrown if a mandatory method parameter is not provided. * @throws WebserverSystemException Thrown in case of an internal error. * @throws de.escidoc.core.common.exceptions.application.invalid.XmlCorruptedException *//*ww w . jav a 2s . c om*/ private StringAttribute getValueForInvocationMapping(final Object arguments, final boolean isArray, final int index, final InvocationMapping invocationMapping) throws WebserverSystemException, MissingMethodParameterException, XmlCorruptedException { // set the value final StringAttribute value; if (invocationMapping.getMappingType() == InvocationMapping.VALUE_MAPPING) { // fetch the value from inside the invocation mapping value = new StringAttribute(invocationMapping.getValue()); } else { // Get the current object addressed by the invocation mapping final Object currentObject; if (isArray) { currentObject = ((Object[]) arguments)[invocationMapping.getPosition()]; } else { if (invocationMapping.getPosition() != 0) { throw new WebserverSystemException("Invocation mapping error. Position " + invocationMapping.getPosition() + " invalid for single argument, must be 0. [id=" + invocationMapping.getId() + ']'); } currentObject = arguments; } // assert the addressed object has been provided if (currentObject == null) { throw new MissingMethodParameterException("The parameter at specified " + "position must be provided" + (invocationMapping.getPosition() + 1)); } if (invocationMapping.getMappingType() == InvocationMapping.SIMPLE_ATTRIBUTE_MAPPING) { value = new StringAttribute(currentObject.toString()); } else if (invocationMapping.getMappingType() == InvocationMapping.XML_ATTRIBUTE_MAPPING || invocationMapping.getMappingType() == InvocationMapping.OPTIONAL_XML_ATTRIBUTE_MAPPING) { // fetch the value from XML document final Document document; try { document = documentCache.retrieveDocument(currentObject); } catch (final SAXException e) { throw new XmlCorruptedException( StringUtility.format("Parsing of provided XML data failed. ", e.getMessage()), e); } catch (final Exception e) { throw new WebserverSystemException("Internal error. Parsing of XML failed.", e); } String path = invocationMapping.getPath(); boolean extractObjidNeeded = false; if (path.startsWith("extractObjid:")) { path = path.substring("extractObjid:".length()); extractObjidNeeded = true; } final String xpath = PATTERN_INDEXED.matcher(path).replaceAll("[" + (index + 1) + ']'); final NodeList nodeList; try { nodeList = XPathAPI.selectNodeList(document, xpath); } catch (final TransformerException e) { throw new WebserverSystemException( StringUtility.format("Invocation mapping error. Xpath invalid?", xpath, index, invocationMapping.getId()), e); } if (nodeList == null || nodeList.getLength() == 0) { if (index > 0) { throw new IndexOutOfBoundsException(); } else if (invocationMapping.getMappingType() == InvocationMapping.XML_ATTRIBUTE_MAPPING) { throw new XmlCorruptedException( StringUtility.format("Expected value not found " + "in provided XML data ", xpath)); } else { // skip undefined optional attribute by setting // the value to null. value = null; } } else { int length = 1; if (invocationMapping.isMultiValue()) { length = nodeList.getLength(); } final Collection<String> values = new HashSet<String>(); for (int i = 0; i < length; i++) { final Node node = nodeList.item(i); String tmpValue = null; if (node.getFirstChild() != null) { tmpValue = node.getFirstChild().getNodeValue(); } else { tmpValue = ""; } if (tmpValue != null) { if (extractObjidNeeded) { tmpValue = XmlUtility.getIdFromURI(tmpValue); } values.add(tmpValue.trim()); } } if (values.isEmpty()) { value = null; } else { final StringBuilder valueBuf = new StringBuilder(""); for (final String val : values) { if (!val.isEmpty()) { if (valueBuf.length() > 0) { valueBuf.append(' '); } valueBuf.append(val); } } value = new StringAttribute(valueBuf.toString()); } } } else { throw new WebserverSystemException(StringUtility.format("Unsupported invocation mapping type", invocationMapping.getMappingType(), invocationMapping.getId())); } } return value; }
From source file:net.sbbi.upnp.messages.ActionMessage.java
/** * Executes the message and retuns the UPNP device response, according to the UPNP specs, * this method could take up to 30 secs to process ( time allowed for a device to respond to a request ) * @return a response object containing the UPNP parsed response * @throws IOException if some IOException occurs during message send and reception process * @throws UPNPResponseException if an UPNP error message is returned from the server * or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message ) *///from ww w .j a v a 2 s . c om public ActionResponse service() throws IOException, UPNPResponseException { ActionResponse rtrVal = null; UPNPResponseException upnpEx = null; IOException ioEx = null; StringBuffer body = new StringBuffer(256); body.append("<?xml version=\"1.0\"?>\r\n"); body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\""); body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"); body.append("<s:Body>"); body.append("<u:").append(serviceAction.getName()).append(" xmlns:u=\"").append(service.getServiceType()) .append("\">"); if (serviceAction.getInputActionArguments() != null) { // this action requires params so we just set them... for (Iterator itr = inputParameters.iterator(); itr.hasNext();) { InputParamContainer container = (InputParamContainer) itr.next(); body.append("<").append(container.name).append(">").append(container.value); body.append("</").append(container.name).append(">"); } } body.append("</u:").append(serviceAction.getName()).append(">"); body.append("</s:Body>"); body.append("</s:Envelope>"); if (log.isDebugEnabled()) log.debug("POST prepared for URL " + service.getControlURL()); URL url = new URL(service.getControlURL().toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); HttpURLConnection.setFollowRedirects(false); //conn.setConnectTimeout( 30000 ); conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort()); conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\""); conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length())); conn.setRequestProperty("SOAPACTION", "\"" + service.getServiceType() + "#" + serviceAction.getName() + "\""); OutputStream out = conn.getOutputStream(); out.write(body.toString().getBytes()); out.flush(); out.close(); conn.connect(); InputStream input = null; if (log.isDebugEnabled()) log.debug("executing query :\n" + body); try { input = conn.getInputStream(); } catch (IOException ex) { // java can throw an exception if he error code is 500 or 404 or something else than 200 // but the device sends 500 error message with content that is required // this content is accessible with the getErrorStream input = conn.getErrorStream(); } if (input != null) { int response = conn.getResponseCode(); String responseBody = getResponseBody(input); if (log.isDebugEnabled()) log.debug("received response :\n" + responseBody); SAXParserFactory saxParFact = SAXParserFactory.newInstance(); saxParFact.setValidating(false); saxParFact.setNamespaceAware(true); ActionMessageResponseParser msgParser = new ActionMessageResponseParser(serviceAction); StringReader stringReader = new StringReader(responseBody); InputSource src = new InputSource(stringReader); try { SAXParser parser = saxParFact.newSAXParser(); parser.parse(src, msgParser); } catch (ParserConfigurationException confEx) { // should never happen // we throw a runtimeException to notify the env problem throw new RuntimeException( "ParserConfigurationException during SAX parser creation, please check your env settings:" + confEx.getMessage()); } catch (SAXException saxEx) { // kind of tricky but better than nothing.. upnpEx = new UPNPResponseException(899, saxEx.getMessage()); } finally { try { input.close(); } catch (IOException ex) { // ignore } } if (upnpEx == null) { if (response == HttpURLConnection.HTTP_OK) { rtrVal = msgParser.getActionResponse(); } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) { upnpEx = msgParser.getUPNPResponseException(); } else { ioEx = new IOException("Unexpected server HTTP response:" + response); } } } try { out.close(); } catch (IOException ex) { // ignore } conn.disconnect(); if (upnpEx != null) { throw upnpEx; } if (rtrVal == null && ioEx == null) { ioEx = new IOException("Unable to receive a response from the UPNP device"); } if (ioEx != null) { throw ioEx; } return rtrVal; }
From source file:eu.planets_project.pp.plato.action.project.XmlAction.java
/** * Imports the uploaded XML-Files and stores the templates in the database. */// ww w . ja v a2s . c o m @RaiseEvent("projectListChanged") public String uploadTemplates() { try { projectImport.storeTemplatesInLibrary(file); fragmentRoot = null; templateRoot = null; } catch (SAXException e) { e.printStackTrace(); FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "Error importing templates. " + e.getMessage()); return null; } catch (IOException e) { FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "Error importing templates. " + e.getMessage()); e.printStackTrace(); return null; } FacesMessages.instance().add(FacesMessage.SEVERITY_INFO, "Templates successfully imported"); return null; }
From source file:de.badw.strauss.glyphpicker.controller.alltab.TeiLoadWorker.java
/** * Triggers parsing of the XML input stream. * * @param is the input stream// w ww . ja va2 s.co m * @return the resulting GlyphDefinition list */ public List<GlyphDefinition> parseXmlSax(InputStream is) { TeiXmlHandler handler = new TeiXmlHandler(dataSource); try { parser.parse(is, handler); handler.resolveReferences(); return handler.getGlyphDefinitions(); } catch (SAXException e) { JOptionPane.showMessageDialog(null, e.toString(), i18n.getString("TeiLoadWorker.xmlParsingError"), JOptionPane.ERROR_MESSAGE); } catch (IOException e) { JOptionPane.showMessageDialog(null, e.toString(), i18n.getString("TeiLoadWorker.xmlParsingError"), JOptionPane.ERROR_MESSAGE); } catch (TeiXmlHandler.RecursionException e) { JOptionPane.showMessageDialog(null, e.getMessage(), i18n.getString("TeiLoadWorker.xmlParsingError"), JOptionPane.ERROR_MESSAGE); } return null; }
From source file:cz.cas.lib.proarc.common.export.cejsh.CejshBuilder.java
List<String> validateCejshXml(Source bwmeta) throws SAXException, IOException { if (bwValidator == null) { bwValidator = getBwSchema().newValidator(); bwValidator.setErrorHandler(new ValidationErrorHandler()); }/* w w w. ja v a 2s . c o m*/ List<String> errors = ((ValidationErrorHandler) bwValidator.getErrorHandler()).getValidationErrors(); try { errors.clear(); bwValidator.validate(bwmeta); } catch (SAXException ex) { errors.add(0, ex.getMessage()); } return errors; }
From source file:org.bedework.calsvc.scheduling.hosts.IscheduleClient.java
/** Parse the content, and return the DOM representation. * * @param resp response from server * @return Document Parsed body or null for no body * @exception CalFacadeException Some error occurred. *//*w w w . j a v a 2s .co m*/ private Document parseContent(final Response resp) throws CalFacadeException { try { BasicHttpClient cl = resp.getClient(); long len = cl.getResponseContentLength(); if (len == 0) { return null; } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); InputStream in = cl.getResponseBodyAsStream(); return builder.parse(new InputSource(new InputStreamReader(in))); } catch (SAXException e) { throw new CalFacadeException(e.getMessage()); } catch (Throwable t) { throw new CalFacadeException(t); } }
From source file:edu.uci.ics.jung.io.GraphMLReader.java
protected void parse(Reader reader) throws IOException { try {// w w w . j a v a 2 s .c o m saxp.parse(new InputSource(reader), this); reader.close(); } catch (SAXException saxe) { throw new IOException(saxe.getMessage()); } }