Example usage for org.xml.sax SAXException getMessage

List of usage examples for org.xml.sax SAXException getMessage

Introduction

In this page you can find the example usage for org.xml.sax SAXException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Return a detail message for this exception.

Usage

From source file:de.uzk.hki.da.cb.UnpackAction.java

private void throwUserExceptionIfNotPremisConsistent() throws IOException {

    try {/*w w w.  j a  v a 2s .  c o  m*/
        if (!PremisXmlValidator.validatePremisFile(Path.make(wa.dataPath(), C.PREMIS_XML).toFile()))
            throw new UserException(UserExceptionId.INVALID_SIP_PREMIS, "PREMIS Datei nicht valide.");
    } catch (FileNotFoundException e1) {
        throw new UserException(UserExceptionId.SIP_PREMIS_NOT_FOUND, "PREMIS Datei nicht gefunden.", e1);
    } catch (SAXException e) {
        logger.error(e.getMessage());
        throw new UserException(UserExceptionId.INVALID_SIP_PREMIS,
                "PREMIS Datei nicht valide.: " + e.getMessage());
    }
    try {
        //just test: parse values and do xml to object mapping
        new ObjectPremisXmlReader().deserialize(Path.makeFile(wa.dataPath(), C.PREMIS_XML));
    } catch (Exception e) {
        throw new UserException(UserExceptionId.READ_SIP_PREMIS_ERROR,
                "Konnte PREMIS Datei nicht erfolgreich einlesen.", e);
    }
}

From source file:org.openmrs.module.sdmxhddataexport.web.controller.report.ReportDataElementController.java

