Search in sources :

Example 41 with IoBuffer

use of org.apache.mina.core.buffer.IoBuffer in project netty by netty.

the class DnsNameResolverTest method testTruncated0.

private static void testTruncated0(boolean tcpFallback, final boolean truncatedBecauseOfMtu) throws IOException {
    final String host = "somehost.netty.io";
    final String txt = "this is a txt record";
    final AtomicReference<DnsMessage> messageRef = new AtomicReference<DnsMessage>();
    TestDnsServer dnsServer2 = new TestDnsServer(new RecordStore() {

        @Override
        public Set<ResourceRecord> getRecords(QuestionRecord question) {
            String name = question.getDomainName();
            if (name.equals(host)) {
                return Collections.<ResourceRecord>singleton(new TestDnsServer.TestResourceRecord(name, RecordType.TXT, Collections.<String, Object>singletonMap(DnsAttribute.CHARACTER_STRING.toLowerCase(), txt)));
            }
            return null;
        }
    }) {

        @Override
        protected DnsMessage filterMessage(DnsMessage message) {
            // Store a original message so we can replay it later on.
            messageRef.set(message);
            if (!truncatedBecauseOfMtu) {
                // Create a copy of the message but set the truncated flag.
                DnsMessageModifier modifier = modifierFrom(message);
                modifier.setTruncated(true);
                return modifier.getDnsMessage();
            }
            return message;
        }
    };
    dnsServer2.start();
    DnsNameResolver resolver = null;
    ServerSocket serverSocket = null;
    try {
        DnsNameResolverBuilder builder = newResolver().queryTimeoutMillis(10000).resolvedAddressTypes(ResolvedAddressTypes.IPV4_PREFERRED).maxQueriesPerResolve(16).nameServerProvider(new SingletonDnsServerAddressStreamProvider(dnsServer2.localAddress()));
        if (tcpFallback) {
            // If we are configured to use TCP as a fallback also bind a TCP socket
            serverSocket = new ServerSocket();
            serverSocket.setReuseAddress(true);
            serverSocket.bind(new InetSocketAddress(dnsServer2.localAddress().getPort()));
            builder.socketChannelType(NioSocketChannel.class);
        }
        resolver = builder.build();
        if (truncatedBecauseOfMtu) {
            resolver.ch.pipeline().addFirst(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    if (msg instanceof DatagramPacket) {
                        // Truncate the packet by 1 byte.
                        DatagramPacket packet = (DatagramPacket) msg;
                        packet.content().writerIndex(packet.content().writerIndex() - 1);
                    }
                    ctx.fireChannelRead(msg);
                }
            });
        }
        Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> envelopeFuture = resolver.query(new DefaultDnsQuestion(host, DnsRecordType.TXT));
        if (tcpFallback) {
            // If we are configured to use TCP as a fallback lets replay the dns message over TCP
            Socket socket = serverSocket.accept();
            InputStream in = socket.getInputStream();
            // skip length field
            assertTrue((in.read() << 8 | (in.read() & 0xff)) > 2);
            int txnId = in.read() << 8 | (in.read() & 0xff);
            IoBuffer ioBuffer = IoBuffer.allocate(1024);
            // Must replace the transactionId with the one from the TCP request
            DnsMessageModifier modifier = modifierFrom(messageRef.get());
            modifier.setTransactionId(txnId);
            new DnsMessageEncoder().encode(ioBuffer, modifier.getDnsMessage());
            ioBuffer.flip();
            ByteBuffer lenBuffer = ByteBuffer.allocate(2);
            lenBuffer.putShort((short) ioBuffer.remaining());
            lenBuffer.flip();
            while (lenBuffer.hasRemaining()) {
                socket.getOutputStream().write(lenBuffer.get());
            }
            while (ioBuffer.hasRemaining()) {
                socket.getOutputStream().write(ioBuffer.get());
            }
            socket.getOutputStream().flush();
            // Let's wait until we received the envelope before closing the socket.
            envelopeFuture.syncUninterruptibly();
            socket.close();
            serverSocket.close();
        }
        AddressedEnvelope<DnsResponse, InetSocketAddress> envelope = envelopeFuture.syncUninterruptibly().getNow();
        assertNotNull(envelope.sender());
        DnsResponse response = envelope.content();
        assertNotNull(response);
        assertEquals(DnsResponseCode.NOERROR, response.code());
        int count = response.count(DnsSection.ANSWER);
        assertEquals(1, count);
        List<String> texts = decodeTxt(response.recordAt(DnsSection.ANSWER, 0));
        assertEquals(1, texts.size());
        assertEquals(txt, texts.get(0));
        if (tcpFallback) {
            assertFalse(envelope.content().isTruncated());
        } else {
            assertTrue(envelope.content().isTruncated());
        }
        assertTrue(envelope.release());
    } finally {
        dnsServer2.stop();
        if (resolver != null) {
            resolver.close();
        }
    }
}
Also used : QuestionRecord(org.apache.directory.server.dns.messages.QuestionRecord) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) InetSocketAddress(java.net.InetSocketAddress) DnsMessage(org.apache.directory.server.dns.messages.DnsMessage) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DnsMessageEncoder(org.apache.directory.server.dns.io.encoder.DnsMessageEncoder) DatagramPacket(io.netty.channel.socket.DatagramPacket) DefaultDnsQuestion(io.netty.handler.codec.dns.DefaultDnsQuestion) AddressedEnvelope(io.netty.channel.AddressedEnvelope) InputStream(java.io.InputStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) ServerSocket(java.net.ServerSocket) ByteBuffer(java.nio.ByteBuffer) IoBuffer(org.apache.mina.core.buffer.IoBuffer) RecordStore(org.apache.directory.server.dns.store.RecordStore) DnsResponse(io.netty.handler.codec.dns.DnsResponse) DnsMessageModifier(org.apache.directory.server.dns.messages.DnsMessageModifier) ServerSocket(java.net.ServerSocket) DatagramSocket(java.net.DatagramSocket) Socket(java.net.Socket) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 42 with IoBuffer

