예제 #1
0
  @Override
  public void handleEvent(Event event) {

    if (!Boolean.TRUE.equals(event.getProperty(BRIDGEMARKER))) {

      // map event from ESH to openHAB
      if (event.getTopic().startsWith(EventConstants.TOPIC_PREFIX)) {
        String topic =
            org.openhab.core.events.EventConstants.TOPIC_PREFIX
                + event.getTopic().substring(EventConstants.TOPIC_PREFIX.length());
        Map<String, Object> properties = constructProperties(event);
        eventAdmin.postEvent(new Event(topic, properties));
      }

      // map event from openHAB to ESH
      if (event.getTopic().startsWith(org.openhab.core.events.EventConstants.TOPIC_PREFIX)) {
        String topic =
            EventConstants.TOPIC_PREFIX
                + event
                    .getTopic()
                    .substring(org.openhab.core.events.EventConstants.TOPIC_PREFIX.length());
        Map<String, Object> properties = constructProperties(event);
        eventAdmin.postEvent(new Event(topic, properties));
      }
    }
  }
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.sakaiproject.nakamura.api.message.LiteMessageTransport#send(org.sakaiproject.nakamura.api.message.MessageRoutes,
   *     org.osgi.service.event.Event, org.sakaiproject.nakamura.api.lite.content.Content)
   */
  public void send(MessageRoutes routes, Event event, Content message) {
    LOGGER.debug("Started handling an email message");

    // delay list instantiation to save object creation when not needed.
    List<String> recipients = null;
    for (MessageRoute route : routes) {
      if (TYPE.equals(route.getTransport())) {
        if (recipients == null) {
          recipients = new ArrayList<String>();
        }
        recipients.add(route.getRcpt());
      }
    }

    if (recipients != null) {
      Properties props = new Properties();
      if (event != null) {
        for (String propName : event.getPropertyNames()) {
          Object propValue = event.getProperty(propName);
          props.put(propName, propValue);
        }
      }
      // make the message deliver to one listener, that means the desination must be a queue.
      props.put(EventDeliveryConstants.DELIVERY_MODE, EventDeliveryMode.P2P);
      // make the message persistent to survive restarts.
      props.put(EventDeliveryConstants.MESSAGE_MODE, EventMessageMode.PERSISTENT);
      props.put(LiteOutgoingEmailMessageListener.RECIPIENTS, recipients);
      props.put(LiteOutgoingEmailMessageListener.CONTENT_PATH_PROPERTY, message.getPath());
      Event emailEvent = new Event(LiteOutgoingEmailMessageListener.QUEUE_NAME, (Map) props);

      LOGGER.debug("Sending event [" + emailEvent + "]");
      eventAdmin.postEvent(emailEvent);
    }
  }
 private void postEvent(
     String topic,
     String path,
     String user,
     String resourceType,
     Map<String, Object> beforeEvent,
     String[] attributes) {
   final Dictionary<String, Object> properties = new Hashtable<String, Object>();
   if (attributes != null) {
     for (String attribute : attributes) {
       String[] parts = StringUtils.split(attribute, ":", 2);
       if (parts != null) {
         if (parts.length == 1) {
           properties.put(parts[0], parts[0]);
         } else if (parts.length == 2) {
           properties.put(parts[0], parts[1]);
         }
       }
     }
   }
   if (path != null) {
     properties.put(PATH_PROPERTY, path);
   }
   if (resourceType != null) {
     properties.put(RESOURCE_TYPE_PROPERTY, resourceType);
   }
   properties.put(USERID_PROPERTY, user);
   if (beforeEvent != null) {
     properties.put(BEFORE_EVENT_PROPERTY, beforeEvent);
   }
   eventAdmin.postEvent(new Event(topic, properties));
 }
예제 #4
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public void sendTravelEvent(String userid) {
    Dictionary payload = new Properties();
    payload.put("price", 80);

    Event event = new Event("manning/osgi/travelagent/hotel", payload);

    admin.postEvent(event);
  }
예제 #5
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public void sendLoginEvent(String userid) {
    Dictionary payload = new Properties();
    payload.put("userid", userid);
    payload.put("timestamp", System.currentTimeMillis());

    Event event = new Event("manning/osgi/login", payload);

    admin.postEvent(event);
  }
