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;
}
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);
}
}
}
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;
}
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;
}
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);
}
Aggregations