Search in sources :

Example 51 with EntityResolver

use of org.xml.sax.EntityResolver in project Payara by payara.

the class WebContainer method postConstruct.

@Override
public void postConstruct() {
    final ReentrantReadWriteLock mapperLock = grizzlyService.obtainMapperLock();
    mapperLock.writeLock().lock();
    try {
        createProbeProviders();
        injectionMgr = habitat.getService(InjectionManager.class);
        invocationMgr = habitat.getService(InvocationManager.class);
        tldProviders = habitat.getAllServices(TldProvider.class);
        createStatsProviders();
        setJspFactory();
        _appsWorkRoot = instance.getApplicationCompileJspPath().getAbsolutePath();
        _modulesRoot = instance.getApplicationRepositoryPath();
        // START S1AS 6178005
        appsStubRoot = instance.getApplicationStubPath().getAbsolutePath();
        // END S1AS 6178005
        // TODO: ParserUtils should become a @Service and it should initialize itself.
        // TODO: there should be only one EntityResolver for both DigesterFactory
        // and ParserUtils
        File root = _serverContext.getInstallRoot();
        File libRoot = new File(root, "lib");
        File schemas = new File(libRoot, "schemas");
        File dtds = new File(libRoot, "dtds");
        try {
            ParserUtils.setSchemaResourcePrefix(schemas.toURI().toURL().toString());
            ParserUtils.setDtdResourcePrefix(dtds.toURI().toURL().toString());
            ParserUtils.setEntityResolver(habitat.<EntityResolver>getService(EntityResolver.class, "web"));
        } catch (MalformedURLException e) {
            logger.log(Level.SEVERE, LogFacade.EXCEPTION_SET_SCHEMAS_DTDS_LOCATION, e);
        }
        instanceName = _serverContext.getInstanceName();
        webContainerFeatureFactory = getWebContainerFeatureFactory();
        configureDynamicReloadingSettings();
        setDebugLevel();
        String maxDepth = null;
        org.glassfish.web.config.serverbeans.WebContainer configWC = serverConfig.getExtensionByType(org.glassfish.web.config.serverbeans.WebContainer.class);
        if (configWC != null)
            maxDepth = configWC.getPropertyValue(DISPATCHER_MAX_DEPTH);
        if (maxDepth != null) {
            int depth = -1;
            try {
                depth = Integer.parseInt(maxDepth);
            } catch (NumberFormatException e) {
            }
            if (depth > 0) {
                Request.setMaxDispatchDepth(depth);
                if (logger.isLoggable(Level.FINE)) {
                    logger.log(Level.FINE, LogFacade.MAX_DISPATCH_DEPTH_SET, maxDepth);
                }
            }
        }
        File currentLogFile = loggingRuntime.getCurrentLogFile();
        if (currentLogFile != null) {
            logServiceFile = currentLogFile.getAbsolutePath();
        }
        Level level = Logger.getLogger("org.apache.catalina.level").getLevel();
        if (level != null) {
            logLevel = level.getName();
        }
        _embedded = habitat.getService(EmbeddedWebContainer.class);
        _embedded.setWebContainer(this);
        _embedded.setLogServiceFile(logServiceFile);
        _embedded.setLogLevel(logLevel);
        _embedded.setFileLoggerHandlerFactory(fileLoggerHandlerFactory);
        _embedded.setWebContainerFeatureFactory(webContainerFeatureFactory);
        _embedded.setCatalinaHome(instance.getDomainRoot().getAbsolutePath());
        _embedded.setCatalinaBase(instance.getDomainRoot().getAbsolutePath());
        _embedded.setUseNaming(false);
        if (_debug > 1)
            _embedded.setDebug(_debug);
        _embedded.setLogger(new IASLogger(logger));
        engine = _embedded.createEngine();
        engine.setParentClassLoader(EmbeddedWebContainer.class.getClassLoader());
        engine.setService(_embedded);
        _embedded.addEngine(engine);
        ((StandardEngine) engine).setDomain(_serverContext.getDefaultDomainName());
        engine.setName(_serverContext.getDefaultDomainName());
        /*
            * Set the server info.
            * By default, the server info is taken from Version#getVersion.
            * However, customers may override it via the product.name system
            * property.
            * Some customers prefer not to disclose the server info
            * for security reasons, in which case they would set the value of the
            * product.name system property to the empty string. In this case,
            * the server name will not be publicly disclosed via the "Server"
            * HTTP response header (which will be suppressed) or any container
            * generated error pages. However, it will still appear in the
            * server logs (see IT 6900).
            */
        String serverInfo = System.getProperty("product.name");
        if (serverInfo == null) {
            ServerInfo.setServerInfo(Version.getVersion());
            ServerInfo.setPublicServerInfo(Version.getVersion());
        } else if (serverInfo.isEmpty()) {
            ServerInfo.setServerInfo(Version.getVersion());
            ServerInfo.setPublicServerInfo(serverInfo);
        } else {
            ServerInfo.setServerInfo(serverInfo);
            ServerInfo.setPublicServerInfo(serverInfo);
        }
        initInstanceSessionProperties();
        configListener = addAndGetWebConfigListener();
        ObservableBean bean = (ObservableBean) ConfigSupport.getImpl(serverConfig.getHttpService());
        bean.addListener(configListener);
        bean = (ObservableBean) ConfigSupport.getImpl(serverConfig.getNetworkConfig().getNetworkListeners());
        bean.addListener(configListener);
        if (serverConfig.getAvailabilityService() != null) {
            bean = (ObservableBean) ConfigSupport.getImpl(serverConfig.getAvailabilityService());
            bean.addListener(configListener);
        }
        transactions.addListenerForType(SystemProperty.class, configListener);
        configListener.setNetworkConfig(serverConfig.getNetworkConfig());
        // embedded mode does not have manager-propertie in domain.xml
        if (configListener.managerProperties != null) {
            ObservableBean managerBean = (ObservableBean) ConfigSupport.getImpl(configListener.managerProperties);
            managerBean.addListener(configListener);
        }
        if (serverConfig.getJavaConfig() != null) {
            ((ObservableBean) ConfigSupport.getImpl(serverConfig.getJavaConfig())).addListener(configListener);
        }
        configListener.setContainer(this);
        configListener.setLogger(logger);
        events.register(this);
        grizzlyService.addMapperUpdateListener(configListener);
        HttpService httpService = serverConfig.getHttpService();
        NetworkConfig networkConfig = serverConfig.getNetworkConfig();
        if (networkConfig != null) {
            // continue;
            securityService = serverConfig.getSecurityService();
            // Configure HTTP listeners
            NetworkListeners networkListeners = networkConfig.getNetworkListeners();
            if (networkListeners != null) {
                List<NetworkListener> listeners = networkListeners.getNetworkListener();
                for (NetworkListener listener : listeners) {
                    createHttpListener(listener, httpService);
                }
            }
            setDefaultRedirectPort(defaultRedirectPort);
            // Configure virtual servers
            createHosts(httpService, securityService);
        }
        loadSystemDefaultWebModules();
        // _lifecycle.fireLifecycleEvent(START_EVENT, null);
        _started = true;
        /*
             * Start the embedded container.
             * Make sure to set the thread's context classloader to the
             * classloader of this class (see IT 8866 for details)
             */
        ClassLoader current = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        try {
            /*
                 * Trigger a call to sun.awt.AppContext.getAppContext().
                 * This will pin the classloader of this class in memory
                 * and fix a memory leak affecting instances of WebappClassLoader
                 * that was caused by a JRE implementation change in 1.6.0_15
                 * onwards. See IT 11110
                 */
            ImageIO.getCacheDirectory();
            _embedded.start();
        } catch (LifecycleException le) {
            logger.log(Level.SEVERE, LogFacade.UNABLE_TO_START_WEB_CONTAINER, le);
            return;
        } finally {
            // Restore original context classloader
            Thread.currentThread().setContextClassLoader(current);
        }
    } finally {
        mapperLock.writeLock().unlock();
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) InvocationManager(org.glassfish.api.invocation.InvocationManager) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) StandardEngine(org.apache.catalina.core.StandardEngine) NetworkListeners(org.glassfish.grizzly.config.dom.NetworkListeners) WebappClassLoader(org.glassfish.web.loader.WebappClassLoader) TldProvider(org.glassfish.api.web.TldProvider) LifecycleException(org.apache.catalina.LifecycleException) NetworkConfig(org.glassfish.grizzly.config.dom.NetworkConfig) EntityResolver(org.xml.sax.EntityResolver) HttpService(com.sun.enterprise.config.serverbeans.HttpService) IASLogger(com.sun.enterprise.web.logger.IASLogger) Level(java.util.logging.Level) ObservableBean(org.jvnet.hk2.config.ObservableBean) File(java.io.File) InjectionManager(com.sun.enterprise.container.common.spi.util.InjectionManager) NetworkListener(org.glassfish.grizzly.config.dom.NetworkListener)

