Search in sources :

Example 46 with EventListener

use of java.util.EventListener in project tomcat70 by apache.

the class ApplicationContext method addListener.

@Override
public void addListener(Class<? extends EventListener> listenerClass) {
    EventListener listener;
    try {
        listener = createListener(listenerClass);
    } catch (ServletException e) {
        throw new IllegalArgumentException(sm.getString("applicationContext.addListener.iae.init", listenerClass.getName()), e);
    }
    addListener(listener);
}
Also used : ServletException(javax.servlet.ServletException) EventListener(java.util.EventListener)

Example 47 with EventListener

use of java.util.EventListener in project imageio-ext by geosolutions-it.

the class ImageReadMTCRIF method getImageReader.

/**
 * Get the <code>ImageReader</code> and set its input and metadata flag.
 * The input set on the reader might not be the same object as the input
 * passed in if the latter was replaced by getImageInputStream().
 */
static ImageReader getImageReader(ParameterBlock pb) {
    // Get the input.
    Object input = pb.getObjectParameter(0);
    // Get the reader parameter.
    ImageReader reader = (ImageReader) pb.getObjectParameter(8);
    // Attempt to create an ImageInputStream from the input.
    ImageInputStream stream = getImageInputStream(input);
    // If no reader passed in, try to find one.
    if (reader == null) {
        // Get all compatible readers.
        Iterator readers = ImageIO.getImageReaders(stream != null ? stream : input);
        // service provider indicates that it can decode the input.
        if (readers != null && readers.hasNext()) {
            do {
                ImageReader tmpReader = (ImageReader) readers.next();
                ImageReaderSpi readerSpi = tmpReader.getOriginatingProvider();
                try {
                    if (readerSpi.canDecodeInput(stream != null ? stream : input)) {
                        reader = tmpReader;
                    }
                } catch (IOException ioe) {
                // XXX Ignore it?
                }
            } while (reader == null && readers.hasNext());
        }
    }
    // If reader found, set its input and metadata flag.
    if (reader != null) {
        // Get the locale parameter and set on the reader.
        Locale locale = (Locale) pb.getObjectParameter(6);
        if (locale != null) {
            reader.setLocale(locale);
        }
        // Get the listeners parameter and set on the reader.
        EventListener[] listeners = (EventListener[]) pb.getObjectParameter(5);
        if (listeners != null) {
            for (int i = 0; i < listeners.length; i++) {
                EventListener listener = listeners[i];
                if (listener instanceof IIOReadProgressListener) {
                    reader.addIIOReadProgressListener((IIOReadProgressListener) listener);
                }
                if (listener instanceof IIOReadUpdateListener) {
                    reader.addIIOReadUpdateListener((IIOReadUpdateListener) listener);
                }
                if (listener instanceof IIOReadWarningListener) {
                    reader.addIIOReadWarningListener((IIOReadWarningListener) listener);
                }
            }
        }
        // Get the metadata reading flag.
        boolean readMetadata = ((Boolean) pb.getObjectParameter(2)).booleanValue();
        // Set the input and indicate metadata reading state.
        // seekForwardOnly
        reader.setInput(// seekForwardOnly
        stream != null ? stream : input, // seekForwardOnly
        false, // ignoreMetadata
        !readMetadata);
    }
    return reader;
}
Also used : Locale(java.util.Locale) IIOReadWarningListener(javax.imageio.event.IIOReadWarningListener) ImageInputStream(javax.imageio.stream.ImageInputStream) IIOReadProgressListener(javax.imageio.event.IIOReadProgressListener) IOException(java.io.IOException) IIOReadUpdateListener(javax.imageio.event.IIOReadUpdateListener) ImageReaderSpi(javax.imageio.spi.ImageReaderSpi) Iterator(java.util.Iterator) EventListener(java.util.EventListener) ImageReader(javax.imageio.ImageReader)

Example 48 with EventListener

