Java Code Examples for java.util.Queue#element()

The following examples show how to use java.util.Queue#element() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestFastCodec.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeDecodeMessage() throws Exception
{
	FASTCodec codec = getCodec(DICTIONARY_URI, TEMPLATE_TITLE);
	ProtocolEncoderOutput output = new MockProtocolEncoderOutput();

	IMessage message = new MapMessage("OEquity", "Logon");

       message.addField("Password", "tnp123");
       message.addField("Username", "MADTY0" );
       message.addField("SendingTime", "20120101-01:01:01.333");
       message.addField("ApplID", "0");
       message.addField("MessageType", "0");

	session.write(message);
	codec.encode(session, message, output);
	Queue<Object> msgQueue = ((AbstractProtocolEncoderOutput)output).getMessageQueue();
	Object lastMessage = msgQueue.element();
	byte[] asd = ((IoBuffer)lastMessage).array();
	int limit = ((IoBuffer)lastMessage).limit();
	byte[] bytes = Arrays.copyOf(asd, limit );

	session.write(lastMessage);
	System.out.println(HexDumper.getHexdump(bytes));
}
 
Example 2
Source File: BICO.java    From moa with GNU General Public License v3.0 6 votes vote down vote up
/**
 * If the number of ClusteringTreeNodes exceeds the maximum bound, the
 * global threshold T will be doubled and the tree will be rebuild with the
 * new threshold.
 *
 */
protected void rebuild() {
	// Checks if the number of nodes in the tree exceeds the maximum number
	while (this.rootCount > this.maxNumClusterFeatures) {
		// Doubles the global threshold
		this.T *= 2.0;
		this.root.setThreshold(calcRSquared(1));
		// Adds all nodes to the ClusteringFeature tree again
		Queue<ClusteringTreeNode> Q = new LinkedList<ClusteringTreeNode>();
		Q.addAll(this.root.getChildren());
		this.root.clearChildren();
		this.rootCount = 0;
		while (!Q.isEmpty()) {
			ClusteringTreeNode x = Q.element();
			Q.addAll(x.getChildren());
			x.clearChildren();
			bicoCFUpdate(x);
			Q.remove();
		}
	}
}
 
Example 3
Source File: TestFastCodec.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncodeMessage() throws Exception
{

	FASTCodec codec = getCodec(DICTIONARY_URI, TEMPLATE_TITLE);

	ProtocolEncoderOutput output = new MockProtocolEncoderOutput();

	IMessage message = new MapMessage("OEquity", "Logon");

	message.addField("Password", "tnp123");
	message.addField("Username", "MADTY0" );
	message.addField("SendingTime", "20120101-01:01:01.333");
	message.addField("ApplID", "0");
	message.addField("MessageType", "0");

	session.write(message);
	codec.encode(session, message, output);
	Queue<Object> msgQueue = ((AbstractProtocolEncoderOutput)output).getMessageQueue();
	Object lastMessage = msgQueue.element();
	byte[] asd = ((IoBuffer)lastMessage).array();
	int limit = ((IoBuffer)lastMessage).limit();
	byte[] bytes = Arrays.copyOf(asd, limit );

	session.write(lastMessage);
	System.out.println(HexDumper.getHexdump(bytes));
}
 
Example 4
Source File: TestITCHHelper.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
protected Object encode(IMessage message, ITCHCodec codec) throws Exception {
       if(codec == null) {
           codec = (ITCHCodec)messageHelper.getCodec(serviceContext);
       }
	ProtocolEncoderOutput output = new MockProtocolEncoderOutput();
	session.write(message);
	codec.encode(session, message, output);
	Queue<Object> msgQueue = ((AbstractProtocolEncoderOutput)output).getMessageQueue();
	Assert.assertNotNull("Message queue from AbstractProtocolEncoderOutput.", msgQueue);
       Assert.assertTrue("Message queue size must be equal 1.", msgQueue.size() == 1);
	Object lastMessage = msgQueue.element();
	Assert.assertNotNull(lastMessage);
	return lastMessage;
}
 
