Java源码示例:io.undertow.io.IoCallback

示例1
public static void main(final String[] args) {

        System.out.println("You can login with the following credentials:");
        System.out.println("User: userOne Password: passwordOne");
        System.out.println("User: userTwo Password: passwordTwo");

        final Map<String, char[]> users = new HashMap<>(2);
        users.put("userOne", "passwordOne".toCharArray());
        users.put("userTwo", "passwordTwo".toCharArray());

        final IdentityManager identityManager = new MapIdentityManager(users);

        Undertow server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(addSecurity(new HttpHandler() {
                    @Override
                    public void handleRequest(final HttpServerExchange exchange) throws Exception {
                        final SecurityContext context = exchange.getSecurityContext();
                        exchange.writeAsync("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), IoCallback.END_EXCHANGE);
                    }
                }, identityManager))
                .build();
        server.start();
    }
 
示例2
private boolean writeBuffer(final ByteBuffer buffer, final IoCallback callback) {
    StringBuilder builder = new StringBuilder();
    try {
        builder.append(charsetDecoder.decode(buffer));
    } catch (CharacterCodingException e) {
        callback.onException(exchange, this, e);
        return false;
    }
    String data = builder.toString();
    writer.write(data);
    if (writer.checkError()) {
        callback.onException(exchange, this, new IOException());
        return false;
    }
    return true;
}
 
示例3
private void queue(final ByteBuffer[] byteBuffers, final IoCallback ioCallback) {
    //if data is sent from withing the callback we queue it, to prevent the stack growing indefinitely
    if (next != null || pendingFile != null) {
        throw UndertowMessages.MESSAGES.dataAlreadyQueued();
    }
    StringBuilder builder = new StringBuilder();
    for (ByteBuffer buffer : byteBuffers) {
        try {
            builder.append(charsetDecoder.decode(buffer));
        } catch (CharacterCodingException e) {
            ioCallback.onException(exchange, this, e);
            return;
        }
    }
    this.next = builder.toString();
    queuedCallback = ioCallback;
}
 
示例4
@Override
public UndertowResponse writeContent(ByteBuffer byteBuffer) {
    beforeWritingContent();
    try {
        endAsync = !blocking();
        Sender sender = sender();
        if (endAsync) {
            sender.send(byteBuffer, IoCallback.END_EXCHANGE);
        } else {
            sender.send(byteBuffer);
        }
        afterWritingContent();
    } catch (RuntimeException e) {
        endAsync = false;
        afterWritingContent();
        throw e;
    }
    return this;
}
 
示例5
private static void sendTextError(HttpServerExchange exchange, ModelNode msg, int errorCode, String contentType) {
    StringWriter stringWriter = new StringWriter();
    final PrintWriter print = new PrintWriter(stringWriter);
    try {
        msg.writeJSONString(print, false);
    } finally {
        print.flush();
        stringWriter.flush();
        print.close();
    }

    String msgString = stringWriter.toString();
    byte[] bytes = msgString.getBytes(StandardCharsets.UTF_8);
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, contentType + "; charset=" + UTF_8);
    exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, String.valueOf(bytes.length));
    exchange.setStatusCode(errorCode);

    exchange.getResponseSender().send(msgString, IoCallback.END_EXCHANGE);
}
 
示例6
@Override
public void send(final ByteBuffer buffer, final IoCallback callback) {
    if (inCall) {
        queue(new ByteBuffer[]{buffer}, callback);
        return;
    }
    if (writeBuffer(buffer, callback)) {
        invokeOnComplete(callback);
    }
}
 
示例7
@Override
public void send(final ByteBuffer[] buffer, final IoCallback callback) {
    if (inCall) {
        queue(buffer, callback);
        return;
    }
    for (ByteBuffer b : buffer) {
        if (!writeBuffer(b, callback)) {
            return;
        }
    }
    invokeOnComplete(callback);
}
 
