@Override
 public void unenroll(Enrollment enrollment) {
   unscheduleJobs(enrollment);
   enrollment.setStatus(UNENROLLED);
   allEnrollments.update(enrollment);
   eventRelay.sendEventMessage(
       new UnenrolledUserEvent(enrollment.getExternalId(), enrollment.getScheduleName())
           .toMotechEvent());
 }
Exemplo n.º 2
0
    private void scheduleTaskRetry(Task task, Map<String, Object> parameters) {
        Map<String, Object> eventParameters = new HashMap<>();
        eventParameters.putAll(parameters);
        Map<String, Object> metadata = new HashMap<>();
        metadata.put(TASK_ID, task.getId());
        metadata.put(JOB_START, task.getRetryIntervalInMilliseconds() / 1000);
        metadata.put(JOB_SUBJECT, task.getTrigger().getEffectiveListenerRetrySubject());
        metadata.put(TASK_RETRY_NUMBER, parameters.get(TASK_RETRY_NUMBER));

        eventRelay.sendEventMessage(new MotechEvent(SCHEDULE_REPEATING_JOB, eventParameters, null, metadata));
    }
Exemplo n.º 3
0
  @Override
  public void saveSettingsFile(MultipartFile configFile) {
    Properties settings = loadMultipartFileIntoProperties(configFile);
    configurationService.savePlatformSettings(settings);

    Map<String, Object> params = new HashMap<>();
    params.put(ConfigurationConstants.SETTINGS, settings);

    MotechEvent platformSettingsChangedEvent =
        new MotechEvent(ConfigurationConstants.PLATFORM_SETTINGS_CHANGED_EVENT_SUBJECT, params);
    eventRelay.sendEventMessage(platformSettingsChangedEvent);
  }
  @Override
  public void onFailure(LiveException e) {
    MotechEvent event = callRequest.getOnFailureEvent();

    if (event != null) {
      CallDetailRecord cdr = new CallDetailRecord(CallDisposition.FAILED, e.getMessage());

      Map<String, Object> parameters = event.getParameters();
      parameters.put(IVREventDelegate.CALL_DETAIL_RECORD_KEY, cdr);

      eventRelay.sendEventMessage(event);
    }
  }
Exemplo n.º 5
0
  @Override
  public void savePlatformSettings(List<Settings> settings) {
    for (Settings s : settings) {
      savePlatformSettings(s);
    }

    Map<String, Object> params = new HashMap<>();
    params.put(ConfigurationConstants.SETTINGS, settings);

    MotechEvent platformSettingsChangedEvent =
        new MotechEvent(ConfigurationConstants.PLATFORM_SETTINGS_CHANGED_EVENT_SUBJECT, params);
    eventRelay.sendEventMessage(platformSettingsChangedEvent);
  }
Exemplo n.º 6
0
 public void dispatch(String aggregationRuleName) {
   AggregationRuleRecord aggregationRule =
       aggregationRuleRecordService.findByName(aggregationRuleName);
   List<Aggregation> aggregations =
       aggregationRecordService.findAllAggregations(aggregationRule.getName());
   if (log.isInfoEnabled()) {
     log.info(format("publishing aggregation for rule: %s", aggregationRuleName));
   }
   for (Aggregation aggregation : aggregations) {
     eventRelay.sendEventMessage(
         new AggregationEvent(aggregationRule, aggregation).toMotechEvent());
     aggregationRecordService.removeByAggregation(aggregation);
   }
 }
