Ejemplo n.º 1
0
  public void activate() {
    injector = RulesStandaloneSetup.getInjector();
    triggerManager = injector.getInstance(RuleTriggerManager.class);

    if (!isEnabled()) {
      logger.info("Rule engine is disabled.");
      return;
    }

    logger.debug("Started rule engine");

    // read all rule files
    Iterable<String> ruleModelNames = modelRepository.getAllModelNamesOfType("rules");
    ArrayList<String> clonedList = Lists.newArrayList(ruleModelNames);
    for (String ruleModelName : clonedList) {
      EObject model = modelRepository.getModel(ruleModelName);
      if (model instanceof RuleModel) {
        RuleModel ruleModel = (RuleModel) model;
        triggerManager.addRuleModel(ruleModel);
      }
    }

    // register us on all items which are already available in the registry
    for (Item item : itemRegistry.getItems()) {
      internalItemAdded(item);
    }
    scheduleStartupRules();
  }
Ejemplo n.º 2
0
 private void dispatchBindingsPerType(BindingConfigReader reader, String[] bindingTypes) {
   if (modelRepository != null) {
     for (String modelName : modelRepository.getAllModelNamesOfType("items")) {
       ItemModel model = (ItemModel) modelRepository.getModel(modelName);
       if (model != null) {
         for (ModelItem modelItem : model.getItems()) {
           for (ModelBinding modelBinding : modelItem.getBindings()) {
             for (String bindingType : bindingTypes) {
               if (bindingType.equals(modelBinding.getType())) {
                 Item item = createItemFromModelItem(modelItem);
                 if (item != null) {
                   internalDispatchBindings(reader, modelName, item, modelItem.getBindings());
                 }
               }
             }
           }
         }
       } else {
         logger.debug("Model repository returned NULL for model named '{}'", modelName);
       }
     }
   } else {
     logger.warn("ModelRepository is NULL > dispatch bindings aborted!");
   }
 }
Ejemplo n.º 3
0
 public void unsetModelRepository(ModelRepository modelRepository) {
   modelRepository.removeModelRepositoryChangeListener(this);
   for (String modelName : modelRepository.getAllModelNamesOfType("persist")) {
     stopEventHandling(modelName);
   }
   this.modelRepository = null;
 }
Ejemplo n.º 4
0
 public void setModelRepository(ModelRepository modelRepository) {
   this.modelRepository = modelRepository;
   modelRepository.addModelRepositoryChangeListener(this);
   for (String modelName : modelRepository.getAllModelNamesOfType("persist")) {
     String serviceName = modelName.substring(0, modelName.length() - ".persist".length());
     stopEventHandling(serviceName);
     startEventHandling(serviceName);
   }
 }
Ejemplo n.º 5
0
  private void processBindingConfigsFromModel(String modelName) {
    logger.debug("Processing binding configs for items from model '{}'", modelName);

    if (modelRepository != null) {
      ItemModel model = (ItemModel) modelRepository.getModel(modelName);
      if (model == null) {
        return;
      }

      // start binding configuration processing
      for (BindingConfigReader reader : bindingConfigReaders.values()) {
        reader.startConfigurationUpdate(modelName);
      }

      // create items and read new binding configuration
      for (ModelItem modelItem : model.getItems()) {
        Item item = createItemFromModelItem(modelItem);
        if (item != null) {
          internalDispatchBindings(modelName, item, modelItem.getBindings());
        }
      }

      // end binding configuration processing
      for (BindingConfigReader reader : bindingConfigReaders.values()) {
        reader.stopConfigurationUpdate(modelName);
      }
    }
  }
Ejemplo n.º 6
0
 /** {@inheritDoc} */
 @Override
 public Collection<Item> getAll() {
   List<Item> items = new ArrayList<Item>();
   stateDescriptions.clear();
   for (String name : modelRepository.getAllModelNamesOfType("items")) {
     items.addAll(getItemsFromModel(name));
   }
   return items;
 }
Ejemplo n.º 7
0
 /**
  * Registers a persistence model file with the persistence manager, so that it becomes active.
  *
  * @param modelName the name of the persistence model without file extension
  */
 private void startEventHandling(String modelName) {
   if (modelRepository != null) {
     PersistenceModel model = (PersistenceModel) modelRepository.getModel(modelName + ".persist");
     if (model != null) {
       persistenceConfigurations.put(modelName, model.getConfigs());
       defaultStrategies.put(modelName, model.getDefaults());
       if (itemRegistry != null) {
         for (PersistenceConfiguration config : model.getConfigs()) {
           if (hasStrategy(modelName, config, GlobalStrategies.RESTORE)) {
             for (Item item : getAllItems(config)) {
               initialize(item);
             }
           }
         }
       }
       createTimers(modelName);
     }
   }
 }
