Example usage for org.xml.sax SAXException printStackTrace

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

Introduction

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

Prototype

public void printStackTrace(PrintStream s) 

Source Link

Document

Prints this throwable and its backtrace to the specified print stream.

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser parser = null;/*from  w  w  w .  ja v  a 2 s. co  m*/
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    try {
        spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
        parser = spf.newSAXParser();
        System.out.println("Parser object is: " + parser);
    } catch (SAXException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    } catch (ParserConfigurationException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }

    MySAXHandler handler = new MySAXHandler();
    parser.parse(new InputSource(new StringReader(xmlString)), handler);
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser parser = null;//from   w  w  w.j a va 2  s .c om
    spf.setNamespaceAware(true);
    try {
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        spf.setSchema(sf.newSchema(new SAXSource(new InputSource(new StringReader(schemaString)))));

        parser = spf.newSAXParser();
    } catch (SAXException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    } catch (ParserConfigurationException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
    MySAXHandler handler = new MySAXHandler();
    System.out.println(schemaString);
    parser.parse(new InputSource(new StringReader(xmlString)), handler);
}

From source file:Main.java

public void process() {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);/*  w w w  . j  a  v  a  2s  .c o m*/
    spf.setValidating(true);
    System.out.println("Parser will " + (spf.isNamespaceAware() ? "" : "not ") + "be namespace aware");
    System.out.println("Parser will " + (spf.isValidating() ? "" : "not ") + "validate XML");
    try {
        parser = spf.newSAXParser();
        System.out.println("Parser object is: " + parser);
    } catch (SAXException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    } catch (ParserConfigurationException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
    try {
        parser.parse(new InputSource(new StringReader(getXMLData())), this);
    } catch (IOException e) {
        e.printStackTrace(System.err);
    } catch (SAXException e) {
        e.printStackTrace(System.err);
    }
}

From source file:TrySAX.java

private void process(File file) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);//from ww w  .  jav a  2  s  .co  m
    spf.setValidating(true);
    System.out.println("Parser will " + (spf.isNamespaceAware() ? "" : "not ") + "be namespace aware");
    System.out.println("Parser will " + (spf.isValidating() ? "" : "not ") + "validate XML");
    try {
        parser = spf.newSAXParser();
        System.out.println("Parser object is: " + parser);
    } catch (SAXException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    } catch (ParserConfigurationException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
    System.out.println("\nStarting parsing of " + file + "\n");
    try {
        parser.parse(file, this);
    } catch (IOException e) {
        e.printStackTrace(System.err);
    } catch (SAXException e) {
        e.printStackTrace(System.err);
    }
}

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 av  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:gate.corpora.FastInfosetDocumentFormat.java

/**
 * Unpack markup from any XML format. The XML elements are translated to
 * annotations on the Original markups annotation set.
 * /*from  w  w  w . j  a v a  2 s . c o m*/
 * @param doc
 *          the document to process
 * @throws DocumentFormatException
 */
