Search in sources :

Example 1 with UserContextWrapper

use of org.jaffa.modules.user.services.UserContextWrapper in project jaffa-framework by jaffa-projects.

the class DatabasePoller method poll.

/**
 * Polls the database for a row represented by the input domain object. This
 * will reload the row in a new UOW with paranoid locking, and then invoke
 * the process() method on the reloaded domain object.
 * @param domain The domain object.
 */
protected void poll(final IPersistent domain) {
    UserContextWrapper ucw = null;
    UOW uow = null;
    try {
        // Setup the user context based on the person who created the row in
        // the database.
        ucw = UserContextWrapperFactory.instance(findCreatedBy(domain));
        // Reload the input domain object in a new UOW with paranoid locking
        // NOTE: Another thread may have modified some flags on the
        // underlying record; in which case a
        // primary-key-based query will still reload the object. But we want
        // to avoid re-processing that object.
        // Hence re-apply the original filters
        uow = new UOW();
        final Criteria criteria = PersistentHelper.generateKeyCriteria(domain);
        customizeCriteria(criteria);
        criteria.setLocking(Criteria.LOCKING_PARANOID);
        final Iterator<IPersistent> i = uow.query(criteria).iterator();
        if (i.hasNext()) {
            process(i.next());
            uow.commit();
        } else {
            LOGGER.error(this.getClass().getSimpleName() + ": Unable to reload domain object. It may already have been processed by another thread. " + domain);
        }
    } catch (Exception e) {
        if (ExceptionHelper.extractException(e, LockedApplicationException.class) != null) {
            LOGGER.error(this.getClass().getSimpleName() + ": Error in reloading domain object. It may be locked by another thread. " + domain, e);
        } else
            LOGGER.error(this.getClass().getSimpleName() + ": Error in polling domain object " + domain, e);
    } finally {
        try {
            if (uow != null)
                uow.rollback();
        } catch (Exception e) {
            LOGGER.error(this.getClass().getSimpleName() + ": Error in closing UOW", e);
        }
        if (ucw != null)
            ucw.unsetContext();
    }
}
Also used : IPersistent(org.jaffa.persistence.IPersistent) UserContextWrapper(org.jaffa.modules.user.services.UserContextWrapper) Criteria(org.jaffa.persistence.Criteria) UOW(org.jaffa.persistence.UOW) FrameworkException(org.jaffa.exceptions.FrameworkException) LockedApplicationException(org.jaffa.persistence.engines.jdbcengine.LockedApplicationException) ApplicationException(org.jaffa.exceptions.ApplicationException)

Example 2 with UserContextWrapper

use of org.jaffa.modules.user.services.UserContextWrapper in project jaffa-framework by jaffa-projects.

the class TransactionInvokerJob method execute.

/**
 * Called by the <code>{@link org.quartz.Scheduler}</code> when a
 * <code>{@link org.quartz.Trigger}</code> fires that is associated with
 * the <code>Job</code>.
 *
 * @param context The Quartz JobExecutionContext structure used to retrieve job specific information
 * @throws JobExecutionException if there is an exception while executing the job.
 */
public void execute(JobExecutionContext context) throws JobExecutionException {
    String scheduledTaskId = null;
    String userId = null;
    Object businessObject = null;
    UserContextWrapper ucw = null;
    try {
        List<JobExecutionContext> jobs = context.getScheduler().getCurrentlyExecutingJobs();
        if (log.isDebugEnabled())
            log.debug("Job Size:- " + jobs.size());
        if (log.isDebugEnabled())
            log.debug("Starting Checking Scheduled Tasks");
        for (JobExecutionContext job : jobs) {
            if (log.isDebugEnabled()) {
                log.debug("Job Trigger: " + job.getTrigger());
                log.debug("Context Trigger: " + context.getTrigger());
            }
            if (job.getTrigger().equals(context.getTrigger()) && !job.getJobInstance().equals(this)) {
                if (log.isDebugEnabled())
                    log.debug("There's another instance running, so leaving" + this);
                return;
            }
        }
        // Obtain the Task from the Job details
        ScheduledTask task = QuartzSchedulerHelper.jobDataMapToTask(context.getJobDetail().getJobDataMap());
        if (log.isDebugEnabled())
            log.debug("Executing " + task);
        scheduledTaskId = task.getScheduledTaskId();
        userId = task.getRunAs();
        businessObject = task.getBusinessObject();
        // Switch the thread to use the context the "RunAs" is set to, so this propergates when creating the JaffaTransaction/JMS records to process
        if (log.isDebugEnabled())
            log.debug("Set up use context. RunAs = " + userId);
        ucw = UserContextWrapperFactory.instance(userId);
        // Sets Log4J's MDC to enable BusinessEventLogging
        MDC.put(BusinessEventLogMeta.SCHEDULED_TASK_ID, scheduledTaskId);
        MDC.put(BusinessEventLogMeta.LOGGED_BY, userId);
        // Set up some Thread Level variables for the Jaffa Transaction. This will help distinguish between a Schedule invoke transaction and any others
        ContextManagerFactory.instance().setProperty(CONTEXT_SCHEDULED_TASK_ID, scheduledTaskId);
        // Send a Jaffa Transaction message
        if (log.isInfoEnabled())
            log.info(MessageHelper.findMessage("label.Jaffa.Scheduler.JaffaTransactionInvokerJob.start", new Object[] { businessObject, userId, scheduledTaskId }));
        UOWHelper.addMessage(businessObject);
        if (log.isInfoEnabled())
            log.info(MessageHelper.findMessage("label.Jaffa.Scheduler.JaffaTransactionInvokerJob.success", new Object[] { businessObject, userId, scheduledTaskId }));
    } catch (Exception e) {
        log.error(MessageHelper.findMessage("error.Jaffa.Scheduler.JaffaTransactionInvokerJob.error", new Object[] { businessObject, userId, scheduledTaskId }), e);
        throw new JobExecutionException(e);
    } finally {
        // Unset the Logging context
        MDC.remove(BusinessEventLogMeta.SCHEDULED_TASK_ID);
        MDC.remove(BusinessEventLogMeta.LOGGED_BY);
        // Clear context for this user
        if (ucw != null) {
            if (log.isDebugEnabled())
                log.debug("Unset user context");
            ucw.unsetContext();
        }
    }
}
Also used : JobExecutionException(org.quartz.JobExecutionException) UserContextWrapper(org.jaffa.modules.user.services.UserContextWrapper) JobExecutionContext(org.quartz.JobExecutionContext) ScheduledTask(org.jaffa.modules.scheduler.services.ScheduledTask) JobExecutionException(org.quartz.JobExecutionException)

