List of usage examples for org.xml.sax SAXParseException getColumnNumber
public int getColumnNumber()
From source file:ca.uhn.fhir.validation.SchemaBaseValidator.java
private void doValidate(IValidationContext<?> theContext, String schemaName) { Schema schema = loadSchema("dstu", schemaName); try {/*from www . j a va 2s . co m*/ Validator validator = schema.newValidator(); MyErrorHandler handler = new MyErrorHandler(theContext); validator.setErrorHandler(handler); String encodedResource; if (theContext.getResourceAsStringEncoding() == EncodingEnum.XML) { encodedResource = theContext.getResourceAsString(); } else { encodedResource = theContext.getFhirContext().newXmlParser() .encodeResourceToString((IBaseResource) theContext.getResource()); } try { /* * See https://github.com/jamesagnew/hapi-fhir/issues/339 * https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing */ validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); } catch (SAXNotRecognizedException ex) { ourLog.warn("Jaxp 1.5 Support not found.", ex); } validator.validate(new StreamSource(new StringReader(encodedResource))); } catch (SAXParseException e) { SingleValidationMessage message = new SingleValidationMessage(); message.setLocationLine(e.getLineNumber()); message.setLocationCol(e.getColumnNumber()); message.setMessage(e.getLocalizedMessage()); message.setSeverity(ResultSeverityEnum.FATAL); theContext.addValidationMessage(message); } catch (SAXException e) { // Catch all throw new ConfigurationException("Could not load/parse schema file", e); } catch (IOException e) { // Catch all throw new ConfigurationException("Could not load/parse schema file", e); } }
From source file:org.openmrs.module.sync.SyncUtil.java
public static Collection<SyncItem> getSyncItemsFromPayload(String payload) throws HibernateException { Collection<SyncItem> items = null; Package pkg = new Package(); try {//from ww w . j a va 2 s . c o m Record record = pkg.createRecordFromString(payload); Item root = record.getRootItem(); List<Item> itemsToDeSerialize = record.getItems(root); if (itemsToDeSerialize != null && itemsToDeSerialize.size() > 0) { items = new LinkedList<SyncItem>(); for (Item i : itemsToDeSerialize) { SyncItem syncItem = new SyncItem(); syncItem.load(record, i); items.add(syncItem); } } } catch (SAXParseException e) { log.error("Error processing XML at column " + e.getColumnNumber() + ", and line number " + e.getLineNumber() + "; public ID of entity causing error: " + e.getPublicId() + "; system id of entity causing error: " + e.getSystemId() + "; contents: " + payload.toString()); throw new HibernateException("Error processing XML while deserializing object from storage", e); } catch (Exception e) { log.error("Could not deserialize object from storage", e); throw new HibernateException("Could not deserialize object from storage", e); } return items; }
From source file:com.gdo.stencils.factory.InterpretedStencilFactory.java
/** * Returns the template descriptor from name (parsing template description * file if needed). Need to be synchronized as using parser (TODO replace it * by SAX!!!)/* w w w .j a v a2s .co m*/ */ @SuppressWarnings({ "unchecked", "static-access" }) public TemplateDescriptor<C, S> getTemplateDescriptor(C stclContext, String className) { // template class name cannot be blank if (StringUtils.isBlank(className)) { return null; } // synchronized to avoid several parsing at same time synchronized (TEMPLATE_DESCRIPTORS) { // change template class name to template stencil xml filename String res = className.replace('.', '/') + ".xml"; // if already exists if (this.TEMPLATE_DESCRIPTORS.containsKey(className)) { return (TemplateDescriptor<C, S>) this.TEMPLATE_DESCRIPTORS.get(className); } // parses it and set descriptor attributes try { // InputStream in = IOHelper.getInputStream(res, // stclContext.getTemplatePathes(), null, true); InputStream in = ClassHelper.getResourceAsStream(res); if (in == null) { return null; } // parses the description InterpretedStencilFactory<C, S> factory = (InterpretedStencilFactory<C, S>) stclContext .<C, S>getStencilFactory(); TemplateDescriptor<C, S> tempDesc = (TemplateDescriptor<C, S>) factory._digester.parse(in); // all plugs in a template are in creation mode tempDesc.forcePlugsInCreationMode(); tempDesc.setName(className); // stores descriptor this.TEMPLATE_DESCRIPTORS.put(className, tempDesc); return tempDesc; } catch (SAXParseException e) { int col = e.getColumnNumber(); int line = e.getLineNumber(); logError(stclContext, "cannot parse template %s (l:%s, c%s)", className, Integer.toString(line), Integer.toString(col)); return null; } catch (Exception e) { logError(stclContext, "cannot parse template %s", className); return null; } } }
From source file:net.sourceforge.fullsync.fs.connection.SyncFileBufferedConnection.java
protected void loadFromBuffer() throws IOException { File fsRoot = fs.getRoot();// ww w .ja va 2 s .com File f = fsRoot.getChild(BUFFER_FILENAME); root = new AbstractBufferedFile(this, fsRoot, null, true, true); if ((null == f) || !f.exists() || f.isDirectory()) { if (isMonitoringFileSystem()) { updateFromFileSystem(root); } return; } ByteArrayOutputStream out = new ByteArrayOutputStream((int) f.getSize()); try (InputStream in = new GZIPInputStream(f.getInputStream())) { int i; byte[] block = new byte[4096]; while ((i = in.read(block)) > 0) { out.write(block, 0, i); } } try { SAXParser sax = SAXParserFactory.newInstance().newSAXParser(); sax.parse(new ByteArrayInputStream(out.toByteArray()), new SyncFileDefaultHandler(this)); } catch (SAXParseException spe) { StringBuilder sb = new StringBuilder(spe.toString()); sb.append("\n Line number: " + spe.getLineNumber()); //$NON-NLS-1$ sb.append("\n Column number: " + spe.getColumnNumber()); //$NON-NLS-1$ sb.append("\n Public ID: " + spe.getPublicId()); //$NON-NLS-1$ sb.append("\n System ID: " + spe.getSystemId() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ System.err.println(sb.toString()); } catch (IOException | SAXException | ParserConfigurationException | FactoryConfigurationError e) { ExceptionHandler.reportException(e); } if (isMonitoringFileSystem()) { updateFromFileSystem(root); } }
From source file:org.slc.sli.ingestion.validation.XsdErrorHandler.java
/** * Incorporate the SAX error message into an ingestion error message. * * @param saxErrorMessage/*from ww w. j a va2 s. com*/ * Error message returned by SAX * @return Error message returned by Ingestion */ private String getErrorMessage(SAXParseException ex) { // Create an ingestion error message incorporating the SAXParseException information. String fullParsefilePathname = (ex.getSystemId() == null) ? "" : ex.getSystemId(); File parseFile = new File(fullParsefilePathname); // Return the ingestion error message. return MessageSourceHelper.getMessage(messageSource, "XSD_VALIDATION_ERROR", parseFile.getName(), String.valueOf(ex.getLineNumber()), String.valueOf(ex.getColumnNumber()), ex.getMessage()); }
From source file:eionet.gdem.validation.ValidationService.java
/** /**/*from w w w . j ava 2 s. c om*/ * Validate XML. If schema is null, then read the schema or DTD from the header of XML. If schema or DTD is defined, then ignore * the defined schema or DTD. * * @param srcStream XML file as InputStream to be validated. * @param schema XML Schema URL. * @return Validation result as HTML snippet. * @throws DCMException in case of unknnown system error. */ public String validateSchema(InputStream srcStream, String schema) throws DCMException { String result = ""; boolean isDTD = false; boolean isBlocker = false; if (Utils.isNullStr(schema)) { schema = null; } try { SAXParserFactory spfact = SAXParserFactory.newInstance(); SAXParser parser = spfact.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(errHandler); XmlconvCatalogResolver catalogResolver = new XmlconvCatalogResolver(); reader.setEntityResolver(catalogResolver); // make parser to validate reader.setFeature("http://xml.org/sax/features/validation", true); reader.setFeature("http://apache.org/xml/features/validation/schema", true); reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); reader.setFeature("http://xml.org/sax/features/namespaces", true); reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); reader.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false); InputAnalyser inputAnalyser = new InputAnalyser(); inputAnalyser.parseXML(uriXml); String namespace = inputAnalyser.getSchemaNamespace(); // if schema is not in the parameter, then sniff it from the header of xml if (schema == null) { schema = inputAnalyser.getSchemaOrDTD(); isDTD = inputAnalyser.isDTD(); } else { // if the given schema ends with dtd, then don't do schema validation isDTD = schema.endsWith("dtd"); } // schema is already given as a parameter. Read the default namespace from XML file and set external schema. if (schema != null) { if (!isDTD) { if (Utils.isNullStr(namespace)) { // XML file does not have default namespace setNoNamespaceSchemaProperty(reader, schema); } else { setNamespaceSchemaProperty(reader, namespace, schema); } } else { // validate against DTD setLocalSchemaUrl(schema); LocalEntityResolver localResolver = new LocalEntityResolver(schema, getValidatedSchema()); reader.setEntityResolver(localResolver); } } else { return validationFeedback.formatFeedbackText( "Could not validate XML file. Unable to locate XML Schema reference.", QAFeedbackType.WARNING, isBlocker); } // if schema is not available, then do not parse the XML and throw error if (!Utils.resourceExists(getValidatedSchema())) { return validationFeedback.formatFeedbackText( "Failed to read schema document from the following URL: " + getValidatedSchema(), QAFeedbackType.ERROR, isBlocker); } Schema schemaObj = schemaManager.getSchema(getOriginalSchema()); if (schemaObj != null) { isBlocker = schemaObj.isBlocker(); } validationFeedback.setSchema(getOriginalSchema()); InputSource is = new InputSource(srcStream); reader.parse(is); } catch (SAXParseException se) { return validationFeedback.formatFeedbackText("Document is not well-formed. Column: " + se.getColumnNumber() + "; line:" + se.getLineNumber() + "; " + se.getMessage(), QAFeedbackType.ERROR, isBlocker); } catch (IOException ioe) { return validationFeedback.formatFeedbackText( "Due to an IOException, the parser could not check the document. " + ioe.getMessage(), QAFeedbackType.ERROR, isBlocker); } catch (Exception e) { Exception se = e; if (e instanceof SAXException) { se = ((SAXException) e).getException(); } if (se != null) { se.printStackTrace(System.err); } else { e.printStackTrace(System.err); } return validationFeedback.formatFeedbackText( "The parser could not check the document. " + e.getMessage(), QAFeedbackType.ERROR, isBlocker); } validationFeedback.setValidationErrors(getErrorList()); result = validationFeedback.formatFeedbackText(isBlocker); // validation post-processor QAResultPostProcessor postProcessor = new QAResultPostProcessor(); result = postProcessor.processQAResult(result, schema); warningMessage = postProcessor.getWarningMessage(schema); return result; }
From source file:com.gdo.stencils.factory.InterpretedStencilFactory.java
@Override @SuppressWarnings("unchecked") public synchronized _Stencil<C, S> loadStencil(C stclContext, Reader in, String name) { try {/*from w w w. j a v a 2 s.com*/ Object parsed = _digester.parse(in); if (parsed instanceof StencilDescriptor) { StencilDescriptor<C, S> descriptor = (StencilDescriptor<C, S>) parsed; String rootId = descriptor.getId(); InstanceRepository<C, S> instances = new InstanceRepository<C, S>(rootId); return descriptor.createInstance(stclContext, rootId, instances, 0); } } catch (SAXParseException e) { logError(stclContext, "'t:%s, l:%s, c:%s : %s)", name, Integer.toString(e.getLineNumber()), Integer.toString(e.getColumnNumber()), e.getMessage()); } catch (Exception e) { logError(stclContext, "Error when loading stencil %s", e); } return null; }
From source file:kmlvalidator.KmlValidatorServlet.java
/** * Handles POST requests for the servlet. *///w w w.j a v a2 s.c o m public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { // Our response is always JSON. response.setContentType("application/json"); // Create the JSON response objects to be filled in later. JSONObject responseObj = new JSONObject(); JSONArray responseErrors = new JSONArray(); try { // Load XSD files here. Note that the Java runtime should be caching // these files. Object[] schemas = { new URL("http://schemas.opengis.net/kml/2.2.0/atom-author-link.xsd").openConnection() .getInputStream(), new URL("http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd").openConnection().getInputStream(), new URL("http://code.google.com/apis/kml/schema/kml22gx.xsd").openConnection() .getInputStream() }; // Create a SAX parser factory (not a DOM parser, we don't need the // overhead) and set it to validate and be namespace aware, for // we want to validate against multiple XSDs. SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // Create a SAX parser and prepare for XSD validation. SAXParser parser = parserFactory.newSAXParser(); parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); parser.setProperty(JAXP_SCHEMA_SOURCE, schemas); // Create a parser handler to trap errors during parse. KmlValidatorParserHandler parserHandler = new KmlValidatorParserHandler(); // Parse the KML and send all errors to our handler. parser.parse(request.getInputStream(), parserHandler); // Check our handler for validation results. if (parserHandler.getErrors().size() > 0) { // There were errors, enumerate through them and create JSON objects // for each one. for (KmlValidationError e : parserHandler.getErrors()) { JSONObject error = new JSONObject(); switch (e.getType()) { case KmlValidationError.VALIDATION_WARNING: error.put("type", "warning"); break; case KmlValidationError.VALIDATION_ERROR: error.put("type", "error"); break; case KmlValidationError.VALIDATION_FATAL_ERROR: error.put("type", "fatal_error"); break; default: error.put("type", "fatal_error"); } // fill in parse exception details SAXParseException innerException = e.getInnerException(); error.put("message", innerException.getMessage()); if (innerException.getLineNumber() >= 0) error.put("line", innerException.getLineNumber()); if (innerException.getColumnNumber() >= 0) error.put("column", innerException.getColumnNumber()); // add this error to the list responseErrors.add(error); } // The KML wasn't valid. responseObj.put("status", "invalid"); } else { // The KML is valid against the XSDs. responseObj.put("status", "valid"); } } catch (SAXException e) { // We should never get here due to regular parse errors. This error // must've been thrown by the schema factory. responseObj.put("status", "internal_error"); JSONObject error = new JSONObject(); error.put("type", "fatal_error"); error.put("message", "Internal error: " + e.getMessage()); responseErrors.add(error); } catch (ParserConfigurationException e) { // Internal error at this point. responseObj.put("status", "internal_error"); JSONObject error = new JSONObject(); error.put("type", "fatal_error"); error.put("message", "Internal parse error."); responseErrors.add(error); } // If there were errors, add them to the final response JSON object. if (responseErrors.size() > 0) { responseObj.put("errors", responseErrors); } // output the JSON object as the HTTP response and append a newline for // prettiness response.getWriter().print(responseObj); response.getWriter().println(); }
From source file:org.apache.uima.ruta.resource.TreeWordList.java
public void readXML(InputStream stream, String encoding) throws IOException { try {/*from ww w .j a va2 s. co m*/ InputStream is = new BufferedInputStream(stream); // adds mark/reset support boolean isXml = MultiTreeWordListPersistence.isSniffedXmlContentType(is); if (!isXml) { // MTWL is encoded is = new ZipInputStream(is); ((ZipInputStream) is).getNextEntry(); // zip must contain a single entry } InputStreamReader streamReader = new InputStreamReader(is, encoding); this.root = new TextNode(); XMLEventHandler handler = new XMLEventHandler(root); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); // XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.setErrorHandler(handler); reader.parse(new InputSource(streamReader)); } catch (SAXParseException spe) { StringBuffer sb = new StringBuffer(spe.toString()); sb.append("\n Line number: " + spe.getLineNumber()); sb.append("\n Column number: " + spe.getColumnNumber()); sb.append("\n Public ID: " + spe.getPublicId()); sb.append("\n System ID: " + spe.getSystemId() + "\n"); System.out.println(sb.toString()); } catch (SAXException se) { System.out.println("loadDOM threw " + se); se.printStackTrace(System.out); } catch (ParserConfigurationException e) { e.printStackTrace(); } }
From source file:com.cyberway.issue.crawler.settings.XMLSettingsHandler.java
/** Read the CrawlerSettings object from a specific file. * * @param settings the settings object to be updated with data from the * persistent storage.// w w w.j a v a 2 s . c o m * @param f the file to read from. * @return the updated settings object or null if there was no data for this * in the persistent storage. */ protected final CrawlerSettings readSettingsObject(CrawlerSettings settings, File f) { CrawlerSettings result = null; try { InputStream is = null; if (!f.exists()) { // Perhaps the file we're looking for is on the CLASSPATH. // DON'T look on the CLASSPATH for 'settings.xml' files. The // look for 'settings.xml' files happens frequently. Not looking // on classpath for 'settings.xml' is an optimization based on // ASSUMPTION that there will never be a 'settings.xml' saved // on classpath. if (!f.getName().startsWith(settingsFilename)) { is = XMLSettingsHandler.class.getResourceAsStream(f.getPath()); } } else { is = new FileInputStream(f); } if (is != null) { XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); InputStream file = new BufferedInputStream(is); parser.setContentHandler(new CrawlSettingsSAXHandler(settings)); InputSource source = new InputSource(file); source.setSystemId(f.toURL().toExternalForm()); parser.parse(source); result = settings; } } catch (SAXParseException e) { logger.warning(e.getMessage() + " in '" + e.getSystemId() + "', line: " + e.getLineNumber() + ", column: " + e.getColumnNumber()); } catch (SAXException e) { logger.warning(e.getMessage() + ": " + e.getException().getMessage()); } catch (ParserConfigurationException e) { logger.warning(e.getMessage() + ": " + e.getCause().getMessage()); } catch (FactoryConfigurationError e) { logger.warning(e.getMessage() + ": " + e.getException().getMessage()); } catch (IOException e) { logger.warning("Could not access file '" + f.getAbsolutePath() + "': " + e.getMessage()); } return result; }