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(Exception e) 

Source Link

Document

Create a new SAXException wrapping an existing exception.

Usage

From source file:com.sshtools.common.hosts.AbstractHostKeyVerification.java

/**
 *
 *
 * @param uri/*from  ww  w  .  j a va  2  s. co m*/
 * @param localName
 * @param qname
 *
 * @throws SAXException
 */
public void endElement(String uri, String localName, String qname) throws SAXException {
    if (currentElement == null) {
        throw new SAXException("Unexpected end element found!");
    }

    if (currentElement.equals("HostAuthorizations")) {
        currentElement = null;

        return;
    }

    if (currentElement.equals("AllowHost")) {
        currentElement = "HostAuthorizations";

        return;
    }

    if (currentElement.equals("DenyHost")) {
        currentElement = "HostAuthorizations";

        return;
    }
}

From source file:net.sf.joost.emitter.XmlEmitter.java

/**
 * SAX2-Callback - Outputs the element-tag.
 *//* www  .java2  s. co m*/
public void endElement(String uri, String lName, String qName) throws SAXException {
    // output end tag only if processLastElement didn't output
    // something (here: empty element tag)
    if (processLastElement(true) == false) {
        try {
            writer.write("</");
            writer.write(qName);
            writer.write(">");
        } catch (IOException ex) {
            if (log != null)
                log.error(ex);
            throw new SAXException(ex);
        }
    }
}

From source file:com.atlassian.jira.action.admin.OfbizImportHandler.java

@Override
public void startElement(final String uri, final String localName, final String qName,
        final Attributes attributes) throws SAXException {
    //if we have an exception - refuse to process any more nodes, and throw the exception
    if (importError.get() != null) {
        throw new SAXException(new Exception(importError.get()));
    }//from ww w .j av a2 s  .c  om

    if (hasRootElement) {
        if (inEntity != null) {
            if (!EntityImportExportExclusions.ENTITIES_EXCLUDED_FROM_IMPORT_EXPORT.contains(inEntity)) {
                if (value == null) {
                    throw new SAXException(
                            "Somehow we have got inside an Entity without creating a GenericValue for it.");
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Read opening subelement " + qName + " of entity " + value.getEntityName());
                    }
                    // It will contain the contents of the tag when it is closed.
                    resetTextBuffer();
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Read opening " + qName + " element");
            }

            final Attributes decodedAttributes = new EscapedAttributes(attributes);

            // Then we must be looking at a GenericValue element,
            // Construct a new one and set its attributes
            inEntity = qName;
            if (createEntities) {
                value = parseValue(qName, decodedAttributes);
            } else {
                // JDEV-22241: continue parsing, don't throw - need to parse all document for validation
                value = parseValueFailsafe(qName, decodedAttributes);
            }

            /**
             * We look ahead here for build numbers and licenses strings and we are making he assumption that they are
             * only in attribute values for a given entity.  This will break in the future if they end up
             * being in CDATA sections (eg they have new lines in the data values)
             */
            recordElementsInfo(qName, decodedAttributes);
            // JRADEV-2376 Need to store default path if using custom paths , the path doesn't exist
            // and the user says use defaultpaths

            if (isPropertyString(qName)) {
                setDefaultPaths(decodedAttributes);
            }
            if (isPropertyNumber(qName)) {
                setUseDefaultPaths(decodedAttributes);
            }
        }
    } else if (ENTITY_ENGINE_XML.equals(qName)) {
        log.debug("Read opening ROOT element");
        // Set that the document has started correctly
        hasRootElement = true;
        // Create an initial value batch for this import
        valueBatch = new ArrayList<GenericValue>();
        String date = attributes.getValue("date");
        this.exportDate = Option.option(date);
    } else {
        throw new SAXException(
                "The XML document does not contain the <entity-engine-xml> root element or it was closed too early.");
    }
}

From source file:net.sf.joost.plugins.traxfilter.THResolver.java

/**
 * @see net.sf.joost.TransformerHandlerResolver#resolve(java.lang.String,
 *      java.lang.String, java.lang.String, javax.xml.transform.URIResolver,
 *      javax.xml.transform.ErrorListener, java.util.Hashtable)
 *///  w  w  w  .  ja va2s .c  o  m
