/**
   * returns a rrd series data, an array of [[timestamp,data1,data2,...]]
   *
   * @param persistenceService
   * @param item
   * @param consilidationFunction
   * @param timeBegin
   * @param timeEnd
   * @param resolution
   * @return
   */
  public Object getRrdSeries(
      QueryablePersistenceService persistenceService,
      Item item,
      ConsolFun consilidationFunction,
      Date timeBegin,
      Date timeEnd,
      long resolution) {
    Map<Long, ArrayList<String>> data = new TreeMap<Long, ArrayList<String>>();
    try {
      List<String> itemNames = new ArrayList<String>();

      if (item instanceof GroupItem) {
        GroupItem groupItem = (GroupItem) item;
        for (Item member : groupItem.getMembers()) {
          itemNames.add(member.getName());
        }
      } else {
        itemNames.add(item.getName());
      }
      for (String itemName : itemNames) {
        addRrdData(data, itemName, consilidationFunction, timeBegin, timeEnd, resolution);
      }

    } catch (FileNotFoundException e) {
      // rrd file does not exist, fallback to generic persistance service
      logger.debug(
          "no rrd file found '{}'", (RRD_FOLDER + File.separator + item.getName() + ".rrd"));
      return getPersistenceSeries(persistenceService, item, timeBegin, timeEnd, resolution);
    } catch (Exception e) {
      logger.error(e.getLocalizedMessage() + ": fallback to generic persistance service");
      return getPersistenceSeries(persistenceService, item, timeBegin, timeEnd, resolution);
    }
    return convertToRrd(data);
  }