use of org.apache.mina.core.buffer.IoBuffer in project directory-ldap-api by apache.

the class LdapProtocolEncoder method encode.

/**
 * {@inheritDoc}
 */
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    ByteBuffer buffer = encoder.encodeMessage((Message) message);
    IoBuffer ioBuffer = IoBuffer.wrap(buffer);
    if (IS_DEBUG) {
        byte[] dumpBuffer = new byte[buffer.limit()];
        buffer.get(dumpBuffer);
        buffer.flip();
        CODEC_LOG.debug(I18n.msg(I18n.MSG_14003_ENCODED_LDAP_MESSAGE, message, Strings.dumpBytes(dumpBuffer)));
    }
    out.write(ioBuffer);
}
Also used : ByteBuffer(java.nio.ByteBuffer) IoBuffer(org.apache.mina.core.buffer.IoBuffer)

Example 43 with IoBuffer

use of org.apache.mina.core.buffer.IoBuffer in project Openfire by igniterealtime.

the class XMLLightweightParserTest method testOF2329SelfTerminatingWithSpace.

/**
 * Asserts that a self-terminating start-tag name can be parsed when it is followed by a space character.
 *
 * This test checks for a variation of the issue described in OF-2329.
 *
 * @see <a href="https://igniterealtime.atlassian.net/browse/OF-2329">OF-2329: XML parsing bug when tag-name is not followed by space or '>'</a>
 */
@Test
public void testOF2329SelfTerminatingWithSpace() throws Exception {
    // Setup test fixture.
    final String input = "<presence to='foo@example.org'/>";
    final IoBuffer buffer = IoBuffer.allocate(input.length(), false);
    buffer.putString(input, StandardCharsets.UTF_8.newEncoder());
    buffer.flip();
    final XMLLightweightParser parser = new XMLLightweightParser(StandardCharsets.UTF_8);
    // Execute system under test.
    parser.read(buffer);
    final String[] result = parser.getMsgs();
    // Verify results.
    assertNotNull(result);
    assertEquals(1, result.length);
}
Also used : IoBuffer(org.apache.mina.core.buffer.IoBuffer) Test(org.junit.Test)

Example 44 with IoBuffer

use of org.apache.mina.core.buffer.IoBuffer in project Openfire by igniterealtime.

the class NIOConnection method deliver.

@Override
public void deliver(Packet packet) throws UnauthorizedException {
    if (isClosed()) {
        if (backupDeliverer != null) {
            backupDeliverer.deliver(packet);
        } else {
            Log.trace("Discarding packet that was due to be delivered on closed connection {}, for which no backup deliverer was configured.", this);
        }
    } else {
        boolean errorDelivering = false;
        IoBuffer buffer = IoBuffer.allocate(4096);
        buffer.setAutoExpand(true);
        try {
            buffer.putString(packet.getElement().asXML(), encoder.get());
            buffer.flip();
            ioSessionLock.lock();
            try {
                ioSession.write(buffer);
            } finally {
                ioSessionLock.unlock();
            }
        } catch (Exception e) {
            Log.debug("Error delivering packet:\n" + packet, e);
            errorDelivering = true;
        }
        if (errorDelivering) {
            close();
            // Message it will be stored offline
            if (backupDeliverer != null) {
                backupDeliverer.deliver(packet);
            } else {
                Log.trace("Discarding packet that failed to be delivered to connection {}, for which no backup deliverer was configured.", this);
            }
        } else {
            session.incrementServerPacketCount();
        }
    }
}
Also used : UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) UnknownHostException(java.net.UnknownHostException) IoBuffer(org.apache.mina.core.buffer.IoBuffer)

Example 45 with IoBuffer

use of org.apache.mina.core.buffer.IoBuffer in project zm-mailbox by Zimbra.

the class MilterHandlerTest method getIoBuffer.

static IoBuffer getIoBuffer(byte[] b) {
    IoBuffer buf = IoBuffer.allocate(b.length, false);
    buf.put(b);
    buf.flip();
    return buf;
}
Also used : IoBuffer(org.apache.mina.core.buffer.IoBuffer)

Aggregations

IoBuffer (org.apache.mina.core.buffer.IoBuffer)49 Test (org.junit.Test)8 VideoData (org.red5.server.net.rtmp.event.VideoData)4 UnknownHostException (java.net.UnknownHostException)3 HashMap (java.util.HashMap)3 UnauthorizedException (org.jivesoftware.openfire.auth.UnauthorizedException)3 AudioData (org.red5.server.net.rtmp.event.AudioData)3 Gson (com.google.gson.Gson)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 ByteBuffer (java.nio.ByteBuffer)2 CharacterCodingException (java.nio.charset.CharacterCodingException)2 Exchange (org.apache.camel.Exchange)2 DefaultCamelContext (org.apache.camel.impl.DefaultCamelContext)2 DefaultExchange (org.apache.camel.impl.DefaultExchange)2 Message (ca.uhn.hl7v2.model.Message)1 AddressedEnvelope (io.netty.channel.AddressedEnvelope)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)1 DatagramPacket (io.netty.channel.socket.DatagramPacket)1