示例#1
0
 /**
  * encode the current Control Message into a channel buffer
  *
  * @throws Exception
  */
 ChannelBuffer buffer() throws Exception {
   ChannelBufferOutputStream bout =
       new ChannelBufferOutputStream(ChannelBuffers.directBuffer(encodeLength()));
   write(bout);
   bout.close();
   return bout.buffer();
 }
 private void sendReply(Channel channel, int checksum) {
   ChannelBuffer reply = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, 3);
   reply.writeByte(0x02);
   reply.writeShort((short) checksum);
   if (channel != null) {
     channel.write(reply);
   }
 }
示例#3
0
 private static void sendResponse(
     Channel channel, SocketAddress remoteAddress, long rawId, int index) {
   if (channel != null) {
     ChannelBuffer response = ChannelBuffers.directBuffer(12);
     response.writeShort(0xfe02);
     response.writeLong(rawId);
     response.writeShort(index);
     channel.write(response, remoteAddress);
   }
 }
 private void requestArchive(Channel channel) {
   if (lastIndex == 0) {
     lastIndex = newIndex;
   } else if (newIndex > lastIndex) {
     ChannelBuffer request = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, 12);
     request.writeShort(MSG_LOG_SYNC);
     request.writeShort(4);
     request.writeInt((int) lastIndex);
     request.writeInt(0);
     channel.write(request);
   }
 }
 private ChannelBuffer allocateBigEndianBuffer(int capacity) {
   ChannelBuffer slice;
   synchronized (bigEndianLock) {
     if (preallocatedBigEndianBuffer == null) {
       preallocatedBigEndianBuffer =
           ChannelBuffers.directBuffer(ByteOrder.BIG_ENDIAN, preallocatedBufferCapacity);
       slice = preallocatedBigEndianBuffer.slice(0, capacity);
       preallocatedBigEndianBufferPosition = capacity;
     } else if (preallocatedBigEndianBuffer.capacity() - preallocatedBigEndianBufferPosition
         >= capacity) {
       slice = preallocatedBigEndianBuffer.slice(preallocatedBigEndianBufferPosition, capacity);
       preallocatedBigEndianBufferPosition += capacity;
     } else {
       preallocatedBigEndianBuffer =
           ChannelBuffers.directBuffer(ByteOrder.BIG_ENDIAN, preallocatedBufferCapacity);
       slice = preallocatedBigEndianBuffer.slice(0, capacity);
       preallocatedBigEndianBufferPosition = capacity;
     }
   }
   return slice;
 }
  private void sendReply(Channel channel, ChannelBuffer data) {
    ChannelBuffer header = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, 16);
    header.writeBytes(ChannelBuffers.copiedBuffer(ByteOrder.LITTLE_ENDIAN, prefix, CHARSET));
    header.writeInt((int) deviceUniqueId);
    header.writeInt((int) serverId);
    header.writeShort(data.readableBytes());
    header.writeByte(checksum(data));
    header.writeByte(checksum(header));

    if (channel != null) {
      channel.write(ChannelBuffers.copiedBuffer(header, data));
    }
  }
示例#7
0
  /** create a buffer containing the encoding of this batch */
  ChannelBuffer buffer() throws Exception {
    ChannelBufferOutputStream bout =
        new ChannelBufferOutputStream(ChannelBuffers.directBuffer(encoded_length));

    for (TaskMessage msg : msgs) {
      writeTaskMessage(bout, msg);
    }

    // add a END_OF_BATCH indicator
    ControlMessage.EOB_MESSAGE.write(bout);

    bout.close();

    return bout.buffer();
  }
 /**
  * Sends the available MBeanServer domains in this JVM through the passed channel to the passed
  * remote address in response to a {@link OpCode#JMX_MBS_INQUIRY} request.
  *
  * @param channel The channel to write to
  * @param remoteAddress The remote address to send to
  */
 public static void sendMBeanServerDomains(Channel channel, SocketAddress remoteAddress) {
   String[] domains = getMBeanServerDomains();
   int size = 4 + (domains.length * 4) + 1;
   for (String s : domains) {
     size += s.getBytes().length;
   }
   ChannelBuffer cb = ChannelBuffers.directBuffer(size);
   cb.writeByte(OpCode.JMX_MBS_INQUIRY_RESPONSE.op());
   cb.writeInt(domains.length);
   for (String s : domains) {
     byte[] bytes = s.getBytes();
     cb.writeInt(bytes.length);
     cb.writeBytes(bytes);
   }
   SimpleLogger.info("Sending MBeanServer Domain List ", Arrays.toString(domains));
   channel.write(cb, remoteAddress);
 }
