io.undertow.io.IoCallback Java Examples

The following examples show how to use io.undertow.io.IoCallback. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BasicAuthServer.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
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();
    }
 
Example #2
Source File: Common.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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);
}
 
Example #3
Source File: BlockingWriterSenderImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: BlockingWriterSenderImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: UndertowResponse.java    From actframework with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #6
Source File: ResponseCachingSender.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #7
Source File: HttpContinue.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #8
Source File: BlockingWriterSenderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #9
Source File: BlockingWriterSenderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #10
Source File: BlockingWriterSenderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
 
Example #11
Source File: BlockingWriterSenderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void transferFrom(FileChannel source, IoCallback callback) {
    if (inCall) {
        queue(source, callback);
        return;
    }
    performTransfer(source, callback);
}
 
Example #12
Source File: ResponseCachingSender.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void close(final IoCallback callback) {
    if (written != length) {
        cacheEntry.disable();
        cacheEntry.dereference();
    }
    delegate.close();
}
 
Example #13
Source File: BlockingWriterSenderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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);
    }
}
 
Example #14
Source File: BlockingWriterSenderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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);
    }
}
 
Example #15
Source File: BlockingWriterSenderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #16
Source File: BlockingWriterSenderImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void send(final ByteBuffer buffer, final IoCallback callback) {
    if (inCall) {
        queue(new ByteBuffer[]{buffer}, callback);
        return;
    }
    if (writeBuffer(buffer, callback)) {
        invokeOnComplete(callback);
    }
}
 
Example #17
Source File: Common.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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);
    }
}
 
Example #18
Source File: PathResource.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void serveRange(final Sender sender, final HttpServerExchange exchange, final long start, final long end, final IoCallback callback) {
    serveImpl(sender, exchange, start, end, callback, true);

}
 
Example #19
Source File: ResponseCachingSender.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void send(final String data, final IoCallback callback) {
    handleUpdate(ByteBuffer.wrap(data.getBytes(StandardCharsets.UTF_8)));
    delegate.send(data, callback);
}
 
Example #20
Source File: ResponseCachingSender.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void send(final ByteBuffer src, final IoCallback callback) {
    ByteBuffer origSrc = src.duplicate();
    handleUpdate(origSrc);
    delegate.send(src, callback);
}
 
Example #21
Source File: CachedResource.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@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));
    }
}
 
Example #22
Source File: ResponseCachingSender.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void send(final String data, final Charset charset, final IoCallback callback) {
    handleUpdate(ByteBuffer.wrap(data.getBytes(charset)));
    delegate.send(data, charset, callback);
}
 
Example #23
Source File: ResponseCachingSender.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void transferFrom(FileChannel channel, IoCallback callback) {
    // Transfer never caches
    delegate.transferFrom(channel, callback);
}
 
Example #24
Source File: NonBlockOutput.java    From actframework with Apache License 2.0 4 votes vote down vote up
@Override
public void close() {
    sender.close(IoCallback.END_EXCHANGE);
}
 
Example #25
Source File: LogoutHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    final HeaderMap requestHeaders = exchange.getRequestHeaders();
    final HeaderMap responseHeaders = exchange.getResponseHeaders();

    String referrer = responseHeaders.getFirst(REFERER);
    String protocol = exchange.getRequestScheme();
    String host = null;
    if (referrer != null) {
        try {
            URI uri = new URI(referrer);
            protocol = uri.getScheme();
            host = uri.getHost() + portPortion(protocol, uri.getPort());
        } catch (URISyntaxException e) {
        }
    }
    if (host == null) {
        host = requestHeaders.getFirst(HOST);
        if (host == null) {
            exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
            return;
        }
    }

    /*
     * Main sequence of events:
     *
     * 1. Redirect to self using user:pass@host form of authority. This forces Safari to overwrite its cache. (Also
     * forces FF and Chrome, but not absolutely necessary) Set the exit flag as a state signal for step 3
     *
     * 2. Send 401 digest without a nonce stale marker, this will force FF and Chrome and likely other browsers to
     * assume an invalid (old) password. In the case of Opera, which doesn't invalidate under such a circumstance,
     * send an invalid realm. This will overwrite its auth cache, since it indexes it by host and not realm.
     *
     * 3. The credentials in 307 redirect wlll be transparently accepted and a final redirect to the console is
     * performed. Opera ignores these, so the user must hit escape which will use javascript to perform the redirect
     *
     * In the case of Internet Explorer, all of this will be bypassed and will simply redirect to the console. The console
     * MUST use a special javascript call before redirecting to logout.
     */
    String userAgent = requestHeaders.getFirst(USER_AGENT);
    boolean opera = userAgent != null && userAgent.contains("Opera");
    boolean win = !opera && userAgent != null && (userAgent.contains("MSIE") || userAgent.contains("Trident"));

    String rawQuery = exchange.getQueryString();
    boolean exit = rawQuery != null && rawQuery.contains(EXIT);



    if (win) {
        responseHeaders.add(LOCATION, protocol + "://" + host + "/");
        exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
    } else {
        // Do the redirects to finish the logout
        String authorization = requestHeaders.getFirst(AUTHORIZATION);

        boolean digest = true;
        Map<String, Deque<String>> parameters = exchange.getQueryParameters();
        if (parameters.containsKey(MECHANISM)) {
            digest = !BASIC.equals(parameters.get(MECHANISM).getFirst());
        }
        if (authorization != null && authorization.length() > BASIC.length()
                && BASIC.equalsIgnoreCase(authorization.substring(0, BASIC.length()))) {
            digest = false;
            ByteBuffer decode = FlexBase64.decode(authorization.substring(6));
            authorization = new String(decode.array(), decode.arrayOffset(), decode.limit(), UTF_8);
        }

        if (authorization == null || !authorization.contains("enter-login-here")) {
            if (!exit) {
                responseHeaders.add(LOCATION, protocol + "://enter-login-here:blah@" + host + "/logout?" + EXIT + "&"
                        + MECHANISM + "=" + (digest ? DIGEST : BASIC));
                exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
                return;
            }

            mechanism(opera, digest).sendChallenge(exchange, null);
            String reply = "<html><script type='text/javascript'>window.location=\"" + protocol + "://" + host
                    + "/\";</script></html>";
            exchange.setStatusCode(StatusCodes.UNAUTHORIZED);
            exchange.getResponseSender().send(reply, IoCallback.END_EXCHANGE);
            return;
        }

        // Success, now back to the login screen
        responseHeaders.add(LOCATION, protocol + "://" + host + "/");
        exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
    }
}
 
Example #26
Source File: SecureServer.java    From tutorials with MIT License 4 votes vote down vote up
private static void setExchange(HttpServerExchange exchange) {
    final SecurityContext context = exchange.getSecurityContext();
    exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), IoCallback.END_EXCHANGE);
}
 
Example #27
Source File: PathResource.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void serve(final Sender sender, final HttpServerExchange exchange, final IoCallback callback) {
    serveImpl(sender, exchange, -1, -1, callback, false);
}
 
Example #28
Source File: URLResource.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void serveRange(Sender sender, HttpServerExchange exchange, long start, long end, IoCallback completionCallback) {
    serveImpl(sender, exchange, start, end, true, completionCallback);
}
 
Example #29
Source File: URLResource.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void serve(Sender sender, HttpServerExchange exchange, IoCallback completionCallback) {
    serveImpl(sender, exchange, -1, -1, false, completionCallback);
}
 
Example #30
Source File: CachedResource.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
DereferenceCallback(DirectBufferCache.CacheEntry entry, final IoCallback callback) {
    this.entry = entry;
    this.callback = callback;
}