Example 5
Source File: Solution.java    From DailyCodingProblem with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static int[] maxSubArr(int[] arr, int k) {
    int[] res = new int[arr.length - k + 1];
    Queue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());

    for (int i = 0, j = 0, m = 0; j < arr.length; ) {
        maxHeap.add(arr[j++]);

        if (maxHeap.size() > k)
            maxHeap.remove(arr[i++]);
        if (maxHeap.size() == k)
            res[m++] = maxHeap.element();
    }

    return res;
}
 
Example 6
Source File: UnsubscribeHandlerTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Test
public void test_unsubscribe_batched_and_acknowledge_error_mqtt5() {

    when(clientSessionSubscriptionPersistence.removeSubscriptions(anyString(), Matchers.any(ImmutableSet.class))).thenReturn(Futures.immediateFailedFuture(new NullPointerException("something is missing")));

    channel.attr(ChannelAttributes.MQTT_VERSION).set(ProtocolVersion.MQTTv5);

    final String topic1 = "myTopic1";
    final String topic2 = "myTopic2";
    final String topic3 = "myTopic3";
    final List<String> aList = newArrayList();
    aList.add(topic1);
    aList.add(topic2);
    aList.add(topic3);

    final UNSUBSCRIBE unsubscribe = new UNSUBSCRIBE(aList, 10);

    channel.writeInbound(unsubscribe);

    final Queue<Object> objects = channel.outboundMessages();

    assertEquals(1, objects.size());

    final UNSUBACK response = (UNSUBACK) objects.element();
    assertEquals(10, response.getPacketIdentifier());
    assertEquals(3, response.getReasonCodes().size());
    assertEquals(Mqtt5UnsubAckReasonCode.UNSPECIFIED_ERROR, response.getReasonCodes().get(0));
    assertEquals(Mqtt5UnsubAckReasonCode.UNSPECIFIED_ERROR, response.getReasonCodes().get(1));
    assertEquals(Mqtt5UnsubAckReasonCode.UNSPECIFIED_ERROR, response.getReasonCodes().get(2));

    verify(clientSessionSubscriptionPersistence).removeSubscriptions(eq("myTestClient"), any(ImmutableSet.class));

}
 
Example 7
Source File: Window.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private Tuple2<Long, Double> increase(Double value, ID id, long windowSize) {
    if (!windows.containsKey(id)) {
        windows.put(id, new LinkedList<>());
    }
    Queue<Tuple2<Long, Double>> window = windows.get(id);
    long now = System.currentTimeMillis();
    window.offer(Tuple.of(now, value));
    Tuple2<Long, Double> ps = window.element();
    if ((now - ps._1) >= windowSize) {
        window.remove();
    }
    return ps;
}
 
Example 8
Source File: CollectionsTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts properties that should hold for any empty queue.
 */
private static void assertQueueEmpty(Queue queue) {
    assertTrue(queue.isEmpty());
    assertEquals(0, queue.size());
    assertNull(queue.peek());
    try {
        queue.element();
        fail();
    } catch (NoSuchElementException expected) {
    }
    assertNull(queue.poll());
}
 
