Esempio n. 1
0
  @DwrPermission(admin = true)
  public List<StringStringPair> versionCheck() {
    if (UPGRADE_DOWNLOADER != null) return UPGRADE_DOWNLOADER.getModules();

    try {
      // Create the request
      List<Module> modules = ModuleRegistry.getModules();
      Module.sortByName(modules);

      Map<String, Object> json = new HashMap<String, Object>();
      json.put("guid", Providers.get(ICoreLicense.class).getGuid());
      json.put("description", SystemSettingsDao.getValue(SystemSettingsDao.INSTANCE_DESCRIPTION));
      json.put("distributor", Common.envProps.getString("distributor"));
      json.put(
          "domain", ControllerUtils.getDomain(WebContextFactory.get().getHttpServletRequest()));

      Map<String, String> jsonModules = new HashMap<String, String>();
      json.put("modules", jsonModules);

      jsonModules.put("core", Common.getVersion().getFullString());
      for (Module module : modules) jsonModules.put(module.getName(), module.getVersion());

      StringWriter stringWriter = new StringWriter();
      new JsonWriter(Common.JSON_CONTEXT, stringWriter).writeObject(json);
      String requestData = stringWriter.toString();

      // Send the request
      String baseUrl = Common.envProps.getString("store.url");
      baseUrl += "/servlet/versionCheck";

      HttpPost post = new HttpPost(baseUrl);
      post.setEntity(new StringEntity(requestData));
      String responseData = HttpUtils4.getTextContent(Common.getHttpClient(), post);

      // Parse the response
      JsonTypeReader jsonReader = new JsonTypeReader(responseData);
      JsonObject root = jsonReader.read().toJsonObject();

      List<StringStringPair> upgrades = new ArrayList<StringStringPair>();
      for (Map.Entry<String, JsonValue> mod : root.entrySet()) {
        String name = mod.getKey();
        String version = mod.getValue().toString();
        upgrades.add(new StringStringPair(name, version));
      }

      return upgrades;
    } catch (Exception e) {
      throw new ShouldNeverHappenException(e);
    }
  }
