Search in sources :

Example 1 with TimerServiceImpl

use of org.jboss.as.ejb3.timerservice.TimerServiceImpl in project wildfly by wildfly.

the class EjbManagementDeploymentUnitProcessor method installManagementResource.

private void installManagementResource(ComponentConfiguration configuration, DeploymentUnit deploymentUnit) {
    final EJBComponentType type = EJBComponentType.getComponentType(configuration);
    PathAddress addr = getComponentAddress(type, configuration, deploymentUnit);
    final AbstractEJBComponentRuntimeHandler<?> handler = type.getRuntimeHandler();
    handler.registerComponent(addr, configuration.getComponentDescription().getStartServiceName());
    deploymentUnit.addToAttachmentList(EjbDeploymentAttachmentKeys.MANAGED_COMPONENTS, new InstalledComponent(type, addr));
    final DeploymentResourceSupport deploymentResourceSupport = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_RESOURCE_SUPPORT);
    deploymentResourceSupport.getDeploymentSubModel(EJB3Extension.SUBSYSTEM_NAME, addr.getLastElement());
    final EJBComponentDescription description = (EJBComponentDescription) configuration.getComponentDescription();
    if (description.isTimerServiceRequired()) {
        final PathAddress timerServiceAddress = PathAddress.pathAddress(addr.getLastElement(), EJB3SubsystemModel.TIMER_SERVICE_PATH);
        final TimerServiceResource timerServiceResource = ((TimerServiceImpl) description.getTimerService()).getResource();
        deploymentResourceSupport.registerDeploymentSubResource(EJB3Extension.SUBSYSTEM_NAME, timerServiceAddress, timerServiceResource);
    }
}
Also used : DeploymentResourceSupport(org.jboss.as.server.deployment.DeploymentResourceSupport) TimerServiceResource(org.jboss.as.ejb3.subsystem.deployment.TimerServiceResource) InstalledComponent(org.jboss.as.ejb3.subsystem.deployment.InstalledComponent) PathAddress(org.jboss.as.controller.PathAddress) EJBComponentType(org.jboss.as.ejb3.subsystem.deployment.EJBComponentType) TimerServiceImpl(org.jboss.as.ejb3.timerservice.TimerServiceImpl) EJBComponentDescription(org.jboss.as.ejb3.component.EJBComponentDescription)

Example 2 with TimerServiceImpl

use of org.jboss.as.ejb3.timerservice.TimerServiceImpl in project wildfly by wildfly.

the class DatabaseTimerPersistence method loadActiveTimers.

