Search in sources :

Example 51 with HttpString

use of io.undertow.util.HttpString in project undertow by undertow-io.

the class MCMPWebManager method processRequest.

private void processRequest(HttpServerExchange exchange) throws IOException {
    Map<String, Deque<String>> params = exchange.getQueryParameters();
    boolean hasNonce = params.containsKey("nonce");
    int refreshTime = 0;
    if (checkNonce) {
        /* Check the nonce */
        if (hasNonce) {
            String receivedNonce = params.get("nonce").getFirst();
            if (receivedNonce.equals(getRawNonce())) {
                boolean refresh = params.containsKey("refresh");
                if (refresh) {
                    String sval = params.get("refresh").getFirst();
                    refreshTime = Integer.parseInt(sval);
                    if (refreshTime < 10)
                        refreshTime = 10;
                    exchange.getResponseHeaders().add(new HttpString("Refresh"), Integer.toString(refreshTime));
                }
                boolean cmd = params.containsKey("Cmd");
                boolean range = params.containsKey("Range");
                if (cmd) {
                    String scmd = params.get("Cmd").getFirst();
                    if (scmd.equals("INFO")) {
                        processInfo(exchange);
                        return;
                    } else if (scmd.equals("DUMP")) {
                        processDump(exchange);
                        return;
                    } else if (scmd.equals("ENABLE-APP") && range) {
                        String srange = params.get("Range").getFirst();
                        final RequestData data = buildRequestData(exchange, params);
                        if (srange.equals("NODE")) {
                            processNodeCommand(exchange, data, MCMPAction.ENABLE);
                        }
                        if (srange.equals("DOMAIN")) {
                            boolean domain = params.containsKey("Domain");
                            if (domain) {
                                String sdomain = params.get("Domain").getFirst();
                                processDomainCmd(exchange, sdomain, MCMPAction.ENABLE);
                            }
                        }
                        if (srange.equals("CONTEXT")) {
                            processAppCommand(exchange, data, MCMPAction.ENABLE);
                        }
                    } else if (scmd.equals("DISABLE-APP") && range) {
                        final String srange = params.get("Range").getFirst();
                        final RequestData data = buildRequestData(exchange, params);
                        if (srange.equals("NODE")) {
                            processNodeCommand(exchange, data, MCMPAction.DISABLE);
                        }
                        if (srange.equals("DOMAIN")) {
                            boolean domain = params.containsKey("Domain");
                            if (domain) {
                                String sdomain = params.get("Domain").getFirst();
                                processDomainCmd(exchange, sdomain, MCMPAction.DISABLE);
                            }
                        }
                        if (srange.equals("CONTEXT")) {
                            processAppCommand(exchange, data, MCMPAction.DISABLE);
                        }
                    }
                    return;
                }
            }
        }
    }
    exchange.setStatusCode(StatusCodes.OK);
    exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "text/html; charset=ISO-8859-1");
    final Sender resp = exchange.getResponseSender();
    final StringBuilder buf = new StringBuilder();
    buf.append("<html><head>\n<title>Mod_cluster Status</title>\n</head><body>\n");
    buf.append("<h1>" + MOD_CLUSTER_EXPOSED_VERSION + "</h1>");
    final String uri = exchange.getRequestPath();
    final String nonce = getNonce();
    if (refreshTime <= 0) {
        buf.append("<a href=\"").append(uri).append("?").append(nonce).append("&refresh=").append(refreshTime).append("\">Auto Refresh</a>");
    }
    buf.append(" <a href=\"").append(uri).append("?").append(nonce).append("&Cmd=DUMP&Range=ALL").append("\">show DUMP output</a>");
    buf.append(" <a href=\"").append(uri).append("?").append(nonce).append("&Cmd=INFO&Range=ALL").append("\">show INFO output</a>");
    buf.append("\n");
    // Show load balancing groups
    final Map<String, List<Node>> nodes = new LinkedHashMap<>();
    for (final Node node : container.getNodes()) {
        final String domain = node.getNodeConfig().getDomain() != null ? node.getNodeConfig().getDomain() : "";
        List<Node> list = nodes.get(domain);
        if (list == null) {
            list = new ArrayList<>();
            nodes.put(domain, list);
        }
        list.add(node);
    }
    for (Map.Entry<String, List<Node>> entry : nodes.entrySet()) {
        final String groupName = entry.getKey();
        if (reduceDisplay) {
            buf.append("<br/><br/>LBGroup " + groupName + ": ");
        } else {
            buf.append("<h1> LBGroup " + groupName + ": ");
        }
        if (allowCmd) {
            domainCommandString(buf, uri, MCMPAction.ENABLE, groupName);
            domainCommandString(buf, uri, MCMPAction.DISABLE, groupName);
        }
        for (final Node node : entry.getValue()) {
            final NodeConfig nodeConfig = node.getNodeConfig();
            if (reduceDisplay) {
                buf.append("<br/><br/>Node " + nodeConfig.getJvmRoute());
                printProxyStat(buf, node, reduceDisplay);
            } else {
                buf.append("<h1> Node " + nodeConfig.getJvmRoute() + " (" + nodeConfig.getConnectionURI() + "): </h1>\n");
            }
            if (allowCmd) {
                nodeCommandString(buf, uri, MCMPAction.ENABLE, nodeConfig.getJvmRoute());
                nodeCommandString(buf, uri, MCMPAction.DISABLE, nodeConfig.getJvmRoute());
            }
            if (!reduceDisplay) {
                buf.append("<br/>\n");
                buf.append("Balancer: " + nodeConfig.getBalancer() + ",LBGroup: " + nodeConfig.getDomain());
                String flushpackets = "off";
                if (nodeConfig.isFlushPackets()) {
                    flushpackets = "Auto";
                }
                buf.append(",Flushpackets: " + flushpackets + ",Flushwait: " + nodeConfig.getFlushwait() + ",Ping: " + nodeConfig.getPing() + " ,Smax: " + nodeConfig.getPing() + ",Ttl: " + nodeConfig.getTtl());
                printProxyStat(buf, node, reduceDisplay);
            } else {
                buf.append("<br/>\n");
            }
            buf.append("\n");
            // Process the virtual-host of the node
            printInfoHost(buf, uri, reduceDisplay, allowCmd, node);
        }
    }
    buf.append("</body></html>\n");
    resp.send(buf.toString());
}
Also used : HttpString(io.undertow.util.HttpString) Deque(java.util.Deque) LinkedHashMap(java.util.LinkedHashMap) Sender(io.undertow.io.Sender) ArrayList(java.util.ArrayList) List(java.util.List) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) HttpString(io.undertow.util.HttpString)

