Example #1
0
  @Test
  public void testReachAgeLimit()
      throws InvalidKeyException, SignatureException, IOException, InterruptedException {
    long waitTime = 2000;

    CountingBufferListener listener = new CountingBufferListener();
    MessageBuffer<Message> buffer =
        new MessageBuffer<Message>(Integer.MAX_VALUE, Long.MAX_VALUE, waitTime);
    buffer.addListener(listener);

    // create one message
    buffer.addMessage(UtilsNAT.createRandomMessage(), 10);

    // buffer did not trigger yet
    assertEquals(0, listener.getTriggerCount());
    assertEquals(0, listener.getBuffer().size());

    // wait for the given time and slightly longer
    Thread.sleep((long) (waitTime * 1.5));

    // buffer triggered already
    assertEquals(1, listener.getTriggerCount());
    assertEquals(1, listener.getBuffer().size());

    // wait again
    Thread.sleep((long) (waitTime * 1.5));

    // test that buffer did not trigger again
    assertEquals(1, listener.getTriggerCount());
    assertEquals(1, listener.getBuffer().size());
  }
  @Test
  public void testBuffer() {
    MessageBuffer b = new MessageBuffer();
    b.append("Hello, world");
    b.appendNewLine();
    b.append("how are you?");

    CharSequence s = b.getBuffer();
    assertEquals("Hello, world\nhow are you?", s.toString());
  }
 @Test
 public void testMaxSize() {
   int max = 5;
   MessageBuffer b = new MessageBuffer(5);
   for (int i = 0; i < max * 2; i++) {
     b.append("Line" + i + "\n");
   }
   String content = b.getBuffer().toString();
   String expected = "(...)\nLine5\nLine6\nLine7\nLine8\nLine9\n";
   assertEquals(expected, content);
 }
Example #4
0
  @Test
  public void testReachSizeLimit() throws InvalidKeyException, SignatureException, IOException {
    CountingBufferListener listener = new CountingBufferListener();
    MessageBuffer<Message> buffer =
        new MessageBuffer<Message>(Integer.MAX_VALUE, 1, Long.MAX_VALUE);
    buffer.addListener(listener);

    // create one message
    buffer.addMessage(UtilsNAT.createRandomMessage(), 2);

    // buffer triggered already
    assertEquals(1, listener.getTriggerCount());
    assertEquals(1, listener.getBuffer().size());
  }
  @Test
  public void testAppendBuffer() {
    MessageBuffer b1 = new MessageBuffer();
    b1.append("Line one");
    int l = b1.getLength();
    MessageBuffer b2 = new MessageBuffer();
    b2.append(b1);
    assertEquals("Wrong length", b2.getLength(), l);

    b2 = new MessageBuffer();
    b2.append("Some stuff");
    int l2 = b2.getLength();
    b2.append(b1);
    assertEquals("Wrong length", b2.getLength(), l + l2);
  }
Example #6
0
  // Run method
  public void run(){
    exptStartTime = (new Date()).getTime();

    // create client to server (Event Listener)
    Socket socket = null;
    PrintWriter out = null;

    try {
      socket = new Socket (ipOfEventListener, portOfServer);
      out = new PrintWriter(socket.getOutputStream(), true);

      while (true){

        while (msgBuffer.lock.tryLock()) {
			// keep polling msgBuffer
	        while (!exptTimeUp() & msgBuffer.isEmpty())
	          ; // get stuck here until msgBuffer contains something or experiment period is up

	        

	        // send message to Event Listener & clear message buffer
	        out.println(msgBuffer.getWholeMsg());
	        System.out.println("Sent: "+ msgBuffer.getWholeMsg());
	        System.out.println("---");
	        msgBuffer.clear();
			msgBuffer.lock.unlock();
		}
		
		// exit if period for experiment is up
        if (exptTimeUp())
          break;

      }
      // Cleanup
      out.close();
      socket.close();
    }
    catch (IOException e) {
      System.err.println("*** FATAL ERROR: " + e.getMessage());
      System.err.println("*** LIKELY REASON: Make sure Push Server is up and listening at the correct IP address and port.");
      System.exit(1);
    }
    catch (Exception e){
      System.err.println("*** FATAL ERROR: " + e.getMessage());
      System.exit(1);
    }
    System.out.println("PushClient exited normally...");
  }
Example #7
0
 /**
  * Returns a {@code CompactId} constructed from the ID's external format contained in the
  * specified message buffer.
  *
  * @param buf a message buffer containing the external format of a {@code CompactId}
  * @return a {@code CompactId} constructed from the external format in the given message buffer
  * @throws IllegalArgumentException if the external format contained in the message buffer is
  *     malformed or unsupported
  */
 public static CompactId getCompactId(MessageBuffer buf) {
   int bufSize = buf.limit() - buf.position();
   if (bufSize == 0) {
     throw new IllegalArgumentException("empty buffer");
   }
   byte lengthByte = buf.getByte();
   int size = getExternalFormByteCount(lengthByte);
   if (bufSize < size) {
     throw new IllegalArgumentException("buffer size insufficient");
   }
   byte[] externalForm = new byte[size];
   externalForm[0] = lengthByte;
   for (int i = 1; i < size; i++) {
     externalForm[i] = buf.getByte();
   }
   return CompactId.fromExternalForm(externalForm);
 }
