Пример #1
0
  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;
  }
Пример #2
0
  public void start() throws Exception {
    log.info("Starting Gravity...");
    synchronized (this) {
      if (!started) {
        adapterFactory = new AdapterFactory(this);
        internalStart();
        serverChannel = new ServerChannel(this, ServerChannel.class.getName(), null, null);

        if (gravityConfig.isUseUdp()) {
          ServiceLoader<UdpReceiverFactory> loader = ServiceLoader.load(UdpReceiverFactory.class);
          Iterator<UdpReceiverFactory> factories = loader.iterator();
          if (factories.hasNext()) {
            udpReceiverFactory = factories.next();
            udpReceiverFactory.setPort(gravityConfig.getUdpPort());
            udpReceiverFactory.setNio(gravityConfig.isUdpNio());
            udpReceiverFactory.setConnected(gravityConfig.isUdpConnected());
            udpReceiverFactory.setSendBufferSize(gravityConfig.getUdpSendBufferSize());
            udpReceiverFactory.start();
          } else log.warn("UDP receiver factory not found");
        }

        started = true;
      }
    }
    log.info("Gravity successfully started.");
  }
Пример #3
0
 public void init(FilterConfig config) throws ServletException {
   String dumpDirString = ServletParams.get(config, DUMP_DIR, String.class, null);
   if (dumpDirString != null) {
     File dumpDir = new File(dumpDirString);
     if (!dumpDir.exists() || !dumpDir.isDirectory() || !dumpDir.canWrite())
       log.warn("Ignoring dump directory (is it a writable directory?): %s", dumpDir);
     else this.dumpDir = dumpDir;
   }
 }
  /* (non-Javadoc)
   * @see org.granite.tide.ejb.EJBServiceContextIntf#postCall(org.granite.messaging.service.ServiceInvocationContext, java.lang.Object, java.lang.String)
   */
  @Override
  public IInvocationResult postCall(
      ServiceInvocationContext context,
      Object result,
      String componentName,
      Class<?> componentClass) {
    try {
      AbstractContext threadContext = AbstractContext.instance();

      List<ContextUpdate> results = new ArrayList<ContextUpdate>(threadContext.size());
      DataContext dataContext = DataContext.get();
      Set<Object[]> dataUpdates = dataContext != null ? dataContext.getDataUpdates() : null;
      Object[][] updates = null;
      if (dataUpdates != null && !dataUpdates.isEmpty())
        updates = dataUpdates.toArray(new Object[dataUpdates.size()][]);

      for (Map.Entry<String, Object> entry : threadContext.entrySet())
        results.add(new ContextUpdate(entry.getKey(), null, entry.getValue(), 3, false));

      InvocationResult ires = new InvocationResult(result, results);
      if (context.getBean() != null) {
        if (context.getBean().getClass().isAnnotationPresent(BypassTideMerge.class))
          ires.setMerge(false);
        else {
          try {
            Method m =
                context
                    .getBean()
                    .getClass()
                    .getMethod(
                        context.getMethod().getName(), context.getMethod().getParameterTypes());
            if (m.isAnnotationPresent(BypassTideMerge.class)) ires.setMerge(false);
          } catch (Exception e) {
            log.warn("Could not find bean method", e);
          }
        }
      }

      ires.setUpdates(updates);
      ires.setEvents(new ArrayList<ContextEvent>(threadContext.getRemoteEvents()));

      if (componentName != null) {
        EjbComponent component = ejbLookupCache.get(componentName);
        if (component != null
            && component.ejbMetadata != null
            && component.ejbMetadata.isStateful()
            && component.ejbMetadata.isRemoveMethod(context.getMethod()))
          ejbLookupCache.remove(componentName);
      }

      return ires;
    } finally {
      AbstractContext.remove();
    }
  }
