@Test
  public void testValidSubscription() {
    // add configuration
    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Capture the arg of subscription and return the mocked future
    ArgumentCaptor<String> urlProviderArg = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<SubscribeContext> subscribeContextArg =
        ArgumentCaptor.forClass(SubscribeContext.class);
    when(ngsiClient.subscribeContext(
            urlProviderArg.capture(), eq(null), subscribeContextArg.capture()))
        .thenReturn(responseFuture);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    // check ngsiClient.unsubscribe() is never called
    verify(ngsiClient, never()).unsubscribeContext(any(), any(), any());
    subscriptionManager.validateSubscriptionId("12345678", "http://iotAgent");
  }
  private void returnKeepAlive(ServiceRequest<PublishRequest, PublishResponse> service) {
    ResponseHeader header = service.createResponseHeader();

    UInteger sequenceNumber = uint(currentSequenceNumber());

    NotificationMessage notificationMessage =
        new NotificationMessage(sequenceNumber, DateTime.now(), new ExtensionObject[0]);

    UInteger[] available = getAvailableSequenceNumbers();

    UInteger requestHandle = service.getRequest().getRequestHeader().getRequestHandle();
    StatusCode[] acknowledgeResults = subscriptionManager.getAcknowledgeResults(requestHandle);

    PublishResponse response =
        new PublishResponse(
            header,
            subscriptionId,
            available,
            moreNotifications,
            notificationMessage,
            acknowledgeResults,
            new DiagnosticInfo[0]);

    service.setResponse(response);

    logger.debug(
        "[id={}] returned keep-alive NotificationMessage sequenceNumber={}.",
        subscriptionId,
        sequenceNumber);
  }
 @Test
 public void testInvalideSubscription() {
   // Mock future for unsubscribeContext
   ListenableFuture<UnsubscribeContextResponse> responseFuture =
       Mockito.mock(ListenableFuture.class);
   doNothing().when(responseFuture).addCallback(any(), any());
   when(ngsiClient.unsubscribeContext(eq("http://iotAgent"), eq(null), eq("9999")))
       .thenReturn(responseFuture);
   subscriptionManager.validateSubscriptionId("9999", "http://iotAgent");
 }
  @Test
  public void testUnsubscribeOnProviderRemoval() {

    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    // Return the mocked future on subscription
    when(ngsiClient.subscribeContext(any(), any(), any())).thenReturn(responseFuture);

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    // Mock future for unsubscribeContext
    ListenableFuture<UnsubscribeContextResponse> responseFuture2 =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture2).addCallback(successArg.capture(), any());
    when(ngsiClient.unsubscribeContext(eq("http://iotAgent"), eq(null), eq("12345678")))
        .thenReturn(responseFuture2);

    // Reset conf should trigger unsubsribeContext
    Configuration emptyConfiguration = getBasicConf();
    emptyConfiguration.getEventTypeIns().get(0).setProviders(Collections.emptySet());
    subscriptionManager.setConfiguration(emptyConfiguration);

    // Check that unsubsribe is called
    Assert.notNull(successArg.getValue());
  }
  // used by My
  public static SubscriptionData createOrUpdateSubscription(
      SubscriptionData inSubscription,
      VObjectData inObject,
      boolean isAmbiant,
      String isoCode,
      String inSrc,
      List<String> inTimeList)
      throws InvalidParameterException, InvalidSettingException, InvalidSchedulingsException,
          MissingSettingException {

    final Map<String, Object> theSettings = new HashMap<String, Object>();
    theSettings.put(AirHandler.LANGUAGE_SETTING, isoCode);
    theSettings.put(AirHandler.SOURCE_SETTING, inSrc);

    final List<Map<String, Object>> theSchedulings = new ArrayList<Map<String, Object>>();

    if (isAmbiant) {
      final Map<String, Object> scheduling = new HashMap<String, Object>();
      scheduling.put(SchedulingType.TYPE_KEY, SchedulingType.SCHEDULING_TYPE.Ambiant.getLabel());
      theSchedulings.add(scheduling);
    }

    final Map<String, Object> scheduling = new HashMap<String, Object>();
    scheduling.put(SchedulingType.TYPE_KEY, SchedulingType.SCHEDULING_TYPE.VoiceTrigger.getLabel());
    scheduling.put(KeywordHandler.KEYWORD, AbstractRecoService.SMOG);
    theSchedulings.add(scheduling);

    theSchedulings.addAll(
        ApplicationHandlerHelper.generateDailySchedulings(
            inTimeList, inObject.getReference().getTimeZone().getJavaTimeZone(), true));

    if (inSubscription == null) {
      return SubscriptionManager.createSubscription(
          AirHandler.AIR_APPLICATION, inObject, theSettings, theSchedulings, null);
    }

    SubscriptionManager.updateSubscription(inSubscription, theSettings, theSchedulings, null);
    return inSubscription;
  }
示例#6
0
 @PostConstruct
 protected void loadConfigurationOnStartup() {
   // Try restoring the persisted configuration if any
   try {
     if (persistence.checkConfigurationDirectory()) {
       Configuration configuration = persistence.loadConfiguration();
       complexEventProcessor.setConfiguration(configuration);
       subscriptionManager.setConfiguration(configuration);
     }
   } catch (PersistenceException | ConfigurationException e) {
     logger.error("Failed to load or apply persisted configuration", e);
   }
 }
