예제 #1
0
 /* (non-Javadoc)
  * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
  */
 @Override
 public void execute(final JobExecutionContext ctx) throws JobExecutionException {
   final JobDetail jobDetail = ctx.getJobDetail();
   final JobDataMap jobDataMap = jobDetail.getJobDataMap();
   final IElement element =
       (IElement) jobDataMap.get(CronConstants.KEY_DATA_ELEMENT_CONFIGURATION);
   final String name = (String) jobDataMap.get(CronConstants.KEY_DATA_NAME);
   final Collection<INotifier> globalNotifiers =
       (Collection<INotifier>) jobDataMap.get(CronConstants.KEY_DATA_NOTIFIERS);
   if (element != null) {
     LOGGER.debug("Going to analyze set [" + name + "], [" + element.getName() + "]");
     try {
       final AnalyzeResult result = element.analyze();
       if (result.hasToBeNotified()) {
         for (final INotifier notifier :
             buildNotifiersList(element.getNotifiers(), globalNotifiers)) {
           LOGGER.info("User [" + name + "], notifying [" + notifier.toString() + "]");
           notifier.execute(result);
         }
       }
     } catch (final CoreException e) {
       throw new JobExecutionException(e);
     }
   }
 }
예제 #2
0
 protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
   try {
     SchedulerContext schCtx = context.getScheduler().getContext();
     // 获取Spring中的上下文
     ApplicationContext appCtx = (ApplicationContext) schCtx.get("applicationContext");
     this.staticPageSvc = (StaticPageSvc) appCtx.getBean("staticPageSvc");
     JobDataMap jdm = context.getJobDetail().getJobDataMap();
     // 获取栏目
     String channelIdStr = (String) jdm.get(CmsTask.TASK_PARAM_CHANNEL_ID);
     if (!StringUtils.isBlank(channelIdStr)) {
       this.channelId = Integer.parseInt(channelIdStr);
       if (channelId.equals(0)) {
         channelId = null;
       }
     }
     // 获取站点
     String siteIdStr = (String) jdm.get(CmsTask.TASK_PARAM_SITE_ID);
     if (!StringUtils.isBlank(siteIdStr)) {
       this.siteId = Integer.parseInt(siteIdStr);
     }
   } catch (SchedulerException e1) {
     // TODO 尚未处理异常
     e1.printStackTrace();
   }
   staitcChannel();
 }
예제 #3
0
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();

    String receiverKey = (String) map.get(QuartzMessageReceiver.QUARTZ_RECEIVER_PROPERTY);
    if (receiverKey == null)
      throw new JobExecutionException(QuartzMessages.receiverNotInJobDataMap().getMessage());

    String connectorName = (String) map.get(QuartzMessageReceiver.QUARTZ_CONNECTOR_PROPERTY);
    if (connectorName == null)
      throw new JobExecutionException(QuartzMessages.connectorNotInJobDataMap().getMessage());

    AbstractConnector connector =
        (AbstractConnector) RegistryContext.getRegistry().lookupConnector(connectorName);
    if (connector == null)
      throw new JobExecutionException(QuartzMessages.noConnectorFound(connectorName).getMessage());

    AbstractMessageReceiver receiver =
        (AbstractMessageReceiver) connector.lookupReceiver(receiverKey);
    if (receiver == null)
      throw new JobExecutionException(
          QuartzMessages.noReceiverInConnector(receiverKey, connectorName).getMessage());

    Object payload =
        jobExecutionContext.getJobDetail().getJobDataMap().get(QuartzConnector.PROPERTY_PAYLOAD);

    try {
      if (payload == null) {
        String ref =
            jobExecutionContext
                .getJobDetail()
                .getJobDataMap()
                .getString(QuartzConnector.PROPERTY_PAYLOAD_REFERENCE);
        // for backward compatibility check the old payload Class property
        // too
        if (ref == null) {
          ref =
              jobExecutionContext
                  .getJobDetail()
                  .getJobDataMap()
                  .getString(QuartzConnector.PROPERTY_PAYLOAD_CLASS_NAME);
        }
        if (ref == null) {
          payload = NullPayload.getInstance();
        } else {
          payload = RegistryContext.getRegistry().lookupObject(ref);
        }

        if (payload == null) {
          logger.warn("There is no payload attached to this quartz job. Sending Null payload");
          payload = NullPayload.getInstance();
        }
      }
      receiver.routeMessage(new MuleMessage(receiver.getConnector().getMessageAdapter(payload)));
    } catch (Exception e) {
      receiver.handleException(e);
    }
  }
 protected void makeAuditRecord(
     final float time, final String messageType, final JobExecutionContext jobExecutionContext) {
   if (jobExecutionContext != null && jobExecutionContext.getJobDetail() != null) {
     final JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
     AuditHelper.audit(
         PentahoSessionHolder.getSession() != null
             ? PentahoSessionHolder.getSession().getId()
             : null,
         jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONUSER) != null
             ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONUSER).toString()
             : null,
         jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_STREAMPROVIDER) != null
             ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_STREAMPROVIDER).toString()
             : null,
         jobExecutionContext.getJobDetail().getJobClass() != null
             ? jobExecutionContext.getJobDetail().getJobClass().getName()
             : null,
         jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONID) != null
             ? jobDataMap.get(QuartzScheduler.RESERVEDMAPKEY_ACTIONID).toString()
             : null,
         messageType,
         jobDataMap.get("lineage-id") != null ? jobDataMap.get("lineage-id").toString() : null,
         null,
         time,
         null); //$NON-NLS-1$
   }
 }
예제 #5
0
 @SuppressWarnings("unchecked")
 @Override
 public void execute(JobExecutionContext context) throws JobExecutionException {
   JobDataMap dataMap = context.getJobDetail().getJobDataMap();
   // 取得所传递的参数
   Map<String, Object> paramMap = (Map<String, Object>) dataMap.get("jobParams");
   SeqLinkedList seqParam = new SeqLinkedList();
   // 放入job参数信息
   if (null != paramMap) {
     Iterator<Entry<String, Object>> iter = paramMap.entrySet().iterator();
     while (iter.hasNext()) {
       Entry<String, Object> entry = iter.next();
       seqParam.putParam(entry.getKey(), entry.getValue());
     }
   }
   // 将所有代码流程添加到容器中
   seqParam.addExec(jobExecuteFlow);
   boolean exec = false;
   try {
     exec = seqParam.nextExec();
   } catch (Exception e) {
     e.printStackTrace();
   }
   // 释放内存
   seqParam = null;
   System.out.println(exec);
 }