Example 9
Source File: TestFastCodec.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Test
public void testDecodeFastMessage_V_1_2() throws Exception {

	FASTCodec codec = getCodec(DICTIONARY_URI_V_1_2, TEMPLATE_TITLE_V_1_2);

	byte[] sourceArray = {
			(byte) 0xb3, (byte) 0xc0, (byte) 0x81, (byte) 0xb0, (byte) 0x32, (byte) 0x30, (byte) 0x31, (byte) 0x32, (byte) 0x30, (byte) 0x31, (byte) 0x30, (byte) 0x31, (byte) 0x2d, (byte) 0x30, (byte) 0x31, (byte) 0x3a,
			(byte) 0x30, (byte) 0x31, (byte) 0x3a, (byte) 0x30, (byte) 0x31, (byte) 0x2e, (byte) 0x33, (byte) 0x33, (byte) 0xb3, (byte) 0xb0, (byte) 0x80, (byte) 0x4d, (byte) 0x41, (byte) 0x44, (byte) 0x54, (byte) 0x59,
			(byte) 0xb0, (byte) 0x74, (byte) 0x6e, (byte) 0x70, (byte) 0x31, (byte) 0x32, (byte) 0xb3, (byte) 0x80, (byte) 0x80, (byte) 0x81, (byte) 0x15, (byte) 0x6f, (byte) 0x6a, (byte) 0x2c, (byte) 0x14, (byte) 0x75,
			(byte) 0x3d, (byte) 0x3c, (byte) 0xab, (byte) 0x81
	};

	IoBuffer toDecode = IoBuffer.wrap(sourceArray);
	toDecode.order(ByteOrder.LITTLE_ENDIAN);
	toDecode.position(0);

	IoSession decodeSession = new DummySession();

	MockProtocolDecoderOutput decoderOutput = new MockProtocolDecoderOutput();
	boolean decodableResult = codec.doDecode(decodeSession, toDecode, decoderOutput);
	Assert.assertTrue("Decoding error.", decodableResult);

	IMessage message = msgFactory.createMessage("Logon", "Test");

	message.addField("Password", "tnp123");
	message.addField("Username", "MADTY0" );
	message.addField("SendingTime", "20120101-01:01:01.333");
	message.addField("ApplID", "0");
	message.addField("MessageType", "0");
	message.addField("EndOfTransaction", true);
	message.addField("Timestamp", LocalDateTime.of(2019, 12, 12, 15, 30, 30, 555));
	message.addField("DeleteReason", 0);

	AbstractProtocolEncoderOutput output = new MockProtocolEncoderOutput();

	session.write(message);
	codec.encode(session, message, output);
	Queue<Object> msgQueue = output.getMessageQueue();
	Object lastMessage = msgQueue.element();
	byte[] asd = ((IoBuffer) lastMessage).array();
	int limit = ((IoBuffer) lastMessage).limit();
	byte[] bytes = Arrays.copyOf(asd, limit);

	session.write(lastMessage);
	Assert.assertArrayEquals("Compare source and encoded\n" + HexDumper.getHexdump(bytes), sourceArray, bytes);
}
 
Example 10
Source File: SubscribeHandlerTest.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Test
public void test_subscribe_single_and_acknowledge() throws Exception {

    final Topic topic = new Topic("test", QoS.AT_LEAST_ONCE);

    final SUBSCRIBE subscribe = new SUBSCRIBE(ImmutableList.copyOf(Lists.newArrayList(topic)), 10);

    channel.writeInbound(subscribe);

    final Queue<Object> objects = channel.outboundMessages();

    assertEquals(1, objects.size());

    final SUBACK response = (SUBACK) objects.element();
    assertEquals(1, response.getReasonCodes().size());
    assertEquals((byte) QoS.AT_LEAST_ONCE.getQosNumber(), response.getReasonCodes().get(0).getCode());

    verify(clientSessionSubscriptionPersistence).addSubscription(eq("client"), same(topic));
}
 
Example 11
Source File: UnsubscribeHandlerTest.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Test
public void test_unsubscribe_batched_and_acknowledge() {

    final String topic1 = "myTopic1";
    final String topic2 = "myTopic2";
    final String topic3 = "myTopic3";
    final List<String> aList = newArrayList();
    aList.add(topic1);
    aList.add(topic2);
    aList.add(topic3);

    final UNSUBSCRIBE unsubscribe = new UNSUBSCRIBE(aList, 10);

    channel.writeInbound(unsubscribe);

    final Queue<Object> objects = channel.outboundMessages();

    assertEquals(1, objects.size());

    final UNSUBACK response = (UNSUBACK) objects.element();
    assertEquals(10, response.getPacketIdentifier());

    verify(clientSessionSubscriptionPersistence).removeSubscriptions(eq("myTestClient"), any(ImmutableSet.class));


}
 