예제 #6
0
  /** Called by the current ClockSyncProvider after each Clock synchronization */
  public void onClockUpdate(long offset) {

    s_logger.info("Clock update. Offset: {}", offset);

    // set system clock if necessary
    boolean bClockUpToDate = false;
    if (offset != 0) {
      long time = System.currentTimeMillis() + offset;
      SafeProcess proc = null;
      try {
        proc = ProcessUtil.exec("date -s @" + time / 1000); // divide by 1000 to switch to seconds
        proc.waitFor();
        if (proc.exitValue() == 0) {
          bClockUpToDate = true;
          s_logger.info("System Clock Updated to {}", new Date());
        } else {
          s_logger.error(
              "Unexpected error while updating System Clock - it should've been {}", new Date());
        }
      } catch (Exception e) {
        s_logger.error("Error updating System Clock", e);
      } finally {
        if (proc != null) ProcessUtil.destroy(proc);
      }
    } else {
      bClockUpToDate = true;
    }

    // set hardware clock
    boolean updateHwClock = false;
    if (m_properties.containsKey("clock.set.hwclock")) {
      updateHwClock = (Boolean) m_properties.get("clock.set.hwclock");
    }
    if (updateHwClock) {
      SafeProcess proc = null;
      try {
        proc = ProcessUtil.exec("hwclock --utc --systohc");
        proc.waitFor();
        if (proc.exitValue() == 0) {
          s_logger.info("Hardware Clock Updated");
        } else {
          s_logger.error("Unexpected error while updating Hardware Clock");
        }
      } catch (Exception e) {
        s_logger.error("Error updating Hardware Clock", e);
      } finally {
        if (proc != null) ProcessUtil.destroy(proc);
      }
    }

    // Raise the event
    if (bClockUpToDate) {
      m_eventAdmin.postEvent(new ClockEvent(new HashMap<String, Object>()));
    }
  }
  /** @see UserAdminUtil#fireEvent(int, Role) */
  @Override
  public void fireEvent(int type, Role role) {
    if (null == role) {
      throw new IllegalArgumentException("parameter role must not be null");
    }
    ServiceReference<?> reference = userAdminRegistration.getReference();
    final UserAdminEvent uaEvent = new UserAdminEvent(reference, type, role);
    //
    // send event to all listeners, asynchronously - in a separate thread!!
    //
    UserAdminListener[] eventListeners = listenerService.getServices(new UserAdminListener[0]);
    if (null != eventListeners) {
      for (Object listenerObject : eventListeners) {
        final UserAdminListener listener = (UserAdminListener) listenerObject;
        eventExecutor.execute(
            new Runnable() {

              @Override
              public void run() {
                listener.roleChanged(uaEvent);
              }
            });
      }
    }
    //
    // send event to EventAdmin if present
    //
    EventAdmin eventAdmin = m_eventService.getService();
    String name = getEventTypeName(type);
    if (null != eventAdmin && name != null) {
      Dictionary<String, Object> properties = new Hashtable<String, Object>();
      properties.put("event", uaEvent);
      properties.put("role", role);
      properties.put("role.name", role.getName());
      properties.put("role.type", role.getType());
      properties.put("service", reference);
      properties.put("service.id", reference.getProperty(Constants.SERVICE_ID));
      properties.put("service.objectClass", reference.getProperty(Constants.OBJECTCLASS));
      properties.put("service.pid", reference.getProperty(Constants.SERVICE_PID));
      //
      Event event = new Event(PaxUserAdminConstants.EVENT_TOPIC_PREFIX + name, properties);
      eventAdmin.postEvent(event);
    } else {
      String message =
          "No event service available or incompatible type - cannot send event of type '"
              + name
              + "' for role '"
              + role.getName()
              + "'";
      logMessage(this, LogService.LOG_DEBUG, message);
    }
  }
예제 #8
0
 @Override
 protected void initializePresenter() {
   view.titleLabel.textProperty().bind(stage.titleProperty());
   view.closeButton.setOnMouseClicked(
       e ->
           Platform.runLater(
               () -> {
                 stage.close();
                 eventAdmin.postEvent(new ApplicationExitEvent());
               }));
   view.minimizeButton.setOnMouseClicked(e -> Platform.runLater(() -> stage.setIconified(true)));
   stage
       .focusedProperty()
       .addListener(
           (dummy, oldVal, newVal) ->
               view.rootContainer.pseudoClassStateChanged(
                   PseudoClass.getPseudoClass("window-focused"), newVal));
 }
