Example usage for org.xml.sax XMLReader setErrorHandler

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

Introduction

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

Prototype

public void setErrorHandler(ErrorHandler handler);

Source Link

Document

Allow an application to register an error event handler.

Usage

From source file:com.typhoon.newsreader.engine.ChannelRefresh.java

public long syncDB(Handler h, long id, String rssurl) throws Exception {
    mHandler = h;//ww w  .j av  a 2  s  .  c  o m
    mID = id;
    mRSSURL = rssurl;

    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();

    xr.setContentHandler(this);
    xr.setErrorHandler(this);

    URL url = new URL(mRSSURL);

    URLConnection c = url.openConnection();
    c.setRequestProperty("User-Agent", "Android/m3-rc37a");
    xr.parse(new InputSource(c.getInputStream()));

    return mID;
}

From source file:be.fedict.eidviewer.lib.file.imports.EidQuickKeyXMLFile.java

public void load(File file) throws CertificateException, FileNotFoundException, SAXException, IOException {
    logger.fine("Loading eID Quick Keys XML File");

    XMLReader reader = null;

    certificateFactory = CertificateFactory.getInstance("X.509");
    FileInputStream fis = new FileInputStream(file);

    reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(this);
    reader.setErrorHandler(this);
    BufferedReader in = new BufferedReader(new InputStreamReader(fis));
    reader.parse(new InputSource(in));

    X509Utilities.setCertificateChainsFromCertificates(eidData, rootCert, citizenCert, authenticationCert,
            signingCert, rrnCert);/*from www. j av  a  2  s.  c o  m*/
}

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

/**
/**/* ww w  . j av  a2  s  .c  o  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:com.determinato.feeddroid.parser.RssParser.java

/**
 * Persists RSS item to the database.//  w w  w .  j a  v  a  2 s .  c om
 * @param id item ID
 * @param folderId ID of containing folder
 * @param rssurl URL of RSS feed
 * @return long containing ID of inserted item
 * @throws Exception
 */
public long syncDb(long id, long folderId, String rssurl) throws Exception {
    mId = id;
    mFolderId = folderId;
    mRssUrl = rssurl;

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

    reader.setContentHandler(this);
    reader.setErrorHandler(this);

    URL url = new URL(mRssUrl);

    URLConnection c = url.openConnection();
    // TODO: Is this a known user agent, or do I need to come up with my own?
    c.setRequestProperty("User-Agent", "Android/m3-rc37a");

    try {
        BufferedReader bufReader = new BufferedReader(new InputStreamReader(c.getInputStream()), 65535);
        reader.parse(new InputSource(bufReader));
    } catch (NullPointerException e) {
        Log.e(TAG, Log.getStackTraceString(e));
        Log.e(TAG, "Failed to load URL" + url.toString());
    }

    return mId;
}

From source file:com.mirth.connect.model.converters.ER7Serializer.java

/**
 * Returns an ER7-encoded HL7 message given an XML-encoded HL7 message.
 * // w ww  . j  a  v  a  2 s. c o m
 * @param source
 *            a XML-encoded HL7 message.
 * @return
 */
public String fromXML(String source) throws SerializerException {
    try {
        if (useStrictParser) {
            return pipeParser.encode(xmlParser.parse(source));
        } else {
            /*
             * The delimiters below need to come from the XML somehow. The
             * ER7 handler should take care of it TODO: Ensure you get these
             * elements from the XML
             */

            String segmentSeparator = "\r";
            String fieldSeparator = getNodeValue(source, "<MSH.1>", "</MSH.1>");

            if (StringUtils.isEmpty(fieldSeparator)) {
                fieldSeparator = "|";
            }

            String componentSeparator = "^";
            String repetitionSeparator = "~";
            String subcomponentSeparator = "&";
            String escapeCharacter = "\\";

            /*
             * Our delimiters usually look like this:
             * <MSH.2>^~\&amp;</MSH.2> We need to decode XML entities
             */
            String separators = getNodeValue(source, "<MSH.2>", "</MSH.2>").replaceAll("&amp;", "&");

            if (separators.length() == 4) {
                // usually ^
                componentSeparator = separators.substring(0, 1);
                // usually ~
                repetitionSeparator = separators.substring(1, 2);
                // usually \
                escapeCharacter = separators.substring(2, 3);
                // usually &
                subcomponentSeparator = separators.substring(3, 4);
            }

            XMLEncodedHL7Handler handler = new XMLEncodedHL7Handler(segmentSeparator, fieldSeparator,
                    componentSeparator, repetitionSeparator, escapeCharacter, subcomponentSeparator, true);
            XMLReader reader = XMLReaderFactory.createXMLReader();
            reader.setContentHandler(handler);
            reader.setErrorHandler(handler);

            /*
             * Parse, but first replace all spaces between brackets. This
             * fixes pretty-printed XML we might receive.
             */
            reader.parse(new InputSource(new StringReader(
                    source.replaceAll("\\s*<([^/][^>]*)>", "<$1>").replaceAll("<(/[^>]*)>\\s*", "<$1>"))));
            return handler.getOutput().toString();
        }
    } catch (Exception e) {
        throw new SerializerException(e);
    }
}