@Override
public List<TimerImpl> loadActiveTimers(final String timedObjectId, final TimerServiceImpl timerService) {
    if (!knownTimerIds.containsKey(timedObjectId)) {
        // if the timedObjectId has not being deployed
        EjbLogger.EJB3_TIMER_LOGGER.timerNotDeployed(timedObjectId);
        return Collections.emptyList();
    }
    String loadTimer = sql.getProperty(LOAD_ALL_TIMERS);
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
        connection = dataSource.getConnection();
        statement = connection.prepareStatement(loadTimer);
        statement.setString(1, timedObjectId);
        statement.setString(2, partition);
        resultSet = statement.executeQuery();
        final List<Holder> timers = new ArrayList<>();
        while (resultSet.next()) {
            String timerId = null;
            try {
                timerId = resultSet.getString(1);
                final Holder timerImpl = timerFromResult(resultSet, timerService, timerId, null);
                if (timerImpl != null) {
                    timers.add(timerImpl);
                } else {
                    final String deleteTimer = sql.getProperty(DELETE_TIMER);
                    try (PreparedStatement deleteStatement = connection.prepareStatement(deleteTimer)) {
                        deleteStatement.setString(1, resultSet.getString(2));
                        deleteStatement.setString(2, timerId);
                        deleteStatement.setString(3, partition);
                        deleteStatement.execute();
                    }
                }
            } catch (Exception e) {
                EjbLogger.EJB3_TIMER_LOGGER.timerReinstatementFailed(resultSet.getString(2), timerId, e);
            }
        }
        synchronized (this) {
            // ids should be always be not null
            Set<String> ids = knownTimerIds.get(timedObjectId);
            for (Holder timer : timers) {
                ids.add(timer.timer.getId());
            }
            for (Holder timer : timers) {
                if (timer.requiresReset) {
                    TimerImpl ret = timer.timer;
                    EjbLogger.DEPLOYMENT_LOGGER.loadedPersistentTimerInTimeout(ret.getId(), ret.getTimedObjectId());
                    if (ret.getNextExpiration() == null) {
                        ret.setTimerState(TimerState.CANCELED, null);
                        persistTimer(ret);
                    } else {
                        ret.setTimerState(TimerState.ACTIVE, null);
                        persistTimer(ret);
                    }
                }
            }
        }
        List<TimerImpl> ret = new ArrayList<>();
        for (Holder timer : timers) {
            ret.add(timer.timer);
        }
        return ret;
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        safeClose(resultSet);
        safeClose(statement);
        safeClose(connection);
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) ParseException(java.text.ParseException) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) HeuristicMixedException(javax.transaction.HeuristicMixedException) SQLException(java.sql.SQLException) RollbackException(javax.transaction.RollbackException) StartException(org.jboss.msc.service.StartException) IOException(java.io.IOException) NotSupportedException(javax.transaction.NotSupportedException) SystemException(javax.transaction.SystemException) ResultSet(java.sql.ResultSet) TimerImpl(org.jboss.as.ejb3.timerservice.TimerImpl)

Example 3 with TimerServiceImpl

use of org.jboss.as.ejb3.timerservice.TimerServiceImpl in project wildfly by wildfly.

the class LegacyFileStore method loadTimersFromFile.

static Map<String, TimerImpl> loadTimersFromFile(final String timedObjectId, final TimerServiceImpl timerService, String directory, MarshallerFactory factory, MarshallingConfiguration configuration) {
    final Map<String, TimerImpl> timers = new HashMap<String, TimerImpl>();
    Unmarshaller unmarshaller = null;
    try {
        final File file = new File(directory);
        if (!file.exists()) {
            // no timers exist yet
            return timers;
        } else if (!file.isDirectory()) {
            EJB3_TIMER_LOGGER.failToRestoreTimers(file);
            return timers;
        }
        File marker = new File(file, MIGRATION_MARKER);
        if (marker.exists()) {
            return timers;
        }
        unmarshaller = factory.createUnmarshaller(configuration);
        for (File timerFile : file.listFiles()) {
            if (timerFile.getName().endsWith(".xml")) {
                continue;
            }
            FileInputStream in = null;
            try {
                in = new FileInputStream(timerFile);
                unmarshaller.start(new InputStreamByteInput(in));
                final TimerEntity entity = unmarshaller.readObject(TimerEntity.class);
                // we load the legacy timer entity class, and turn it into a timer state
                TimerImpl.Builder builder;
                if (entity instanceof CalendarTimerEntity) {
                    CalendarTimerEntity c = (CalendarTimerEntity) entity;
                    final ScheduleExpression scheduleExpression = new ScheduleExpression();
                    scheduleExpression.second(c.getSecond()).minute(c.getMinute()).hour(c.getHour()).dayOfWeek(c.getDayOfWeek()).dayOfMonth(c.getDayOfMonth()).month(c.getMonth()).year(c.getYear()).start(c.getStartDate()).end(c.getEndDate()).timezone(c.getTimezone());
                    builder = CalendarTimer.builder().setScheduleExpression(scheduleExpression).setAutoTimer(c.isAutoTimer()).setTimeoutMethod(CalendarTimer.getTimeoutMethod(c.getTimeoutMethod(), timerService.getTimedObjectInvoker().getValue().getClassLoader()));
                } else {
                    builder = TimerImpl.builder();
                }
                builder.setId(entity.getId()).setTimedObjectId(entity.getTimedObjectId()).setInitialDate(entity.getInitialDate()).setRepeatInterval(entity.getInterval()).setNextDate(entity.getNextDate()).setPreviousRun(entity.getPreviousRun()).setInfo(entity.getInfo()).setTimerState(entity.getTimerState()).setPersistent(true);
                timers.put(entity.getId(), builder.build(timerService));
                unmarshaller.finish();
            } catch (Exception e) {
                EJB3_TIMER_LOGGER.failToRestoreTimersFromFile(timerFile, e);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        EJB3_TIMER_LOGGER.failToCloseFile(e);
                    }
                }
            }
        }
        if (!timers.isEmpty()) {
            Files.write(marker.toPath(), new Date().toString().getBytes(StandardCharsets.UTF_8));
        }
    } catch (Exception e) {
        EJB3_TIMER_LOGGER.failToRestoreTimersForObjectId(timedObjectId, e);
    } finally {
        VFSUtils.safeClose(unmarshaller);
    }
    return timers;
}
Also used : ScheduleExpression(javax.ejb.ScheduleExpression) HashMap(java.util.HashMap) CalendarTimerEntity(org.jboss.as.ejb3.timerservice.persistence.CalendarTimerEntity) TimerEntity(org.jboss.as.ejb3.timerservice.persistence.TimerEntity) CalendarTimerEntity(org.jboss.as.ejb3.timerservice.persistence.CalendarTimerEntity) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) Date(java.util.Date) InputStreamByteInput(org.jboss.marshalling.InputStreamByteInput) TimerImpl(org.jboss.as.ejb3.timerservice.TimerImpl) Unmarshaller(org.jboss.marshalling.Unmarshaller) File(java.io.File)

