Example usage for org.xml.sax XMLReader setContentHandler

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

Introduction

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

Prototype

public void setContentHandler(ContentHandler handler);

Source Link

Document

Allow an application to register a content event handler.

Usage

From source file:Examples.java

/**
 * Show the Transformer using SAX events in and DOM nodes out.
 *//*from  w w w .  j a v a 2  s  .  c o  m*/
public static void exampleContentHandler2DOM(String sourceID, String xslID) throws TransformerException,
        TransformerConfigurationException, SAXException, IOException, ParserConfigurationException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // Make sure the transformer factory we obtained supports both
    // DOM and SAX.
    if (tfactory.getFeature(SAXSource.FEATURE) && tfactory.getFeature(DOMSource.FEATURE)) {
        // We can now safely cast to a SAXTransformerFactory.
        SAXTransformerFactory sfactory = (SAXTransformerFactory) tfactory;

        // Create an Document node as the root for the output.
        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
        org.w3c.dom.Document outNode = docBuilder.newDocument();

        // Create a ContentHandler that can liston to SAX events 
        // and transform the output to DOM nodes.
        TransformerHandler handler = sfactory.newTransformerHandler(new StreamSource(xslID));
        handler.setResult(new DOMResult(outNode));

        // Create a reader and set it's ContentHandler to be the 
        // transformer.
        XMLReader reader = null;

        // Use JAXP1.1 ( if possible )
        try {
            javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
            reader = jaxpParser.getXMLReader();

        } catch (javax.xml.parsers.ParserConfigurationException ex) {
            throw new org.xml.sax.SAXException(ex);
        } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
            throw new org.xml.sax.SAXException(ex1.toString());
        } catch (NoSuchMethodError ex2) {
        }
        if (reader == null)
            reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        // Send the SAX events from the parser to the transformer,
        // and thus to the DOM tree.
        reader.parse(sourceID);

        // Serialize the node for diagnosis.
        exampleSerializeNode(outNode);
    } else {
        System.out.println(
                "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
    }
}

From source file:com.gc.iotools.fmt.detect.droid.DroidDetectorImpl.java

private XMLReader getXMLReader(final SAXModelBuilder mb) throws Exception {
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);//from   www .j  av  a2 s . c om
    // factory.setValidating(true);
    final SAXParser saxParser = factory.newSAXParser();
    final XMLReader parser = saxParser.getXMLReader();
    // URL url = DroidDetectorImpl.class
    // .getResource("DROID_SignatureFile.xsd");
    // parser.setProperty(
    // "http://java.sun.com/xml/jaxp/properties/schemaSource", url);
    mb.setupNamespace(SIGNATURE_FILE_NS, true);
    parser.setContentHandler(mb);
    return parser;
}

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);/*from  w  ww  .j ava 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:de.ks.idnadrev.expimp.xls.SingleSheetImport.java

@Override
public Void call() throws Exception {
    try {/*  w ww .ja va  2 s . c o m*/
        XMLReader parser = XMLReaderFactory.createXMLReader();
        ImportSheetHandler importSheetHandler = new ImportSheetHandler(clazz, reader.getSharedStringsTable(),
                columnProvider, this::importEntity);
        parser.setContentHandler(importSheetHandler);

        InputSource inputSource = new InputSource(sheetStream);
        parser.parse(inputSource);

    } catch (SAXException | IOException | InvalidFormatException e) {
        result.generalError("Failed to parse sheet " + clazz.getName(), e);
        throw new RuntimeException(e);
    } finally {
        try {
            sheetStream.close();
        } catch (IOException e) {
            result.generalError("Could not close sheet stream " + clazz.getName(), e);
            throw new RuntimeException(e);
        }
        return null;
    }
}

From source file:de.laeubisoft.tools.ant.validation.W3CMarkupValidationTask.java

/**
 * Takes an {@link URL} and tries to find out all linked resources
 * //from w  ww .  j  a  v  a2 s .  c  om
 * @param uriToRecurse
 * @return a set of discovered urls
 */
private Set<URL> recurseInto(final URL uriToRecurse) throws BuildException {
    final Set<URL> urlsFound = new HashSet<URL>();
    XMLReader reader = new Parser();
    reader.setContentHandler(new DefaultHandler() {
        @Override
        public void startElement(String nsuri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if ("a".equalsIgnoreCase(qName)) {
                String value = attributes.getValue("href");
                if (value != null) {
                    try {
                        URL url = new URL(uriToRecurse, value);
                        if (url.getHost().equalsIgnoreCase(uriToRecurse.getHost())
                                && url.getPort() == uriToRecurse.getPort()) {
                            urlsFound.add(url);
                        }
                    } catch (MalformedURLException e) {
                        log("can't parse URL for href = " + value + ", it will be ignored!", Project.MSG_ERR);
                    }
                }
            }
        }
    });
    // Parsen wird gestartet
    try {
        reader.parse(new InputSource(uriToRecurse.openStream()));
        return urlsFound;
    } catch (IOException e) {
        throw new BuildException("error while accessing data at " + uriToRecurse, e);
    } catch (SAXException e) {
        throw new BuildException("error while parsing data at " + uriToRecurse, e);
    }
}