Пример #5
0
  protected void createUdpReceiver(UdpReceiverFactory factory, AsyncHttpContext asyncHttpContext) {
    OutputStream os = null;
    try {
      Message connectMessage = asyncHttpContext.getConnectMessage();

      if (udpReceiver == null || udpReceiver.isClosed())
        udpReceiver = factory.newReceiver(this, asyncHttpContext.getRequest(), connectMessage);

      AsyncMessage reply = udpReceiver.acknowledge(connectMessage);

      HttpServletRequest request = asyncHttpContext.getRequest();
      HttpServletResponse response = asyncHttpContext.getResponse();

      GraniteContext context =
          HttpGraniteContext.createThreadIntance(
              gravity.getGraniteConfig(), gravity.getServicesConfig(), null, request, response);
      ((AMFContextImpl) context.getAMFContext())
          .setCurrentAmf3Message(asyncHttpContext.getConnectMessage());

      GravityServletUtil.serialize(
          gravity,
          response,
          new AsyncMessage[] {reply},
          ContentType.forMimeType(request.getContentType()));
    } catch (ServletException e) {
      log.error(e, "Could not send UDP connect acknowledgement to channel: %s", this);
    } catch (IOException e) {
      log.error(e, "Could not send UDP connect acknowledgement to channel: %s", this);
    } finally {
      try {
        GraniteContext.release();
      } catch (Exception e) {
        // should never happen...
      }

      // Close output stream.
      try {
        if (os != null) {
          try {
            os.close();
          } catch (IOException e) {
            log.warn(e, "Could not close output stream (ignored)");
          }
        }
      } finally {
        releaseAsyncHttpContext(asyncHttpContext);
      }
    }
  }
  protected List<ExtendedObjectCodec> loadExtendedObjectCodecs(ServletContext servletContext) {
    String extendedObjectCodecsParam =
        servletContext.getInitParameter(EXTENDED_OBJECT_CODECS_PARAM);

    if (extendedObjectCodecsParam == null) return detectExtendedObjectCodecs();

    ClassLoader classLoader = getClass().getClassLoader();

    List<ExtendedObjectCodec> extendedObjectCodecs = new ArrayList<ExtendedObjectCodec>();
    for (String className : extendedObjectCodecsParam.trim().split("\\s*\\,\\s*")) {
      if (className.length() == 0) continue;

      log.info("Loading JMF extended object codec: %s", className);
      try {
        @SuppressWarnings("unchecked")
        Class<? extends ExtendedObjectCodec> cls =
            (Class<? extends ExtendedObjectCodec>) classLoader.loadClass(className);
        extendedObjectCodecs.add(cls.getDeclaredConstructor().newInstance());
      } catch (Throwable t) {
        log.warn(t, "Could not load JMF codec: %s", className);
      }
    }
    return extendedObjectCodecs;
  }