Esempio n. 2
0
  public static void writeChart(
      PointTimeSeriesCollection pointTimeSeriesCollection,
      boolean showLegend,
      OutputStream out,
      int width,
      int height,
      long from,
      long to)
      throws IOException {
    // 创建主题样式
    StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
    // 设置标题字体
    standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 18));
    // 设置图例的字体
    standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 14));
    // 设置轴向的字体
    standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 14));
    // 应用主题样式
    ChartFactory.setChartTheme(standardChartTheme);

    JFreeChart chart =
        ChartFactory.createTimeSeriesChart(null, null, null, null, showLegend, false, false);
    chart.setBackgroundPaint(
        SystemSettingsDao.getColour(SystemSettingsDao.CHART_BACKGROUND_COLOUR));

    XYPlot plot = chart.getXYPlot();
    ((DateAxis) plot.getDomainAxis()).setTimeZone(pointTimeSeriesCollection.getTimeZone());
    plot.setBackgroundPaint(SystemSettingsDao.getColour(SystemSettingsDao.PLOT_BACKGROUND_COLOUR));
    Color gridlines = SystemSettingsDao.getColour(SystemSettingsDao.PLOT_GRIDLINE_COLOUR);
    plot.setDomainGridlinePaint(gridlines);
    plot.setRangeGridlinePaint(gridlines);
    ((NumberAxis) plot.getRangeAxis()).setAutoRangeStickyZero(false);

    double numericMin = 0;
    double numericMax = 1;

    int numericSeriesCount = pointTimeSeriesCollection.getNumericSeriesCount();
    if (pointTimeSeriesCollection.hasNumericData()) {
      for (int i = 0; i < numericSeriesCount; i++) {
        NumericTimeSeries nts = pointTimeSeriesCollection.getNumericTimeSeries(i);
        AbstractXYItemRenderer renderer;
        if (nts.getPlotType() == DataPointVO.PlotTypes.STEP) renderer = new XYStepRenderer();
        else if (nts.getPlotType() == DataPointVO.PlotTypes.LINE)
          renderer = new XYLineAndShapeRenderer(true, false);
        else {
          XYSplineRenderer spline = new XYSplineRenderer();
          spline.setBaseShapesVisible(false);
          renderer = spline;
        }

        if (nts.getPaint() != null) renderer.setSeriesPaint(0, nts.getPaint(), false);
        if (nts.getStroke() != null) renderer.setSeriesStroke(0, nts.getStroke(), false);

        plot.setDataset(i, new TimeSeriesCollection(nts.getTimeSeries()));
        plot.setRenderer(i, renderer);
      }

      numericMin = plot.getRangeAxis().getLowerBound();
      numericMax = plot.getRangeAxis().getUpperBound();

      if (!pointTimeSeriesCollection.hasMultiplePoints()) {
        // If this chart displays a single point, check if there should be a range description.
        TimeSeries timeSeries = pointTimeSeriesCollection.getNumericTimeSeries(0).getTimeSeries();
        String desc = timeSeries.getRangeDescription();
        if (!StringUtils.isBlank(desc)) {
          // Replace any HTML entities with Java equivalents
          desc = StripEntities.stripHTMLEntities(desc, ' ');
          plot.getRangeAxis().setLabel(desc);
        }
      }
    } else plot.getRangeAxis().setVisible(false);

    if (pointTimeSeriesCollection.getRangeMarkers() != null) {
      boolean rangeAdjusted = false;
      for (Marker marker : pointTimeSeriesCollection.getRangeMarkers()) {
        plot.addRangeMarker(marker);
        if (marker instanceof ValueMarker) {
          ValueMarker vm = (ValueMarker) marker;
          if (numericMin > vm.getValue()) {
            numericMin = vm.getValue();
            rangeAdjusted = true;
          }
          if (numericMax < vm.getValue()) {
            numericMax = vm.getValue();
            rangeAdjusted = true;
          }
        }
      }

      if (rangeAdjusted) {
        double adj = (numericMax - numericMin);
        plot.getRangeAxis().setLowerBound(numericMin - adj * plot.getRangeAxis().getLowerMargin());
        plot.getRangeAxis().setUpperBound(numericMax + adj * plot.getRangeAxis().getUpperMargin());
      }
    }

    int discreteValueCount = pointTimeSeriesCollection.getDiscreteValueCount();
    double interval = (numericMax - numericMin) / (discreteValueCount + 1);
    int intervalIndex = 1;

    if (pointTimeSeriesCollection.hasDiscreteData()) {
      for (int i = 0; i < pointTimeSeriesCollection.getDiscreteSeriesCount(); i++) {
        DiscreteTimeSeries dts = pointTimeSeriesCollection.getDiscreteTimeSeries(i);
        XYStepRenderer renderer = new XYStepRenderer();

        TimeSeries ts = new TimeSeries(dts.getName(), null, null);
        for (IValueTime vt : dts.getValueTimes())
          addMillisecond(
              ts,
              vt.getTime(),
              numericMin + (interval * (dts.getValueIndex(vt.getValue()) + intervalIndex)));

        if (dts.getPaint() != null) renderer.setSeriesPaint(0, dts.getPaint(), false);
        if (dts.getStroke() != null) renderer.setSeriesStroke(0, dts.getStroke(), false);

        plot.setDataset(
            numericSeriesCount + i,
            new TimeSeriesCollection(ts, pointTimeSeriesCollection.getTimeZone()));
        plot.setRenderer(numericSeriesCount + i, renderer);

        intervalIndex += dts.getDiscreteValueCount();
      }
    }

    if (from > 0) plot.getDomainAxis().setLowerBound(from);
    if (to > 0) plot.getDomainAxis().setUpperBound(to);

    if (pointTimeSeriesCollection.hasDiscreteData()) {
      // Add the value annotations.
      double annoX = plot.getDomainAxis().getLowerBound();
      intervalIndex = 1;
      for (int i = 0; i < pointTimeSeriesCollection.getDiscreteSeriesCount(); i++) {
        DiscreteTimeSeries dts = pointTimeSeriesCollection.getDiscreteTimeSeries(i);

        for (int j = 0; j < dts.getDiscreteValueCount(); j++) {
          XYTextAnnotation anno =
              new XYTextAnnotation(
                  " " + dts.getValueText(j), annoX, numericMin + (interval * (j + intervalIndex)));
          if (!pointTimeSeriesCollection.hasNumericData()
              && intervalIndex + j == discreteValueCount)
            // This prevents the top label from getting cut off
            anno.setTextAnchor(TextAnchor.TOP_LEFT);
          else anno.setTextAnchor(TextAnchor.BOTTOM_LEFT);
          anno.setPaint(
              ((AbstractRenderer) plot.getRenderer(numericSeriesCount + i)).lookupSeriesPaint(0));
          plot.addAnnotation(anno);
        }

        intervalIndex += dts.getDiscreteValueCount();
      }
    }

    // Return the image.
    ChartUtilities.writeChartAsPNG(out, chart, width, height);
  }