Example #8
0
  @Test
  public void testBufferOrder()
      throws InvalidKeyException, SignatureException, IOException, NoSuchAlgorithmException,
          InvalidKeySpecException {
    CountingBufferListener listener = new CountingBufferListener();
    MessageBuffer<Message> buffer = new MessageBuffer<Message>(5, Long.MAX_VALUE, Long.MAX_VALUE);
    buffer.addListener(listener);

    // create five messages
    Message first = UtilsNAT.createRandomMessage();
    Message second = UtilsNAT.createRandomMessage();
    Message third = UtilsNAT.createRandomMessage();
    Message fourth = UtilsNAT.createRandomMessage();
    Message fifth = UtilsNAT.createRandomMessage();

    buffer.addMessage(first, RelayUtils.getMessageSize(first, signature));
    buffer.addMessage(second, RelayUtils.getMessageSize(second, signature));
    buffer.addMessage(third, RelayUtils.getMessageSize(third, signature));
    buffer.addMessage(fourth, RelayUtils.getMessageSize(fourth, signature));
    buffer.addMessage(fifth, RelayUtils.getMessageSize(fifth, signature));

    // buffer triggered by now, check the order
    List<Message> content = listener.getBuffer();
    assertEquals(first.messageId(), content.get(0).messageId());
    assertEquals(second.messageId(), content.get(1).messageId());
    assertEquals(third.messageId(), content.get(2).messageId());
    assertEquals(fourth.messageId(), content.get(3).messageId());
    assertEquals(fifth.messageId(), content.get(4).messageId());
  }
Example #9
0
  @Test
  public void testBufferFlush()
      throws InvalidKeyException, SignatureException, IOException, NoSuchAlgorithmException,
          InvalidKeySpecException {
    CountingBufferListener listener = new CountingBufferListener();
    MessageBuffer<Message> buffer = new MessageBuffer<Message>(3, Long.MAX_VALUE, Long.MAX_VALUE);
    buffer.addListener(listener);

    // add two messages
    buffer.addMessage(UtilsNAT.createRandomMessage(), 10);
    buffer.addMessage(UtilsNAT.createRandomMessage(), 10);

    buffer.flushNow();

    // check whether the buffer has been pre-emptied
    assertEquals(1, listener.getTriggerCount());
    assertEquals(2, listener.getBuffer().size());
  }
