/**
   * Writes the specified TaskResult data to the channel output. Only the raw output data is written
   * and rest of the TaskResult fields are ignored
   *
   * @param ctx the ChannelHandlerContext
   * @param event the ChannelEvent
   * @throws Exception in case of any errors
   */
  private void writeCommandExecutionResponse(
      ChannelHandlerContext ctx, ChannelEvent event, HttpResponse response) throws Exception {
    // Don't write anything if the response is null
    if (response == null) {
      // write empty response
      event
          .getChannel()
          .write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT))
          .addListener(ChannelFutureListener.CLOSE);
      return;
    }
    org.jboss.netty.handler.codec.http.HttpResponse httpResponse =
        new DefaultHttpResponse(
            HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(response.getStatusLine().getStatusCode()));
    // write headers
    for (Header header : response.getAllHeaders()) {
      if (!RoutingHttpChannelHandler.REMOVE_HEADERS.contains(header.getName())) {
        httpResponse.setHeader(header.getName(), header.getValue());
      }
    }

    // write entity
    HttpEntity responseEntity = response.getEntity();
    byte[] responseData = EntityUtils.toByteArray(responseEntity);
    httpResponse.setContent(ChannelBuffers.copiedBuffer(responseData));
    // write response
    event.getChannel().write(httpResponse).addListener(ChannelFutureListener.CLOSE);
  }
Пример #2
0
  @Override
  public void log(ChannelEvent e) {
    StringBuilder sb = new StringBuilder();

    // System.out.println(e);
    if (e instanceof DownstreamMessageEvent) {
      DownstreamMessageEvent devm = (DownstreamMessageEvent) e;
      Object mes = devm.getMessage();
      sb.append('[');
      sb.append(e.getChannel().getId());
      sb.append(" >out> ");
      if (mes instanceof ChannelBuffer)
        encodeBuffer((ChannelBuffer) ((DownstreamMessageEvent) e).getMessage(), sb);
      else sb.append(mes.toString());
    } else if (e instanceof UpstreamMessageEvent) {
      sb.append(e.getChannel().getId());
      sb.append(" <in< ");
      Object message = ((UpstreamMessageEvent) e).getMessage();
      if (message instanceof ChannelBuffer)
        encodeBuffer((ChannelBuffer) ((UpstreamMessageEvent) e).getMessage(), sb);
    } else if (e instanceof ExceptionEvent) {
      sb.append(e.toString());
    } else sb.append(e.toString());

    Constants.ahessianLogger.info(sb.toString());
  }
