Java Code Examples for org.xml.sax.EntityResolver

The following examples show how to use org.xml.sax.EntityResolver. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: micro-integrator   Source File: XSLTTransformer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method provides a secured document builder which will secure XXE attacks.
 *
 * @param setIgnoreComments whether to set setIgnoringComments in DocumentBuilderFactory.
 * @return DocumentBuilder
 * @throws ParserConfigurationException
 */
private static DocumentBuilder getSecuredDocumentBuilder(boolean setIgnoreComments) throws
                                                                                    ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setIgnoringComments(setIgnoreComments);
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setXIncludeAware(false);
    documentBuilderFactory.setExpandEntityReferences(false);
    documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(0);
    documentBuilderFactory.setAttribute(Constants.XERCES_PROPERTY_PREFIX +
            Constants.SECURITY_MANAGER_PROPERTY, securityManager);
    documentBuilder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            throw new SAXException("Possible XML External Entity (XXE) attack. Skip resolving entity");
        }
    });
    return documentBuilder;
}
 
Example 2
public void parse(InputSource source, ContentHandler handler, ErrorHandler errorHandler, EntityResolver entityResolver)

            throws SAXException, IOException {
        String systemId = source.getSystemId();
        Document dom = forest.get(systemId);

        if (dom == null) {
            // if no DOM tree is built for it,
            // let the fall back parser parse the original document.
            //
            // for example, XSOM parses datatypes.xsd (XML Schema part 2)
            // but this will never be built into the forest.
            fallbackParser.parse(source, handler, errorHandler, entityResolver);
            return;
        }

        scanner.scan(dom, handler);

    }
 
Example 3
Source Project: openjdk-jdk9   Source File: DOMParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the current entity resolver.
 *
 * @return The current entity resolver, or null if none
 *         has been registered.
 * @see #setEntityResolver
 */
public EntityResolver getEntityResolver() {

    EntityResolver entityResolver = null;
    try {
        XMLEntityResolver xmlEntityResolver =
            (XMLEntityResolver)fConfiguration.getProperty(ENTITY_RESOLVER);
        if (xmlEntityResolver != null) {
            if (xmlEntityResolver instanceof EntityResolverWrapper) {
                entityResolver =
                    ((EntityResolverWrapper) xmlEntityResolver).getEntityResolver();
            }
            else if (xmlEntityResolver instanceof EntityResolver2Wrapper) {
                entityResolver =
                    ((EntityResolver2Wrapper) xmlEntityResolver).getEntityResolver();
            }
        }
    }
    catch (XMLConfigurationException e) {
        // do nothing
    }
    return entityResolver;

}
 
Example 4
Source Project: netbeans   Source File: MakeNBM.java    License: Apache License 2.0 6 votes vote down vote up
static void validateAgainstAUDTDs(InputSource input, final Path updaterJar, final Task task) throws IOException, SAXException {
    XMLUtil.parse(input, true, false, XMLUtil.rethrowHandler(), new EntityResolver() {
        ClassLoader loader = new AntClassLoader(task.getProject(), updaterJar);
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            String remote = "http://www.netbeans.org/dtds/";
            if (systemId.startsWith(remote)) {
                String rsrc = "org/netbeans/updater/resources/" + systemId.substring(remote.length());
                URL u = loader.getResource(rsrc);
                if (u != null) {
                    return new InputSource(u.toString());
                } else {
                    task.log(rsrc + " not found in " + updaterJar, Project.MSG_WARN);
                }
            }
            return null;
        }
    });
}
 
Example 5
Source Project: Alite   Source File: XMLPropertyListParser.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets a DocumentBuilder to parse a XML property list.
 * As DocumentBuilders are not thread-safe a new DocBuilder is generated for each request.
 *
 * @return A new DocBuilder that can parse property lists w/o an internet connection.
 * @throws javax.xml.parsers.ParserConfigurationException If a document builder for parsing a XML property list
 *                                                        could not be created. This should not occur.
 */
