Search in sources :

Example 81 with Handler

use of io.vertx.core.Handler 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 82 with Handler

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

the class DnsClientImpl method reverseLookup.

@Override
public DnsClient reverseLookup(String address, Handler<AsyncResult<String>> handler) {
    //        An other option would be to change address to be of type InetAddress.
    try {
        InetAddress inetAddress = InetAddress.getByName(address);
        byte[] addr = inetAddress.getAddress();
        StringBuilder reverseName = new StringBuilder(64);
        if (inetAddress instanceof Inet4Address) {
            // reverse ipv4 address
            reverseName.append(addr[3] & 0xff).append(".").append(addr[2] & 0xff).append(".").append(addr[1] & 0xff).append(".").append(addr[0] & 0xff);
        } else {
            // It is an ipv 6 address time to reverse it
            for (int i = 0; i < 16; i++) {
                reverseName.append(HEX_TABLE[(addr[15 - i] & 0xf)]);
                reverseName.append(".");
                reverseName.append(HEX_TABLE[(addr[15 - i] >> 4) & 0xf]);
                if (i != 15) {
                    reverseName.append(".");
                }
            }
        }
        reverseName.append(".in-addr.arpa");
        return resolvePTR(reverseName.toString(), handler);
    } catch (UnknownHostException e) {
        // Should never happen as we work with ip addresses as input
        // anyway just in case notify the handler
        actualCtx.runOnContext((v) -> handler.handle(Future.failedFuture(e)));
    }
    return this;
}
Also used : DatagramDnsQueryEncoder(io.netty.handler.codec.dns.DatagramDnsQueryEncoder) DnsRecord(io.netty.handler.codec.dns.DnsRecord) DnsResponse(io.netty.handler.codec.dns.DnsResponse) DnsException(io.vertx.core.dns.DnsException) ChannelOption(io.netty.channel.ChannelOption) ContextImpl(io.vertx.core.impl.ContextImpl) DefaultDnsQuestion(io.netty.handler.codec.dns.DefaultDnsQuestion) SrvRecord(io.vertx.core.dns.SrvRecord) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DatagramChannel(io.netty.channel.socket.DatagramChannel) DnsSection(io.netty.handler.codec.dns.DnsSection) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) DnsResponseCode(io.vertx.core.dns.DnsResponseCode) AsyncResult(io.vertx.core.AsyncResult) DnsRecordType(io.netty.handler.codec.dns.DnsRecordType) VertxInternal(io.vertx.core.impl.VertxInternal) ChannelInitializer(io.netty.channel.ChannelInitializer) DatagramDnsQuery(io.netty.handler.codec.dns.DatagramDnsQuery) PartialPooledByteBufAllocator(io.vertx.core.net.impl.PartialPooledByteBufAllocator) ChannelPipeline(io.netty.channel.ChannelPipeline) Future(io.vertx.core.Future) Inet4Address(java.net.Inet4Address) InetSocketAddress(java.net.InetSocketAddress) UnknownHostException(java.net.UnknownHostException) RecordDecoder(io.vertx.core.dns.impl.decoder.RecordDecoder) ChannelFuture(io.netty.channel.ChannelFuture) DnsClient(io.vertx.core.dns.DnsClient) Objects(java.util.Objects) Bootstrap(io.netty.bootstrap.Bootstrap) List(java.util.List) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) DatagramDnsResponseDecoder(io.netty.handler.codec.dns.DatagramDnsResponseDecoder) MxRecord(io.vertx.core.dns.MxRecord) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) InetAddress(java.net.InetAddress)

Example 83 with Handler

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

the class HttpServerResponseImpl method doSendFile.