Example 52 with EntityResolver

use of org.xml.sax.EntityResolver in project tomee by apache.

the class SuperProperties method getDocumentBuilder.

private DocumentBuilder getDocumentBuilder() {
    if (builder == null) {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        try {
            builder = factory.newDocumentBuilder();
        } catch (final ParserConfigurationException e) {
            throw new Error(e);
        }
        builder.setErrorHandler(new ErrorHandler() {

            public void warning(final SAXParseException e) throws SAXException {
                throw e;
            }

            public void error(final SAXParseException e) throws SAXException {
                throw e;
            }

            public void fatalError(final SAXParseException e) throws SAXException {
                throw e;
            }
        });
        builder.setEntityResolver(new EntityResolver() {

            public InputSource resolveEntity(final String publicId, final String systemId) throws SAXException, IOException {
                if (systemId.equals(PROP_DTD_NAME)) {
                    final InputSource result = new InputSource(new StringReader(PROP_DTD));
                    result.setSystemId(PROP_DTD_NAME);
                    return result;
                }
                throw new SAXException("Invalid DOCTYPE declaration: " + systemId);
            }
        });
    }
    return builder;
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) SAXParseException(org.xml.sax.SAXParseException) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) EntityResolver(org.xml.sax.EntityResolver) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException)