private void unpackGeneralXmlMarkup(Document doc, RepositioningInfo repInfo, RepositioningInfo ampCodingInfo,
        StatusListener statusListener) throws DocumentFormatException {
    boolean docHasContentButNoValidURL = hasContentButNoValidUrl(doc);

    XmlDocumentHandler xmlDocHandler = null;
    try {

        // Create a new Xml document handler
        xmlDocHandler = new XmlDocumentHandler(doc, this.markupElementsMap, this.element2StringMap);

        // Register a status listener with it
        xmlDocHandler.addStatusListener(statusListener);

        // set repositioning object
        xmlDocHandler.setRepositioningInfo(repInfo);

        // set the object with ampersand coding positions
        xmlDocHandler.setAmpCodingInfo(ampCodingInfo);

        // create the parser
        SAXDocumentParser newxmlParser = new SAXDocumentParser();

        // Set up the factory to create the appropriate type of parser
        // Fast Infoset doesn't support validating which is good as we would want
        // it off any way, but we do want it to be namesapace aware
        newxmlParser.setFeature("http://xml.org/sax/features/namespaces", true);
        newxmlParser.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
        newxmlParser.setContentHandler(xmlDocHandler);
        newxmlParser.setErrorHandler(xmlDocHandler);
        newxmlParser.setDTDHandler(xmlDocHandler);
        newxmlParser.setEntityResolver(xmlDocHandler);

        // Parse the XML Document with the appropriate encoding
        Reader docReader = null;
        try {
            InputSource is;
            if (docHasContentButNoValidURL) {
                // no URL, so parse from string
                is = new InputSource(new StringReader(doc.getContent().toString()));
            } else if (doc instanceof TextualDocument) {
                // textual document - load with user specified encoding
                String docEncoding = ((TextualDocument) doc).getEncoding();
                // don't strip BOM on XML.
                docReader = new InputStreamReader(doc.getSourceUrl().openStream(), docEncoding);
                is = new InputSource(docReader);
                // must set system ID to allow relative URLs (e.g. to a DTD) to
                // work
                is.setSystemId(doc.getSourceUrl().toString());
            } else {
                // let the parser decide the encoding
                is = new InputSource(doc.getSourceUrl().toString());
            }
            newxmlParser.parse(is);
        } finally {
            // make sure the open streams are closed
            if (docReader != null)
                docReader.close();
        }

        ((DocumentImpl) doc).setNextAnnotationId(xmlDocHandler.getCustomObjectsId());
    } catch (SAXException e) {
        doc.getFeatures().put("parsingError", Boolean.TRUE);

        Boolean bThrow = (Boolean) doc.getFeatures().get(GateConstants.THROWEX_FORMAT_PROPERTY_NAME);

        if (bThrow != null && bThrow.booleanValue()) {
            throw new DocumentFormatException(e);
        } else {
            Out.println("Warning: Document remains unparsed. \n" + "\n  Stack Dump: ");
            e.printStackTrace(Out.getPrintWriter());
        }

    } catch (IOException e) {
        throw new DocumentFormatException("I/O exception for " + doc.getSourceUrl(), e);
    } finally {
        if (xmlDocHandler != null)
            xmlDocHandler.removeStatusListener(statusListener);
    }
}

From source file:cl.utfsm.cdbChecker.CDBChecker.java

/**
 * This method validates the XSD files.//from ww  w .ja  va2 s.  c o  m
 * 
 * @param xsdFilenames names with absolute path of the XSD file to validate.
 */