Esempio n. 3
0
  private void savePointValue(
      PointValueTime newValue, SetPointSource source, boolean async, boolean saveToDatabase) {
    // Null values are not very nice, and since they don't have a specific meaning they are hereby
    // ignored.
    if (newValue == null) return;

    // Check the data type of the value against that of the locator, just for fun.
    int valueDataType = DataTypes.getDataType(newValue.getValue());
    if (valueDataType != DataTypes.UNKNOWN && valueDataType != vo.getPointLocator().getDataTypeId())
      // This should never happen, but if it does it can have serious downstream consequences. Also,
      // we need
      // to know how it happened, and the stack trace here provides the best information.
      throw new ShouldNeverHappenException(
          "Data type mismatch between new value and point locator: newValue="
              + DataTypes.getDataType(newValue.getValue())
              + ", locator="
              + vo.getPointLocator().getDataTypeId());

    // Check if this value qualifies for discardation.
    if (vo.isDiscardExtremeValues()
        && DataTypes.getDataType(newValue.getValue()) == DataTypes.NUMERIC) {
      double newd = newValue.getDoubleValue();
      if (newd < vo.getDiscardLowLimit() || newd > vo.getDiscardHighLimit())
        // Discard the value
        return;
    }

    if (newValue.getTime() > System.currentTimeMillis() + SystemSettingsDao.getFutureDateLimit()) {
      // Too far future dated. Toss it. But log a message first.
      LOG.warn(
          "Future dated value detected: pointId="
              + vo.getId()
              + ", value="
              + newValue.getStringValue()
              + ", type="
              + vo.getPointLocator().getDataTypeId()
              + ", ts="
              + newValue.getTime(),
          new Exception());
      return;
    }

    boolean backdated = pointValue != null && newValue.getTime() < pointValue.getTime();

    // Determine whether the new value qualifies for logging.
    boolean logValue;
    // ... or even saving in the cache.
    boolean saveValue = true;
    switch (vo.getLoggingType()) {
      case DataPointVO.LoggingTypes.ON_CHANGE:
        if (pointValue == null) logValue = true;
        else if (backdated)
          // Backdated. Ignore it
          logValue = false;
        else {
          if (newValue.getValue() instanceof NumericValue) {
            // Get the new double
            double newd = newValue.getDoubleValue();

            // See if the new value is outside of the tolerance.
            double diff = toleranceOrigin - newd;
            if (diff < 0) diff = -diff;

            if (diff > vo.getTolerance()) {
              toleranceOrigin = newd;
              logValue = true;
            } else logValue = false;
          } else logValue = !ObjectUtils.equals(newValue.getValue(), pointValue.getValue());
        }

        saveValue = logValue;
        break;
      case DataPointVO.LoggingTypes.ALL:
        logValue = true;
        break;
      case DataPointVO.LoggingTypes.ON_TS_CHANGE:
        if (pointValue == null) logValue = true;
        else if (backdated)
          // Backdated. Ignore it
          logValue = false;
        else logValue = newValue.getTime() != pointValue.getTime();

        saveValue = logValue;
        break;
      case DataPointVO.LoggingTypes.INTERVAL:
        if (!backdated) intervalSave(newValue);
      default:
        logValue = false;
    }

    if (!saveToDatabase) logValue = false;

    if (saveValue) valueCache.savePointValue(newValue, source, logValue, async);

    // add annotation to newValue before firing events so event detectors can
    // fetch the annotation
    if (source != null) {
      newValue =
          new AnnotatedPointValueTime(
              newValue.getValue(), newValue.getTime(), source.getSetPointSourceMessage());
    }

    // Ignore historical values.
    if (pointValue == null || newValue.getTime() >= pointValue.getTime()) {
      PointValueTime oldValue = pointValue;
      pointValue = newValue;
      fireEvents(oldValue, newValue, source != null, false);
    } else fireEvents(null, newValue, false, true);
  }
Esempio n. 4
0
  //
  // 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();
    }
  }