Example #10
0
 private Midi receiveBlocks(MessageBuffer messageBuffer, String message) {
   Midi midi = null;
   try {
     int comma = message.indexOf(',', RSJM.length());
     int equals = message.indexOf('=', comma);
     int blockNumber = Integer.parseInt(message.substring(RSJM.length(), comma));
     int blockCount = Integer.parseInt(message.substring(comma + 1, equals));
     String block = message.substring(equals + 1);
     messageBuffer.addBlock(blockNumber, blockCount, block);
     if (messageBuffer.getBlockCount() == blockCount) {
       String base64 = messageBuffer.consume();
       midi = Midi.fromBase64(base64);
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return midi;
 }
Example #11
0
  @Test
  public void testGarbageCollect()
      throws InvalidKeyException, SignatureException, IOException, InterruptedException {
    CountingBufferListener listener = new CountingBufferListener();
    MessageBuffer<Message> buffer = new MessageBuffer<Message>(2, Long.MAX_VALUE, Long.MAX_VALUE);
    buffer.addListener(listener);

    // create one message
    buffer.addMessage(UtilsNAT.createRandomMessage(), 10);

    // garbage collect
    System.gc();

    // create another message
    buffer.addMessage(UtilsNAT.createRandomMessage(), 12);

    // buffer triggered two messages
    assertEquals(2, listener.getBuffer().size());
  }
Example #12
0
  @Test
  public void testReachCountLimit() throws InvalidKeyException, SignatureException, IOException {
    CountingBufferListener listener = new CountingBufferListener();
    MessageBuffer<Message> buffer = new MessageBuffer<Message>(3, Long.MAX_VALUE, Long.MAX_VALUE);
    buffer.addListener(listener);

    // create three messages
    Message first = UtilsNAT.createRandomMessage();
    Message second = UtilsNAT.createRandomMessage();
    Message third = UtilsNAT.createRandomMessage();

    buffer.addMessage(first, RelayUtils.getMessageSize(first, signature));
    buffer.addMessage(second, RelayUtils.getMessageSize(second, signature));

    // buffer did not trigger yet
    assertEquals(0, listener.getTriggerCount());
    assertEquals(0, listener.getBuffer().size());

    // buffer triggered now
    buffer.addMessage(third, RelayUtils.getMessageSize(third, signature));
    assertEquals(1, listener.getTriggerCount());
    assertEquals(3, listener.getBuffer().size());
  }
  protected final <T extends Message> IoBufferEx encode(
      String cacheKey,
      MessageEncoder<T> encoder,
      T message,
      IoBufferAllocatorEx<?> allocator,
      int flags) {
    ConcurrentMap<String, IoBufferEx> cache = message.getCache();

    // if cache is not initialized, throw exception (caller should guard)
    if (cache == null) {
      throw new IllegalStateException("Cache not initialized");
    }

    // lookup existing cached encoding entry
    IoBufferEx cachedBuffer = cache.get(cacheKey);
    if (cachedBuffer == null) {
      // when cachedBuffer is null, perform encode, then cache the result
      // with standard atomic race condition awareness (put-if-absent)
      if ((flags & FLAG_ZERO_COPY) != 0) {
        if (!cache.isEmpty()) {
          flags &= ~FLAG_ZERO_COPY;
        }
      }

      IoBufferEx newCachedBuffer = encoder.encode(allocator, message, flags);
      if (newCachedBuffer instanceof MessageBuffer<?>) {
        MessageBuffer<?> cacheableBuffer = (MessageBuffer<?>) newCachedBuffer;
        cacheableBuffer.setAutoCache(true);
      }
      cachedBuffer = cache.putIfAbsent(cacheKey, newCachedBuffer);
      if (cachedBuffer == null) {
        cachedBuffer = newCachedBuffer;
      }
    }

    return cachedBuffer;
  }
  // Run method. Fires events periodically & ends when all events are fired.
  public void run() {
    int pointer = 0; // pointer used in delayIntervals array

    // repeat until all the events have been fired
    while (pointer < delayIntervals.size()) {
      // extract delay interval
      int nextDelayInterval = delayIntervals.get(pointer++).intValue();

      // delay for nextDelayInternal number of seconds
      delay(
          nextDelayInterval
              * 1000); // remember that delay intervals are given in seconds. so multiply by 1000
                       // before passing into the delay method

      // An event happens here
      Date rightNow = new Date();
      System.out.println("Event " + pointer + " fired at time " + rightNow);
      System.out.println("---");

      // Create event message & append it to message buffer
      msgBuffer.setMessageBufferText(createNewMessage(rightNow, '~', msgLength, '*'));
    }
    System.out.println("Exiting EventGenerator thread...");
  }
  /*
   * This method handles RTSP server responses
   * */
  public void incomingMessage(MessageBuffer buffer) throws Exception {

    // read a message bytes data in buffer
    ByteArrayInputStream in =
        new ByteArrayInputStream(buffer.getData(), buffer.getOffset(), buffer.getLength());

    int initial = in.available();
    Message message = null;

    try {
      String line = readLine(in);
      if (line.startsWith(Message.RTSP_TOKEN)) {
        message = new RtspResponse(line);
      } else {
        RtspRequest.Method method = null;
        try {
          method = RtspRequest.Method.valueOf(line.substring(0, line.indexOf(' ')));
        } catch (IllegalArgumentException ilae) {

        }
        // 从Map中取出相应类型的Request信息
        Class<? extends RtspRequest> cls = requestMap.get(method);
        if (cls != null) message = cls.getConstructor(String.class).newInstance(line);
        else message = new RtspRequest(line);
      }

      while (true) {
        line = readLine(in);
        if (in == null) throw new Exception();
        if (line.length() == 0) break;
        Constructor<? extends RtspHeader> c =
            headerMap.get(line.substring(0, line.indexOf(':')).toLowerCase());
        if (c != null) message.addHeader(c.newInstance(line));
        else message.addHeader(new RtspHeader(line));
      }
      buffer.setMessage(message);

      try {
        int length = ((ContentLengthHeader) message.getHeader(ContentLengthHeader.NAME)).getValue();
        if (in.available() < length) throw new Exception();
        RtspContent content = new RtspContent();
        content.setDescription(message);
        byte[] data = new byte[length];
        in.read(data);
        content.setBytes(data);
        message.setEntityMessage(new RtspEntityMessage(message, content));
      } catch (Exception e) {
        e.printStackTrace();
      }
    } catch (Exception e) {
      throw new Exception(e);
    } finally {
      // TODO:读取后更新buffer状态
      buffer.setused(initial - in.available());
      // buffer.discardData();

      try {
        in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Example #16
0
 /**
  * Puts the external form of this {@code CompactId} in the specified message buffer.
  *
  * @param buf a message buffer
  * @throws IllegalArgumentException if the message buffer size is insufficient
  */
 public void putCompactId(MessageBuffer buf) {
   if (buf.capacity() - buf.position() < externalForm.length) {
     throw new IllegalArgumentException("buffer size insufficient");
   }
   buf.putBytes(externalForm);
 }