/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2012 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.undertow.test.handlers;

import java.io.IOException;
import java.io.OutputStream;

import io.undertow.server.HttpServerConnection;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.blocking.BlockingHandler;
import io.undertow.server.handlers.blocking.BlockingHttpHandler;
import io.undertow.test.utils.DefaultServer;
import io.undertow.test.utils.HttpClientUtils;
import io.undertow.util.Headers;
import io.undertow.util.TestHttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.xnio.streams.ChannelOutputStream;

/**
 *
 * Tests that persistent connections work with fixed length responses
 * @author Stuart Douglas
 */
@RunWith(DefaultServer.class)
public class FixedLengthResponseTestCase {

    private static final String MESSAGE = "My HTTP Request!";

    private static volatile String message;

    private static volatile HttpServerConnection connection;

    @BeforeClass
    public static void setup() {
        final BlockingHandler blockingHandler = new BlockingHandler();
        DefaultServer.setRootHandler(blockingHandler);
        blockingHandler.setRootHandler(new BlockingHttpHandler() {
            @Override
            public void handleBlockingRequest(final HttpServerExchange exchange) {
                try {
                    if(connection == null) {
                        connection = exchange.getConnection();
                    } else if(!DefaultServer.isAjp() && connection.getChannel() != exchange.getConnection().getChannel()){
                        final OutputStream outputStream = new ChannelOutputStream(exchange.getResponseChannel());
                        outputStream.write("Connection not persistent".getBytes());
                        outputStream.close();
                        return;
                    }
                    final OutputStream outputStream = new ChannelOutputStream(exchange.getResponseChannel());
                    exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, message.length() + "");
                    outputStream.write(message.getBytes());
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    @Test
    public void sendHttpRequest() throws IOException {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerAddress() + "/path");
        TestHttpClient client = new TestHttpClient();
        try {
            generateMessage(1);
            HttpResponse result = client.execute(get);
            Assert.assertEquals(200, result.getStatusLine().getStatusCode());
            Assert.assertEquals(message, HttpClientUtils.readResponse(result));

            generateMessage(1000);
            result = client.execute(get);
            Assert.assertEquals(200, result.getStatusLine().getStatusCode());
            Assert.assertEquals(message, HttpClientUtils.readResponse(result));
        } finally {
            client.getConnectionManager().shutdown();
        }
    }


    private static void generateMessage(int repetitions) {
        final StringBuilder builder = new StringBuilder(repetitions * MESSAGE.length());
        for (int i = 0; i < repetitions; ++i) {
            builder.append(MESSAGE);
        }
        message = builder.toString();
    }
}

@@ -795,16 +795,119 @@
 tream;%0A%0A
+import io.undertow.io.IoCallback;%0Aimport io.undertow.io.Sender;%0Aimport io.undertow.server.HttpHandler;%0A
 import i
@@ -1528,19 +1528,16 @@
 m;%0A%0A/**%0A
- *%0A
  * Tests
@@ -1598,16 +1598,19 @@
 sponses%0A
+ *%0A
  * @auth
@@ -1937,177 +1937,41 @@
     
-final BlockingHandler blockingHandler = new BlockingHandler();%0A        DefaultServer.setRootHandler(blockingHandler);%0A        blockingHandler.setRootHandler(new Blocking
+DefaultServer.setRootHandler(new 
 Http
@@ -1978,24 +1978,25 @@
 Handler() %7B%0A
+%0A
             
@@ -2035,24 +2035,16 @@
 d handle
-Blocking
 Request(
@@ -2084,34 +2084,8 @@
 ) %7B%0A
-                try %7B%0A    
     
@@ -2098,16 +2098,17 @@
       if
+ 
 (connect
@@ -2142,20 +2142,16 @@
         
-    
 connecti
@@ -2197,20 +2197,16 @@
         
-    
 %7D else i
@@ -2206,16 +2206,17 @@
  else if
+ 
 (!Defaul
@@ -2299,16 +2299,17 @@
 annel())
+ 
 %7B%0A      
@@ -2326,70 +2326,24 @@
     
- 
-   final OutputStream outputStream = new ChannelOutputStream(
+Sender sender = 
 exch
@@ -2354,33 +2354,31 @@
 .getResponse
-Channel()
+Sender(
 );%0A         
@@ -2388,38 +2388,27 @@
         
-    outputStream.write
+sender.send
 (%22Connec
@@ -2431,546 +2431,310 @@
 ent%22
-.getBytes());%0A                        outputStream.close();%0A                        return;%0A                    %7D%0A                    final OutputStream outputStream = new ChannelOutputStream(exchange.getResponseChannel());%0A                    exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, message.length() + %22%22);%0A                    outputStream.write(message.getBytes());%0A                    outputStream.close();%0A                %7D catch (IOException e) %7B%0A                    throw new RuntimeException(e);%0A                %7D
+, IoCallback.END_EXCHANGE);%0A                    return;%0A                %7D%0A                exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, message.length() + %22%22);%0A                final Sender sender = exchange.getResponseSender();%0A                sender.send(message, IoCallback.END_EXCHANGE);
 %0A   

Change test to use sender