예제 #1
0
 @Test
 public void onlyFirstShouldSubscribeAndLastUnsubscribe() {
   final AtomicInteger subscriptionCount = new AtomicInteger();
   final AtomicInteger unsubscriptionCount = new AtomicInteger();
   Observable<Integer> observable =
       Observable.create(
           new Observable.OnSubscribeFunc<Integer>() {
             @Override
             public Subscription onSubscribe(Observer<? super Integer> observer) {
               subscriptionCount.incrementAndGet();
               return Subscriptions.create(
                   new Action0() {
                     @Override
                     public void call() {
                       unsubscriptionCount.incrementAndGet();
                     }
                   });
             }
           });
   Observable<Integer> refCounted = observable.publish().refCount();
   @SuppressWarnings("unchecked")
   Observer<Integer> observer = mock(Observer.class);
   Subscription first = refCounted.subscribe(observer);
   assertEquals(1, subscriptionCount.get());
   Subscription second = refCounted.subscribe(observer);
   assertEquals(1, subscriptionCount.get());
   first.unsubscribe();
   assertEquals(0, unsubscriptionCount.get());
   second.unsubscribe();
   assertEquals(1, unsubscriptionCount.get());
 }
예제 #2
0
 public void copySubscribers(AEntity from, AEntity to) {
   Subscription fromSubscription = subscriptionDao.getSubscriptionBySubject(from);
   if (fromSubscription == null || fromSubscription.isSubscribersEmailsEmpty()) return;
   Subscription toSubscription = subscriptionDao.getSubscriptionBySubject(to);
   if (toSubscription == null) toSubscription = subscriptionDao.postSubscription(to);
   toSubscription.addSubscribersEmails(fromSubscription.getSubscribersEmails());
 }
 @Override
 public synchronized int match(
     final Message message, final Set<Object> matches, final List<Subscription> triggers) {
   final MessageType type = message.getMsgType();
   final Map<Object, List<Subscription>> objectMap = this.messageTypes.get(type);
   if (objectMap == null) {
     return 0;
   }
   int count = 0;
   for (final Map.Entry<Object, List<Subscription>> entry : objectMap.entrySet()) {
     final List<Subscription> subs = entry.getValue();
     boolean matched = false;
     for (final Subscription sub : subs) {
       if (sub.filter.matchRemaining(message)) {
         if (!matched && matches.add(entry.getKey())) {
           ++count;
           matched = true;
         }
         if (triggers == null || sub.getTrigger() == null || !sub.getTrigger().match(message)) {
           break;
         }
         triggers.add(sub);
       }
     }
   }
   return count;
 }
예제 #4
0
  @Override
  public List<Forum> getForumsOfaUser(int userId) {
    // TODO Auto-generated method stub
    List<Forum> forums = new ArrayList<Forum>();
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();
      Query query = session.createQuery("from Subscription where userId = :userId");
      query.setString("userId", String.valueOf(userId));
      List<Subscription> userSubscribedGroups = query.list();
      for (Subscription subsc : userSubscribedGroups) {
        query = session.createQuery("from Forum where forumId = :forumId");
        query.setParameter("forumId", subsc.getForumId());
        // add this to a list variable query.uniqueResult();
        forums.add((Forum) query.uniqueResult());
      }

    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
    return forums;
  }
