Search in sources :

Example 11 with HttpServerExchange

use of io.undertow.server.HttpServerExchange in project ovirt-engine-sdk-java by oVirt.

the class ServerTest method setXmlResponse.

protected void setXmlResponse(String path, final int code, final String body, final int delay) {
    HttpHandler xmlResponseHandler = new BlockingHandler(new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            lastRequestQuery = exchange.getQueryString();
            lastRequestHeaders = exchange.getRequestHeaders();
            lastRequestContent = getRequestContent(exchange);
            if (!exchange.getRequestHeaders().getFirst("Authorization").equals("Bearer " + TOKEN)) {
                exchange.setStatusCode(401);
                exchange.getResponseSender().send("");
            } else {
                Thread.sleep(delay);
                exchange.setStatusCode(code);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/xml");
                exchange.getResponseSender().send(body);
            }
        }
    });
    testHandler().addPrefixPath(testPrefix() + "/api/" + path, xmlResponseHandler);
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpHandler(io.undertow.server.HttpHandler) BlockingHandler(io.undertow.server.handlers.BlockingHandler) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) UnknownHostException(java.net.UnknownHostException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 12 with HttpServerExchange

use of io.undertow.server.HttpServerExchange in project iri by iotaledger.

the class API method init.

public void init() throws IOException {
    readPreviousEpochsSpentAddresses();
    final int apiPort = instance.configuration.integer(DefaultConfSettings.PORT);
    final String apiHost = instance.configuration.string(DefaultConfSettings.API_HOST);
    log.debug("Binding JSON-REST API Undertow server on {}:{}", apiHost, apiPort);
    server = Undertow.builder().addHttpListener(apiPort, apiHost).setHandler(path().addPrefixPath("/", addSecurity(new HttpHandler() {

        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            HttpString requestMethod = exchange.getRequestMethod();
            if (Methods.OPTIONS.equals(requestMethod)) {
                String allowedMethods = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
                // return list of allowed methods in response headers
                exchange.setStatusCode(StatusCodes.OK);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, MimeMappings.DEFAULT_MIME_MAPPINGS.get("txt"));
                exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, 0);
                exchange.getResponseHeaders().put(Headers.ALLOW, allowedMethods);
                exchange.getResponseHeaders().put(new HttpString("Access-Control-Allow-Origin"), "*");
                exchange.getResponseHeaders().put(new HttpString("Access-Control-Allow-Headers"), "Origin, X-Requested-With, Content-Type, Accept, X-IOTA-API-Version");
                exchange.getResponseSender().close();
                return;
            }
            if (exchange.isInIoThread()) {
                exchange.dispatch(this);
                return;
            }
            processRequest(exchange);
        }
    }))).build();
    server.start();
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpHandler(io.undertow.server.HttpHandler) HttpString(io.undertow.util.HttpString) URISyntaxException(java.net.URISyntaxException) HttpString(io.undertow.util.HttpString)

Example 13 with HttpServerExchange

use of io.undertow.server.HttpServerExchange in project spring-framework by spring-projects.

the class UndertowRequestUpgradeStrategy method upgrade.

@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, @Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) {
    HttpServerExchange httpExchange = ServerHttpRequestDecorator.getNativeRequest(exchange.getRequest());
    Set<String> protocols = (subProtocol != null ? Collections.singleton(subProtocol) : Collections.emptySet());
    Hybi13Handshake handshake = new Hybi13Handshake(protocols, false);
    List<Handshake> handshakes = Collections.singletonList(handshake);
    HandshakeInfo handshakeInfo = handshakeInfoFactory.get();
    DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
    // Trigger WebFlux preCommit actions and upgrade
    return exchange.getResponse().setComplete().then(Mono.deferContextual(contextView -> {
        DefaultCallback callback = new DefaultCallback(handshakeInfo, ContextWebSocketHandler.decorate(handler, contextView), bufferFactory);
        try {
            new WebSocketProtocolHandshakeHandler(handshakes, callback).handleRequest(httpExchange);
        } catch (Exception ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    }));
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) HttpServerExchange(io.undertow.server.HttpServerExchange) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) RequestUpgradeStrategy(org.springframework.web.reactive.socket.server.RequestUpgradeStrategy) Set(java.util.Set) Mono(reactor.core.publisher.Mono) WebSocketConnectionCallback(io.undertow.websockets.WebSocketConnectionCallback) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) Supplier(java.util.function.Supplier) UndertowWebSocketHandlerAdapter(org.springframework.web.reactive.socket.adapter.UndertowWebSocketHandlerAdapter) ServerWebExchange(org.springframework.web.server.ServerWebExchange) List(java.util.List) UndertowWebSocketSession(org.springframework.web.reactive.socket.adapter.UndertowWebSocketSession) WebSocketHttpExchange(io.undertow.websockets.spi.WebSocketHttpExchange) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) Handshake(io.undertow.websockets.core.protocol.Handshake) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) ServerHttpRequestDecorator(org.springframework.http.server.reactive.ServerHttpRequestDecorator) Nullable(org.springframework.lang.Nullable) WebSocketHandler(org.springframework.web.reactive.socket.WebSocketHandler) ContextWebSocketHandler(org.springframework.web.reactive.socket.adapter.ContextWebSocketHandler) Collections(java.util.Collections) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) Handshake(io.undertow.websockets.core.protocol.Handshake)

Example 14 with HttpServerExchange

use of io.undertow.server.HttpServerExchange in project pinpoint by naver.

the class ConnectorsExecuteRootHandlerInterceptor method before.

