Ejemplo n.º 1
0
 /**
  * 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);
             }
           }
         }
       }
     }
   }
 }