Search in sources :

Example 16 with AsyncResult

use of io.vertx.core.AsyncResult 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 17 with AsyncResult

use of io.vertx.core.AsyncResult 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 18 with AsyncResult

use of io.vertx.core.AsyncResult 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 19 with AsyncResult

use of io.vertx.core.AsyncResult 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)

Example 20 with AsyncResult

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

the class FutureTest method testDefaultCompleter.

@Test
public void testDefaultCompleter() {
    AsyncResult<Object> succeededAsyncResult = new AsyncResult<Object>() {

        Object result = new Object();

        public Object result() {
            return result;
        }

        public Throwable cause() {
            throw new UnsupportedOperationException();
        }

        public boolean succeeded() {
            return true;
        }

        public boolean failed() {
            throw new UnsupportedOperationException();
        }

        public <U> AsyncResult<U> map(Function<Object, U> mapper) {
            throw new UnsupportedOperationException();
        }

        public <V> AsyncResult<V> map(V value) {
            throw new UnsupportedOperationException();
        }
    };
    AsyncResult<Object> failedAsyncResult = new AsyncResult<Object>() {

        Throwable cause = new Throwable();

        public Object result() {
            throw new UnsupportedOperationException();
        }

        public Throwable cause() {
            return cause;
        }

        public boolean succeeded() {
            return false;
        }

        public boolean failed() {
            throw new UnsupportedOperationException();
        }

        public <U> AsyncResult<U> map(Function<Object, U> mapper) {
            throw new UnsupportedOperationException();
        }

        public <V> AsyncResult<V> map(V value) {
            throw new UnsupportedOperationException();
        }
    };
    class DefaultCompleterTestFuture<T> implements Future<T> {

        boolean succeeded;

        boolean failed;

        T result;

        Throwable cause;

        public boolean isComplete() {
            throw new UnsupportedOperationException();
        }

        public Future<T> setHandler(Handler<AsyncResult<T>> handler) {
            throw new UnsupportedOperationException();
        }

        public void complete(T result) {
            if (!tryComplete(result)) {
                throw new IllegalStateException();
            }
        }

        public void complete() {
            if (!tryComplete()) {
                throw new IllegalStateException();
            }
        }

        public void fail(Throwable cause) {
            if (!tryFail(cause)) {
                throw new IllegalStateException();
            }
        }

        public void fail(String failureMessage) {
            if (!tryFail(failureMessage)) {
                throw new IllegalStateException();
            }
        }

        public boolean tryComplete(T result) {
            if (succeeded || failed) {
                return false;
            }
            succeeded = true;
            this.result = result;
            return true;
        }

        public boolean tryComplete() {
            throw new UnsupportedOperationException();
        }

        public boolean tryFail(Throwable cause) {
            if (succeeded || failed) {
                return false;
            }
            failed = true;
            this.cause = cause;
            return true;
        }

        public boolean tryFail(String failureMessage) {
            throw new UnsupportedOperationException();
        }

        public T result() {
            throw new UnsupportedOperationException();
        }

        public Throwable cause() {
            throw new UnsupportedOperationException();
        }

        public boolean succeeded() {
            throw new UnsupportedOperationException();
        }

        public boolean failed() {
            throw new UnsupportedOperationException();
        }

        public void handle(AsyncResult<T> asyncResult) {
            if (asyncResult.succeeded()) {
                complete(asyncResult.result());
            } else {
                fail(asyncResult.cause());
            }
        }
    }
    DefaultCompleterTestFuture<Object> successFuture = new DefaultCompleterTestFuture<>();
    successFuture.completer().handle(succeededAsyncResult);
    assertTrue(successFuture.succeeded);
    assertEquals(succeededAsyncResult.result(), successFuture.result);
    DefaultCompleterTestFuture<Object> failureFuture = new DefaultCompleterTestFuture<>();
    failureFuture.completer().handle(failedAsyncResult);
    assertTrue(failureFuture.failed);
    assertEquals(failedAsyncResult.cause(), failureFuture.cause);
}
Also used : Handler(io.vertx.core.Handler) BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) NoStackTraceThrowable(io.vertx.core.impl.NoStackTraceThrowable) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture) AsyncResult(io.vertx.core.AsyncResult) Test(org.junit.Test)

Aggregations

AsyncResult (io.vertx.core.AsyncResult)20 Handler (io.vertx.core.Handler)15 Future (io.vertx.core.Future)14 Buffer (io.vertx.core.buffer.Buffer)10 ContextImpl (io.vertx.core.impl.ContextImpl)8 VertxInternal (io.vertx.core.impl.VertxInternal)8 Logger (io.vertx.core.logging.Logger)8 LoggerFactory (io.vertx.core.logging.LoggerFactory)8 ByteBuf (io.netty.buffer.ByteBuf)7 Unpooled (io.netty.buffer.Unpooled)6 Map (java.util.Map)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 Channel (io.netty.channel.Channel)5 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)5 ChannelPipeline (io.netty.channel.ChannelPipeline)5 SslHandler (io.netty.handler.ssl.SslHandler)5 Context (io.vertx.core.Context)5 MultiMap (io.vertx.core.MultiMap)5 NetSocket (io.vertx.core.net.NetSocket)5 File (java.io.File)5