Beispiel #1
0
  //
  // / Interval logging
  //
  private void initializeIntervalLogging() {
    synchronized (intervalLoggingLock) {
      if (vo.getLoggingType() != DataPointVO.LoggingTypes.INTERVAL) return;

      // Are we using a custom timer?
      if (this.timer == null)
        intervalLoggingTask =
            new TimeoutTask(
                new FixedRateTrigger(
                    0,
                    Common.getMillis(
                        vo.getIntervalLoggingPeriodType(), vo.getIntervalLoggingPeriod())),
                this);
      else
        intervalLoggingTask =
            new TimeoutTask(
                new FixedRateTrigger(
                    0,
                    Common.getMillis(
                        vo.getIntervalLoggingPeriodType(), vo.getIntervalLoggingPeriod())),
                this,
                this.timer);

      intervalValue = pointValue;
      if (vo.getIntervalLoggingType() == DataPointVO.IntervalLoggingTypes.AVERAGE) {
        intervalStartTime = System.currentTimeMillis();
        averagingValues = new ArrayList<IValueTime>();
      }
    }
  }
  @DwrPermission(admin = true)
  public synchronized void scheduleRestart() {
    if (RESTART_TASK == null) {
      SystemEventType.raiseEvent(
          new SystemEventType(SystemEventType.TYPE_SYSTEM_SHUTDOWN),
          System.currentTimeMillis(),
          false,
          new TranslatableMessage("modules.restartScheduledBy", Common.getUser().getUsername()));

      long timeout = Common.getMillis(Common.TimePeriods.SECONDS, 10);
      RESTART_TASK =
          new TimeoutTask(
              timeout,
              new TimeoutClient() {
                @Override
                public void scheduleTimeout(long fireTime) {
                  File restartFlag = new File(Common.M2M2_HOME, "RESTART");
                  if (!restartFlag.exists()) {
                    try {
                      FileWriter fw = new FileWriter(restartFlag);
                      fw.write("restart");
                      fw.close();
                    } catch (IOException e) {
                      LOG.error("Unabled to create restart flag file", e);
                    }
                  }
                  Providers.get(ILifecycle.class).terminate();
                }
              });
    }
  }
 private void checkDomain(HttpServletRequest request, BindException errors) {
   if (Common.license() != null && !"localhost".equals(request.getServerName())) {
     if (!ControllerUtils.getDomain(request).equals(Common.license().getDomain()))
       ValidationUtils.reject(
           errors, "login.validation.wrongDomain", Common.license().getDomain());
   }
 }
  @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);
    }
  }
  @DwrPermission(user = true)
  public ProcessResult getHistoryTableData(int limit) {
    DataPointVO pointVO = Common.getUser().getEditPoint();
    PointValueFacade facade = new PointValueFacade(pointVO.getId());

    List<PointValueTime> rawData = facade.getLatestPointValues(limit);
    List<RenderedPointValueTime> renderedData =
        new ArrayList<RenderedPointValueTime>(rawData.size());

    for (PointValueTime pvt : rawData) {
      RenderedPointValueTime rpvt = new RenderedPointValueTime();
      rpvt.setValue(Functions.getHtmlText(pointVO, pvt));
      rpvt.setTime(Functions.getTime(pvt));
      if (pvt.isAnnotated()) {
        AnnotatedPointValueTime apvt = (AnnotatedPointValueTime) pvt;
        rpvt.setAnnotation(apvt.getAnnotation(getTranslations()));
      }
      renderedData.add(rpvt);
    }

    ProcessResult response = new ProcessResult();
    response.addData("history", renderedData);
    addAsof(response);
    return response;
  }
  public static PointDetailsState getPointData() {
    // Get the point from the user's session. It should have been set by the controller.
    HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
    User user = Common.getUser(request);
    DataPointVO pointVO = user.getEditPoint();

    // Create the watch list state.
    Map<String, Object> model = new HashMap<String, Object>();

    // Get the data point status from the data image.
    DataPointRT pointRT = Common.runtimeManager.getDataPoint(pointVO.getId());

    PointDetailsState state = new PointDetailsState();
    state.setId(Integer.toString(pointVO.getId()));

    PointValueTime pointValue =
        prepareBasePointState(Integer.toString(pointVO.getId()), state, pointVO, pointRT, model);
    setPrettyText(request, state, pointVO, model, pointValue);
    setChange(pointVO, state, pointRT, request, model, user);

    setEvents(pointVO, user, model);
    setMessages(state, request, "dataPointMessages.jsp", model);

    return state;
  }
  @DwrPermission(user = true)
  public ProcessResult getFlipbookData(int limit) {
    HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
    DataPointVO vo = Common.getUser(request).getEditPoint();
    PointValueFacade facade = new PointValueFacade(vo.getId());

    List<PointValueTime> values = facade.getLatestPointValues(limit);
    Collections.reverse(values);
    List<ImageValueBean> result = new ArrayList<ImageValueBean>();
    for (PointValueTime pvt : values) {
      ImageValue imageValue = (ImageValue) pvt.getValue();
      String uri =
          ImageValueServlet.servletPath
              + ImageValueServlet.historyPrefix
              + pvt.getTime()
              + "_"
              + vo.getId()
              + "."
              + imageValue.getTypeExtension();
      result.add(new ImageValueBean(Functions.getTime(pvt), uri));
    }

    ProcessResult response = new ProcessResult();
    response.addData("images", result);
    addAsof(response);
    return response;
  }
 @DwrPermission(user = true)
 public void getChartData(
     int fromYear,
     int fromMonth,
     int fromDay,
     int fromHour,
     int fromMinute,
     int fromSecond,
     boolean fromNone,
     int toYear,
     int toMonth,
     int toDay,
     int toHour,
     int toMinute,
     int toSecond,
     boolean toNone) {
   User user = Common.getUser();
   DateTimeZone dtz = user.getDateTimeZoneInstance();
   DateTime from =
       createDateTime(
           fromYear, fromMonth, fromDay, fromHour, fromMinute, fromSecond, fromNone, dtz);
   DateTime to = createDateTime(toYear, toMonth, toDay, toHour, toMinute, toSecond, toNone, dtz);
   DataExportDefinition def =
       new DataExportDefinition(new int[] {getDataPointVO().getId()}, from, to);
   user.setDataExportDefinition(def);
 }
  @DwrPermission(user = true)
  public ProcessResult getStatsChartData(int periodType, int period, boolean includeSum) {
    HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
    DataPointVO pointVO = Common.getUser(request).getEditPoint();

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("point", pointVO);
    StatisticsChartRenderer r = new StatisticsChartRenderer(periodType, period, includeSum);
    r.addDataToModel(model, pointVO);

    ProcessResult response = new ProcessResult();
    response.addData("stats", generateContent(request, "statsChart.jsp", model));
    addAsof(response);
    return response;
  }
  @DwrPermission(user = true)
  public ProcessResult getImageChartData(
      int fromYear,
      int fromMonth,
      int fromDay,
      int fromHour,
      int fromMinute,
      int fromSecond,
      boolean fromNone,
      int toYear,
      int toMonth,
      int toDay,
      int toHour,
      int toMinute,
      int toSecond,
      boolean toNone,
      int width,
      int height) {
    DateTimeZone dtz = Common.getUser().getDateTimeZoneInstance();
    DateTime from =
        createDateTime(
            fromYear, fromMonth, fromDay, fromHour, fromMinute, fromSecond, fromNone, dtz);
    DateTime to = createDateTime(toYear, toMonth, toDay, toHour, toMinute, toSecond, toNone, dtz);

    StringBuilder htmlData = new StringBuilder();
    htmlData.append("<img src=\"chart/ft_");
    htmlData.append(System.currentTimeMillis());
    htmlData.append('_');
    htmlData.append(fromNone ? -1 : from.getMillis());
    htmlData.append('_');
    htmlData.append(toNone ? -1 : to.getMillis());
    htmlData.append('_');
    htmlData.append(getDataPointVO().getId());
    htmlData.append(".png?w=");
    htmlData.append(width);
    htmlData.append("&h=");
    htmlData.append(height);
    htmlData.append("\" alt=\"" + translate("common.imageChart") + "\"/>");

    ProcessResult response = new ProcessResult();
    response.addData("chart", htmlData.toString());
    addAsof(response);
    return response;
  }
    @Override
    public void run() {
      HttpClient httpClient = Common.getHttpClient();

      for (StringStringPair mod : modules) {
        String name = mod.getKey();
        String version = mod.getValue();

        String filename = ModuleUtils.moduleFilename(name, version);
        String url =
            Common.envProps.getString("store.url")
                + "/"
                + ModuleUtils.downloadFilename(name, version);
        HttpGet get = new HttpGet(url);

        FileOutputStream out = null;
        try {
          String saveDir = Common.M2M2_HOME;
          if (!"core".equals(name))
            saveDir += "/" + Constants.DIR_WEB + "/" + Constants.DIR_MODULES;
          out = new FileOutputStream(new File(saveDir, filename));

          HttpUtils4.execute(httpClient, get, out);

          synchronized (results) {
            results.add(new StringStringPair(name, null));
          }
        } catch (IOException e) {
          synchronized (results) {
            results.add(new StringStringPair(name, e.getMessage()));
            LOG.warn("Upgrade download error", e);
          }
        } finally {
          try {
            if (out != null) out.close();
          } catch (IOException e) {
            // no op
          }
        }
      }

      finished = true;
    }
  @DwrPermission(user = true)
  public ProcessResult saveGalilDataSource(
      BasicDataSourceVO basic,
      String host,
      int port,
      int timeout,
      int retries,
      int updatePeriods,
      int updatePeriodType) {
    GalilDataSourceVO ds = (GalilDataSourceVO) Common.getUser().getEditDataSource();

    setBasicProps(ds, basic);
    ds.setHost(host);
    ds.setPort(port);
    ds.setTimeout(timeout);
    ds.setRetries(retries);
    ds.setUpdatePeriods(updatePeriods);
    ds.setUpdatePeriodType(updatePeriodType);

    return tryDataSourceSave(ds);
  }
  private ModelAndView performLogin(HttpServletRequest request, User user) {
    if (user.isDisabled())
      throw new RuntimeException("User " + user.getUsername() + " is disabled. Aborting login");

    // Update the last login time.
    new UserDao().recordLogin(user.getId());

    // Add the user object to the session. This indicates to the rest of the application whether the
    // user is logged
    // in or not. Will replace any existing user object.
    Common.setUser(request, user);
    if (logger.isDebugEnabled()) logger.debug("User object added to session");

    if (user.isFirstLogin()) return new ModelAndView(new RedirectView(newUserUrl));
    if (!StringUtils.isBlank(user.getHomeUrl()))
      return new ModelAndView(new RedirectView(user.getHomeUrl()));

    for (AuthenticationDefinition def :
        ModuleRegistry.getDefinitions(AuthenticationDefinition.class)) def.postLogin(user);

    return new ModelAndView(new RedirectView(successUrl));
  }
  @Override
  protected ModelAndView onSubmit(
      HttpServletRequest request,
      HttpServletResponse response,
      Object command,
      BindException errors)
      throws Exception {
    LoginForm login = (LoginForm) command;

    // Check if the user exists
    User user = new UserDao().getUser(login.getUsername());
    if (user == null)
      ValidationUtils.rejectValue(errors, "username", "login.validation.noSuchUser");
    else if (user.isDisabled()) ValidationUtils.reject(errors, "login.validation.accountDisabled");
    else {
      boolean authenticated = false;

      for (AuthenticationDefinition def :
          ModuleRegistry.getDefinitions(AuthenticationDefinition.class)) {
        authenticated = def.authenticate(request, response, user, login.getPassword(), errors);
        if (authenticated) break;
      }

      if (!authenticated) {
        String passwordHash = Common.encrypt(login.getPassword());

        // Validating the password against the database.
        if (!passwordHash.equals(user.getPassword()))
          ValidationUtils.reject(errors, "login.validation.invalidLogin");
      }
    }

    if (errors.hasErrors()) return showForm(request, response, errors);

    return performLogin(request, user);
  }
 private DataPointVO getDataPointVO() {
   return Common.getUser().getEditPoint();
 }