示例#7
0
  public SubscriptionHandler(final SubscriptionManager manager) {
    this.behaviour = Behaviour.none;

    manager.onSubscriptionRequested(
        new Listener2<XmppURI, String>() {
          @Override
          public void onEvent(XmppURI uri, String nick) {
            GWT.log("Subscription requested: " + nick, null);
            if (behaviour == Behaviour.acceptAll) {
              manager.approveSubscriptionRequest(uri, nick);
            } else if (behaviour == Behaviour.refuseAll) {
              manager.refuseSubscriptionRequest(uri);
            }
          }
        });
  }
  @Override
  public void handle(Request request, Response response, SubscribeRequest message)
      throws Exception {
    String key = message.getKey();
    StatusResponse status = new StatusResponse(key, true);
    manager.subscribe(message);
    String content = gson.toJson(status);
    OutputStream output = response.getOutputStream();
    byte[] data = content.getBytes("UTF-8");

    response.setContentType("text/json");
    response.setContentLength(data.length);
    output.write(data);
    output.flush();
    response.close();
  }
  @Test
  public void setConfigurationOK() throws Exception {

    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Capture the arg of subscription and return the mocked future
    ArgumentCaptor<String> urlProviderArg = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<SubscribeContext> subscribeContextArg =
        ArgumentCaptor.forClass(SubscribeContext.class);
    when(ngsiClient.subscribeContext(
            urlProviderArg.capture(), eq(null), subscribeContextArg.capture()))
        .thenReturn(responseFuture);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    SubscribeContext subscribeContext = subscribeContextArg.getValue();
    assertEquals("S.*", subscribeContext.getEntityIdList().get(0).getId());
    assertEquals("TempSensor", subscribeContext.getEntityIdList().get(0).getType());
    assertEquals(true, subscribeContext.getEntityIdList().get(0).getIsPattern());
    assertEquals("temp", subscribeContext.getAttributeList().get(0));
    assertEquals("PT1H", subscribeContext.getDuration());
    assertEquals("http://iotAgent", urlProviderArg.getValue());

    Set<Provider> providers = configuration.getEventTypeIns().get(0).getProviders();
    for (Provider provider : providers) {
      assertEquals("12345678", provider.getSubscriptionId());
      assertNotNull(provider.getSubscriptionDate());
    }
  }
示例#10
0
  synchronized void startPublishingTimer() {
    if (state.get() == State.Closed) return;

    lifetimeCounter--;

    if (lifetimeCounter < 1) {
      logger.debug("[id={}] lifetime expired.", subscriptionId);

      setState(State.Closing);
    } else {
      long interval = DoubleMath.roundToLong(publishingInterval, RoundingMode.UP);

      subscriptionManager
          .getServer()
          .getScheduledExecutorService()
          .schedule(this::onPublishingTimer, interval, TimeUnit.MILLISECONDS);
    }
  }
示例#11
0
 public Session getSession() {
   return subscriptionManager.getSession();
 }
示例#12
0
  private void sendNotifications(
      ServiceRequest<PublishRequest, PublishResponse> service, List<UaStructure> notifications) {

    List<MonitoredItemNotification> dataNotifications = Lists.newArrayList();
    List<EventFieldList> eventNotifications = Lists.newArrayList();

    notifications.forEach(
        notification -> {
          if (notification instanceof MonitoredItemNotification) {
            dataNotifications.add((MonitoredItemNotification) notification);
          } else if (notification instanceof EventFieldList) {
            eventNotifications.add((EventFieldList) notification);
          }
        });

    List<ExtensionObject> notificationData = Lists.newArrayList();

    if (dataNotifications.size() > 0) {
      DataChangeNotification dataChange =
          new DataChangeNotification(
              dataNotifications.toArray(new MonitoredItemNotification[dataNotifications.size()]),
              new DiagnosticInfo[0]);

      notificationData.add(ExtensionObject.encode(dataChange));
    }

    if (eventNotifications.size() > 0) {
      EventNotificationList eventChange =
          new EventNotificationList(
              eventNotifications.toArray(new EventFieldList[eventNotifications.size()]));

      notificationData.add(ExtensionObject.encode(eventChange));
    }

    UInteger sequenceNumber = uint(nextSequenceNumber());

    NotificationMessage notificationMessage =
        new NotificationMessage(
            sequenceNumber,
            new DateTime(),
            notificationData.toArray(new ExtensionObject[notificationData.size()]));

    availableMessages.put(notificationMessage.getSequenceNumber(), notificationMessage);
    UInteger[] available = getAvailableSequenceNumbers();

    UInteger requestHandle = service.getRequest().getRequestHeader().getRequestHandle();
    StatusCode[] acknowledgeResults = subscriptionManager.getAcknowledgeResults(requestHandle);

    ResponseHeader header = service.createResponseHeader();

    PublishResponse response =
        new PublishResponse(
            header,
            subscriptionId,
            available,
            moreNotifications,
            notificationMessage,
            acknowledgeResults,
            new DiagnosticInfo[0]);

    service.setResponse(response);

    logger.debug(
        "[id={}] returning {} DataChangeNotification(s) and {} EventNotificationList(s) sequenceNumber={}.",
        subscriptionId,
        dataNotifications.size(),
        eventNotifications.size(),
        sequenceNumber);
  }
示例#13
0
 private synchronized PublishQueue publishQueue() {
   return subscriptionManager.getPublishQueue();
 }