Search in sources :

Example 26 with NetSocket

use of io.vertx.core.net.NetSocket in project vert.x by eclipse.

the class NetSocketImpl method sendFile.

@Override
public NetSocket sendFile(String filename, long offset, long length, final Handler<AsyncResult<Void>> resultHandler) {
    File f = vertx.resolveFile(filename);
    if (f.isDirectory()) {
        throw new IllegalArgumentException("filename must point to a file and not to a directory");
    }
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(f, "r");
        ChannelFuture future = super.sendFile(raf, Math.min(offset, f.length()), Math.min(length, f.length() - offset));
        if (resultHandler != null) {
            future.addListener(fut -> {
                final AsyncResult<Void> res;
                if (future.isSuccess()) {
                    res = Future.succeededFuture();
                } else {
                    res = Future.failedFuture(future.cause());
                }
                vertx.runOnContext(v -> resultHandler.handle(res));
            });
        }
    } catch (IOException e) {
        try {
            if (raf != null) {
                raf.close();
            }
        } catch (IOException ignore) {
        }
        if (resultHandler != null) {
            vertx.runOnContext(v -> resultHandler.handle(Future.failedFuture(e)));
        } else {
            log.error("Failed to send file", e);
        }
    }
    return this;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) RandomAccessFile(java.io.RandomAccessFile) ContextImpl(io.vertx.core.impl.ContextImpl) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) NetworkMetrics(io.vertx.core.spi.metrics.NetworkMetrics) LoggerFactory(io.vertx.core.logging.LoggerFactory) Unpooled(io.netty.buffer.Unpooled) ByteBuf(io.netty.buffer.ByteBuf) Charset(java.nio.charset.Charset) ChannelFutureListener(io.netty.channel.ChannelFutureListener) CharsetUtil(io.netty.util.CharsetUtil) AsyncResult(io.vertx.core.AsyncResult) Logger(io.vertx.core.logging.Logger) SocketAddress(io.vertx.core.net.SocketAddress) VertxInternal(io.vertx.core.impl.VertxInternal) Message(io.vertx.core.eventbus.Message) IOException(java.io.IOException) UUID(java.util.UUID) X509Certificate(javax.security.cert.X509Certificate) Future(io.vertx.core.Future) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Handler(io.vertx.core.Handler) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) NetSocket(io.vertx.core.net.NetSocket) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) RandomAccessFile(java.io.RandomAccessFile) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 27 with NetSocket

use of io.vertx.core.net.NetSocket in project vert.x by eclipse.

the class VertxHttp2NetSocket method sendFile.

@Override
public NetSocket sendFile(String filename, long offset, long length, Handler<AsyncResult<Void>> resultHandler) {
    synchronized (conn) {
        Context resultCtx = resultHandler != null ? vertx.getOrCreateContext() : null;
        File file = vertx.resolveFile(filename);
        if (!file.exists()) {
            if (resultHandler != null) {
                resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(new FileNotFoundException())));
            } else {
            // log.error("File not found: " + filename);
            }
            return this;
        }
        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(file, "r");
        } catch (IOException e) {
            if (resultHandler != null) {
                resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(e)));
            } else {
            //log.error("Failed to send file", e);
            }
            return this;
        }
        long contentLength = Math.min(length, file.length() - offset);
        FileStreamChannel fileChannel = new FileStreamChannel(ar -> {
            if (resultHandler != null) {
                resultCtx.runOnContext(v -> {
                    resultHandler.handle(Future.succeededFuture());
                });
            }
        }, this, offset, contentLength);
        drainHandler(fileChannel.drainHandler);
        handlerContext.channel().eventLoop().register(fileChannel);
        fileChannel.pipeline().fireUserEventTriggered(raf);
    }
    return this;
}
Also used : Context(io.vertx.core.Context) RandomAccessFile(java.io.RandomAccessFile) MultiMap(io.vertx.core.MultiMap) IOException(java.io.IOException) X509Certificate(javax.security.cert.X509Certificate) Context(io.vertx.core.Context) Future(io.vertx.core.Future) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) Unpooled(io.netty.buffer.Unpooled) Nullable(io.vertx.codegen.annotations.Nullable) Buffer(io.vertx.core.buffer.Buffer) Charset(java.nio.charset.Charset) Http2Stream(io.netty.handler.codec.http2.Http2Stream) CharsetUtil(io.netty.util.CharsetUtil) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) StreamResetException(io.vertx.core.http.StreamResetException) NetSocket(io.vertx.core.net.NetSocket) SocketAddress(io.vertx.core.net.SocketAddress) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) RandomAccessFile(java.io.RandomAccessFile) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 28 with NetSocket

use of io.vertx.core.net.NetSocket in project java-chassis by ServiceComb.

the class TestHighwayServerConnection method testRequestNormal.

