/* (non-Javadoc)
   * @see org.jboss.netty.channel.SimpleChannelDownstreamHandler#writeRequested(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent)
   */
  public synchronized void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
      throws Exception {
    Object msg = e.getMessage();
    if (msg instanceof FlushRequestMessage) {
      hOut.flush(e.getFuture());
      e.getFuture().await(5000);
      return;
    }

    try {
      //				if (e.getMessage() instanceof Integer)
      //				{
      //					hOut.flush();
      //					return;
      //				}
      HessianRPCReplyMessage message = (HessianRPCReplyMessage) e.getMessage();
      // Constants.ahessianLogger.warn("encode reply for
      // #"+message.getHeaders().get(Constants.CALL_ID_STRING));

      hOut.resetReferences();
      hOut.writeReply(message);
      // hOut.flush();
      // e.getFuture().setSuccess();
    } catch (Exception ex) {
      Constants.ahessianLogger.warn("", ex);
      e.getFuture().setFailure(ex);
    }
  }
Exemple #2
0
  private static void cleanUpWriteBuffer(NioSocketChannel channel) {
    Exception cause = null;
    boolean fireExceptionCaught = false;

    // Clean up the stale messages in the write buffer.
    synchronized (channel.writeLock) {
      MessageEvent evt = channel.currentWriteEvent;
      if (evt != null) {
        channel.currentWriteEvent = null;
        channel.currentWriteIndex = 0;

        // Create the exception only once to avoid the excessive overhead
        // caused by fillStackTrace.
        if (channel.isOpen()) {
          cause = new NotYetConnectedException();
        } else {
          cause = new ClosedChannelException();
        }
        evt.getFuture().setFailure(cause);
        fireExceptionCaught = true;
      }

      Queue<MessageEvent> writeBuffer = channel.writeBuffer;
      if (!writeBuffer.isEmpty()) {
        // Create the exception only once to avoid the excessive overhead
        // caused by fillStackTrace.
        if (cause == null) {
          if (channel.isOpen()) {
            cause = new NotYetConnectedException();
          } else {
            cause = new ClosedChannelException();
          }
        }

        for (; ; ) {
          evt = writeBuffer.poll();
          if (evt == null) {
            break;
          }
          evt.getFuture().setFailure(cause);
          fireExceptionCaught = true;
        }
      }
    }

    if (fireExceptionCaught) {
      fireExceptionCaught(channel, cause);
    }
  }
  @Override
  public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    UnixTime time = (UnixTime) e.getMessage();

    ChannelBuffer buf = buffer(4);
    buf.writeInt(time.getValue());

    Channels.write(ctx, e.getFuture(), buf);
  }
  @Override
  public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) {

    // logger.info("Mongo message encoding...");

    Message message = (Message) e.getMessage();

    ChannelBuffer buf = message.encode(null);

    Channels.write(ctx, e.getFuture(), buf);
  }
  @Override
  public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    logger.info("server writeRequested start.");

    if (e.getMessage() instanceof Message) {
      Message msg = (Message) e.getMessage();
      ChannelBuffer totalBuffer = CodecUtil.encodeMessage(msg);
      Channels.write(ctx, e.getFuture(), totalBuffer);

    } else {
      logger.info("Channel message is not instance of Message");
    }

    logger.info("server writeRequested end.");
  }
Exemple #6
0
 static MessageEvent consolidateComposite(MessageEvent e) {
   // Convert a composite buffer into a simple buffer to save memory
   // bandwidth on full write buffer.
   // This method should be eliminated once gathering write works.
   Object m = e.getMessage();
   if (m instanceof CompositeChannelBuffer) {
     e =
         new DownstreamMessageEvent(
             e.getChannel(),
             e.getFuture(),
             ((CompositeChannelBuffer) m).copy(),
             e.getRemoteAddress());
   }
   return e;
 }