Example 12
Source File: UnsubscribeHandlerTest.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Test
public void test_unsubscribe_single_and_acknowledge_error_mqtt5() {

    when(clientSessionSubscriptionPersistence.remove(anyString(), any(String.class))).thenReturn(Futures.immediateFailedFuture(new NullPointerException("something is missing")));

    channel.attr(ChannelAttributes.MQTT_VERSION).set(ProtocolVersion.MQTTv5);

    final String topic = "myTopic";
    final UNSUBSCRIBE unsubscribe = new UNSUBSCRIBE(Lists.newArrayList(topic), 10);

    channel.writeInbound(unsubscribe);

    final Queue<Object> objects = channel.outboundMessages();

    assertEquals(1, objects.size());

    final UNSUBACK response = (UNSUBACK) objects.element();
    assertEquals(10, response.getPacketIdentifier());
    assertEquals(1, response.getReasonCodes().size());
    assertEquals(Mqtt5UnsubAckReasonCode.UNSPECIFIED_ERROR, response.getReasonCodes().get(0));

    verify(clientSessionSubscriptionPersistence).remove("myTestClient", topic);

}
 
Example 13
Source File: SubscribeHandlerTest.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Test
public void test_shared_subscription_disabled_mqtt3_1_1() {
    when(mqttConfigurationService.sharedSubscriptionsEnabled()).thenReturn(false);

    channel.attr(ChannelAttributes.MQTT_VERSION).set(ProtocolVersion.MQTTv3_1_1);

    final Topic topic = new Topic("$share/group1/topic1", QoS.EXACTLY_ONCE);

    final SUBSCRIBE subscribe = new SUBSCRIBE(ImmutableList.copyOf(Lists.newArrayList(topic)), 10);

    channel.writeInbound(subscribe);

    final Queue<Object> objects = channel.outboundMessages();

    assertEquals(1, objects.size());

    final SUBACK response = (SUBACK) objects.element();
    assertEquals(1, response.getReasonCodes().size());
    assertEquals(Mqtt5SubAckReasonCode.UNSPECIFIED_ERROR.getCode(), response.getReasonCodes().get(0).getCode());

    verify(clientSessionSubscriptionPersistence, never()).addSubscriptions(any(), any());
}
 
Example 14
Source File: TestNTGCodecPositive.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
private void testRoundTrip(IMessage message, IDictionaryStructure dictionary) {
	try
	{
           IMessageStructure msgStruct = dictionary.getMessages().get(message.getName());

		Assert.assertNotNull("Message structure is null.", msgStruct);

           NTGCodec encodeCodec = new NTGCodec();

		encodeCodec.init(serviceContext, null, DefaultMessageFactory.getFactory(), dictionary);

           ProtocolEncoderOutput output = new TestNTGHelper().new MockProtocolEncoderOutput();
			encodeCodec.encode(new DummySession(), message, output);

		Queue<Object> msgQueue = ((AbstractProtocolEncoderOutput) output).getMessageQueue();

		Assert.assertNotNull("Message queue from AbstractProtocolEncoderOutput.", msgQueue);
           Assert.assertTrue("Message queue size must be equal 1.", msgQueue.size() == 1);

		Object lastMessage = msgQueue.element();

		if (lastMessage instanceof IoBuffer) {
               NTGCodec decodeCodec = new NTGCodec();
			decodeCodec.init(serviceContext, null, DefaultMessageFactory.getFactory(), dictionary);
			AbstractProtocolDecoderOutput decoderOutput = new MockProtocolDecoderOutput();

			IoBuffer toDecode = IoBuffer.wrap( new byte[0] );
			toDecode.setAutoExpand(true);
			toDecode.put(((IoBuffer)lastMessage).array());
			//IoBuffer.wrap( Arrays.copyOf(((IoBuffer)lastMessage).array(), ((IoBuffer)lastMessage).limit() ));
			toDecode.compact();
			toDecode.order(ByteOrder.LITTLE_ENDIAN);

			IoSession decodeSession = new DummySession();
			boolean decodableResult = decodeCodec.decodable(decodeSession, toDecode);
			decoderOutput = new MockProtocolDecoderOutput();

			Assert.assertTrue("Test for decoding error.", decodableResult);

			boolean decodeResult = decodeCodec.doDecode(decodeSession, toDecode, decoderOutput);
			Assert.assertTrue("Decoding error.", decodeResult);

               Assert.assertTrue("Message queue size must not less then 1.", decoderOutput.getMessageQueue().size() >= 1);
			Object decodedMessage = decoderOutput.getMessageQueue().element();

			Assert.assertTrue( "Object must be instance of IMessage.", decodedMessage instanceof IMessage);
			Assert.assertTrue( "Object must be instance of MapMessage.", decodedMessage instanceof MapMessage);
               Assert.assertTrue("Messages must be equal. Original message:" + JsonMessageConverter.toJson(message, dictionary) + "; "
                       + "result message:" + JsonMessageConverter.toJson((IMessage)decodedMessage, dictionary),
                       message.compare((MapMessage) decodedMessage));
		}
	}
	catch (Exception e)
	{
	    logger.error(e.getMessage(), e);
		Assert.fail(ErrorUtil.formatException(e));
	}
}
 