예제 #5
0
 public void subscribe(String email, AEntity subject) {
   if (!Str.isEmail(email)) throw new RuntimeException("Invalid email: " + email);
   email = email.toLowerCase();
   Subscription subscription = subscriptionDao.getSubscriptionBySubject(subject);
   if (subscription == null) subscription = subscriptionDao.postSubscription(subject);
   subscription.addSubscribersEmail(email);
   log.info(email, "subscribed to", subject);
 }
 private void shutdown(QueueConsumer consumer) {
   synchronized (consumer) {
     consumer.shutdown();
     queueConsumers.remove(consumer.getId());
     Subscription subscription = (Subscription) consumer;
     if (subscription.isDeleteWhenIdle()) deleteSubscriberQueue(consumer);
   }
 }
    @Override
    public void onSubscribe(Subscription s) {
      if (SubscriptionHelper.validateSubscription(this.s, s)) {
        return;
      }
      this.s = s;

      Subscriber<? super U> actual = this.actual;

      U b;

      try {
        b = bufferSupplier.get();
      } catch (Throwable e) {
        cancelled = true;
        s.cancel();
        EmptySubscription.error(e, actual);
        return;
      }

      if (b == null) {
        cancelled = true;
        s.cancel();
        EmptySubscription.error(new NullPointerException("The buffer supplied is null"), actual);
        return;
      }
      buffer = b;

      Publisher<B> boundary;

      try {
        boundary = boundarySupplier.get();
      } catch (Throwable ex) {
        cancelled = true;
        s.cancel();
        EmptySubscription.error(ex, actual);
        return;
      }

      if (boundary == null) {
        cancelled = true;
        s.cancel();
        EmptySubscription.error(
            new NullPointerException("The boundary publisher supplied is null"), actual);
        return;
      }

      BufferBoundarySubscriber<T, U, B> bs = new BufferBoundarySubscriber<T, U, B>(this);
      other = bs;

      actual.onSubscribe(this);

      if (!cancelled) {
        s.request(Long.MAX_VALUE);

        boundary.subscribe(bs);
      }
    }
예제 #8
0
 static void zza(Subscription subscription, Parcel parcel, int i) {
   int j = zzb.zzK(parcel);
   zzb.zza(parcel, 1, subscription.getDataSource(), i, false);
   zzb.zzc(parcel, 1000, subscription.getVersionCode());
   zzb.zza(parcel, 2, subscription.getDataType(), i, false);
   zzb.zza(parcel, 3, subscription.zzlI());
   zzb.zzc(parcel, 4, subscription.getAccuracyMode());
   zzb.zzH(parcel, j);
 }
    void next() {

      Disposable o = other;

      U next;

      try {
        next = bufferSupplier.get();
      } catch (Throwable e) {
        cancel();
        actual.onError(e);
        return;
      }

      if (next == null) {
        cancel();
        actual.onError(new NullPointerException("The buffer supplied is null"));
        return;
      }

      Publisher<B> boundary;

      try {
        boundary = boundarySupplier.get();
      } catch (Throwable ex) {
        cancelled = true;
        s.cancel();
        actual.onError(ex);
        return;
      }

      if (boundary == null) {
        cancelled = true;
        s.cancel();
        actual.onError(new NullPointerException("The boundary publisher supplied is null"));
        return;
      }

      BufferBoundarySubscriber<T, U, B> bs = new BufferBoundarySubscriber<T, U, B>(this);

      if (!OTHER.compareAndSet(this, o, bs)) {
        return;
      }

      U b;
      synchronized (this) {
        b = buffer;
        if (b == null) {
          return;
        }
        buffer = next;
      }

      boundary.subscribe(bs);

      fastpathEmitMax(b, false, this);
    }
예제 #10
0
  public static boolean includesSubscription(
      ResourceCollection<Subscription> collection, Subscription item) {
    for (Subscription subscription : collection) {
      if (subscription.getId().equals(item.getId())) {
        return true;
      }
    }

    return false;
  }
 public void stop() {
   for (QueueConsumer consumer : queueConsumers.values()) {
     consumer.shutdown();
     Subscription subscription = (Subscription) consumer;
     if (!subscription.isDurable()) {
       deleteSubscriberQueue(consumer);
     }
   }
   queueConsumers.clear();
 }
예제 #12
0
 @Override
 public void setSubscriptions(final Collection<Subscription> subscriptions)
     throws MetaClientException {
   if (subscriptions == null) {
     return;
   }
   for (final Subscription subscription : subscriptions) {
     this.subscribe(
         subscription.getTopic(), subscription.getMaxSize(), subscription.getMessageListener());
   }
 }
예제 #13
0
 private void unsubscribeAll(String email, String key) {
   email = email.toLowerCase();
   Set<Subscription> subscriptions = subscriptionDao.getSubscriptionsBySubscribersEmail(email);
   if (subscriptions.isEmpty()) {
     log.debug(email, "is not subscribed to anything");
     return;
   }
   for (Subscription subscription : subscriptions) {
     subscription.removeSubscribersEmail(email);
   }
   log.info(email, "unsubscribed from", subscriptions.size(), "entities");
 }