예제 #9
0
 @Override
 public boolean post(String topic, Object data) {
   Event event = constructEvent(topic, data);
   Activator activator = Activator.getDefault();
   if (activator == null) {
     if (logger != null) {
       logger.error(NLS.bind(ServiceMessages.NO_EVENT_ADMIN, event.toString()));
     }
     return false;
   }
   EventAdmin eventAdmin = activator.getEventAdmin();
   if (eventAdmin == null) {
     if (logger != null) {
       logger.error(NLS.bind(ServiceMessages.NO_EVENT_ADMIN, event.toString()));
     }
     return false;
   }
   eventAdmin.postEvent(event);
   return true;
 }
  /**
   * {@inheritDoc} This post processor is only interested in posts to messages, so it should iterate
   * rapidly through all messages.
   *
   * @see
   *     org.apache.sling.servlets.post.SlingPostProcessor#process(org.apache.sling.api.SlingHttpServletRequest,
   *     java.util.List)
   */
  public void process(SlingHttpServletRequest request, List<Modification> changes)
      throws Exception {

    Resource resource = request.getResource();
    ResourceResolver resourceResolver = request.getResourceResolver();
    if (SparseContentResource.SPARSE_CONTENT_RT.equals(resource.getResourceSuperType())) {
      Session session = resource.adaptTo(Session.class);
      ContentManager contentManager = session.getContentManager();
      Map<Content, String> messageMap = new HashMap<Content, String>();
      for (Modification m : changes) {
        try {
          switch (m.getType()) {
            case CREATE:
            case MODIFY:
              String path = m.getSource();
              if (path.lastIndexOf("@") > 0) {
                path = path.substring(0, path.lastIndexOf("@"));
              }
              if (path.endsWith("/" + MessageConstants.PROP_SAKAI_MESSAGEBOX)) {
                path =
                    path.substring(
                        0, path.length() - MessageConstants.PROP_SAKAI_MESSAGEBOX.length() - 1);
              }

              // The Modification Source is the Resource path, and so we
              // need to translate that into a Content path.
              // TODO This is not a cheap operation. We might be better off
              // if we start including the Content path in our Modification objects.
              Resource modifiedResource = resourceResolver.getResource(path);
              if (modifiedResource == null) {
                return;
              }
              Content content = modifiedResource.adaptTo(Content.class);
              String contentPath = content.getPath();

              if (contentManager.exists(contentPath)) {
                content = contentManager.get(contentPath);
                if (content.hasProperty(SLING_RESOURCE_TYPE_PROPERTY)
                    && content.hasProperty(PROP_SAKAI_MESSAGEBOX)) {
                  if (SAKAI_MESSAGE_RT.equals(content.getProperty(SLING_RESOURCE_TYPE_PROPERTY))
                      && BOX_OUTBOX.equals(content.getProperty(PROP_SAKAI_MESSAGEBOX))) {
                    String sendstate;
                    if (content.hasProperty(PROP_SAKAI_SENDSTATE)) {
                      sendstate = (String) content.getProperty(PROP_SAKAI_SENDSTATE);
                    } else {
                      sendstate = STATE_NONE;
                    }
                    messageMap.put(content, sendstate);
                  }
                }
              }
              break;
          }
        } catch (StorageClientException ex) {
          LOGGER.warn("Failed to process on create for {} ", m.getSource(), ex);
        } catch (AccessDeniedException ex) {
          LOGGER.warn("Failed to process on create for {} ", m.getSource(), ex);
        }
      }

      List<String> handledNodes = new ArrayList<String>();
      // Check if we have any nodes that have a pending state and launch an OSGi
      // event
      for (Entry<Content, String> mm : messageMap.entrySet()) {
        Content content = mm.getKey();
        String path = content.getPath();
        String state = mm.getValue();
        if (!handledNodes.contains(path)) {
          if (STATE_NONE.equals(state) || STATE_PENDING.equals(state)) {

            content.setProperty(PROP_SAKAI_SENDSTATE, STATE_NOTIFIED);
            contentManager.update(content);

            Dictionary<String, Object> messageDict = new Hashtable<String, Object>();
            // WARNING
            // We can't pass in the node, because the session might expire before the event gets
            // handled
            // This does mean that the listener will have to get the node each time, and probably
            // create a new session for each message
            // This might be heavy on performance.
            messageDict.put(EVENT_LOCATION, path);
            messageDict.put(UserConstants.EVENT_PROP_USERID, request.getRemoteUser());
            LOGGER.debug("Launched event for message: {} ", path);
            Event pendingMessageEvent = new Event(PENDINGMESSAGE_EVENT, messageDict);
            // KERN-790: Initiate a synchronous event.
            try {
              eventAdmin.postEvent(pendingMessageEvent);
              handledNodes.add(path);
            } catch (Exception e) {
              LOGGER.warn("Failed to post message dispatch event, cause {} ", e.getMessage(), e);
            }
          }
        }
      }
    }
  }
예제 #11
0
 @Override
 public boolean post(String topic, Object data) {
   Event event = constructEvent(topic, data);
   eventAdmin.postEvent(event);
   return true;
 }