protected void validateSchemas(Vector<String> xsdFilenames) {

    System.out.println("*** Will verify XSD files in: " + this.XSDPath);

    // We share the resolver, to benefit more from its cache.
    CDBSchemasResolver resolver = new CDBSchemasResolver(this, schemaFolder + File.pathSeparator + XSDPath);
    ErrorHandler errorHandler = new CDBErrorHandler(this);

    for (String xsdFilename : xsdFilenames) {
        final File xsdFile = new File(xsdFilename);
        if (xsdFile.length() != 0) {
            if (verbose) {
                System.out.print("    " + xsdFilename);
            }
            try {
                validateFileEncoding(xsdFilename);
                SP.reset();
                resolver.setResolveOnlyHttp(true); // not sure why, but this is the legacy behavior
                SP.setEntityResolver(resolver);
                SP.setFeature("http://xml.org/sax/features/validation", true);
                SP.setFeature("http://apache.org/xml/features/validation/schema", true);
                SP.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
                SP.setFeature("http://xml.org/sax/features/namespaces", true);
                SP.setErrorHandler(errorHandler);
                SP.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
                        "http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema.xsd");

                FileInputStream fis = new FileInputStream(xsdFile);
                InputSource inputSource = new InputSource(fis);
                inputSource.setSystemId("file:///" + xsdFile.getAbsolutePath());
                SP.parse(inputSource);
                fis.close();
                try {
                    // Now we know that the schema is technically valid (well, it does not seem to check xsd imports...)
                    // Still we have to check special requirements for CharacteristicComponent XSDs.
                    // This second check probably includes the first check's functionality, so that the
                    // first check could be removed once we have verified XSOM's xsd error reporting
                    // and hooked up the shared error handler in BaciSchemaChecker.
                    resolver.setResolveOnlyHttp(false); // here we want to resolve all schemas
                    BaciSchemaChecker baciChecker = new BaciSchemaChecker(xsdFile, resolver, errorHandler,
                            logger);
                    List<BaciPropertyLocator> badProps = baciChecker.findBaciPropsOutsideCharacteristicComp();
                    if (!badProps.isEmpty()) {
                        // Reduce the available error output to show only xsd element(s), not the individual baci properties
                        Set<String> badXsdElementNames = new HashSet<String>();
                        for (BaciPropertyLocator badProp : badProps) {
                            badXsdElementNames.add(badProp.elementName);
                        }
                        System.out.println(xsdFilename
                                + ": illegal use of baci properties in xsd elements that are not derived from baci:CharacteristicComponent. "
                                + "Offending element(s): " + StringUtils.join(badXsdElementNames, ' '));
                        errorFlag = true;
                        globalErrorFlag = true;
                    }
                } catch (SAXException ex) {
                    // ignore SAXException coming from BaciSchemaChecker, because we don't want to report errors
                    // twice when the xsd file is really messed up. 
                    // There are cases where xerces reports a normal error but XSOM reports a fatal error and throws this exception.
                }
                if (verbose && !errorFlag) {
                    System.out.println("[OK]");
                }
            } catch (SAXException e) {
                System.out.println("Caught a SAXException in validateSchemas: ");
                e.printStackTrace(System.out);
            } catch (IOException e) {
                System.out.println("[IOException] Probably " + xsdFilename + " doesn't exists.");
            }
        } else {
            System.out.print(xsdFilename + ": [Warning] file is empty.\n");
        }
    }
    resolver.setResolveOnlyHttp(true); // back to legacy mode again... yuck, our resolver still sticks to the "SP" field and will be used elsewhere!
}

From source file:hudson.remoting.Launcher.java

/**
 * Parses the connection arguments from JNLP file given in the URL.
 *///from  w  w w.j a  va2 s. co m
public List<String> parseJnlpArguments()
        throws ParserConfigurationException, SAXException, IOException, InterruptedException {
    while (true) {
        try {
            URLConnection con = slaveJnlpURL.openConnection();
            if (con instanceof HttpURLConnection && slaveJnlpCredentials != null) {
                HttpURLConnection http = (HttpURLConnection) con;
                String userPassword = slaveJnlpCredentials;
                String encoding = new String(Base64.encodeBase64(userPassword.getBytes()));
                http.setRequestProperty("Authorization", "Basic " + encoding);
            }
            con.connect();

            if (con instanceof HttpURLConnection) {
                HttpURLConnection http = (HttpURLConnection) con;
                if (http.getResponseCode() >= 400)
                    // got the error code. report that (such as 401)
                    throw new IOException("Failed to load " + slaveJnlpURL + ": " + http.getResponseCode() + " "
                            + http.getResponseMessage());
            }

            Document dom;

            // check if this URL points to a .jnlp file
            String contentType = con.getHeaderField("Content-Type");
            if (contentType == null || !contentType.startsWith("application/x-java-jnlp-file")) {
                // load DOM anyway, but if it fails to parse, that's probably because this is not an XML file to begin with.
                try {
                    dom = loadDom(slaveJnlpURL, con);
                } catch (SAXException e) {
                    throw new IOException(
                            slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType);
                } catch (IOException e) {
                    throw new IOException(
                            slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType);
                }
            } else {
                dom = loadDom(slaveJnlpURL, con);
            }

            // exec into the JNLP launcher, to fetch the connection parameter through JNLP.
            NodeList argElements = dom.getElementsByTagName("argument");
            List<String> jnlpArgs = new ArrayList<String>();
            for (int i = 0; i < argElements.getLength(); i++)
                jnlpArgs.add(argElements.item(i).getTextContent());
            if (slaveJnlpCredentials != null) {
                jnlpArgs.add("-credentials");
                jnlpArgs.add(slaveJnlpCredentials);
            }
            // force a headless mode
            jnlpArgs.add("-headless");
            return jnlpArgs;
        } catch (SSLHandshakeException e) {
            if (e.getMessage().contains("PKIX path building failed")) {
                // invalid SSL certificate. One reason this happens is when the certificate is self-signed
                IOException x = new IOException(
                        "Failed to validate a server certificate. If you are using a self-signed certificate, you can use the -noCertificateCheck option to bypass this check.");
                x.initCause(e);
                throw x;
            } else
                throw e;
        } catch (IOException e) {
            System.err.println("Failing to obtain " + slaveJnlpURL);
            e.printStackTrace(System.err);
            System.err.println("Waiting 10 seconds before retry");
            Thread.sleep(10 * 1000);
            // retry
        }
    }
}

