Example usage for javax.xml.parsers SAXParser parse

List of usage examples for javax.xml.parsers SAXParser parse

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParser parse.

Prototype

public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException 

Source Link

Document

Parse the content given org.xml.sax.InputSource as XML using the specified org.xml.sax.helpers.DefaultHandler .

Usage

From source file:oscar.util.Doc2PDF.java

public static void PrintPDFFromHTMLString(HttpServletResponse response, String docText) {

    // step 1: creation of a document-object
    Document document = new Document(PageSize.A4, 36, 36, 36, 36);
    //Document document = new Document(PageSize.A4.rotate());

    try {/*  w  ww .j a  v a  2 s  .  c o  m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);

        // step 3: we create a parser and set the document handler
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

        // step 4: we parse the document
        // use input stream        
        parser.parse(new ByteArrayInputStream(docText.getBytes()), new SAXmyHtmlHandler(document));

        document.close();

        // String yourString = new String(theBytesOfYourString, "UTF-8");
        // byte[] theBytesOfYourString = yourString.getBytes("UTF-8");

        byte[] binArray = baos.toByteArray();

        PrintPDFFromBytes(response, binArray);

    }

    catch (Exception e) {
        logger.error("Unexpected error", e);
    }

}

From source file:pt.iflow.api.licensing.FileBasedLicenseService.java

private void parseXMLSnapshot(byte[] xml) throws SAXException, IOException, ParserConfigurationException {
    DefaultHandler handler = new DefaultHandler() {
        LicenseEntry currOrg;//ww w  . j  ava 2 s.c  om

        public void startDocument() throws SAXException {
            licenseEntries.clear();
        }

        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if ("org".equals(qName)) {
                currOrg = new LicenseEntry();
                currOrg.available = Long.parseLong(attributes.getValue("available"));
                currOrg.consumed = Long.parseLong(attributes.getValue("consumed"));
                licenseEntries.put(attributes.getValue("id"), currOrg);
            } else if ("flow".equals(qName)) {
                currOrg.flowBased.put(new Integer(attributes.getValue("id")),
                        new Long(attributes.getValue("consumed")));
            }
        }

    };

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    SAXParser parser = factory.newSAXParser();
    parser.parse(new ByteArrayInputStream(xml), handler);

}

From source file:reconf.client.setup.XmlConfigurationParser.java

public static XmlConfigurationParser from(String xmlContent) {
    try {// w  ww.  java  2s.c o  m
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XmlConfigurationParser reader = new XmlConfigurationParser();
        parser.parse(IOUtils.toInputStream(xmlContent), reader);

        if (!reader.begin) {
            LoggerHolder.getLog().error("error parsing the configuration file. check if the file is valid");
        }

        return reader;

    } catch (Exception e) {
        throw new ReConfInitializationError(
                "error parsing the configuration file with content" + LineSeparator.value() + xmlContent, e);
    }
}

From source file:se.rebootit.android.tagbiljetter.DataParser.java

/**
 * Return the list of loaded companies//w w w .  j a  v  a  2s. co  m
 */
@SuppressWarnings("unchecked")
public ArrayList<TransportCompany> getCompanies() {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    DefaultHandler handler = new TransportCompanyHandler();
    AssetManager assetManager = context.getAssets();
    try {
        InputStream inputStream = assetManager.open("TransportCompanies.xml");
        SAXParser parser = factory.newSAXParser();
        parser.parse(inputStream, handler);
    } catch (Exception e) {
        e.printStackTrace();
    }

    this.lstCompanies.clear();
    this.lstCompanies.addAll((ArrayList) ((TransportCompanyHandler) handler).getCompanies());

    for (TransportCompany transportCompany : this.lstCompanies) {
        mapCompanies.put(transportCompany.getId(), transportCompany);
    }

    Collections.sort(this.lstCompanies, new Comparator<TransportCompany>() {
        public int compare(TransportCompany p1, TransportCompany p2) {
            return p1.getName().compareTo(p2.getName());
        }
    });

    return this.lstCompanies;
}

From source file:test.common.TestBase.java

/**
 * @param xmlData//from   w  w w.  java  2s  .  c o  m
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
private static String getNameSpaceFromXml(final String xmlData)
        throws ParserConfigurationException, SAXException, IOException, UnsupportedEncodingException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    DefaultHandler handler = new DefaultHandler() {
        private String nameSpace = null;
        private boolean first = true;

        public void startElement(String uri, String localName, String qName, Attributes attributes) {
            if (first) {
                if (qName.contains(":")) {
                    String prefix = qName.substring(0, qName.indexOf(":"));
                    String attributeName = "xmlns:" + prefix;
                    nameSpace = attributes.getValue(attributeName);
                } else {
                    nameSpace = attributes.getValue("xmlns");
                }
                first = false;
            }
        }

        public String toString() {
            return nameSpace;
        }
    };
    parser.parse(new ByteArrayInputStream(xmlData.getBytes("UTF-8")), handler);
    String nameSpace = handler.toString();
    return nameSpace;
}

From source file:test.common.TestBase.java

/**
 * @throws IOException/*from   www.j av  a  2 s . c o  m*/
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private static void initializeSchemas() throws IOException, SAXException, ParserConfigurationException {
    File[] schemaFiles = ResourceUtil.getFilenamesInDirectory("xsd/", TestBase.class.getClassLoader());
    PrintWriter pwriter = new PrintWriter("target/schemas.txt");
    logger.debug("Number of schema files: " + schemaFiles.length);
    pwriter.println("Number of schema files: " + schemaFiles.length);

    schemas = new HashMap<String, Schema>();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    //        sf.setResourceResolver(new ImportResolver());
    for (File file : schemaFiles) {
        logger.debug("Schema file: " + file.getCanonicalPath());
        pwriter.println("Schema file: " + file.getCanonicalPath());

        try {

            //TODO remove this hack when xsd files are cleared
            if (file.getCanonicalPath().contains("rest")) {
                logger.debug("Skipping schema file: " + file.getCanonicalPath());
                continue;
            }
            if (file.getCanonicalPath().endsWith("srw-types.xsd") && !file.getCanonicalPath().contains("0.8")) {
                logger.debug("Skipping schema file: " + file.getCanonicalPath());
                continue;
            }
            // end TODO                

            Schema schema = sf.newSchema(file);

            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            DefaultHandler handler = new DefaultHandler() {
                private String nameSpace = null;
                private boolean found = false;

                public void startElement(String uri, String localName, String qName, Attributes attributes) {
                    if (!found) {
                        String tagName = null;
                        int ix = qName.indexOf(":");
                        if (ix >= 0) {
                            tagName = qName.substring(ix + 1);
                        } else {
                            tagName = qName;
                        }
                        if ("schema".equals(tagName)) {
                            nameSpace = attributes.getValue("targetNamespace");
                            found = true;
                        }
                    }
                }

                public String toString() {
                    return nameSpace;
                }
            };
            parser.parse(file, handler);
            if (handler.toString() != null) {
                Schema s = schemas.get(handler.toString());
                if (s != null) {
                    logger.debug("overwriting key '" + handler.toString() + "'");
                }
                schemas.put(handler.toString(), schema);
                logger.debug("Successfully added: " + file.getCanonicalPath() + " key: '" + handler.toString()
                        + "' value: " + schema.toString() + " " + schema.newValidator());
            } else {
                logger.warn("Error reading xml schema: " + file);
            }
        } catch (Exception e) {
            logger.warn("Invalid xml schema " + file + " , cause " + e.getLocalizedMessage());
            logger.debug("Stacktrace: ", e);
        }
    }
    logger.info("XSD Schemas found: " + schemas);
    pwriter.close();
}

From source file:tml.conceptmap.ConceptMap.java

public static ConceptMap getFromXML(String filename) throws Exception {
    File f = new File(filename);
    if (!f.exists())
        throw new Exception("Concept Map file doesn't exist");
    logger.debug("Loading Concept Map from file " + f.getName());
    ConceptMap map = new ConceptMap();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {/*  ww w .  jav a  2  s . co m*/
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(f, map.new ConceptMapHandler(map));
    } catch (Throwable e) {
        e.printStackTrace();
        throw new Exception("Error parsing XML for Concept Map file " + f.getName(), e);
    }
    logger.debug("Concept Map loaded from file " + filename);
    map.setName(f.getName());
    if (map.vertexSet().size() == 0)
        logger.warn("Concept Map " + map + " is empty!");
    return map;
}

From source file:tml.conceptmap.TerminologicalConceptMap.java

public static TerminologicalConceptMap getFromXML(String filename) throws Exception {
    File f = new File(filename);
    if (!f.exists())
        throw new Exception("Concept Map file doesn't exist");
    logger.debug("Loading Concept Map from file " + f.getName());
    TerminologicalConceptMap map = new TerminologicalConceptMap();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {/* w w  w.ja  v  a  2  s . c  o m*/
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(f, map.new ConceptMapHandler(map));
    } catch (Throwable e) {
        e.printStackTrace();
        throw new Exception("Error parsing XML for Concept Map file " + f.getName(), e);
    }
    logger.debug("Concept Map loaded from file " + filename);
    map.setName(f.getName());
    if (map.vertexSet().size() == 0)
        logger.warn("Concept Map " + map + " is empty!");
    return map;
}

From source file:uk.ac.ebi.intact.dataexchange.psimi.xml.exchange.PsiExchangeImpl.java

/**
 * Gets the release dates from a PSI-MI XML InputStream
 * @param is//  w w w  . java 2s .  co  m
 * @return
 */
public List<DateTime> getReleaseDates(InputStream is) throws IOException {
    final List<DateTime> releaseDates = new ArrayList<DateTime>();

    DefaultHandler handler = new DefaultHandler() {

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if (localName.equals("source")) {
                final String releaseDateStr = attributes.getValue("releaseDate");
                DateTime releaseDate = toDateTime(releaseDateStr);
                releaseDates.add(releaseDate);
            }
        }
    };

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);

    try {
        SAXParser parser = factory.newSAXParser();
        parser.parse(new InputSource(is), handler);
    } catch (Exception e) {
        throw new IntactException(e);
    }

    return releaseDates;
}

From source file:uk.co.grahamcox.xml.Parser.java

/**
 * Parse the given input stream/*  www . ja  va 2 s.c o m*/
 * @param input the input stream
 * @param handler the handler to use
 * @throws IOException if an error occurs reading the stream
 * @throws XmlParseException if an error occurs parsing the stream
 */
public void parse(final InputStream input, final Handler handler) throws IOException, XmlParseException {
    try {
        LOG.debug("Parsing input stream: " + input + " into handler: " + handler);
        SAXParser parser = parserFactory.newSAXParser();
        DefaultHandler defaultHandler = new XmlHandler(handler);
        parser.parse(input, defaultHandler);
    } catch (ParserConfigurationException ex) {
        LOG.error("Configuration error creating parser", ex);
        throw new XmlParseException("Configuration error creating parser", ex);
    } catch (SAXException ex) {
        LOG.error("Error creating parser", ex);
        throw new XmlParseException("Error creating parser", ex);
    }

}