@Test
public void testRequestNormal() throws Exception {
    header.setMsgType(MsgType.REQUEST);
    Buffer headerBuffer = createBuffer(requestHeaderSchema, header);
    Buffer bodyBuffer = Buffer.buffer();
    Holder<Boolean> holder = new Holder<>();
    new MockUp<HighwayServerInvoke>() {

        @Mock
        public boolean init(NetSocket netSocket, long msgId, RequestHeader header, Buffer bodyBuffer) {
            return true;
        }

        @Mock
        public void execute() {
            holder.value = true;
        }
    };
    connection.handle(0, headerBuffer, bodyBuffer);
    Assert.assertEquals(null, connection.getProtocol());
    Assert.assertEquals(null, connection.getZipName());
    Assert.assertEquals(true, holder.value);
}
Also used : LinkedBuffer(io.protostuff.LinkedBuffer) Buffer(io.vertx.core.buffer.Buffer) NetSocket(io.vertx.core.net.NetSocket) Holder(javax.xml.ws.Holder) RequestHeader(io.servicecomb.transport.highway.message.RequestHeader) MockUp(mockit.MockUp) Test(org.junit.Test)

Example 29 with NetSocket

use of io.vertx.core.net.NetSocket in project vertx-tcp-eventbus-bridge by vert-x3.

the class TcpEventBusBridgeTest method testNoHandlers.

@Test
public void testNoHandlers(TestContext context) {
    // Send a request and get a response
    NetClient client = vertx.createNetClient();
    final Async async = context.async();
    client.connect(7000, "localhost", conn -> {
        context.assertFalse(conn.failed());
        NetSocket socket = conn.result();
        final FrameParser parser = new FrameParser(parse -> {
            context.assertTrue(parse.succeeded());
            JsonObject frame = parse.result();
            context.assertEquals("err", frame.getString("type"));
            context.assertEquals("#backtrack", frame.getString("address"));
            client.close();
            async.complete();
        });
        socket.handler(parser);
        FrameHelper.sendFrame("send", "test", "#backtrack", new JsonObject().put("value", "vert.x"), socket);
    });
}
Also used : NetSocket(io.vertx.core.net.NetSocket) NetClient(io.vertx.core.net.NetClient) Async(io.vertx.ext.unit.Async) JsonObject(io.vertx.core.json.JsonObject) FrameParser(io.vertx.ext.eventbus.bridge.tcp.impl.protocol.FrameParser) Test(org.junit.Test)

Example 30 with NetSocket

use of io.vertx.core.net.NetSocket in project vertx-tcp-eventbus-bridge by vert-x3.

the class TcpEventBusBridgeTest method testSendMessageWithDuplicateReplyID.

@Test
public void testSendMessageWithDuplicateReplyID(TestContext context) {
    // replies must always return to the same origin
    NetClient client = vertx.createNetClient();
    final Async async = context.async();
    client.connect(7000, "localhost", conn -> {
        context.assertFalse(conn.failed());
        NetSocket socket = conn.result();
        vertx.eventBus().consumer("third-party-receiver", msg -> context.fail());
        final FrameParser parser = new FrameParser(parse -> {
            context.assertTrue(parse.succeeded());
            client.close();
            async.complete();
        });
        socket.handler(parser);
        FrameHelper.sendFrame("send", "hello", "third-party-receiver", new JsonObject().put("value", "vert.x"), socket);
    });
}
Also used : NetSocket(io.vertx.core.net.NetSocket) NetClient(io.vertx.core.net.NetClient) Async(io.vertx.ext.unit.Async) JsonObject(io.vertx.core.json.JsonObject) FrameParser(io.vertx.ext.eventbus.bridge.tcp.impl.protocol.FrameParser) Test(org.junit.Test)

Aggregations

NetSocket (io.vertx.core.net.NetSocket)33 Test (org.junit.Test)23 NetClient (io.vertx.core.net.NetClient)16 Buffer (io.vertx.core.buffer.Buffer)14 Handler (io.vertx.core.Handler)13 Async (io.vertx.ext.unit.Async)11 Vertx (io.vertx.core.Vertx)10 JsonObject (io.vertx.core.json.JsonObject)10 AsyncResult (io.vertx.core.AsyncResult)9 Context (io.vertx.core.Context)9 Future (io.vertx.core.Future)9 FrameParser (io.vertx.ext.eventbus.bridge.tcp.impl.protocol.FrameParser)9 ByteBuf (io.netty.buffer.ByteBuf)7 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7 Unpooled (io.netty.buffer.Unpooled)6 Channel (io.netty.channel.Channel)6 SslHandler (io.netty.handler.ssl.SslHandler)6 MultiMap (io.vertx.core.MultiMap)6 VertxInternal (io.vertx.core.impl.VertxInternal)6 NetClientOptions (io.vertx.core.net.NetClientOptions)6