Example 3 with UserContextWrapper

use of org.jaffa.modules.user.services.UserContextWrapper in project jaffa-framework by jaffa-projects.

the class GraphCreateThread method run.

@Override
public void run() {
    UserContextWrapper ucw = null;
    ApplicationExceptions appExps = new ApplicationExceptions();
    try {
        synchronized (this) {
            ucw = UserContextWrapperFactory.instance(userId);
        }
        List<GraphDataObject> graphs = new ArrayList<GraphDataObject>();
        graphs.add(this.graph);
        GraphService service = (GraphService) serviceClazz.newInstance();
        Object graphArray = Array.newInstance(graph.getClass(), 1);
        Array.set(graphArray, 0, graph);
        Method m = serviceClazz.getDeclaredMethod("update", graphArray.getClass());
        GraphUpdateResponse[] responses = (GraphUpdateResponse[]) m.invoke(serviceClazz.newInstance(), graphArray);
        if (responses != null && responses.length > 0) {
            for (GraphUpdateResponse response : responses) {
                ServiceError[] faults = response.getErrors();
                if (faults != null && faults.length > 0) {
                    for (ServiceError fault : faults) {
                        appExps.add(new ApplicationException("error", new String[] { fault.getLocalizedMessage() }));
                    }
                }
                synchronized (this) {
                    test.getUpdateResponses().add(response);
                }
            }
        }
        if (appExps.size() > 0)
            throw appExps;
    } catch (ApplicationExceptions | UserSessionSetupException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        log.error(e);
    } finally {
        synchronized (this) {
            if (ucw != null)
                ucw.unsetContext();
        }
    }
}
Also used : ServiceError(org.jaffa.soa.graph.ServiceError) ApplicationExceptions(org.jaffa.exceptions.ApplicationExceptions) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) UserSessionSetupException(org.jaffa.presentation.portlet.session.UserSessionSetupException) InvocationTargetException(java.lang.reflect.InvocationTargetException) GraphService(org.jaffa.soa.dataaccess.GraphService) ApplicationException(org.jaffa.exceptions.ApplicationException) UserContextWrapper(org.jaffa.modules.user.services.UserContextWrapper) GraphDataObject(org.jaffa.soa.graph.GraphDataObject) GraphUpdateResponse(org.jaffa.soa.graph.GraphUpdateResponse)

Example 4 with UserContextWrapper

use of org.jaffa.modules.user.services.UserContextWrapper in project jaffa-framework by jaffa-projects.

the class TestThread method run.

