Ejemplo n.º 1
0
 /** {@inheritDoc} */
 @Override
 public void removed(Item item) {
   if (item instanceof GenericItem) {
     GenericItem genericItem = (GenericItem) item;
     genericItem.removeStateChangeListener(this);
   }
 }
Ejemplo n.º 2
0
 @Override
 public void added(Item item) {
   initialize(item);
   if (item instanceof GenericItem) {
     GenericItem genericItem = (GenericItem) item;
     genericItem.addStateChangeListener(this);
   }
 }
Ejemplo n.º 3
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);
             }
           }
         }
       }
     }
   }
 }
Ejemplo n.º 4
0
 /** {@inheritDoc} */
 @Override
 public void receiveUpdate(String itemName, State newStatus) {
   if (itemRegistry != null) {
     try {
       GenericItem item = (GenericItem) itemRegistry.getItem(itemName);
       boolean isAccepted = false;
       if (item.getAcceptedDataTypes().contains(newStatus.getClass())) {
         isAccepted = true;
       } else {
         // Look for class hierarchy
         for (Class<? extends State> state : item.getAcceptedDataTypes()) {
           try {
             if (!state.isEnum()
                 && state.newInstance().getClass().isAssignableFrom(newStatus.getClass())) {
               isAccepted = true;
               break;
             }
           } catch (InstantiationException e) {
             logger.warn("InstantiationException on {}", e.getMessage()); // Should never happen
           } catch (IllegalAccessException e) {
             logger.warn("IllegalAccessException on {}", e.getMessage()); // Should never happen
           }
         }
       }
       if (isAccepted) {
         item.setState(newStatus);
       } else {
         logger.debug(
             "Received update of a not accepted type ("
                 + newStatus.getClass().getSimpleName()
                 + ") for item "
                 + itemName);
       }
     } catch (ItemNotFoundException e) {
       logger.debug("Received update for non-existing item: {}", e.getMessage());
     }
   }
 }
Ejemplo n.º 5
0
 /**
  * This method only returns when a change has occurred to any item on the page to display or if
  * the timeout is reached
  *
  * @param widgets the widgets of the page to observe
  */
 private boolean waitForChanges(EList<Widget> widgets) {
   long startTime = (new Date()).getTime();
   boolean timeout = false;
   BlockingStateChangeListener listener = new BlockingStateChangeListener();
   // let's get all items for these widgets
   Set<GenericItem> items = getAllItems(widgets);
   for (GenericItem item : items) {
     item.addStateChangeListener(listener);
   }
   while (!listener.hasChangeOccurred() && !timeout) {
     timeout = (new Date()).getTime() - startTime > TIMEOUT_IN_MS;
     try {
       Thread.sleep(300);
     } catch (InterruptedException e) {
       timeout = true;
       break;
     }
   }
   for (GenericItem item : items) {
     item.removeStateChangeListener(listener);
   }
   return !timeout;
 }
Ejemplo n.º 6
0
 private Item createItemFromModelItem(ModelItem modelItem) {
   GenericItem item = null;
   if (modelItem instanceof ModelGroupItem) {
     ModelGroupItem modelGroupItem = (ModelGroupItem) modelItem;
     String baseItemType = modelGroupItem.getType();
     GenericItem baseItem = createItemOfType(baseItemType, modelGroupItem.getName());
     if (baseItem != null) {
       ModelGroupFunction function = modelGroupItem.getFunction();
       if (function == null) {
         item = new GroupItem(modelGroupItem.getName(), baseItem);
       } else {
         item = applyGroupFunction(baseItem, modelGroupItem, function);
       }
     } else {
       item = new GroupItem(modelGroupItem.getName());
     }
   } else {
     ModelNormalItem normalItem = (ModelNormalItem) modelItem;
     String itemName = normalItem.getName();
     item = createItemOfType(normalItem.getType(), itemName);
   }
   if (item != null) {
     String label = modelItem.getLabel();
     String format = StringUtils.substringBetween(label, "[", "]");
     if (format != null) {
       label = StringUtils.substringBefore(label, "[").trim();
       stateDescriptions.put(
           modelItem.getName(), new StateDescription(null, null, null, format, false, null));
     }
     item.setLabel(label);
     item.setCategory(modelItem.getIcon());
     assignTags(modelItem, item);
     return item;
   } else {
     return null;
   }
 }