Exemple #7
0
    @Override
    public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) {
      PaxosMessage msg;
      ChannelBuffer sendBuf;
      byte[] data;

      msg = (PaxosMessage) e.getMessage(); // The original message.

      // Serialize the message.
      data = msg.serialize();
      sendBuf = ChannelBuffers.buffer(data.length);
      sendBuf.writeBytes(data); // Write the actual msg.

      // Send the message upstream.
      Channels.write(ctx, e.getFuture(), sendBuf);
    }
  /* (non-Javadoc)
   * @see org.jboss.netty.channel.SimpleChannelHandler#writeRequested(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent)
   */
  @Override
  public void writeRequested(final ChannelHandlerContext context, final MessageEvent e)
      throws Exception {

    // extract the string from the message event
    final Object message = e.getMessage();
    if (!(message instanceof String)) {
      context.sendDownstream(e);
      return;
    }
    String string = (String) message;

    // encode the string into a buffer
    ByteOrder byteOrder = context.getChannel().getConfig().getBufferFactory().getDefaultOrder();
    ChannelBuffer buffer = copiedBuffer(byteOrder, string, Charset.forName("utf-8"));

    // send the buffer downstream
    Channels.write(context, e.getFuture(), buffer, e.getRemoteAddress());
  }
  @Override
  public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
    if (!(evt instanceof MessageEvent)) {
      ctx.sendDownstream(evt);
      return;
    }

    MessageEvent e = (MessageEvent) evt;
    Object originalMessage = e.getMessage();

    if (originalMessage instanceof ChannelBuffer) {
      // 对于ChannelBuffer不尝试编码
      ctx.sendDownstream(evt);
    } else {
      ChannelBuffer encodedMessage = encode(ctx, e.getChannel(), originalMessage);
      if (encodedMessage != null) {
        Channels.write(ctx, e.getFuture(), encodedMessage, e.getRemoteAddress());
      }
    }
  }
Exemple #10
0
 @Override
 public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent e) {
   Channels.write(ctx, e.getFuture(), encode((RtmpMessage) e.getMessage()));
 }
  @Override
  public void outgoingMessage(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
    if (event.getMessage() instanceof MappingHttpResponse) {
      MappingHttpResponse httpResponse = (MappingHttpResponse) event.getMessage();
      BaseMessage msg = (BaseMessage) httpResponse.getMessage();

      // Ordering if-else conditions from most to least restrictive i.e. narrow to broad filters
      if (msg instanceof PostObjectResponseType) {
        PostObjectResponseType postObjectResponse = (PostObjectResponseType) msg;
        String redirectUrl = postObjectResponse.getRedirectUrl();
        if (redirectUrl != null) {
          httpResponse.addHeader(HttpHeaders.Names.LOCATION, redirectUrl);
          httpResponse.setStatus(HttpResponseStatus.SEE_OTHER);
          httpResponse.setMessage(null);
        } else {
          Integer successCode = postObjectResponse.getSuccessCode();
          if (successCode != null) {
            if (successCode != 201) {
              httpResponse.setMessage(null);
              httpResponse.setStatus(new HttpResponseStatus(successCode, "OK"));
            } else {
              httpResponse.setStatus(new HttpResponseStatus(successCode, "Created"));
            }
          }
        }
        // have to force a close for browsers
        event.getFuture().addListener(ChannelFutureListener.CLOSE);
      } else if (msg instanceof CopyObjectResponseType) {
        CopyObjectResponseType copyResponse = (CopyObjectResponseType) msg;
        if (copyResponse.getVersionId() != null)
          httpResponse.addHeader("x-amz-version-id", copyResponse.getVersionId());
        if (copyResponse.getCopySourceVersionId() != null)
          httpResponse.addHeader(
              "x-amz-copy-source-version-id", copyResponse.getCopySourceVersionId());
      } else if (msg instanceof CreateBucketResponseType) {
        httpResponse.setStatus(HttpResponseStatus.OK);
        removeResponseBody(msg, httpResponse);
        event.getFuture().addListener(ChannelFutureListener.CLOSE);
      } else if (msg
          instanceof ObjectStorageDataResponseType) { // Filter for GETs and PUTs related to data
        ObjectStorageDataResponseType response = (ObjectStorageDataResponseType) msg;
        if (response.getEtag() != null) {
          httpResponse.setHeader(HttpHeaders.Names.ETAG, '\"' + response.getEtag() + '\"');
        }
        if (response.getVersionId() != null) {
          httpResponse.setHeader(ObjectStorageProperties.X_AMZ_VERSION_ID, response.getVersionId());
        }
        if (msg instanceof ObjectStorageDataGetResponseType && response.getLastModified() != null) {
          httpResponse.setHeader(
              HttpHeaders.Names.LAST_MODIFIED,
              DateFormatter.dateToHeaderFormattedString(response.getLastModified()));
        }
        // Remove the content in response for certain operations
        if (msg instanceof PutObjectResponseType || msg instanceof UploadPartResponseType) {
          removeResponseBody(msg, httpResponse);
        }
      } else if (msg
          instanceof ObjectStorageResponseType) { // Filter for GETs and PUTs *NOT* related to data
        // Remove the content in response for certain operations
        if (msg instanceof SetBucketAccessControlPolicyResponseType
            || msg instanceof SetBucketLifecycleResponseType
            || msg instanceof SetBucketLoggingStatusResponseType
            || msg instanceof SetBucketVersioningStatusResponseType
            || msg instanceof SetObjectAccessControlPolicyResponseType
            || msg instanceof SetBucketTaggingResponseType) {
          if (msg instanceof SetObjectAccessControlPolicyResponseType
              && ((SetObjectAccessControlPolicyResponseType) msg).getVersionId() != null) {
            httpResponse.setHeader(
                ObjectStorageProperties.X_AMZ_VERSION_ID,
                ((SetObjectAccessControlPolicyResponseType) msg).getVersionId());
          }

          // Moved the below logic to the actual operation in ObjectStorageGateway.java.
          /*// AWS returns in a 204, rather than a 200 like other requests for SetBucketTaggingResponseType
          if ( msg instanceof SetBucketTaggingResponseType ) {
          	httpResponse.setStatus( HttpResponseStatus.NO_CONTENT );
          }*/
          removeResponseBody(msg, httpResponse);
        }
      }
    }
  }