@Override
public void before(Object target, Object[] args) {
    if (isDebug) {
        logger.beforeInterceptor(target, args);
    }
    if (!argumentValidator.validate(args)) {
        return;
    }
    try {
        final HttpServerExchange request = (HttpServerExchange) args[1];
        this.servletRequestListener.initialized(request, UndertowConstants.UNDERTOW_METHOD, this.methodDescriptor);
        // must after request listener due to trace block begin
        this.servletResponseListener.initialized(request, UndertowConstants.UNDERTOW_METHOD, this.methodDescriptor);
        this.httpHeaderFilter.filter(request);
    } catch (Throwable t) {
        if (isInfo) {
            logger.info("Failed to servlet request event handle.", t);
        }
    }
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange)

Example 15 with HttpServerExchange

use of io.undertow.server.HttpServerExchange in project undertow by undertow-io.

the class PathResource method serveImpl.

private void serveImpl(final Sender sender, final HttpServerExchange exchange, final long start, final long end, final IoCallback callback, final boolean range) {
    abstract class BaseFileTask implements Runnable {

        protected volatile FileChannel fileChannel;

        protected boolean openFile() {
            try {
                fileChannel = FileChannel.open(file, StandardOpenOption.READ);
                if (range) {
                    fileChannel.position(start);
                }
            } catch (NoSuchFileException e) {
                exchange.setStatusCode(StatusCodes.NOT_FOUND);
                callback.onException(exchange, sender, e);
                return false;
            } catch (IOException e) {
                exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
                callback.onException(exchange, sender, e);
                return false;
            }
            return true;
        }
    }
    class ServerTask extends BaseFileTask implements IoCallback {

        private PooledByteBuffer pooled;

        long remaining = end - start + 1;

        @Override
        public void run() {
            if (range && remaining == 0) {
                // we are done
                if (pooled != null) {
                    pooled.close();
                    pooled = null;
                }
                IoUtils.safeClose(fileChannel);
                callback.onComplete(exchange, sender);
                return;
            }
            if (fileChannel == null) {
                if (!openFile()) {
                    return;
                }
                pooled = exchange.getConnection().getByteBufferPool().allocate();
            }
            if (pooled != null) {
                ByteBuffer buffer = pooled.getBuffer();
                try {
                    buffer.clear();
                    int res = fileChannel.read(buffer);
                    if (res == -1) {
                        // we are done
                        pooled.close();
                        IoUtils.safeClose(fileChannel);
                        callback.onComplete(exchange, sender);
                        return;
                    }
                    buffer.flip();
                    if (range) {
                        if (buffer.remaining() > remaining) {
                            buffer.limit((int) (buffer.position() + remaining));
                        }
                        remaining -= buffer.remaining();
                    }
                    sender.send(buffer, this);
                } catch (IOException e) {
                    onException(exchange, sender, e);
                }
            }
        }

        @Override
        public void onComplete(final HttpServerExchange exchange, final Sender sender) {
            if (exchange.isInIoThread()) {
                exchange.dispatch(this);
            } else {
                run();
            }
        }

        @Override
        public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) {
            UndertowLogger.REQUEST_IO_LOGGER.ioException(exception);
            if (pooled != null) {
                pooled.close();
                pooled = null;
            }
            IoUtils.safeClose(fileChannel);
            if (!exchange.isResponseStarted()) {
                exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
            }
            callback.onException(exchange, sender, exception);
        }
    }
    class TransferTask extends BaseFileTask {

        @Override
        public void run() {
            if (!openFile()) {
                return;
            }
            sender.transferFrom(fileChannel, new IoCallback() {

                @Override
                public void onComplete(HttpServerExchange exchange, Sender sender) {
                    try {
                        IoUtils.safeClose(fileChannel);
                    } finally {
                        callback.onComplete(exchange, sender);
                    }
                }

                @Override
                public void onException(HttpServerExchange exchange, Sender sender, IOException exception) {
                    try {
                        IoUtils.safeClose(fileChannel);
                    } finally {
                        callback.onException(exchange, sender, exception);
                    }
                }
            });
        }
    }
    BaseFileTask task;
    try {
        task = manager.getTransferMinSize() > Files.size(file) || range ? new ServerTask() : new TransferTask();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    if (exchange.isInIoThread()) {
        exchange.dispatch(task);
    } else {
        task.run();
    }
}
Also used : FileChannel(java.nio.channels.FileChannel) NoSuchFileException(java.nio.file.NoSuchFileException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) PooledByteBuffer(io.undertow.connector.PooledByteBuffer) HttpServerExchange(io.undertow.server.HttpServerExchange) Sender(io.undertow.io.Sender) PooledByteBuffer(io.undertow.connector.PooledByteBuffer) IoCallback(io.undertow.io.IoCallback)

Aggregations

HttpServerExchange (io.undertow.server.HttpServerExchange)270 HttpHandler (io.undertow.server.HttpHandler)126 Test (org.junit.Test)109 IOException (java.io.IOException)87 UnitTest (io.undertow.testutils.category.UnitTest)45 BeforeClass (org.junit.BeforeClass)43 TestHttpClient (io.undertow.testutils.TestHttpClient)42 HttpGet (org.apache.http.client.methods.HttpGet)40 HttpResponse (org.apache.http.HttpResponse)37 HttpString (io.undertow.util.HttpString)36 Header (org.apache.http.Header)24 Undertow (io.undertow.Undertow)19 ByteBuffer (java.nio.ByteBuffer)19 Map (java.util.Map)16 SessionConfig (io.undertow.server.session.SessionConfig)15 Sender (io.undertow.io.Sender)14 ExchangeCompletionListener (io.undertow.server.ExchangeCompletionListener)14 HeaderMap (io.undertow.util.HeaderMap)13 HeaderValues (io.undertow.util.HeaderValues)12 URI (java.net.URI)12