private static synchronized DocumentBuilder getDocBuilder() throws ParserConfigurationException {
    if (docBuilderFactory == null)
        initDocBuilderFactory();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    docBuilder.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) {
            if ("-//Apple Computer//DTD PLIST 1.0//EN".equals(publicId) || // older publicId
                    "-//Apple//DTD PLIST 1.0//EN".equals(publicId)) { // newer publicId
                // return a dummy, zero length DTD so we don't have to fetch
                // it from the network.
                return new InputSource(new ByteArrayInputStream(new byte[0]));
            }
            return null;
        }
    });
    return docBuilder;
}
 
Example 6
public void parse(InputSource source, ContentHandler handler, ErrorHandler errorHandler, EntityResolver entityResolver)

            throws SAXException, IOException {
        String systemId = source.getSystemId();
        Document dom = forest.get(systemId);

        if (dom == null) {
            // if no DOM tree is built for it,
            // let the fall back parser parse the original document.
            //
            // for example, XSOM parses datatypes.xsd (XML Schema part 2)
            // but this will never be built into the forest.
            fallbackParser.parse(source, handler, errorHandler, entityResolver);
            return;
        }

        scanner.scan(dom, handler);

    }
 
Example 7
Source Project: java-technology-stack   Source File: DefaultDocumentLoader.java    License: MIT License 5 votes vote down vote up
/**
 * Load the {@link Document} at the supplied {@link InputSource} using the standard JAXP-configured
 * XML parser.
 */
@Override
public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
		ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {

	DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
	if (logger.isTraceEnabled()) {
		logger.trace("Using JAXP provider [" + factory.getClass().getName() + "]");
	}
	DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);
	return builder.parse(inputSource);
}
 
Example 8
Source Project: openjdk-jdk9   Source File: WSEndpoint.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Deprecated version that assumes {@code isTransportSynchronous==false}
 */
@Deprecated
public static <T> WSEndpoint<T> create(
    @NotNull Class<T> implType,
    boolean processHandlerAnnotation,
    @Nullable Invoker invoker,
    @Nullable QName serviceName,
    @Nullable QName portName,
    @Nullable Container container,
    @Nullable WSBinding binding,
    @Nullable SDDocumentSource primaryWsdl,
    @Nullable Collection<? extends SDDocumentSource> metadata,
    @Nullable EntityResolver resolver) {
    return create(implType,processHandlerAnnotation,invoker,serviceName,portName,container,binding,primaryWsdl,metadata,resolver,false);
}
 
Example 9
/**
     * convert an array of {@link InputSource InputSource} into an
     * array of {@link Source Source}
     *
     * @param schemas array of {@link InputSource InputSource}
     * @return array of {@link Source Source}
     */
    private static Source[] getSchemaSource(InputSource[] schemas, EntityResolver entityResolver) throws SAXException {
        SAXSource[] sources = new SAXSource[schemas.length];
        for (int i = 0; i < schemas.length; i++) {
            sources[i] = new SAXSource(schemas[i]);
//            sources[i].getXMLReader().setEntityResolver(entityResolver);
        }
        return sources;
    }
 
Example 10
/**
     * convert an array of {@link InputSource InputSource} into an
     * array of {@link Source Source}
     *
     * @param schemas array of {@link InputSource InputSource}
     * @return array of {@link Source Source}
     */
    private static Source[] getSchemaSource(InputSource[] schemas, EntityResolver entityResolver) throws SAXException {
        SAXSource[] sources = new SAXSource[schemas.length];
        for (int i = 0; i < schemas.length; i++) {
            sources[i] = new SAXSource(schemas[i]);
//            sources[i].getXMLReader().setEntityResolver(entityResolver);
        }
        return sources;
    }
 