public String transform(String str) throws Exception {
    try {/* ww  w. j av a  2s. co  m*/
        //String XMLFileName = "src\\cdcatalog.xml";
        //String OutputFileName = "src\\myResult.html";
        //  String StyleFileName = "/media/xml-to-string.xsl";
        InputStream inpXsl = OpenmrsClassLoader.getInstance().getResourceAsStream("xml-to-string.xsl");

        XMLReader reader = XMLReaderFactory.createXMLReader();
        InputStream inp = new ByteArrayInputStream(str.getBytes());
        Source source = new SAXSource(reader, new InputSource(inp));
        //Source source2 = new SAXSource(reader, new InputSource(StyleFileName));
        //ContentHandler theHandler = new MyHandler();
        StringWriter outWriter = new StringWriter();
        StreamResult result = new StreamResult(outWriter);
        //Result result = new StreamResult(OutputFileName);
        //          InputStream stinp=new ByteArrayInputStream(styleText.getBytes());         
        Source style = new StreamSource(inpXsl);

        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer trans = transFactory.newTransformer(style);

        trans.transform(source, result);
        String s = outWriter.getBuffer().toString();
        System.out.println(s);
        return s;
    } catch (SAXException e) {
        System.out.println(e.getMessage());
        return e.getMessage();
    }
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static Document parseDocument(String doc) {
    try {/*  w w  w.ja va 2 s . c  o  m*/
        DocumentBuilder loader = createDocumentBuilder();
        return loader.parse(IOUtils.toInputStream(doc, "utf-8"));
    } catch (SAXException ex) {
        throw new IllegalStateException("Error parsing XML document " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new IllegalStateException("Error parsing XML document " + ex.getMessage(), ex);
    }
}

From source file:com.litwan.yanel.impl.resources.svg.SvgEditResource.java

/**
 * Checks if InputStream is wellformed/*from ww  w  . j  av a 2  s . c  om*/
 * @return boolean true if wellformed, false if not
 * @param InputStream which is checked if wellformed
 * @throws UsecaseException
 */
private boolean isWellformed(InputStream is) throws UsecaseException {
    try {
        //TODO: code borrowed from YanelServlet.java r40436. see line 902. 1. maybe there is a better way to do so. 2. this code could maybe be refactored into a some xml.util lib. 
        javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
        javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();
        // NOTE: DOCTYPE is being resolved/retrieved (e.g. xhtml schema from w3.org) also
        //       if isValidating is set to false.
        //       Hence, for performance and network reasons we use a local catalog ...
        //       Also see http://www.xml.com/pub/a/2004/03/03/catalogs.html
        //       resp. http://xml.apache.org/commons/components/resolver/
        // TODO: What about a resolver factory?
        parser.setEntityResolver(new CatalogResolver());
        parser.parse(is);
        return true;
    } catch (org.xml.sax.SAXException e) {
        addError("Document is not wellformed: " + e.getMessage() + " ");
        return false;
    } catch (Exception e) {
        addError(e.getMessage());
        return false;
    }
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static Document parseFile(File file) {
    try {/*from ww w. ja va 2 s .c  o m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder loader = factory.newDocumentBuilder();
        return loader.parse(file);
    } catch (SAXException ex) {
        throw new IllegalStateException("Error parsing XML document " + ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new IllegalStateException("Error parsing XML document " + ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        throw new IllegalStateException("Error parsing XML document " + ex.getMessage(), ex);
    }
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static Document parse(InputStream inputStream) throws IOException {
    try {/*from  w  w  w  .  j a v a 2 s .  c o m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setFeature("http://xml.org/sax/features/namespaces", true);
        // voodoo to turn off reading of DTDs during parsing. This is needed e.g. to pre-parse schemas
        factory.setValidating(false);
        factory.setFeature("http://xml.org/sax/features/validation", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        DocumentBuilder loader = factory.newDocumentBuilder();
        return loader.parse(inputStream);
    } catch (SAXException ex) {
        throw new IllegalStateException("Error parsing XML document " + ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        throw new IllegalStateException("Error parsing XML document " + ex.getMessage(), ex);
    }
}

From source file:com.qcadoo.plugin.internal.descriptorparser.DefaultPluginDescriptorParser.java

private InternalPlugin parse(final InputStream inputStream, final boolean ignoreModules, final String fileName)
        throws IOException {
    try {//from  w  w w  . ja v a 2 s .  co  m
        Document document = documentBuilder.parse(inputStream);

        Node root = document.getDocumentElement();

        Builder pluginBuilder = parsePluginNode(root, ignoreModules);

        InternalPlugin plugin = pluginBuilder.withFileName(fileName).build();

        LOG.info("Parse complete");

        return plugin;
    } catch (SAXException e) {
        throw new PluginException(e.getMessage(), e);
    }
}

From source file:com.bordercloud.sparql.Endpoint.java

private HashMap<String, HashMap> getResult() {
    //parse the message
    _handler = new ParserSPARQLResultHandler();

    try {/*from  w  ww  .jav  a2 s .c  o  m*/
        _parser.parse(new InputSource(new StringReader(_response)), _handler);
    } catch (SAXException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }

    if (_handler != null) {
        return ((ParserSPARQLResultHandler) _handler).getResult();//new HashMap<String, HashMap>();
    } else {
        return null;
    }
}

From source file:net.pandoragames.far.ui.FARConfigurationFactory.java

/**
 * Restores the saved mime types from the file system, or loads the default list.
 * @throws IOException /*  w  w w  . j  av  a2  s.  c om*/
 */
private void loadMimeTypes() {
    MimeConfParser parser = new MimeConfParser();
    // load default settings first
    InputStream in = null;
    try {
        in = this.getClass().getClassLoader().getResourceAsStream("META-INF/" + mimeTypesList);
        parser.parse(in);
        for (MimeType mime : MimeType.MimeRegistry.listAll()) {
            mime.setPredefined(true);
        }
    } catch (IOException iox) {
        logger.error("IOException loading default mime types: " + iox.getMessage());
    } catch (SAXException sax) {
        logger.error("SAXException loading default mime types: " + sax.getMessage(), sax);
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException x) {
                /* nix */}
    }
    // now override with use settings
    File storedList = new File(getConfigDir(), mimeTypesList);
    if (storedList.isFile()) {
        InputStream input = null;
        try {
            input = new FileInputStream(storedList);
            parser.parse(input);
        } catch (IOException iox) {
            logger.error("IOException loading mime types: " + iox.getMessage());
        } catch (SAXException sax) {
            logger.error("SAXException loading mime types: " + sax.getMessage(), sax);
        } finally {
            if (input != null)
                try {
                    input.close();
                } catch (IOException x) {
                    /* nix */}
        }
    } else {
    }
}

From source file:com.panet.imeta.trans.steps.xsdvalidator.XsdValidator.java

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (XsdValidatorMeta) smi;// ww w  .  j  a v a 2  s. c  o  m
    data = (XsdValidatorData) sdi;

    Object[] row = getRow();

    if (row == null) // no more input to be expected...
    {
        setOutputDone();
        return false;
    }

    if (first) {
        first = false;
        data.outputRowMeta = getInputRowMeta().clone();
        meta.getFields(data.outputRowMeta, getStepname(), null, null, this);

        // Check if XML stream is given
        if (meta.getXMLStream() != null) {
            // Try to get XML Field index
            data.xmlindex = getInputRowMeta().indexOfValue(meta.getXMLStream());
            // Let's check the Field
            if (data.xmlindex < 0) {
                // The field is unreachable !
                logError(Messages.getString("XsdValidator.Log.ErrorFindingField") + "[" + meta.getXMLStream() //$NON-NLS-1$//$NON-NLS-2$
                        + "]");
                throw new KettleStepException(
                        Messages.getString("XsdValidator.Exception.CouldnotFindField", meta.getXMLStream())); //$NON-NLS-1$ //$NON-NLS-2$
            }

            // Let's check that Result Field is given
            if (meta.getResultfieldname() == null) {
                //   Result field is missing !
                logError(Messages.getString("XsdValidator.Log.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
                throw new KettleStepException(
                        Messages.getString("XsdValidator.Exception.ErrorResultFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
            }

            // Is XSD file is provided?
            if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) {
                if (meta.getXSDFilename() == null) {
                    logError(Messages.getString("XsdValidator.Log.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$
                    throw new KettleStepException(
                            Messages.getString("XsdValidator.Exception.ErrorXSDFileMissing")); //$NON-NLS-1$ //$NON-NLS-2$
                } else {
                    // Is XSD file exists ?
                    FileObject xsdfile = null;
                    try {
                        xsdfile = KettleVFS.getFileObject(environmentSubstitute(meta.getXSDFilename()));
                        if (!xsdfile.exists()) {
                            logError(Messages.getString("XsdValidator.Log.Error.XSDFileNotExists"));
                            throw new KettleStepException(
                                    Messages.getString("XsdValidator.Exception.XSDFileNotExists"));
                        }

                    } catch (Exception e) {
                        logError(Messages.getString("XsdValidator.Log.Error.GettingXSDFile"));
                        throw new KettleStepException(
                                Messages.getString("XsdValidator.Exception.GettingXSDFile"));
                    } finally {
                        try {
                            if (xsdfile != null)
                                xsdfile.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }

            // Is XSD field is provided?
            if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) {
                if (meta.getXSDDefinedField() == null) {
                    logError(Messages.getString("XsdValidator.Log.Error.XSDFieldMissing"));
                    throw new KettleStepException(Messages.getString("XsdValidator.Exception.XSDFieldMissing"));
                } else {
                    // Let's check if the XSD field exist
                    // Try to get XML Field index
                    data.xsdindex = getInputRowMeta().indexOfValue(meta.getXSDDefinedField());

                    if (data.xsdindex < 0) {
                        // The field is unreachable !
                        logError(Messages.getString("XsdValidator.Log.ErrorFindingXSDField", //$NON-NLS-1$
                                meta.getXSDDefinedField())); //$NON-NLS-2$
                        throw new KettleStepException(Messages.getString(
                                "XsdValidator.Exception.ErrorFindingXSDField", meta.getXSDDefinedField())); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                }
            }

        } else {
            // XML stream field is missing !
            logError(Messages.getString("XsdValidator.Log.Error.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
            throw new KettleStepException(Messages.getString("XsdValidator.Exception.XmlStreamFieldMissing")); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }

    boolean sendToErrorRow = false;
    String errorMessage = null;

    try {

        // Get the XML field value
        String XMLFieldvalue = getInputRowMeta().getString(row, data.xmlindex);

        boolean isvalid = false;

        // XSD filename
        String xsdfilename = null;

        if (meta.getXSDSource().equals(meta.SPECIFY_FILENAME)) {
            xsdfilename = environmentSubstitute(meta.getXSDFilename());
        } else if (meta.getXSDSource().equals(meta.SPECIFY_FIELDNAME)) {
            // Get the XSD field value
            xsdfilename = getInputRowMeta().getString(row, data.xsdindex);
        }

        // Get XSD filename
        FileObject xsdfile = null;
        String validationmsg = null;
        try {

            SchemaFactory factoryXSDValidator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            xsdfile = KettleVFS.getFileObject(xsdfilename);
            File XSDFile = new File(KettleVFS.getFilename(xsdfile));

            //   Get XML stream      
            Source sourceXML = new StreamSource(new StringReader(XMLFieldvalue));

            if (meta.getXMLSourceFile()) {

                // We deal with XML file
                // Get XML File
                File xmlfileValidator = new File(XMLFieldvalue);
                if (!xmlfileValidator.exists()) {
                    logError(Messages.getString("XsdValidator.Log.Error.XMLfileMissing", XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$
                    throw new KettleStepException(
                            Messages.getString("XsdValidator.Exception.XMLfileMissing", XMLFieldvalue)); //$NON-NLS-1$ //$NON-NLS-2$
                }
                sourceXML = new StreamSource(xmlfileValidator);
            }

            // Create XSD schema
            Schema SchematXSD = factoryXSDValidator.newSchema(XSDFile);

            if (meta.getXSDSource().equals(meta.NO_NEED)) {
                // ---Some documents specify the schema they expect to be validated against, 
                // ---typically using xsi:noNamespaceSchemaLocation and/or xsi:schemaLocation attributes
                //---Schema SchematXSD = factoryXSDValidator.newSchema();
                SchematXSD = factoryXSDValidator.newSchema();
            }

            // Create XSDValidator
            Validator XSDValidator = SchematXSD.newValidator();
            // Validate XML / XSD      
            XSDValidator.validate(sourceXML);

            isvalid = true;

        } catch (SAXException ex) {
            validationmsg = ex.getMessage();
            logError("SAX Exception : " + ex);
        } catch (IOException ex) {
            validationmsg = ex.getMessage();
            logError("SAX Exception : " + ex);
        } finally {
            try {
                if (xsdfile != null)
                    xsdfile.close();

            } catch (IOException e) {
            }
        }

        Object[] outputRowData = null;
        Object[] outputRowData2 = null;

        if (meta.getOutputStringField()) {
            // Output type=String
            if (isvalid)
                outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(),
                        environmentSubstitute(meta.getIfXmlValid()));
            else
                outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(),
                        environmentSubstitute(meta.getIfXmlInvalid()));
        } else {
            outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), isvalid);
        }

        if (meta.useAddValidationMessage())
            outputRowData2 = RowDataUtil.addValueData(outputRowData, getInputRowMeta().size() + 1,
                    validationmsg);
        else
            outputRowData2 = outputRowData;

        if (log.isRowLevel())
            logRowlevel(
                    Messages.getString("XsdValidator.Log.ReadRow") + " " + getInputRowMeta().getString(row));

        //   add new values to the row.
        putRow(data.outputRowMeta, outputRowData2); // copy row to output rowset(s);
    } catch (KettleException e) {
        if (getStepMeta().isDoingErrorHandling()) {
            sendToErrorRow = true;
            errorMessage = e.toString();
        }

        if (sendToErrorRow) {
            // Simply add this row to the error row
            putError(getInputRowMeta(), row, 1, errorMessage, null, "XSD001");
        } else {
            logError(Messages.getString("XsdValidator.ErrorProcesing" + " : " + e.getMessage()));
            throw new KettleStepException(Messages.getString("XsdValidator.ErrorProcesing"), e);
        }
    }

    return true;

}