示例8
@Override
public void send(final String data, final IoCallback callback) {
    if (inCall) {
        queue(data, callback);
        return;
    }
    writer.write(data);

    if (writer.checkError()) {
        callback.onException(exchange, this, new IOException());
    } else {
        invokeOnComplete(callback);
    }
}
 
示例9
@Override
public void send(final String data, final Charset charset, final IoCallback callback) {
    if (inCall) {
        queue(new ByteBuffer[]{ByteBuffer.wrap(data.getBytes(charset))}, callback);
        return;
    }
    writer.write(data);
    if (writer.checkError()) {
        callback.onException(exchange, this, new IOException());
    } else {
        invokeOnComplete(callback);
    }
}
 
示例10
@Override
public void transferFrom(FileChannel source, IoCallback callback) {
    if (inCall) {
        queue(source, callback);
        return;
    }
    performTransfer(source, callback);
}
 
示例11
private void performTransfer(FileChannel source, IoCallback callback) {

        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
        try {
            long pos = source.position();
            long size = source.size();
            while (size - pos > 0) {
                int ret = source.read(buffer);
                if (ret <= 0) {
                    break;
                }
                pos += ret;
                buffer.flip();
                if (!writeBuffer(buffer, callback)) {
                    return;
                }
                buffer.clear();
            }

            if (pos != size) {
                throw new EOFException("Unexpected EOF reading file");
            }

        } catch (IOException e) {
            callback.onException(exchange, this, e);
        }
        invokeOnComplete(callback);
    }
 
示例12
private void queue(final String data, final IoCallback callback) {
    //if data is sent from withing the callback we queue it, to prevent the stack growing indefinitely
    if (next != null || pendingFile != null) {
        throw UndertowMessages.MESSAGES.dataAlreadyQueued();
    }
    next = data;
    queuedCallback = callback;
}
 
示例13
private void queue(final FileChannel data, final IoCallback callback) {
    //if data is sent from withing the callback we queue it, to prevent the stack growing indefinitely
    if (next != null || pendingFile != null) {
        throw UndertowMessages.MESSAGES.dataAlreadyQueued();
    }
    pendingFile = data;
    queuedCallback = callback;
}
 
示例14
/**
 * Sends a continuation using async IO, and calls back when it is complete.
 *
 * @param exchange The exchange
 * @param callback The completion callback
 */
public static void sendContinueResponse(final HttpServerExchange exchange, final IoCallback callback) {
    if (!exchange.isResponseChannelAvailable()) {
        callback.onException(exchange, null, UndertowMessages.MESSAGES.cannotSendContinueResponse());
        return;
    }
    internalSendContinueResponse(exchange, callback);
}
 
示例15
@Override
public void send(final ByteBuffer[] srcs, final IoCallback callback) {
    ByteBuffer[] origSrc = new ByteBuffer[srcs.length];
    long total = 0;
    for (int i = 0; i < srcs.length; i++) {
        origSrc[i] = srcs[i].duplicate();
        total += origSrc[i].remaining();
    }
    handleUpdate(origSrc, total);
    delegate.send(srcs, callback);
}
 
示例16
@Override
public void close(final IoCallback callback) {
    if (written != length) {
        cacheEntry.disable();
        cacheEntry.dereference();
    }
    delegate.close();
}
 
示例17
static void sendError(HttpServerExchange exchange, boolean encode, ModelNode msg, int errorCode) {
    if(encode) {

        try {
            ModelNode response = new ModelNode();
            response.set(msg);

            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            response.writeBase64(bout);
            byte[] bytes = bout.toByteArray();

            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, APPLICATION_DMR_ENCODED+ "; charset=" + UTF_8);
            exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, String.valueOf(bytes.length));
            exchange.setStatusCode(errorCode);

            exchange.getResponseSender().send(new String(bytes, StandardCharsets.UTF_8), IoCallback.END_EXCHANGE);

        } catch (IOException e) {
            // fallback, should not happen
            sendError(exchange, false, msg);
        }

    }
    else {
        sendTextError(exchange, msg, errorCode, APPLICATION_JSON);
    }
}
 
示例18
/**
 * @return the callback
 */