Example 11
Source Project: openjdk-8   Source File: WSEndpoint.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static <T> WSEndpoint<T> create(
    @NotNull Class<T> implType,
    boolean processHandlerAnnotation,
    @Nullable Invoker invoker,
    @Nullable QName serviceName,
    @Nullable QName portName,
    @Nullable Container container,
    @Nullable WSBinding binding,
    @Nullable SDDocumentSource primaryWsdl,
    @Nullable Collection<? extends SDDocumentSource> metadata,
    @Nullable EntityResolver resolver,
    boolean isTransportSynchronous,
    boolean isStandard)
{
    final WSEndpoint<T> endpoint =
        EndpointFactory.createEndpoint(
            implType,processHandlerAnnotation, invoker,serviceName,portName,container,binding,primaryWsdl,metadata,resolver,isTransportSynchronous,isStandard);

    final Iterator<ManagedEndpointFactory> managementFactories = ServiceFinder.find(ManagedEndpointFactory.class).iterator();
    if (managementFactories.hasNext()) {
        final ManagedEndpointFactory managementFactory = managementFactories.next();
        final EndpointCreationAttributes attributes = new EndpointCreationAttributes(
                processHandlerAnnotation, invoker, resolver, isTransportSynchronous);

        WSEndpoint<T> managedEndpoint = managementFactory.createEndpoint(endpoint, attributes);

        if (endpoint.getAssemblerContext().getTerminalTube() instanceof EndpointAwareTube) {
            ((EndpointAwareTube)endpoint.getAssemblerContext().getTerminalTube()).setEndpoint(managedEndpoint);
        }

        return managedEndpoint;
    }


    return endpoint;
}
 
Example 12
Source Project: ph-commons   Source File: MicroSAXHandler.java    License: Apache License 2.0 5 votes vote down vote up
public MicroSAXHandler (final boolean bSaveIgnorableWhitespaces,
                        @Nullable final EntityResolver aEntityResolver,
                        final boolean bTrackPosition)
{
  m_bSaveIgnorableWhitespaces = bSaveIgnorableWhitespaces;
  m_aEntityResolver = aEntityResolver;
  m_aEntityResolver2 = aEntityResolver instanceof EntityResolver2 ? (EntityResolver2) aEntityResolver : null;
  m_bTrackPosition = bTrackPosition;
}
 
Example 13
/**
     * convert an array of {@link InputSource InputSource} into an
     * array of {@link Source Source}
     *
     * @param schemas array of {@link InputSource InputSource}
     * @return array of {@link Source Source}
     */
    private static Source[] getSchemaSource(InputSource[] schemas, EntityResolver entityResolver) throws SAXException {
        SAXSource[] sources = new SAXSource[schemas.length];
        for (int i = 0; i < schemas.length; i++) {
            sources[i] = new SAXSource(schemas[i]);
//            sources[i].getXMLReader().setEntityResolver(entityResolver);
        }
        return sources;
    }
 
Example 14
/**
 * Sets the resolver used to resolve external entities. The EntityResolver
 * interface supports resolution of public and system identifiers.
 *
 * @param resolver The new entity resolver. Passing a null value will
 *                 uninstall the currently installed resolver.
 */
public void setEntityResolver(EntityResolver resolver) {

    try {
        XMLEntityResolver xer = (XMLEntityResolver) fConfiguration.getProperty(ENTITY_RESOLVER);
        if (fUseEntityResolver2 && resolver instanceof EntityResolver2) {
            if (xer instanceof EntityResolver2Wrapper) {
                EntityResolver2Wrapper er2w = (EntityResolver2Wrapper) xer;
                er2w.setEntityResolver((EntityResolver2) resolver);
            }
            else {
                fConfiguration.setProperty(ENTITY_RESOLVER,
                        new EntityResolver2Wrapper((EntityResolver2) resolver));
            }
        }
        else {
            if (xer instanceof EntityResolverWrapper) {
                EntityResolverWrapper erw = (EntityResolverWrapper) xer;
                erw.setEntityResolver(resolver);
            }
            else {
                fConfiguration.setProperty(ENTITY_RESOLVER,
                        new EntityResolverWrapper(resolver));
            }
        }
    }
    catch (XMLConfigurationException e) {
        // do nothing
    }

}
 