From source file:de.uzk.hki.da.model.RightsSectionURNMetsXmlReader.java

/**
 * Read urn./* ww  w .  j  av  a2  s  .co  m*/
 *
 * @param file the file
 * @return The URN specified in the METS file or null if the METS file doesn't specify an URN
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ParseException the parse exception
 * @author Thomas Kleinke
 */
public String readURN(File file) throws IOException, ParseException {

    FileInputStream fileInputStream = new FileInputStream(file);
    BOMInputStream bomInputStream = new BOMInputStream(fileInputStream);

    XMLReader xmlReader = null;
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        xmlReader = spf.newSAXParser().getXMLReader();
    } catch (Exception e) {
        fileInputStream.close();
        bomInputStream.close();
        throw new IOException("Error creating SAX parser", e);
    }
    xmlReader.setErrorHandler(err);
    NodeFactory nodeFactory = new PremisXmlReaderNodeFactory();
    Builder parser = new Builder(xmlReader, false, nodeFactory);
    logger.trace("Successfully built builder and XML reader");

    try {
        String urn = null;

        Document doc = parser.build(bomInputStream);
        Element root = doc.getRootElement();

        Element dmdSecEl = root.getFirstChildElement("dmdSec", METS_NS);
        if (dmdSecEl == null)
            return null;

        Element mdWrapEl = dmdSecEl.getFirstChildElement("mdWrap", METS_NS);
        if (mdWrapEl == null)
            return null;

        Element xmlDataEl = mdWrapEl.getFirstChildElement("xmlData", METS_NS);
        if (xmlDataEl == null)
            return null;

        Element modsEl = xmlDataEl.getFirstChildElement("mods", MODS_NS);
        if (modsEl == null)
            return null;

        Elements identifierEls = modsEl.getChildElements("identifier", MODS_NS);
        for (int i = 0; i < identifierEls.size(); i++) {
            Element element = identifierEls.get(i);
            Attribute attribute = element.getAttribute("type");
            if (attribute.getValue().toLowerCase().equals("urn"))
                urn = element.getValue();
        }

        if (urn != null && urn.equals(""))
            urn = null;

        return urn;
    } catch (ValidityException ve) {
        throw new IOException(ve);
    } catch (ParsingException pe) {
        throw new IOException(pe);
    } catch (IOException ie) {
        throw new IOException(ie);
    } finally {
        fileInputStream.close();
        bomInputStream.close();
    }
}

From source file:com.thruzero.common.core.infonode.builder.SaxInfoNodeBuilder.java

/** construct complete {@code InfoNodeElement} from dom. */
protected InfoNodeElement doBuildInfoNode(final String xml, final InfoNodeElement targetNode,
        final InfoNodeFilterChain infoNodeFilterChain) throws Exception {
    handlePrimaryKey(targetNode);//from w  ww .  j  a v a  2 s .c o  m
    if (StringUtils.isNotEmpty(xml)) {
        XMLReader parser = XMLReaderFactory.createXMLReader();
        InfoNodeSaxHandler dnHandler = new InfoNodeSaxHandler(targetNode, infoNodeFilterChain); // state for this build is kept in this InfoNode Handler instance

        parser.setContentHandler(dnHandler);
        parser.setErrorHandler(dnHandler);
        parser.setFeature("http://xml.org/sax/features/validation", false);

        InputSource input = new InputSource(new StringReader(xml));
        parser.parse(input);
    }
    handleRootNode(targetNode);

    return targetNode;
}

From source file:be.fedict.eidviewer.lib.file.imports.Version35XMLFile.java