@Override
public void run() {
    UOW uow = null;
    UserContextWrapper ucw = null;
    try {
        synchronized (this) {
            ucw = UserContextWrapperFactory.instance(userId);
        }
        uow = new UOW();
        HeaderParam headerParam = new HeaderParam(soaEventParamName, soaEventParamValue);
        RaiseEventService raiseEventService = new RaiseEventService();
        List<HeaderParam> headerParamList = new ArrayList<HeaderParam>();
        headerParamList.add(headerParam);
        raiseEventService.raiseSoaEvent(uow, eventName, eventDesc, null, headerParamList);
        uow.commit();
    } catch (ApplicationExceptions applicationExceptions) {
        applicationExceptions.printStackTrace();
    } catch (FrameworkException fe) {
        fe.printStackTrace();
    } catch (ApplicationException ae) {
        ae.printStackTrace();
    } finally {
        synchronized (this) {
            if (ucw != null)
                ucw.unsetContext();
        }
        if (uow != null) {
            try {
                uow.rollback();
            } catch (Exception e) {
                e.printStackTrace();
            // the uow cannot be rolled back
            }
        }
    }
}
Also used : HeaderParam(org.jaffa.modules.messaging.services.HeaderParam) ApplicationExceptions(org.jaffa.exceptions.ApplicationExceptions) ApplicationException(org.jaffa.exceptions.ApplicationException) FrameworkException(org.jaffa.exceptions.FrameworkException) UserContextWrapper(org.jaffa.modules.user.services.UserContextWrapper) RaiseEventService(org.jaffa.soa.services.RaiseEventService) ArrayList(java.util.ArrayList) UOW(org.jaffa.persistence.UOW) FrameworkException(org.jaffa.exceptions.FrameworkException) ApplicationException(org.jaffa.exceptions.ApplicationException)

Example 5 with UserContextWrapper

use of org.jaffa.modules.user.services.UserContextWrapper in project jaffa-framework by jaffa-projects.

the class DatabasePoller method poll.

/**
 * Polls the database for a row represented by the input domain object. This
 * will reload the row in a new UOW with paranoid locking, and then invoke
 * the process() method on the reloaded domain object.
 * @param domain The domain object.
 */
protected void poll(final IPersistent domain) {
    UserContextWrapper ucw = null;
    UOW uow = null;
    try {
        // Setup the user context based on the person who created the row in
        // the database.
        ucw = UserContextWrapperFactory.instance(findCreatedBy(domain));
        // Reload the input domain object in a new UOW with paranoid locking
        // NOTE: Another thread may have modified some flags on the
        // underlying record; in which case a
        // primary-key-based query will still reload the object. But we want
        // to avoid re-processing that object.
        // Hence re-apply the original filters
        uow = new UOW();
        final Criteria criteria = PersistentHelper.generateKeyCriteria(domain);
        customizeCriteria(criteria);
        criteria.setLocking(Criteria.LOCKING_PARANOID);
        final Iterator<IPersistent> i = uow.query(criteria).iterator();
        if (i.hasNext()) {
            process(i.next());
            uow.commit();
        } else {
            LOGGER.error(this.getClass().getSimpleName() + ": Unable to reload domain object. It may already have been processed by another thread. " + domain);
        }
    } catch (Exception e) {
        if (ExceptionHelper.extractException(e, LockedApplicationException.class) != null) {
            LOGGER.error(this.getClass().getSimpleName() + ": Error in reloading domain object. It may be locked by another thread. " + domain, e);
        } else
            LOGGER.error(this.getClass().getSimpleName() + ": Error in polling domain object " + domain, e);
    } finally {
        try {
            if (uow != null)
                uow.rollback();
        } catch (Exception e) {
            LOGGER.error(this.getClass().getSimpleName() + ": Error in closing UOW", e);
        }
        if (ucw != null)
            ucw.unsetContext();
    }
}
Also used : IPersistent(org.jaffa.persistence.IPersistent) UserContextWrapper(org.jaffa.modules.user.services.UserContextWrapper) Criteria(org.jaffa.persistence.Criteria) UOW(org.jaffa.persistence.UOW) FrameworkException(org.jaffa.exceptions.FrameworkException) LockedApplicationException(org.jaffa.persistence.engines.jdbcengine.LockedApplicationException) ApplicationException(org.jaffa.exceptions.ApplicationException)

Aggregations

UserContextWrapper (org.jaffa.modules.user.services.UserContextWrapper)6 ApplicationException (org.jaffa.exceptions.ApplicationException)5 FrameworkException (org.jaffa.exceptions.FrameworkException)4 UOW (org.jaffa.persistence.UOW)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 ArrayList (java.util.ArrayList)2 ApplicationExceptions (org.jaffa.exceptions.ApplicationExceptions)2 Criteria (org.jaffa.persistence.Criteria)2 IPersistent (org.jaffa.persistence.IPersistent)2 LockedApplicationException (org.jaffa.persistence.engines.jdbcengine.LockedApplicationException)2 UserSessionSetupException (org.jaffa.presentation.portlet.session.UserSessionSetupException)2 Method (java.lang.reflect.Method)1 MessagingException (javax.mail.MessagingException)1 HeaderParam (org.jaffa.modules.messaging.services.HeaderParam)1 ScheduledTask (org.jaffa.modules.scheduler.services.ScheduledTask)1 GraphService (org.jaffa.soa.dataaccess.GraphService)1 GraphDataObject (org.jaffa.soa.graph.GraphDataObject)1 GraphUpdateResponse (org.jaffa.soa.graph.GraphUpdateResponse)1 ServiceError (org.jaffa.soa.graph.ServiceError)1 RaiseEventService (org.jaffa.soa.services.RaiseEventService)1