Пример #3
0
  public void handleDownstream(final ChannelHandlerContext context, final ChannelEvent evt)
      throws Exception {
    if (evt instanceof ChannelStateEvent) {
      ChannelStateEvent e = (ChannelStateEvent) evt;
      switch (e.getState()) {
        case OPEN:
        case CONNECTED:
        case BOUND:
          if (Boolean.FALSE.equals(e.getValue()) || e.getValue() == null) {
            closeOutboundAndChannel(context, e);
            return;
          }
      }
    }
    if (!(evt instanceof MessageEvent)) {
      context.sendDownstream(evt);
      return;
    }

    MessageEvent e = (MessageEvent) evt;
    if (!(e.getMessage() instanceof ChannelBuffer)) {
      context.sendDownstream(evt);
      return;
    }

    // Do not encrypt the first write request if this handler is
    // created with startTLS flag turned on.
    if (startTls && sentFirstMessage.compareAndSet(false, true)) {
      context.sendDownstream(evt);
      return;
    }

    // Otherwise, all messages are encrypted.
    ChannelBuffer msg = (ChannelBuffer) e.getMessage();
    PendingWrite pendingWrite;

    if (msg.readable()) {
      pendingWrite =
          new PendingWrite(
              evt.getFuture(), msg.toByteBuffer(msg.readerIndex(), msg.readableBytes()));
    } else {
      pendingWrite = new PendingWrite(evt.getFuture(), null);
    }
    synchronized (pendingUnencryptedWrites) {
      boolean offered = pendingUnencryptedWrites.offer(pendingWrite);
      assert offered;
    }

    wrap(context, evt.getChannel());
  }
 /**
  * Interface method implementation. Reads and processes commands sent to the service proxy.
  * Expects data in the command protocol defined in the class summary. Discards commands that do
  * not have a {@link TaskHandler} mapping.
  *
  * @see
  *     org.jboss.netty.channel.SimpleChannelUpstreamHandler#handleUpstream(org.jboss.netty.channel.ChannelHandlerContext,
  *     org.jboss.netty.channel.ChannelEvent)
  */
 public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent event) throws Exception {
   if (MessageEvent.class.isAssignableFrom(event.getClass())) {
     CommandInterpreter commandInterpreter = new CommandInterpreter();
     CommandInterpreter.ProxyCommand readCommand =
         commandInterpreter.readCommand((MessageEvent) event);
     LOGGER.debug("Read Command : " + readCommand);
     String pool = readCommand.getCommandParams().get("pool");
     TaskHandlerExecutor executor;
     // Try to execute command using ThreadPool, if "pool" is found in the command, else the
     // command name
     if (pool != null) {
       executor = this.repository.get(readCommand.getCommand(), pool);
     } else {
       executor = this.repository.get(readCommand.getCommand(), readCommand.getCommand());
     }
     executor.setParams(readCommand.getCommandParams());
     executor.setData(readCommand.getCommandData());
     try {
       TaskResult result = executor.execute();
       LOGGER.debug("The output is: " + result);
       // write the results to the channel output
       commandInterpreter.writeCommandExecutionResponse(ctx, event, result);
     } catch (Exception e) {
       LOGGER.error("Error in executing command/fallBack : " + readCommand, e);
       throw new RuntimeException("Error in executing command : " + readCommand, e);
     }
   }
   super.handleUpstream(ctx, event);
 }
 @Override
 public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
   if (e instanceof ChannelStateEvent) {
     logger.info(e.toString());
   }
   super.handleUpstream(ctx, e);
 }
  @Before
  public void setup() throws Exception {
    host = "4.3.2.1";
    hostbytes = new byte[] {0x4, 0x3, 0x2, 0x1};
    port = 5646;
    jsonResponse = "{\"name\":\"name\",\"host\":\"" + host + "\",\"port\":" + port + "}";
    cmasBaseUrl = "http://test/";
    parser = new JSONParser();
    client = mock(Client.class);
    clientResponse = mock(ClientResponse.class);
    e = mock(ChannelEvent.class);
    channel = mock(Channel.class);
    remoteAddress = new InetSocketAddress(InetAddress.getByAddress(null, hostbytes), port);

    when(e.getChannel()).thenReturn(channel);
    when(channel.getRemoteAddress()).thenReturn(remoteAddress);

    webResource = mock(WebResource.class);
    builder = PowerMockito.mock(Builder.class);

    when(client.resource((String) any())).thenReturn(webResource);
    when(webResource.accept((String) any())).thenReturn(builder);
    PowerMockito.when(builder.post(ClientResponse.class)).thenReturn(clientResponse);
    when(clientResponse.getStatus()).thenReturn(200);
    when(clientResponse.getEntity(String.class)).thenReturn(jsonResponse);
  }
Пример #7
0
 @Override
 public void handleUpstream(final ChannelHandlerContext ctx, final ChannelEvent e)
     throws Exception {
   if (LOG.isDebugEnabled()) {
     LOG.debug(getPeerUuidLoggingString() + e.toString());
   }
   super.handleUpstream(ctx, e);
 }
Пример #8
0
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.jboss.netty.channel.ChannelUpstreamHandler#handleUpstream(org.jboss.netty.channel.ChannelHandlerContext,
  *     org.jboss.netty.channel.ChannelEvent)
  */
 @Override
 public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
   if (e instanceof MessageEvent) {
     MessageEvent me = (MessageEvent) e;
     if (me.getMessage() instanceof ChannelBuffer) {
       ChannelBuffer postDetectBuffer =
           protocolSwitch(ctx, e.getChannel(), (ChannelBuffer) me.getMessage(), e);
       if (postDetectBuffer != null) {
         ctx.getPipeline().remove(this);
         ctx.sendUpstream(
             new UpstreamMessageEvent(
                 e.getChannel(), postDetectBuffer, ((MessageEvent) e).getRemoteAddress()));
       }
     }
   } else {
     ctx.sendUpstream(e);
   }
 }
  @Test
  public void testResultParsing() throws Exception {
    CMASRestResolver resolver = new CMASRestResolver(cmasBaseUrl, parser, client);

    InetSocketAddress resultAddress = resolver.resolveTarget(e.getChannel());

    assertEquals(host, resultAddress.getHostName());
    assertEquals(port, resultAddress.getPort());
  }
  @Test
  public void testBaseUrlHandlingNoTrailingDelimiter() throws Exception {
    cmasBaseUrl = "http://test";
    CMASRestResolver resolver = new CMASRestResolver(cmasBaseUrl, parser, client);

    InetSocketAddress resultAddress = resolver.resolveTarget(e.getChannel());

    verify(client).resource(cmasBaseUrl + "/uirest/vnc/registration/" + host);

    assertEquals(host, resultAddress.getHostName());
    assertEquals(port, resultAddress.getPort());
  }