Example 15
Source File: SubscribeHandlerTest.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Test
public void test_subscribe_wildcard_disabled_mqtt3_1_1() {
    when(mqttConfigurationService.wildcardSubscriptionsEnabled()).thenReturn(false);
    channel.attr(ChannelAttributes.MQTT_VERSION).set(ProtocolVersion.MQTTv3_1_1);

    final Topic topic = new Topic("#", QoS.EXACTLY_ONCE);

    final SUBSCRIBE subscribe = new SUBSCRIBE(ImmutableList.copyOf(Lists.newArrayList(topic)), 10);

    channel.writeInbound(subscribe);

    final Queue<Object> objects = channel.outboundMessages();

    assertEquals(1, objects.size());

    final SUBACK response = (SUBACK) objects.element();
    assertEquals(1, response.getReasonCodes().size());
    assertEquals(Mqtt5SubAckReasonCode.UNSPECIFIED_ERROR.getCode(), response.getReasonCodes().get(0).getCode());

    verify(clientSessionSubscriptionPersistence, never()).addSubscriptions(any(), any());
}
 
Example 16
Source File: TestFastCodec.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Test
public void testDecodeFastMessage() throws Exception {

    String dictName = "FAST";
    SailfishURI dictUri = SailfishURI.unsafeParse(CORE_ALIAS + ":" + dictName);
    FASTCodec codec = getCodec(dictUri, dictName);

    byte[] sourceArray = { (byte) 0xab, (byte) 0xc0, (byte) 0x83, 0x42, (byte) 0xd7, 0x32, 0x30, 0x31, 0x36, 0x30, 0x32, 0x31, 0x30,
            0x2d, 0x30, 0x37, 0x3a, 0x31, 0x30, 0x3a, 0x30, 0x36, 0x2e, 0x31, 0x39, (byte) 0xb3, 0x36, 0x30, 0x36, 0x36, 0x36, (byte) 0xb0,
            (byte) 0x80, (byte) 0x82, (byte) 0x82, (byte) 0xc0, (byte) 0x87, 0x54, 0x4d, (byte) 0xd0, 0x21, (byte) 0xe9, 0x21, (byte) 0xee};

    IoBuffer toDecode = IoBuffer.wrap(sourceArray);
    toDecode.order(ByteOrder.LITTLE_ENDIAN);
    toDecode.position(0);

    IoSession decodeSession = new DummySession();

    MockProtocolDecoderOutput decoderOutput = new MockProtocolDecoderOutput();
    boolean decodableResult = codec.doDecode(decodeSession, toDecode, decoderOutput);
    Assert.assertTrue("Decoding error.", decodableResult);

    IMessage message = DefaultMessageFactory.getFactory().createMessage("ApplicationMessageRequest", "fast");
    message.addField("MsgType", "BW");
    message.addField("SendingTime", "20160210-07:10:06.193");
    message.addField("ApplReqID", "606660");
    message.addField("ApplReqType", 0L);
    message.addField("NoApplIDs", 1L);
    List<IMessage> list = new ArrayList<>();
    IMessage subMessage = DefaultMessageFactory.getFactory().createMessage("ApplicationMessageRequest_IndicesRequestEntries", "fast");
    subMessage.addField("RefApplID", "TMP");
    subMessage.addField("Reserved1", 6L);
    subMessage.addField("ApplBegSeqNum", 4328L);
    subMessage.addField("ApplEndSeqNum", 4333L);

    list.add(subMessage);
    message.addField("IndicesRequestEntries", list);

    AbstractProtocolEncoderOutput output = new MockProtocolEncoderOutput();

    session.write(message);
    codec.encode(session, message, output);
    Queue<Object> msgQueue = output.getMessageQueue();
    Object lastMessage = msgQueue.element();
    byte[] asd = ((IoBuffer) lastMessage).array();
    int limit = ((IoBuffer) lastMessage).limit();
    byte[] bytes = Arrays.copyOf(asd, limit);

    session.write(lastMessage);
    Assert.assertArrayEquals("Compare source and encoded\n" + HexDumper.getHexdump(bytes), sourceArray, bytes);
}
 
