public void process(Message message, String command) throws Exception {
    if (processThread == null) {
      processThread = new ProcessThread();

      processThread.setCommand(command);
      processThread.setMessage(message);

      processThread.run();
    }

    if (Validator.isNotNull(processMessageResponse)) {
      message.setPayload(processMessageResponse);

      if (!processMessageResponse.equals(MESSAGE_RESPONSE_WAIT)) {
        processMessageResponse = null;

        processThread.join();

        processThread = null;
      }
    } else {
      message.setPayload(MESSAGE_RESPONSE_WAIT);
    }

    MessageBusUtil.sendMessage(message.getResponseDestinationName(), message);
  }
  public static void sendMulticastMessage(Object payload, Priority priority) {
    Message message = new Message();

    message.setPayload(payload);

    sendMulticastMessage(message, priority);
  }
示例#3
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;
  }
  @Test
  public void testSuppressError() throws Exception {
    SchedulerResponse schedulerResponse =
        _quartzSchedulerEngine.getScheduledJob(
            _TEST_JOB_NAME_0, _MEMORY_TEST_GROUP_NAME, StorageType.MEMORY);

    Message message = schedulerResponse.getMessage();

    JobState jobState = (JobState) message.get(SchedulerEngine.JOB_STATE);

    Assert.assertNotNull(jobState.getExceptions());

    _quartzSchedulerEngine.suppressError(
        _TEST_JOB_NAME_0, _MEMORY_TEST_GROUP_NAME, StorageType.MEMORY);

    schedulerResponse =
        _quartzSchedulerEngine.getScheduledJob(
            _TEST_JOB_NAME_0, _MEMORY_TEST_GROUP_NAME, StorageType.MEMORY);

    message = schedulerResponse.getMessage();

    jobState = (JobState) message.get(SchedulerEngine.JOB_STATE);

    Assert.assertNull(jobState.getExceptions());
  }
 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);
 }
  public void receive(Message message) throws MessageListenerException {
    String destinationName =
        GetterUtil.getString(message.getString(SchedulerEngine.DESTINATION_NAME));

    if (destinationName.equals(DestinationNames.SCHEDULER_DISPATCH)) {
      String receiverKey = GetterUtil.getString(message.getString(SchedulerEngine.RECEIVER_KEY));

      if (!receiverKey.equals(_key)) {
        return;
      }
    }

    try {
      _messageListener.receive(message);
    } catch (Exception e) {
      handleException(message, e);

      if (e instanceof MessageListenerException) {
        throw (MessageListenerException) e;
      } else {
        throw new MessageListenerException(e);
      }
    } finally {
      if (message.getBoolean(SchedulerEngine.DISABLE)
          && destinationName.equals(DestinationNames.SCHEDULER_DISPATCH)) {

        MessageBusUtil.unregisterMessageListener(destinationName, this);
      }
    }
  }
  /* (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);
    }
  }
  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);
      }
    }
  }
  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());
  }
 protected boolean checkMessagePayload(final Message message) {
   if (!(message.getPayload() instanceof MessageStatus)) {
     LOGGER.warn(
         "Received a Message which doesn't contain a MessageStatus: {}", message.getPayload());
     return false;
   }
   return true;
 }
  protected void unregisterMessageListener(Scheduler scheduler, JobKey jobKey) throws Exception {

    JobDetail jobDetail = scheduler.getJobDetail(jobKey);

    if (jobDetail == null) {
      return;
    }

    JobDataMap jobDataMap = jobDetail.getJobDataMap();

    if (jobDataMap == null) {
      return;
    }

    Message message = getMessage(jobDataMap);

    String messageListenerUUID = message.getString(SchedulerEngine.MESSAGE_LISTENER_UUID);

    if (messageListenerUUID == null) {
      return;
    }

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

    Destination destination = _messageBus.getDestination(destinationName);

    if (destination == null) {
      return;
    }

    Set<MessageListener> messageListeners = destination.getMessageListeners();

    for (MessageListener messageListener : messageListeners) {
      if (!(messageListener instanceof InvokerMessageListener)) {
        continue;
      }

      InvokerMessageListener invokerMessageListener = (InvokerMessageListener) messageListener;

      messageListener = invokerMessageListener.getMessageListener();

      if (!(messageListener instanceof SchedulerEventMessageListenerWrapper)) {

        continue;
      }

      SchedulerEventMessageListenerWrapper schedulerMessageListener =
          (SchedulerEventMessageListenerWrapper) messageListener;

      if (messageListenerUUID.equals(schedulerMessageListener.getMessageListenerUUID())) {

        _messageBus.unregisterMessageListener(destinationName, schedulerMessageListener);

        return;
      }
    }
  }
示例#12
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);
    }
示例#13
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));
    }
示例#14
0
  private void _assertSuppressErrorValue(
      SchedulerResponse schedulerResponse, Object expectedValue) {

    Message message = schedulerResponse.getMessage();

    Object object = message.get(_SUPPRESS_ERROR);

    Assert.assertEquals(expectedValue, object);
  }
  @Clusterable(onMaster = true)
  @Override
  public void triggerBackgroundTask(long backgroundTaskId) {
    Message message = new Message();

    message.put("backgroundTaskId", backgroundTaskId);

    MessageBusUtil.sendMessage(DestinationNames.BACKGROUND_TASK, message);
  }
  @Override
  protected void doReceive(Message message) throws Exception {
    String command = message.getString("command");
    String servletContextName = message.getString("servletContextName");

    if (command.equals("undeploy") && servletContextName.equals(getServletContextName())) {
      UserNoteLocalServiceUtil.clearService();
    }
  }
  @Override
  public void receive(Message message) {
    if (!message.getResponseId().equals(_responseId)) {
      return;
    }

    _results = message.getPayload();

    _countDownLatch.countDown();
  }
  @Override
  protected void doReceive(Message message) throws Exception {
    long userId = message.getLong("userId");

    Map<String, Boolean> results = TestPACLUtil.testCurrentThread(userId);

    message.setPayload(results);

    MessageBusUtil.sendMessage(message.getResponseDestinationName(), message);
  }
示例#19
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));
      }
    }
  protected void doReceive(Message message) throws Exception {
    String command = message.getString("command");
    String servletContextName = message.getString("servletContextName");

    if (command.equals("undeploy") && servletContextName.equals(SERVLET_CONTEXT_NAME)) {
      RuleLocalServiceUtil.clearService();

      RuleServiceUtil.clearService();
    }
  }
  /**
   * 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);
    }
  }
  protected void assertTriggerState(
      SchedulerResponse schedulerResponse, TriggerState expectedTriggerState) {

    Message message = schedulerResponse.getMessage();

    JobState jobState = (JobState) message.get(SchedulerEngine.JOB_STATE);

    TriggerState triggerState = jobState.getTriggerState();

    Assert.assertEquals(expectedTriggerState, triggerState);
  }
  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);
  }
  @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);
    }
  }
  protected void handleException(Message message, Exception exception) {
    JobState jobState = (JobState) message.get(SchedulerEngine.JOB_STATE);

    if (jobState != null) {
      jobState.addException(exception, new Date());
    }
  }
  @Override
  protected void doReceive(Message message) throws Exception {
    DLFileEntry dlFileEntry = (DLFileEntry) message.getPayload();

    DLFolderLocalServiceUtil.updateLastPostDate(
        dlFileEntry.getFolderId(), dlFileEntry.getModifiedDate());
  }
  @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);
  }
  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;
  }
  protected KaleoTimerInstanceToken getKaleoTimerInstanceToken(Message message)
      throws PortalException, SystemException {

    long kaleoTimerInstanceTokenId = message.getLong("kaleoTimerInstanceTokenId");

    KaleoTimerInstanceToken kaleoTimerInstanceToken =
        KaleoTimerInstanceTokenLocalServiceUtil.getKaleoTimerInstanceToken(
            kaleoTimerInstanceTokenId);

    return kaleoTimerInstanceToken;
  }
  @Override
  protected void doReceive(Message message) throws Exception {
    PortalCacheClusterEvent portalCacheClusterEvent =
        (PortalCacheClusterEvent) message.getPayload();

    if (portalCacheClusterEvent == null) {
      if (_log.isWarnEnabled()) {
        _log.warn("Payload is null");
      }

      return;
    }

    String cacheName = portalCacheClusterEvent.getCacheName();

    Ehcache ehcache = _portalCacheManager.getEhcache(cacheName);

    if (ehcache == null) {
      ehcache = _hibernateCacheManager.getEhcache(cacheName);
    }

    if (ehcache != null) {
      PortalCacheClusterEventType portalCacheClusterEventType =
          portalCacheClusterEvent.getEventType();

      if (portalCacheClusterEventType.equals(PortalCacheClusterEventType.REMOVEALL)) {

        ehcache.removeAll(true);
      } else if (portalCacheClusterEventType.equals(PortalCacheClusterEventType.PUT)
          || portalCacheClusterEventType.equals(PortalCacheClusterEventType.UPDATE)) {

        Serializable elementKey = portalCacheClusterEvent.getElementKey();
        Serializable elementValue = portalCacheClusterEvent.getElementValue();

        if (elementValue == null) {
          ehcache.remove(portalCacheClusterEvent.getElementKey(), true);
        } else {
          Element oldElement = ehcache.get(elementKey);
          Element newElement = new Element(elementKey, elementValue);

          if (oldElement != null) {
            ehcache.replace(newElement);
          } else {
            ehcache.put(newElement);
          }
        }
      } else {
        ehcache.remove(portalCacheClusterEvent.getElementKey(), true);
      }
    }
  }