Пример #11
0
 /**
  * Handle downstream event.
  *
  * @param pipeline the {@link ChannelPipeline} that passes down the downstream event.
  * @param e The downstream event.
  */
 @Override
 public void eventSunk(final ChannelPipeline pipeline, final ChannelEvent e) throws Exception {
   final NioDatagramChannel channel = (NioDatagramChannel) e.getChannel();
   final ChannelFuture future = e.getFuture();
   if (e instanceof ChannelStateEvent) {
     final ChannelStateEvent stateEvent = (ChannelStateEvent) e;
     final ChannelState state = stateEvent.getState();
     final Object value = stateEvent.getValue();
     switch (state) {
       case OPEN:
         if (Boolean.FALSE.equals(value)) {
           channel.worker.close(channel, future);
         }
         break;
       case BOUND:
         if (value != null) {
           bind(channel, future, (InetSocketAddress) value);
         } else {
           channel.worker.close(channel, future);
         }
         break;
       case CONNECTED:
         if (value != null) {
           connect(channel, future, (InetSocketAddress) value);
         } else {
           NioDatagramWorker.disconnect(channel, future);
         }
         break;
       case INTEREST_OPS:
         channel.worker.setInterestOps(channel, future, ((Integer) value).intValue());
         break;
     }
   } else if (e instanceof MessageEvent) {
     final MessageEvent event = (MessageEvent) e;
     final boolean offered = channel.writeBufferQueue.offer(event);
     assert offered;
     channel.worker.writeFromUserCode(channel);
   }
 }
Пример #12
0
 public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) throws Exception {
   OioDatagramChannel channel = (OioDatagramChannel) e.getChannel();
   ChannelFuture future = e.getFuture();
   if (e instanceof ChannelStateEvent) {
     ChannelStateEvent stateEvent = (ChannelStateEvent) e;
     ChannelState state = stateEvent.getState();
     Object value = stateEvent.getValue();
     switch (state) {
       case OPEN:
         if (Boolean.FALSE.equals(value)) {
           OioDatagramWorker.close(channel, future);
         }
         break;
       case BOUND:
         if (value != null) {
           bind(channel, future, (SocketAddress) value);
         } else {
           OioDatagramWorker.close(channel, future);
         }
         break;
       case CONNECTED:
         if (value != null) {
           connect(channel, future, (SocketAddress) value);
         } else {
           OioDatagramWorker.disconnect(channel, future);
         }
         break;
       case INTEREST_OPS:
         OioDatagramWorker.setInterestOps(channel, future, ((Integer) value).intValue());
         break;
     }
   } else if (e instanceof MessageEvent) {
     MessageEvent evt = (MessageEvent) e;
     OioDatagramWorker.write(channel, future, evt.getMessage(), evt.getRemoteAddress());
   }
 }
