private static void runScheduledJob(String jobName, String groupName) {
   Message message = new Message();
   message.put(SchedulerEngine.MESSAGE_LISTENER_CLASS_NAME, jobName);
   message.put(SchedulerEngine.DESTINATION_NAME, DestinationNames.SCHEDULER_DISPATCH);
   message.put(SchedulerEngine.RECEIVER_KEY, new ReceiverKey(jobName, groupName));
   MessageBusUtil.sendMessage(DestinationNames.SCHEDULER_DISPATCH, message);
 }
  protected void initJobState() throws Exception {
    List<String> groupNames = _persistedScheduler.getJobGroupNames();

    for (String groupName : groupNames) {
      Set<JobKey> jobkeys = _persistedScheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName));

      for (JobKey jobKey : jobkeys) {
        Trigger trigger =
            _persistedScheduler.getTrigger(new TriggerKey(jobKey.getName(), jobKey.getGroup()));

        if (trigger != null) {
          continue;
        }

        JobDetail jobDetail = _persistedScheduler.getJobDetail(jobKey);

        JobDataMap jobDataMap = jobDetail.getJobDataMap();

        Message message = getMessage(jobDataMap);

        message.put(SchedulerEngine.JOB_NAME, jobKey.getName());
        message.put(SchedulerEngine.GROUP_NAME, jobKey.getGroup());

        if (_schedulerEngineHelper != null) {
          _schedulerEngineHelper.auditSchedulerJobs(message, TriggerState.EXPIRED);
        }

        _persistedScheduler.deleteJob(jobKey);
      }
    }
  }
  /* (non-Javadoc)
   * @see com.liferay.support.task.TaskManager#addTask(java.lang.String, java.lang.String, com.liferay.portal.kernel.scheduler.Trigger, java.lang.String)
   */
  public void addTask(String jobName, String groupName, Trigger trigger, String logMessage) {
    try {
      Message message = new Message();
      message.put("info", "Hello world!");
      message.put("logMessage", logMessage);

      SchedulerEntryImpl schedulerEntry = new SchedulerEntryImpl();

      schedulerEntry.setTrigger(trigger);
      schedulerEntry.setDescription("This is the schedulerEntry description");
      schedulerEntry.setEventListenerClass(LogMessageListener.class.getName());

      _log.fatal(
          "Scheduling new task:: jobName["
              + jobName
              + "] groupName["
              + PersistedTaskConstants.GROUP_NAME
              + "]");

      _schedulerEngineHelper.schedule(
          trigger,
          StorageType.PERSISTED,
          "This is an example of persisted task",
          DestinationNames.SCHEDULER_DISPATCH,
          message,
          10);

      registerListener(trigger);

    } catch (Exception e) {
      _log.error(e);
    }
  }
  @Override
  public void schedule(
      com.liferay.portal.kernel.scheduler.Trigger trigger,
      String description,
      String destination,
      Message message,
      StorageType storageType)
      throws SchedulerException {

    try {
      Scheduler scheduler = getScheduler(storageType);

      Trigger quartzTrigger = (Trigger) trigger.getWrappedTrigger();

      if (quartzTrigger == null) {
        return;
      }

      description = fixMaxLength(description, _descriptionMaxLength, storageType);

      message = message.clone();

      message.put(SchedulerEngine.GROUP_NAME, trigger.getGroupName());
      message.put(SchedulerEngine.JOB_NAME, trigger.getJobName());

      schedule(scheduler, storageType, quartzTrigger, description, destination, message);
    } catch (RuntimeException re) {
      if (PortalRunMode.isTestMode()) {
        StackTraceElement[] stackTraceElements = re.getStackTrace();

        for (StackTraceElement stackTraceElement : stackTraceElements) {
          String className = stackTraceElement.getClassName();

          if (className.contains(ServerDetector.class.getName())) {
            if (_log.isInfoEnabled()) {
              _log.info(re, re);
            }

            return;
          }

          throw new SchedulerException("Unable to schedule job", re);
        }
      } else {
        throw new SchedulerException("Unable to schedule job", re);
      }
    } catch (Exception e) {
      throw new SchedulerException("Unable to schedule job", e);
    }
  }
  /**
   * Takes a submitted contact and adds it to the database if it passes validation.
   *
   * @param request
   * @param response
   */
  public void registerContact(ActionRequest request, ActionResponse response) throws Exception {

    _log.debug("registerContact");

    Contact contact = ActionUtil.contactFromRequest(request);
    ArrayList<String> errors = new ArrayList();
    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    String community = "";
    try {
      community = themeDisplay.getScopeGroupName();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    boolean regValid = ContactMeRegValidator.validateRegistration(contact, errors);

    if (regValid) {

      long userId = themeDisplay.getUserId();

      contact.setCreateDate(new Date(System.currentTimeMillis()));
      contact.setUserId(userId);
      contact.setStatus(Constants.CONTACT_RECEIVED);
      contact.setCommunity(community);

      ContactLocalServiceUtil.addContact(contact);
      SessionMessages.add(request, "thank-you-message");

      PortletPreferences preferences = request.getPreferences();

      long companyId = PortalUtil.getCompanyId(request);

      Message message = new Message();

      message.put("from-name", preferences.getValue("fromName", ""));
      message.put("from-address", preferences.getValue("fromEMail", ""));
      message.put("subject", preferences.getValue("subject", ""));
      message.put("body", preferences.getValue("body", ""));
      message.put("signature", preferences.getValue("signature", ""));
      message.put("to-name", contact.getFullname());
      message.put("to-address", contact.getEmail());
      message.put("community", contact.getCommunity());
      message.put("companyId", companyId);

      MessageBusUtil.sendMessage("liferay/contactme", message);

      response.setRenderParameter("jspPage", viewThankYouJSP);

    } else {
      for (String error : errors) {
        SessionErrors.add(request, error);
      }
      SessionErrors.add(request, "error-saving-contact");
      response.setRenderParameter("jspPage", viewAddContactJSP);
      request.setAttribute("cmContact", contact);
    }
  }
Beispiel #6
0
  private Map<String, SchedulerResponse> _getMemoryClusteredJobs(
      ClusterSchedulerEngine clusterSchedulerEngine) throws Exception {

    Field field =
        ReflectionUtil.getDeclaredField(ClusterSchedulerEngine.class, "_memoryClusteredJobs");

    Map<String, ObjectValuePair<SchedulerResponse, TriggerState>> memoryJobs =
        (Map<String, ObjectValuePair<SchedulerResponse, TriggerState>>)
            field.get(clusterSchedulerEngine);

    if (memoryJobs.isEmpty()) {
      return Collections.emptyMap();
    }

    Map<String, SchedulerResponse> schedulerResponses =
        new HashMap<String, SchedulerResponse>(memoryJobs.size());

    for (String key : memoryJobs.keySet()) {
      ObjectValuePair<SchedulerResponse, TriggerState> value = memoryJobs.get(key);

      SchedulerResponse schedulerResponse = value.getKey();

      Message message = schedulerResponse.getMessage();

      TriggerState triggerState = value.getValue();

      message.put(SchedulerEngine.JOB_STATE, new JobState(triggerState));

      schedulerResponses.put(key, schedulerResponse);
    }

    return schedulerResponses;
  }
  protected void registerMessageListeners(String destinationName, Message message)
      throws SchedulerException {

    if (_portletLocalService == null) {
      throw new IllegalStateException("Portlet local service not initialized");
    }

    String messageListenerClassName =
        message.getString(SchedulerEngine.MESSAGE_LISTENER_CLASS_NAME);

    if (Validator.isNull(messageListenerClassName)) {
      return;
    }

    String portletId = message.getString(SchedulerEngine.PORTLET_ID);

    ClassLoader classLoader = null;

    if (Validator.isNull(portletId)) {
      classLoader = PortalClassLoaderUtil.getClassLoader();
    } else {
      Portlet portlet = _portletLocalService.getPortletById(portletId);

      if (portlet == null) {

        // No portlet found for the portlet ID. Try getting the class
        // loader where we assume the portlet ID is actually a servlet
        // context name.

        classLoader = ClassLoaderPool.getClassLoader(portletId);
      } else {
        PortletApp portletApp = portlet.getPortletApp();

        ServletContext servletContext = portletApp.getServletContext();

        classLoader = servletContext.getClassLoader();
      }
    }

    if (classLoader == null) {
      throw new SchedulerException("Unable to find class loader for portlet " + portletId);
    }

    MessageListener schedulerEventListener =
        getMessageListener(messageListenerClassName, classLoader);

    SchedulerEventMessageListenerWrapper schedulerEventListenerWrapper =
        new SchedulerEventMessageListenerWrapper();

    schedulerEventListenerWrapper.setMessageListener(schedulerEventListener);

    schedulerEventListenerWrapper.afterPropertiesSet();

    _messageBus.registerMessageListener(destinationName, schedulerEventListenerWrapper);

    message.put(
        SchedulerEngine.MESSAGE_LISTENER_UUID,
        schedulerEventListenerWrapper.getMessageListenerUUID());
  }
Beispiel #8
0
    @Override
    public void suppressError(String jobName, String groupName) throws SchedulerException {

      SchedulerResponse schedulerResponse = getScheduledJob(jobName, groupName);

      Message message = schedulerResponse.getMessage();

      message.put(_SUPPRESS_ERROR, Boolean.TRUE);
    }
  @Clusterable(onMaster = true)
  @Override
  public void triggerBackgroundTask(long backgroundTaskId) {
    Message message = new Message();

    message.put("backgroundTaskId", backgroundTaskId);

    MessageBusUtil.sendMessage(DestinationNames.BACKGROUND_TASK, message);
  }
Beispiel #10
0
    @Override
    public void unschedule(String jobName, String groupName) throws SchedulerException {

      SchedulerResponse schedulerResponse = getScheduledJob(jobName, groupName);

      Message message = schedulerResponse.getMessage();

      message.put(SchedulerEngine.JOB_STATE, new JobState(TriggerState.UNSCHEDULED));
    }
Beispiel #11
0
    @Override
    public void unschedule(String groupName) throws SchedulerException {
      List<SchedulerResponse> schedulerResponses = getScheduledJobs(groupName);

      for (SchedulerResponse schedulerResponse : schedulerResponses) {
        Message message = schedulerResponse.getMessage();

        message.put(SchedulerEngine.JOB_STATE, new JobState(TriggerState.UNSCHEDULED));
      }
    }
  private void _processJoinEvent(ClusterNode clusterNode) {
    Message message = new Message();

    message.put(ClusterLink.CLUSTER_FORWARD_MESSAGE, true);

    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

    jsonObject.put("clusterNodeId", clusterNode.getClusterNodeId());
    jsonObject.put("command", "addClusterNode");

    message.setPayload(jsonObject.toString());

    MessageBusUtil.sendMessage(DestinationNames.LIVE_USERS, message);
  }
  protected SchedulerResponse getScheduledJob(Scheduler scheduler, JobKey jobKey) throws Exception {

    JobDetail jobDetail = scheduler.getJobDetail(jobKey);

    if (jobDetail == null) {
      return null;
    }

    SchedulerResponse schedulerResponse = new SchedulerResponse();

    JobDataMap jobDataMap = jobDetail.getJobDataMap();

    String description = jobDataMap.getString(SchedulerEngine.DESCRIPTION);

    schedulerResponse.setDescription(description);

    String destinationName = jobDataMap.getString(SchedulerEngine.DESTINATION_NAME);

    schedulerResponse.setDestinationName(destinationName);

    Message message = getMessage(jobDataMap);

    JobState jobState = getJobState(jobDataMap);

    message.put(SchedulerEngine.JOB_STATE, jobState);

    schedulerResponse.setMessage(message);

    StorageType storageType =
        StorageType.valueOf(jobDataMap.getString(SchedulerEngine.STORAGE_TYPE));

    schedulerResponse.setStorageType(storageType);

    String jobName = jobKey.getName();
    String groupName = jobKey.getGroup();

    TriggerKey triggerKey = new TriggerKey(jobName, groupName);

    Trigger trigger = scheduler.getTrigger(triggerKey);

    if (trigger == null) {
      schedulerResponse.setGroupName(groupName);
      schedulerResponse.setJobName(jobName);

      return schedulerResponse;
    }

    message.put(SchedulerEngine.END_TIME, trigger.getEndTime());
    message.put(SchedulerEngine.FINAL_FIRE_TIME, trigger.getFinalFireTime());
    message.put(SchedulerEngine.NEXT_FIRE_TIME, trigger.getNextFireTime());
    message.put(SchedulerEngine.PREVIOUS_FIRE_TIME, trigger.getPreviousFireTime());
    message.put(SchedulerEngine.START_TIME, trigger.getStartTime());

    schedulerResponse.setTrigger(new QuartzTrigger(trigger));

    return schedulerResponse;
  }
  @Clusterable(onMaster = true)
  @Override
  public void resumeBackgroundTask(long backgroundTaskId) throws SystemException {

    BackgroundTask backgroundTask = backgroundTaskPersistence.fetchByPrimaryKey(backgroundTaskId);

    if ((backgroundTask == null)
        || (backgroundTask.getStatus() != BackgroundTaskConstants.STATUS_QUEUED)) {

      return;
    }

    Message message = new Message();

    message.put("backgroundTaskId", backgroundTaskId);

    MessageBusUtil.sendMessage(DestinationNames.BACKGROUND_TASK, message);
  }
Beispiel #15
0
    private SchedulerResponse _addJobs(
        String jobName,
        String groupName,
        StorageType storageType,
        Trigger trigger,
        Message message) {

      SchedulerResponse schedulerResponse = new SchedulerResponse();

      schedulerResponse.setDestinationName(DestinationNames.SCHEDULER_DISPATCH);
      schedulerResponse.setGroupName(_getOriginalGroupName(groupName));
      schedulerResponse.setJobName(jobName);

      if (message == null) {
        message = new Message();
      }

      message.put(SchedulerEngine.JOB_STATE, new JobState(TriggerState.NORMAL));

      schedulerResponse.setMessage(message);

      schedulerResponse.setStorageType(storageType);

      if (trigger == null) {
        try {
          trigger =
              TriggerFactoryUtil.buildTrigger(
                  TriggerType.SIMPLE,
                  jobName,
                  _getOriginalGroupName(groupName),
                  null,
                  null,
                  _DEFAULT_INTERVAL);
        } catch (Exception e) {
        }
      }

      schedulerResponse.setTrigger(trigger);

      _defaultJobs.put(_getFullName(jobName, groupName), schedulerResponse);

      return schedulerResponse;
    }
  public static Message setAddress(Message message, Address address) {
    message.put(_ADDRESS, address);

    return message;
  }
  protected SchedulerResponse getScheduledJob(Scheduler scheduler, JobKey jobKey) throws Exception {

    JobDetail jobDetail = scheduler.getJobDetail(jobKey);

    if (jobDetail == null) {
      return null;
    }

    SchedulerResponse schedulerResponse = new SchedulerResponse();

    JobDataMap jobDataMap = jobDetail.getJobDataMap();

    String description = jobDataMap.getString(SchedulerEngine.DESCRIPTION);

    schedulerResponse.setDescription(description);

    String destinationName = jobDataMap.getString(SchedulerEngine.DESTINATION_NAME);

    schedulerResponse.setDestinationName(destinationName);

    Message message = getMessage(jobDataMap);

    JobState jobState = getJobState(jobDataMap);

    message.put(SchedulerEngine.JOB_STATE, jobState);

    schedulerResponse.setMessage(message);

    StorageType storageType =
        StorageType.valueOf(jobDataMap.getString(SchedulerEngine.STORAGE_TYPE));

    schedulerResponse.setStorageType(storageType);

    String jobName = jobKey.getName();
    String groupName = jobKey.getGroup();

    TriggerKey triggerKey = new TriggerKey(jobName, groupName);

    Trigger trigger = scheduler.getTrigger(triggerKey);

    if (trigger == null) {
      schedulerResponse.setGroupName(groupName);
      schedulerResponse.setJobName(jobName);

      return schedulerResponse;
    }

    message.put(SchedulerEngine.END_TIME, trigger.getEndTime());
    message.put(SchedulerEngine.FINAL_FIRE_TIME, trigger.getFinalFireTime());
    message.put(SchedulerEngine.NEXT_FIRE_TIME, trigger.getNextFireTime());
    message.put(SchedulerEngine.PREVIOUS_FIRE_TIME, trigger.getPreviousFireTime());
    message.put(SchedulerEngine.START_TIME, trigger.getStartTime());

    if (trigger instanceof CalendarIntervalTrigger) {
      CalendarIntervalTrigger calendarIntervalTrigger = CalendarIntervalTrigger.class.cast(trigger);

      IntervalUnit intervalUnit = calendarIntervalTrigger.getRepeatIntervalUnit();

      schedulerResponse.setTrigger(
          new IntervalTrigger(
              jobName,
              groupName,
              calendarIntervalTrigger.getStartTime(),
              calendarIntervalTrigger.getEndTime(),
              calendarIntervalTrigger.getRepeatInterval(),
              TimeUnit.valueOf(intervalUnit.name())));
    } else if (trigger instanceof CronTrigger) {
      CronTrigger cronTrigger = CronTrigger.class.cast(trigger);

      schedulerResponse.setTrigger(
          new com.liferay.portal.kernel.scheduler.CronTrigger(
              jobName,
              groupName,
              cronTrigger.getStartTime(),
              cronTrigger.getEndTime(),
              cronTrigger.getCronExpression()));
    } else if (trigger instanceof SimpleTrigger) {
      SimpleTrigger simpleTrigger = SimpleTrigger.class.cast(trigger);

      schedulerResponse.setTrigger(
          new IntervalTrigger(
              jobName,
              groupName,
              simpleTrigger.getStartTime(),
              simpleTrigger.getEndTime(),
              (int) simpleTrigger.getRepeatInterval(),
              TimeUnit.MILLISECOND));
    }

    return schedulerResponse;
  }
  @Override
  protected void doReceive(Message message) throws Exception {
    long backgroundTaskId = (Long) message.get(BackgroundTaskConstants.BACKGROUND_TASK_ID);

    BackgroundTaskThreadLocal.setBackgroundTaskId(backgroundTaskId);

    ServiceContext serviceContext = new ServiceContext();

    BackgroundTask backgroundTask =
        _backgroundTaskManager.amendBackgroundTask(
            backgroundTaskId, null, BackgroundTaskConstants.STATUS_IN_PROGRESS, serviceContext);

    if (backgroundTask == null) {
      if (_log.isDebugEnabled()) {
        _log.debug("Unable to find background task " + backgroundTaskId);
      }

      return;
    }

    BackgroundTaskExecutor backgroundTaskExecutor = null;
    BackgroundTaskStatusMessageListener backgroundTaskStatusMessageListener = null;

    int status = backgroundTask.getStatus();
    String statusMessage = null;

    try {
      ClassLoader classLoader = getBackgroundTaskExecutorClassLoader(backgroundTask);

      backgroundTaskExecutor = wrapBackgroundTaskExecutor(backgroundTask, classLoader);

      _backgroundTaskStatusRegistry.registerBackgroundTaskStatus(backgroundTaskId);

      BackgroundTaskStatusMessageTranslator backgroundTaskStatusMessageTranslator =
          backgroundTaskExecutor.getBackgroundTaskStatusMessageTranslator();

      if (backgroundTaskStatusMessageTranslator != null) {
        backgroundTaskStatusMessageListener =
            new BackgroundTaskStatusMessageListener(
                backgroundTaskId,
                backgroundTaskStatusMessageTranslator,
                _backgroundTaskStatusRegistry);

        _messageBus.registerMessageListener(
            DestinationNames.BACKGROUND_TASK_STATUS, backgroundTaskStatusMessageListener);
      }

      backgroundTask =
          _backgroundTaskManager.fetchBackgroundTask(backgroundTask.getBackgroundTaskId());

      BackgroundTaskResult backgroundTaskResult = backgroundTaskExecutor.execute(backgroundTask);

      status = backgroundTaskResult.getStatus();
      statusMessage = backgroundTaskResult.getStatusMessage();
    } catch (DuplicateLockException dle) {
      status = BackgroundTaskConstants.STATUS_QUEUED;

      if (_log.isDebugEnabled()) {
        _log.debug("Unable to acquire lock, queuing background task " + backgroundTaskId);
      }
    } catch (Exception e) {
      status = BackgroundTaskConstants.STATUS_FAILED;

      if (e instanceof SystemException) {
        Throwable cause = e.getCause();

        if (cause instanceof Exception) {
          e = (Exception) cause;
        }
      }

      if (backgroundTaskExecutor != null) {
        statusMessage = backgroundTaskExecutor.handleException(backgroundTask, e);
      }

      if (_log.isInfoEnabled()) {
        if (statusMessage != null) {
          statusMessage = statusMessage.concat(StackTraceUtil.getStackTrace(e));
        } else {
          statusMessage = StackTraceUtil.getStackTrace(e);
        }
      }

      _log.error("Unable to execute background task", e);
    } finally {
      if (_log.isDebugEnabled()) {
        _log.debug("Completing background task " + backgroundTaskId + " with status: " + status);
      }

      _backgroundTaskManager.amendBackgroundTask(
          backgroundTaskId, null, status, statusMessage, serviceContext);

      _backgroundTaskStatusRegistry.unregisterBackgroundTaskStatus(backgroundTaskId);

      if (backgroundTaskStatusMessageListener != null) {
        _messageBus.unregisterMessageListener(
            DestinationNames.BACKGROUND_TASK_STATUS, backgroundTaskStatusMessageListener);
      }

      Message responseMessage = new Message();

      responseMessage.put(
          BackgroundTaskConstants.BACKGROUND_TASK_ID, backgroundTask.getBackgroundTaskId());
      responseMessage.put("name", backgroundTask.getName());
      responseMessage.put("status", status);
      responseMessage.put("taskExecutorClassName", backgroundTask.getTaskExecutorClassName());

      _messageBus.sendMessage(DestinationNames.BACKGROUND_TASK_STATUS, responseMessage);
    }
  }
 // Workflow code
 private void sendMessage(Books book, ServiceContext serviceContext) {
   Message message = new Message();
   message.put("userId", serviceContext.getUserId());
   message.put("title", book.getTitle());
   MessageBusUtil.sendMessage("book/title", message);
 }
 public static void setForwardMessage(Message message) {
   message.put(ClusterLink.CLUSTER_FORWARD_MESSAGE, true);
 }