Example 52 with HttpString

use of io.undertow.util.HttpString in project undertow by undertow-io.

the class LoadBalancingProxyHTTP2TestCase method setup.

@BeforeClass
public static void setup() throws URISyntaxException {
    int port = DefaultServer.getHostPort("default");
    final HttpHandler handler1 = getRootHandler("s1", "server1");
    server1 = Undertow.builder().addHttpsListener(port + 1, DefaultServer.getHostAddress("default"), DefaultServer.getServerSslContext()).setServerOption(UndertowOptions.ENABLE_HTTP2, true).setServerOption(UndertowOptions.NO_REQUEST_TIMEOUT, IDLE_TIMEOUT).setSocketOption(Options.REUSE_ADDRESSES, true).setHandler(new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            if (!(exchange.getConnection() instanceof Http2ServerConnection)) {
                throw new RuntimeException("Not HTTP2");
            }
            exchange.getResponseHeaders().add(new HttpString("X-Custom-Header"), "foo");
            handler1.handleRequest(exchange);
        }
    }).build();
    final HttpHandler handler2 = getRootHandler("s2", "server2");
    server2 = Undertow.builder().addHttpsListener(port + 2, DefaultServer.getHostAddress("default"), DefaultServer.getServerSslContext()).setServerOption(UndertowOptions.ENABLE_HTTP2, true).setSocketOption(Options.REUSE_ADDRESSES, true).setServerOption(UndertowOptions.NO_REQUEST_TIMEOUT, IDLE_TIMEOUT).setHandler(new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            if (!(exchange.getConnection() instanceof Http2ServerConnection)) {
                throw new RuntimeException("Not HTTP2");
            }
            exchange.getResponseHeaders().add(new HttpString("X-Custom-Header"), "foo");
            handler2.handleRequest(exchange);
        }
    }).build();
    server1.start();
    server2.start();
    UndertowXnioSsl ssl = new UndertowXnioSsl(DefaultServer.getWorker().getXnio(), OptionMap.EMPTY, DefaultServer.SSL_BUFFER_POOL, DefaultServer.createClientSslContext());
    DefaultServer.setRootHandler(new ProxyHandler(new LoadBalancingProxyClient().setConnectionsPerThread(4).addHost(new URI("https", null, DefaultServer.getHostAddress("default"), port + 1, null, null, null), "s1", ssl, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).addHost(new URI("https", null, DefaultServer.getHostAddress("default"), port + 2, null, null, null), "s2", ssl, OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)), 10000, ResponseCodeHandler.HANDLE_404, false, false, 2));
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpHandler(io.undertow.server.HttpHandler) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) Http2ServerConnection(io.undertow.server.protocol.http2.Http2ServerConnection) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) HttpString(io.undertow.util.HttpString) BeforeClass(org.junit.BeforeClass)