Пример #13
0
 static void sendRedirect(
     final ChannelHandlerContext ctx,
     final ChannelEvent e,
     final Class<? extends ComponentId> compClass,
     final MappingHttpRequest request) {
   e.getFuture().cancel();
   String redirectUri = null;
   if (Topology.isEnabled(compClass)) { // have an enabled service, lets use that
     final URI serviceUri = ServiceUris.remote(Topology.lookup(compClass));
     redirectUri =
         serviceUri.toASCIIString() + request.getServicePath().replace(serviceUri.getPath(), "");
   } else if (Topology.isEnabled(
       Eucalyptus.class)) { // can't find service info, redirect via clc master
     final URI serviceUri = ServiceUris.remote(Topology.lookup(Eucalyptus.class));
     redirectUri =
         serviceUri.toASCIIString().replace(Eucalyptus.INSTANCE.getServicePath(), "")
             + request.getServicePath().replace(serviceUri.getPath(), "");
   }
   HttpResponse response = null;
   if (redirectUri == null || isRedirectLoop(request, redirectUri)) {
     response =
         new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.SERVICE_UNAVAILABLE);
     if (Logs.isDebug()) {
       String errorMessage =
           "Failed to lookup service for "
               + Components.lookup(compClass).getName()
               + " for path "
               + request.getServicePath()
               + ".\nCurrent state: \n\t"
               + Joiner.on("\n\t").join(Topology.enabledServices());
       byte[] errorBytes = Exceptions.string(new ServiceStateException(errorMessage)).getBytes();
       response.setContent(ChannelBuffers.wrappedBuffer(errorBytes));
     }
   } else {
     response =
         new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT);
     if (request.getQuery() != null) {
       redirectUri += "?" + request.getQuery();
     }
     response.setHeader(HttpHeaders.Names.LOCATION, redirectUri);
   }
   response.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
   if (ctx.getChannel().isConnected()) {
     ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
   }
 }
 @Override
 public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
   if (e instanceof MessageEvent) {
     MessageEvent event = (MessageEvent) e;
     ChannelBuffer buffer = (ChannelBuffer) event.getMessage();
     while (buffer.readableBytes() > 0) {
       ChannelBuffer newBuffer = ChannelBuffers.dynamicBuffer();
       if (buffer.readableBytes() >= chunkSize) {
         newBuffer.writeBytes(buffer.readBytes(chunkSize));
       } else {
         newBuffer.writeBytes(buffer.readBytes(buffer.readableBytes()));
       }
       Thread.sleep(latency);
       write(ctx, e.getFuture(), newBuffer, event.getRemoteAddress());
     }
   } else {
     ctx.sendDownstream(e);
   }
 }
Пример #15
0
  @Override
  public void msgTimedEvent() throws UnsupportedEncodingException {

    SmqOppResult ruCount = getmsgList().Opp(QueueMethod.Count, null);

    int len = ruCount.count;

    for (int i = 0; i < len; i++) {

      // C# TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java:
      /// #region 获取消息及Session

      SmqOppResult ruShift = getmsgList().Opp(QueueMethod.Shift, null);

      if (!ruShift.oppSucess) {
        Log.WriteStrByArgument(
            RCLogicLPU.class.getName(), "msgTimedEvent", "QueueMethod.Shift", "oppSucess is false");
        continue;
      }

      if (null == ruShift.item) {
        Log.WriteStrByArgument(
            RCLogicLPU.class.getName(), "msgTimedEvent", "QueueMethod.Shift", "item is null");
        continue;
      }

      SessionMessage item = ruShift.item;

      //
      XmlDocument doc = item.doc();
      String strIpPort = item.strIpPort();
      String action = item.action();
      ChannelEvent e = item.e();

      item.Dereference();
      AppSession c = new AppSession(e.getChannel(), e);

      //
      if (action.equals(RCClientAction.loadG)) {
        RCLogic.doorLoadG(c, doc);

        continue;
      }

      if (action.equals(RCClientAction.betG)) {
        RCLogic.doorBetG(c, doc);

        continue;
      }

      if (action.equals(RCClientAction.updG)) {
        RCLogic.doorUpdG(c, doc);

        continue;
      }

      if (action.equals(RCClientAction.updHonor)) {
        RCLogic.doorUpdHonor(c, doc);

        continue;
      }

      if (action.equals(RCClientAction.login)) {
        RCLogic.doorLogin(c, doc);

        continue;
      }

      if (action.equals(RCClientAction.hasReg)) {
        RCLogic.doorHasReg(c, doc);

        continue;
      }

      if (action.equals(RCClientAction.reg)) {
        RCLogic.doorReg(c, doc);

        continue;
      }

      if (action.equals(RCClientAction.chkEveryDayLoginAndGet)) {
        RCLogic.doorChkEveryDayLoginAndGet(c, doc);

        continue;
      }

      if (action.equals(RCClientAction.loadChart)) {
        RCLogic.doorLoadChart(c, doc);

        continue;
      }

      if (action.equals(RCClientAction.loadTopList)) {
        RCLogic.doorLoadTopList(c, doc);

        continue;
      }

      if (action.equals(RCClientAction.hasProof)) {
        RCLogic.doorHasProof(c, doc);

        continue;
      }

      if (action.equals(RCClientAction.loadDBType)) {
        RCLogic.doorLoadDBType(c, doc);

        continue;
      }

      // Logger.WriteStr("无效协议号:" + clientServerAction);
      Log.WriteStr(SR.GetString(SR.getInvalid_protocol_num(), action));
    }
  }