From source file:com.kdmanalytics.toif.adaptor.FindbugsAdaptor.java

/**
 * the xml produced form the tool is parsed by a sax parser and our own content handler.
 * /*  w  w w . ja v  a 2 s. c  o  m*/
 * @throws ToifException
 */
@Override
public ArrayList<Element> parse(java.io.File process, AdaptorOptions options, IFileResolver resolver,
        boolean[] validLines, boolean unknownCWE) throws ToifException {
    // InputStream inputStream = null;
    try {
        InputStream fis = null;
        String theString = "";
        try {
            fis = new FileInputStream(process);
            StringWriter writer = new StringWriter();
            IOUtils.copy(fis, writer, "UTF-8");
            theString = writer.toString();
        } finally {
            if (fis != null)
                fis.close();
        }

        // inputStream = new ByteArrayInputStream(theString.getBytes(StandardCharsets.UTF_8));
        // Thread stderr;
        final FindBugsParser parser = new FindBugsParser(getProperties(), resolver, getAdaptorName(),
                unknownCWE);

        // final ByteArrayOutputStream errStream = new ByteArrayOutputStream();

        /*
         * The two streams could probably be merged with redirectErrorStream(), that was we would only
         * have to deal with one stream.
         */

        // stderr = new Thread(new StreamGobbler(inputStream, errStream));
        //
        // stderr.start();
        // stderr.join();
        //
        // final byte[] data = errStream.toByteArray();
        // final ByteArrayInputStream in = new ByteArrayInputStream(data);

        final XMLReader rdr = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
        rdr.setContentHandler(parser);
        rdr.parse(new InputSource(new StringReader(theString)));

        // return the elements gathered during the parse.
        ArrayList<Element> elements = parser.getElements();

        return elements;

    } catch (final SAXException e) {

        final String msg = getAdaptorName()
                + ": Possibly the file the tool is run against is too large, the wrong kind of file, or not just one file.";
        LOG.error(msg, e);
        e.printStackTrace();
        throw new ToifException(msg);
    } catch (final IOException e) {
        final String msg = getAdaptorName()
                + ": Possibly the file the tool is run against is too large, the wrong kind of file, or not just one file.";

        LOG.error(msg, e);
        throw new ToifException(msg);

    }
    // finally
    // {
    // if(inputStream != null) {
    // try {
    // inputStream.close();
    // }
    // catch (IOException e) {
    // e.printStackTrace();
    // }
    // }
    // }
    // catch (final InterruptedException e) {
    // final String msg = getAdaptorName()
    // + ": Possibly the file the tool is run against is too large, the wrong kind of file, or not
    // just one file.";
    //
    // LOG.error(msg, e);
    // throw new ToifException(msg);
    //
    // }
}

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

/**
 * Returns an ER7-encoded HL7 message given an XML-encoded HL7 message.
 * /*w ww  .  ja v  a 2 s . c om*/
 * @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:com.prowidesoftware.swift.io.parser.MxParser.java

/**
 * Non-namespace aware parse.<br />
 * Parses the complete message content into an {@link MxNode} tree structure.
 * The parser should be initialized with a valid source.
 *
 * @since 7.7/*from  w w w. j a v a  2s  .c  o  m*/
 */
public MxNode parse() {
    Validate.notNull(buffer, "the source must be initialized");
    try {
        final javax.xml.parsers.SAXParserFactory spf = javax.xml.parsers.SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        final javax.xml.parsers.SAXParser saxParser = spf.newSAXParser();
        final MxNodeContentHandler contentHandler = new MxNodeContentHandler();
        final org.xml.sax.XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setContentHandler(contentHandler);
        xmlReader.parse(new org.xml.sax.InputSource(new StringReader(this.buffer)));
        return contentHandler.getRootNode();
    } catch (final Exception e) {
        log.log(Level.SEVERE, "Error parsing: ", e);
    }
    return null;
}

From source file:se.lu.nateko.edca.svc.DescribeFeatureType.java

/**
 * Parses an XML response from a DescribeFeatureType request and stores the layer
 * attribute names and their data types in a GeographyLayer object.
 * @param xmlResponse A reader wrapped around an InputStream containing the XML response from a DescribeFeatureType request.
 *//*from   ww w .j ava  2 s . c  o m*/
protected boolean parseXMLResponse(Reader xmlResponse) {
    //      Log.d(TAG, "parseXMLResponse(Reader) called.");

    try {
        SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Make a SAXParser factory.
        spfactory.setValidating(false); // Tell the factory not to make validating parsers.
        SAXParser saxParser = spfactory.newSAXParser(); // Use the factory to make a SAXParser.
        XMLReader xmlReader = saxParser.getXMLReader(); // Get an XML reader from the parser, which will send event calls to its specified event handler.
        XMLEventHandler xmlEventHandler = new XMLEventHandler();
        xmlReader.setContentHandler(xmlEventHandler); // Set which event handler to use.
        xmlReader.setErrorHandler(xmlEventHandler); // Also set where to send error calls.
        InputSource source = new InputSource(xmlResponse); // Make an InputSource from the XML input to give to the reader.
        xmlReader.parse(source); // Start parsing the XML.
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        return false;
    }
    return true;
}

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 a  va2  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();
    }
}