Example 17
Source File: SubscribeHandlerTest.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Test
public void test_subscribe_batched_to_batched_with_same_filter_and_acknowledge() throws Exception {


    final Topic topic1 = new Topic("test1", QoS.EXACTLY_ONCE);
    final Topic topic2 = new Topic("test2", QoS.AT_LEAST_ONCE);
    final Topic topic3 = new Topic("test2", QoS.AT_MOST_ONCE);

    final SUBSCRIBE subscribe = new SUBSCRIBE(ImmutableList.copyOf(Lists.newArrayList(topic1, topic2, topic3)), 10);

    final ImmutableSet<Topic> persistedTopics = ImmutableSet.of(topic1, topic3);

    channel.writeInbound(subscribe);

    final Queue<Object> objects = channel.outboundMessages();

    assertEquals(1, objects.size());

    final SUBACK response = (SUBACK) objects.element();
    assertEquals(3, response.getReasonCodes().size());
    assertEquals((byte) QoS.EXACTLY_ONCE.getQosNumber(), response.getReasonCodes().get(0).getCode());
    assertEquals((byte) QoS.AT_LEAST_ONCE.getQosNumber(), response.getReasonCodes().get(1).getCode());
    assertEquals((byte) QoS.AT_MOST_ONCE.getQosNumber(), response.getReasonCodes().get(2).getCode());

    verify(clientSessionSubscriptionPersistence).addSubscriptions(eq("client"), eq(persistedTopics));
}
 
Example 18
Source File: SubscribeHandlerTest.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Test
public void test_subscribe_batched_to_non_batched_with_same_filter_and_acknowledge() throws Exception {


    final Topic topic1 = new Topic("test", QoS.EXACTLY_ONCE);
    final Topic topic2 = new Topic("test", QoS.AT_LEAST_ONCE);
    final Topic topic3 = new Topic("test", QoS.AT_MOST_ONCE);

    final SUBSCRIBE subscribe = new SUBSCRIBE(ImmutableList.copyOf(Lists.newArrayList(topic1, topic2, topic3)), 10);

    channel.writeInbound(subscribe);

    final Queue<Object> objects = channel.outboundMessages();

    assertEquals(1, objects.size());

    final SUBACK response = (SUBACK) objects.element();
    assertEquals(3, response.getReasonCodes().size());
    assertEquals((byte) QoS.EXACTLY_ONCE.getQosNumber(), response.getReasonCodes().get(0).getCode());
    assertEquals((byte) QoS.AT_LEAST_ONCE.getQosNumber(), response.getReasonCodes().get(1).getCode());
    assertEquals((byte) QoS.AT_MOST_ONCE.getQosNumber(), response.getReasonCodes().get(2).getCode());

    verify(clientSessionSubscriptionPersistence).addSubscription(eq("client"), same(topic3));
}
 
