Search in sources :

Example 1 with ApplicationEvent

use of org.glassfish.jersey.server.monitoring.ApplicationEvent in project jersey by jersey.

the class ApplicationHandler method initialize.

/**
     * Assumes the configuration field is initialized with a valid ResourceConfig.
     */
private ServerRuntime initialize(Iterable<ComponentProvider> componentProviders) {
    LOGGER.config(LocalizationMessages.INIT_MSG(Version.getBuildId()));
    // Lock original ResourceConfig.
    if (application instanceof ResourceConfig) {
        ((ResourceConfig) application).lock();
    }
    final boolean ignoreValidationErrors = ServerProperties.getValue(runtimeConfig.getProperties(), ServerProperties.RESOURCE_VALIDATION_IGNORE_ERRORS, Boolean.FALSE, Boolean.class);
    final boolean disableValidation = ServerProperties.getValue(runtimeConfig.getProperties(), ServerProperties.RESOURCE_VALIDATION_DISABLE, Boolean.FALSE, Boolean.class);
    final ResourceBag resourceBag;
    final ProcessingProviders processingProviders;
    final ComponentBag componentBag;
    ResourceModel resourceModel;
    CompositeApplicationEventListener compositeListener = null;
    // mark begin of validation phase
    Errors.mark();
    try {
        // AutoDiscoverable.
        if (!CommonProperties.getValue(runtimeConfig.getProperties(), RuntimeType.SERVER, CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, Boolean.FALSE, Boolean.class)) {
            runtimeConfig.configureAutoDiscoverableProviders(injectionManager);
        } else {
            runtimeConfig.configureForcedAutoDiscoverableProviders(injectionManager);
        }
        // Configure binders and features.
        runtimeConfig.configureMetaProviders(injectionManager);
        final ResourceBag.Builder resourceBagBuilder = new ResourceBag.Builder();
        // Adding programmatic resource models
        for (final Resource programmaticResource : runtimeConfig.getResources()) {
            resourceBagBuilder.registerProgrammaticResource(programmaticResource);
        }
        // Introspecting classes & instances
        for (final Class<?> c : runtimeConfig.getClasses()) {
            try {
                final Resource resource = Resource.from(c, disableValidation);
                if (resource != null) {
                    resourceBagBuilder.registerResource(c, resource);
                }
            } catch (final IllegalArgumentException ex) {
                LOGGER.warning(ex.getMessage());
            }
        }
        for (final Object o : runtimeConfig.getSingletons()) {
            try {
                final Resource resource = Resource.from(o.getClass(), disableValidation);
                if (resource != null) {
                    resourceBagBuilder.registerResource(o, resource);
                }
            } catch (final IllegalArgumentException ex) {
                LOGGER.warning(ex.getMessage());
            }
        }
        resourceBag = resourceBagBuilder.build();
        runtimeConfig.lock();
        componentBag = runtimeConfig.getComponentBag();
        final Class<ExternalRequestScope>[] extScopes = ServiceFinder.find(ExternalRequestScope.class, true).toClassArray();
        boolean extScopeBound = false;
        if (extScopes.length == 1) {
            for (final ComponentProvider p : componentProviders) {
                if (p.bind(extScopes[0], new HashSet<Class<?>>() {

                    {
                        add(ExternalRequestScope.class);
                    }
                })) {
                    extScopeBound = true;
                    break;
                }
            }
        } else if (extScopes.length > 1) {
            if (LOGGER.isLoggable(Level.WARNING)) {
                final StringBuilder scopeList = new StringBuilder("\n");
                for (final Class<ExternalRequestScope> ers : extScopes) {
                    scopeList.append("   ").append(ers.getTypeParameters()[0]).append('\n');
                }
                LOGGER.warning(LocalizationMessages.WARNING_TOO_MANY_EXTERNAL_REQ_SCOPES(scopeList.toString()));
            }
        }
        if (!extScopeBound) {
            injectionManager.register(new ServerRuntime.NoopExternalRequestScopeBinder());
        }
        bindProvidersAndResources(componentProviders, componentBag, resourceBag.classes, resourceBag.instances);
        for (final ComponentProvider componentProvider : componentProviders) {
            componentProvider.done();
        }
        final Iterable<ApplicationEventListener> appEventListeners = Providers.getAllProviders(injectionManager, ApplicationEventListener.class, new RankedComparator<>());
        if (appEventListeners.iterator().hasNext()) {
            compositeListener = new CompositeApplicationEventListener(appEventListeners);
            compositeListener.onEvent(new ApplicationEventImpl(ApplicationEvent.Type.INITIALIZATION_START, this.runtimeConfig, componentBag.getRegistrations(), resourceBag.classes, resourceBag.instances, null));
        }
        processingProviders = getProcessingProviders(componentBag);
        // initialize processing provider reference
        final GenericType<Ref<ProcessingProviders>> refGenericType = new GenericType<Ref<ProcessingProviders>>() {
        };
        final Ref<ProcessingProviders> refProcessingProvider = injectionManager.getInstance(refGenericType.getType());
        refProcessingProvider.set(processingProviders);
        resourceModel = new ResourceModel.Builder(resourceBag.getRootResources(), false).build();
        resourceModel = processResourceModel(resourceModel);
        if (!disableValidation) {
            final ComponentModelValidator validator = new ComponentModelValidator(injectionManager);
            validator.validate(resourceModel);
        }
        if (Errors.fatalIssuesFound() && !ignoreValidationErrors) {
            throw new ModelValidationException(LocalizationMessages.RESOURCE_MODEL_VALIDATION_FAILED_AT_INIT(), ModelErrors.getErrorsAsResourceModelIssues(true));
        }
    } finally {
        if (ignoreValidationErrors) {
            Errors.logErrors(true);
            // reset errors to the state before validation phase
            Errors.reset();
        } else {
            Errors.unmark();
        }
    }
    bindEnhancingResourceClasses(resourceModel, resourceBag, componentProviders);
    ExecutorProviders.createInjectionBindings(injectionManager);
    // initiate resource model into JerseyResourceContext
    final JerseyResourceContext jerseyResourceContext = injectionManager.getInstance(JerseyResourceContext.class);
    jerseyResourceContext.setResourceModel(resourceModel);
    msgBodyWorkers = injectionManager.getInstance(MessageBodyWorkers.class);
    // assembly request processing chain
    final ReferencesInitializer referencesInitializer = injectionManager.createAndInitialize(ReferencesInitializer.class);
    final ContainerFilteringStage preMatchRequestFilteringStage = new ContainerFilteringStage(processingProviders.getPreMatchFilters(), processingProviders.getGlobalResponseFilters());
    final ChainableStage<RequestProcessingContext> routingStage = Routing.forModel(resourceModel.getRuntimeResourceModel()).beanManager(injectionManager).resourceContext(jerseyResourceContext).configuration(runtimeConfig).entityProviders(msgBodyWorkers).processingProviders(processingProviders).buildStage();
    final ContainerFilteringStage resourceFilteringStage = new ContainerFilteringStage(processingProviders.getGlobalRequestFilters(), null);
    /**
         *  Root linear request acceptor. This is the main entry point for the whole request processing.
         */
    final Stage<RequestProcessingContext> rootStage = Stages.chain(referencesInitializer).to(preMatchRequestFilteringStage).to(routingStage).to(resourceFilteringStage).build(Routing.matchedEndpointExtractor());
    final ServerRuntime serverRuntime = injectionManager.createAndInitialize(ServerRuntime.Builder.class).build(rootStage, compositeListener, processingProviders);
    // Inject instances.
    for (final Object instance : componentBag.getInstances(ComponentBag.excludeMetaProviders(injectionManager))) {
        injectionManager.inject(instance);
    }
    for (final Object instance : resourceBag.instances) {
        injectionManager.inject(instance);
    }
    logApplicationInitConfiguration(injectionManager, resourceBag, processingProviders);
    if (compositeListener != null) {
        final ApplicationEvent initFinishedEvent = new ApplicationEventImpl(ApplicationEvent.Type.INITIALIZATION_APP_FINISHED, runtimeConfig, componentBag.getRegistrations(), resourceBag.classes, resourceBag.instances, resourceModel);
        compositeListener.onEvent(initFinishedEvent);
        final MonitoringContainerListener containerListener = injectionManager.getInstance(MonitoringContainerListener.class);
        containerListener.init(compositeListener, initFinishedEvent);
    }
    return serverRuntime;
}
Also used : JerseyResourceContext(org.glassfish.jersey.server.internal.JerseyResourceContext) ModelValidationException(org.glassfish.jersey.server.model.ModelValidationException) RequestProcessingContext(org.glassfish.jersey.server.internal.process.RequestProcessingContext) ResourceModel(org.glassfish.jersey.server.model.ResourceModel) ComponentModelValidator(org.glassfish.jersey.server.model.ComponentModelValidator) ApplicationEventImpl(org.glassfish.jersey.server.internal.monitoring.ApplicationEventImpl) CompositeApplicationEventListener(org.glassfish.jersey.server.internal.monitoring.CompositeApplicationEventListener) ApplicationEventListener(org.glassfish.jersey.server.monitoring.ApplicationEventListener) CompositeApplicationEventListener(org.glassfish.jersey.server.internal.monitoring.CompositeApplicationEventListener) MessageBodyWorkers(org.glassfish.jersey.message.MessageBodyWorkers) ComponentBag(org.glassfish.jersey.model.internal.ComponentBag) ExternalRequestScope(org.glassfish.jersey.server.spi.ExternalRequestScope) GenericType(javax.ws.rs.core.GenericType) ReferencesInitializer(org.glassfish.jersey.server.internal.process.ReferencesInitializer) MonitoringContainerListener(org.glassfish.jersey.server.internal.monitoring.MonitoringContainerListener) Resource(org.glassfish.jersey.server.model.Resource) ApplicationEvent(org.glassfish.jersey.server.monitoring.ApplicationEvent) Ref(org.glassfish.jersey.internal.util.collection.Ref) ComponentProvider(org.glassfish.jersey.server.spi.ComponentProvider) ProcessingProviders(org.glassfish.jersey.server.internal.ProcessingProviders)

