@DwrPermission(admin = true)
  public ProcessResult getMaintenanceEvents() {
    ProcessResult response = new ProcessResult();
    final Translations translations = getTranslations();

    List<MaintenanceEventVO> events = new MaintenanceEventDao().getMaintenanceEvents();
    Collections.sort(
        events,
        new Comparator<MaintenanceEventVO>() {
          @Override
          public int compare(MaintenanceEventVO m1, MaintenanceEventVO m2) {
            return m1.getDescription()
                .translate(translations)
                .compareTo(m1.getDescription().translate(translations));
          }
        });
    response.addData("events", events);

    List<IntStringPair> dataSources = new ArrayList<IntStringPair>();
    for (DataSourceVO<?> ds : new DataSourceDao().getDataSources())
      dataSources.add(new IntStringPair(ds.getId(), ds.getName()));
    response.addData("dataSources", dataSources);

    return response;
  }
  private boolean initializeDataSource(DataSourceVO<?> vo) {
    synchronized (runningDataSources) {
      // If the data source is already running, just quit.
      if (isDataSourceRunning(vo.getId())) return false;

      // Ensure that the data source is enabled.
      Assert.isTrue(vo.isEnabled());

      // Create and initialize the runtime version of the data source.
      DataSourceRT dataSource = vo.createDataSourceRT();
      dataSource.initialize();

      // Add it to the list of running data sources.
      runningDataSources.add(dataSource);

      // Add the enabled points to the data source.
      List<DataPointVO> dataSourcePoints = new DataPointDao().getDataPoints(vo.getId(), null);
      for (DataPointVO dataPoint : dataSourcePoints) {
        if (dataPoint.isEnabled()) startDataPoint(dataPoint);
      }

      LOG.info("Data source '" + vo.getName() + "' initialized");

      return true;
    }
  }
 public DataSourceVO<?> mapRow(ResultSet rs, int rowNum) throws SQLException {
   DataSourceVO<?> ds =
       (DataSourceVO<?>)
           SerializationHelper.readObjectInContext(rs.getBlob(5).getBinaryStream());
   ds.setId(rs.getInt(1));
   ds.setXid(rs.getString(2));
   ds.setName(rs.getString(3));
   ds.setDefinition(ModuleRegistry.getDataSourceDefinition(rs.getString(4)));
   return ds;
 }
 public void _updateDataSource(DataSourceVO<?> vo) {
   ejt.update(
       "update dataSources set xid=?, name=?, dataSourceType=?, data=? where id=?",
       new Object[] {
         vo.getXid(),
         vo.getName(),
         vo.getDefinition().getDataSourceTypeName(),
         SerializationHelper.writeObject(vo),
         vo.getId()
       },
       new int[] {Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.BLOB, Types.INTEGER});
 }
  public void saveDataSource(DataSourceVO<?> vo) {
    // If the data source is running, stop it.
    stopDataSource(vo.getId());

    // In case this is a new data source, we need to save to the database first so that it has a
    // proper id.
    new DataSourceDao().saveDataSource(vo);

    // If the data source is enabled, start it.
    if (vo.isEnabled()) {
      if (initializeDataSource(vo)) startDataSourcePolling(vo);
    }
  }
  @Override
  protected void importImpl() {
    String xid = json.getString("xid");

    if (StringUtils.isBlank(xid)) xid = ctx.getDataSourceDao().generateUniqueXid();

    DataSourceVO<?> vo = ctx.getDataSourceDao().getDataSource(xid);
    if (vo == null) {
      String typeStr = json.getString("type");
      if (StringUtils.isBlank(typeStr))
        addFailureMessage(
            "emport.dataSource.missingType", xid, ModuleRegistry.getDataSourceDefinitionTypes());
      else {
        DataSourceDefinition def = ModuleRegistry.getDataSourceDefinition(typeStr);
        if (def == null)
          addFailureMessage(
              "emport.dataSource.invalidType",
              xid,
              typeStr,
              ModuleRegistry.getDataSourceDefinitionTypes());
        else {
          vo = def.baseCreateDataSourceVO();
          vo.setXid(xid);
        }
      }
    }

    if (vo != null) {
      try {
        // The VO was found or successfully created. Finish reading it in.
        ctx.getReader().readInto(vo, json);

        // Now validate it. Use a new response object so we can distinguish errors in this vo from
        // other errors.
        ProcessResult voResponse = new ProcessResult();
        vo.validate(voResponse);
        if (voResponse.getHasMessages())
          setValidationMessages(voResponse, "emport.dataSource.prefix", xid);
        else {
          // Sweet. Save it.
          boolean isnew = vo.isNew();
          Common.runtimeManager.saveDataSource(vo);
          addSuccessMessage(isnew, "emport.dataSource.prefix", xid);
        }
      } catch (TranslatableJsonException e) {
        addFailureMessage("emport.dataSource.prefix", xid, e.getMsg());
      } catch (JsonException e) {
        addFailureMessage("emport.dataSource.prefix", xid, getJsonExceptionMessage(e));
      }
    }
  }
  private void insertDataSource(final DataSourceVO<?> vo) {
    vo.setId(
        doInsert(
            "insert into dataSources (xid, name, dataSourceType, data) values (?,?,?,?)",
            new Object[] {
              vo.getXid(),
              vo.getName(),
              vo.getDefinition().getDataSourceTypeName(),
              SerializationHelper.writeObject(vo)
            },
            new int[] {Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.BLOB}));

    AuditEventType.raiseAddedEvent(AuditEventType.TYPE_DATA_SOURCE, vo);
  }
 @SuppressWarnings("unchecked")
 private void updateDataSource(final DataSourceVO<?> vo) {
   DataSourceVO<?> old = getDataSource(vo.getId());
   _updateDataSource(vo);
   AuditEventType.raiseChangedEvent(
       AuditEventType.TYPE_DATA_SOURCE, old, (ChangeComparable<DataSourceVO<?>>) vo);
 }
  //
  // Lifecycle
  public synchronized void initialize(boolean safe) {
    if (started) throw new ShouldNeverHappenException("RuntimeManager already started");

    // Set the started indicator to true.
    started = true;

    // Get the RTM defs from modules
    List<RuntimeManagerDefinition> defs =
        ModuleRegistry.getDefinitions(RuntimeManagerDefinition.class);
    Collections.sort(
        defs,
        new Comparator<RuntimeManagerDefinition>() {
          @Override
          public int compare(RuntimeManagerDefinition def1, RuntimeManagerDefinition def2) {
            return def1.getInitializationPriority() - def2.getInitializationPriority();
          }
        });

    // Start everything with priority up to and including 4.
    int rtmdIndex = startRTMDefs(defs, safe, 0, 4);

    // Initialize data sources that are enabled. Start by organizing all enabled data sources by
    // start priority.
    DataSourceDao dataSourceDao = new DataSourceDao();
    List<DataSourceVO<?>> configs = dataSourceDao.getDataSources();
    Map<DataSourceDefinition.StartPriority, List<DataSourceVO<?>>> priorityMap =
        new HashMap<DataSourceDefinition.StartPriority, List<DataSourceVO<?>>>();
    for (DataSourceVO<?> config : configs) {
      if (config.isEnabled()) {
        if (safe) {
          config.setEnabled(false);
          dataSourceDao.saveDataSource(config);
        } else if (config.getDefinition() != null) {
          List<DataSourceVO<?>> priorityList =
              priorityMap.get(config.getDefinition().getStartPriority());
          if (priorityList == null) {
            priorityList = new ArrayList<DataSourceVO<?>>();
            priorityMap.put(config.getDefinition().getStartPriority(), priorityList);
          }
          priorityList.add(config);
        }
      }
    }

    // Initialize the prioritized data sources. Start the polling later.
    List<DataSourceVO<?>> pollingRound = new ArrayList<DataSourceVO<?>>();
    for (DataSourceDefinition.StartPriority startPriority :
        DataSourceDefinition.StartPriority.values()) {
      List<DataSourceVO<?>> priorityList = priorityMap.get(startPriority);
      if (priorityList != null) {
        for (DataSourceVO<?> config : priorityList) {
          if (initializeDataSource(config)) pollingRound.add(config);
        }
      }
    }

    // Tell the data sources to start polling. Delaying the polling start gives the data points a
    // chance to
    // initialize such that point listeners in meta points and set point handlers can run properly.
    for (DataSourceVO<?> config : pollingRound) startDataSourcePolling(config);

    // Run everything else.
    rtmdIndex = startRTMDefs(defs, safe, rtmdIndex, Integer.MAX_VALUE);

    // Start the publishers that are enabled
    PublisherDao publisherDao = new PublisherDao();
    List<PublisherVO<? extends PublishedPointVO>> publishers = publisherDao.getPublishers();
    for (PublisherVO<? extends PublishedPointVO> vo : publishers) {
      if (vo.isEnabled()) {
        if (safe) {
          vo.setEnabled(false);
          publisherDao.savePublisher(vo);
        } else startPublisher(vo);
      }
    }

    // Schedule the Backup Task if necessary
    // No way to set the default value for Bools in SystemSettingsDao so must do here
    if (SystemSettingsDao.getBooleanValue(SystemSettingsDao.BACKUP_ENABLED, true)) {
      BackupWorkItem.schedule();
    }
  }
 private void startDataSourcePolling(DataSourceVO<?> vo) {
   DataSourceRT dataSource = getRunningDataSource(vo.getId());
   if (dataSource != null) dataSource.beginPolling();
 }
 public int compare(DataSourceVO<?> ds1, DataSourceVO<?> ds2) {
   if (StringUtils.isBlank(ds1.getName())) return -1;
   return ds1.getName().compareToIgnoreCase(ds2.getName());
 }
 public void saveDataSource(final DataSourceVO<?> vo) {
   // Decide whether to insert or update.
   if (vo.getId() == Common.NEW_ID) insertDataSource(vo);
   else updateDataSource(vo);
 }