private void doSendFile(String filename, long offset, long length, Handler<AsyncResult<Void>> resultHandler) {
    synchronized (conn) {
        if (headWritten) {
            throw new IllegalStateException("Head already written");
        }
        checkWritten();
        File file = vertx.resolveFile(filename);
        if (!file.exists()) {
            if (resultHandler != null) {
                ContextImpl ctx = vertx.getOrCreateContext();
                ctx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(new FileNotFoundException())));
            } else {
                log.error("File not found: " + filename);
            }
            return;
        }
        long contentLength = Math.min(length, file.length() - offset);
        bytesWritten = contentLength;
        if (!contentLengthSet()) {
            putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength));
        }
        if (!contentTypeSet()) {
            String contentType = MimeMapping.getMimeTypeForFilename(filename);
            if (contentType != null) {
                putHeader(HttpHeaders.CONTENT_TYPE, contentType);
            }
        }
        prepareHeaders();
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "r");
            conn.queueForWrite(response);
            conn.sendFile(raf, Math.min(offset, file.length()), contentLength);
        } catch (IOException e) {
            try {
                if (raf != null) {
                    raf.close();
                }
            } catch (IOException ignore) {
            }
            if (resultHandler != null) {
                ContextImpl ctx = vertx.getOrCreateContext();
                ctx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(e)));
            } else {
                log.error("Failed to send file", e);
            }
            return;
        }
        // write an empty last content to let the http encoder know the response is complete
        channelFuture = conn.writeToChannel(LastHttpContent.EMPTY_LAST_CONTENT);
        written = true;
        if (resultHandler != null) {
            ContextImpl ctx = vertx.getOrCreateContext();
            channelFuture.addListener(future -> {
                AsyncResult<Void> res;
                if (future.isSuccess()) {
                    res = Future.succeededFuture();
                } else {
                    res = Future.failedFuture(future.cause());
                }
                ctx.runOnContext((v) -> resultHandler.handle(res));
            });
        }
        if (!keepAlive) {
            closeConnAfterWrite();
        }
        conn.responseComplete();
        if (bodyEndHandler != null) {
            bodyEndHandler.handle(null);
        }
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) HttpVersion(io.netty.handler.codec.http.HttpVersion) VertxInternal(io.vertx.core.impl.VertxInternal) ContextImpl(io.vertx.core.impl.ContextImpl) MultiMap(io.vertx.core.MultiMap) HttpHeaders(io.vertx.core.http.HttpHeaders) IOException(java.io.IOException) Future(io.vertx.core.Future) io.vertx.core.http(io.vertx.core.http) LoggerFactory(io.vertx.core.logging.LoggerFactory) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) Unpooled(io.netty.buffer.Unpooled) ChannelFuture(io.netty.channel.ChannelFuture) Nullable(io.vertx.codegen.annotations.Nullable) io.netty.handler.codec.http(io.netty.handler.codec.http) ByteBuf(io.netty.buffer.ByteBuf) Buffer(io.vertx.core.buffer.Buffer) HttpMethod(io.vertx.core.http.HttpMethod) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) Logger(io.vertx.core.logging.Logger) RandomAccessFile(java.io.RandomAccessFile) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) ContextImpl(io.vertx.core.impl.ContextImpl) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 84 with Handler

use of io.vertx.core.Handler 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 85 with Handler

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

the class AsyncFileImpl method doWrite.

private synchronized AsyncFile doWrite(Buffer buffer, long position, Handler<AsyncResult<Void>> handler) {
    Objects.requireNonNull(buffer, "buffer");
    Arguments.require(position >= 0, "position must be >= 0");
    check();
    Handler<AsyncResult<Void>> wrapped = ar -> {
        if (ar.succeeded()) {
            checkContext();
            if (writesOutstanding == 0 && closedDeferred != null) {
                closedDeferred.run();
            } else {
                checkDrained();
            }
            if (handler != null) {
                handler.handle(ar);
            }
        } else {
            if (handler != null) {
                handler.handle(ar);
            } else {
                handleException(ar.cause());
            }
        }
    };
    ByteBuf buf = buffer.getByteBuf();
    if (buf.nioBufferCount() > 1) {
        doWrite(buf.nioBuffers(), position, wrapped);
    } else {
        ByteBuffer bb = buf.nioBuffer();
        doWrite(bb, position, bb.limit(), wrapped);
    }
    return this;
}
Also used : AsyncFile(io.vertx.core.file.AsyncFile) ContextImpl(io.vertx.core.impl.ContextImpl) Arguments(io.vertx.core.impl.Arguments) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AsynchronousFileChannel(java.nio.channels.AsynchronousFileChannel) FileSystemException(io.vertx.core.file.FileSystemException) LoggerFactory(io.vertx.core.logging.LoggerFactory) ByteBuffer(java.nio.ByteBuffer) HashSet(java.util.HashSet) PosixFilePermissions(java.nio.file.attribute.PosixFilePermissions) ByteBuf(io.netty.buffer.ByteBuf) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AsyncResult(io.vertx.core.AsyncResult) Logger(io.vertx.core.logging.Logger) Path(java.nio.file.Path) VertxInternal(io.vertx.core.impl.VertxInternal) OpenOptions(io.vertx.core.file.OpenOptions) OpenOption(java.nio.file.OpenOption) StandardOpenOption(java.nio.file.StandardOpenOption) IOException(java.io.IOException) FileAttribute(java.nio.file.attribute.FileAttribute) Future(io.vertx.core.Future) Objects(java.util.Objects) Buffer(io.vertx.core.buffer.Buffer) Paths(java.nio.file.Paths) Handler(io.vertx.core.Handler) ByteBuf(io.netty.buffer.ByteBuf) AsyncResult(io.vertx.core.AsyncResult) ByteBuffer(java.nio.ByteBuffer)

Aggregations

Handler (io.vertx.core.Handler)119 Test (org.junit.Test)78 Future (io.vertx.core.Future)67 Vertx (io.vertx.core.Vertx)59 AsyncResult (io.vertx.core.AsyncResult)57 Context (io.vertx.core.Context)52 Buffer (io.vertx.core.buffer.Buffer)48 Async (io.vertx.ext.unit.Async)41 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)39 Map (java.util.Map)38 TestContext (io.vertx.ext.unit.TestContext)37 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)36 RunWith (org.junit.runner.RunWith)36 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)34 Collections (java.util.Collections)33 JsonObject (io.vertx.core.json.JsonObject)31 HttpURLConnection (java.net.HttpURLConnection)31 Before (org.junit.Before)31 StandardCharsets (java.nio.charset.StandardCharsets)29 TimeUnit (java.util.concurrent.TimeUnit)29