예제 #14
0
  /** @param event Event */
  public void publish(E event) {
    // TODO On background thread, take a copy to iterate over.
    for (Subscription<S, E> subscription : subscriptions) {
      if (subscription.criteria() != null) {
        if (!subscription.criteria().apply(event)) {
          continue;
        }
      }

      subscription.callback().apply(event);
    }
  }
 public void testTimeout(String target) {
   QueueConsumer consumer = queueConsumers.get(target);
   Subscription subscription = (Subscription) consumer;
   if (consumer == null) return;
   synchronized (consumer) {
     if (System.currentTimeMillis() - consumer.getLastPingTime() > subscription.getTimeout()) {
       HornetQRestLogger.LOGGER.shutdownRestSubscription(consumer.getId());
       consumer.shutdown();
       queueConsumers.remove(consumer.getId());
       serviceManager.getTimeoutTask().remove(consumer.getId());
       if (subscription.isDeleteWhenIdle()) deleteSubscriberQueue(consumer);
     }
   }
 }
예제 #16
0
  @Test
  public void countDownTest() {
    EventSource<Void> src1 = new EventSource<Void>();
    EventSource<Void> src2 = new EventSource<Void>();
    EventSource<Void> reset = new EventSource<Void>();

    BiFunction<Integer, Void, Tuple2<Integer, Optional<String>>> countdown =
        (s, i) -> s == 1 ? t(3, Optional.of("COUNTDOWN REACHED")) : t(s - 1, Optional.empty());

    EventStream<String> countdowns =
        StateMachine.init(3)
            .on(src1)
            .transmit(countdown)
            .on(src2)
            .transmit(countdown)
            .on(reset)
            .transition((s, i) -> 3)
            .toEventStream();

    Counter counter = new Counter();
    Subscription sub = countdowns.hook(x -> counter.inc()).pin();

    src1.push(null);
    src2.push(null);
    assertEquals(0, counter.get());

    src1.push(null);
    assertEquals(1, counter.getAndReset());

    src2.push(null);
    src2.push(null);
    reset.push(null);
    assertEquals(0, counter.get());
    src2.push(null);
    assertEquals(0, counter.get());
    src1.push(null);
    assertEquals(0, counter.get());
    src2.push(null);
    assertEquals(1, counter.getAndReset());

    sub.unsubscribe();
    src1.push(null);
    src1.push(null);
    src1.push(null);
    src1.push(null);
    src1.push(null);
    src1.push(null);
    assertEquals(0, counter.get());
  }
예제 #17
0
 public void unsubscribe(String email, AEntity subject, String key) throws InvalidKeyException {
   email = email.toLowerCase();
   if (!createKey(email).equals(key)) throw new InvalidKeyException(email);
   if (subject == null) {
     unsubscribeAll(email, key);
     return;
   }
   Subscription subscription = subscriptionDao.getSubscriptionBySubject(subject);
   if (subscription == null || !subscription.containsSubscribersEmail(email)) {
     log.debug(email, "is not subscribed to", subject);
     return;
   }
   subscription.removeSubscribersEmail(email);
   log.info(email, "unsubscribed from", subject);
 }
 @Override
 public boolean testTimeout(String target, boolean autoShutdown) {
   QueueConsumer consumer = queueConsumers.get(target);
   Subscription subscription = (Subscription) consumer;
   if (consumer == null) return false;
   if (System.currentTimeMillis() - consumer.getLastPingTime() > subscription.getTimeout()) {
     ActiveMQRestLogger.LOGGER.shutdownRestSubscription(consumer.getId());
     if (autoShutdown) {
       shutdown(consumer);
     }
     return true;
   } else {
     return false;
   }
 }
예제 #19
0
 public synchronized void onSubscribe(Subscription s) {
   threadAssertTrue(sn == null);
   sn = s;
   notifyAll();
   if (throwOnCall) throw new SPException();
   if (request) sn.request(1L);
 }