use of java.util.EventListener in project gate-core by GateNLP.

the class CreoleProxy method createResource.

/**
 * Create an instance of a resource, and return it. Callers of this
 * method are responsible for querying the resource's parameter lists,
 * putting together a set that is complete apart from runtime
 * parameters, and passing a feature map containing these parameter
 * settings.
 *
 * In the case of ProcessingResources they will have their runtime
 * parameters initialised to their default values.
 *
 * @param resourceClassName the name of the class implementing the
 *          resource.
 * @param parameterValues the feature map containing intialisation
 *          time parameterValues for the resource.
 * @param features the features for the new resource or null to not
 *          assign any (new) features.
 * @param resourceName the name to be given to the resource or null to
 *          assign a default name.
 * @return an instantiated resource.
 */
public static Resource createResource(String resourceClassName, FeatureMap parameterValues, FeatureMap features, String resourceName) throws ResourceInstantiationException {
    // get the resource metadata
    ResourceData resData = Gate.getCreoleRegister().get(resourceClassName);
    if (resData == null) {
        Set<Plugin> plugins = Gate.getPlugins(resourceClassName);
        StringBuilder msg = new StringBuilder();
        msg.append("Couldn't get resource data for ").append(resourceClassName).append(".\n\n");
        if (plugins.isEmpty()) {
            msg.append("You may need first to load the plugin that contains your resource.\n");
            msg.append("For example, to create a gate.creole.tokeniser.DefaultTokeniser\n");
            msg.append("you need first to load the ANNIE plugin.\n\n");
        } else if (plugins.size() == 1) {
            msg.append(resourceClassName).append(" can be found in the ").append(plugins.iterator().next().getName()).append(" plugin\n\n");
        } else {
            msg.append(resourceClassName).append(" can be found in the following plugins\n   ");
            for (Plugin dInfo : plugins) {
                msg.append(dInfo.getName()).append(", ");
            }
            msg.setLength(msg.length() - 2);
            msg.append("\n\n");
        }
        msg.append("Go to the menu File->Manage CREOLE plugins or use the method\n");
        msg.append("Gate.getCreoleRegister().registerDirectories(pluginDirectoryURL).");
        throw new ResourceInstantiationException(msg.toString());
    }
    // get the default implementation class
    Class<? extends Resource> resClass = null;
    try {
        resClass = resData.getResourceClass();
    } catch (ClassNotFoundException e) {
        throw new ResourceInstantiationException("Couldn't get resource class from the resource data:" + Strings.getNl() + e);
    }
    // create a pointer for the resource
    Resource res = null;
    // if the object is an LR and it should come from a DS then create
    // that way
    DataStore dataStore;
    if (LanguageResource.class.isAssignableFrom(resClass) && ((dataStore = (DataStore) parameterValues.get(DataStore.DATASTORE_FEATURE_NAME)) != null)) {
        // ask the datastore to create our object
        if (dataStore instanceof SerialDataStore) {
            // serialisability
            if (!Serializable.class.isAssignableFrom(resClass))
                throw new ResourceInstantiationException("Resource cannot be (de-)serialized: " + resClass.getName());
        }
        // get the datastore instance id and retrieve the resource
        Object instanceId = parameterValues.get(DataStore.LR_ID_FEATURE_NAME);
        if (instanceId == null)
            throw new ResourceInstantiationException("No instance id for " + resClass);
        try {
            res = dataStore.getLr(resClass.getName(), instanceId);
        } catch (PersistenceException pe) {
            throw new ResourceInstantiationException("Bad read from DB: " + pe);
        } catch (SecurityException se) {
            throw new ResourceInstantiationException("Insufficient permissions: " + se);
        }
        resData.addInstantiation(res);
        if (features != null) {
            if (res.getFeatures() == null) {
                res.setFeatures(newFeatureMap());
            }
            res.getFeatures().putAll(features);
        }
        // set the name
        if (res.getName() == null) {
            res.setName(resourceName == null ? resData.getName() + "_" + Gate.genSym() : resourceName);
        }
        // fire the event
        creoleProxy.fireResourceLoaded(new CreoleEvent(res, CreoleEvent.RESOURCE_LOADED));
        return res;
    }
    // create an object using the resource's default constructor
    try {
        if (DEBUG)
            Out.prln("Creating resource " + resClass.getName());
        res = resClass.newInstance();
    } catch (IllegalAccessException e) {
        throw new ResourceInstantiationException("Couldn't create resource instance, access denied: " + e);
    } catch (InstantiationException e) {
        throw new ResourceInstantiationException("Couldn't create resource instance due to newInstance() failure: " + e);
    }
    if (LanguageResource.class.isAssignableFrom(resClass)) {
        // type-specific stuff for LRs
        if (DEBUG)
            Out.prln(resClass.getName() + " is a LR");
    } else if (ProcessingResource.class.isAssignableFrom(resClass)) {
        // type-specific stuff for PRs
        if (DEBUG)
            Out.prln(resClass.getName() + " is a PR");
        // set the runtime parameters to their defaults
        try {
            FeatureMap parameters = newFeatureMap();
            parameters.putAll(resData.getParameterList().getRuntimeDefaults());
            res.setParameterValues(parameters);
        } catch (ParameterException pe) {
            throw new ResourceInstantiationException("Could not set the runtime parameters " + "to their default values for: " + res.getClass().getName() + " :\n" + pe.toString());
        }
    // type-specific stuff for VRs
    } else if (VisualResource.class.isAssignableFrom(resClass)) {
        if (DEBUG)
            Out.prln(resClass.getName() + " is a VR");
    } else if (Controller.class.isAssignableFrom(resClass)) {
        // type specific stuff for Controllers
        if (DEBUG)
            Out.prln(resClass.getName() + " is a Controller");
    }
    // set the parameterValues of the resource
    try {
        FeatureMap parameters = newFeatureMap();
        // put the defaults
        parameters.putAll(resData.getParameterList().getInitimeDefaults());
        // overwrite the defaults with the user provided values
        parameters.putAll(parameterValues);
        res.setParameterValues(parameters);
    } catch (ParameterException pe) {
        throw new ResourceInstantiationException("Could not set the init parameters for: " + res.getClass().getName() + " :\n" + pe.toString());
    }
    // suitable name if the resource doesn't already have one
    if (resourceName != null && resourceName.trim().length() > 0) {
        res.setName(resourceName);
    } else if (res.getName() == null) {
        // -> let's try and find a reasonable one
        try {
            // first try to get a filename from the various parameters
            URL sourceUrl = null;
            if (res instanceof SimpleDocument) {
                sourceUrl = ((SimpleDocument) res).getSourceUrl();
            } else if (res instanceof AnnotationSchema) {
                sourceUrl = ((AnnotationSchema) res).getXmlFileUrl();
            } else if (res.getClass().getName().startsWith("gate.creole.ontology.owlim.")) {
                // get the name for the OWLIM2 ontology LR
                java.lang.reflect.Method m = resClass.getMethod("getRdfXmlURL");
                sourceUrl = (java.net.URL) m.invoke(res);
                if (sourceUrl == null) {
                    m = resClass.getMethod("getN3URL");
                    sourceUrl = (java.net.URL) m.invoke(res);
                }
                if (sourceUrl == null) {
                    m = resClass.getMethod("getNtriplesURL");
                    sourceUrl = (java.net.URL) m.invoke(res);
                }
                if (sourceUrl == null) {
                    m = resClass.getMethod("getTurtleURL");
                    sourceUrl = (java.net.URL) m.invoke(res);
                }
            } else if (res.getClass().getName().startsWith("gate.creole.ontology.impl.")) {
                java.lang.reflect.Method m = resClass.getMethod("getSourceURL");
                sourceUrl = (java.net.URL) m.invoke(res);
            }
            if (sourceUrl != null) {
                URI sourceURI = sourceUrl.toURI();
                resourceName = sourceURI.getPath();
                if (resourceName == null || resourceName.length() == 0 || resourceName.equals("/")) {
                    // this URI has no path -> use the whole string
                    resourceName = sourceURI.toString();
                } else {
                    // there is a significant path value -> get the last element
                    resourceName = resourceName.trim();
                    int lastSlash = resourceName.lastIndexOf('/');
                    if (lastSlash >= 0) {
                        String subStr = resourceName.substring(lastSlash + 1);
                        if (subStr.trim().length() > 0)
                            resourceName = subStr;
                    }
                }
            }
        } catch (RuntimeException t) {
        // even runtime exceptions are safe to ignore at this point
        } catch (Exception t) {
        // there were problems while trying to guess a name
        // we can safely ignore them
        } finally {
            // make sure there is a name provided, whatever happened
            if (resourceName == null || resourceName.trim().length() == 0) {
                resourceName = resData.getName();
            }
        }
        resourceName += "_" + Gate.genSym();
        res.setName(resourceName);
    }
    // else if(res.getName() == null)
    // if res.getName() != null, leave it as it is
    Map<String, EventListener> listeners = new HashMap<String, EventListener>(gate.Gate.getListeners());
    // set the listeners if any
    if (!listeners.isEmpty()) {
        try {
            if (DEBUG)
                Out.prln("Setting the listeners for  " + res.toString());
            AbstractResource.setResourceListeners(res, listeners);
        } catch (Exception e) {
            if (DEBUG)
                Out.prln("Failed to set listeners for " + res.toString());
            throw new ResourceInstantiationException("Parameterisation failure" + e);
        }
    }
    // set them to the features of the resource data
    if (res.getFeatures() == null || res.getFeatures().isEmpty()) {
        FeatureMap fm = newFeatureMap();
        fm.putAll(resData.getFeatures());
        res.setFeatures(fm);
    }
    // add the features specified by the user
    if (features != null)
        res.getFeatures().putAll(features);
    // initialise the resource
    if (DEBUG)
        Out.prln("Initialising resource " + res.toString());
    res = res.init();
    // remove the listeners if any
    if (!listeners.isEmpty()) {
        try {
            if (DEBUG)
                Out.prln("Removing the listeners for  " + res.toString());
            AbstractResource.removeResourceListeners(res, listeners);
        } catch (Exception e) {
            if (DEBUG)
                Out.prln("Failed to remove the listeners for " + res.toString());
            throw new ResourceInstantiationException("Parameterisation failure" + e);
        }
    }
    // record the instantiation on the resource data's stack
    resData.addInstantiation(res);
    // fire the event
    creoleProxy.fireResourceLoaded(new CreoleEvent(res, CreoleEvent.RESOURCE_LOADED));
    return res;
}
Also used : Serializable(java.io.Serializable) HashMap(java.util.HashMap) IdentityHashMap(java.util.IdentityHashMap) AbstractProcessingResource(gate.creole.AbstractProcessingResource) URI(java.net.URI) URL(java.net.URL) AnnotationSchema(gate.creole.AnnotationSchema) SerialDataStore(gate.persist.SerialDataStore) ParameterException(gate.creole.ParameterException) EventListener(java.util.EventListener) ResourceData(gate.creole.ResourceData) CreoleEvent(gate.event.CreoleEvent) AbstractProcessingResource(gate.creole.AbstractProcessingResource) AbstractResource(gate.creole.AbstractResource) ConditionalController(gate.creole.ConditionalController) ResourceInstantiationException(gate.creole.ResourceInstantiationException) PersistenceException(gate.persist.PersistenceException) ParameterException(gate.creole.ParameterException) ResourceInstantiationException(gate.creole.ResourceInstantiationException) PersistenceException(gate.persist.PersistenceException) SerialDataStore(gate.persist.SerialDataStore) Plugin(gate.creole.Plugin) ResourceInstantiationException(gate.creole.ResourceInstantiationException)