From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.FeatureCatalogue.java

private void PrintClass(ClassInfo ci, boolean onlyProperties, Operation op, PackageInfo pix) {

    if (!ExportClass(ci, onlyProperties, op))
        return;/*from  w w  w. ja  va2s  . c o  m*/

    try {

        if (onlyProperties) {

            String ciid = "_C" + ci.id();
            ciid = options.internalize(ciid);

            writer.startElement("FeatureType", "id", ciid, op);

            PrintDescriptors(ci, true, op);

            // NOTE: the Differ currently does not check abstractness
            if (ci.isAbstract()) {
                writer.dataElement("isAbstract", "1");
            }

            for (String t : ci.supertypes()) {

                ClassInfo cix = lookupClassById(t);

                if (cix != null) {

                    String name = cix.name();

                    String cixid = "_C" + cix.id();
                    cixid = options.internalize(cixid);

                    // check for insertion
                    boolean inserted = false;
                    Operation opForGeneralization = op;
                    if (hasDiff(ci, ElementType.SUPERTYPE, Operation.INSERT, cix)) {
                        name = "[[ins]]" + name + "[[/ins]]";
                        inserted = true;
                        opForGeneralization = Operation.INSERT;
                    }

                    if (inserted || !Inherit || cix.category() != Options.MIXIN) {

                        name = options.internalize(name);

                        writer.dataElement("subtypeOf", cix.name(), "idref", cixid, opForGeneralization);
                    }
                }
            }
            // Diff: check for potential deletions of supertypes
            if (hasDiff(ci, ElementType.SUPERTYPE, Operation.DELETE)) {

                for (DiffElement diff : getDiffs(ci, ElementType.SUPERTYPE, Operation.DELETE)) {

                    String nameOfDeletedSupertype = "[[del]]" + diff.subElement.name() + "[[/del]]";

                    String supertypeId = diff.subElement.id();

                    /*
                     * Don't simply use the id from the diff's subElement as
                     * reference. Rather, try to look up the class in the
                     * input model.
                     */
                    ClassInfo supertype = lookupClassById(supertypeId);

                    String cixid = "_C" + supertype.id();
                    cixid = options.internalize(cixid);

                    writer.dataElement("subtypeOf", nameOfDeletedSupertype, "idref", cixid, Operation.DELETE);
                }
            }

            PrintProperties(ci, true, op);
            /*
             * TODO PrintOperations true;
             */

            writer.emptyElement("package", "idref", "_P" + pix.id());

            switch (ci.category()) {
            case Options.FEATURE:
            case Options.OKSTRAFID:

                String text = featureTerm + " Type";
                text = options.internalize(text);

                writer.dataElement("type", text, op);

                break;
            case Options.OBJECT:
                writer.dataElement("type", "Object Type", op);
                break;
            case Options.OKSTRAKEY:
            case Options.DATATYPE:
                writer.dataElement("type", "Data Type", op);
                break;
            case Options.UNION:
                writer.dataElement("type", "Union Data Type", op);
                break;
            }

            String s;
            for (Constraint ocl : ci.constraints()) {

                writer.startElement("constraint");

                writer.dataElement("name", ocl.name());

                s = ocl.text();
                String description = null;
                String expression = null;
                if (s != null && s.contains("/*") && s.contains("*/")) {
                    String[] sa = s.split("\\*/");
                    description = sa[0].replaceFirst("/\\*", "").trim();
                    expression = sa[1].trim();
                } else {
                    expression = s;
                }

                if (description != null && description.length() > 0) {
                    writer.dataElement("description", description);
                }

                if (expression != null && expression.length() > 0) {
                    writer.dataElement("expression", expression);
                }

                writer.endElement("constraint");
            }

            s = ci.taggedValue("alwaysVoid");
            if (s != null && s.length() > 0) {
                writer.startElement("constraint");
                writer.dataElement("description", "Properties that are always void: " + s);
                writer.endElement("constraint");
            }
            s = ci.taggedValue("neverVoid");
            if (s != null && s.length() > 0) {
                writer.startElement("constraint");
                writer.dataElement("description", "Properties that are never void: " + s);
                writer.endElement("constraint");
            }
            s = ci.taggedValue("appliesTo");
            if (s != null && s.length() > 0) {
                writer.startElement("constraint");
                writer.dataElement("description", "Applies to the following network elements: " + s);
                writer.endElement("constraint");
            }

            writer.startElement("taggedValues");

            s = ci.taggedValue("name");
            if (s != null && s.trim().length() > 0) {
                writer.dataElement("name", PrepareToPrint(s), op);
            }
            writer.endElement("taggedValues");

            if (ci.getDiagrams() != null) {
                appendImageInfo(ci.getDiagrams());
            }

            writer.endElement("FeatureType");
        }

        PrintProperties(ci, false, op);
        /*
         * TODO PrintOperations false;
         */

    } catch (SAXException e) {

        String m = e.getMessage();
        if (m != null) {
            result.addError(m);
        }
        e.printStackTrace(System.err);
    }
}