예제 #20
0
  /**
   * Creates and sends a SUBSCRIBE request to the subscription <tt>Address</tt>/Request URI of a
   * specific <tt>Subscription</tt> in order to request receiving event notifications and adds the
   * specified <tt>Subscription</tt> to the list of subscriptions managed by this instance. The
   * added <tt>Subscription</tt> may later receive notifications to process the <tt>Request</tt>s
   * and/or <tt>Response</tt>s which constitute the signaling session associated with it. If the
   * attempt to create and send the SUBSCRIBE request fails, the specified <tt>Subscription</tt> is
   * not added to the list of subscriptions managed by this instance.
   *
   * @param subscription a <tt>Subscription</tt> which specifies the properties of the SUBSCRIBE
   *     request to be created and sent, to be added to the list of subscriptions managed by this
   *     instance
   * @throws OperationFailedException if we fail constructing or sending the subscription request.
   */
  public void subscribe(Subscription subscription) throws OperationFailedException {
    Dialog dialog = subscription.getDialog();

    if ((dialog != null) && DialogState.TERMINATED.equals(dialog.getState())) dialog = null;

    // create the subscription
    ClientTransaction subscribeTransaction = null;
    try {
      subscribeTransaction =
          (dialog == null)
              ? createSubscription(subscription, subscriptionDuration)
              : createSubscription(subscription, dialog, subscriptionDuration);
    } catch (OperationFailedException ex) {
      ProtocolProviderServiceSipImpl.throwOperationFailedException(
          "Failed to create the subscription", OperationFailedException.INTERNAL_ERROR, ex, logger);
    }

    // we register the contact to find him when the OK will arrive
    CallIdHeader callIdHeader =
        (CallIdHeader) subscribeTransaction.getRequest().getHeader(CallIdHeader.NAME);
    String callId = callIdHeader.getCallId();
    addSubscription(callId, subscription);

    // send the message
    try {
      if (dialog == null) subscribeTransaction.sendRequest();
      else dialog.sendRequest(subscribeTransaction);
    } catch (SipException ex) {
      // this contact will never been accepted or rejected
      removeSubscription(callId, subscription);

      ProtocolProviderServiceSipImpl.throwOperationFailedException(
          "Failed to send the subscription", OperationFailedException.NETWORK_FAILURE, ex, logger);
    }
  }
예제 #21
0
 /** Adds all containers and parameters to the subscription */
 public void startProvidingAll() {
   for (SequenceContainer c : xtcedb.getSequenceContainers()) {
     if (c.getBaseContainer() == null) {
       subscription.addAll(c);
     }
   }
 }
 @Override
 public void alert(Incident incident, Subscription subscription) {
   String target = subscription.getTarget();
   if (StringUtils.isEmpty(target)) {
     target = "/stagemonitor/alerts";
   }
   httpClient.sendAsJson("POST", corePlugin.getElasticsearchUrl() + target, incident);
 }
예제 #23
0
  public Channel removeChannel(String channelId, boolean timeout) {
    if (channelId == null) return null;

    // Remove existing channel id/subscriptions in distributed data (clustering).
    try {
      DistributedData gdd = graniteConfig.getDistributedDataFactory().getInstance();
      if (gdd != null) {
        log.debug("Removing channel id from distributed data: %s", channelId);
        gdd.removeChannelId(channelId);
      }
    } catch (Exception e) {
      log.error(e, "Could not remove channel id from distributed data: %s", channelId);
    }

    TimeChannel<?> timeChannel = channels.get(channelId);
    Channel channel = null;
    if (timeChannel != null) {
      try {
        if (timeChannel.getTimerTask() != null) timeChannel.getTimerTask().cancel();
      } catch (Exception e) {
        // Should never happen...
      }

      channel = timeChannel.getChannel();

      try {
        for (Subscription subscription : channel.getSubscriptions()) {
          try {
            Message message = subscription.getUnsubscribeMessage();
            handleMessage(channel.getFactory(), message, true);
          } catch (Exception e) {
            log.error(
                e,
                "Error while unsubscribing channel: %s from subscription: %s",
                channel,
                subscription);
          }
        }
      } finally {
        channels.remove(channelId);
        channel.destroy(timeout);
      }
    }
    return channel;
  }
 @Override
 public void onNext(Try<Optional<T>> t) {
   if (done) {
     return;
   }
   if (t.hasError()) {
     s.cancel();
     onError(t.error());
   } else {
     Optional<T> o = t.value();
     if (o.isPresent()) {
       actual.onNext(o.get());
     } else {
       s.cancel();
       onComplete();
     }
   }
 }