public void load(File file) throws CertificateException, FileNotFoundException, SAXException, IOException,
        ParseException, DataConvertorException {
    logger.fine("Loading Version 35X XML File");

    XMLReader reader = null;

    certificateFactory = CertificateFactory.getInstance("X.509");
    DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
    FileInputStream fis = new FileInputStream(file);

    reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(this);
    reader.setErrorHandler(this);
    BufferedReader in = new BufferedReader(new InputStreamReader(fis));
    reader.parse(new InputSource(in));

    Identity identity = new Identity();
    identity.cardDeliveryMunicipality = discreteValues.get("issuing_municipality");
    identity.cardNumber = discreteValues.get("logical_nr");
    GregorianCalendar validityStartCalendar = new GregorianCalendar();
    validityStartCalendar.setTime(dateFormat.parse(discreteValues.get("date_begin")));
    identity.cardValidityDateBegin = validityStartCalendar;
    GregorianCalendar validityEndCalendar = new GregorianCalendar();
    validityEndCalendar.setTime(dateFormat.parse(discreteValues.get("date_end")));
    identity.cardValidityDateEnd = validityEndCalendar;
    identity.chipNumber = discreteValues.get("chip_nr");
    identity.dateOfBirth = (new DateOfBirthDataConvertor())
            .convert(discreteValues.get("date_of_birth").getBytes());
    identity.documentType = DocumentType.toDocumentType(discreteValues.get("type").getBytes());
    identity.duplicate = discreteValues.get("duplicata");
    identity.gender = discreteValues.get("gender").equals("M") ? Gender.MALE : Gender.FEMALE;

    TextFormatHelper.setFirstNamesFromString(identity, discreteValues.get("name"));
    identity.name = discreteValues.get("surname");

    identity.nationalNumber = discreteValues.get("national_nr");
    identity.nationality = discreteValues.get("nationality");
    identity.nobleCondition = discreteValues.get("nobility");
    identity.placeOfBirth = discreteValues.get("location_of_birth");
    identity.specialStatus = SpecialStatus.toSpecialStatus(discreteValues.get("specialStatus"));
    eidData.setIdentity(identity);//w  ww . j a va  2 s  .c o  m

    Address address = new Address();
    address.municipality = discreteValues.get("municipality");
    address.zip = discreteValues.get("zip");
    address.streetAndNumber = discreteValues.get("street");
    eidData.setAddress(address);

    eidData.setPhoto(pictureData);

    X509Utilities.setCertificateChainsFromCertificates(eidData, rootCert, citizenCert, authenticationCert,
            signingCert, rrnCert);
}

From source file:com.mirth.connect.plugins.datatypes.hl7v2.ER7Serializer.java

/**
 * Returns an ER7-encoded HL7 message given an XML-encoded HL7 message.
 * /*from www. ja v  a  2  s.co  m*/
 * @param source
 *            a XML-encoded HL7 message.
 * @return
 */
@Override
public String fromXML(String source) throws MessageSerializerException {
    try {
        if (deserializationProperties.isUseStrictParser()) {
            return deserializationPipeParser.encode(deserializationXmlParser.parse(source));
        } else {
            /*
             * The delimiters below need to come from the XML somehow. The
             * ER7 handler should take care of it TODO: Ensure you get these
             * elements from the XML
             */

            String fieldSeparator = getNodeValue(source, "<MSH.1>", "</MSH.1>");

            if (StringUtils.isEmpty(fieldSeparator)) {
                fieldSeparator = "|";
            }

            String componentSeparator = "^";
            String repetitionSeparator = "~";
            String subcomponentSeparator = "&";
            String escapeCharacter = "\\";

            /*
             * Our delimiters usually look like this:
             * <MSH.2>^~\&amp;</MSH.2> We need to decode XML entities
             */
            String separators = ampersandPattern.matcher(getNodeValue(source, "<MSH.2>", "</MSH.2>"))
                    .replaceAll("&");

            if (separators.length() == 4) {
                // usually ^
                componentSeparator = separators.substring(0, 1);
                // usually ~
                repetitionSeparator = separators.substring(1, 2);
                // usually \
                escapeCharacter = separators.substring(2, 3);
                // usually &
                subcomponentSeparator = separators.substring(3, 4);
            }

            XMLEncodedHL7Handler handler = new XMLEncodedHL7Handler(deserializationSegmentDelimiter,
                    fieldSeparator, componentSeparator, repetitionSeparator, escapeCharacter,
                    subcomponentSeparator, true);
            XMLReader reader = XMLReaderFactory.createXMLReader();
            reader.setContentHandler(handler);
            reader.setErrorHandler(handler);

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

From source file:org.apache.uima.ruta.resource.TreeWordList.java

public void readXML(InputStream stream, String encoding) throws IOException {
    try {//from w ww.  j a  va 2s  .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();
    }
}