Example 53 with HttpString

use of io.undertow.util.HttpString in project undertow by undertow-io.

the class SSLSessionTestCase method testSslSession.

@Test
public void testSslSession() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {
        InMemorySessionManager sessionManager = new InMemorySessionManager("");
        final SslSessionConfig sessionConfig = new SslSessionConfig(sessionManager);
        final SessionAttachmentHandler handler = new SessionAttachmentHandler(sessionManager, sessionConfig).setNext(new HttpHandler() {

            @Override
            public void handleRequest(final HttpServerExchange exchange) throws Exception {
                final SessionManager manager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
                Session session = manager.getSession(exchange, sessionConfig);
                if (session == null) {
                    session = manager.createSession(exchange, sessionConfig);
                    session.setAttribute(COUNT, 0);
                }
                Integer count = (Integer) session.getAttribute(COUNT);
                exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
                session.setAttribute(COUNT, ++count);
            }
        });
        DefaultServer.startSSLServer();
        client.setSSLContext(DefaultServer.getClientSSLContext());
        DefaultServer.setRootHandler(handler);
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerSSLAddress() + "/notamatchingpath");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        Header[] header = result.getHeaders(COUNT);
        Assert.assertEquals("0", header[0].getValue());
        get = new HttpGet(DefaultServer.getDefaultServerSSLAddress() + "/notamatchingpath");
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("1", header[0].getValue());
        get = new HttpGet(DefaultServer.getDefaultServerSSLAddress() + "/notamatchingpath");
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("2", header[0].getValue());
        Assert.assertEquals(0, client.getCookieStore().getCookies().size());
    } finally {
        DefaultServer.stopSSLServer();
        client.getConnectionManager().shutdown();
    }
}
Also used : HttpHandler(io.undertow.server.HttpHandler) SessionManager(io.undertow.server.session.SessionManager) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) TestHttpClient(io.undertow.testutils.TestHttpClient) HttpServerExchange(io.undertow.server.HttpServerExchange) SessionAttachmentHandler(io.undertow.server.session.SessionAttachmentHandler) SslSessionConfig(io.undertow.server.session.SslSessionConfig) Header(org.apache.http.Header) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) Session(io.undertow.server.session.Session) HttpString(io.undertow.util.HttpString) Test(org.junit.Test)

Example 54 with HttpString

use of io.undertow.util.HttpString in project undertow by undertow-io.

the class SimpleParserTestCase method testSameHttpStringReturned.

