Example usage for org.xml.sax XMLReader parse

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

Introduction

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

Prototype

public void parse(String systemId) throws IOException, SAXException;

Source Link

Document

Parse an XML document from a system identifier (URI).

Usage

From source file:org.nuxeo.ecm.core.convert.plugins.text.extractors.PPTX2TextConverter.java

protected void readXmlZipContent(ZipInputStream zis, XMLReader reader, StringBuilder sb)
        throws IOException, SAXException {

    Set<PresentationSlide> slides = new TreeSet<PresentationSlide>();

    ZipEntry zipEntry = zis.getNextEntry();
    while (zipEntry != null) {
        String zipEntryName = zipEntry.getName();
        if (zipEntryName.startsWith(PRESENTATION_SLIDE_ZIP_ENTRY_NAME_PREFIX)
                && zipEntryName.length() > PRESENTATION_SLIDE_ZIP_ENTRY_NAME_PREFIX.length()) {
            char slideNumberChar = zipEntryName.charAt(PRESENTATION_SLIDE_ZIP_ENTRY_NAME_PREFIX.length());
            int slideNumber = -1;
            try {
                slideNumber = Integer.parseInt(String.valueOf(slideNumberChar));
            } catch (NumberFormatException nfe) {
                log.warn("Slide number is not an non integer, won't take this slide into account.");
            }//from   w ww.  jav  a  2s  .co  m
            if (slideNumber > -1) {
                OpenXmlContentHandler contentHandler = new OpenXmlContentHandler();
                reader.setContentHandler(contentHandler);
                reader.parse(new InputSource(new ByteArrayInputStream(IOUtils.toByteArray(zis))));
                slides.add(new PresentationSlide(contentHandler.getContent(), slideNumber));
            }
        }
        zipEntry = zis.getNextEntry();
    }
    if (!slides.isEmpty()) {
        Iterator<PresentationSlide> slidesIt = slides.iterator();
        while (slidesIt.hasNext()) {
            PresentationSlide slide = slidesIt.next();
            sb.append(slide.getContent());
            sb.append("\n");
        }
    }
}

From source file:org.nuxeo.ecm.platform.xmlrpc.connector.NuxeoXmlRpcServletServer.java

/**
 * Same as base class method, but with an additionnal parameter
 * that contains component name extracted from request.
 *
 * @param pConfig//from  w w  w .j  ava  2 s.co m
 * @param pStream
 * @param handlerPrefix componentName extracted from request
 * @return
 * @throws XmlRpcException
 */
protected XmlRpcRequest getRequest(final XmlRpcStreamRequestConfig pConfig, InputStream pStream,
        final String handlerPrefix) throws XmlRpcException {

    final XmlRpcRequestParser parser = new XmlRpcRequestParser(pConfig, getTypeFactory());
    final XMLReader xr = SAXParsers.newXMLReader();
    xr.setContentHandler(parser);
    try {
        xr.parse(new InputSource(pStream));
    } catch (SAXException e) {
        Exception ex = e.getException();
        if (ex != null && ex instanceof XmlRpcException) {
            throw (XmlRpcException) ex;
        }
        throw new XmlRpcException("Failed to parse XML-RPC request: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new XmlRpcException("Failed to read XML-RPC request: " + e.getMessage(), e);
    }
    final List params = parser.getParams();
    return new XmlRpcRequest() {
        public XmlRpcRequestConfig getConfig() {
            return pConfig;
        }

        public String getMethodName() {
            String mName = parser.getMethodName();
            if (handlerPrefix == null || "".equals(handlerPrefix)) {
                return mName;
            } else {
                return handlerPrefix + '.' + mName;
            }
        }

        public int getParameterCount() {
            return params == null ? 0 : params.size();
        }

        public Object getParameter(int pIndex) {
            return params.get(pIndex);
        }
    };
}

From source file:org.nuxeo.wss.fprpc.FPRPCRequest.java

protected void parseCAMLRequest() throws MalformedFPRPCRequest {
    XMLReader reader;
    try {/*from   w w w  . j  av  a  2 s  . c  om*/
        reader = CAMLHandler.getXMLReader();
        reader.parse(new InputSource(httpRequest.getInputStream()));
        calls = ((CAMLHandler) reader.getContentHandler()).getParsedCalls();
    } catch (Exception e) {
        throw new MalformedFPRPCRequest("Unable to parse CAML Request");
    }
}

From source file:org.openbravo.test.webservice.BaseWSTest.java

/**
 * Validates the xml against the generated schema.
 * //  w  w w . ja v  a 2  s . c  om
 * @param xml
 *          the xml to validate
 */
protected void validateXML(String xml) {
    final Reader schemaReader = new StringReader(getXMLSchema());
    final Reader xmlReader = new StringReader(xml);
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);

        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

        factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource(schemaReader) }));

        SAXParser parser = factory.newSAXParser();

        XMLReader reader = parser.getXMLReader();
        reader.setErrorHandler(new SimpleErrorHandler());
        reader.parse(new InputSource(xmlReader));
    } catch (Exception e) {
        throw new OBException(e);
    }

}

From source file:org.opencms.xml.CmsXmlUtils.java

/**
 * Validates the structure of a XML document contained in a byte array 
 * with the DTD or XML schema used by the document.<p>
 * /*from  w  ww.  jav a  2  s.c o  m*/
 * @param xmlStream a source providing a XML document that should be validated
 * @param resolver the XML entity resolver to use
 * 
 * @throws CmsXmlException if the validation fails
 */