From source file:org.sipfoundry.sipxbridge.ConfigurationParser.java

/**
 * Create an account manager structure and initialize it with the information pointed to by
 * the given URL./* w w  w . j  a  v  a  2s.  com*/
 *
 * @param url -- the rul from where to fetch the config file.
 *
 * @return
 */

public AccountManagerImpl createAccountManager(String url) {
    // Create a Digester instance
    Digester digester = new Digester();

    digester.setSchema("file:schema/sipxbridge.xsd");

    addRules(digester);

    // Process the input file.
    try {
        InputSource inputSource = new InputSource(url);
        digester.parse(inputSource);
        AccountManagerImpl accountManagerImpl = (AccountManagerImpl) digester.getRoot();
        BridgeConfiguration bridgeConfiguration = accountManagerImpl.getBridgeConfiguration();
        if (bridgeConfiguration.getStunServerAddress() == null) {
            for (ItspAccountInfo itspAccountInfo : accountManagerImpl.getItspAccounts()) {
                if (itspAccountInfo.isGlobalAddressingUsed() && bridgeConfiguration.getGlobalAddress() == null)
                    throw new SAXException(
                            "Need stun server address or public address to be specified in sipxbridge configuration.");

            }
        }
        return (AccountManagerImpl) digester.getRoot();
    } catch (java.io.IOException ioe) {
        // Note that we do not have a debug file here so we need to print to stderr.
        ioe.printStackTrace(System.err);
        throw new SipXbridgeException("Initialization exception", ioe);
    } catch (org.xml.sax.SAXException se) {
        se.printStackTrace(System.err);
        throw new SipXbridgeException("Initialization exception", se);
    }

}