Example usage for org.xml.sax SAXException SAXException

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

Introduction

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

Prototype

public SAXException(String message, Exception e) 

Source Link

Document

Create a new SAXException from an existing exception.

Usage

From source file:DomUtil.java

/**
 * Work method for public save() methods.
 *//*from   w  w w. j  a  v  a  2s .  c  om*/
private static void saveImpl(Document document, StreamResult output, Properties outputProperties)
        throws SAXException {
    try {
        TransformerFactory tFactory = getTransformerFactory();
        Transformer transformer = tFactory.newTransformer();
        if (outputProperties != null) {
            transformer.setOutputProperties(outputProperties);
        }
        DOMSource source = new DOMSource(document);

        transformer.transform(source, output);
    } catch (TransformerException ex) {
        throw new SAXException("Unable to write document to OutputStream.", ex);
    }
}

From source file:fr.lip6.move.coloane.projects.its.io.ModelHandler.java

/**
 * Analyze a type declaration//from  w  w w.  j  a  va2 s . c  o  m
 * @param attributes Les attributs attache  la balise
 * @throws SAXException if the referenced model file is bad.
 */
private void startType(Attributes attributes) throws SAXException {
    TypeList types = (TypeList) stack.peek();

    int id = Integer.parseInt(attributes.getValue("id")); //$NON-NLS-1$

    String name = attributes.getValue("name"); //$NON-NLS-1$
    String formalism = attributes.getValue("formalism"); //$NON-NLS-1$

    String workDir = new File(workFile).getParentFile().toURI().getPath();
    String filePath = workDir + "/" + attributes.getValue("path");

    URI file = new File(filePath).toURI();

    if (file == null || !new File(filePath).canRead()) {
        throw new SAXException("Could not open referenced file " + filePath, null);
    }
    ITypeDeclaration type;
    try {
        type = TypeDeclarationFactory.create(name, file, types);
    } catch (IOException e) {
        throw new SAXException("Could not open referenced file " + filePath, null);
    }
    if (!formalism.equals(type.getTypeType())) {
        String errmsg = "Model formalism type for file " + filePath + " does not match file contents.\n "
                + "Expected type " + formalism + " read type " + type.getTypeType();
        logger.fine(errmsg);

        throw new SAXParseException(errmsg, null);
    }
    // store type in hash
    ids.put(id, type);
    types.addTypeDeclaration(type);
}

From source file:MapTranslater.java

private void emit(String s) throws SAXException {
    try {// w w w.jav a 2  s  .  c  o m
        out.write(s);
        //out.flush();
    } catch (IOException e) {
        throw new SAXException("I/O error", e);
    }
}

From source file:MapTranslater.java