예제 #25
0
 public synchronized void onNext(Integer t) {
   ++nexts;
   notifyAll();
   int current = t.intValue();
   threadAssertTrue(current >= last);
   last = current;
   if (request) sn.request(1L);
   if (throwOnCall) throw new SPException();
 }
  @SuppressWarnings("unchecked")
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Utils.registerObjectifyClasses();
    Objectify ofy = ObjectifyService.begin();
    log.setLevel(Level.ALL);

    List<Subscription> q = ofy.query(Subscription.class).list();

    resp.setContentType("application/json");
    JSONArray jResult = new JSONArray();

    String query = (String) req.getParameter("q");

    // log.info("Search called with query: " + query);

    if (query == null) {
      resp.getWriter().println("[]");
    }

    // Best matches
    for (Subscription s : q) {
      if (s.id.toLowerCase().startsWith(query.toLowerCase())
          || s.name.toLowerCase().startsWith(query.toLowerCase())) {
        JSONObject jSubscription = new JSONObject();
        jSubscription.put("id", s.id);
        jSubscription.put("name", s.name);
        jResult.add(jSubscription);
        s.name = ""; // Hack to prevent duplicates..
      }
    }

    // Middle matches
    for (Subscription s : q) {
      if (s.id.toLowerCase().contains(query.toLowerCase())
          || s.name.toLowerCase().contains(query.toLowerCase())) {
        JSONObject jSubscription = new JSONObject();
        jSubscription.put("id", s.id);
        jSubscription.put("name", s.name);
        jResult.add(jSubscription);
      }
    }

    resp.getWriter().println(jResult.toJSONString());
  }
예제 #27
0
    @SuppressWarnings("unchecked")
    // mocking is unchecked, unfortunately
    @Test
    public void testPeriodicScheduling() {
      final Func1<Long, Void> calledOp = mock(Func1.class);

      final TestScheduler scheduler = new TestScheduler();
      Subscription subscription =
          scheduler.schedulePeriodically(
              new Action0() {
                @Override
                public void call() {
                  System.out.println(scheduler.now());
                  calledOp.call(scheduler.now());
                }
              },
              1,
              2,
              TimeUnit.SECONDS);

      verify(calledOp, never()).call(anyLong());

      InOrder inOrder = Mockito.inOrder(calledOp);

      scheduler.advanceTimeBy(999L, TimeUnit.MILLISECONDS);
      inOrder.verify(calledOp, never()).call(anyLong());

      scheduler.advanceTimeBy(1L, TimeUnit.MILLISECONDS);
      inOrder.verify(calledOp, times(1)).call(1000L);

      scheduler.advanceTimeBy(1999L, TimeUnit.MILLISECONDS);
      inOrder.verify(calledOp, never()).call(3000L);

      scheduler.advanceTimeBy(1L, TimeUnit.MILLISECONDS);
      inOrder.verify(calledOp, times(1)).call(3000L);

      scheduler.advanceTimeBy(5L, TimeUnit.SECONDS);
      inOrder.verify(calledOp, times(1)).call(5000L);
      inOrder.verify(calledOp, times(1)).call(7000L);

      subscription.unsubscribe();
      scheduler.advanceTimeBy(11L, TimeUnit.SECONDS);
      inOrder.verify(calledOp, never()).call(anyLong());
    }
    @Override
    public void cancel() {
      if (!cancelled) {
        cancelled = true;
        s.cancel();
        disposeOther();

        if (enter()) {
          queue.clear();
        }
      }
    }
  @Override
  public ArrayList<Subscription> getSubscriptionList() throws AzureCmdException {

    String[] cmd = new String[] {"account", "list", "--json"};

    String json = AzureCommandHelper.getInstance().consoleExec(cmd);

    CustomJsonSlurper slurper = new CustomJsonSlurper();
    List<Map<String, Object>> tempRes = (List<Map<String, Object>>) slurper.parseText(json);

    ArrayList<Subscription> res = new ArrayList<Subscription>();
    for (Map<String, Object> item : tempRes) {
      Subscription s = new Subscription();
      s.setId(UUID.fromString(item.get("id").toString()));
      s.setName(item.get("name").toString());
      s.setCurrent((Boolean) item.get("isDefault"));

      res.add(s);
    }

    return res;
  }
예제 #30
0
    @Override
    public void onNext(T t) {
      if (done) {
        return;
      }
      try {
        onNext.accept(t);
      } catch (Throwable e) {
        s.cancel();
        onError(e);
        return;
      }

      actual.onNext(t);
    }