public TransformerHandler resolve(String method, String href, String base, URIResolver uriResolver,
        ErrorListener errorListener, Hashtable params) throws SAXException {
    if (!available(method))
        throw new SAXException("Not supported filter-method:" + method);

    if (DEBUG)
        log.debug("resolve(url): href=" + href + ", base=" + base);

    if (href == null)
        throw new SAXException("method-src must be url() or buffer()");

    setFilterAttributes(params);

    TransformerHandler th = null;

    // reuse th if available
    th = getReusableHrefTH(method, href);

    // new transformer if non available
    if (th == null) {
        // prepare the source
        Source source = null;
        try {
            // use custom URIResolver if present
            if (uriResolver != null) {
                source = uriResolver.resolve(href, base);
            }
            if (source == null) {
                if (HREF_IS_SYSTEM_ID.booleanValue()) {
                    // systemId
                    if (DEBUG)
                        log.debug("resolve(url): new source out of systemId='" + href + "'");
                    source = new StreamSource(href);
                } else {
                    // file
                    String url = new URL(new URL(base), href).toExternalForm();
                    if (DEBUG)
                        log.debug("resolve(url): new source out of file='" + url + "'");
                    source = new StreamSource(url);
                }
            }
        } catch (MalformedURLException muex) {
            throw new SAXException(muex);
        } catch (TransformerException tex) {
            throw new SAXException(tex);
        }

        th = newTHOutOfTrAX(method, source, params, errorListener, uriResolver);

        // cache the instance if required
        cacheHrefTH(method, href, th);
    }

    prepareTh(th, params);
    return th;
}

From source file:geogebra.io.MyI2GHandler.java

final public void endDocument() throws SAXException {
    debug("endDocument", "");
    if (mode == MODE_INVALID)
        throw new SAXException("invalid file: <construction> not found");
    else if (mode != MODE_CONSTRUCTION)
        throw new SAXException("closing tag </construction> not found");
}

From source file:net.sf.joost.emitter.StreamEmitter.java

/**
 * Encode a character from a character array, respect surrogate pairs
 * @param chars the character array//from www.  j  a va2  s  .c  o  m
 * @param index the current index
 * @param sb the buffer to append the encoded character
 * @return the new index (if a pair has been consumed)
 * @throws SAXException when there's no low surrogate
 */
protected int encodeCharacters(char[] chars, int index, StringBuffer sb) throws SAXException {
    // check surrogate pairs
    if (chars[index] >= '\uD800' && chars[index] <= '\uDBFF') {
        // found a high surrogate
        index++;
        if (index < chars.length && chars[index] >= '\uDC00' && chars[index] <= '\uDFFF') {
            // found a low surrogate
            // output the calculated code value
            sb.append("&#").append((chars[index - 1] - 0xD800) * 0x400 + (chars[index] - 0xDC00) + 0x10000)
                    .append(';');
        } else
            throw new SAXException("Surrogate pair encoding error - " + "missing low surrogate after code "
                    + (int) chars[index - 1]);
    }
    // else: single character
    else if (charsetEncoder.canEncode(chars[index])) {
        sb.append(chars[index]);
    } else {
        sb.append("&#").append((int) chars[index]).append(';');
    }
    return index;
}

From source file:net.sf.joost.emitter.XmlEmitter.java

/**
 * SAX2-Callback - Constructs characters.
 *//* w w  w.ja v  a2 s . c  o m*/
public void characters(char[] ch, int start, int length) throws SAXException {
    processLastElement(false);

    try {
        if (insideCDATA || disabledOutputEscaping) {
            // check that the characters can be represented in the current
            // encoding (escaping not possible within CDATA)
            for (int i = 0; i < length; i++)
                if (!charsetEncoder.canEncode(ch[start + i]))
                    throw new SAXException("Cannot output character with code " + (int) ch[start + i]
                            + " in the encoding '" + encoding + "' within a CDATA section");
            writer.write(ch, start, length);
        } else {
            StringBuffer out = new StringBuffer(length);
            // output escaping
            for (int i = 0; i < length; i++)
                switch (ch[start + i]) {
                case '&':
                    out.append("&amp;");
                    break;
                case '<':
                    out.append("&lt;");
                    break;
                case '>':
                    out.append("&gt;");
                    break;
                default:
                    i = encodeCharacters(ch, start + i, out) - start;
                }
            writer.write(out.toString());
        }
        if (DEBUG)
            log.debug("'" + new String(ch, start, length) + "'");
    } catch (IOException ex) {
        if (log != null)
            log.error(ex);
        throw new SAXException(ex);
    }
}

