Example usage for org.xml.sax XMLReader setEntityResolver

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

Introduction

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

Prototype

public void setEntityResolver(EntityResolver resolver);

Source Link

Document

Allow an application to register an entity resolver.

Usage

From source file:org.rhq.plugins.diameter.jbossas5.util.JnpConfig.java

private void parseServiceXML(File distributionDirectory, File serviceXmlFile)
        throws IOException, SAXException, ParserConfigurationException {
    FileInputStream is = null;//from w  w w  .jav a2  s .c o m
    try {
        is = new FileInputStream(serviceXmlFile);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();

        EntityResolver r = new LocalEntityResolver(distributionDirectory);

        JBossServiceHandler handler = new JBossServiceHandler(serviceXmlFile);

        XMLReader reader = parser.getXMLReader();

        reader.setEntityResolver(r);

        reader.setContentHandler(handler);

        reader.parse(new InputSource(is));

        this.jnpAddress = handler.getNamingBindAddress();
        this.jnpPort = handler.getNamingPort();
        this.storeFile = handler.getStoreFile();
        this.serverName = handler.getServerName();
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.rhq.plugins.jbossas.util.JnpConfig.java

private void parseServiceXML(File serviceXmlFile)
        throws IOException, SAXException, ParserConfigurationException {
    FileInputStream is = null;//  w  ww  .ja  v  a2 s . c  o  m
    try {
        is = new FileInputStream(serviceXmlFile);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();

        XMLReader reader = parser.getXMLReader();

        EntityResolver entityResolver = SelectiveSkippingEntityResolver.getDtdAndXsdSkippingInstance();
        reader.setEntityResolver(entityResolver);

        JBossServiceHandler contentHandler = new JBossServiceHandler(serviceXmlFile);
        reader.setContentHandler(contentHandler);

        reader.parse(new InputSource(is));

        this.jnpAddress = contentHandler.getNamingBindAddress();
        this.jnpPort = contentHandler.getNamingPort();
        this.storeFile = contentHandler.getStoreFile();
        this.serverName = contentHandler.getServerName();
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.roda.core.common.RodaUtils.java

/**
 * INFO 20160711 this method does not cache stylesheet related resources
 *//*from  ww  w .j  a va  2  s .co m*/
public static void applyStylesheet(Reader xsltReader, Reader fileReader, Map<String, String> parameters,
        Writer result) throws IOException, TransformerException {

    TransformerFactory factory = new net.sf.saxon.TransformerFactoryImpl();
    factory.setURIResolver(new RodaURIFileResolver());
    Source xsltSource = new StreamSource(xsltReader);
    Transformer transformer = factory.newTransformer(xsltSource);
    for (Entry<String, String> parameter : parameters.entrySet()) {
        transformer.setParameter(parameter.getKey(), parameter.getValue());
    }
    try {
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setEntityResolver(new RodaEntityResolver());
        InputSource source = new InputSource(fileReader);
        Source text = new SAXSource(xmlReader, source);
        transformer.transform(text, new StreamResult(result));
    } catch (SAXException se) {
        LOGGER.error(se.getMessage(), se);
    }
}

From source file:org.roda.core.common.RodaUtils.java

public static Reader applyMetadataStylesheet(Binary binary, String basePath, String metadataType,
        String metadataVersion, Map<String, String> parameters) throws GenericException {
    try (Reader descMetadataReader = new InputStreamReader(
            new BOMInputStream(binary.getContent().createInputStream()))) {

        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setEntityResolver(new RodaEntityResolver());
        InputSource source = new InputSource(descMetadataReader);
        Source text = new SAXSource(xmlReader, source);

        XsltExecutable xsltExecutable = CACHE.get(Triple.of(basePath, metadataType, metadataVersion));

        XsltTransformer transformer = xsltExecutable.load();
        CharArrayWriter transformerResult = new CharArrayWriter();

        transformer.setSource(text);/*from   ww  w.  j  a  v  a 2s. com*/
        transformer.setDestination(PROCESSOR.newSerializer(transformerResult));

        for (Entry<String, String> parameter : parameters.entrySet()) {
            QName qName = new QName(parameter.getKey());
            XdmValue xdmValue = new XdmAtomicValue(parameter.getValue());
            transformer.setParameter(qName, xdmValue);
        }

        transformer.transform();

        return new CharArrayReader(transformerResult.toCharArray());

    } catch (IOException | SAXException | ExecutionException | SaxonApiException e) {
        throw new GenericException("Could not process descriptive metadata binary " + binary.getStoragePath()
                + " metadata type " + metadataType + " and version " + metadataVersion, e);
    }
}

From source file:org.roda.core.common.RodaUtils.java

public static Reader applyEventStylesheet(Binary binary, boolean onlyDetails, Map<String, String> translations,
        String path) throws GenericException {
    try (Reader descMetadataReader = new InputStreamReader(
            new BOMInputStream(binary.getContent().createInputStream()))) {

        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setEntityResolver(new RodaEntityResolver());
        InputSource source = new InputSource(descMetadataReader);
        Source text = new SAXSource(xmlReader, source);

        XsltExecutable xsltExecutable = EVENT_CACHE.get(path);

        XsltTransformer transformer = xsltExecutable.load();
        CharArrayWriter transformerResult = new CharArrayWriter();

        transformer.setSource(text);//from   w ww.  j av a 2 s. co  m
        transformer.setDestination(PROCESSOR.newSerializer(transformerResult));

        // send param to filter stylesheet work
        transformer.setParameter(new QName("onlyDetails"), new XdmAtomicValue(Boolean.toString(onlyDetails)));

        for (Entry<String, String> parameter : translations.entrySet()) {
            QName qName = new QName(parameter.getKey());
            XdmValue xdmValue = new XdmAtomicValue(parameter.getValue());
            transformer.setParameter(qName, xdmValue);
        }

        transformer.transform();
        return new CharArrayReader(transformerResult.toCharArray());
    } catch (IOException | SAXException | ExecutionException | SaxonApiException e) {
        LOGGER.error(e.getMessage(), e);
        throw new GenericException("Could not process event binary " + binary.getStoragePath(), e);
    }
}

From source file:org.roda.core.common.validation.ValidationUtils.java

public static ValidationReport isXMLValid(ContentPayload xmlPayload) {
    ValidationReport ret = new ValidationReport();

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);/*from   w w w . j a  v  a2  s  . c  om*/
    factory.setNamespaceAware(true);

    RodaErrorHandler errorHandler = new RodaErrorHandler();

    try (Reader reader = new InputStreamReader(new BOMInputStream(xmlPayload.createInputStream()))) {
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setEntityResolver(new RodaEntityResolver());
        InputSource inputSource = new InputSource(reader);

        xmlReader.setErrorHandler(errorHandler);
        xmlReader.parse(inputSource);
        ret.setValid(errorHandler.getErrors().isEmpty());
        for (SAXParseException saxParseException : errorHandler.getErrors()) {
            ret.addIssue(convertSAXParseException(saxParseException));
        }
    } catch (SAXException e) {
        ret.setValid(false);
        for (SAXParseException saxParseException : errorHandler.getErrors()) {
            ret.addIssue(convertSAXParseException(saxParseException));
        }
    } catch (IOException e) {
        ret.setValid(false);
        ret.setMessage(e.getMessage());
    }
    return ret;
}

From source file:org.roda.core.common.validation.ValidationUtils.java

/**
 * Validates descriptive medatada (e.g. against its schema, but other
 * strategies may be used)/*  www .ja  va  2 s .com*/
 * 
 * @param descriptiveMetadataType
 * 
 * @param failIfNoSchema
 * @throws ValidationException
 */
public static ValidationReport validateDescriptiveBinary(ContentPayload descriptiveMetadataPayload,
        String descriptiveMetadataType, String descriptiveMetadataVersion, boolean failIfNoSchema) {
    ValidationReport ret = new ValidationReport();
    InputStream inputStream = null;
    Optional<Schema> xmlSchema = RodaCoreFactory.getRodaSchema(descriptiveMetadataType,
            descriptiveMetadataVersion);
    try {
        if (xmlSchema.isPresent()) {
            RodaErrorHandler errorHandler = new RodaErrorHandler();

            try (InputStreamReader inputStreamReader = new InputStreamReader(
                    new BOMInputStream(descriptiveMetadataPayload.createInputStream()))) {

                XMLReader xmlReader = XMLReaderFactory.createXMLReader();
                xmlReader.setEntityResolver(new RodaEntityResolver());
                InputSource inputSource = new InputSource(inputStreamReader);
                Source source = new SAXSource(xmlReader, inputSource);

                Validator validator = xmlSchema.get().newValidator();

                validator.setErrorHandler(errorHandler);

                validator.validate(source);
                ret.setValid(errorHandler.getErrors().isEmpty());
                for (SAXParseException saxParseException : errorHandler.getErrors()) {
                    ret.addIssue(convertSAXParseException(saxParseException));
                }
            } catch (SAXException e) {
                LOGGER.debug("Error validating descriptive binary " + descriptiveMetadataType, e);
                ret.setValid(false);
                for (SAXParseException saxParseException : errorHandler.getErrors()) {
                    ret.addIssue(convertSAXParseException(saxParseException));
                }
            }
        } else {
            if (failIfNoSchema) {
                LOGGER.error(
                        "Will fail validating descriptive metadata with type '{}' and version '{}' because couldn't find its schema",
                        descriptiveMetadataType, descriptiveMetadataVersion);
                ret.setValid(false);
                ret.setMessage("No schema to validate " + descriptiveMetadataType);
            } else {
                LOGGER.debug(
                        "Found no schema do validate descriptive metadata but will try to validate XML syntax...");
                ret = isXMLValid(descriptiveMetadataPayload);
            }
        }
    } catch (IOException e) {
        LOGGER.error("Error validating descriptive metadata", e);
        ret.setValid(false);
        ret.setMessage(e.getMessage());
    } finally {
        IOUtils.closeQuietly(inputStream);
    }

    return ret;

}

From source file:org.smartfrog.projects.alpine.xmlutils.CatalogHandler.java

/**
 * bind an XML reader to this catalog/*w w  w .j  a v a  2  s.  c o m*/
 *
 * @param parser
 */
public void bind(XMLReader parser) throws SAXNotSupportedException, SAXNotRecognizedException, IOException {
    setImportPaths(parser);
    parser.setEntityResolver(this);
}

From source file:org.smartfrog.services.cddlm.cdl.CdlCatalog.java

/**
 * bind an XML reader to this bunny//from w  w  w. j a  v a2s .c  o m
 *
 * @param parser
 */
public void bind(XMLReader parser) throws SAXNotSupportedException, SAXNotRecognizedException {
    setImportPaths(parser);
    parser.setEntityResolver(this);
}

From source file:org.springframework.oxm.jaxb.Jaxb2Marshaller.java

@SuppressWarnings("deprecation") // on JDK 9
private Source processSource(Source source) {
    if (StaxUtils.isStaxSource(source) || source instanceof DOMSource) {
        return source;
    }//  w  w w.j  a  va  2s  .  c  o m

    XMLReader xmlReader = null;
    InputSource inputSource = null;

    if (source instanceof SAXSource) {
        SAXSource saxSource = (SAXSource) source;
        xmlReader = saxSource.getXMLReader();
        inputSource = saxSource.getInputSource();
    } else if (source instanceof StreamSource) {
        StreamSource streamSource = (StreamSource) source;
        if (streamSource.getInputStream() != null) {
            inputSource = new InputSource(streamSource.getInputStream());
        } else if (streamSource.getReader() != null) {
            inputSource = new InputSource(streamSource.getReader());
        } else {
            inputSource = new InputSource(streamSource.getSystemId());
        }
    }

    try {
        if (xmlReader == null) {
            xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
        }
        xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd());
        String name = "http://xml.org/sax/features/external-general-entities";
        xmlReader.setFeature(name, isProcessExternalEntities());
        if (!isProcessExternalEntities()) {
            xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
        }
        return new SAXSource(xmlReader, inputSource);
    } catch (SAXException ex) {
        logger.warn("Processing of external entities could not be disabled", ex);
        return source;
    }
}