public IoCallback getIoCallback()
{
    return ioCallback;
}
 
示例19
/**
 * @param ioCallback
 *            the ioCallback to set
 */
public void setIoCallback(IoCallback ioCallback)
{
    this.ioCallback = ioCallback;
}
 
示例20
public ServerResponse<T> withIoCallback(IoCallback ioCallback)
{
    this.ioCallback = ioCallback;
    this.hasIoCallback = ioCallback == null;
    return this;
}
 
示例21
@Override
public void send(final ByteBuffer buffer) {
    send(buffer, IoCallback.END_EXCHANGE);
}
 
示例22
@Override
public void send(final ByteBuffer[] buffer) {
    send(buffer, IoCallback.END_EXCHANGE);
}
 
示例23
@Override
public void send(final String data) {
    send(data, IoCallback.END_EXCHANGE);
}
 
示例24
@Override
public void send(final String data, final Charset charset) {
    send(data, charset, IoCallback.END_EXCHANGE);
}
 
示例25
@Override
public void close(final IoCallback callback) {
    writer.close();
    invokeOnComplete(callback);
}
 
示例26
@Override
public void serveRange(Sender sender, HttpServerExchange exchange, long start, long end, IoCallback completionCallback) {
    final DirectBufferCache dataCache = cachingResourceManager.getDataCache();
    if(dataCache == null) {
        ((RangeAwareResource)underlyingResource).serveRange(sender, exchange, start, end, completionCallback);
        return;
    }

    final DirectBufferCache.CacheEntry existing = dataCache.get(cacheKey);
    final Long length = getContentLength();
    //if it is not eligible to be served from the cache
    if (length == null || length > cachingResourceManager.getMaxFileSize()) {
        underlyingResource.serve(sender, exchange, completionCallback);
        return;
    }
    //it is not cached yet, just serve it directly
    if (existing == null || !existing.enabled() || !existing.reference()) {
        //it is not cached yet, install a wrapper to grab the data
        ((RangeAwareResource)underlyingResource).serveRange(sender, exchange, start, end, completionCallback);
    } else {
        //serve straight from the cache
        ByteBuffer[] buffers;
        boolean ok = false;
        try {
            LimitedBufferSlicePool.PooledByteBuffer[] pooled = existing.buffers();
            buffers = new ByteBuffer[pooled.length];
            for (int i = 0; i < buffers.length; i++) {
                // Keep position from mutating
                buffers[i] = pooled[i].getBuffer().duplicate();
            }
            ok = true;
        } finally {
            if (!ok) {
                existing.dereference();
            }
        }
        if(start > 0) {
            long startDec = start;
            long endCount = 0;
            //handle the start of the range
            for(ByteBuffer b : buffers) {
                if(endCount == end) {
                    b.limit(b.position());
                    continue;
                } else if(endCount + b.remaining() < end) {
                    endCount += b.remaining();
                } else {
                    b.limit((int) (b.position() + (end - endCount)));
                    endCount = end;
                }
                if(b.remaining() >= startDec) {
                    startDec = 0;
                    b.position((int) (b.position() + startDec));
                } else {
                    startDec -= b.remaining();
                    b.position(b.limit());
                }
            }
        }
        sender.send(buffers, new DereferenceCallback(existing, completionCallback));
    }
}
 
示例27
DereferenceCallback(DirectBufferCache.CacheEntry entry, final IoCallback callback) {
    this.entry = entry;
    this.callback = callback;
}
 
示例28
@Override
public void serve(Sender sender, HttpServerExchange exchange, IoCallback completionCallback) {
    serveImpl(sender, exchange, -1, -1, false, completionCallback);
}
 
示例29
@Override
public void serveRange(Sender sender, HttpServerExchange exchange, long start, long end, IoCallback completionCallback) {
    serveImpl(sender, exchange, start, end, true, completionCallback);
}
 
示例30
@Override
public void serve(final Sender sender, final HttpServerExchange exchange, final IoCallback callback) {
    serveImpl(sender, exchange, -1, -1, callback, false);
}