Example #2
0
  private void internalDispatchBindings(
      BindingConfigReader reader, String modelName, Item item, EList<ModelBinding> bindings) {
    for (ModelBinding binding : bindings) {
      String bindingType = binding.getType();
      String config = binding.getConfiguration();

      BindingConfigReader localReader = reader;
      if (reader == null) {
        logger.trace(
            "Given binding config reader is null > query cache to find appropriate reader!");
        localReader = bindingConfigReaders.get(bindingType);
      } else {
        if (!localReader.getBindingType().equals(binding.getType())) {
          logger.trace(
              "The Readers' binding type '{}' and the Bindings' type '{}' doesn't match > continue processing next binding.",
              localReader.getBindingType(),
              binding.getType());
          continue;
        } else {
          logger.debug(
              "Start processing binding configuration of Item '{}' with '{}' reader.",
              item,
              localReader.getClass().getSimpleName());
        }
      }

      if (localReader != null) {
        try {
          localReader.validateItemType(item.getType(), config);
          localReader.processBindingConfiguration(
              modelName, item.getType(), item.getName(), config);
        } catch (BindingConfigParseException e) {
          logger.error(
              "Binding configuration of type '"
                  + bindingType
                  + "' of item '"
                  + item.getName()
                  + "' could not be parsed correctly.",
              e);
        } catch (Exception e) {
          // Catch badly behaving binding exceptions and continue processing
          logger.error(
              "Binding configuration of type '"
                  + bindingType
                  + "' of item '"
                  + item.getName()
                  + "' could not be parsed correctly.",
              e);
        }
      } else {
        logger.trace(
            "Couldn't find config reader for binding type '{}' > "
                + "parsing binding configuration of Item '{}' aborted!",
            bindingType,
            item);
      }
    }
  }
 /**
  * Checks if a given persistence configuration entry is relevant for an item
  *
  * @param config the persistence configuration entry
  * @param item to check if the configuration applies to
  * @return true, if the configuration applies to the item
  */
 protected boolean appliesToItem(PersistenceConfiguration config, Item item) {
   for (EObject itemCfg : config.getItems()) {
     if (itemCfg instanceof AllConfig) {
       return true;
     }
     if (itemCfg instanceof ItemConfig) {
       ItemConfig singleItemConfig = (ItemConfig) itemCfg;
       if (item.getName().equals(singleItemConfig.getItem())) {
         return true;
       }
     }
     if (itemCfg instanceof GroupConfig) {
       GroupConfig groupItemCfg = (GroupConfig) itemCfg;
       String groupName = groupItemCfg.getGroup();
       try {
         Item gItem = itemRegistry.getItem(groupName);
         if (gItem instanceof GroupItem) {
           GroupItem groupItem = (GroupItem) gItem;
           if (groupItem.getAllMembers().contains(item)) {
             return true;
           }
         }
       } catch (Exception e) {
       }
     }
   }
   return false;
 }
 /**
  * Handles the "restoreOnStartup" strategy for the item. If the item state is still undefined when
  * entering this method, all persistence configurations are checked, if they have the
  * "restoreOnStartup" strategy configured for the item. If so, the item state will be set to its
  * last persisted value.
  *
  * @param item the item to restore the state for
  */
 protected void initialize(Item item) {
   // get the last persisted state from the persistence service if no state is yet set
   if (item.getState().equals(UnDefType.NULL) && item instanceof GenericItem) {
     for (Entry<String, List<PersistenceConfiguration>> entry :
         persistenceConfigurations.entrySet()) {
       String serviceName = entry.getKey();
       for (PersistenceConfiguration config : entry.getValue()) {
         if (hasStrategy(serviceName, config, GlobalStrategies.RESTORE)) {
           if (appliesToItem(config, item)) {
             PersistenceService service = persistenceServices.get(serviceName);
             if (service instanceof QueryablePersistenceService) {
               QueryablePersistenceService queryService = (QueryablePersistenceService) service;
               FilterCriteria filter =
                   new FilterCriteria().setItemName(item.getName()).setPageSize(1);
               Iterable<HistoricItem> result = queryService.query(filter);
               Iterator<HistoricItem> it = result.iterator();
               if (it.hasNext()) {
                 HistoricItem historicItem = it.next();
                 GenericItem genericItem = (GenericItem) item;
                 genericItem.removeStateChangeListener(this);
                 genericItem.setState(historicItem.getState());
                 genericItem.addStateChangeListener(this);
                 logger.debug(
                     "Restored item state from '{}' for item '{}' -> '{}'",
                     new Object[] {
                       DateFormat.getDateTimeInstance().format(historicItem.getTimestamp()),
                       item.getName(),
                       historicItem.getState().toString()
                     });
                 return;
               }
             } else if (service != null) {
               logger.warn(
                   "Failed to restore item states as persistence service '{}' can not be queried.",
                   serviceName);
             }
           }
         }
       }
     }
   }
 }
  public Object getPersistenceSeries(
      QueryablePersistenceService persistenceService,
      Item item,
      Date timeBegin,
      Date timeEnd,
      long resolution) {
    Map<Long, ArrayList<String>> data = new HashMap<Long, ArrayList<String>>();

    // Define the data filter
    FilterCriteria filter = new FilterCriteria();
    filter.setBeginDate(timeBegin);
    filter.setEndDate(timeEnd);
    filter.setItemName(item.getName());
    filter.setOrdering(Ordering.ASCENDING);

    // Get the data from the persistence store
    Iterable<HistoricItem> result = persistenceService.query(filter);
    Iterator<HistoricItem> it = result.iterator();

    // Iterate through the data
    int dataCounter = 0;
    while (it.hasNext()) {
      dataCounter++;
      HistoricItem historicItem = it.next();
      org.eclipse.smarthome.core.types.State state = historicItem.getState();
      if (state instanceof DecimalType) {
        ArrayList<String> vals = new ArrayList<String>();
        vals.add(formatDouble(((DecimalType) state).doubleValue(), "null", true));
        data.put(historicItem.getTimestamp().getTime(), vals);
      }
    }
    logger.debug(
        "'{}' querying item '{}' from '{}' to '{}' => '{}' results",
        persistenceService.getId(),
        filter.getItemName(),
        filter.getBeginDate(),
        filter.getEndDate(),
        dataCounter);
    return convertToRrd(data);
  }