/*
 * Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard.  All Rights Reserved.
 *
 * This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
 * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
 *
 * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR
 * WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING,
 * WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER
 * OR NOT DISCOVERABLE.  IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE
 * TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES
 * OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
 * ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER
 * THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT
 * SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.broad.igv.remote;

//~--- non-JDK imports --------------------------------------------------------

import org.apache.log4j.Logger;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.util.IGVHttpUtils;

import java.awt.*;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * 
 * This is a mostly deprecated class, created before range-byte requests were implemented.  It is still neccessary for a few
 * organizations, chiefly the Partners network, that inexplicably strip range-byte headers off outgoing http requests.
 * 
 * @author jrobinso
 */
public class SequenceServletWrapper {

    /**
     * Field description
     */
    public static boolean SEQUENCE_SERVER_AVAILALBLE = true;
    public static final int CONNECTION_TIMEOUT = 20000;
    private static Logger logger = Logger.getLogger(SequenceServletWrapper.class);


    public static byte[] readBytes(String urlString, String chr, int start, int end) {

        byte[] bytes = new byte[end - start];

        if (!SEQUENCE_SERVER_AVAILALBLE) {
            return bytes;
        }

        try {

            URL url = new URL(urlString + "?chr=" + chr + "&start=" + start + "&end=" + end);
            URLConnection connection = IGVHttpUtils.openConnection(url);
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setDoOutput(true);
            connection.setAllowUserInteraction(true);

            InputStream cis = connection.getInputStream();

            DataInputStream is = new DataInputStream(new BufferedInputStream(cis));
            int offset = 0;
            int numRead = 0;
            while ((offset < bytes.length) && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }
            is.close();

            return bytes;


        } catch (IOException ex) {

            // Log connection errors once per session to prevent filling the log
            if (SEQUENCE_SERVER_AVAILALBLE) {
                SEQUENCE_SERVER_AVAILALBLE = false;

                showUnavailableMessage();

                logger.error("Error retrieving sequence from : " + urlString + ex.getMessage());
            }
            return null;
        }
    }

    private static void showUnavailableMessage() throws HeadlessException {
        MessageUtils.showMessage(
                "<html>The IGV server at the Broad Institute is currently unavailable.  " +
                        "Features that require a reference sequence, <br>" +
                        "such as displaying alignment mismatches, will be disabled.  " +
                        "If this problem persists please <br>" +
                        "send email to igv-help@broadinstitute.org");
    }


}

@@ -1353,16 +1353,62 @@
 eUtils;%0A
+import org.broad.igv.util.IGVHttpClientUtils;%0A
 import o
@@ -2303,24 +2303,56 @@
 %0A        %7D%0A%0A
+        InputStream cis = null;%0A
         try 
@@ -2448,16 +2448,17 @@
 + end);%0A
+%0A
         
@@ -2465,284 +2465,57 @@
     
-URLConnection connection = IGVHttpUtils.openConnection(url);%0A            connection.setConnectTimeout(CONNECTION_TIMEOUT);%0A            connection.setDoOutput(true);%0A            connection.setAllowUserInteraction(true);%0A%0A            InputStream cis = connection.getInputStream(
+cis = IGVHttpClientUtils.openConnectionStream(url
 );%0A%0A
@@ -2649,20 +2649,16 @@
  numRead
- = 0
 ;%0A      
@@ -3266,24 +3266,184 @@
 ;%0A        %7D%0A
+        finally %7B%0A            if(cis != null) try %7B%0A                cis.close();%0A            %7D catch (IOException e) %7B%0A                %0A            %7D%0A        %7D%0A
     %7D%0A%0A    p

Fix sequence server bug. Issue #10