Ejemplo n.º 8
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.º 9
0
  @Override
  public void modelChanged(String modelName, org.eclipse.smarthome.model.core.EventType type) {
    if (triggerManager != null) {
      if (isEnabled() && modelName.endsWith("rules")) {
        RuleModel model = (RuleModel) modelRepository.getModel(modelName);

        // remove the rules from the trigger sets
        if (type == org.eclipse.smarthome.model.core.EventType.REMOVED
            || type == org.eclipse.smarthome.model.core.EventType.MODIFIED) {
          triggerManager.removeRuleModel(model);
        }

        // add new and modified rules to the trigger sets
        if (model != null
            && (type == org.eclipse.smarthome.model.core.EventType.ADDED
                || type == org.eclipse.smarthome.model.core.EventType.MODIFIED)) {
          triggerManager.addRuleModel(model);
          // now execute all rules that are meant to trigger at startup
          scheduleStartupRules();
        }
      }
    }
  }
Ejemplo n.º 10
0
  /**
   * Creates and schedules a new quartz-job and trigger with model and rule name as jobData.
   *
   * @param rule the rule to schedule
   * @param trigger the defined trigger
   * @throws SchedulerException if there is an internal Scheduler error.
   */
  private void createTimers(String modelName) {
    PersistenceModel persistModel =
        (PersistenceModel) modelRepository.getModel(modelName + ".persist");
    if (persistModel != null) {
      for (Strategy strategy : persistModel.getStrategies()) {
        if (strategy instanceof CronStrategy) {
          CronStrategy cronStrategy = (CronStrategy) strategy;
          String cronExpression = cronStrategy.getCronExpression();
          JobKey jobKey = new JobKey(strategy.getName(), modelName);
          try {
            JobDetail job =
                newJob(PersistItemsJob.class)
                    .usingJobData(
                        PersistItemsJob.JOB_DATA_PERSISTMODEL,
                        cronStrategy.eResource().getURI().trimFileExtension().path())
                    .usingJobData(PersistItemsJob.JOB_DATA_STRATEGYNAME, cronStrategy.getName())
                    .withIdentity(jobKey)
                    .build();

            Trigger quartzTrigger =
                newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)).build();

            scheduler.scheduleJob(job, quartzTrigger);

            logger.debug(
                "Scheduled strategy {} with cron expression {}",
                new Object[] {jobKey.toString(), cronExpression});
          } catch (SchedulerException e) {
            logger.error(
                "Failed to schedule job for strategy {} with cron expression {}",
                new String[] {jobKey.toString(), cronExpression},
                e);
          }
        }
      }
    }
  }
Ejemplo n.º 11
0
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String sitemapName = request.getParameter("sitemap");
    String widgetId = request.getParameter("widgetId");

    if (sitemapName == null) {
      throw new ServletException("Parameter 'sitemap' must be provided!");
    }
    if (widgetId == null) {
      throw new ServletException("Parameter 'widget' must be provided!");
    }

    String uriString = null;

    Sitemap sitemap = (Sitemap) modelRepository.getModel(sitemapName);
    if (sitemap != null) {
      Widget widget = itemUIRegistry.getWidget(sitemap, widgetId);
      if (widget instanceof Image) {
        Image image = (Image) widget;
        uriString = image.getUrl();
      } else if (widget instanceof Video) {
        Video video = (Video) widget;
        uriString = video.getUrl();
      } else {
        if (widget == null) {
          throw new ServletException("Widget '" + widgetId + "' could not be found!");
        } else {
          throw new ServletException(
              "Widget type '" + widget.getClass().getName() + "' is not supported!");
        }
      }
    } else {
      throw new ServletException("Sitemap '" + sitemapName + "' could not be found!");
    }

    HttpClient httpClient = new HttpClient();

    try {
      // check if the uri uses credentials and configure the http client accordingly
      URI uri = URI.create(uriString);

      if (uri.getUserInfo() != null) {
        String[] userInfo = uri.getUserInfo().split(":");
        httpClient.getParams().setAuthenticationPreemptive(true);
        Credentials creds = new UsernamePasswordCredentials(userInfo[0], userInfo[1]);
        httpClient
            .getState()
            .setCredentials(
                new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM), creds);
      }
    } catch (IllegalArgumentException e) {
      throw new ServletException("URI '" + uriString + "' is not valid: " + e.getMessage());
    }

    // do the client request
    GetMethod method = new GetMethod(uriString);
    httpClient.executeMethod(method);

    // copy all headers
    for (Header header : method.getResponseHeaders()) {
      response.setHeader(header.getName(), header.getValue());
    }

    // now copy/stream the body content
    IOUtils.copy(method.getResponseBodyAsStream(), response.getOutputStream());
    method.releaseConnection();
  }
Ejemplo n.º 12
0
 public void unsetModelRepository(ModelRepository modelRepository) {
   modelRepository.removeModelRepositoryChangeListener(this);
   this.modelRepository = null;
 }
Ejemplo n.º 13
0
 public void setModelRepository(ModelRepository modelRepository) {
   this.modelRepository = modelRepository;
   modelRepository.addModelRepositoryChangeListener(this);
 }