Example usage for org.xml.sax.helpers XMLReaderFactory createXMLReader

List of usage examples for org.xml.sax.helpers XMLReaderFactory createXMLReader

Introduction

In this page you can find the example usage for org.xml.sax.helpers XMLReaderFactory createXMLReader.

Prototype

public static XMLReader createXMLReader() throws SAXException 

Source Link

Document

Obtains a new instance of a org.xml.sax.XMLReader .

Usage

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

private static long runTest(String testMessage) throws MessageSerializerException, SAXException, IOException {
    Stopwatch stopwatch = new Stopwatch();
    //      Properties properties = new Properties();
    String SchemaUrl = "/ncpdp51.xsd";
    //        properties.put("useStrictParser", "true");
    //        properties.put("http://java.sun.com/xml/jaxp/properties/schemaSource",SchemaUrl);
    stopwatch.start();//from   w w  w.j  a v  a 2  s. com
    NCPDPSerializer serializer = new NCPDPSerializer(null);
    String xmloutput = serializer.toXML(testMessage);
    //System.out.println(xmloutput);
    DocumentSerializer docser = new DocumentSerializer();
    Document doc = docser.fromXML(xmloutput);
    XMLReader xr = XMLReaderFactory.createXMLReader();

    NCPDPXMLHandler handler = new NCPDPXMLHandler("\u001E", "\u001D", "\u001C", "51");

    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);
    xr.setFeature("http://xml.org/sax/features/validation", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    xr.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", SchemaUrl);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp51.xsd");
    xr.parse(new InputSource(new StringReader(xmloutput)));
    stopwatch.stop();

    //System.out.println(docser.serialize(doc)); //handler.getOutput());
    //System.out.println(handler.getOutput());
    //System.out.println(xmloutput);
    if (handler.getOutput().toString().replace('\n', '\r').trim()
            .equals(testMessage.replaceAll("\\r\\n", "\r").trim())) {
        System.out.println("Test Successful!");
    } else {
        String original = testMessage.replaceAll("\\r\\n", "\r").trim();
        String newm = handler.getOutput().toString().replace('\n', '\r').trim();
        for (int i = 0; i < original.length(); i++) {
            if (original.charAt(i) == newm.charAt(i)) {
                System.out.print(newm.charAt(i));
            } else {
                System.out.println("");
                System.out.print("Saw: ");
                System.out.println(newm.charAt(i));
                System.out.print("Expected: ");
                System.out.print(original.charAt(i));
                break;
            }
        }
        System.out.println("Test Failed!");
    }
    return stopwatch.toValue();
}

From source file:net.sf.jmimemagic.MagicParser.java

/**
 * parse the provided xml and create our MagicMatcher object list
 *
 * @throws MagicParseException DOCUMENT ME!
 *///from   w  w w.  j a v a  2s .  c  om
