Example usage for org.xml.sax SAXParseException getLineNumber

List of usage examples for org.xml.sax SAXParseException getLineNumber

Introduction

In this page you can find the example usage for org.xml.sax SAXParseException getLineNumber.

Prototype

public int getLineNumber() 

Source Link

Document

The line number of the end of the text where the exception occurred.

Usage

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 av a 2s.c o m
 *            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:com.gdo.stencils.factory.InterpretedStencilFactory.java

@Override
@SuppressWarnings("unchecked")
public synchronized _Stencil<C, S> loadStencil(C stclContext, Reader in, String name) {
    try {//from ww  w  . j a v  a 2 s. co m
        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: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!!!)/*from w  w w  . jav a 2s . c  o 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:org.apache.uima.ruta.resource.TreeWordList.java

public void readXML(InputStream stream, String encoding) throws IOException {
    try {/*from   w  w w. j  a  v  a2  s. c  o  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:eionet.gdem.validation.ValidationService.java

/**
/**/*from   w  ww  .  j a  v a 2s .c o  m*/
 * 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:SAXTreeValidator.java

/**
 * <p>//w  ww.  j  a  v  a  2  s  .c  o m
 * This will report an error that has occurred; this indicates
 *   that a rule was broken, typically in validation, but that
 *   parsing can reasonably continue.
 * </p>
 *
 * @param exception <code>SAXParseException</code> that occurred.
 * @throws <code>SAXException</code> when things go wrong 
 */
public void error(SAXParseException exception) throws SAXException {

    System.out.println("**Parsing Error**\n" + "  Line:    " + exception.getLineNumber() + "\n" + "  URI:     "
            + exception.getSystemId() + "\n" + "  Message: " + exception.getMessage());
    throw new SAXException("Error encountered");
}

From source file:SAXTreeValidator.java

/**
 * <p>//from  w w  w .j a v a 2s.  c o  m
 * This will report a warning that has occurred; this indicates
 *   that while no XML rules were "broken", something appears
 *   to be incorrect or missing.
 * </p>
 *
 * @param exception <code>SAXParseException</code> that occurred.
 * @throws <code>SAXException</code> when things go wrong 
 */
public void warning(SAXParseException exception) throws SAXException {

    System.out.println("**Parsing Warning**\n" + "  Line:    " + exception.getLineNumber() + "\n"
            + "  URI:     " + exception.getSystemId() + "\n" + "  Message: " + exception.getMessage());
    throw new SAXException("Warning encountered");
}

From source file:SAXTreeValidator.java

/**
 * <p>//from  ww  w  .  j ava2s .co m
 * This will report a fatal error that has occurred; this indicates
 *   that a rule has been broken that makes continued parsing either
 *   impossible or an almost certain waste of time.
 * </p>
 *
 * @param exception <code>SAXParseException</code> that occurred.
 * @throws <code>SAXException</code> when things go wrong 
 */
public void fatalError(SAXParseException exception) throws SAXException {

    System.out.println("**Parsing Fatal Error**\n" + "  Line:    " + exception.getLineNumber() + "\n"
            + "  URI:     " + exception.getSystemId() + "\n" + "  Message: " + exception.getMessage());
    throw new SAXException("Fatal Error encountered");
}

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./*from  w ww. j  a  va2s.co  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;
}

From source file:com.tc.config.schema.setup.StandardXMLFileConfigurationCreator.java

private TcConfiguration getConfigFromSourceStream(InputStream in, boolean trustedSource, String descrip,
        String source, ClassLoader loader) throws ConfigurationSetupException {
    TcConfiguration tcConfigDoc;/* w  w  w .  j ava2 s .  c  om*/
    try {
        ByteArrayOutputStream dataCopy = new ByteArrayOutputStream();
        IOUtils.copy(in, dataCopy);
        in.close();

        InputStream copyIn = new ByteArrayInputStream(dataCopy.toByteArray());
        BeanWithErrors beanWithErrors = beanFactory.createBean(copyIn, descrip, source, loader);

        if (beanWithErrors.errors() != null && beanWithErrors.errors().length > 0) {
            logger.debug("Configuration didn't parse; it had " + beanWithErrors.errors().length + " error(s).");

            StringBuffer buf = new StringBuffer();
            for (int i = 0; i < beanWithErrors.errors().length; ++i) {
                SAXParseException error = beanWithErrors.errors()[i];
                buf.append("  [" + i + "]: Line " + error.getLineNumber() + ", column "
                        + error.getColumnNumber() + ": " + error.getMessage() + "\n");
            }

            throw new ConfigurationSetupException("The configuration data in the " + descrip
                    + " does not obey the Terracotta schema:\n" + buf);
        } else {
            logger.debug("Configuration is valid.");
        }

        tcConfigDoc = ((TcConfiguration) beanWithErrors.bean());
        this.providedTcConfigDocument = tcConfigDoc;
    } catch (IOException ioe) {
        throw new ConfigurationSetupException("We were unable to read configuration data from the " + descrip
                + ": " + ioe.getLocalizedMessage(), ioe);
    } catch (SAXException saxe) {
        throw new ConfigurationSetupException("The configuration data in the " + descrip
                + " is not well-formed XML: " + saxe.getLocalizedMessage(), saxe);
    } catch (ParserConfigurationException pce) {
        throw Assert.failure("The XML parser can't be configured correctly; this should not happen.", pce);
    }

    return tcConfigDoc;
}