Example 15
Source Project: jdk8u60   Source File: ModelLoader.java    License: GNU General Public License v2.0 5 votes vote down vote up
public XSOMParser createXSOMParser(final DOMForest forest) {
    XSOMParser p = createXSOMParser(forest.createParser());
    p.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            // DOMForest only parses documents that are reachable through systemIds,
            // and it won't pick up references like <xs:import namespace="..." /> without
            // @schemaLocation. So we still need to use an entity resolver here to resolve
            // these references, yet we don't want to just run them blindly, since if we do that
            // DOMForestParser always get the translated system ID when catalog is used
            // (where DOMForest records trees with their original system IDs.)
            if(systemId!=null && forest.get(systemId)!=null)
                return new InputSource(systemId);
            if(opt.entityResolver!=null)
                return opt.entityResolver.resolveEntity(publicId,systemId);

            return null;
        }
    });
    return p;
}
 
Example 16
Source Project: TencentKona-8   Source File: ExternalEntity.java    License: GNU General Public License v2.0 5 votes vote down vote up
public InputSource getInputSource(EntityResolver r)
        throws IOException, SAXException {

    InputSource retval;

    retval = r.resolveEntity(publicId, systemId);
    // SAX sez if null is returned, use the URI directly
    if (retval == null)
        retval = Resolver.createInputSource(new URL(systemId), false);
    return retval;
}
 
Example 17
Source Project: hottub   Source File: EndpointFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static <T> WSEndpoint<T> createEndpoint(
        Class<T> implType, boolean processHandlerAnnotation, @Nullable Invoker invoker,
        @Nullable QName serviceName, @Nullable QName portName,
        @Nullable Container container, @Nullable WSBinding binding,
        @Nullable SDDocumentSource primaryWsdl,
        @Nullable Collection<? extends SDDocumentSource> metadata,
        EntityResolver resolver, boolean isTransportSynchronous, boolean isStandard) {
    EndpointFactory factory = container != null ? container.getSPI(EndpointFactory.class) : null;
    if (factory == null)
            factory = EndpointFactory.getInstance();

    return factory.create(
            implType,processHandlerAnnotation, invoker,serviceName,portName,container,binding,primaryWsdl,metadata,resolver,isTransportSynchronous,isStandard);
}
 
Example 18
Source Project: openjdk-jdk8u   Source File: ExternalEntity.java    License: GNU General Public License v2.0 5 votes vote down vote up
public InputSource getInputSource(EntityResolver r)
        throws IOException, SAXException {

    InputSource retval;

    retval = r.resolveEntity(publicId, systemId);
    // SAX sez if null is returned, use the URI directly
    if (retval == null)
        retval = Resolver.createInputSource(new URL(systemId), false);
    return retval;
}
 
Example 19
Source Project: openjdk-jdk9   Source File: XmlCatalogUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets an EntityResolver using XML catalog
 *
 * @param catalogUrl
 * @return
 */
public static EntityResolver createEntityResolver(@Nullable URL catalogUrl) {
    ArrayList<URL> urlsArray = new ArrayList<>();
    EntityResolver er;
    if (catalogUrl != null) {
        urlsArray.add(catalogUrl);
    }
    try {
        er = createCatalogResolver(urlsArray);
    } catch (Exception e) {
        throw new ServerRtException("server.rt.err", e);
    }
    return er;
}
 
Example 20
/**
 * Creates an {@link EntityResolver} that consults {@code /WEB-INF/jax-ws-catalog.xml}.
 */
private EntityResolver createEntityResolver() {
    try {
        return XmlUtil.createEntityResolver(loader.getCatalogFile());
    } catch (MalformedURLException e) {
        throw new WebServiceException(e);
    }
}
 
