Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2011 JBoss, by Red Hat, Inc
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *    http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.jboss.errai.enterprise.client.cdi.api;
 
 import java.util.*;
 
CDI client interface.

Author(s):
Heiko Braun <hbraun@redhat.com>
Christian Sadilek <csadilek@redhat.com>
Mike Brock <cbrock@redhat.com>
 
 public class CDI {
   public static final String CDI_SUBJECT_PREFIX = "cdi.event:";
 
   public static final String CDI_SERVICE_SUBJECT_PREFIX = "cdi.event:";
   public static final String SERVER_DISPATCHER_SUBJECT =  + "Dispatcher";
   public static final String CLIENT_DISPATCHER_SUBJECT =  + "ClientDispatcher";
   private static final String CLIENT_ALREADY_FIRED_RESOURCE =  + "AlreadyFired";
 
   private static final Set<StringremoteEvents = new HashSet<String>();
   private static boolean active = false;
 
   private static Set<StringlocalOnlyObserverTypes = new HashSet<String>();
   private static Map<StringCollection<String>> lookupTable = Collections.emptyMap();
 
   private static Logger logger = LoggerFactory.getLogger(CDI.class);
   
   public static final MessageCallback ROUTING_CALLBACK = new MessageCallback() {
     @Override
     public void callback(final Message message) {
       consumeEventFromMessage(message);
     }
   };
 
   public static String getSubjectNameByType(final String typeName) {
     return  + typeName;
   }

  
Should only be called by bootstrapper for testing purposes.
 
   public void __resetSubsystem() {
     for (final String eventType : new HashSet<String>(((ClientMessageBus) ErraiBus.get()).getAllRegisteredSubjects())) {
       if (eventType.startsWith()) {
         ErraiBus.get().unsubscribeAll(eventType);
       }
     }
 
     .clear();
      = false;
     .clear();
      = Collections.emptyMap();
   }
 
   public void initLookupTable(final CDIEventTypeLookup lookup) {
      = lookup.getTypeLookupMap();
   }

  
Return a list of string representations for the qualifiers.

Parameters:
qualifiers -
Returns:
  public static Set<StringgetQualifiersPart(final Annotation[] qualifiers) {
    Set<StringqualifiersPart = null;
    if (qualifiers != null) {
      for (final Annotation qualifier : qualifiers) {
        if (qualifiersPart == null)
          qualifiersPart = new HashSet<String>(qualifiers.length);
        qualifiersPart.add(qualifier.annotationType().getName());
      }
    }
    return qualifiersPart == null ? Collections.<String>emptySet() : qualifiersPart;
  }
  public static void fireEvent(final Object payloadfinal Annotation... qualifiers) {
    fireEvent(falsepayloadqualifiers);
  }
  public static void fireEvent(final boolean local,
                               final Object payload,
                               final Annotation... qualifiers) {
    if (payload == nullreturn;
    final Object beanRef;
    if (payload instanceof WrappedPortable) {
      beanRef = ((WrappedPortablepayload).unwrap();
      if (beanRef == nullreturn;
    }
    else {
      beanRef = payload;
    }
    final Map<StringObjectmessageMap = new HashMap<StringObject>();
    messageMap.put(..name(), beanRef.getClass().getName());
    messageMap.put(..name(), beanRef);
    messageMap.put(..name(), "1");
    if (qualifiers != null && qualifiers.length > 0) {
      messageMap.put(..name(), getQualifiersPart(qualifiers));
    }
    consumeEventFromMessage(CommandMessage.createWithParts(messageMap));
      final CommandMessage withParts = CommandMessage.createWithParts(messageMap);
      fireOnSubscribe(beanRef.getClass().getName(), withParts);
    }
  }
  public static Subscription subscribeLocal(final String eventTypefinal AbstractCDIEventCallback<?> callback) {
    return subscribeLocal(eventTypecallbacktrue);
  }
  private static Subscription subscribeLocal(final String eventTypefinal AbstractCDIEventCallback<?> callback,
          boolean isLocalOnly) {
    if (!.containsKey(eventType)) {
      .put(eventTypenew ArrayList<AbstractCDIEventCallback<?>>());
    }
    .get(eventType).add(callback);
    
    if (isLocalOnly) {
      .add(eventType);
    }
    return new Subscription() {
      @Override
      public void remove() {
        unsubscribe(eventTypecallback);
      }
    };
  }
  public static Subscription subscribe(final String eventTypefinal AbstractCDIEventCallback<?> callback) {
    if (isRemoteCommunicationEnabled() && ErraiBus.get() instanceof ClientMessageBusImpl
            && ((ClientMessageBusImpl) ErraiBus.get()).getState().equals(.)) {
      MessageBuilder.createMessage()
          .command(.)
          .with(.eventType)
          .with(.callback.getQualifiers())
          .noErrorHandling().sendNowWith(ErraiBus.get());
    }
    return subscribeLocal(eventTypecallbackfalse);
  }
  private static void unsubscribe(final String eventTypefinal AbstractCDIEventCallback<?> callback) {
    if (.containsKey(eventType)) {
      .get(eventType).remove(callback);
      
      if (!.contains(eventType)) {
        boolean shouldUnsubscribe = true;
        for (AbstractCDIEventCallback<?> cb : .get(eventType)) {
          if (cb.getQualifiers().equals(callback.getQualifiers())) {
            // found another matching observer -> do not unsubscribe
            shouldUnsubscribe = false;
            break;
          }
        }
        
        if (isRemoteCommunicationEnabled() && shouldUnsubscribe) {
          MessageBuilder.createMessage()
              .toSubject(.)
              .command(.)
              .with(.eventType)
              .with(.callback.getQualifiers())
              .noErrorHandling().sendNowWith(ErraiBus.get());
        }
        
        if (.get(eventType).isEmpty()) {
          .remove(eventType);
        }
      }
    }
  }

  
Informs the server of all active CDI observers currently registered on the client. This is not strictly necessary when the client bus first connects, because observers register themselves with the server as they are created. However, if the QueueSession expires and the bus reconnects, it is essential to inform the server of all existing CDI observers so the server-side event routing can be established for the new session.

Application code should never have to call this method directly. The Errai framework calls this method when required.

  public static void resendSubscriptionRequestForAllEventTypes() {
      int remoteEventCount = 0;
      for (Map.Entry<StringList<AbstractCDIEventCallback<?>>> mapEntry : .entrySet()) {
        String eventType = mapEntry.getKey();
        if (!.contains(eventType)) {
          for (AbstractCDIEventCallback<?> callback : mapEntry.getValue()) {
            remoteEventCount++;
            MessageBuilder.createMessage()
                .toSubject(.)
                .command(.)
                .with(.eventType)
                .with(.callback.getQualifiers())
                .noErrorHandling().sendNowWith(ErraiBus.get());
          }
        }
      }
      .info("requested server to forward CDI events for " + remoteEventCount + " existing observers");
    }
  }
  public static void consumeEventFromMessage(final Message message) {
    final String beanType = message.get(String.class.);
    _fireEvent(beanTypemessage);
    if (.containsKey(beanType)) {
      for (final String superType : .get(beanType)) {
        _fireEvent(superTypemessage);
      }
    }
  }
  private static void _fireEvent(final String beanTypefinal Message message) {
    if (.containsKey(beanType)) {
      for (final MessageCallback callback : new ArrayList<MessageCallback>(.get(beanType))) {
        fireIfNotFired(callbackmessage);
      }
    }
  }
  @SuppressWarnings("unchecked")
  private static void fireIfNotFired(final MessageCallback callbackfinal Message message) {
    }
    if (!message.getResource(Map.class).containsKey(callback)) {
      callback.callback(message);
      message.getResource(Map.class).put(callback"");
    }
  }
  public static void addRemoteEventType(final String remoteEvent) {
    .add(remoteEvent);
    if () {
      fireIfWaiting(remoteEvent);
    }
  }
  private static void fireIfWaiting(final String remoteEvent) {
    if (.containsKey(remoteEvent)) {
      for (final MessageFireDeferral runnable : .get(remoteEvent)) {
        runnable.send();
      }
      .remove(remoteEvent);
    }
  }
  private static void fireAllIfWaiting() {
    for (final String svc : new HashSet<String>(.keySet())) {
      fireIfWaiting(svc);
    }
  }
  public static void addRemoteEventTypes(final String[] remoteEvent) {
    for (final String s : remoteEvent) {
      addRemoteEventType(s);
    }
  }
  public static void addPostInitTask(final Runnable runnable) {
    InitVotes.registerOneTimeDependencyCallback(CDI.classrunnable);
  }
  private static void fireOnSubscribe(final String typefinal Message message) {
    if (MarshallerFramework.canMarshall(type)) {
      final MessageFireDeferral deferral = new MessageFireDeferral(System.currentTimeMillis(), message);
      if (.contains(type)) {
        ErraiBus.get().send(message);
        return;
      }
      List<MessageFireDeferralrunnables = .get(type);
      if (runnables == null) {
        .put(typerunnables = new ArrayList<MessageFireDeferral>());
      }
      runnables.add(deferral);
    }
  }
  public static void activate(final String... remoteTypes) {
    if (!) {
      addRemoteEventTypes(remoteTypes);
       = true;
      fireAllIfWaiting();
      .info("activated CDI eventing subsystem.");
      InitVotes.voteFor(CDI.class);
    }
  }
  static class MessageFireDeferral {
    final Message message;
    final long time;
    MessageFireDeferral(final long timefinal Message message) {
      this. = time;
      this. = message;
    }
    public Message getMessage() {
      return ;
    }
    public long getTime() {
      return ;
    }
    public void send() {
      ErraiBus.get().send();
    }
  }
  private static boolean isRemoteCommunicationEnabled() {
    return BusToolsCli.isRemoteCommunicationEnabled();
  }
New to GrepCode? Check out our FAQ X