Exemplo n.º 7
0
  @Override
  public void savePlatformSettings(Settings settings) {
    for (SettingsOption option : settings.getSettings()) {
      Object val = option.getValue();
      configurationService.setPlatformSetting(
          option.getKey(), val == null ? null : String.valueOf(val));
    }

    Map<String, Object> params = new HashMap<>();
    params.put(ConfigurationConstants.SETTINGS, settings);

    MotechEvent platformSettingsChangedEvent =
        new MotechEvent(ConfigurationConstants.BUNDLE_SETTINGS_CHANGED_EVENT_SUBJECT, params);
    eventRelay.sendEventMessage(platformSettingsChangedEvent);
  }
  @Override
  public String enroll(
      String externalId,
      String scheduleName,
      String startingMilestoneName,
      DateTime referenceDateTime,
      DateTime enrollmentDateTime,
      Time preferredAlertTime,
      Map<String, String> metadata) {
    Schedule schedule = allSchedules.getByName(scheduleName);
    Enrollment enrollment =
        new Enrollment()
            .setExternalId(externalId)
            .setSchedule(schedule)
            .setCurrentMilestoneName(startingMilestoneName)
            .setStartOfSchedule(referenceDateTime)
            .setEnrolledOn(enrollmentDateTime)
            .setPreferredAlertTime(preferredAlertTime)
            .setStatus(EnrollmentStatus.ACTIVE)
            .setMetadata(metadata);

    if (schedule.hasExpiredSince(
        enrollment.getCurrentMilestoneStartDate(), startingMilestoneName)) {
      enrollment.setStatus(EnrollmentStatus.DEFAULTED);
    }

    Enrollment activeEnrollment = allEnrollments.getActiveEnrollment(externalId, scheduleName);
    if (activeEnrollment == null) {
      allEnrollments.add(enrollment);
      eventRelay.sendEventMessage(
          new EnrolledUserEvent(
                  enrollment.getExternalId(),
                  enrollment.getScheduleName(),
                  enrollment.getPreferredAlertTime(),
                  referenceDateTime,
                  enrollmentDateTime,
                  enrollment.getCurrentMilestoneName())
              .toMotechEvent());
    } else {
      unscheduleJobs(activeEnrollment);
      enrollment = activeEnrollment.copyFrom(enrollment);
      allEnrollments.update(enrollment);
    }

    scheduleJobs(enrollment);
    return enrollment.getId();
  }
Exemplo n.º 9
0
  /**
   * 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
   */
  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());
    }
  }
  @Override
  public void onBusy(AsteriskChannel asteriskChannel) {
    MotechEvent event = callRequest.getOnBusyEvent();

    if (event != null) {
      org.asteriskjava.live.CallDetailRecord aCDR = asteriskChannel.getCallDetailRecord();
      CallDetailRecord cdr =
          new CallDetailRecord(
              aCDR.getStartDate(),
              aCDR.getEndDate(),
              aCDR.getAnswerDate(),
              translateDisposition(aCDR.getDisposition()),
              aCDR.getDuration());

      Map<String, Object> parameters = event.getParameters();
      parameters.put(IVREventDelegate.CALL_DETAIL_RECORD_KEY, cdr);

      eventRelay.sendEventMessage(event);
    }
  }