public static void validateXmlStructure(InputStream xmlStream, EntityResolver resolver) throws CmsXmlException {

    XMLReader reader;
    try {
        reader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    } catch (SAXException e) {
        // xerces parser not available - no schema validation possible
        if (LOG.isWarnEnabled()) {
            LOG.warn(Messages.get().getBundle().key(Messages.LOG_VALIDATION_INIT_XERXES_SAX_READER_FAILED_0),
                    e);
        }
        // no validation of the content is possible
        return;
    }
    // turn on validation
    try {
        reader.setFeature("http://xml.org/sax/features/validation", true);
        // turn on schema validation
        reader.setFeature("http://apache.org/xml/features/validation/schema", true);
        // configure namespace support
        reader.setFeature("http://xml.org/sax/features/namespaces", true);
        reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
    } catch (SAXNotRecognizedException e) {
        // should not happen as Xerces 2 support this feature
        if (LOG.isWarnEnabled()) {
            LOG.warn(Messages.get().getBundle().key(Messages.LOG_SAX_READER_FEATURE_NOT_RECOGNIZED_0), e);
        }
        // no validation of the content is possible
        return;
    } catch (SAXNotSupportedException e) {
        // should not happen as Xerces 2 support this feature
        if (LOG.isWarnEnabled()) {
            LOG.warn(Messages.get().getBundle().key(Messages.LOG_SAX_READER_FEATURE_NOT_SUPPORTED_0), e);
        }
        // no validation of the content is possible
        return;
    }

    // add an error handler which turns any errors into XML
    CmsXmlValidationErrorHandler errorHandler = new CmsXmlValidationErrorHandler();
    reader.setErrorHandler(errorHandler);

    if (resolver != null) {
        // set the resolver for the "opencms://" URIs
        reader.setEntityResolver(resolver);
    }

    try {
        reader.parse(new InputSource(xmlStream));
    } catch (IOException e) {
        // should not happen since we read form a byte array
        if (LOG.isErrorEnabled()) {
            LOG.error(Messages.get().getBundle().key(Messages.LOG_READ_XML_FROM_BYTE_ARR_FAILED_0), e);
        }
        return;
    } catch (SAXException e) {
        // should not happen since all errors are handled in the XML error handler
        if (LOG.isErrorEnabled()) {
            LOG.error(Messages.get().getBundle().key(Messages.LOG_PARSE_SAX_EXC_0), e);
        }
        return;
    }

    if (errorHandler.getErrors().elements().size() > 0) {
        // there was at last one validation error, so throw an exception
        StringWriter out = new StringWriter(256);
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(out, format);
        try {
            writer.write(errorHandler.getErrors());
            writer.write(errorHandler.getWarnings());
            writer.close();
        } catch (IOException e) {
            // should not happen since we write to a StringWriter
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_STRINGWRITER_IO_EXC_0), e);
            }
        }
        // generate String from XML for display of document in error message
        throw new CmsXmlException(Messages.get().container(Messages.ERR_XML_VALIDATION_1, out.toString()));
    }
}

From source file:org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.java

public boolean isValidXml(byte[] xmlToParse) {
    XMLReader parser = new SAXParser();
    boolean isXmlValid = true;
    try {// w ww.  j  av a2  s.com
        parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
    } catch (IOException | SAXException e) {
        isXmlValid = false;
    }
    return isXmlValid;
}

From source file:org.openhab.binding.sonos.internal.SonosXMLParser.java

/**
 * @param xml/*w ww .  jav a 2 s  .c om*/
 * @return a list of alarms from the given xml string.
 * @throws IOException
 * @throws SAXException
 */
public static List<SonosAlarm> getAlarmsFromStringResult(String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    AlarmHandler handler = new AlarmHandler();
    reader.setContentHandler(handler);
    try {
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        logger.error("Could not parse Alarms from String {}", xml);
    }
    return handler.getAlarms();
}

From source file:org.openhab.binding.sonos.internal.SonosXMLParser.java

/**
 * @param xml//from  w w w  .j a  va  2s .  co  m
 * @return a list of Entrys from the given xml string.
 * @throws IOException
 * @throws SAXException
 */
public static List<SonosEntry> getEntriesFromString(String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    EntryHandler handler = new EntryHandler();
    reader.setContentHandler(handler);
    try {
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        logger.error("Could not parse Entries from String {}", xml);
    }
    return handler.getArtists();
}

From source file:org.openhab.binding.sonos.internal.SonosXMLParser.java

/**
 * Returns the meta data which is needed to play Pandora 
 * (and others?) favorites/*from  w  w  w . j  a va  2  s.c  om*/
 * @param xml
 * @return The value of the desc xml tag
 * @throws SAXException
 */
public static SonosResourceMetaData getEmbededMetaDataFromResource(String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    EmbededMetaDataHandler handler = new EmbededMetaDataHandler();
    reader.setContentHandler(handler);
    try {
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        logger.error("Could not parse Entries from String {}", xml);
    }
    return handler.getMetaData();
}

From source file:org.openhab.binding.sonos.internal.SonosXMLParser.java

/**
 * @param controller//  w w  w  . j av  a  2  s .  c  om
 * @param xml
 * @return zone group from the given xml
 * @throws IOException
 * @throws SAXException
 */
public static List<SonosZoneGroup> getZoneGroupFromXML(String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    ZoneGroupHandler handler = new ZoneGroupHandler();
    reader.setContentHandler(handler);
    try {
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        // This should never happen - we're not performing I/O!
        logger.error("Could not parse ZoneGroup from String {}", xml);
    }

    return handler.getGroups();

}