Exemple #12
0
  private static void writeNow(NioSocketChannel channel, int writeSpinCount) {

    boolean open = true;
    boolean addOpWrite = false;
    boolean removeOpWrite = false;

    MessageEvent evt;
    ChannelBuffer buf;
    int bufIdx;
    int writtenBytes = 0;

    Queue<MessageEvent> writeBuffer = channel.writeBuffer;
    synchronized (channel.writeLock) {
      channel.inWriteNowLoop = true;
      evt = channel.currentWriteEvent;
      for (; ; ) {
        if (evt == null) {
          evt = writeBuffer.poll();
          if (evt == null) {
            channel.currentWriteEvent = null;
            removeOpWrite = true;
            break;
          }

          evt = consolidateComposite(evt);
          buf = (ChannelBuffer) evt.getMessage();
          bufIdx = buf.readerIndex();
        } else {
          buf = (ChannelBuffer) evt.getMessage();
          bufIdx = channel.currentWriteIndex;
        }

        try {
          for (int i = writeSpinCount; i > 0; i--) {
            int localWrittenBytes =
                buf.getBytes(bufIdx, channel.socket, buf.writerIndex() - bufIdx);

            if (localWrittenBytes != 0) {
              bufIdx += localWrittenBytes;
              writtenBytes += localWrittenBytes;
              break;
            }
          }

          if (bufIdx == buf.writerIndex()) {
            // Successful write - proceed to the next message.
            channel.currentWriteEvent = null;
            evt.getFuture().setSuccess();
            evt = null;
          } else {
            // Not written fully - perhaps the kernel buffer is full.
            channel.currentWriteEvent = evt;
            channel.currentWriteIndex = bufIdx;
            addOpWrite = true;
            break;
          }
        } catch (AsynchronousCloseException e) {
          // Doesn't need a user attention - ignore.
          channel.currentWriteEvent = evt;
          channel.currentWriteIndex = bufIdx;
        } catch (Throwable t) {
          channel.currentWriteEvent = null;
          evt.getFuture().setFailure(t);
          evt = null;
          fireExceptionCaught(channel, t);
          if (t instanceof IOException) {
            open = false;
            close(channel, succeededFuture(channel));
          }
        }
      }
      channel.inWriteNowLoop = false;
    }

    fireWriteComplete(channel, writtenBytes);

    if (open) {
      if (addOpWrite) {
        setOpWrite(channel);
      } else if (removeOpWrite) {
        clearOpWrite(channel);
      }
    }
  }