Search in sources :

Example 11 with TaskHandlerException

use of org.motechproject.tasks.exception.TaskHandlerException in project motech by motech.

the class TaskActionExecutor method execute.

/**
 * Executes the action for the given task.
 *
 * @param task  the task for which its action should be executed, not null
 * @param actionInformation  the information about the action, not null
 * @param actionIndex the order of the task action
 * @param taskContext  the context of the current task execution, not null
 * @param activityId the ID of the activity associated with this execution
 * @throws TaskHandlerException when the task couldn't be executed
 */
@Transactional
public void execute(Task task, TaskActionInformation actionInformation, Integer actionIndex, TaskContext taskContext, long activityId) throws TaskHandlerException {
    LOGGER.info("Executing task action: {} from task: {}", actionInformation.getName(), task.getName());
    KeyEvaluator keyEvaluator = new KeyEvaluator(taskContext);
    ActionEvent action = getActionEvent(actionInformation);
    Map<String, Object> parameters = createParameters(actionInformation, action, keyEvaluator);
    addTriggerParameters(task, action, parameters, taskContext.getTriggerParameters());
    LOGGER.debug("Parameters created: {} for task action: {}", parameters.toString(), action.getName());
    if (action.hasService() && bundleContext != null) {
        if (callActionServiceMethod(action, actionIndex, parameters, taskContext)) {
            LOGGER.info("Action: {} from task: {} was executed through an OSGi service call", actionInformation.getName(), task.getName());
            postExecutionHandler.handleActionExecuted(taskContext.getTriggerParameters(), taskContext.getMetadata(), activityId);
            return;
        }
        LOGGER.info("There is no service: {}", action.getServiceInterface());
        activityService.addWarning(task, "task.warning.serviceUnavailable", action.getServiceInterface());
    }
    if (!action.hasSubject()) {
        throw new TaskHandlerException(ACTION, "task.error.cantExecuteAction");
    } else {
        eventRelay.sendEventMessage(new MotechEvent(action.getSubject(), parameters, TasksEventCallbackService.TASKS_EVENT_CALLBACK_NAME, taskContext.getMetadata()));
        LOGGER.info("Event: {} was sent", action.getSubject());
    }
}
Also used : TaskHandlerException(org.motechproject.tasks.exception.TaskHandlerException) ActionEvent(org.motechproject.tasks.domain.mds.channel.ActionEvent) MotechEvent(org.motechproject.event.MotechEvent) KeyEvaluator(org.motechproject.tasks.service.util.KeyEvaluator) Transactional(org.springframework.transaction.annotation.Transactional)

Example 12 with TaskHandlerException

use of org.motechproject.tasks.exception.TaskHandlerException in project motech by motech.

the class TaskActionExecutor method createParameters.

private Map<String, Object> createParameters(TaskActionInformation info, ActionEvent action, KeyEvaluator keyEvaluator) throws TaskHandlerException {
    SortedSet<ActionParameter> actionParameters = action.getActionParameters();
    Map<String, Object> parameters = new HashMap<>(actionParameters.size());
    for (ActionParameter actionParameter : actionParameters) {
        String key = actionParameter.getKey();
        if (info.getValues().containsKey(key)) {
            String template = info.getValues().get(key);
            if (template == null) {
                throw new TaskHandlerException(TRIGGER, "task.error.templateNull", key, action.getDisplayName());
            }
            switch(actionParameter.getType()) {
                case LIST:
                    parameters.put(key, convertToList((List<String>) LIST.parse(template), keyEvaluator));
                    break;
                case MAP:
                    parameters.put(key, convertToMap(template, keyEvaluator));
                    break;
                default:
                    try {
                        String userInput = keyEvaluator.evaluateTemplateString(template);
                        Object obj = actionParameter.getType().parse(userInput);
                        parameters.put(key, obj);
                    } catch (MotechException ex) {
                        throw new TaskHandlerException(TRIGGER, ex.getMessage(), ex, key);
                    }
            }
        } else {
            if (actionParameter.isRequired()) {
                throw new TaskHandlerException(TRIGGER, "task.error.taskActionNotContainsField", action.getDisplayName(), key);
            } else if (actionParameter.getType() == MAP) {
                parameters.put(key, new HashMap<>());
            } else if (actionParameter.getType() == LIST) {
                parameters.put(key, new ArrayList<>());
            } else {
                parameters.put(key, null);
            }
        }
    }
    return parameters;
}
Also used : MotechException(org.motechproject.commons.api.MotechException) TaskHandlerException(org.motechproject.tasks.exception.TaskHandlerException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) List(java.util.List) ActionParameter(org.motechproject.tasks.domain.mds.channel.ActionParameter)

Example 13 with TaskHandlerException

use of org.motechproject.tasks.exception.TaskHandlerException in project motech by motech.

the class TaskFilterExecutor method checkFilters.

/**
 * Checks whether task with the given context matches the given filters.
 *
 * @param filters  the filters, null returns true
 * @param logicalOperator  the logical operator
 * @param taskContext  the task context, not null
 * @return true if the task matches the filters
 * @throws TaskHandlerException if there were problems while handling task
 */