Пример #7
0
  public boolean runReceived(AsyncHttpContext asyncHttpContext) {

    GravityInternal gravity = getGravity();

    if (asyncHttpContext != null && gravity.hasUdpReceiverFactory()) {
      UdpReceiverFactory factory = gravity.getUdpReceiverFactory();

      if (factory.isUdpConnectRequest(asyncHttpContext.getConnectMessage())) {
        createUdpReceiver(factory, asyncHttpContext);
        return true;
      }

      if (udpReceiver != null) {
        if (!udpReceiver.isClosed()) udpReceiver.close(false);
        udpReceiver = null;
      }
    }

    boolean httpAsParam = (asyncHttpContext != null);
    LinkedList<AsyncMessage> messages = null;
    OutputStream os = null;

    try {
      receivedQueueLock.lock();
      try {
        // Do we have any pending messages?
        if (receivedQueue.isEmpty()) return false;

        // Do we have a valid http context?
        if (asyncHttpContext == null) {
          asyncHttpContext = acquireAsyncHttpContext();
          if (asyncHttpContext == null) return false;
        }

        // Both conditions are ok, get all pending messages.
        messages = receivedQueue;
        receivedQueue = new LinkedList<AsyncMessage>();
      } finally {
        receivedQueueLock.unlock();
      }

      HttpServletRequest request = asyncHttpContext.getRequest();
      HttpServletResponse response = asyncHttpContext.getResponse();

      // Set response messages correlation ids to connect request message id.
      String correlationId = asyncHttpContext.getConnectMessage().getMessageId();
      AsyncMessage[] messagesArray = new AsyncMessage[messages.size()];
      int i = 0;
      for (AsyncMessage message : messages) {
        message.setCorrelationId(correlationId);
        messagesArray[i++] = message;
      }

      // Setup serialization context (thread local)
      GraniteContext context =
          HttpGraniteContext.createThreadIntance(
              gravity.getGraniteConfig(), gravity.getServicesConfig(), null, request, response);
      ((AMFContextImpl) context.getAMFContext())
          .setCurrentAmf3Message(asyncHttpContext.getConnectMessage());

      // Write messages to response output stream.
      GravityServletUtil.serialize(
          gravity, response, messagesArray, ContentType.forMimeType(request.getContentType()));

      return true; // Messages were delivered, http context isn't valid anymore.
    } catch (ServletException e) {
      log.error(e, "Configuration error for channel: %s", getId());

      return true;
    } catch (IOException e) {
      log.warn(e, "Could not send messages to channel: %s (retrying later)", getId());

      GravityConfig gravityConfig = getGravity().getGravityConfig();
      if (gravityConfig.isRetryOnError()) {
        receivedQueueLock.lock();
        try {
          if (receivedQueue.size() + messages.size()
              > gravityConfig.getMaxMessagesQueuedPerChannel()) {
            log.warn(
                "Channel %s has reached its maximum queue capacity %s (throwing %s messages)",
                getId(), gravityConfig.getMaxMessagesQueuedPerChannel(), messages.size());
          } else receivedQueue.addAll(0, messages);
        } finally {
          receivedQueueLock.unlock();
        }
      }

      return true; // Messages weren't delivered, but http context isn't valid anymore.
    } finally {
      // Cleanup serialization context (thread local)
      try {
        GraniteContext.release();
      } catch (Exception e) {
        // should never happen...
      }

      // Close output stream.
      try {
        if (os != null) {
          try {
            os.close();
          } catch (IOException e) {
            log.warn(e, "Could not close output stream (ignored)");
          }
        }
      } finally {
        // Cleanup http context (only if this method wasn't explicitly called with a non null
        // AsyncHttpContext from the servlet).
        if (!httpAsParam) releaseAsyncHttpContext(asyncHttpContext);
      }
    }
  }
  /* (non-Javadoc)
   * @see org.granite.tide.ejb.EJBServiceContextIntf#findComponent(java.lang.String)
   */
  @Override
  public Object findComponent(String componentName, Class<?> componentClass) {
    if ("identity".equals(componentName)) return identity;

    EjbComponent component = ejbLookupCache.get(componentName);
    if (component != null) return component.ejbInstance;

    // Compute EJB JNDI binding.
    String name = componentName;
    if (lookup != null) {
      name = lookup;
      if (lookup.contains(CAPITALIZED_DESTINATION_ID))
        name = lookup.replace(CAPITALIZED_DESTINATION_ID, capitalize(componentName));
      if (lookup.contains(DESTINATION_ID)) name = lookup.replace(DESTINATION_ID, componentName);
    }

    InitialContext ic = null;
    try {
      ic = new InitialContext();
    } catch (Exception e) {
      throw new ServiceException("Could not get InitialContext", e);
    }

    log.debug(">> New EjbServiceInvoker looking up: %s", name);

    try {
      component = new EjbComponent();
      component.ejbInstance = ic.lookup(name);
      component.ejbClasses = new HashSet<Class<?>>();
      Class<?> scannedClass = null;
      EjbScannedItemHandler itemHandler = EjbScannedItemHandler.instance();
      for (Class<?> i : component.ejbInstance.getClass().getInterfaces()) {
        if (itemHandler.getScannedClasses().containsKey(i)) {
          scannedClass = itemHandler.getScannedClasses().get(i);
          break;
        }
      }
      if (scannedClass == null)
        scannedClass = itemHandler.getScannedClasses().get(component.ejbInstance.getClass());
      // GDS-768: handle of proxied no-interface EJBs in GlassFish v3
      if (scannedClass == null && component.ejbInstance.getClass().getSuperclass() != null)
        scannedClass =
            itemHandler.getScannedClasses().get(component.ejbInstance.getClass().getSuperclass());

      if (scannedClass != null) {
        component.ejbClasses.add(scannedClass);
        for (Map.Entry<Class<?>, Class<?>> me : itemHandler.getScannedClasses().entrySet()) {
          if (me.getValue().equals(scannedClass)) component.ejbClasses.add(me.getKey());
        }
        component.ejbMetadata =
            new EjbServiceMetadata(scannedClass, component.ejbInstance.getClass());
      } else
        log.warn(
            "Ejb "
                + componentName
                + " was not scanned: remove method will not be called if it is a Stateful bean. Add META-INF/services-config.properties if needed.");

      ejbLookupCache.put(componentName, component);

      return component.ejbInstance;
    } catch (NamingException e) {
      log.error("EJB not found " + name + ": " + e.getMessage());
      throw new ServiceException("Could not lookup for: " + name, e);
    }
  }