Example 53 with EntityResolver

use of org.xml.sax.EntityResolver in project webtools.sourceediting by eclipse.

the class CommonXML method getEntityResolver.

/**
 * Returns an EntityResolver that won't try to load and resolve ANY
 * entities
 */
private static EntityResolver getEntityResolver() {
    EntityResolver resolver = new EntityResolver() {

        public InputSource resolveEntity(String publicID, String systemID) throws SAXException, IOException {
            InputSource result = new InputSource(new ByteArrayInputStream(new byte[0]));
            result.setPublicId(publicID);
            // $NON-NLS-1$
            result.setSystemId(systemID != null ? systemID : "/_" + getClass().getName());
            return result;
        }
    };
    return resolver;
}
Also used : InputSource(org.xml.sax.InputSource) ByteArrayInputStream(java.io.ByteArrayInputStream) EntityResolver(org.xml.sax.EntityResolver)

Example 54 with EntityResolver

use of org.xml.sax.EntityResolver in project sw360portal by sw360.

the class XhtmlGeneratorTest method generateDocumentsFromXml.

private static void generateDocumentsFromXml() throws Exception {
    EntityResolver resolver = new EntityResolver() {

        public InputSource resolveEntity(String publicId, String systemId) {
            if (publicId.equals("-//W3C//DTD XHTML 1.0 Strict//EN")) {
                InputStream in = getClass().getResourceAsStream("/xhtml1-strict.dtd");
                return new InputSource(in);
            }
            if (publicId.equals("-//W3C//ENTITIES Latin 1 for XHTML//EN")) {
                InputStream in = getClass().getResourceAsStream("/xhtml-lat1.ent");
                return new InputSource(in);
            }
            if (publicId.equals("-//W3C//ENTITIES Symbols for XHTML//EN")) {
                InputStream in = getClass().getResourceAsStream("/xhtml-symbol.ent");
                return new InputSource(in);
            }
            if (publicId.equals("-//W3C//ENTITIES Special for XHTML//EN")) {
                InputStream in = getClass().getResourceAsStream("/xhtml-special.ent");
                return new InputSource(in);
            }
            return null;
        }
    };
    SAXReader reader = new SAXReader();
    reader.setEntityResolver(resolver);
    document = reader.read(new InputSource(new StringReader(xmlString)));
    document2 = reader.read(new InputSource(new StringReader(xmlString2)));
    document3 = reader.read(new InputSource(new StringReader(xmlString3)));
    documentEmpty = reader.read(new InputSource(new StringReader(xmlStringEmpty)));
}
Also used : InputSource(org.xml.sax.InputSource) InputStream(java.io.InputStream) SAXReader(org.dom4j.io.SAXReader) StringReader(java.io.StringReader) EntityResolver(org.xml.sax.EntityResolver) Matchers.containsString(org.hamcrest.Matchers.containsString)