@Test
public void testSameHttpStringReturned() throws HttpRequestParser.BadRequestException {
    byte[] in = "GET\thttp://www.somehost.net/somepath\tHTTP/1.1\nHost: \t www.somehost.net\nAccept-Charset:\tsome\n \t  value\n\r\n".getBytes();
    final ParseState context1 = new ParseState();
    HttpServerExchange result1 = new HttpServerExchange(null);
    HttpRequestParser.instance(OptionMap.EMPTY).handle(ByteBuffer.wrap(in), context1, result1);
    final ParseState context2 = new ParseState();
    HttpServerExchange result2 = new HttpServerExchange(null);
    HttpRequestParser.instance(OptionMap.EMPTY).handle(ByteBuffer.wrap(in), context2, result2);
    Assert.assertSame(result1.getProtocol(), result2.getProtocol());
    Assert.assertSame(result1.getRequestMethod(), result2.getRequestMethod());
    for (final HttpString header : result1.getRequestHeaders().getHeaderNames()) {
        boolean found = false;
        for (final HttpString header2 : result1.getRequestHeaders().getHeaderNames()) {
            if (header == header2) {
                found = true;
                break;
            }
        }
        if (header.equals(Headers.HOST)) {
            Assert.assertSame(Headers.HOST, header);
        }
        Assert.assertTrue("Could not found header " + header, found);
    }
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) HttpString(io.undertow.util.HttpString) UnitTest(io.undertow.testutils.category.UnitTest) Test(org.junit.Test)

Example 55 with HttpString

use of io.undertow.util.HttpString in project undertow by undertow-io.

the class InMemorySessionTestCase method inMemoryMaxSessionsTest.

@Test
public void inMemoryMaxSessionsTest() throws IOException {
    TestHttpClient client1 = new TestHttpClient();
    client1.setCookieStore(new BasicCookieStore());
    TestHttpClient client2 = new TestHttpClient();
    client2.setCookieStore(new BasicCookieStore());
    try {
        final SessionCookieConfig sessionConfig = new SessionCookieConfig();
        final SessionAttachmentHandler handler = new SessionAttachmentHandler(new InMemorySessionManager("", 1, true), sessionConfig);
        handler.setNext(new HttpHandler() {

            @Override
            public void handleRequest(final HttpServerExchange exchange) throws Exception {
                final SessionManager manager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
                Session session = manager.getSession(exchange, sessionConfig);
                if (session == null) {
                    session = manager.createSession(exchange, sessionConfig);
                    session.setAttribute(COUNT, 0);
                }
                Integer count = (Integer) session.getAttribute(COUNT);
                exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
                session.setAttribute(COUNT, ++count);
            }
        });
        DefaultServer.setRootHandler(handler);
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
        HttpResponse result = client1.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        Header[] header = result.getHeaders(COUNT);
        Assert.assertEquals("0", header[0].getValue());
        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
        result = client1.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("1", header[0].getValue());
        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
        result = client2.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("0", header[0].getValue());
        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
        result = client1.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("0", header[0].getValue());
    } finally {
        client1.getConnectionManager().shutdown();
        client2.getConnectionManager().shutdown();
    }
}
Also used : HttpHandler(io.undertow.server.HttpHandler) SessionManager(io.undertow.server.session.SessionManager) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) TestHttpClient(io.undertow.testutils.TestHttpClient) HttpServerExchange(io.undertow.server.HttpServerExchange) SessionAttachmentHandler(io.undertow.server.session.SessionAttachmentHandler) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) SessionCookieConfig(io.undertow.server.session.SessionCookieConfig) InMemorySessionManager(io.undertow.server.session.InMemorySessionManager) Session(io.undertow.server.session.Session) HttpString(io.undertow.util.HttpString) Test(org.junit.Test)

Aggregations

HttpString (io.undertow.util.HttpString)59 IOException (java.io.IOException)18 HttpServerExchange (io.undertow.server.HttpServerExchange)16 HeaderMap (io.undertow.util.HeaderMap)15 HttpHandler (io.undertow.server.HttpHandler)9 ByteBuffer (java.nio.ByteBuffer)9 Map (java.util.Map)8 HashMap (java.util.HashMap)7 PooledByteBuffer (io.undertow.connector.PooledByteBuffer)6 HeaderValues (io.undertow.util.HeaderValues)6 ClientRequest (io.undertow.client.ClientRequest)5 Session (io.undertow.server.session.Session)5 URISyntaxException (java.net.URISyntaxException)5 ArrayList (java.util.ArrayList)5 Test (org.junit.Test)5 InMemorySessionManager (io.undertow.server.session.InMemorySessionManager)4 SessionAttachmentHandler (io.undertow.server.session.SessionAttachmentHandler)4 SessionManager (io.undertow.server.session.SessionManager)4 List (java.util.List)4 TypeConverter (org.apache.camel.TypeConverter)4