Example 2 with ApplicationEvent

use of org.glassfish.jersey.server.monitoring.ApplicationEvent in project jersey by jersey.

the class MonitoringEventListener method onEvent.

@Override
public void onEvent(final ApplicationEvent event) {
    final ApplicationEvent.Type type = event.getType();
    switch(type) {
        case INITIALIZATION_START:
            break;
        case RELOAD_FINISHED:
        case INITIALIZATION_FINISHED:
            this.monitoringStatisticsProcessor = new MonitoringStatisticsProcessor(injectionManager, this);
            this.monitoringStatisticsProcessor.startMonitoringWorker();
            break;
        case DESTROY_FINISHED:
            if (monitoringStatisticsProcessor != null) {
                try {
                    monitoringStatisticsProcessor.shutDown();
                } catch (final InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new ProcessingException(LocalizationMessages.ERROR_MONITORING_SHUTDOWN_INTERRUPTED(), e);
                }
            }
            // onDestroy
            final List<DestroyListener> listeners = injectionManager.getAllInstances(DestroyListener.class);
            for (final DestroyListener listener : listeners) {
                try {
                    listener.onDestroy();
                } catch (final Exception e) {
                    LOGGER.log(Level.WARNING, LocalizationMessages.ERROR_MONITORING_STATISTICS_LISTENER_DESTROY(listener.getClass()), e);
                }
            }
            break;
    }
}
Also used : ApplicationEvent(org.glassfish.jersey.server.monitoring.ApplicationEvent) DestroyListener(org.glassfish.jersey.server.monitoring.DestroyListener) ProcessingException(javax.ws.rs.ProcessingException) ProcessingException(javax.ws.rs.ProcessingException)