Exemplo n.º 11
0
  @Override
  public void saveBundleSettings(Settings settings, long bundleId) throws IOException {
    Properties props = ParamParser.constructProperties(settings);

    configurationService.addOrUpdateProperties(
        getBundleSymbolicName(bundleId),
        getVersion(bundleId),
        settings.getSection(),
        props,
        getBundleDefaultProperties(bundleId).get(settings.getSection()));

    Map<String, Object> params = new HashMap<>();
    params.put(ConfigurationConstants.BUNDLE_ID, bundleId);
    params.put(ConfigurationConstants.BUNDLE_SYMBOLIC_NAME, getBundleSymbolicName(bundleId));
    params.put(ConfigurationConstants.BUNDLE_SECTION, settings.getSection());

    MotechEvent bundleSettingsChangedEvent =
        new MotechEvent(ConfigurationConstants.BUNDLE_SETTINGS_CHANGED_EVENT_SUBJECT, params);
    eventRelay.sendEventMessage(bundleSettingsChangedEvent);
  }
 private void sendActions(List<Action> actions, Map<String, Object> params) {
   for (Action action : actions) {
     eventRelay.sendEventMessage(new MotechEvent(action.getEventId(), params));
   }
 }
  @Override
  /** Sends an SMS */
  public void send(OutgoingSms sms) {

    // todo: cache that?
    Configs configs = new ConfigReader(settingsFacade).getConfigs();
    Config config;
    Template template;

    if (sms.hasConfig()) {
      config = configs.getConfig(sms.getConfig());
    } else {
      logger.debug("No config specified, using default config.");
      config = configs.getDefaultConfig();
    }
    template = templates.getTemplate(config.getTemplateName());

    // todo: die if things aren't right, right?
    // todo: SMS_SCHEDULE_FUTURE_SMS research if any sms provider provides that, for now assume not.

    Integer maxSize = template.getOutgoing().getMaxSmsSize();
    String header = config.getSplitHeader();
    String footer = config.getSplitFooter();
    Boolean excludeLastFooter = config.getExcludeLastFooter();
    // todo: maximum number of supported recipients : per template/provider and/or per http specs

    // todo - cr - move that to the Config object so calculated only once ?
    // todo - cr - investigate if that might be a problem on windows
    // -2 to account for the added \n after the header and before the footer
    if ((maxSize - header.length() - footer.length() - 2) <= 0) {
      throw new IllegalArgumentException(
          "The combined sizes of the header and footer templates are larger than the maximum SMS size!");
    }

    List<String> messageParts =
        splitMessage(sms.getMessage(), maxSize, header, footer, excludeLastFooter);
    List<List<String>> recipientsList =
        splitRecipientList(sms.getRecipients(), template.getOutgoing().getMaxRecipient());

    // todo: delivery_time on the sms provider's side if they support it?
    for (List<String> recipients : recipientsList) {
      if (sms.hasDeliveryTime()) {
        DateTime dt = sms.getDeliveryTime();
        for (String part : messageParts) {
          String motechId = generateMotechId();
          MotechEvent event =
              outboundEvent(
                  SmsEventSubjects.SCHEDULED,
                  config.getName(),
                  recipients,
                  part,
                  motechId,
                  null,
                  null,
                  null,
                  null);
          // MOTECH scheduler needs unique job ids, so adding motechId as job_id_key will do that
          event.getParameters().put(MotechSchedulerService.JOB_ID_KEY, motechId);
          event.getParameters().put(SmsEventParams.DELIVERY_TIME, dt);
          schedulerService.safeScheduleRunOnceJob(new RunOnceSchedulableJob(event, dt.toDate()));
          logger.info(
              String.format(
                  "Scheduling message [%s] to [%s] at %s.",
                  part.replace("\n", "\\n"), recipients, sms.getDeliveryTime()));
          // add one millisecond to the next sms part so they will be delivered in order
          // without that it seems Quartz doesn't fire events in the order they were scheduled
          dt = dt.plus(1);
          for (String recipient : recipients) {
            smsAuditService.log(
                new SmsRecord(
                    config.getName(),
                    OUTBOUND,
                    recipient,
                    part,
                    now(),
                    DeliveryStatus.SCHEDULED,
                    null,
                    motechId,
                    null,
                    null));
          }
        }
      } else {
        for (String part : messageParts) {
          String motechId = generateMotechId();
          eventRelay.sendEventMessage(
              outboundEvent(
                  SmsEventSubjects.PENDING,
                  config.getName(),
                  recipients,
                  part,
                  motechId,
                  null,
                  null,
                  null,
                  null));
          logger.info("Sending message [{}] to [{}].", part.replace("\n", "\\n"), recipients);
          for (String recipient : recipients) {
            smsAuditService.log(
                new SmsRecord(
                    config.getName(),
                    OUTBOUND,
                    recipient,
                    part,
                    now(),
                    DeliveryStatus.PENDING,
                    null,
                    motechId,
                    null,
                    null));
          }
        }
      }
    }
  }
 private void raiseSendSmsEvent(List<String> recipients, String message, DateTime deliveryTime) {
   log.info(String.format("Sending message [%s] to number %s.", message, recipients));
   eventRelay.sendEventMessage(sendSmsEvent(recipients, message, deliveryTime));
 }