public boolean checkFilters(List<Filter> filters, LogicalOperator logicalOperator, TaskContext taskContext) throws TaskHandlerException {
    LOGGER.debug("Checking if task: {} matches the filters", taskContext.getTask().getName());
    Map<String, Object> parameters = taskContext.getTriggerParameters();
    if (isEmpty(filters) || parameters == null) {
        return true;
    }
    boolean filterCheck = false;
    for (Filter filter : filters) {
        KeyInformation key = parse(filter.getKey());
        Object value;
        try {
            KeyEvaluator keyEvaluator = new KeyEvaluator(taskContext);
            value = keyEvaluator.getManipulatedValue(key);
        } catch (TaskHandlerException e) {
            if (TaskFailureCause.DATA_SOURCE.equals(e.getFailureCause())) {
                // data source lookups disable the task
                throw e;
            }
            // trigger parameter lookups don't disable the task
            value = null;
            LOGGER.error("Unable to retrieve value for filter", e);
        } catch (RuntimeException e) {
            value = null;
            LOGGER.error("Unable to retrieve value for filter", e);
        }
        filterCheck = value != null && checkValue(filter, value);
        if (!filter.isNegationOperator()) {
            filterCheck = !filterCheck;
        }
        LOGGER.debug("Result of checking filter: {} for task: {} is: {}", filter.getDisplayName(), taskContext.getTask().getName(), filterCheck);
        if (isFilterConditionFulfilled(filterCheck, logicalOperator)) {
            LOGGER.debug("Filters condition is fulfilled, because logicalOperator is: {} and filters checking has already: {} value", logicalOperator, filterCheck);
            break;
        }
    }
    LOGGER.info("Result of checking filters for task: {} is: {}", taskContext.getTask().getName(), filterCheck);
    return filterCheck;
}
Also used : TaskHandlerException(org.motechproject.tasks.exception.TaskHandlerException) Filter(org.motechproject.tasks.domain.mds.task.Filter) KeyInformation(org.motechproject.tasks.domain.KeyInformation)

Example 14 with TaskHandlerException

use of org.motechproject.tasks.exception.TaskHandlerException in project motech by motech.

the class TaskActivityServiceImplTest method shouldAddErrorActivityWithTaskException.

@Test
public void shouldAddErrorActivityWithTaskException() {
    when(taskActivitiesDataService.findById(TASK_ACTIVITY_ID)).thenReturn(createInProgress());
    String messageKey = "error.notFoundTrigger";
    TaskHandlerException exception = new TaskHandlerException(TRIGGER, messageKey, ERROR_FIELD.get(0));
    ArgumentCaptor<TaskActivity> captor = ArgumentCaptor.forClass(TaskActivity.class);
    activityService.addFailedExecution(TASK_ACTIVITY_ID, exception);
    verify(taskActivitiesDataService).update(captor.capture());
    assertActivity(messageKey, ERROR_FIELD, TASK_ID, TaskActivityType.ERROR, getStackTrace(exception), null, captor.getValue());
}
Also used : TaskHandlerException(org.motechproject.tasks.exception.TaskHandlerException) TaskActivity(org.motechproject.tasks.domain.mds.task.TaskActivity) Test(org.junit.Test)

Example 15 with TaskHandlerException

use of org.motechproject.tasks.exception.TaskHandlerException in project motech by motech.

the class TaskTriggerHandlerTest method shouldHandleUnrecognizedError.

@Test
public void shouldHandleUnrecognizedError() throws Exception {
    setTriggerEvent();
    setActionEvent();
    actionEvent.setServiceInterface("TestService");
    actionEvent.setServiceMethod("abc");
    when(taskService.findActiveTasksForTriggerSubject(TRIGGER_SUBJECT)).thenReturn(tasks);
    when(taskService.getActionEventFor(task.getActions().get(0))).thenThrow(new RuntimeException());
    handler.setBundleContext(bundleContext);
    handler.handle(createEvent());
    ArgumentCaptor<TaskHandlerException> exceptionArgumentCaptor = ArgumentCaptor.forClass(TaskHandlerException.class);
    verify(postExecutionHandler).handleError(eq(createEventParameters()), anyMap(), eq(task), exceptionArgumentCaptor.capture(), eq(TASK_ACTIVITY_ID));
    TaskHandlerException handlerException = exceptionArgumentCaptor.getValue();
    assertEquals("task.error.unrecognizedError", handlerException.getMessage());
    assertEquals(TaskFailureCause.TRIGGER, handlerException.getFailureCause());
    verify(postExecutionHandler, never()).handleActionExecuted(eq(createEventParameters()), anyMap(), eq(TASK_ACTIVITY_ID));
}
Also used : TaskHandlerException(org.motechproject.tasks.exception.TaskHandlerException) Test(org.junit.Test)

Aggregations

TaskHandlerException (org.motechproject.tasks.exception.TaskHandlerException)15 Transactional (org.springframework.transaction.annotation.Transactional)4 Test (org.junit.Test)3 TaskActivity (org.motechproject.tasks.domain.mds.task.TaskActivity)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 MotechException (org.motechproject.commons.api.MotechException)2 KeyInformation (org.motechproject.tasks.domain.KeyInformation)2 FilterSet (org.motechproject.tasks.domain.mds.task.FilterSet)2 KeyEvaluator (org.motechproject.tasks.service.util.KeyEvaluator)2 TaskFilterExecutor (org.motechproject.tasks.service.util.TaskFilterExecutor)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 List (java.util.List)1 DataProvider (org.motechproject.commons.api.DataProvider)1 MotechEvent (org.motechproject.event.MotechEvent)1 ActionEvent (org.motechproject.tasks.domain.mds.channel.ActionEvent)1 ActionParameter (org.motechproject.tasks.domain.mds.channel.ActionParameter)1 DataSource (org.motechproject.tasks.domain.mds.task.DataSource)1 Filter (org.motechproject.tasks.domain.mds.task.Filter)1