Aggregations

ApplicationEvent (org.glassfish.jersey.server.monitoring.ApplicationEvent)2 ProcessingException (javax.ws.rs.ProcessingException)1 GenericType (javax.ws.rs.core.GenericType)1 Ref (org.glassfish.jersey.internal.util.collection.Ref)1 MessageBodyWorkers (org.glassfish.jersey.message.MessageBodyWorkers)1 ComponentBag (org.glassfish.jersey.model.internal.ComponentBag)1 JerseyResourceContext (org.glassfish.jersey.server.internal.JerseyResourceContext)1 ProcessingProviders (org.glassfish.jersey.server.internal.ProcessingProviders)1 ApplicationEventImpl (org.glassfish.jersey.server.internal.monitoring.ApplicationEventImpl)1 CompositeApplicationEventListener (org.glassfish.jersey.server.internal.monitoring.CompositeApplicationEventListener)1 MonitoringContainerListener (org.glassfish.jersey.server.internal.monitoring.MonitoringContainerListener)1 ReferencesInitializer (org.glassfish.jersey.server.internal.process.ReferencesInitializer)1 RequestProcessingContext (org.glassfish.jersey.server.internal.process.RequestProcessingContext)1 ComponentModelValidator (org.glassfish.jersey.server.model.ComponentModelValidator)1 ModelValidationException (org.glassfish.jersey.server.model.ModelValidationException)1 Resource (org.glassfish.jersey.server.model.Resource)1 ResourceModel (org.glassfish.jersey.server.model.ResourceModel)1 ApplicationEventListener (org.glassfish.jersey.server.monitoring.ApplicationEventListener)1 DestroyListener (org.glassfish.jersey.server.monitoring.DestroyListener)1 ComponentProvider (org.glassfish.jersey.server.spi.ComponentProvider)1