List of usage examples for org.xml.sax SAXException getException
public Exception getException()
From source file:net.sf.joost.trax.TransformerImpl.java
/** * Transforms a xml-source : SAXSource, DOMSource, StreamSource to SAXResult, * DOMResult and StreamResult/* w w w. j av a2 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.fhg.fokus.diameter.DiameterPeer.DiameterPeer.java
private boolean readConfigFile(String cfgFile) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // factory.setValidating(true); // factory.setNamespaceAware(true); try {//w w w .ja v a 2 s. co m DocumentBuilder builder = factory.newDocumentBuilder(); config = builder.parse(cfgFile); } catch (SAXException sxe) { // Error generated during parsing) Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); return false; } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace(); return false; } catch (IOException ioe) { // I/O error ioe.printStackTrace(); return false; } return true; }
From source file:de.fhg.fokus.diameter.DiameterPeer.DiameterPeer.java
private boolean readConfigString(String cfgString) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // factory.setValidating(true); // factory.setNamespaceAware(true); try {//from w ww . ja v a 2s. c om DocumentBuilder builder = factory.newDocumentBuilder(); config = builder.parse(new InputSource(new StringReader(cfgString))); } catch (SAXException sxe) { // Error generated during parsing) Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); x.printStackTrace(); return false; } catch (ParserConfigurationException pce) { // Parser with specified options can't be built pce.printStackTrace(); return false; } catch (IOException ioe) { // I/O error ioe.printStackTrace(); return false; } return true; }
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 ww .j a v a2 s. c o 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:com.evolveum.midpoint.prism.schema.DomToSchemaProcessor.java
private XSSchemaSet parseSchema(Element schema) throws SchemaException { // Make sure that the schema parser sees all the namespace declarations DOMUtil.fixNamespaceDeclarations(schema); XSSchemaSet xss = null;/*from w ww .j av a2 s . co m*/ try { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(schema); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamResult result = new StreamResult(out); trans.transform(source, result); XSOMParser parser = createSchemaParser(); InputSource inSource = new InputSource(new ByteArrayInputStream(out.toByteArray())); // XXX: hack: it's here to make entity resolver work... inSource.setSystemId("SystemId"); // XXX: end hack inSource.setEncoding("utf-8"); parser.parse(inSource); xss = parser.getResult(); } catch (SAXException e) { throw new SchemaException("XML error during XSD schema parsing: " + e.getMessage() + "(embedded exception " + e.getException() + ") in " + shortDescription, e); } catch (TransformerException e) { throw new SchemaException("XML transformer error during XSD schema parsing: " + e.getMessage() + "(locator: " + e.getLocator() + ", embedded exception:" + e.getException() + ") in " + shortDescription, e); } catch (RuntimeException e) { // This sometimes happens, e.g. NPEs in Saxon if (LOGGER.isErrorEnabled()) { LOGGER.error("Unexpected error {} during parsing of schema:\n{}", e.getMessage(), DOMUtil.serializeDOMToString(schema)); } throw new SchemaException( "XML error during XSD schema parsing: " + e.getMessage() + " in " + shortDescription, e); } return xss; }
From source file:ca.sqlpower.architect.ProjectLoader.java
/** * Loads the project data from the given input stream. * <p>// w w w . jav a 2 s .c om * Note: the input stream is always closed afterwards. * * @param in * Used to load in the project data, must support mark. * @param dataSources * Collection of the data sources used in the project */ public void load(InputStream in, DataSourceCollection<? extends SPDataSource> dataSources, ArchitectSession messageDelegate) throws IOException, SQLObjectException { UnclosableInputStream uin = new UnclosableInputStream(in); siblingSession = messageDelegate; try { dbcsLoadIdMap = new HashMap<String, JDBCDataSource>(); sqlObjectLoadIdMap = new HashMap<String, SQLObject>(); Digester digester = null; // use digester to read from file try { digester = setupDigester(); digester.parse(uin); } catch (SAXException ex) { //The digester likes to wrap the cancelled exception in a SAXException. if (ex.getException() instanceof DigesterCancelledException) { //Digeseter was cancelled by the user. Do not load anything. throw new RuntimeException(new InterruptedIOException("progress")); } logger.error("SAX Exception in project file parse!", ex); String message; if (digester == null) { message = "Couldn't create an XML parser"; } else { message = "There is an XML parsing error in project file at Line:" + digester.getDocumentLocator().getLineNumber() + " Column:" + digester.getDocumentLocator().getColumnNumber(); } throw new SQLObjectException(message, ex); } catch (IOException ex) { logger.error("IO Exception in project file parse!", ex); throw new SQLObjectException("There was an I/O error while reading the file", ex); } catch (Exception ex) { logger.error("General Exception in project file parse!", ex); throw new SQLObjectException("Unexpected Exception", ex); } SQLObject dbConnectionContainer = ((SQLObject) getSession().getRootObject()); // hook up data source parent types for (SQLDatabase db : dbConnectionContainer.getChildren(SQLDatabase.class)) { JDBCDataSource ds = db.getDataSource(); String parentTypeId = ds.getPropertiesMap().get(JDBCDataSource.DBCS_CONNECTION_TYPE); if (parentTypeId != null) { for (JDBCDataSourceType dstype : dataSources.getDataSourceTypes()) { if (dstype.getName().equals(parentTypeId)) { ds.setParentType(dstype); // TODO unit test that this works } } if (ds.getParentType() == null) { logger.error("Data Source \"" + ds.getName() + "\" has type \"" + parentTypeId + "\", which is not configured in the user prefs."); // TODO either reconstruct the parent type, or bring this problem to the attention of the user. // TODO test this } else { // TODO test that the referenced parent type is properly configured (has a driver, etc) // TODO test for this behaviour } } } /* * for backward compatibilty, in the old project file, we have * primaryKeyName in the table attrbute, but nothing * in the sqlIndex that indicates primary key index, * so, we have to set the index as primary key index * if the index name == table.primaryKeyName after load the project, * table.primaryKeyName is save in the map now, not in the table object */ for (SQLTable table : (List<SQLTable>) getSession().getTargetDatabase().getTables()) { if (logger.isDebugEnabled()) { if (!table.isPopulated()) { logger.debug("Table [" + table.getName() + "] not populated"); } else { logger.debug( "Table [" + table.getName() + "] index folder contents: " + table.getIndices()); } } if (table.getPrimaryKeyIndex() == null) { logger.debug("primary key index is null in table: " + table); logger.debug("number of children found in indices folder: " + table.getIndices().size()); for (SQLIndex index : table.getIndices()) { if (sqlObjectLoadIdMap.get(table.getName() + "." + index.getName()) != null) { table.getPrimaryKeyIndex().updateToMatch(index); break; } } } logger.debug("Table [" + table.getName() + "]2 index folder contents: " + table.getIndices()); logger.debug("Table [" + table.getName() + "]3 index folder contents: " + table.getIndices()); if (logger.isDebugEnabled()) { if (!table.isPopulated()) { logger.debug("Table [" + table.getName() + "] not populated"); } else { logger.debug("Table [" + table.getName() + "] index folder contents: " + table.getIndices().size()); } } } /* * In old versions of the architect, user defined types weren't * available, so all columns stored their type as a JDBC type code. * For all columns in the playpen, we need to hook up upstream user * defined types. */ ListMultimap<String, SQLColumn> columns = ArrayListMultimap.create(); for (SQLTable table : getSession().getTargetDatabase().getTables()) { for (SQLColumn column : table.getChildren(SQLColumn.class)) { SQLColumn sourceColumn = column.getSourceColumn(); if (sourceColumn != null && sourceColumn.getPlatform() != null) { columns.put(column.getSourceColumn().getPlatform(), column); } else { columns.put(SQLTypePhysicalPropertiesProvider.GENERIC_PLATFORM, column); } } } for (String platform : columns.keySet()) { SQLColumn.assignTypes(columns.get(platform), dataSources, platform, new DefaultUserPrompterFactory()); } setModified(false); } finally { uin.forceClose(); } }
From source file:org.apache.axis.providers.java.JavaProvider.java
/** * Invoke the message by obtaining various common fields, looking up * the service object (via getServiceObject), and actually processing * the message (via processMessage).// w ww .java 2 s .c om */ public void invoke(MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) log.debug("Enter: JavaProvider::invoke (" + this + ")"); /* Find the service we're invoking so we can grab it's options */ /***************************************************************/ String serviceName = msgContext.getTargetService(); Handler service = msgContext.getService(); /* Now get the service (RPC) specific info */ /********************************************/ String clsName = getServiceClassName(service); if ((clsName == null) || clsName.equals("")) { throw new AxisFault("Server.NoClassForService", Messages.getMessage("noOption00", getServiceClassNameOptionName(), serviceName), null, null); } IntHolder scope = new IntHolder(); Object serviceObject = null; try { serviceObject = getServiceObject(msgContext, service, clsName, scope); SOAPEnvelope resEnv = null; // If there IS a response message AND this is a one-way operation, // we delete the response message here. Note that this might // cause confusing results in some cases - i.e. nothing fails, // but your response headers don't go anywhere either. It might // be nice if in the future there was a way to detect an error // when trying to install a response message in a MessageContext // associated with a one-way operation.... OperationDesc operation = msgContext.getOperation(); if (operation != null && OperationType.ONE_WAY.equals(operation.getMep())) { msgContext.setResponseMessage(null); } else { Message resMsg = msgContext.getResponseMessage(); // If we didn't have a response message, make sure we set one up // with the appropriate versions of SOAP and Schema if (resMsg == null) { resEnv = new SOAPEnvelope(msgContext.getSOAPConstants(), msgContext.getSchemaVersion()); resMsg = new Message(resEnv); String encoding = XMLUtils.getEncoding(msgContext); resMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, encoding); msgContext.setResponseMessage(resMsg); } else { resEnv = resMsg.getSOAPEnvelope(); } } Message reqMsg = msgContext.getRequestMessage(); SOAPEnvelope reqEnv = reqMsg.getSOAPEnvelope(); processMessage(msgContext, reqEnv, resEnv, serviceObject); } catch (SAXException exp) { entLog.debug(Messages.getMessage("toAxisFault00"), exp); Exception real = exp.getException(); if (real == null) { real = exp; } throw AxisFault.makeFault(real); } catch (Exception exp) { entLog.debug(Messages.getMessage("toAxisFault00"), exp); AxisFault fault = AxisFault.makeFault(exp); //make a note if this was a runtime fault, for better logging if (exp instanceof RuntimeException) { fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION, "true"); } throw fault; } finally { // If this is a request scoped service object which implements // ServiceLifecycle, let it know that it's being destroyed now. if (serviceObject != null && scope.value == Scope.REQUEST.getValue() && serviceObject instanceof ServiceLifecycle) { ((ServiceLifecycle) serviceObject).destroy(); } } if (log.isDebugEnabled()) log.debug("Exit: JavaProvider::invoke (" + this + ")"); }
From source file:org.apache.axis.providers.java.RPCProvider.java
/** * Process the current message./*from w ww .ja va 2s.c o m*/ * Result in resEnv. * * @param msgContext self-explanatory * @param reqEnv the request envelope * @param resEnv the response envelope * @param obj the service object itself */ public void processMessage(MessageContext msgContext, SOAPEnvelope reqEnv, SOAPEnvelope resEnv, Object obj) throws Exception { if (log.isDebugEnabled()) { log.debug("Enter: RPCProvider.processMessage()"); } SOAPService service = msgContext.getService(); ServiceDesc serviceDesc = service.getServiceDescription(); RPCElement body = getBody(reqEnv, msgContext); Vector args = null; try { args = body.getParams(); } catch (SAXException e) { if (e.getException() != null) throw e.getException(); throw e; } int numArgs = args.size(); OperationDesc operation = getOperationDesc(msgContext, body); // Create the array we'll use to hold the actual parameter // values. We know how big to make it from the metadata. Object[] argValues = new Object[operation.getNumParams()]; // A place to keep track of the out params (INOUTs and OUTs) ArrayList outs = new ArrayList(); // Put the values contained in the RPCParams into an array // suitable for passing to java.lang.reflect.Method.invoke() // Make sure we respect parameter ordering if we know about it // from metadata, and handle whatever conversions are necessary // (values -> Holders, etc) for (int i = 0; i < numArgs; i++) { RPCParam rpcParam = (RPCParam) args.get(i); Object value = rpcParam.getObjectValue(); // first check the type on the paramter ParameterDesc paramDesc = rpcParam.getParamDesc(); // if we found some type info try to make sure the value type is // correct. For instance, if we deserialized a xsd:dateTime in // to a Calendar and the service takes a Date, we need to convert if (paramDesc != null && paramDesc.getJavaType() != null) { // Get the type in the signature (java type or its holder) Class sigType = paramDesc.getJavaType(); // Convert the value into the expected type in the signature value = JavaUtils.convert(value, sigType); rpcParam.setObjectValue(value); if (paramDesc.getMode() == ParameterDesc.INOUT) { outs.add(rpcParam); } } // Put the value (possibly converted) in the argument array // make sure to use the parameter order if we have it if (paramDesc == null || paramDesc.getOrder() == -1) { argValues[i] = value; } else { argValues[paramDesc.getOrder()] = value; } if (log.isDebugEnabled()) { log.debug(" " + Messages.getMessage("value00", "" + argValues[i])); } } // See if any subclasses want a crack at faulting on a bad operation // FIXME : Does this make sense here??? String allowedMethods = (String) service.getOption("allowedMethods"); checkMethodName(msgContext, allowedMethods, operation.getName()); // Now create any out holders we need to pass in int count = numArgs; for (int i = 0; i < argValues.length; i++) { // We are interested only in OUT/INOUT ParameterDesc param = operation.getParameter(i); if (param.getMode() == ParameterDesc.IN) continue; Class holderClass = param.getJavaType(); if (holderClass != null && Holder.class.isAssignableFrom(holderClass)) { int index = count; // Use the parameter order if specified or just stick them to the end. if (param.getOrder() != -1) { index = param.getOrder(); } else { count++; } // If it's already filled, don't muck with it if (argValues[index] != null) { continue; } argValues[index] = holderClass.newInstance(); // Store an RPCParam in the outs collection so we // have an easy and consistent way to write these // back to the client below RPCParam p = new RPCParam(param.getQName(), argValues[index]); p.setParamDesc(param); outs.add(p); } else { throw new AxisFault( Messages.getMessage("badOutParameter00", "" + param.getQName(), operation.getName())); } } // OK! Now we can invoke the method Object objRes = null; try { objRes = invokeMethod(msgContext, operation.getMethod(), obj, argValues); } catch (IllegalArgumentException e) { String methodSig = operation.getMethod().toString(); String argClasses = ""; for (int i = 0; i < argValues.length; i++) { if (argValues[i] == null) { argClasses += "null"; } else { argClasses += argValues[i].getClass().getName(); } if (i + 1 < argValues.length) { argClasses += ","; } } log.info(Messages.getMessage("dispatchIAE00", new String[] { methodSig, argClasses }), e); throw new AxisFault(Messages.getMessage("dispatchIAE00", new String[] { methodSig, argClasses }), e); } /** If this is a one-way operation, there is nothing more to do. */ if (OperationType.ONE_WAY.equals(operation.getMep())) return; RPCElement resBody = createResponseBody(body, msgContext, operation, serviceDesc, objRes, resEnv, outs); resEnv.addBodyElement(resBody); }
From source file:org.apache.axis.SOAPPart.java
/** * Get the contents of this Part (not the MIME headers!), as a * SOAPEnvelope. This will force a complete parse of the * message./* ww w. j a v a2s. c om*/ * * @return a <code>SOAPEnvelope</code> containing the message content * @throws AxisFault if the envelope could not be constructed */ public SOAPEnvelope getAsSOAPEnvelope() throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: SOAPPart::getAsSOAPEnvelope()"); log.debug(Messages.getMessage("currForm", formNames[currentForm])); } if (currentForm == FORM_SOAPENVELOPE) return (SOAPEnvelope) currentMessage; if (currentForm == FORM_BODYINSTREAM) { InputStreamBody bodyEl = new InputStreamBody((InputStream) currentMessage); SOAPEnvelope env = new SOAPEnvelope(); env.setOwnerDocument(this); env.addBodyElement(bodyEl); setCurrentForm(env, FORM_SOAPENVELOPE); return env; } InputSource is; if (currentForm == FORM_INPUTSTREAM) { is = new InputSource((InputStream) currentMessage); String encoding = XMLUtils.getEncoding(msgObject, null, null); if (encoding != null) { currentEncoding = encoding; is.setEncoding(currentEncoding); } } else { is = new InputSource(new StringReader(getAsString())); } DeserializationContext dser = new DeserializationContext(is, getMessage().getMessageContext(), getMessage().getMessageType()); dser.getEnvelope().setOwnerDocument(this); // This may throw a SAXException try { dser.parse(); } catch (SAXException e) { Exception real = e.getException(); if (real == null) real = e; throw AxisFault.makeFault(real); } SOAPEnvelope nse = dser.getEnvelope(); if (currentMessageAsEnvelope != null) { //Need to synchronize back processed header info. Vector newHeaders = nse.getHeaders(); Vector oldHeaders = currentMessageAsEnvelope.getHeaders(); if (null != newHeaders && null != oldHeaders) { Iterator ohi = oldHeaders.iterator(); Iterator nhi = newHeaders.iterator(); while (ohi.hasNext() && nhi.hasNext()) { SOAPHeaderElement nhe = (SOAPHeaderElement) nhi.next(); SOAPHeaderElement ohe = (SOAPHeaderElement) ohi.next(); if (ohe.isProcessed()) nhe.setProcessed(true); } } } setCurrentForm(nse, FORM_SOAPENVELOPE); log.debug("Exit: SOAPPart::getAsSOAPEnvelope"); SOAPEnvelope env = (SOAPEnvelope) currentMessage; env.setOwnerDocument(this); return env; }
From source file:org.apache.fop.render.pdf.BasePDFTest.java
private static Exception extractOriginalException(Exception e) { if (e.getCause() != null) { return extractOriginalException((Exception) e.getCause()); } else if (e instanceof SAXException) { SAXException se = (SAXException) e; if (se.getException() != null) { return extractOriginalException(se.getException()); }/*from w ww . ja va2s.c o m*/ } return e; }