Example 4 with TimerServiceImpl

use of org.jboss.as.ejb3.timerservice.TimerServiceImpl in project wildfly by wildfly.

the class TimerServiceDeploymentProcessor method deploy.

@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION);
    final Module module = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.MODULE);
    final EjbJarMetaData ejbJarMetaData = deploymentUnit.getAttachment(EjbDeploymentAttachmentKeys.EJB_JAR_METADATA);
    // support for using capabilities to resolve service names
    CapabilityServiceSupport capabilityServiceSupport = deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT);
    ServiceName defaultTimerPersistenceService = getTimerPersistenceServiceName(capabilityServiceSupport, defaultTimerDataStore);
    final Map<String, ServiceName> timerPersistenceServices = new HashMap<String, ServiceName>();
    // if this is an EJB deployment then create an EJB module level TimerServiceRegistry which can be used by the timer services
    // of all EJB components that belong to this EJB module.
    final TimerServiceRegistry timerServiceRegistry = EjbDeploymentMarker.isEjbDeployment(deploymentUnit) ? new TimerServiceRegistry() : null;
    // determine the per-EJB timer persistence service names required
    if (ejbJarMetaData != null && ejbJarMetaData.getAssemblyDescriptor() != null) {
        List<TimerServiceMetaData> timerService = ejbJarMetaData.getAssemblyDescriptor().getAny(TimerServiceMetaData.class);
        if (timerService != null) {
            for (TimerServiceMetaData data : timerService) {
                if (data.getEjbName().equals("*")) {
                    defaultTimerPersistenceService = getTimerPersistenceServiceName(capabilityServiceSupport, data.getDataStoreName());
                } else {
                    timerPersistenceServices.put(data.getEjbName(), getTimerPersistenceServiceName(capabilityServiceSupport, data.getDataStoreName()));
                }
            }
        }
    }
    final ServiceName finalDefaultTimerPersistenceService = defaultTimerPersistenceService;
    for (final ComponentDescription componentDescription : moduleDescription.getComponentDescriptions()) {
        // set up the per-EJB timer persistence service dependencies
        if (componentDescription.isTimerServiceApplicable()) {
            if (componentDescription.isTimerServiceRequired()) {
                // the component has timeout methods, it needs a 'real' timer service
                final String deploymentName;
                if (moduleDescription.getDistinctName() == null || moduleDescription.getDistinctName().length() == 0) {
                    deploymentName = moduleDescription.getApplicationName() + "." + moduleDescription.getModuleName();
                } else {
                    deploymentName = moduleDescription.getApplicationName() + "." + moduleDescription.getModuleName() + "." + moduleDescription.getDistinctName();
                }
                ROOT_LOGGER.debugf("Installing timer service for component %s", componentDescription.getComponentName());
                componentDescription.getConfigurators().add(new ComponentConfigurator() {

                    @Override
                    public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
                        final EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) description;
                        // install the timed object invoker service
                        final ServiceName invokerServiceName = ejbComponentDescription.getServiceName().append(TimedObjectInvokerImpl.SERVICE_NAME);
                        final TimedObjectInvokerImpl invoker = new TimedObjectInvokerImpl(deploymentName, module);
                        context.getServiceTarget().addService(invokerServiceName, invoker).addDependency(componentDescription.getCreateServiceName(), EJBComponent.class, invoker.getEjbComponent()).install();
                        // install the timer create service for this EJB
                        final ServiceName serviceName = componentDescription.getServiceName().append(TimerServiceImpl.SERVICE_NAME);
                        final TimerServiceImpl service = new TimerServiceImpl(ejbComponentDescription.getScheduleMethods(), serviceName, timerServiceRegistry);
                        final ServiceBuilder<javax.ejb.TimerService> createBuilder = context.getServiceTarget().addService(serviceName, service);
                        createBuilder.addDependency(capabilityServiceSupport.getCapabilityServiceName(TimerServiceResourceDefinition.TIMER_SERVICE_CAPABILITY_NAME), Timer.class, service.getTimerInjectedValue());
                        createBuilder.addDependency(componentDescription.getCreateServiceName(), EJBComponent.class, service.getEjbComponentInjectedValue());
                        createBuilder.addDependency(timerServiceThreadPool, ExecutorService.class, service.getExecutorServiceInjectedValue());
                        if (timerPersistenceServices.containsKey(ejbComponentDescription.getEJBName())) {
                            createBuilder.addDependency(timerPersistenceServices.get(ejbComponentDescription.getEJBName()), TimerPersistence.class, service.getTimerPersistence());
                        } else {
                            createBuilder.addDependency(finalDefaultTimerPersistenceService, TimerPersistence.class, service.getTimerPersistence());
                        }
                        createBuilder.addDependency(invokerServiceName, TimedObjectInvoker.class, service.getTimedObjectInvoker());
                        createBuilder.install();
                        ejbComponentDescription.setTimerService(service);
                        // inject the timer service directly into the start service
                        configuration.getStartDependencies().add(new DependencyConfigurator<ComponentStartService>() {

                            @Override
                            public void configureDependency(final ServiceBuilder<?> serviceBuilder, final ComponentStartService service) throws DeploymentUnitProcessingException {
                                serviceBuilder.requires(serviceName);
                            }
                        });
                    }
                });
            } else {
                // the EJB is of a type that could have a timer service, but has no timer methods. just bind the non-functional timer service
                componentDescription.getConfigurators().add(new ComponentConfigurator() {

                    @Override
                    public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
                        final EJBComponentDescription ejbComponentDescription = (EJBComponentDescription) description;
                        final ServiceName nonFunctionalTimerServiceName = NonFunctionalTimerService.serviceNameFor(ejbComponentDescription);
                        final NonFunctionalTimerService nonFunctionalTimerService;
                        if (ejbComponentDescription instanceof StatefulComponentDescription) {
                            // for stateful beans, use a different error message that gets thrown from the NonFunctionalTimerService
                            nonFunctionalTimerService = new NonFunctionalTimerService(EjbLogger.ROOT_LOGGER.timerServiceMethodNotAllowedForSFSB(ejbComponentDescription.getComponentName()), timerServiceRegistry);
                        } else {
                            nonFunctionalTimerService = new NonFunctionalTimerService(EjbLogger.ROOT_LOGGER.ejbHasNoTimerMethods(), timerServiceRegistry);
                        }
                        // add the non-functional timer service as a MSC service
                        context.getServiceTarget().addService(nonFunctionalTimerServiceName, nonFunctionalTimerService).install();
                        // set the timer service in the EJB component
                        ejbComponentDescription.setTimerService(nonFunctionalTimerService);
                        // now we want the EJB component to depend on this non-functional timer service to start
                        configuration.getStartDependencies().add(new DependencyConfigurator<ComponentStartService>() {

                            @Override
                            public void configureDependency(ServiceBuilder<?> serviceBuilder, ComponentStartService service) throws DeploymentUnitProcessingException {
                                serviceBuilder.requires(nonFunctionalTimerServiceName);
                            }
                        });
                    }
                });
            }
        }
    }
}
Also used : DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) StatefulComponentDescription(org.jboss.as.ejb3.component.stateful.StatefulComponentDescription) EJBComponentDescription(org.jboss.as.ejb3.component.EJBComponentDescription) ComponentDescription(org.jboss.as.ee.component.ComponentDescription) HashMap(java.util.HashMap) ComponentConfigurator(org.jboss.as.ee.component.ComponentConfigurator) DependencyConfigurator(org.jboss.as.ee.component.DependencyConfigurator) DeploymentPhaseContext(org.jboss.as.server.deployment.DeploymentPhaseContext) EJBComponentDescription(org.jboss.as.ejb3.component.EJBComponentDescription) CapabilityServiceSupport(org.jboss.as.controller.capability.CapabilityServiceSupport) ServiceBuilder(org.jboss.msc.service.ServiceBuilder) EEModuleDescription(org.jboss.as.ee.component.EEModuleDescription) StatefulComponentDescription(org.jboss.as.ejb3.component.stateful.StatefulComponentDescription) TimedObjectInvokerImpl(org.jboss.as.ejb3.timerservice.TimedObjectInvokerImpl) TimerServiceImpl(org.jboss.as.ejb3.timerservice.TimerServiceImpl) TimerPersistence(org.jboss.as.ejb3.timerservice.persistence.TimerPersistence) ComponentStartService(org.jboss.as.ee.component.ComponentStartService) TimerServiceMetaData(org.jboss.as.ejb3.timerservice.TimerServiceMetaData) EjbJarMetaData(org.jboss.metadata.ejb.spec.EjbJarMetaData) TimedObjectInvoker(org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker) EJBComponent(org.jboss.as.ejb3.component.EJBComponent) ComponentConfiguration(org.jboss.as.ee.component.ComponentConfiguration) TimerServiceRegistry(org.jboss.as.ejb3.component.TimerServiceRegistry) Timer(java.util.Timer) ServiceName(org.jboss.msc.service.ServiceName) NonFunctionalTimerService(org.jboss.as.ejb3.timerservice.NonFunctionalTimerService) ExecutorService(java.util.concurrent.ExecutorService) Module(org.jboss.modules.Module) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit)