예제 #6
0
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();
    AbstractMessageReceiver receiver =
        (AbstractMessageReceiver) map.get(QuartzMessageReceiver.QUARTZ_RECEIVER_PROPERTY);
    Object payload =
        jobExecutionContext.getJobDetail().getJobDataMap().get(QuartzConnector.PROPERTY_PAYLOAD);

    try {
      if (payload == null) {
        String ref =
            jobExecutionContext
                .getJobDetail()
                .getJobDataMap()
                .getString(QuartzConnector.PROPERTY_PAYLOAD_REFERENCE);
        // for backward compatibility check the old payload Class property too
        if (ref == null) {
          ref =
              jobExecutionContext
                  .getJobDetail()
                  .getJobDataMap()
                  .getString(QuartzConnector.PROPERTY_PAYLOAD_CLASS_NAME);
        }
        try {
          payload = MuleManager.getInstance().getContainerContext().getComponent(ref);
        } catch (ObjectNotFoundException e) {
          logger.warn("There is no payload attached to this quartz job. Sending Null payload");
          payload = new NullPayload();
        }
      }
      receiver.routeMessage(new MuleMessage(receiver.getConnector().getMessageAdapter(payload)));
    } catch (Exception e) {
      receiver.handleException(e);
    }
  }
  protected Message getMessage(JobDataMap jobDataMap) {
    String messageJSON = (String) jobDataMap.get(SchedulerEngine.MESSAGE);

    if (_jsonFactory == null) {
      throw new IllegalStateException("JSON factory not initialized");
    }

    return (Message) _jsonFactory.deserialize(messageJSON);
  }
예제 #8
0
  @Override
  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

    JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap();
    CronEventTrigger cronEventTrigger = (CronEventTrigger) dataMap.get("trigger");
    if (log.isDebugEnabled()) {
      log.debug("Running Trigger Job '" + cronEventTrigger.getId() + "'");
    }
    cronEventTrigger.sendEvent();
  }
  public static Map<String, String> convertParametersFromNativeObject(
      org.quartz.JobDataMap quartzParameters) {
    Map<String, String> spagobiParameters = new HashMap<String, String>();

    Set<String> parameterNames = quartzParameters.keySet();
    for (String parameterName : parameterNames) {
      String parameterValue = (String) quartzParameters.get(parameterName);
      spagobiParameters.put(parameterName, parameterValue);
    }
    return spagobiParameters;
  }
예제 #10
0
 /** Calls the feed cleaner to do its work */
 public void execute(JobExecutionContext context) throws JobExecutionException {
   JobDataMap jobData = context.getJobDetail().getJobDataMap();
   // extract the feed cleaner to use
   Object feedCleanerObj = jobData.get("feedCleaner");
   if (feedCleanerObj == null || !(feedCleanerObj instanceof FeedCleaner)) {
     throw new AlfrescoRuntimeException(
         "FeedCleanupJob data must contain valid 'feedCleaner' reference");
   }
   FeedCleaner feedCleaner = (FeedCleaner) feedCleanerObj;
   feedCleaner.execute();
 }
예제 #11
0
 public void execute(JobExecutionContext context) throws JobExecutionException {
   JobDataMap jobData = context.getJobDetail().getJobDataMap();
   // extract the content cleaner to use
   Object certificateAlertObj = jobData.get("certificateAlert");
   if (certificateAlertObj == null || !(certificateAlertObj instanceof CertificateAlert)) {
     throw new AlfrescoRuntimeException(
         "CertificateAlertJob data must contain valid 'certificateAlert' reference");
   }
   CertificateAlert certificateAlert = (CertificateAlert) certificateAlertObj;
   certificateAlert.execute();
 }
예제 #12
0
 @Override
 public void execute(JobExecutionContext context) throws JobExecutionException {
   JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
   try {
     String jobBeanName = jobDataMap.getString(TASK_BEAN_NAME);
     BeanFactory beanFactory = (BeanFactory) jobDataMap.get(BEAN_FACTORY);
     jobBean = (Job) beanFactory.getBean(jobBeanName);
     log.debug("Executing job bean with name: " + jobBeanName);
     jobBean.execute(context);
   } catch (Exception e) {
     throw new JobExecutionException("Exception occurred running job bean", e);
   }
 }
예제 #13
0
 protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
   try {
     SchedulerContext schCtx = context.getScheduler().getContext();
     JobDataMap jdm = context.getJobDetail().getJobDataMap();
     // 获取采集源
     this.acquId = Integer.parseInt((String) jdm.get(CmsTask.TASK_PARAM_ACQU_ID));
     // 获取Spring中的上下文
     ApplicationContext appCtx = (ApplicationContext) schCtx.get("applicationContext");
     this.acquisitionSvc = (AcquisitionSvc) appCtx.getBean("acquisitionSvc");
   } catch (SchedulerException e1) {
     // TODO 尚未处理异常
     e1.printStackTrace();
   }
   acquStart();
 }
 protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
   try {
     SchedulerContext schCtx = context.getScheduler().getContext();
     JobDataMap jdm = context.getJobDetail().getJobDataMap();
     // 获取Spring中的上下文
     ApplicationContext appCtx = (ApplicationContext) schCtx.get("applicationContext");
     this.cmsSiteMng = (CmsSiteMng) appCtx.getBean("cmsSiteMng");
     this.staticPageSvc = (StaticPageSvc) appCtx.getBean("staticPageSvc");
     this.sessionFactory = (SessionFactory) appCtx.getBean("sessionFactory");
     this.siteId = Integer.parseInt((String) jdm.get(CmsTask.TASK_PARAM_SITE_ID));
   } catch (SchedulerException e1) {
     // TODO 尚未处理异常
     e1.printStackTrace();
   }
   staticIndex();
 }
예제 #15
0
  @Override
  public void toExecute(JobExecutionContext context) throws JobExecutionException {
    JobDataMap map = context.getMergedJobDataMap();
    String consumerUuid = map.getString(JobStatus.TARGET_ID);
    String cdnLabel = map.getString(CDN_LABEL);
    String webAppPrefix = map.getString(WEBAPP_PREFIX);
    String apiUrl = map.getString(API_URL);
    Map<String, String> extensionData = (Map<String, String>) map.get(EXTENSION_DATA);

    log.info("Starting async export for {}", consumerUuid);
    try {
      ExportResult result =
          manifestManager.generateAndStoreManifest(
              consumerUuid, cdnLabel, webAppPrefix, apiUrl, extensionData);
      context.setResult(result);
      log.info("Async export complete.");
    } catch (Exception e) {
      throw new JobExecutionException(e.getMessage(), e, false);
    }
  }