Example 21
Source Project: xmlunit   Source File: XMLUnit.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Obtains the EntityResolver to be added to all new control parsers.
 */
public static EntityResolver getControlEntityResolver() {
    return controlEntityResolver;
}
 
Example 22
/** Wraps the specified SAX entity resolver. */
public EntityResolverWrapper(EntityResolver entityResolver) {
    setEntityResolver(entityResolver);
}
 
Example 23
Source Project: openjdk-8-source   Source File: JAXBSource.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void setEntityResolver(EntityResolver resolver) {
    this.entityResolver = resolver;
}
 
Example 24
Source Project: exificient   Source File: SAXDecoder.java    License: MIT License 4 votes vote down vote up
public EntityResolver getEntityResolver() {
	return null;
}
 
Example 25
Source Project: j2objc   Source File: DoNothingXMLReader.java    License: Apache License 2.0 4 votes vote down vote up
public void setEntityResolver(EntityResolver resolver) {
}
 
Example 26
/** Sets the SAX entity resolver. */
public void setEntityResolver(EntityResolver entityResolver) {
    fEntityResolver = entityResolver;
}
 
Example 27
Source Project: jdk1.8-source-analysis   Source File: StAXEvent2SAX.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * This class is only used internally so this method should never
 * be called.
 */
public void setEntityResolver(EntityResolver resolver) throws
    NullPointerException
{
}
 
Example 28
Source Project: j2objc   Source File: MockReader.java    License: Apache License 2.0 4 votes vote down vote up
public void setEntityResolver(EntityResolver resolver) {
    this.resolver = resolver;
}
 
Example 29
public void setEntityResolver(EntityResolver resolver) {
    _entityResolver = resolver;
}
 
Example 30
Source Project: unitime   Source File: MenuBackend.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	try {
		String menu = ApplicationProperty.MenuFile.value();
		Document document = null;
        URL menuUrl = ApplicationProperties.class.getClassLoader().getResource(menu);
        SAXReader sax = new SAXReader();
        sax.setEntityResolver(new EntityResolver() {
        	public InputSource resolveEntity(String publicId, String systemId) {
        		if (publicId.equals("-//UniTime//UniTime Menu DTD/EN")) {
        			return new InputSource(ApplicationProperties.class.getClassLoader().getResourceAsStream("menu.dtd"));
        		}
        		return null;
        	}
        });
        if (menuUrl!=null) {
            sLog.info("Reading menu from " + URLDecoder.decode(menuUrl.getPath(), "UTF-8") + " ...");
            document = sax.read(menuUrl.openStream());
        } else if (new File(menu).exists()) {
            sLog.info("Reading menu from " + menu + " ...");
            document = sax.read(new File(menu));
        }
        if (document==null)
            throw new ServletException("Unable to create menu, reason: resource " + menu + " not found.");

        if (!"unitime-menu".equals(document.getRootElement().getName())) throw new ServletException("Menu has an unknown format.");
        iRoot = document.getRootElement();
        
        String customMenu = ApplicationProperty.CustomMenuFile.value();
		Document customDocument = null;
        URL customMenuUrl = ApplicationProperties.class.getClassLoader().getResource(customMenu);
        if (customMenuUrl!=null) {
        	sLog.info("Reading custom menu from " + URLDecoder.decode(customMenuUrl.getPath(), "UTF-8") + " ...");
            customDocument = sax.read(customMenuUrl.openStream());
        } else if (new File(customMenu).exists()) {
        	sLog.info("Reading custom menu from " + customMenu + " ...");
            customDocument = sax.read(new File(customMenu));
        }
        if (customDocument != null) {
        	merge(iRoot, customDocument.getRootElement());
        }
        
	} catch (Exception e) {
		if (e instanceof RuntimeException) throw (RuntimeException)e;
		throw new RuntimeException("Unable to initialize, reason: "+e.getMessage(), e);
	}
}