Ejemplo n.º 7
0
  private Collection<Item> getItemsFromModel(String modelName) {
    logger.debug("Read items from model '{}'", modelName);

    List<Item> items = new ArrayList<Item>();
    if (modelRepository != null) {
      ItemModel model = (ItemModel) modelRepository.getModel(modelName);
      if (model != null) {
        for (ModelItem modelItem : model.getItems()) {
          Item item = createItemFromModelItem(modelItem);
          if (item != null) {
            for (String groupName : modelItem.getGroups()) {
              ((GenericItem) item).addGroupName(groupName);
            }
            items.add(item);
          }
        }
      }
    }
    return items;
  }
Ejemplo n.º 8
0
 private void internalItemAdded(Item item) {
   if (item instanceof GenericItem) {
     GenericItem genericItem = (GenericItem) item;
     genericItem.addStateChangeListener(this);
   }
 }
Ejemplo n.º 9
0
  private GroupItem applyGroupFunction(
      GenericItem baseItem, ModelGroupItem modelGroupItem, ModelGroupFunction function) {
    List<State> args = new ArrayList<State>();
    for (String arg : modelGroupItem.getArgs()) {
      State state = TypeParser.parseState(baseItem.getAcceptedDataTypes(), arg);
      if (state == null) {
        logger.warn(
            "State '{}' is not valid for group item '{}' with base type '{}'",
            new Object[] {arg, modelGroupItem.getName(), modelGroupItem.getType()});
        args.clear();
        break;
      } else {
        args.add(state);
      }
    }

    GroupFunction groupFunction = null;
    switch (function) {
      case AND:
        if (args.size() == 2) {
          groupFunction = new ArithmeticGroupFunction.And(args.get(0), args.get(1));
          break;
        } else {
          logger.error("Group function 'AND' requires two arguments. Using Equality instead.");
        }
      case OR:
        if (args.size() == 2) {
          groupFunction = new ArithmeticGroupFunction.Or(args.get(0), args.get(1));
          break;
        } else {
          logger.error("Group function 'OR' requires two arguments. Using Equality instead.");
        }
      case NAND:
        if (args.size() == 2) {
          groupFunction = new ArithmeticGroupFunction.NAnd(args.get(0), args.get(1));
          break;
        } else {
          logger.error("Group function 'NOT AND' requires two arguments. Using Equality instead.");
        }
        break;
      case NOR:
        if (args.size() == 2) {
          groupFunction = new ArithmeticGroupFunction.NOr(args.get(0), args.get(1));
          break;
        } else {
          logger.error("Group function 'NOT OR' requires two arguments. Using Equality instead.");
        }
      case COUNT:
        if (args.size() == 1) {
          groupFunction = new ArithmeticGroupFunction.Count(args.get(0));
          break;
        } else {
          logger.error("Group function 'COUNT' requires one argument. Using Equality instead.");
        }
      case AVG:
        groupFunction = new ArithmeticGroupFunction.Avg();
        break;
      case SUM:
        groupFunction = new ArithmeticGroupFunction.Sum();
        break;
      case MIN:
        groupFunction = new ArithmeticGroupFunction.Min();
        break;
      case MAX:
        groupFunction = new ArithmeticGroupFunction.Max();
        break;
      default:
        logger.error(
            "Unknown group function '" + function.getName() + "'. Using Equality instead.");
    }

    if (groupFunction == null) {
      groupFunction = new GroupFunction.Equality();
    }

    return new GroupItem(modelGroupItem.getName(), baseItem, groupFunction);
  }
Ejemplo n.º 10
0
 private void assignTags(ModelItem modelItem, GenericItem item) {
   List<String> tags = modelItem.getTags();
   for (String tag : tags) {
     item.addTag(tag);
   }
 }