예제 #16
0
  public void execute(JobExecutionContext context) throws JobExecutionException {
    Object tokenId = "?";

    try {
      ProcessFacade processFacade = processServer.getProcessFacade();

      // TODO Fix 3 This should be JobDataMap dataMap = context.getJobDataMap();
      JobDataMap dataMap = context.getJobDetail().getJobDataMap();

      boolean disabled = dataMap.getBoolean(KEY_DISABLED);
      if (disabled) return;

      TokenContext tc = null;
      tokenId = dataMap.get(KEY_TOKEN_ID);
      if (tokenId == null) {
        // No token given, create new one
        tc = processFacade.createToken();
        processFacade.prepareTokenForScheduler(tc);
        tokenId = tc.getId();
      } else {
        // Use existing token
        tc = processFacade.getTokenById(tokenId);
        if (tc == null) {
          String msg =
              LogUtil.error(
                  getClass(),
                  "Cannot find the scheduled token context (id $0) for job $1.",
                  tokenId,
                  context.getJobDetail().getGroup() + "." + context.getJobDetail().getName());
          JobExecutionException ex = new JobExecutionException(msg);
          ex.setUnscheduleAllTriggers(true);
          throw ex;
        }
      }

      String positionRef = dataMap.getString(KEY_POSITION_REF);
      String executionMode = dataMap.getString(KEY_EXECUTION_MODE);
      String startMode = dataMap.getString(KEY_START_MODE);

      Map inputParamValues = null;

      for (Iterator it = dataMap.entrySet().iterator(); it.hasNext(); ) {
        Map.Entry entry = (Map.Entry) it.next();

        String key = (String) entry.getKey();
        if (key.startsWith(KEY_PARAM_PREFIX)) {
          if (inputParamValues == null) {
            inputParamValues = new HashMap();
          }
          key = key.substring(KEY_PARAM_PREFIX.length());
          inputParamValues.put(key, entry.getValue());
        } else if (key.startsWith(KEY_RUNTIME_ATRIBUTE_PREFIX)) {
          key = key.substring(KEY_RUNTIME_ATRIBUTE_PREFIX.length());
          tc.setRuntimeAttribute(key, entry.getValue());
        }
      }

      Engine engine = processServer.getEngine();

      if (ProcessJobDescriptor.START_MODE_RESUME.equals(startMode)) {
        // Resume an existing token
        if (engine.hasActiveObservers(SchedulerEngineEvent.RESUME_JOB, tc)) {
          ProcessJobDescriptor desc =
              ((QuartzProcessScheduler) processServer.getProcessScheduler())
                  .createJobDescriptor(context.getJobDetail());
          engine.fireEngineEvent(
              new SchedulerEngineEvent(SchedulerEngineEvent.RESUME_JOB, tc, desc, engine));
        }
        processFacade.resumeToken(tc, positionRef, inputParamValues);
      } else {
        // Start a new token
        if (engine.hasActiveObservers(SchedulerEngineEvent.START_JOB, tc)) {
          ProcessJobDescriptor desc =
              ((QuartzProcessScheduler) processServer.getProcessScheduler())
                  .createJobDescriptor(context.getJobDetail());
          engine.fireEngineEvent(
              new SchedulerEngineEvent(SchedulerEngineEvent.START_JOB, tc, desc, engine));
        }
        processFacade.startToken(tc, positionRef, inputParamValues);
      }

      // Process the token immediately if desired, otherwise let the execution thread pool do this.
      if (ProcessJobDescriptor.EXECUTION_MODE_SYNCHRONOUS.equals(executionMode)) {
        // We do not need to set the lifecycle to LifecycleState.SELECTED, it will be set to
        // LifecycleState.RUNNING by the executeContext method
        tc = processFacade.getTokenById(tokenId);
        if (tc == null) {
          String msg =
              LogUtil.error(
                  getClass(),
                  "Cannot find the scheduled token context (id $0) for job $1.",
                  tokenId,
                  context.getJobDetail().getGroup() + context.getJobDetail().getName());
          JobExecutionException ex = new JobExecutionException(msg);
          ex.setUnscheduleAllTriggers(true);
          throw ex;
        }
        engine.executeContext(tc);
        processFacade.commitTokenContextTransaction();
      }
    } catch (Exception e) {
      JobExecutionException jex = null;
      if (e instanceof JobExecutionException) {
        jex = (JobExecutionException) e;
      } else {
        String msg =
            LogUtil.error(
                getClass(),
                "Error occured while processing scheduled token context (id $0) for job $1.",
                tokenId,
                context.getJobDetail().getGroup() + context.getJobDetail().getName(),
                e);
        jex = new JobExecutionException(msg, e, true);
      }
      jex.setUnscheduleAllTriggers(true);
      // TODO This will lead to an endless loop
      // throw jex;
    }
  }
  public void execute(JobExecutionContext context) throws JobExecutionException {
    JobDataMap properties = context.getMergedJobDataMap();
    long language = 0;
    boolean isMultilanguage = false;
    try {
      language = Long.parseLong(properties.getString("language"));

      if (language == -1) {
        isMultilanguage = true;
      }
    } catch (Exception e4) {
      language = APILocator.getLanguageAPI().getDefaultLanguage().getId();
    }
    String filePath = null;

    String logPath = "";
    String fileName = "";
    try {
      filePath = (String) properties.get("filePath");

      logPath = pluginAPI.loadProperty("org.dotcms.plugins.contentImporter", "logFile");
      File file = new File(filePath);
      fileName = file.getName();
      int index = fileName.lastIndexOf(".");
      if (-1 < index) fileName = fileName.substring(0, index);
    } catch (Exception e) {
    }

    try {
      String structure = (String) properties.get("structure");

      String[] fields = {};
      if (UtilMethods.isSet(properties.get("fields"))) {
        String[] strFields = ((String) properties.get("fields")).split(",");
        List<String> longFields = new ArrayList<String>(strFields.length);
        for (String field : strFields) {
          longFields.add(field);
        }

        String[] tempArray = new String[longFields.size()];
        for (int pos = 0; pos < longFields.size(); ++pos) {
          tempArray[pos] = longFields.get(pos);
        }
        fields = tempArray;
      }

      String reportEmail = (String) properties.get("reportEmail");

      String csvSeparatorDelimiter = (String) properties.get("csvSeparatorDelimiter");
      if (!UtilMethods.isSet(csvSeparatorDelimiter)) csvSeparatorDelimiter = ",";
      else csvSeparatorDelimiter = "" + csvSeparatorDelimiter.trim().charAt(0);

      String csvTextDelimiter = (String) properties.get("csvTextDelimiter");
      if (UtilMethods.isSet(csvTextDelimiter))
        csvTextDelimiter = "" + csvTextDelimiter.trim().charAt(0);

      boolean publishContent = new Boolean((String) properties.get("publishContent"));

      HashMap<String, List<String>> results = new HashMap<String, List<String>>();
      results.put("warnings", new ArrayList<String>());
      results.put("errors", new ArrayList<String>());
      results.put("messages", new ArrayList<String>());
      results.put("results", new ArrayList<String>());

      File tempfile = new File(filePath);
      List<File> filesList = new ArrayList<File>();
      if (!tempfile.exists()) {
        ((List<String>) results.get("errors")).add("File: " + filePath + " doesn't exist.");

        sendResults(results, reportEmail, fileName + " Import Results", logPath, fileName);
      } else if (tempfile.isDirectory()) {
        File[] files = tempfile.listFiles();
        for (File f : files) {
          if (f.getName().toLowerCase().endsWith(".csv")) {
            filesList.add(f);
          }
        }
      } else {
        filesList.add(tempfile);
      }
      Collections.sort(filesList);
      for (File file : filesList) {
        if (!file.exists()) {
          ((List<String>) results.get("errors")).add("File: " + filePath + " doesn't exist.");

          sendResults(results, reportEmail, fileName + " Import Results", logPath, fileName);
        } else if (!file.isFile()) {
          ((List<String>) results.get("errors")).add(filePath + " isn't a file.");

          sendResults(results, reportEmail, fileName + " Import Results", logPath, fileName);
        } else if (!file.canRead()) {
          ((List<String>) results.get("errors")).add("File: " + filePath + " can't be readed.");

          sendResults(results, reportEmail, fileName + " Import Results", logPath, fileName);
        } else {
          Reader reader = null;
          CsvReader csvreader = null;

          try {
            File renameFile = new File(file.getPath() + ".lock");
            boolean renamed = file.renameTo(renameFile);
            file = renameFile;

            reader = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
            csvreader = new CsvReader(reader, csvSeparatorDelimiter.charAt(0));

            if (UtilMethods.isSet(csvTextDelimiter))
              csvreader.setTextQualifier(csvTextDelimiter.charAt(0));

            csvreader.setSafetySwitch(false);

            User user = APILocator.getUserAPI().getSystemUser();

            if (csvreader.readHeaders()) {
              ContentletUtil contentletUtil = new ContentletUtil(reader, csvreader);
              results =
                  contentletUtil.importFile(
                      structure, fields, false, user, isMultilanguage, language, publishContent);
            }
          } catch (Exception e) {
            ((List<String>) results.get("errors")).add("Exception: " + e.toString());
            Logger.error(ContentImporterThread.class, e.getMessage(), e);
          } finally {
            if (reader != null) {
              try {
                reader.close();
              } catch (Exception e) {
              }
            }

            if (csvreader != null) {
              try {
                csvreader.close();
              } catch (Exception e) {
              }
            }

            moveImportedFile(file.getPath());
            sendResults(results, reportEmail, fileName + " Import Results", logPath, fileName);
          }
        }
      }
    } catch (Exception e1) {
      Logger.warn(this, e1.toString());
    }
  }
  protected JobState getJobState(JobDataMap jobDataMap) {
    Map<String, Object> jobStateMap =
        (Map<String, Object>) jobDataMap.get(SchedulerEngine.JOB_STATE);

    return JobStateSerializeUtil.deserialize(jobStateMap);
  }
 @Override
 public Object fromJobData(JobDataMap jobData) {
   return jobData.get(EVENT_KEY);
 }
