/*
 * $Header: /home/cvspublic/jakarta-slide/testsuite/testsuite/junit/src/org/apache/slide/testsuite/testtools/tprocessor/StreamResponseBodyAssert.java,v 1.13 2004/09/03 13:56:37 luetzkendorf Exp $
 * $Revision: 1.13 $
 * $Date: 2004/09/03 13:56:37 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Slide", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * [Additional notices, if required by prior licensing conditions]
 *
 */

package org.apache.slide.testsuite.testtools.tprocessor;

//java
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.slide.testsuite.testtools.tutil.XConf;



/**
 * Abstract root class to perform the necessary checks for the received and expected stream body
 *
 * @version $Revision: 1.13 $
 */
public abstract class StreamResponseBodyAssert extends ResponseBodyAssert{


    private final static boolean extendedPrintlnsrequested = false;


    protected HttpMethod    method;
    protected InputStream   expectedBody;
    protected InputStream   receivedBody;

    /** constructer
     * @param WebdavMethodBase Element
     */
    public StreamResponseBodyAssert(HttpMethod method, InputStream expectedBody, XConf xconf, XMLOutput xmlresult, List expectedResponseCodes){


        super(xconf, method.getName(), xmlresult, expectedResponseCodes);

        this.method = method;
        this.expectedBody = expectedBody;
        try {
                this.receivedBody = method.getResponseBodyAsStream();
        }
        catch (Exception e) {
            e.printStackTrace();
            xmlresult.writeException(e);
        }


    }




    /**
     * checks if Expected Response and Response are same
     */
    public boolean assertResponseBody(){
        if (method.getStatusCode() < 200  || method.getStatusCode() > 300  ){
            return true;
        }

        if (receivedBody != null && expectedBody != null) {
            return compareStreams(receivedBody, expectedBody);
        }
        if (receivedBody == null) {
            return expectedBody == null;
        } 
        
        return false;
    }


    /**
     * checks if Expected and the received Response bodies are identical
     */
    protected boolean compareStreams(InputStream receivedBody, InputStream expectedBody){
        String contentValueProblem = null;
        byte[] receivedBuffer = new byte[1];
        byte[] expectedBuffer = new byte[1];
        int receivedCount = 0;
        int expectedCount = 0;
        int bytesRead     = 0;
        try {
            receivedCount=receivedBody.read(receivedBuffer);
            expectedCount=expectedBody.read(expectedBuffer);
            while ((receivedCount > 0) && (expectedCount > 0)) {
                bytesRead ++;

if (extendedPrintlnsrequested) System.out.println(getStreamCharByte(bytesRead, expectedBuffer, receivedBuffer) );

                if (receivedBuffer[0] != expectedBuffer[0]) {
                    if (contentValueProblem == null) {
                        contentValueProblem = "Position = " + bytesRead;
                    } else {
                        if (contentValueProblem.length() < 1024)
                            contentValueProblem += " ," + bytesRead;
                    }
                }
            receivedCount=receivedBody.read(receivedBuffer);
            expectedCount=expectedBody.read(expectedBuffer);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
            xmlresult.writeException(e);
        }

if (extendedPrintlnsrequested && expectedCount > 0) {
    System.out.println(" Expected ");
    printPostfixStreamCharByte(bytesRead, expectedBuffer, expectedBody);
}
if (extendedPrintlnsrequested && receivedCount > 0) {
    System.out.println(" Received ");
    printPostfixStreamCharByte(bytesRead, receivedBuffer, receivedBody);
}

        if (receivedCount != expectedCount) {
            xmlresult.writeElement("ContentLengthError", "Position = " + bytesRead );
        }

        if (contentValueProblem != null) {
            xmlresult.writeElement("ContentValueError", contentValueProblem);
        }

        // length and value are identical
        return (receivedCount == expectedCount) && (contentValueProblem == null);
    }

//////////////////////////////////////////////
//   some debugging printlns and methods    //
//////////////////////////////////////////////


    protected static final String[] hexadecimal =
    {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
            "A", "B", "C", "D", "E", "F"};


    protected static String convertHexDigit( byte toEncode ) {
        String result;
        int low = (int) (toEncode & 0x0f);
        int high = (int) ((toEncode & 0xf0) >> 4);
        result = hexadecimal[high] + hexadecimal[low];
        return result;
    }



    /**
     * get a byte as decimal and (try) as character
     */
    protected String getStreamCharByte(byte[] input){
        return " " + new String(input) + "   [" + convertHexDigit(input[0]) + "]";
    }


    /**
     * get a byte as decimal and (try) as character with prefix
     */
    protected String getStreamCharByte(int counter, byte[] input){
        return getPrefixStreamCharByte(counter) + getStreamCharByte(input);
    }



    /**
     * get a byte as decimal and (try) as character with prefix
     */
    protected String getStreamCharByte(int counter, byte[] exp, byte[] rec){
        if (exp[0] == rec[0]) return getPrefixStreamCharByte(counter) +
                                     getStreamCharByte(exp);
        else                  return getPrefixStreamCharByte(counter) +
                                     getStreamCharByte(exp) +
                                     " " + getStreamCharByte(rec) +
                                     " Difference";
    }


    /**
     * get a prefix string for printing
     */
    protected String getPrefixStreamCharByte(int position){
        return " " + position + ": \t" ;
    }



    /**
     * Print the final stream content a prefix string for printing
     */
    protected void printPostfixStreamCharByte(int counter, byte[] buffer, InputStream input){
        try {
            System.out.println(getStreamCharByte(++counter, buffer));
            int bytesRead;
            while (((bytesRead=input.read(buffer)) > 0) ) {
            System.out.println(getStreamCharByte(++counter, buffer));
            }
        }
        catch (IOException e) { e.printStackTrace();}
    }



}