Example 5 with TimerServiceImpl

use of org.jboss.as.ejb3.timerservice.TimerServiceImpl in project wildfly by wildfly.

the class DatabaseTimerPersistence method timerFromResult.

private Holder timerFromResult(final ResultSet resultSet, final TimerServiceImpl timerService) throws SQLException {
    boolean calendarTimer = resultSet.getBoolean(24);
    final String nodeName = resultSet.getString(25);
    boolean requiresReset = false;
    TimerImpl.Builder builder = null;
    if (calendarTimer) {
        CalendarTimer.Builder cb = CalendarTimer.builder();
        builder = cb;
        //set calendar timer specifics first
        cb.setScheduleExprSecond(resultSet.getString(10));
        cb.setScheduleExprMinute(resultSet.getString(11));
        cb.setScheduleExprHour(resultSet.getString(12));
        cb.setScheduleExprDayOfWeek(resultSet.getString(13));
        cb.setScheduleExprDayOfMonth(resultSet.getString(14));
        cb.setScheduleExprMonth(resultSet.getString(15));
        cb.setScheduleExprYear(resultSet.getString(16));
        cb.setScheduleExprStartDate(resultSet.getTimestamp(17));
        cb.setScheduleExprEndDate(resultSet.getTimestamp(18));
        cb.setScheduleExprTimezone(resultSet.getString(19));
        cb.setAutoTimer(resultSet.getBoolean(20));
        final String clazz = resultSet.getString(21);
        final String methodName = resultSet.getString(22);
        if (methodName != null) {
            final String paramString = resultSet.getString(23);
            final String[] params = paramString == null || paramString.isEmpty() ? new String[0] : paramString.split(";");
            final Method timeoutMethod = CalendarTimer.getTimeoutMethod(new TimeoutMethod(clazz, methodName, params), timerService.getTimedObjectInvoker().getValue().getClassLoader());
            if (timeoutMethod == null) {
                EjbLogger.EJB3_TIMER_LOGGER.timerReinstatementFailed(resultSet.getString(2), resultSet.getString(1), new NoSuchMethodException());
                return null;
            }
            cb.setTimeoutMethod(timeoutMethod);
        }
    } else {
        builder = TimerImpl.builder();
    }
    builder.setId(resultSet.getString(1));
    builder.setTimedObjectId(resultSet.getString(2));
    builder.setInitialDate(resultSet.getTimestamp(3));
    builder.setRepeatInterval(resultSet.getLong(4));
    builder.setNextDate(resultSet.getTimestamp(5));
    builder.setPreviousRun(resultSet.getTimestamp(6));
    builder.setPrimaryKey(deSerialize(resultSet.getString(7)));
    builder.setInfo((Serializable) deSerialize(resultSet.getString(8)));
    builder.setTimerState(TimerState.valueOf(resultSet.getString(9)));
    builder.setPersistent(true);
    TimerImpl ret = builder.build(timerService);
    if (nodeName != null && (nodeName.equals(this.nodeName))) {
        if (ret.getState() == TimerState.IN_TIMEOUT || ret.getState() == TimerState.RETRY_TIMEOUT) {
            requiresReset = true;
        }
    }
    return new Holder(ret, requiresReset);
}
Also used : CalendarTimer(org.jboss.as.ejb3.timerservice.CalendarTimer) TimeoutMethod(org.jboss.as.ejb3.timerservice.persistence.TimeoutMethod) Method(java.lang.reflect.Method) TimeoutMethod(org.jboss.as.ejb3.timerservice.persistence.TimeoutMethod) TimerImpl(org.jboss.as.ejb3.timerservice.TimerImpl)

Aggregations

TimerImpl (org.jboss.as.ejb3.timerservice.TimerImpl)7 HashMap (java.util.HashMap)4 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 Method (java.lang.reflect.Method)2 Connection (java.sql.Connection)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 SQLException (java.sql.SQLException)2 Map (java.util.Map)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 ConcurrentMap (java.util.concurrent.ConcurrentMap)2 ScheduleExpression (javax.ejb.ScheduleExpression)2 SystemException (javax.transaction.SystemException)2 EJBComponentDescription (org.jboss.as.ejb3.component.EJBComponentDescription)2 CalendarTimer (org.jboss.as.ejb3.timerservice.CalendarTimer)2 TimerServiceImpl (org.jboss.as.ejb3.timerservice.TimerServiceImpl)2 TimeoutMethod (org.jboss.as.ejb3.timerservice.persistence.TimeoutMethod)2