From source file:com.meterware.httpunit.HttpUnitUtils.java

/**
 * creates a parser using JAXP API./*from w w w. j a  va2 s  . c om*/
 */
public static DocumentBuilder newParser() throws SAXException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new HttpUnitUtils.ClasspathEntityResolver());
        return builder;
    } catch (ParserConfigurationException ex) {
        // redirect the new exception for code compatibility
        throw new SAXException(ex);
    }
}

From source file:net.sf.joost.stx.TransformerHandlerResolverImpl.java

/**
 * This is essentially same method as common resolve
 * but it assumes that params are already "parsed" via
 * {@link #createExternalParameters(Hashtable)}
 *//*from   ww w  .j  ava 2s  .c om*/
public TransformerHandler resolve(String method, XMLReader reader, URIResolver uriResolver,
        ErrorListener errorListener, Hashtable params) throws SAXException {
    Hashtable externalParams = createExternalParameters(params);
    if (customResolver != null) {
        TransformerHandler handler = customResolver.resolve(method, reader, uriResolver, errorListener,
                externalParams);
        if (handler != null)
            return handler;
    }

    if (notInitializedYet)
        init();

    TransformerHandlerResolver impl = (TransformerHandlerResolver) plugins.get(method);
    if (impl == null)
        throw new SAXException("Undefined filter implementation for method '" + method + "'");
    return impl.resolve(method, reader, uriResolver, errorListener, externalParams);
}

From source file:com.granule.json.utils.XML.java

/**
 * Method to do the transform from an XML input stream to a JSON stream.
 * Neither input nor output streams are closed.  Closure is left up to the caller.
 *
 * @param XMLStream The XML stream to convert to JSON
 * @param JSONStream The stream to write out JSON to.  The contents written to this stream are always in UTF-8 format.
 * @param verbose Flag to denote whether or not to render the JSON text in verbose (indented easy to read), or compact (not so easy to read, but smaller), format.
 *
 * @throws SAXException Thrown if a parse error occurs.
 * @throws IOException Thrown if an IO error occurs.
 *///from   w  ww . ja  va 2s .com
public static void toJson(InputStream XMLStream, OutputStream JSONStream, boolean verbose)
        throws SAXException, IOException {
    if (logger.isLoggable(Level.FINER)) {
        logger.entering(className, "toJson(InputStream, OutputStream)");
    }

    if (XMLStream == null) {
        throw new NullPointerException("XMLStream cannot be null");
    } else if (JSONStream == null) {
        throw new NullPointerException("JSONStream cannot be null");
    } else {

        if (logger.isLoggable(Level.FINEST)) {
            logger.logp(Level.FINEST, className, "transform",
                    "Fetching a SAX parser for use with JSONSAXHandler");
        }

        try {
            /**
             * Get a parser.
             */
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            SAXParser sParser = factory.newSAXParser();
            XMLReader parser = sParser.getXMLReader();
            JSONSAXHandler jsonHandler = new JSONSAXHandler(JSONStream, verbose);
            parser.setContentHandler(jsonHandler);
            parser.setErrorHandler(jsonHandler);
            InputSource source = new InputSource(new BufferedInputStream(XMLStream));

            if (logger.isLoggable(Level.FINEST)) {
                logger.logp(Level.FINEST, className, "transform", "Parsing the XML content to JSON");
            }

            /** 
             * Parse it.
             */
            source.setEncoding("UTF-8");
            parser.parse(source);
            jsonHandler.flushBuffer();
        } catch (javax.xml.parsers.ParserConfigurationException pce) {
            throw new SAXException("Could not get a parser: " + pce.toString());
        }
    }

    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toJson(InputStream, OutputStream)");
    }
}