private void nl() throws SAXException {
    String lineEnd = System.getProperty("line.separator");

    try {//from   w ww.  jav a 2  s. c  om
        out.write(lineEnd);
    } catch (IOException e) {
        throw new SAXException("I/O error", e);
    }
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulatorParserHandler.java

private void defineOption(Attributes attributes) throws SAXException {
    String name = null;//from   ww  w  .j  a  v  a 2 s.  c o  m
    String value = null;

    try {
        for (int i = 0; i < attributes.getLength(); i++) {
            String attName = attributes.getQName(i);
            String attValue = expandEnvVars(attributes.getValue(i));

            if (attName.equals(SIM_XML_ATTR_NAME))
                name = attValue;
            else if (attName.equals(SIM_XML_ATTR_VALUE)) {
                value = attValue;
                String[] args = value.split(",");
                TNT4JSimulator.processArgs(this, args);
            } else {
                throw new SAXParseException("Unknown <" + SIM_XML_PROP + "> attribute '" + attName + "'",
                        saxLocator);
            }
        }

        if (StringUtils.isEmpty(name))
            throw new SAXParseException("<" + SIM_XML_VAR + ">: must specify '" + SIM_XML_ATTR_NAME + "'",
                    saxLocator);
        TNT4JSimulator.trace(simCurrTime, "Defining option: '" + name + "=" + value + "'");
    } catch (Exception e) {
        if (e instanceof SAXException)
            throw (SAXException) e;
        throw new SAXException("Failed processing definition for option '" + name + "': " + e, e);
    }
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulatorParserHandler.java

private void defineVar(Attributes attributes) throws SAXException {
    String name = null;//from   w w w .  j a  v  a  2  s.co  m
    String value = null;

    try {
        for (int i = 0; i < attributes.getLength(); i++) {
            String attName = attributes.getQName(i);
            String attValue = expandEnvVars(attributes.getValue(i));

            if (attName.equals(SIM_XML_ATTR_NAME))
                name = attValue;
            else if (attName.equals(SIM_XML_ATTR_VALUE)) {
                value = processVarValue(attValue);
            } else {
                throw new SAXParseException("Unknown <" + SIM_XML_PROP + "> attribute '" + attName + "'",
                        saxLocator);
            }
        }

        if (StringUtils.isEmpty(name))
            throw new SAXParseException("<" + SIM_XML_VAR + ">: must specify '" + SIM_XML_ATTR_NAME + "'",
                    saxLocator);

        if (value.equalsIgnoreCase("=?")) {
            // requires input if not defined
            String oVal = vars.get(name);
            if (oVal == null) {
                value = processVarValue(TNT4JSimulator.readFromConsole("\nDefine variable [" + name + "]:"));
            } else {
                TNT4JSimulator.trace(simCurrTime, "Skipping duplicate variable: '" + name + "=" + value
                        + "', existing.value='" + oVal + "'");
            }
        }

        String eVal = vars.putIfAbsent(name, value);
        if (eVal != null) {
            TNT4JSimulator.trace(simCurrTime,
                    "Skipping duplicate variable: '" + name + "=" + value + "', existing.value='" + eVal + "'");
        }
        TNT4JSimulator.trace(simCurrTime, "Defining variable: '" + name + "=" + value + "'");
    } catch (Exception e) {
        if (e instanceof SAXException)
            throw (SAXException) e;
        throw new SAXException("Failed processing definition for variable '" + name + "': " + e, e);
    }
}

From source file:com.netspective.commons.xdm.XdmHandler.java

public void endElement(String url, String localName, String qName) throws SAXException {
    if (handleDefaultEndElement(url, localName, qName))
        return;/*from ww  w .j  av  a  2  s  . c  om*/

    if (inAttrSetterTextEntry != null) {
        inAttrSetterTextEntry = null;
        return;
    }

    if (!getTemplateDefnStack().isEmpty()) {
        Object templateNode = getTemplateDefnStack().pop();

        // if, after popping the stack, the stack is empty it means we're at the root template definition element
        if (getTemplateDefnStack().isEmpty()) {
            // now that we have finished "recording" the template, see if we're supposed to treat this template
            // as an object/instance also -- if we are, immediately apply the template at the active entry level
            Template template = (Template) templateNode;
            if (template.getTemplateProducer().isUnmarshallContents()) {
                unmarshallingTemplate = true;
                XdmHandlerNodeStackEntry activeEntry = (XdmHandlerNodeStackEntry) getNodeStack().peek();
                template.applySelfAndChildren(template.createApplyContext(this, activeEntry.getElementName(),
                        activeEntry.getAttributes()));
                unmarshallingTemplate = false;
            }
        }
    } else if (!getIgnoreStack().isEmpty())
        getIgnoreStack().pop();
    else {
        try {
            XdmHandlerNodeStackEntry activeEntry = (XdmHandlerNodeStackEntry) getNodeStack().peek();
            if (activeEntry != null) {
                if (activeEntry.getInstance() instanceof XmlDataModelSchema.InputSourceLocatorListener) {
                    InputSourceLocator isl = ((XmlDataModelSchema.InputSourceLocatorListener) activeEntry
                            .getInstance()).getInputSourceLocator();
                    final Locator locator = getParseContext().getLocator();
                    if (isl != null)
                        isl.setEndLine(locator.getLineNumber(), locator.getColumnNumber());
                }

                activeEntry.getSchema().finalizeElementConstruction(((XdmParseContext) getParseContext()),
                        activeEntry.getInstance(), activeEntry.getElementName());
            }
            getNodeStack().pop();
        } catch (DataModelException e) {
            throw new SAXException(e.getMessage() + " " + getStateText(), e);
        }
    }
}

From source file:de.uzk.hki.da.sb.Cli.java

/**
 * Copies the files listed in a SIP list to a single directory
 * /*  w w  w .  j  a  v a 2s. c  o  m*/
 * @param fileListFile The SIP list file
 * @return The path to the directory containing the files
 */
private String copySipListContentToFolder(File sipListFile) {

    CliProgressManager progressManager = new CliProgressManager();

    String tempFolderName = getTempFolderName();

    XMLReader xmlReader = null;
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        xmlReader = spf.newSAXParser().getXMLReader();
    } catch (Exception e) {
        logger.log("ERROR: Failed to create SAX parser", e);
        System.out.println("Fehler beim Einlesen der SIP-Liste: SAX-Parser konnte nicht erstellt werden.");
        return "";
    }
    xmlReader.setErrorHandler(new ErrorHandler() {

        @Override
        public void error(SAXParseException e) throws SAXException {
            throw new SAXException("Beim Einlesen der SIP-Liste ist ein Fehler aufgetreten.", e);
        }

        @Override
        public void fatalError(SAXParseException e) throws SAXException {
            throw new SAXException("Beim Einlesen der SIP-Liste ist ein schwerer Fehler aufgetreten.", e);
        }

        @Override
        public void warning(SAXParseException e) throws SAXException {
            logger.log("WARNING: Warning while parsing siplist", e);
            System.out.println("\nWarnung:\n" + e.getMessage());
        }
    });

    InputStream inputStream;
    try {
        inputStream = new FileInputStream(sipListFile);

        Reader reader = new InputStreamReader(inputStream, "UTF-8");
        Builder parser = new Builder(xmlReader);
        Document doc = parser.build(reader);
        reader.close();

        Element root = doc.getRootElement();
        Elements sipElements = root.getChildElements("sip");

        long files = 0;
        for (int i = 0; i < sipElements.size(); i++) {
            Elements fileElements = sipElements.get(i).getChildElements("file");
            if (fileElements != null)
                files += fileElements.size();
        }
        progressManager.setTotalSize(files);

        for (int i = 0; i < sipElements.size(); i++) {
            Element sipElement = sipElements.get(i);
            String sipName = sipElement.getAttributeValue("name");

            File tempDirectory = new File(tempFolderName + File.separator + sipName);
            if (tempDirectory.exists()) {
                FileUtils.deleteQuietly(new File(tempFolderName));
                System.out.println("\nDie SIP-Liste enthlt mehrere SIPs mit dem Namen " + sipName + ". "
                        + "Bitte vergeben Sie fr jedes SIP einen eigenen Namen.");
                return "";
            }
            tempDirectory.mkdirs();

            Elements fileElements = sipElement.getChildElements("file");

            for (int j = 0; j < fileElements.size(); j++) {
                Element fileElement = fileElements.get(j);
                String filepath = fileElement.getValue();

                File file = new File(filepath);
                if (!file.exists()) {
                    logger.log("ERROR: File " + file.getAbsolutePath() + " is referenced in siplist, "
                            + "but does not exist");
                    System.out.println("\nDie in der SIP-Liste angegebene Datei " + file.getAbsolutePath()
                            + " existiert nicht.");
                    FileUtils.deleteQuietly(new File(tempFolderName));
                    return "";
                }

                try {
                    if (file.isDirectory())
                        FileUtils.copyDirectoryToDirectory(file, tempDirectory);
                    else
                        FileUtils.copyFileToDirectory(file, tempDirectory);
                    progressManager.copyFilesFromListProgress();
                } catch (IOException e) {
                    logger.log("ERROR: Failed to copy file " + file.getAbsolutePath() + " to folder "
                            + tempDirectory.getAbsolutePath(), e);
                    System.out.println("\nDie in der SIP-Liste angegebene Datei " + file.getAbsolutePath()
                            + " konnte nicht kopiert werden.");
                    FileUtils.deleteQuietly(new File(tempFolderName));
                    return "";
                }
            }
        }
    } catch (Exception e) {
        logger.log("ERROR: Failed to read siplist " + sipListFile.getAbsolutePath(), e);
        System.out.println("\nBeim Lesen der SIP-Liste ist ein Fehler aufgetreten. ");
        return "";
    }

    return (new File(tempFolderName).getAbsolutePath());
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulatorParserHandler.java

private void recordSnapshot(Attributes attributes) throws SAXException {
    if ((curActivity == null || !SIM_XML_ACTIVITY.equals(curElement))
            && (curEvent == null || !SIM_XML_EVENT.equals(curElement))) {
        throw new SAXParseException("<" + SIM_XML_SNAPSHOT + ">: must have <" + SIM_XML_ACTIVITY + "> or <"
                + SIM_XML_EVENT + "> as parent element", saxLocator);
    }//w  w  w  .j a v a  2s . c  o m

    String name = null;
    String category = null;
    OpLevel severity = OpLevel.INFO;

    try {
        for (int i = 0; i < attributes.getLength(); i++) {
            String attName = attributes.getQName(i);
            String attValue = expandEnvVars(attributes.getValue(i));

            if (attName.equals(SIM_XML_ATTR_NAME)) {
                name = attValue;
                TNT4JSimulator.trace(simCurrTime, "Recording Snapshot: " + attValue + " ...");
            } else if (attName.equals(SIM_XML_ATTR_CAT)) {
                category = attValue;
            } else if (attName.equals(SIM_XML_ATTR_SEVERITY)) {
                severity = getLevel(attValue);
            } else {
                throw new SAXParseException("Unknown <" + SIM_XML_SNAPSHOT + "> attribute '" + attName + "'",
                        saxLocator);
            }
        }

        if (StringUtils.isEmpty(name))
            throw new SAXParseException("<" + SIM_XML_SNAPSHOT + ">: missing '" + SIM_XML_ATTR_NAME + "'",
                    saxLocator);

        if (StringUtils.isEmpty(category))
            category = null;

        curSnapshot = new PropertySnapshot(category, name, severity, simCurrTime);
        curSnapshot.setTTL(TNT4JSimulator.getTTL());
    } catch (Exception e) {
        if (e instanceof SAXException)
            throw (SAXException) e;
        throw new SAXException("Failed processing definition for snapshot '" + name + "': " + e, e);
    }
}

From source file:fr.gouv.finances.dgfip.xemelios.importers.DefaultImporter.java

protected XmlSplitter splitFile(File fHeader, File fRef, File fFooter, File tmpDir, File fToImport,
        String fileEncoding)/* w w w.  j a  v  a2s.  c o  m*/
        throws FileNotFoundException, UnsupportedEncodingException, SAXException, ParserConfigurationException {
    FileOutputStream fisHeader = new FileOutputStream(fHeader);
    FileOutputStream fisRef = new FileOutputStream(fRef);
    FileOutputStream fisFooter = new FileOutputStream(fFooter);
    XmlSplitter xs = new XmlSplitter(fisHeader, fisRef, fisFooter, tmpDir, dm, fileEncoding);
    xs.setImportLogPrintWriter(importTimingOS);
    xs.setSplittedFileName(fToImport.getName());
    SAXParserFactory sf = FactoryProvider.getSaxParserFactory();
    SAXParser parser = sf.newSAXParser();
    try {
        parser.parse(fToImport, xs);
    } catch (Exception ex) {
        ex.printStackTrace();
        String position = "line " + xs.getLocator().getLineNumber() + ": ";
        throw new SAXException(position + ex.getMessage(), ex);
    } finally {
        if (fisHeader != null) {
            try {
                fisHeader.flush();
                fisHeader.close();
            } catch (Throwable t) {
            }
        }
        if (fisRef != null) {
            try {
                fisRef.flush();
                fisRef.close();
            } catch (Throwable t) {
            }
        }
        if (fisFooter != null) {
            try {
                fisFooter.flush();
                fisFooter.close();
            } catch (Throwable t) {
            }
        }
    }
    return xs;
}