private Message handleSecurityMessage(CommandMessage message) {
    GraniteConfig config = GraniteContext.getCurrentInstance().getGraniteConfig();

    Message response = null;

    if (!config.hasSecurityService())
      log.warn(
          "Ignored security operation (no security settings in granite-config.xml): %s", message);
    else if (!config.getSecurityService().acceptsContext())
      log.info(
          "Ignored security operation (security service does not handle this kind of granite context)",
          message);
    else {
      SecurityService securityService = config.getSecurityService();
      try {
        if (message.isLoginOperation())
          securityService.login(
              message.getBody(), (String) message.getHeader(Message.CREDENTIALS_CHARSET_HEADER));
        else securityService.logout();
      } catch (Exception e) {
        if (e instanceof SecurityServiceException)
          log.debug(e, "Could not process security operation: %s", message);
        else log.error(e, "Could not process security operation: %s", message);
        response = new ErrorMessage(message, e, true);
      }
    }

    if (response == null) {
      response = new AcknowledgeMessage(message, true);
      // For SDK 2.0.1_Hotfix2.
      if (message.isSecurityOperation()) response.setBody("success");
    }

    return response;
  }
  private Message handlePublishMessage(
      final ChannelFactory<?> channelFactory, final AsyncMessage message, final Channel channel) {

    GraniteContext context = GraniteContext.getCurrentInstance();

    // Get and check destination.
    Destination destination =
        context
            .getServicesConfig()
            .findDestinationById(message.getClass().getName(), message.getDestination());

    if (destination == null) return getInvalidDestinationError(message);

    if (message.getMessageId() == null) message.setMessageId(UUIDUtil.randomUUID());
    message.setTimestamp(System.currentTimeMillis());
    if (channel != null) message.setClientId(channel.getId());

    GravityInvocationContext invocationContext =
        new GravityInvocationContext(message, destination) {
          @Override
          public Object invoke() throws Exception {
            // Publish...
            Channel fromChannel = channel;
            if (fromChannel == null)
              fromChannel = getChannel(channelFactory, (String) message.getClientId());
            if (fromChannel == null) return handleUnknownClientMessage(message);

            ServiceAdapter adapter = adapterFactory.getServiceAdapter(message);

            AsyncMessage reply = (AsyncMessage) adapter.invoke(fromChannel, message);

            reply.setDestination(message.getDestination());
            reply.setClientId(fromChannel.getId());

            return reply;
          }
        };

    // Check security 1 (destination).
    if (destination.getSecurizer() instanceof GravityDestinationSecurizer) {
      try {
        ((GravityDestinationSecurizer) destination.getSecurizer()).canPublish(invocationContext);
      } catch (Exception e) {
        return new ErrorMessage(message, e, true);
      }
    }

    // Check security 2 (security service).
    GraniteConfig config = context.getGraniteConfig();
    try {
      if (config.hasSecurityService() && config.getSecurityService().acceptsContext())
        return (Message) config.getSecurityService().authorize(invocationContext);

      return (Message) invocationContext.invoke();
    } catch (Exception e) {
      return new ErrorMessage(message, e, true);
    }
  }
 protected JavaClassDescriptor(Class<?> type) {
   GraniteConfig config = GraniteContext.getCurrentInstance().getGraniteConfig();
   this.type = type;
   this.name = getClassName(type);
   this.externalizer = config.getExternalizer(type.getName());
   this.converters = config.getConverters();
   this.encoding = findEncoding(type);
   this.properties = introspectProperties();
 }
  protected void internalStart() {
    gravityPool = new GravityPool(gravityConfig);
    channelsTimer = new Timer();

    if (graniteConfig.isRegisterMBeans()) {
      try {
        ObjectName name =
            new ObjectName(
                "org.graniteds:type=Gravity,context=" + graniteConfig.getMBeanContextName());
        log.info("Registering MBean: %s", name);
        OpenMBean mBean = OpenMBean.createMBean(this);
        MBeanServerLocator.getInstance().register(mBean, name, true);
      } catch (Exception e) {
        log.error(
            e,
            "Could not register Gravity MBean for context: %s",
            graniteConfig.getMBeanContextName());
      }
    }
  }
  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;
  }
  private Message handleUnsubscribeMessage(
      final ChannelFactory<?> channelFactory, CommandMessage message) {
    Channel channel = getChannel(channelFactory, (String) message.getClientId());
    if (channel == null) return handleUnknownClientMessage(message);

    AsyncMessage reply = null;

    ServiceAdapter adapter = adapterFactory.getServiceAdapter(message);

    reply = (AcknowledgeMessage) adapter.manage(channel, message);

    postManage(channel);

    if (!(reply instanceof ErrorMessage)) {
      // Remove subscription message in distributed data (clustering).
      try {
        DistributedData gdd = graniteConfig.getDistributedDataFactory().getInstance();
        if (gdd != null) {
          String subscriptionId =
              (String) message.getHeader(AsyncMessage.DESTINATION_CLIENT_ID_HEADER);
          log.debug(
              "Removing subscription message from channel info: %s - %s",
              channel.getId(), subscriptionId);
          gdd.removeSubcription(channel.getId(), subscriptionId);
        }
      } catch (Exception e) {
        log.error(
            e,
            "Could not remove subscription from distributed data: %s - %s",
            channel.getId(),
            message.getHeader(AsyncMessage.DESTINATION_CLIENT_ID_HEADER));
      }
    }

    reply.setDestination(message.getDestination());
    reply.setClientId(channel.getId());
    reply.getHeaders().putAll(message.getHeaders());

    return reply;
  }
  @SuppressWarnings("unchecked")
  public <C extends Channel> C getChannel(ChannelFactory<C> channelFactory, String clientId) {
    if (clientId == null) return null;

    TimeChannel<C> timeChannel = (TimeChannel<C>) channels.get(clientId);
    if (timeChannel == null) {
      // Look for existing channel id/subscriptions in distributed data (clustering).
      log.debug("Lookup channel %s in distributed data", clientId);
      try {
        DistributedData gdd = graniteConfig.getDistributedDataFactory().getInstance();
        if (gdd != null && gdd.hasChannelId(clientId)) {
          log.debug("Found channel id in distributed data: %s", clientId);
          String channelFactoryClassName = gdd.getChannelFactoryClassName(clientId);
          String clientType = gdd.getChannelClientType(clientId);
          channelFactory =
              (ChannelFactory<C>)
                  TypeUtil.newInstance(
                      channelFactoryClassName, new Class<?>[] {Gravity.class}, new Object[] {this});
          C channel = channelFactory.newChannel(clientId, clientType);
          timeChannel = new TimeChannel<C>(channel);
          if (channels.putIfAbsent(clientId, timeChannel) == null) {
            for (CommandMessage subscription : gdd.getSubscriptions(clientId)) {
              log.debug("Resubscribing channel: %s - %s", clientId, subscription);
              handleSubscribeMessage(channelFactory, subscription, false);
            }
            access(clientId);
          }
        }
      } catch (Exception e) {
        log.error(
            e, "Could not recreate channel/subscriptions from distributed data: %s", clientId);
      }
    }

    return (timeChannel != null ? timeChannel.getChannel() : null);
  }
  protected <C extends Channel> C createChannel(ChannelFactory<C> channelFactory, String clientId) {
    C channel = null;
    if (clientId != null) {
      channel = getChannel(channelFactory, clientId);
      if (channel != null) return channel;
    }

    String clientType = GraniteContext.getCurrentInstance().getClientType();
    channel = channelFactory.newChannel(UUIDUtil.randomUUID(), clientType);
    TimeChannel<C> timeChannel = new TimeChannel<C>(channel);
    for (int i = 0; channels.putIfAbsent(channel.getId(), timeChannel) != null; i++) {
      if (i >= 10)
        throw new RuntimeException("Could not find random new clientId after 10 iterations");
      channel.destroy(false);
      channel = channelFactory.newChannel(UUIDUtil.randomUUID(), clientType);
      timeChannel = new TimeChannel<C>(channel);
    }

    String channelId = channel.getId();

    // Save channel id in distributed data (clustering).
    try {
      DistributedData gdd = graniteConfig.getDistributedDataFactory().getInstance();
      if (gdd != null) {
        log.debug("Saving channel id in distributed data: %s", channelId);
        gdd.addChannelId(channelId, channelFactory.getClass().getName(), clientType);
      }
    } catch (Exception e) {
      log.error(e, "Could not add channel id in distributed data: %s", channelId);
    }

    // Initialize timer task.
    access(channelId);

    return channel;
  }
  private Message handleSubscribeMessage(
      final ChannelFactory<?> channelFactory,
      final CommandMessage message,
      final boolean saveMessageInSession) {

    final GraniteContext context = GraniteContext.getCurrentInstance();

    // Get and check destination.
    final Destination destination =
        context
            .getServicesConfig()
            .findDestinationById(message.getMessageRefType(), message.getDestination());

    if (destination == null) return getInvalidDestinationError(message);

    GravityInvocationContext invocationContext =
        new GravityInvocationContext(message, destination) {
          @Override
          public Object invoke() throws Exception {
            // Subscribe...
            Channel channel = getChannel(channelFactory, (String) message.getClientId());
            if (channel == null) return handleUnknownClientMessage(message);

            String subscriptionId =
                (String) message.getHeader(AsyncMessage.DESTINATION_CLIENT_ID_HEADER);
            if (subscriptionId == null) {
              subscriptionId = UUIDUtil.randomUUID();
              message.setHeader(AsyncMessage.DESTINATION_CLIENT_ID_HEADER, subscriptionId);
            }

            DistributedData gdd = graniteConfig.getDistributedDataFactory().getInstance();
            if (gdd != null) {
              if (!gdd.hasChannelId(channel.getId())) {
                gdd.addChannelId(
                    channel.getId(),
                    channel.getFactory().getClass().getName(),
                    context.getClientType());
                log.debug("Stored channel %s in distributed data", channel.getId());
              }

              if (Boolean.TRUE
                  .toString()
                  .equals(destination.getProperties().get("session-selector"))) {
                String selector = gdd.getDestinationSelector(destination.getId());
                log.debug("Session selector found: %s", selector);
                if (selector != null) message.setHeader(CommandMessage.SELECTOR_HEADER, selector);
              }
            }

            ServiceAdapter adapter = adapterFactory.getServiceAdapter(message);

            AsyncMessage reply = (AsyncMessage) adapter.manage(channel, message);

            postManage(channel);

            if (saveMessageInSession && !(reply instanceof ErrorMessage)) {
              // Save subscription message in distributed data (clustering).
              try {
                if (gdd != null) {
                  log.debug(
                      "Saving new subscription message for channel: %s - %s",
                      channel.getId(), message);
                  gdd.addSubcription(channel.getId(), message);
                }
              } catch (Exception e) {
                log.error(
                    e,
                    "Could not add subscription in distributed data: %s - %s",
                    channel.getId(),
                    subscriptionId);
              }
            }

            reply.setDestination(message.getDestination());
            reply.setClientId(channel.getId());
            reply.getHeaders().putAll(message.getHeaders());

            if (gdd != null && message.getDestination() != null) {
              gdd.setDestinationClientId(message.getDestination(), channel.getId());
              gdd.setDestinationSubscriptionId(message.getDestination(), subscriptionId);
            }

            return reply;
          }
        };

    // Check security 1 (destination).
    if (destination.getSecurizer() instanceof GravityDestinationSecurizer) {
      try {
        ((GravityDestinationSecurizer) destination.getSecurizer()).canSubscribe(invocationContext);
      } catch (Exception e) {
        return new ErrorMessage(message, e);
      }
    }

    // Check security 2 (security service).
    GraniteConfig config = context.getGraniteConfig();
    try {
      if (config.hasSecurityService() && config.getSecurityService().acceptsContext())
        return (Message) config.getSecurityService().authorize(invocationContext);

      return (Message) invocationContext.invoke();
    } catch (Exception e) {
      return new ErrorMessage(message, e, true);
    }
  }