Example 49 with EventListener

use of java.util.EventListener in project runwar by cfmlprojects.

the class WebXMLParser method parseWebXml.

/**
 * Parses the web.xml and configures the context.
 *
 * @param webxml
 * @param info
 */
@SuppressWarnings("unchecked")
public static void parseWebXml(File webxml, File webinf, DeploymentInfo info, SessionCookieConfig sessionConfig, boolean ignoreWelcomePages, boolean ignoreRestMappings) {
    if (!webxml.exists() || !webxml.canRead()) {
        LOG.error("Error reading web.xml! exists:" + webxml.exists() + "readable:" + webxml.canRead());
    }
    Map<String, ServletInfo> servletMap = new HashMap<String, ServletInfo>();
    Map<String, FilterInfo> filterMap = new HashMap<String, FilterInfo>();
    try {
        final String webinfPath;
        if (File.separatorChar == '\\') {
            webinfPath = webinf.getCanonicalPath().replace("\\", "\\\\");
        } else {
            webinfPath = webinf.getCanonicalPath();
        }
        trace("parsing %s", webxml.getCanonicalPath());
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        // disable validation, so we don't incur network calls
        docBuilderFactory.setValidating(false);
        docBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        // parse and normalize text representation
        Document doc = docBuilder.parse(webxml);
        doc.getDocumentElement().normalize();
        trace("Root element of the doc is %s", doc.getDocumentElement().getNodeName());
        String displayName = $(doc).find("context-param").text();
        if (displayName != null) {
            info.setDisplayName(displayName);
        }
        $(doc).find("context-param").each(ctx -> {
            String pName = $(ctx).find("param-name").text();
            String pValue = $(ctx).find("param-value").text();
            info.addServletContextAttribute(pName, pValue);
            info.addInitParameter(pName, pValue);
            LOG.tracef("context param: %s = %s", pName, pValue);
        });
        trace("Total no of context-params: %s", info.getServletContextAttributes().size());
        Match listeners = $(doc).find("listener");
        trace("Total no of listeners: %s", listeners.size());
        listeners.each(ctx -> {
            String pName = $(ctx).find("listener-class").text();
            LOG.tracef("Listener: %s", pName);
            ListenerInfo listener;
            try {
                listener = new ListenerInfo((Class<? extends EventListener>) info.getClassLoader().loadClass(pName));
                info.addListener(listener);
            } catch (ClassNotFoundException e) {
                LOG.error(e);
            }
        });
        // do filters
        Match filters = $(doc).find("filter");
        trace("Total no of filters: %s", filters.size());
        filters.each(ctx -> {
            String filterName = $(ctx).find("filter-name").text();
            String className = $(ctx).find("filter-class").text();
            LOG.tracef("filter-name: %s, filter-class: %s", filterName, className);
            try {
                FilterInfo filter = new FilterInfo(filterName, (Class<? extends Filter>) info.getClassLoader().loadClass(className));
                Match initParams = $(ctx).find("init-param");
                LOG.debugf("Total no of %s init-params: %s", filterName, initParams.size());
                initParams.each(cctx -> {
                    String pName = $(cctx).find("param-name").text();
                    String pValue = $(cctx).find("param-value").text();
                    filter.addInitParam(pName, pValue);
                    LOG.tracef("%s init-param: param-name: %s  param-value: %s", filterName, pName, pValue);
                });
                if ($(ctx).find("async-supported").size() > 0) {
                    trace("Async supported: %s", $(ctx).find("async-supported").text());
                    filter.setAsyncSupported(Boolean.valueOf($(ctx).find("async-supported").text()));
                }
                filterMap.put(filterName, filter);
            } catch (ClassNotFoundException e) {
                LOG.error(e);
            }
        });
        info.addFilters(filterMap.values());
        Match filterMappings = $(doc).find("filter-mapping");
        trace("Total no of filters-mappings: %s", filterMappings.size());
        filterMappings.each(ctx -> {
            String filterName = $(ctx).find("filter-name").text();
            String className = $(ctx).find("filter-class").text();
            LOG.tracef("filter-name: %s, filter-class: %s", filterName, className);
            FilterInfo filter = filterMap.get(filterName);
            if (filter == null) {
                LOG.errorf("No filter found for filter-mapping: %s", filterName);
            } else {
                String urlPattern = $(ctx).find("url-pattern").text();
                Match dispatchers = $(ctx).find("dispatcher");
                if (dispatchers == null) {
                    LOG.debugf("filter-name: %s url-pattern: %s dispatcher: REQUEST", filterName, urlPattern);
                    info.addFilterUrlMapping(filterName, urlPattern, DispatcherType.valueOf("REQUEST"));
                } else {
                    dispatchers.each(dCtx -> {
                        String dispatcher = $(dCtx).text();
                        LOG.debugf("filter-name: %s url-pattern: %s dispatcher: %s", filterName, urlPattern, dispatcher);
                        info.addFilterUrlMapping(filterName, $(dCtx).text(), DispatcherType.valueOf(dispatcher));
                    });
                }
                String servletName = $(ctx).find("servlet-name").text();
                if (servletName != null) {
                    LOG.debugf("Adding servlet mapping: %s", servletName);
                    info.addFilterServletNameMapping(filterName, servletName, DispatcherType.valueOf("REQUEST"));
                }
            }
        });
        Match servlets = $(doc).find("servlet");
        trace("Total no of servlets: %s", servlets.size());
        servlets.each(ctx -> {
            String servletName = $(ctx).find("servlet-name").text();
            String servletClassName = $(ctx).find("servlet-class").text();
            String loadOnStartup = $(ctx).find("load-on-startup").text();
            LOG.tracef("servlet-name: %s, servlet-class: %s", servletName, servletClassName);
            LOG.tracef("Adding servlet to undertow: ************* %s: %s *************", servletName, servletClassName);
            Class<?> servletClass;
            try {
                servletClass = info.getClassLoader().loadClass(servletClassName);
            } catch (Exception e) {
                String msg = "Could not load servlet class: " + servletClassName;
                LOG.error(msg);
                throw new RuntimeException(msg);
            }
            ServletInfo servlet = new ServletInfo(servletName, (Class<? extends Servlet>) servletClass);
            servlet.setRequireWelcomeFileMapping(true);
            if (loadOnStartup != null) {
                trace("Load on startup: %s", loadOnStartup);
                servlet.setLoadOnStartup(Integer.valueOf(loadOnStartup));
            }
            Match initParams = $(ctx).find("init-param");
            LOG.debugf("Total no of %s init-params: %s", servletName, initParams.size());
            initParams.each(cctx -> {
                String pName = $(cctx).find("param-name").text();
                String pValue = $(cctx).find("param-value").text();
                pValue = pValue.replaceAll(".?/WEB-INF", SPECIAL_REGEX_CHARS.matcher(webinfPath).replaceAll("\\\\$0"));
                LOG.tracef("%s init-param: param-name: %s  param-value: %s", servletName, pName, pValue);
                servlet.addInitParam(pName, pValue);
            });
            servletMap.put(servlet.getName(), servlet);
        });
        Match servletMappings = $(doc).find("servlet-mapping");
        trace("Total no of servlet-mappings: %s", servletMappings.size());
        servletMappings.each(ctx -> {
            String servletName = $(ctx).find("servlet-name").text();
            ServletInfo servlet = servletMap.get(servletName);
            if (servlet == null) {
                LOG.errorf("No servlet found for servlet-mapping: %s", servletName);
            } else {
                Match urlPatterns = $(ctx).find("url-pattern");
                urlPatterns.each(urlPatternElement -> {
                    String urlPattern = $(urlPatternElement).text();
                    if (ignoreRestMappings && (servletName.toLowerCase().equals("restservlet") || servletName.toLowerCase().equals("cfrestservlet"))) {
                        LOG.tracef("Skipping mapping servlet-name:%s, url-partern: %s", servletName, urlPattern);
                    } else {
                        LOG.tracef("mapping servlet-name:%s, url-pattern: %s", servletName, urlPattern);
                        servlet.addMapping(urlPattern);
                    }
                });
            }
        });
        // add servlets to deploy info
        info.addServlets(servletMap.values());
        // do welcome files
        if (ignoreWelcomePages) {
            LOG.info("Ignoring any welcome pages in web.xml");
        } else {
            Match welcomeFileList = $(doc).find("welcome-file-list");
            trace("Total no of welcome files: %s", welcomeFileList.find("welcome-file").size());
            welcomeFileList.find("welcome-file").each(welcomeFileElement -> {
                String welcomeFile = $(welcomeFileElement).text();
                LOG.debugf("welcome-file: %s", welcomeFile);
                info.addWelcomePage(welcomeFile);
            });
        }
        Match mimeMappings = $(doc).find("mime-mapping");
        trace("Total no of mime-mappings: %s", mimeMappings.size());
        mimeMappings.each(ctx -> {
            String extension = $(ctx).find("extension").text();
            String mimeType = $(ctx).find("mime-type").text();
            LOG.tracef("filter-name: %s, filter-class: %s", extension, mimeType);
            info.addMimeMapping(new MimeMapping(extension, mimeType));
        });
        Match errorPages = $(doc).find("error-page");
        trace("Total no of error-pages: %s", errorPages.size());
        errorPages.each(ctx -> {
            String location = $(ctx).find("location").text();
            String errorCode = $(ctx).find("error-code").text();
            String exceptionType = $(ctx).find("exception-type").text();
            if (errorCode != null && exceptionType != null) {
                LOG.errorf("Cannot specify both error-code and exception-type, using exception-type: %s", exceptionType);
                errorCode = null;
            }
            if (errorCode == null && exceptionType == null) {
                LOG.tracef("default error-page location: %s", location);
                info.addErrorPage(new ErrorPage(location));
            } else if (errorCode != null) {
                LOG.tracef("error-code: %s - location: %s", location, errorCode);
                info.addErrorPage(new ErrorPage(location, Integer.parseInt(errorCode)));
            } else {
                LOG.tracef("exception-type: %s - location: %s", location, errorCode);
                try {
                    info.addErrorPage(new ErrorPage(location, (Class<? extends Throwable>) info.getClassLoader().loadClass(exceptionType)));
                } catch (ClassNotFoundException e) {
                    LOG.error(e);
                }
            }
        });
        Match sessionConfigElement = $(doc).find("session-config");
        trace("Total no of cookie config elements: %s", sessionConfigElement.find("cookie-config").size());
        sessionConfigElement.find("cookie-config").each(welcomeFileElement -> {
            String httpOnly = $(welcomeFileElement).find("http-only").text();
            String secure = $(welcomeFileElement).find("secure").text();
            sessionConfig.setHttpOnly(Boolean.valueOf(httpOnly));
            sessionConfig.setSecure(Boolean.valueOf(secure));
            LOG.debugf("http-only: %s", Boolean.valueOf(httpOnly).toString());
            LOG.debugf("secure: %s", Boolean.valueOf(secure).toString());
        });
    } catch (Exception e) {
        LOG.error("Error reading web.xml", e);
        throw new RuntimeException(e);
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) ErrorPage(io.undertow.servlet.api.ErrorPage) HashMap(java.util.HashMap) Document(org.w3c.dom.Document) Match(org.joox.Match) ServletInfo(io.undertow.servlet.api.ServletInfo) ListenerInfo(io.undertow.servlet.api.ListenerInfo) DocumentBuilder(javax.xml.parsers.DocumentBuilder) EventListener(java.util.EventListener) FilterInfo(io.undertow.servlet.api.FilterInfo) MimeMapping(io.undertow.servlet.api.MimeMapping)

Example 50 with EventListener

use of java.util.EventListener in project ignite by apache.

the class ServiceDeploymentDiscoveryListenerNotificationOrderTest method testServiceDiscoveryListenerNotifiedEarlierThanPME.

/**
 * <b>Strongly depends on internal implementation of {@link GridEventStorageManager}.</b>
 * <p/>
 * Tests that discovery listener registered by {@link ServiceDeploymentManager} is in collection of hight priority
 * listeners, at the same time discovery listener registered by {@link GridCachePartitionExchangeManager} is in
 * collection of usual listeners.
 * <p/>
 * This guarantees that service deployment discovery listener will be notified earlier that PME's discovery listener
 * and will be able to capture custom messages which may be nullified in PME process.
 *
 * @throws Exception In case of an error.
 */
@Test
public void testServiceDiscoveryListenerNotifiedEarlierThanPME() throws Exception {
    try {
        IgniteEx ignite = startGrid(0);
        ConcurrentMap<Integer, Object> lsnrs = GridTestUtils.getFieldValue(ignite.context().event(), "lsnrs");
        Object customLsnrs = lsnrs.get(DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT);
        List<EventListener> highPriorityLsnrs = GridTestUtils.getFieldValue(customLsnrs, "highPriorityLsnrs");
        GridConcurrentLinkedHashSet<EventListener> usualLsnrs = GridTestUtils.getFieldValue(customLsnrs, "lsnrs");
        assertTrue("Failed to find service deployment manager's listener in high priority listeners.", containsListener(highPriorityLsnrs, ServiceDeploymentManager.class));
        assertFalse("Service deployment manager's listener shoud not be registered in usual listeners.", containsListener(usualLsnrs, ServiceDeploymentManager.class));
        assertTrue("Failed to find PME manager's discovery listener in usual listeners.", containsListener(usualLsnrs, GridCachePartitionExchangeManager.class));
        assertFalse("PME manager's discovery listener shoud not be registered in high priority listeners.", containsListener(highPriorityLsnrs, GridCachePartitionExchangeManager.class));
    } finally {
        stopAllGrids();
    }
}
Also used : GridCachePartitionExchangeManager(org.apache.ignite.internal.processors.cache.GridCachePartitionExchangeManager) IgniteEx(org.apache.ignite.internal.IgniteEx) EventListener(java.util.EventListener) GridCommonAbstractTest(org.apache.ignite.testframework.junits.common.GridCommonAbstractTest) Test(org.junit.Test)

Aggregations

EventListener (java.util.EventListener)71 Test (org.junit.Test)11 ListenerInfo (io.undertow.servlet.api.ListenerInfo)5 ServletRequestListener (javax.servlet.ServletRequestListener)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 ServletContextListener (javax.servlet.ServletContextListener)3 HttpSessionListener (javax.servlet.http.HttpSessionListener)3 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)3 EventListenerList (org.eclipse.scout.rt.platform.util.EventListenerList)3 Bundle (org.osgi.framework.Bundle)3 BundleContext (org.osgi.framework.BundleContext)3 EntryListenerConfig (com.hazelcast.config.EntryListenerConfig)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Method (java.lang.reflect.Method)2 EventObject (java.util.EventObject)2 List (java.util.List)2 NamingException (javax.naming.NamingException)2 ServletRequestEvent (javax.servlet.ServletRequestEvent)2 HttpSessionIdListener (javax.servlet.http.HttpSessionIdListener)2