Example usage for org.xml.sax XMLReader setFeature

List of usage examples for org.xml.sax XMLReader setFeature

Introduction

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

Prototype

public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException;

Source Link

Document

Set the value of a feature flag.

Usage

From source file:com.mirth.connect.plugins.datatypes.ncpdp.NCPDPSerializer.java

@Override
public String fromXML(String source) throws MessageSerializerException {
    /*// w  w w. j  a  v  a 2s . c om
     * Need to determine the version by looking at the raw message.
     * The transaction header will contain the version ("51" for 5.1 and
     * "D0" for D.0)
     */
    String version = "D0";

    if (source.indexOf("D0") == -1) {
        version = "51";
    } else if (source.indexOf("51") == -1) {
        version = "D0";
    } else if (source.indexOf("51") < source.indexOf("D0")) {
        version = "51";
    }

    try {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        NCPDPXMLHandler handler = new NCPDPXMLHandler(deserializationSegmentDelimiter,
                deserializationGroupDelimiter, deserializationFieldDelimiter, version);
        reader.setContentHandler(handler);

        if (deserializationProperties.isUseStrictValidation()) {
            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.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
            reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                    "ncpdp" + version + ".xsd");
            reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
                    "/ncpdp" + version + ".xsd");
        }

        /*
         * Parse, but first replace all spaces between brackets. This fixes
         * pretty-printed XML we might receive
         */
        reader.parse(new InputSource(new StringReader(prettyPattern.matcher(source).replaceAll("><"))));
        return handler.getOutput().toString();
    } catch (Exception e) {
        throw new MessageSerializerException("Error converting XML to NCPDP message.", e, ErrorMessageBuilder
                .buildErrorMessage(this.getClass().getSimpleName(), "Error converting XML to NCPDP", e));
    }
}

From source file:eionet.gdem.conversion.spreadsheet.DDXMLConverter.java

/**
 * Converts XML file//from  w  w  w  .j  a  va2s. c  om
 * @param xmlSchema XML schema
 * @param outStream OutputStream
 * @throws Exception If an error occurs.
 */
protected void doConversion(String xmlSchema, OutputStream outStream) throws Exception {
    String instanceUrl = DataDictUtil.getInstanceUrl(xmlSchema);

    DD_XMLInstance instance = new DD_XMLInstance(instanceUrl);
    DD_XMLInstanceHandler handler = new DD_XMLInstanceHandler(instance);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    XMLReader reader = parser.getXMLReader();

    factory.setValidating(false);
    factory.setNamespaceAware(true);
    reader.setFeature("http://xml.org/sax/features/validation", false);
    reader.setFeature("http://apache.org/xml/features/validation/schema", false);
    reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    reader.setFeature("http://xml.org/sax/features/namespaces", true);

    reader.setContentHandler(handler);
    reader.parse(instanceUrl);

    if (Utils.isNullStr(instance.getEncoding())) {
        String enc_url = Utils.getEncodingFromStream(instanceUrl);
        if (!Utils.isNullStr(enc_url)) {
            instance.setEncoding(enc_url);
        }
    }
    importSheetSchemas(sourcefile, instance, xmlSchema);
    instance.startWritingXml(outStream);
    sourcefile.writeContentToInstance(instance);
    instance.flushXml();
}

From source file:eionet.gdem.validation.ValidationService.java

/**
/**//from  w w w .jav a  2 s .  co  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:hu.sztaki.lpds.pgportal.services.dspace.LNIclient.java

/**
 * Completes the two-part operation started by startPut(), by
 * collecting status of the PUT operation and converting the
 * WebDAV URI of the newly-created resource back to a Handle,
 * which it returns.//from   w  w w  .  j  av  a 2 s  .  co  m
 * <p>
 * Any failure results in an exception.
 *
 * @return Handle of the newly-created DSpace resource.
 */
public String finishPut() throws InterruptedException, IOException, SAXException, SAXNotRecognizedException,
        ParserConfigurationException {
    if (lastPutThread != null) {
        lastPutThread.join();
        lastPutThread = null;
    }

    Header loc = lastPut.getResponseHeader("Location");
    lastStatus = lastPut.getStatusCode();
    if (lastStatus < 100 || lastStatus >= 400)
        throw new IOException("PUT returned status = " + lastStatus + "; text=" + lastPut.getStatusText());

    lastPut = null;
    if (loc != null) {
        String newURL = loc.getValue();

        // do a quick PROPFIND to get the handle
        PropfindMethod pf = new PropfindMethod(newURL, propfindBody);
        pf.setDoAuthentication(true);
        client.executeMethod(pf);

        int pfStatus = pf.getStatusCode();
        if (pfStatus < 200 || pfStatus >= 300)
            throw new IOException(
                    "finishPut.propfind got status = " + pfStatus + "; text=" + pf.getStatusText());

        // Maybe move all this crap to within Propfind class??
        // so it can get the inputstream directly?
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        PropfindHandler handler = new PropfindHandler();

        // XXX FIXME: should turn off validation here explicitly, but
        //  it seems to be off by default.
        xr.setFeature("http://xml.org/sax/features/namespaces", true);
        xr.setContentHandler(handler);
        xr.setErrorHandler(handler);
        xr.parse(new InputSource(pf.getResponseBodyAsStream()));

        return handler.handle;
    } else
        throw new IOException("PUT response was missing a Location: header.");
}