예제 #20
0
  public void execute(JobExecutionContext context) throws JobExecutionException {
    String jobName = context.getJobDetail().getFullName();
    JobDataMap data = context.getJobDetail().getJobDataMap();

    MonitorTimedeventqueue mqueue = (MonitorTimedeventqueue) data.get("mqueue");
    if (mqueue != null) {
      Integer objectid = mqueue.getObjectId();
      MonitorHostAll monitorhost = monitorHostService.getMonitorHostAll(objectid);

      if (monitorhost == null) {
        System.out.println("主机信息,id=" + objectid + "似乎被删除,无法找到");
        return;
      }
      // 判断是否监控
      if ((monitorhost.getActiveChecksEnabled() == null)
          || (monitorhost.getActiveChecksEnabled() == 0)) {
        System.out.println("主机信息,id=" + objectid + "ActiveCheck is set to false");
        // set host checkflag = 0
        if (monitorhost.getCheckFlag() == null || monitorhost.getCheckFlag() == 1) {
          monitorhost.setCheckFlag(0);
          monitorHostService.updateMonitorHostAll(monitorhost);
        }

        return;
      }
      // 判断是否在监控工作时间以内
      if (monitorhost.getCheckTimeperiod() != null) {
        if (!MonitorJobUtil.checkinWorktime(
            DateUtil.getNow(), monitorhost.getCheckTimeperiod().getTimerangers())) {
          // set host checkflag = 0
          if (monitorhost.getCheckFlag() == null || monitorhost.getCheckFlag() == 1) {
            monitorhost.setCheckFlag(0);
            monitorHostService.updateMonitorHostAll(monitorhost);
          }
          return;
        }
      }
      downtime = 0;
      // 判断是否在downtime时间内
      if (monitorSupportService.checkHostDowntime(objectid, DateUtil.getNow())) {
        downtime = 1;
      }
      notification = 0;

      MonitorHostStatus hoststatus = monitorHostService.getMonitorHostStatus(objectid);
      String hostAddress = monitorhost.getHostAddress();
      String commandLine = monitorhost.getCheckCommand().getCommandLine();
      String commandName = monitorhost.getCheckCommand().getCommandName();
      String commandArgs = monitorhost.getCheckCommandArgs();
      try {
        String checkedbeftime = DateUtil.getNow();
        String message = "";
        // String message = "PING OK - Packet loss = 0%, RTA = 2.25
        // ms|rta=2.253000ms;3000.000000;5000.000000;0.000000 pl=0%;80;100;0";

        message = MonitorUtils.commandExec(hostAddress, commandLine, commandArgs);
        System.out.println(message);
        String checkedafttime = DateUtil.getNow();
        // check whether first check
        if (monitorhost.getCheckFlag() != null && monitorhost.getCheckFlag() == 0) {
          // continue to check from uncheck as first check
          // 1、update last history record's endtime to last check time
          MonitorHostchecks monitorcheck =
              monitorHostService.getLattestMonitorHostchecks(monitorhost.getHostId());
          if (monitorcheck != null) {
            if (hoststatus != null) {
              monitorcheck.setEndTime(hoststatus.getStatusUpdateTime());
            } else {
              monitorcheck.setEndTime(checkedafttime);
            }
            monitorHostService.updateMonitorHostchecks(monitorcheck);
          }
        }

        if ((message.indexOf(STATUS_OK) != -1) || (message.indexOf(STATUS_WARNING) != -1)) {
          // up-ok or warning
          if (hoststatus != null) {
            // update 0:up  1:down
            if (hoststatus.getCurrentState() == 0) {
              // no change
              hoststatus.setLastCheck(checkedbeftime);
              hoststatus.setStatusUpdateTime(checkedafttime);
              hoststatus.setLastTimeUp(checkedbeftime);
              if (message.indexOf("|") != -1) {
                hoststatus.setOutput(message.substring(0, message.indexOf("|")));
                hoststatus.setPerfdata(message.substring(message.indexOf("|") + 1));
              } else {
                hoststatus.setOutput(message);
              }
              hoststatus.setCurrentCheckAttempt(1);
              hoststatus.setNormalCheckInterval(monitorhost.getCheckInterval());
              hoststatus.setRetryCheckInterval(monitorhost.getRetryInterval());
              hoststatus.setMaxCheckAttempts(monitorhost.getMaxCheckAttempts());
              hoststatus.setNextCheck(
                  DateUtil.getNewTime(checkedafttime, (int) (monitorhost.getCheckInterval() * 60)));
              monitorHostService.updateMonitorHostStatus(hoststatus);

              if (monitorhost.getCheckFlag() != null && monitorhost.getCheckFlag() == 0) {
                // add new check to history record
                MonitorHostchecks MHcheck = new MonitorHostchecks();
                MHcheck.setCheckType(0);
                MHcheck.setCommandArgs(commandArgs);
                MHcheck.setCommandId(monitorhost.getCheckCommand().getCommandId());
                MHcheck.setCommandLine(commandLine);
                MHcheck.setCurrentCheckAttempt(hoststatus.getCurrentCheckAttempt());
                MHcheck.setExecutionTime(Double.valueOf(0));
                MHcheck.setHostId(monitorhost.getHostId());
                MHcheck.setLatency(Double.valueOf(0));
                MHcheck.setMaxCheckAttempts(hoststatus.getMaxCheckAttempts());
                MHcheck.setOutput(hoststatus.getOutput());
                MHcheck.setPerfdata(hoststatus.getPerfdata());
                MHcheck.setReturnCode(0);
                MHcheck.setStartTime(hoststatus.getStatusUpdateTime());
                MHcheck.setStateType(0);
                MHcheck.setState(hoststatus.getCurrentState());
                MHcheck.setTimeout(0);
                monitorHostService.saveMonitorHostchecks(MHcheck);
              }

            } else {
              // changed status host recovery!
              // first  log history
              // 1、update last history record's endtime to last check time
              MonitorHostchecks monitorcheck =
                  monitorHostService.getLattestMonitorHostchecks(monitorhost.getHostId());
              if (monitorcheck != null) {
                if (monitorcheck.getState() != 0) {
                  // truely recovery from down not from retry!!!
                  monitorcheck.setEndTime(checkedafttime);
                  monitorHostService.updateMonitorHostchecks(monitorcheck);
                }
              }
              hoststatus.setCurrentState(0);
              hoststatus.setLastTimeDown(hoststatus.getStatusUpdateTime());
              hoststatus.setLastTimeUp(checkedafttime);
              hoststatus.setCurrentCheckAttempt(1);
              hoststatus.setLastCheck(checkedbeftime);
              if (message.indexOf("|") != -1) {
                hoststatus.setOutput(message.substring(0, message.indexOf("|")));
                hoststatus.setPerfdata(message.substring(message.indexOf("|") + 1));
              } else {
                hoststatus.setOutput(message);
              }
              hoststatus.setStatusUpdateTime(checkedafttime);
              hoststatus.setNormalCheckInterval(monitorhost.getCheckInterval());
              hoststatus.setRetryCheckInterval(monitorhost.getRetryInterval());
              hoststatus.setMaxCheckAttempts(monitorhost.getMaxCheckAttempts());
              hoststatus.setNextCheck(
                  DateUtil.getNewTime(
                      checkedafttime, (int) (hoststatus.getNormalCheckInterval() * 60)));
              hoststatus.setLastHardState(0);
              hoststatus.setLastStateChange(checkedafttime);
              hoststatus.setLastHardStateChange(checkedafttime);
              if (hoststatus.getStateType() == 0) {
                // 原来是retrey 现在变成check
                MonitorTaskDelegate.getinstance()
                    .changeTrigger(
                        mqueue, DateUtil.getDate(hoststatus.getNextCheck(), "yyyyMMddHHmmss"), 0);
              }
              hoststatus.setStateType(1);
              monitorHostService.updateMonitorHostStatus(hoststatus);
              if (monitorcheck != null) {
                if (monitorcheck.getState() != 0) {
                  // add new check to history record
                  MonitorHostchecks MHcheck = new MonitorHostchecks();
                  MHcheck.setCheckType(0);
                  MHcheck.setCommandArgs(commandArgs);
                  MHcheck.setCommandId(monitorhost.getCheckCommand().getCommandId());
                  MHcheck.setCommandLine(commandLine);
                  MHcheck.setCurrentCheckAttempt(hoststatus.getCurrentCheckAttempt());
                  MHcheck.setExecutionTime(Double.valueOf(0));
                  MHcheck.setHostId(monitorhost.getHostId());
                  MHcheck.setLatency(Double.valueOf(0));
                  MHcheck.setMaxCheckAttempts(hoststatus.getMaxCheckAttempts());
                  MHcheck.setOutput(hoststatus.getOutput());
                  MHcheck.setPerfdata(hoststatus.getPerfdata());
                  MHcheck.setReturnCode(0);
                  MHcheck.setStartTime(hoststatus.getStatusUpdateTime());
                  MHcheck.setStateType(0);
                  MHcheck.setState(hoststatus.getCurrentState());
                  MHcheck.setTimeout(0);
                  monitorHostService.saveMonitorHostchecks(MHcheck);
                  // NotifyOnRecovery
                  if (monitorhost.getNotifyOnRecovery() != null
                      && monitorhost.getNotifyOnRecovery() > 0) {
                    notification = 1;
                  }
                }
              }
            }
          } else {
            // save first time
            hoststatus = new MonitorHostStatus();
            hoststatus.setHostId(monitorhost.getHostId());
            hoststatus.setStatusUpdateTime(checkedafttime);
            if (message.indexOf("|") != -1) {
              hoststatus.setOutput(message.substring(0, message.indexOf("|")));
              hoststatus.setPerfdata(message.substring(message.indexOf("|") + 1));
            } else {
              hoststatus.setOutput(message);
            }
            hoststatus.setLastCheck(checkedbeftime);
            hoststatus.setLastTimeUp(checkedafttime);
            hoststatus.setNextCheck(
                DateUtil.getNewTime(checkedafttime, (int) (monitorhost.getCheckInterval() * 60)));
            hoststatus.setCurrentState(0);
            hoststatus.setHasBeenChecked(1);
            hoststatus.setShouldBeScheduled(1);
            hoststatus.setCurrentCheckAttempt(1);
            hoststatus.setLastTimeDown("");
            hoststatus.setMaxCheckAttempts(monitorhost.getMaxCheckAttempts());
            hoststatus.setCheckType(0);
            hoststatus.setLastStateChange(checkedbeftime);
            hoststatus.setLastHardStateChange(checkedbeftime);
            hoststatus.setLastHardState(0);
            hoststatus.setLastTimeUnreachable("");
            hoststatus.setStateType(1);
            hoststatus.setLastNotification("");
            hoststatus.setNextNotification("");
            hoststatus.setNotificationsEnabled(monitorhost.getNotificationsEnabled());
            hoststatus.setProblemHasBeenAcknowledged(0);
            hoststatus.setAcknowledgementType(0);
            hoststatus.setCurrentNotificationNumber(0);
            hoststatus.setPassiveChecksEnabled(monitorhost.getPassiveChecksEnabled());
            hoststatus.setActiveChecksEnabled(monitorhost.getActiveChecksEnabled());
            hoststatus.setEventHandlerEnabled(monitorhost.getEventHandlerEnabled());
            hoststatus.setFlapDetectionEnabled(monitorhost.getFlapDetectionEnabled());
            hoststatus.setIsFlapping(0);
            hoststatus.setPercentStateChange(Double.valueOf(0));
            hoststatus.setLatency(Double.valueOf(0));
            hoststatus.setExecutionTime(Double.valueOf(0));
            hoststatus.setEventHandler("");
            hoststatus.setCheckCommand(commandName);
            hoststatus.setNormalCheckInterval(monitorhost.getCheckInterval());
            hoststatus.setRetryCheckInterval(monitorhost.getRetryInterval());
            hoststatus.setCheckTimeperiodId(monitorhost.getCheckTimeperiod().getTimeperiodId());
            monitorHostService.saveMonitorHostStatus(hoststatus);

            // add new check to history record
            MonitorHostchecks MHcheck = new MonitorHostchecks();
            MHcheck.setCheckType(0);
            MHcheck.setCommandArgs(commandArgs);
            MHcheck.setCommandId(monitorhost.getCheckCommand().getCommandId());
            MHcheck.setCommandLine(commandLine);
            MHcheck.setCurrentCheckAttempt(hoststatus.getCurrentCheckAttempt());
            MHcheck.setExecutionTime(Double.valueOf(0));
            MHcheck.setHostId(monitorhost.getHostId());
            MHcheck.setLatency(Double.valueOf(0));
            MHcheck.setMaxCheckAttempts(hoststatus.getMaxCheckAttempts());
            MHcheck.setOutput(hoststatus.getOutput());
            MHcheck.setPerfdata(hoststatus.getPerfdata());
            MHcheck.setReturnCode(0);
            MHcheck.setStartTime(hoststatus.getStatusUpdateTime());
            MHcheck.setStateType(0);
            MHcheck.setState(hoststatus.getCurrentState());
            MHcheck.setTimeout(0);
            monitorHostService.saveMonitorHostchecks(MHcheck);
          }
        } else {
          // critical or unknow status
          if (hoststatus != null) {
            // update 0:up  1:down
            if (hoststatus.getCurrentState() == 0) {
              // changed status
              hoststatus.setCurrentState(1);
              hoststatus.setLastTimeUp(hoststatus.getStatusUpdateTime());
              hoststatus.setLastTimeDown(checkedafttime);
              hoststatus.setCurrentCheckAttempt(1);
              hoststatus.setLastCheck(checkedbeftime);
              hoststatus.setStatusUpdateTime(checkedafttime);
              hoststatus.setOutput(message);
              hoststatus.setPerfdata("");
              hoststatus.setNormalCheckInterval(monitorhost.getCheckInterval());
              hoststatus.setRetryCheckInterval(monitorhost.getRetryInterval());
              hoststatus.setMaxCheckAttempts(monitorhost.getMaxCheckAttempts());
              hoststatus.setNextCheck(
                  DateUtil.getNewTime(checkedafttime, (int) (monitorhost.getRetryInterval() * 60)));
              hoststatus.setLastStateChange(checkedafttime);
              hoststatus.setStateType(0); // retry attempt
              monitorHostService.updateMonitorHostStatus(hoststatus);
              // retry trriger
              MonitorTaskDelegate.getinstance()
                  .changeTrigger(
                      mqueue, DateUtil.getDate(hoststatus.getNextCheck(), "yyyyMMddHHmmss"), 1);

            } else {
              // no change
              if (hoststatus.getStateType() == 0) {
                hoststatus.setLastTimeDown(hoststatus.getStatusUpdateTime());
                hoststatus.setLastCheck(checkedbeftime);
                hoststatus.setOutput(message);
                hoststatus.setPerfdata("");
                hoststatus.setStatusUpdateTime(checkedafttime);
                hoststatus.setLastStateChange(checkedafttime);
                hoststatus.setNormalCheckInterval(monitorhost.getCheckInterval());
                hoststatus.setRetryCheckInterval(monitorhost.getRetryInterval());
                hoststatus.setMaxCheckAttempts(monitorhost.getMaxCheckAttempts());
                if (hoststatus.getCurrentCheckAttempt() >= hoststatus.getMaxCheckAttempts()) {
                  // max attempt
                  hoststatus.setCurrentCheckAttempt(1);
                  hoststatus.setNextCheck(
                      DateUtil.getNewTime(
                          checkedafttime, (int) (monitorhost.getCheckInterval() * 60)));
                  hoststatus.setLastHardState(1);
                  hoststatus.setLastHardStateChange(checkedafttime);
                  hoststatus.setStateType(1);
                  MonitorTaskDelegate.getinstance()
                      .changeTrigger(
                          mqueue, DateUtil.getDate(hoststatus.getNextCheck(), "yyyyMMddHHmmss"), 0);
                  // NotifyOnDown
                  if ((downtime == 0)
                      || (monitorhost.getNotifyOnDowntime() != null
                          && monitorhost.getNotifyOnDowntime() == 1)) {
                    if (monitorhost.getNotifyOnDown() != null
                        && monitorhost.getNotifyOnDown() == 1) {
                      notification = 2; // server down definitely after serval retry check.
                    }
                  }

                } else {
                  // retry attempt
                  hoststatus.setCurrentCheckAttempt(hoststatus.getCurrentCheckAttempt() + 1);
                  hoststatus.setNextCheck(
                      DateUtil.getNewTime(
                          checkedafttime, (int) (monitorhost.getRetryInterval() * 60)));
                }
                monitorHostService.updateMonitorHostStatus(hoststatus);

                if (hoststatus.getStateType() == 1) {
                  // first  log history
                  // 1、update last history record's endtime to last check time
                  MonitorHostchecks monitorcheck =
                      monitorHostService.getLattestMonitorHostchecks(monitorhost.getHostId());
                  if (monitorcheck != null) {
                    monitorcheck.setEndTime(checkedafttime);
                  }
                  monitorHostService.updateMonitorHostchecks(monitorcheck);
                  // add new check to history record
                  MonitorHostchecks MHcheck = new MonitorHostchecks();
                  MHcheck.setCheckType(0);
                  MHcheck.setCommandArgs(commandArgs);
                  MHcheck.setCommandId(monitorhost.getCheckCommand().getCommandId());
                  MHcheck.setCommandLine(commandLine);
                  MHcheck.setCurrentCheckAttempt(hoststatus.getCurrentCheckAttempt());
                  MHcheck.setExecutionTime(Double.valueOf(0));
                  MHcheck.setHostId(monitorhost.getHostId());
                  MHcheck.setLatency(Double.valueOf(0));
                  MHcheck.setMaxCheckAttempts(hoststatus.getMaxCheckAttempts());
                  MHcheck.setOutput(hoststatus.getOutput());
                  MHcheck.setPerfdata(hoststatus.getPerfdata());
                  MHcheck.setReturnCode(0);
                  MHcheck.setStartTime(hoststatus.getStatusUpdateTime());
                  MHcheck.setStateType(0);
                  MHcheck.setState(hoststatus.getCurrentState());
                  MHcheck.setTimeout(0);
                  monitorHostService.saveMonitorHostchecks(MHcheck);
                }

              } else {

                // nomal check
                hoststatus.setLastTimeDown(hoststatus.getStatusUpdateTime());
                hoststatus.setLastCheck(checkedbeftime);
                hoststatus.setOutput(message);
                hoststatus.setPerfdata("");
                hoststatus.setNormalCheckInterval(monitorhost.getCheckInterval());
                hoststatus.setRetryCheckInterval(monitorhost.getRetryInterval());
                hoststatus.setMaxCheckAttempts(monitorhost.getMaxCheckAttempts());
                hoststatus.setStatusUpdateTime(checkedafttime);
                hoststatus.setCurrentCheckAttempt(1);
                hoststatus.setNextCheck(
                    DateUtil.getNewTime(
                        checkedafttime, (int) (monitorhost.getCheckInterval() * 60)));
                monitorHostService.updateMonitorHostStatus(hoststatus);

                if (monitorhost.getCheckFlag() != null && monitorhost.getCheckFlag() == 0) {
                  // add new check to history record
                  MonitorHostchecks MHcheck = new MonitorHostchecks();
                  MHcheck.setCheckType(0);
                  MHcheck.setCommandArgs(commandArgs);
                  MHcheck.setCommandId(monitorhost.getCheckCommand().getCommandId());
                  MHcheck.setCommandLine(commandLine);
                  MHcheck.setCurrentCheckAttempt(hoststatus.getCurrentCheckAttempt());
                  MHcheck.setExecutionTime(Double.valueOf(0));
                  MHcheck.setHostId(monitorhost.getHostId());
                  MHcheck.setLatency(Double.valueOf(0));
                  MHcheck.setMaxCheckAttempts(hoststatus.getMaxCheckAttempts());
                  MHcheck.setOutput(hoststatus.getOutput());
                  MHcheck.setPerfdata(hoststatus.getPerfdata());
                  MHcheck.setReturnCode(0);
                  MHcheck.setStartTime(hoststatus.getStatusUpdateTime());
                  MHcheck.setStateType(0);
                  MHcheck.setState(hoststatus.getCurrentState());
                  MHcheck.setTimeout(0);
                  monitorHostService.saveMonitorHostchecks(MHcheck);
                }

                if ((downtime == 0)
                    || (monitorhost.getNotifyOnDowntime() != null
                        && monitorhost.getNotifyOnDowntime() == 1)) {
                  if (monitorhost.getNotifyOnDown() != null && monitorhost.getNotifyOnDown() == 1) {
                    notification = 3; // server still down.
                  }
                }
              }
            }
          } else {
            // save
            hoststatus = new MonitorHostStatus();
            hoststatus.setHostId(monitorhost.getHostId());
            hoststatus.setStatusUpdateTime(checkedafttime);
            hoststatus.setOutput(message);
            hoststatus.setPerfdata("");
            hoststatus.setLastCheck(checkedbeftime);
            hoststatus.setLastTimeUp("");
            hoststatus.setNextCheck(
                DateUtil.getNewTime(checkedafttime, (int) (monitorhost.getRetryInterval() * 60)));
            hoststatus.setCurrentState(1);
            hoststatus.setHasBeenChecked(1);
            hoststatus.setShouldBeScheduled(1);
            hoststatus.setCurrentCheckAttempt(1);
            hoststatus.setLastTimeDown(checkedafttime);
            hoststatus.setMaxCheckAttempts(monitorhost.getMaxCheckAttempts());
            hoststatus.setCheckType(0);
            hoststatus.setLastStateChange(checkedbeftime);
            hoststatus.setLastHardStateChange(checkedbeftime);
            hoststatus.setLastHardState(0);
            hoststatus.setLastTimeUnreachable("");
            hoststatus.setStateType(0);
            hoststatus.setLastNotification("");
            hoststatus.setNextNotification("");
            hoststatus.setNotificationsEnabled(monitorhost.getNotificationsEnabled());
            hoststatus.setProblemHasBeenAcknowledged(0);
            hoststatus.setAcknowledgementType(0);
            hoststatus.setCurrentNotificationNumber(0);
            hoststatus.setPassiveChecksEnabled(monitorhost.getPassiveChecksEnabled());
            hoststatus.setActiveChecksEnabled(monitorhost.getActiveChecksEnabled());
            hoststatus.setEventHandlerEnabled(monitorhost.getEventHandlerEnabled());
            hoststatus.setFlapDetectionEnabled(monitorhost.getFlapDetectionEnabled());
            hoststatus.setIsFlapping(0);
            hoststatus.setPercentStateChange(Double.valueOf(0));
            hoststatus.setLatency(Double.valueOf(0));
            hoststatus.setExecutionTime(Double.valueOf(0));
            hoststatus.setEventHandler("");
            hoststatus.setCheckCommand(commandName);
            hoststatus.setNormalCheckInterval(monitorhost.getCheckInterval());
            hoststatus.setRetryCheckInterval(monitorhost.getRetryInterval());
            hoststatus.setCheckTimeperiodId(monitorhost.getCheckTimeperiod().getTimeperiodId());
            monitorHostService.saveMonitorHostStatus(hoststatus);

            // add new check to history record
            MonitorHostchecks MHcheck = new MonitorHostchecks();
            MHcheck.setCheckType(0);
            MHcheck.setCommandArgs(commandArgs);
            MHcheck.setCommandId(monitorhost.getCheckCommand().getCommandId());
            MHcheck.setCommandLine(commandLine);
            MHcheck.setCurrentCheckAttempt(hoststatus.getCurrentCheckAttempt());
            MHcheck.setExecutionTime(Double.valueOf(0));
            MHcheck.setHostId(monitorhost.getHostId());
            MHcheck.setLatency(Double.valueOf(0));
            MHcheck.setMaxCheckAttempts(hoststatus.getMaxCheckAttempts());
            MHcheck.setOutput(hoststatus.getOutput());
            MHcheck.setPerfdata(hoststatus.getPerfdata());
            MHcheck.setReturnCode(0);
            MHcheck.setStartTime(hoststatus.getStatusUpdateTime());
            MHcheck.setStateType(0);
            MHcheck.setState(hoststatus.getCurrentState());
            MHcheck.setTimeout(0);
            monitorHostService.saveMonitorHostchecks(MHcheck);

            MonitorTaskDelegate.getinstance()
                .changeTrigger(
                    mqueue, DateUtil.getDate(hoststatus.getNextCheck(), "yyyyMMddHHmmss"), 1);
          }
        }

        if (monitorhost.getCheckFlag() != null && monitorhost.getCheckFlag() == 0) {
          monitorhost.setCheckFlag(1);
          monitorHostService.updateMonitorHostAll(monitorhost);
        }

        // 修改timed event
        mqueue.setScheduledTime(hoststatus.getNextCheck());
        monitorSupportService.updateMonitorTimedeventqueue(mqueue);
        // notification about
        if (notification > 0) {
          // need notification
          if (notification == 1) {
            // server recovery
            if (monitorhost.getContactGroups() != null) {
              MonitorNotifications mn = new MonitorNotifications();
              mn.setContactGroup(monitorhost.getContactGroups());
              mn.setNotificationTime(DateUtil.getNow());
              mn.setNotificationType(1); // host
              mn.setObjectId(monitorhost.getHostId());
              mn.setOutput(
                  "<pre>时间:"
                      + hoststatus.getStatusUpdateTime()
                      + "		主机:"
                      + monitorhost.getDisplayName()
                      + "	状态:"
                      + STATUS_ARR[hoststatus.getCurrentState()]
                      + "	返回信息:["
                      + hoststatus.getOutput()
                      + "|"
                      + hoststatus.getPerfdata()
                      + "]</pre>");
              mn.setSendOrNot(0);
              mn.setState(hoststatus.getCurrentState());
              monitorSupportService.saveMonitorNotifications(mn);
            }
          } else if (notification == 2) {
            // server first down
            if (monitorhost.getContactGroups() != null) {
              MonitorNotifications mn = new MonitorNotifications();
              mn.setContactGroup(monitorhost.getContactGroups());
              mn.setNotificationTime(DateUtil.getNow());
              mn.setNotificationType(1);
              mn.setObjectId(monitorhost.getHostId());
              mn.setOutput(
                  "<pre>时间:"
                      + hoststatus.getStatusUpdateTime()
                      + "		主机:"
                      + monitorhost.getDisplayName()
                      + "	状态:"
                      + STATUS_ARR[hoststatus.getCurrentState()]
                      + "	返回信息:["
                      + hoststatus.getOutput()
                      + "]</pre>");
              mn.setSendOrNot(0);
              mn.setState(hoststatus.getCurrentState());
              monitorSupportService.saveMonitorNotifications(mn);
            }
          }
        }

      } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
      }
    }
  }
  /**
   * Though it says init() it does not instantiate objects every time the service is running. This
   * simply initialize the local variables with pre-instantiated objects.
   *
   * @param jobExecutionContext is the Quartz context
   * @return true if it is successfully executed.
   */
  public boolean init(JobExecutionContext jobExecutionContext) {

    JobDataMap jdm = jobExecutionContext.getMergedJobDataMap();
    Map<String, Object> parameters =
        (Map<String, Object>) jdm.get(MessageProcessorConstants.PARAMETERS);
    sender = (BlockingMsgSender) jdm.get(ScheduledMessageForwardingProcessor.BLOCKING_SENDER);

    String mdaParam = (String) parameters.get(MessageProcessorConstants.MAX_DELIVER_ATTEMPTS);
    if (mdaParam != null) {
      try {
        maxDeliverAttempts = Integer.parseInt(mdaParam);
      } catch (NumberFormatException nfe) {
        parameters.remove(MessageProcessorConstants.MAX_DELIVER_ATTEMPTS);
        log.error("Invalid value for max delivery attempts switching back to default value", nfe);
      }
    }

    if (jdm.get(ForwardingProcessorConstants.TARGET_ENDPOINT) != null) {
      targetEndpoint = (String) jdm.get(ForwardingProcessorConstants.TARGET_ENDPOINT);
    }

    String ri = (String) parameters.get(MessageProcessorConstants.RETRY_INTERVAL);
    if (ri != null) {
      try {
        retryInterval = Integer.parseInt(ri);
      } catch (NumberFormatException nfe) {
        parameters.remove(MessageProcessorConstants.RETRY_INTERVAL);
        log.error("Invalid value for retry interval switching back to default value", nfe);
      }
    }

    messageProcessor = (MessageProcessor) jdm.get(MessageProcessorConstants.PROCESSOR_INSTANCE);
    messageConsumer = messageProcessor.getMessageConsumer();

    if (parameters.get(ForwardingProcessorConstants.FAULT_SEQUENCE) != null) {
      faultSeq = (String) parameters.get(ForwardingProcessorConstants.FAULT_SEQUENCE);
    }

    if (parameters.get(ForwardingProcessorConstants.REPLY_SEQUENCE) != null) {
      replySeq = (String) parameters.get(ForwardingProcessorConstants.REPLY_SEQUENCE);
    }

    if (jdm.get(ForwardingProcessorConstants.NON_RETRY_STATUS_CODES) != null) {
      nonRetryStatusCodes = (String[]) jdm.get(ForwardingProcessorConstants.NON_RETRY_STATUS_CODES);
    }

    if (jdm.get(ForwardingProcessorConstants.THROTTLE) != null) {
      isThrottling = (Boolean) jdm.get(ForwardingProcessorConstants.THROTTLE);
    }

    if (isThrottling) {
      if (jdm.get(ForwardingProcessorConstants.THROTTLE_INTERVAL) != null) {
        throttlingInterval = (Long) jdm.get(ForwardingProcessorConstants.THROTTLE_INTERVAL);
      }
    }

    // Configure property for the drop message after maximum delivery
    if (parameters.get(ForwardingProcessorConstants.MAX_DELIVERY_DROP) != null) {
      if ((parameters.get(ForwardingProcessorConstants.MAX_DELIVERY_DROP))
          .toString()
          .equals("Enabled")) {
        if (this.maxDeliverAttempts > 0) {
          isMaxDeliveryAttemptDropEnabled = true;
        }
      }
    }

    return true;
  }