public synchronized void initialize(URL magicXmlUrl) throws MagicParseException {
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean validation = DEFAULT_VALIDATION;
    boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;

    if (!initialized) {
        // use default parser
        try {
            parser = XMLReaderFactory.createXMLReader();
        } catch (Exception e) {
            try {
                log.debug("falling back to default parser: " + DEFAULT_PARSER_NAME);
                parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
            } catch (Exception ee) {
                throw new MagicParseException("unable to instantiate parser");
            }
        }

        // set parser features
        try {
            parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
        } catch (SAXException e) {
            log.debug("initialize(): warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")");
        }

        try {
            parser.setFeature(VALIDATION_FEATURE_ID, validation);
        } catch (SAXException e) {
            log.debug("initialize(): warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")");
        }

        try {
            parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
        } catch (SAXNotRecognizedException e) {
            // ignore
        } catch (SAXNotSupportedException e) {
            log.debug("initialize(): warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID
                    + ")");
        }

        try {
            parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            // ignore
        } catch (SAXNotSupportedException e) {
            log.debug("initialize(): warning: Parser does not support feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }

        // set handlers
        parser.setErrorHandler(this);
        parser.setContentHandler(this);

        // set resolver for DTD
        parser.setEntityResolver(new MagicDtdResolver());

        // parse file
        try {

            parser.parse(magicXmlUrl.toString());
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            e.printStackTrace();
            throw new MagicParseException("parse error occurred - " + e.getMessage());
        }

        initialized = true;
    }
}

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;//from   w ww.j a  va  2s . c  om

    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);

    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:ar.com.qbe.siniestros.model.utils.MimeMagic.MagicParser.java

/**
 * parse the xml file and create our MagicMatcher object list
 *
 * @throws MagicParseException DOCUMENT ME!
 *///ww  w . j a v  a2  s  .  c om
public synchronized void initialize() throws MagicParseException {
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean validation = DEFAULT_VALIDATION;
    boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;

    if (!initialized) {
        // use default parser
        try {
            parser = XMLReaderFactory.createXMLReader();
        } catch (Exception e) {
            try {
                log.debug("falling back to default parser: " + DEFAULT_PARSER_NAME);
                parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
            } catch (Exception ee) {
                throw new MagicParseException("unable to instantiate parser");
            }
        }

        // set parser features
        try {
            parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
        } catch (SAXException e) {
            log.debug("initialize(): warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")");
        }

        try {
            parser.setFeature(VALIDATION_FEATURE_ID, validation);
        } catch (SAXException e) {
            log.debug("initialize(): warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")");
        }

        try {
            parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
        } catch (SAXNotRecognizedException e) {
            // ignore
        } catch (SAXNotSupportedException e) {
            log.debug("initialize(): warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID
                    + ")");
        }

        try {
            parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            // ignore
        } catch (SAXNotSupportedException e) {
            log.debug("initialize(): warning: Parser does not support feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }

        // set handlers
        parser.setErrorHandler(this);
        parser.setContentHandler(this);

        // parse file
        try {
            // get the magic file URL
            String magicURL = MagicParser.class.getResource(magicFile).toString();

            if (magicURL == null) {
                log.error("initialize(): couldn't load '" + magicURL + "'");
                throw new MagicParseException("couldn't load '" + magicURL + "'");
            }

            parser.parse(magicURL);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            e.printStackTrace();
            throw new MagicParseException("parse error occurred - " + e.getMessage());
        }

        initialized = true;
    }
}

From source file:com.mirth.connect.model.converters.tests.NCPDPTest.java

private static long runTest(String testMessage) throws SerializerException, SAXException, IOException {
    Stopwatch stopwatch = new Stopwatch();
    Properties properties = new Properties();
    String SchemaUrl = "/ncpdp51.xsd";
    properties.put("useStrictParser", "true");
    properties.put("http://java.sun.com/xml/jaxp/properties/schemaSource", SchemaUrl);
    stopwatch.start();// www.  j a v  a 2  s.  c  o m
    NCPDPSerializer serializer = new NCPDPSerializer(properties);
    String xmloutput = serializer.toXML(testMessage);
    //System.out.println(xmloutput);
    DocumentSerializer docser = new DocumentSerializer();
    Document doc = docser.fromXML(xmloutput);
    XMLReader xr = XMLReaderFactory.createXMLReader();

    NCPDPXMLHandler handler = new NCPDPXMLHandler("\u001E", "\u001D", "\u001C", "51");

    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);
    xr.setFeature("http://xml.org/sax/features/validation", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema", true);
    xr.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    xr.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", SchemaUrl);
    xr.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp51.xsd");
    xr.parse(new InputSource(new StringReader(xmloutput)));
    stopwatch.stop();

    //System.out.println(docser.toXML(doc)); //handler.getOutput());
    //System.out.println(handler.getOutput());
    //System.out.println(xmloutput);
    if (handler.getOutput().toString().replace('\n', '\r').trim()
            .equals(testMessage.replaceAll("\\r\\n", "\r").trim())) {
        System.out.println("Test Successful!");
    } else {
        String original = testMessage.replaceAll("\\r\\n", "\r").trim();
        String newm = handler.getOutput().toString().replace('\n', '\r').trim();
        for (int i = 0; i < original.length(); i++) {
            if (original.charAt(i) == newm.charAt(i)) {
                System.out.print(newm.charAt(i));
            } else {
                System.out.println("");
                System.out.print("Saw: ");
                System.out.println(newm.charAt(i));
                System.out.print("Expected: ");
                System.out.print(original.charAt(i));
                break;
            }
        }
        System.out.println("Test Failed!");
    }
    return stopwatch.toValue();
}

From source file:in.gov.uidai.core.aua.client.BfdClient.java

private BfdRes parseBfdResponseXML(String xmlToParse) throws JAXBException {

    //Create an XMLReader to use with our filter 
    try {//from w ww. j  a v  a 2 s  .  c  om
        //Prepare JAXB objects 
        JAXBContext jc = JAXBContext.newInstance(BfdRes.class);
        Unmarshaller u = jc.createUnmarshaller();

        XMLReader reader;
        reader = XMLReaderFactory.createXMLReader();

        //Create the filter (to add namespace) and set the xmlReader as its parent. 
        NamespaceFilter inFilter = new NamespaceFilter("http://www.uidai.gov.in/auth/uid-bfd-response/1.0",
                true);
        inFilter.setParent(reader);

        //Prepare the input, in this case a java.io.File (output) 
        InputSource is = new InputSource(new StringReader(xmlToParse));

        //Create a SAXSource specifying the filter 
        SAXSource source = new SAXSource(inFilter, is);

        //Do unmarshalling 
        BfdRes res = u.unmarshal(source, BfdRes.class).getValue();
        return res;
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

From source file:in.gov.uidai.auth.aua.httpclient.BfdClient.java

private BfdRes parseBfdResponseXML(String xmlToParse) throws JAXBException {

    //Create an XMLReader to use with our filter 
    try {//from   w  ww  .  j ava  2 s  . c  om
        //Prepare JAXB objects 
        JAXBContext jc = JAXBContext.newInstance(BfdRes.class);
        Unmarshaller u = jc.createUnmarshaller();

        XMLReader reader;
        reader = XMLReaderFactory.createXMLReader();

        //Create the filter (to add namespace) and set the xmlReader as its parent. 
        NamespaceFilter inFilter = new NamespaceFilter(
                "http://www.uidai.gov.in/authentication/uid-bfd-response/1.0", true);
        inFilter.setParent(reader);

        //Prepare the input, in this case a java.io.File (output) 
        InputSource is = new InputSource(new StringReader(xmlToParse));

        //Create a SAXSource specifying the filter 
        SAXSource source = new SAXSource(inFilter, is);

        //Do unmarshalling 
        BfdRes res = u.unmarshal(source, BfdRes.class).getValue();
        return res;
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

From source file:org.openmrs.module.sdmxhddataexport.web.controller.report.ReportDataElementController.java

public String transform(String str) throws Exception {
    try {/* w w  w.j av a  2s .c o m*/
        //String XMLFileName = "src\\cdcatalog.xml";
        //String OutputFileName = "src\\myResult.html";
        //  String StyleFileName = "/media/xml-to-string.xsl";
        InputStream inpXsl = OpenmrsClassLoader.getInstance().getResourceAsStream("xml-to-string.xsl");

        XMLReader reader = XMLReaderFactory.createXMLReader();
        InputStream inp = new ByteArrayInputStream(str.getBytes());
        Source source = new SAXSource(reader, new InputSource(inp));
        //Source source2 = new SAXSource(reader, new InputSource(StyleFileName));
        //ContentHandler theHandler = new MyHandler();
        StringWriter outWriter = new StringWriter();
        StreamResult result = new StreamResult(outWriter);
        //Result result = new StreamResult(OutputFileName);
        //          InputStream stinp=new ByteArrayInputStream(styleText.getBytes());         
        Source style = new StreamSource(inpXsl);

        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer trans = transFactory.newTransformer(style);

        trans.transform(source, result);
        String s = outWriter.getBuffer().toString();
        System.out.println(s);
        return s;
    } catch (SAXException e) {
        System.out.println(e.getMessage());
        return e.getMessage();
    }
}

From source file:com.webcohesion.ofx4j.io.BaseOFXReader.java

/**
 * Parse an OFX version 2 stream from the first OFX element (defined by the {@link #getFirstElementStart() first element characters}).
 *
 * @param reader The reader.//ww w.  j  a  v a2s. c  o  m
 */
protected void parseV2FromFirstElement(Reader reader) throws IOException, OFXParseException {
    try {
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setFeature("http://xml.org/sax/features/namespaces", false);
        xmlReader.setContentHandler(new OFXV2ContentHandler(getContentHandler()));
        xmlReader.parse(new InputSource(reader));
    } catch (SAXException e) {
        if (e.getCause() instanceof OFXParseException) {
            throw (OFXParseException) e.getCause();
        }

        throw new OFXParseException(e);
    }
}

From source file:com.servicelibre.jxsl.scenario.XslScenario.java

protected void init() {
    try {//from w  ww  . ja v a2 s  . com
        reader = XMLReaderFactory.createXMLReader();
        reader.setEntityResolver(new CatalogResolver());
    } catch (SAXException e) {
        logger.error("Error while creating XMLReader", e);
    }

    try {
        factory.setNamespaceAware(true);
        this.xmlBuilder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        logger.error("Error while creating XML DocumentBuilder.", e);
    }

}