Example 19
Source File: TestNTGCodecNegative.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
/**
 * Negative test encode Heartbeat message with StartOfMessage=3 and decode it after
 */
@Test
public void testWrongMessage(){
       IMessage message = DefaultMessageFactory.getFactory().createMessage("Heartbeat", "NTG");
       IMessage messageHeader = DefaultMessageFactory.getFactory().createMessage("MessageHeader", "NTG");
	messageHeader.addField("StartOfMessage", 3);
	messageHeader.addField("MessageLength", 9);
	messageHeader.addField("MessageType", "2");
	message.addField("MessageHeader", messageHeader);
	try{
           IDictionaryStructure dictionary = TestNTGHelper.getDictionary();
           IMessageStructure msgStruct = dictionary.getMessages().get(message.getName());
		Assert.assertNotNull("Message structure is null.", msgStruct);
           NTGCodec encodeCodec = new NTGCodec();
		encodeCodec.init(serviceContext, null, DefaultMessageFactory.getFactory(), dictionary);
           ProtocolEncoderOutput output = new TestNTGHelper().new MockProtocolEncoderOutput();
 		encodeCodec.encode(new DummySession(), message, output);

		Queue<Object> msgQueue = ((AbstractProtocolEncoderOutput) output).getMessageQueue();

		Assert.assertNotNull("Message queue from AbstractProtocolEncoderOutput.", msgQueue);
           Assert.assertTrue("Message queue size must be equal 1.", msgQueue.size() == 1);

		Object lastMessage = msgQueue.element();

		if (lastMessage instanceof IoBuffer) {
               NTGCodec decodeCodec = new NTGCodec();
			decodeCodec.init(serviceContext, null, DefaultMessageFactory.getFactory(), dictionary);
			IoBuffer toDecode = IoBuffer.wrap( new byte[0] );
			toDecode.setAutoExpand(true);
			toDecode.put(((IoBuffer)lastMessage).array());
			toDecode.compact();
			toDecode.order(ByteOrder.LITTLE_ENDIAN);

			IoSession decodeSession = new DummySession();
			decodeCodec.decodable(decodeSession, toDecode);
			Assert.fail("Exception hasn't been thrown");
		}
	}catch(Exception e){
		Assert.assertEquals("Unexpected start of message: 3", e.getMessage());
	}

}
 
Example 20
Source File: SubscribeHandlerTest.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Test
public void test_subscribe_three_and_acknowledge() throws Exception {


    final Topic topic1 = new Topic("test1", QoS.AT_LEAST_ONCE);
    final Topic topic2 = new Topic("test2", QoS.AT_MOST_ONCE);
    final Topic topic3 = new Topic("test3", QoS.EXACTLY_ONCE);

    final SUBSCRIBE subscribe = new SUBSCRIBE(ImmutableList.copyOf(Lists.newArrayList(topic1, topic2, topic3)), 10);

    channel.writeInbound(subscribe);

    final Queue<Object> objects = channel.outboundMessages();

    assertEquals(1, objects.size());

    final SUBACK response = (SUBACK) objects.element();
    assertEquals(3, response.getReasonCodes().size());
    assertEquals((byte) QoS.AT_LEAST_ONCE.getQosNumber(), response.getReasonCodes().get(0).getCode());
    assertEquals((byte) QoS.AT_MOST_ONCE.getQosNumber(), response.getReasonCodes().get(1).getCode());
    assertEquals((byte) QoS.EXACTLY_ONCE.getQosNumber(), response.getReasonCodes().get(2).getCode());

    verify(clientSessionSubscriptionPersistence).addSubscriptions(eq("client"), any(ImmutableSet.class));
}