Example 55 with EntityResolver

use of org.xml.sax.EntityResolver in project BibleMultiConverter by schierlm.

the class LogosVerseMapDownloader method main.

public static void main(String[] args) throws Exception {
    String basedir = args.length == 0 ? "." : args[0];
    File versemap = new File(basedir, "src/main/resources/logos-versemap.dat");
    if (versemap.exists())
        return;
    System.out.println("Downloading Logos verse map...");
    try (InputStream in = new URL("https://wiki.logos.com/Bible_Verse_Maps").openStream();
        Writer w = new OutputStreamWriter(new FileOutputStream(versemap), StandardCharsets.ISO_8859_1)) {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        builder.setEntityResolver(new EntityResolver() {

            @Override
            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                return new InputSource(new StringReader(""));
            }
        });
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[4096];
        int len;
        while ((len = in.read(buf)) != -1) baos.write(buf, 0, len);
        String xml = new String(baos.toByteArray(), StandardCharsets.UTF_8);
        xml = xml.replaceAll("<script type=\"text/javascript\">window.*?</script>", "").replace("createCookie&authorizationHeader=", "").replaceAll("<script async charset=\"utf-8\"", "<script charset=\"utf-8\"");
        parseVerseMap(builder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))), w);
    }
    System.out.println("Downloading Logos verse map done.");
}
Also used : InputSource(org.xml.sax.InputSource) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) EntityResolver(org.xml.sax.EntityResolver) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) URL(java.net.URL) SAXException(org.xml.sax.SAXException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) StringReader(java.io.StringReader) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer)

Aggregations

EntityResolver (org.xml.sax.EntityResolver)72 InputSource (org.xml.sax.InputSource)39 SAXException (org.xml.sax.SAXException)34 IOException (java.io.IOException)29 DocumentBuilder (javax.xml.parsers.DocumentBuilder)22 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)22 Document (org.w3c.dom.Document)17 DefaultHandler (org.xml.sax.helpers.DefaultHandler)17 Test (org.junit.Test)16 StringReader (java.io.StringReader)13 SAXParseException (org.xml.sax.SAXParseException)12 ByteArrayInputStream (java.io.ByteArrayInputStream)10 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)10 NodeList (org.w3c.dom.NodeList)10 InputStream (java.io.InputStream)9 ArrayList (java.util.ArrayList)8 Node (org.w3c.dom.Node)8 ErrorHandler (org.xml.sax.ErrorHandler)8 Element (org.w3c.dom.Element)7 File (java.io.File)6