示例#9
0
 /** 假定js都是只读的,如有更新必然体现在文件名上标记版本。 */
 public void tryReloadJs() {
   if (System.currentTimeMillis() - lastReloadTime < jsReloadPeriodMs) {
     return;
   }
   lastReloadTime = System.currentTimeMillis();
   Map<String, ChannelBuffer> newBufferMap = null; // = new HashMap<String, ChannelBuffer>();
   for (File f : new File(confAdmin.getFullPathRelatedToConfRoot("js")).listFiles()) {
     String name = f.getName();
     if (name.endsWith(".js")) {
       if (jsBufferMap.containsKey(name)) {
         continue;
       }
       if (newBufferMap == null) {
         newBufferMap = new HashMap<String, ChannelBuffer>(jsBufferMap);
       }
       // TODO: use new io
       InputStream in = null;
       try {
         in = new FileInputStream(f);
         ByteArrayOutputStream bao = new ByteArrayOutputStream();
         GZIPOutputStreamEx gzo = new GZIPOutputStreamEx(bao, Deflater.BEST_COMPRESSION);
         gzo.write(trackUrlExpBa);
         byte[] buf = new byte[1024];
         int c = 0;
         while ((c = in.read(buf)) != -1) {
           gzo.write(buf, 0, c);
         }
         gzo.close();
         in.close();
         byte[] ba = bao.toByteArray();
         ChannelBuffer cbuf = ChannelBuffers.directBuffer(ba.length);
         cbuf.writeBytes(ba);
         newBufferMap.put(name, cbuf);
       } catch (IOException e) { // never happen
         log.error(e);
       }
     }
   }
   if (newBufferMap != null) {
     jsBufferMap = newBufferMap;
   }
 }
 /**
  * Writes a notification back to the originating listener registrar
  *
  * @param channel The channel to write on
  * @param remoteAddress The remote address to write to
  * @param requestId The request ID of the original listener registration
  * @param notification The notification to write
  * @param handback The optional contextual handback
  */
 public static void writeNotification(
     Channel channel,
     SocketAddress remoteAddress,
     int requestId,
     Notification notification,
     Object handback) {
   byte[] payload = getOutput(notification, handback);
   int size =
       payload.length
           + 1
           + 4
           + 4; // size is <payload size> + <OpCode> + <requestId> + <<payload length>
   ChannelBuffer cb = ChannelBuffers.directBuffer(size);
   cb.writeByte(OpCode.JMX_NOTIFICATION.op());
   cb.writeInt(requestId);
   cb.writeInt(payload.length);
   cb.writeBytes(payload);
   channel.write(cb, remoteAddress);
   SimpleLogger.info("Wrote JMX Notification [", size, "] bytes");
 }
  public ChannelBuffer getBuffer(ByteOrder order, int capacity) {
    if (order == null) {
      throw new NullPointerException("order");
    }
    if (capacity < 0) {
      throw new IllegalArgumentException("capacity: " + capacity);
    }
    if (capacity == 0) {
      return ChannelBuffers.EMPTY_BUFFER;
    }
    if (capacity >= preallocatedBufferCapacity) {
      return ChannelBuffers.directBuffer(order, capacity);
    }

    ChannelBuffer slice;
    if (order == ByteOrder.BIG_ENDIAN) {
      slice = allocateBigEndianBuffer(capacity);
    } else {
      slice = allocateLittleEndianBuffer(capacity);
    }
    slice.clear();
    return slice;
  }
 /**
  * Writes a JMX invocation response back to the caller
  *
  * @param requestId The original request id
  * @param methodId The {@link MBeanServerConnection} method ID byte
  * @param channel The channel to write to
  * @param remoteAddress The remote address that the channel will write to
  * @param response AN array of object responses
  */
 public static void writeJMXResponse(
     int requestId,
     byte methodId,
     Channel channel,
     SocketAddress remoteAddress,
     Object... response) {
   byte[] payload = getOutput(response);
   int size =
       payload.length
           + 1
           + 4
           + 1
           + 4; // size is <payload size> + <OpCode> + <requestId> + <method ID byte> + <payload
                // length>
   ChannelBuffer cb = ChannelBuffers.directBuffer(size);
   cb.writeByte(OpCode.JMX_RESPONSE.op());
   cb.writeInt(requestId);
   cb.writeByte(methodId);
   cb.writeInt(payload.length);
   cb.writeBytes(payload);
   channel.write(cb, remoteAddress);
   SimpleLogger.info("Wrote JMX Response [", size, "] bytes");
 }
  private void sendReply(Channel channel, long deviceId, byte packetNumber) {
    ChannelBuffer reply = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, 28);
    reply.writeByte('M');
    reply.writeByte('C');
    reply.writeByte('G');
    reply.writeByte('P');
    reply.writeByte(MSG_SERVER_ACKNOWLEDGE);
    reply.writeInt((int) deviceId);
    reply.writeByte(commandCount++);
    reply.writeInt(0); // authentication code
    reply.writeByte(0);
    reply.writeByte(packetNumber);
    reply.writeZero(11);

    byte checksum = 0;
    for (int i = 4; i < 27; i++) {
      checksum += reply.getByte(i);
    }
    reply.writeByte(checksum);

    if (channel != null) {
      channel.write(reply);
    }
  }
  /**
   * {@inheritDoc}
   *
   * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method,
   *     java.lang.Object[])
   */
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (MBeanServerConnection.class != method.getDeclaringClass()) {
      return method.invoke(Modifier.isStatic(method.getModifiers()) ? null : this, args);
    }
    if (channel.getPipeline().get(getClass().getSimpleName()) == null) {
      throw new IOException("This MBeanServerConnection has been closed", new Throwable());
    }
    // SimpleLogger.debug("MBeanServerConnection [", method.getName(), "] Payload Size [",
    // sargs.length+6+4, "]");
    final int reqId = requestId.incrementAndGet();
    if ("addNotificationListener".equals(method.getName())
        && !method.getParameterTypes()[1].equals(ObjectName.class)) {
      NotificationListener listener = (NotificationListener) args[1];
      args[1] = reqId;
      addRegisteredListener(reqId, listener);
    } else if ("removeNotificationListener".equals(method.getName())
        && !method.getParameterTypes()[1].equals(ObjectName.class)) {
      removeRegisteredListener((NotificationListener) args[1]);
      args = new Object[0];
    }
    byte[] sargs = getOutput(args);
    ChannelBuffer cb =
        ChannelBuffers.directBuffer(1 + domainInfoData.length + 4 + 1 + 4 + sargs.length);
    cb.writeByte(OpCode.JMX_REQUEST.op()); // 1
    cb.writeBytes(domainInfoData); // domain data
    cb.writeInt(reqId); // 4
    cb.writeByte(methodToKey.get(method)); // 1
    cb.writeInt(sargs.length); // 4
    cb.writeBytes(sargs); // sargs.length

    if (listener == null) {
      synchTimeoutMap.addListener(
          new TimeoutListener<Integer, CountDownLatch>() {
            @Override
            public void onTimeout(Integer key, CountDownLatch value) {
              if (reqId == key) {
                synchTimeoutMap.remove(key);
                synchTimeoutMap.removeListener(this);
                onSynchronousResponse(
                    reqId,
                    new IOException(
                        "Operation timed out after [" + timeout + "] ms.", new Throwable()));
              }
            }
          });
    } else {
      asynchTimeoutMap.put(reqId, listener, timeout);
      asynchTimeoutMap.addListener(
          new TimeoutListener<Integer, AsynchJMXResponseListener>() {
            @Override
            public void onTimeout(Integer key, AsynchJMXResponseListener value) {
              if (reqId == key) {
                asynchTimeoutMap.remove(key);
                listener.onTimeout(reqId, timeout);
                asynchTimeoutMap.removeListener(this);
              }
            }
          });
    }

    channel
        .write(cb, remoteAddress)
        .addListener(
            new ChannelFutureListener() {
              @Override
              public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                  SimpleLogger.debug("Sent JMX Request to [", remoteAddress, "]");
                } else {
                  SimpleLogger.error(
                      "Failed to send JMX Request to [", remoteAddress, "]", future.getCause());
                }
              }
            });
    if (listener == null) {
      waitForSynchronousResponse(reqId, timeout);
      Object result = synchResultMap.get(reqId);
      if (result != null && result instanceof Throwable) {
        throw (Throwable) result;
      }
      return result;
    }
    return null;
  }