Пример #9
0
  public GraniteConfig(
      String stdConfig,
      InputStream customConfigIs,
      Configuration configuration,
      String MBeanContextName)
      throws IOException, SAXException {
    try {
      amf3SerializerConstructor =
          TypeUtil.getConstructor(AMF3Serializer.class, new Class<?>[] {OutputStream.class});
      amf3DeserializerConstructor =
          TypeUtil.getConstructor(AMF3Deserializer.class, new Class<?>[] {InputStream.class});
    } catch (Exception e) {
      throw new GraniteConfigException("Could not get constructor for AMF3 (de)serializers", e);
    }

    this.MBeanContextName = MBeanContextName;

    ClassLoader loader = GraniteConfig.class.getClassLoader();

    final ByteArrayInputStream dtd =
        StreamUtil.getResourceAsStream("org/granite/config/granite-config.dtd", loader);
    final EntityResolver resolver =
        new EntityResolver() {
          public InputSource resolveEntity(String publicId, String systemId)
              throws SAXException, IOException {
            if (GRANITE_CONFIG_PUBLIC_ID.equals(publicId)) {
              dtd.reset();
              InputSource source = new InputSource(dtd);
              source.setPublicId(publicId);
              return source;
            }
            return null;
          }
        };

    // Load standard config.
    InputStream is = null;
    try {
      is = StreamUtil.getResourceAsStream("org/granite/config/granite-config.xml", loader);
      XMap doc = new XMap(is, resolver);
      forElement(doc, false, null);
    } finally {
      if (is != null) is.close();
    }

    if (stdConfig != null) {
      try {
        is = StreamUtil.getResourceAsStream(stdConfig, loader);
        XMap doc = new XMap(is, resolver);
        forElement(doc, false, null);
      } finally {
        if (is != null) is.close();
      }
    }

    // Load custom config (override).
    if (customConfigIs != null) {
      XMap doc = new XMap(customConfigIs, resolver);
      forElement(
          doc, true, configuration != null ? configuration.getGraniteConfigProperties() : null);
    }

    if (amf3DeserializerSecurizer == null)
      log.warn(
          "You should configure a deserializer securizer in your granite-config.xml file in order to prevent potential security exploits!");
  }
Пример #10
0
  public boolean runReceived(AsyncHttpContext asyncHttpContext) {

    boolean httpAsParam = (asyncHttpContext != null);
    LinkedList<AsyncMessage> messages = null;
    OutputStream os = null;

    try {
      receivedQueueLock.lock();
      try {
        // Do we have any pending messages?
        if (receivedQueue.isEmpty()) return false;

        // Do we have a valid http context?
        if (asyncHttpContext == null) {
          asyncHttpContext = acquireAsyncHttpContext();
          if (asyncHttpContext == null) return false;
        }

        // Both conditions are ok, get all pending messages.
        messages = receivedQueue;
        receivedQueue = new LinkedList<AsyncMessage>();
      } finally {
        receivedQueueLock.unlock();
      }

      HttpServletRequest request = asyncHttpContext.getRequest();
      HttpServletResponse response = asyncHttpContext.getResponse();

      // Set response messages correlation ids to connect request message id.
      String correlationId = asyncHttpContext.getConnectMessage().getMessageId();
      AsyncMessage[] messagesArray = new AsyncMessage[messages.size()];
      int i = 0;
      for (AsyncMessage message : messages) {
        message.setCorrelationId(correlationId);
        messagesArray[i++] = message;
      }

      // Setup serialization context (thread local)
      Gravity gravity = getGravity();
      GraniteContext context =
          HttpGraniteContext.createThreadIntance(
              gravity.getGraniteConfig(), gravity.getServicesConfig(), null, request, response);
      ((AMFContextImpl) context.getAMFContext())
          .setCurrentAmf3Message(asyncHttpContext.getConnectMessage());

      // Write messages to response output stream.

      response.setStatus(HttpServletResponse.SC_OK);
      response.setContentType(AMF0Message.CONTENT_TYPE);
      response.setDateHeader("Expire", 0L);
      response.setHeader("Cache-Control", "no-store");

      os = response.getOutputStream();
      ObjectOutput amf3Serializer = context.getGraniteConfig().newAMF3Serializer(os);

      log.debug("<< [MESSAGES for channel=%s] %s", this, messagesArray);

      amf3Serializer.writeObject(messagesArray);

      os.flush();
      response.flushBuffer();

      return true; // Messages were delivered, http context isn't valid anymore.
    } catch (IOException e) {
      log.warn(e, "Could not send messages to channel: %s (retrying later)", this);

      GravityConfig gravityConfig = getGravity().getGravityConfig();
      if (messages != null && gravityConfig.isRetryOnError()) {
        receivedQueueLock.lock();
        try {
          if (receivedQueue.size() + messages.size()
              > gravityConfig.getMaxMessagesQueuedPerChannel()) {
            log.warn(
                "Channel %s has reached its maximum queue capacity %s (throwing %s messages)",
                this, gravityConfig.getMaxMessagesQueuedPerChannel(), messages.size());
          } else receivedQueue.addAll(0, messages);
        } finally {
          receivedQueueLock.unlock();
        }
      }

      return true; // Messages weren't delivered, but http context isn't valid anymore.
    } finally {

      // Cleanup serialization context (thread local)
      try {
        GraniteContext.release();
      } catch (Exception e) {
        // should never happen...
      }

      // Close output stream.
      try {
        if (os != null) {
          try {
            os.close();
          } catch (IOException e) {
            log.warn(e, "Could not close output stream (ignored)");
          }
        }
      } finally {
        // Cleanup http context (only if this method wasn't explicitly called with a non null
        // AsyncHttpContext from the servlet).
        if (!httpAsParam) releaseAsyncHttpContext(asyncHttpContext);
      }
    }
  }