From source file:org.esco.grouper.parsing.SGSParsingUtil.java

/**
 * Starts the parsing process.// w ww .  j av a 2s .  co  m
 * @throws SAXException If there is an error during the parsing (invalid group defintion for instance).
 * @throws IOException  If there is an IO error.
 */
public void parse() throws IOException, SAXException {

    XMLReader saxReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    saxReader.setFeature("http://xml.org/sax/features/validation", true);
    saxReader.setContentHandler(this);
    saxReader.setErrorHandler(this);
    saxReader.setEntityResolver(this);
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("---------------------------------");
        LOGGER.info("Parsing definition file: ");
        LOGGER.info(definitionsFileURI);
        LOGGER.info("---------------------------------");
    }
    InputStream iStream = getClass().getClassLoader().getResourceAsStream(definitionsFileURI);

    if (iStream == null) {
        LOGGER.fatal("Unable to load (from classpath) file: " + definitionsFileURI + ".");
    }

    //final InputSource is =
    saxReader.parse(new InputSource(iStream));

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("---------------------------------");
        LOGGER.info("Definition file parsed.");
        LOGGER.info("---------------------------------");
    }
}

From source file:SAXTreeValidator.java

/**
 * <p>This handles building the Swing UI tree.</p>
 *
 * @param treeModel Swing component to build upon.
 * @param base tree node to build on./*w w w . jav a  2 s. co m*/
 * @param xmlURI URI to build XML document from.
 * @throws <code>IOException</code> - when reading the XML URI fails.
 * @throws <code>SAXException</code> - when errors in parsing occur.
 */
public void buildTree(DefaultTreeModel treeModel, DefaultMutableTreeNode base, String xmlURI)
        throws IOException, SAXException {

    // Create instances needed for parsing
    XMLReader reader = XMLReaderFactory.createXMLReader(vendorParserClass);
    ContentHandler jTreeContentHandler = new JValidatorContentHandler(treeModel, base);
    ErrorHandler jTreeErrorHandler = new JValidatorErrorHandler();

    // Register content handler
    reader.setContentHandler(jTreeContentHandler);

    // Register error handler
    reader.setErrorHandler(jTreeErrorHandler);

    // Turn on validation
    reader.setFeature("http://xml.org/sax/features/validation", true);
    reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

    // Parse
    InputSource inputSource = new InputSource(xmlURI);
    reader.parse(inputSource);
}

From source file:edu.virginia.speclab.juxta.author.model.JuxtaXMLParser.java

public void parse() throws ReportedException {
    firstPassReadFile();/*from  w w w. j  a  v a 2  s  . com*/
    offsetMap = new OffsetMap(rawXMLText.length());

    // Setup special tag handling to cover behavior for
    // add, del, note and pb tags
    setupCustomTagHandling();

    try {
        if (file.getName().endsWith("xml")) {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            parser = factory.newSAXParser();

            XMLReader xmlReader = parser.getXMLReader();
            xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", this);

            // ignore external DTDs
            xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

            parser.parse(new InputSource(new StringReader(rawXMLText)), this);
            if (getDocumentType() == DocumentType.UNKNOWN) {
                // If we made it here and we don't know what the document type is,
                // it's just an XML document
                setDocumentType(DocumentType.XML);
            }
            // Uncomment these lines for some verbose debugging of the XML parsing
            // and the resulting processed output.
            //                getRootNode().debugPrint();
            //                try {
            //                    printDebuggingInfo();
            //                } catch (ReportedException ex) {
            //Logger.getLogger(JuxtaXMLParser.class.getName()).log(Level.SEVERE, null, ex);
            //                }
        } else {
            processAsPlaintext();
        }
    } catch (ParserConfigurationException ex) {
        throw new ReportedException(ex, "Problem with our parser configuration.");
    } catch (SAXParseException ex) {
        throw new ReportedException(ex, "XML Parsing Error at column " + ex.getColumnNumber() + ", line "
                + ex.getLineNumber() + " :\n" + ex.getLocalizedMessage());
    } catch (SAXException ex) {
        throw new ReportedException(ex, "SAX Exception: " + ex.getLocalizedMessage());
    } catch (IOException ex) {
        throw new ReportedException(ex, ex.getLocalizedMessage());
    }
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

protected XMLReader createTagSoupParser() throws Exception {
    XMLReader reader = new Parser();
    reader.setFeature(Parser.namespacesFeature, false);
    reader.setFeature(Parser.namespacePrefixesFeature, false);
    reader.setProperty(Parser.schemaProperty, new org.ccil.cowan.tagsoup.HTMLSchema() {
        {//from   w ww  . java 2s. c om
            //problem with nested lists that the confluence {toc} macro creates
            elementType("ul", M_LI, M_BLOCK | M_LI, 0);
        }
    });

    return reader;
}