/*
 * SarURLConnection.java
 *
 * Created on October 10, 2001, 4:07 PM
 */

package test.protocol.sar;

import java.net.URL;
import java.net.URLConnection;
import java.net.MalformedURLException;
import java.io.InputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;

/**
 *
 * @author  mtoma
 * @version
 */
public class SarURLConnection extends URLConnection
{
    
    private static final char SEPARATOR = '-';
    private JarInputStream m_input;
    private URL m_nestedURL;
    private String m_entryName;
    private final ArrayList m_entryNames = new ArrayList();
    
    private JarEntry m_entry;
    private Manifest m_manifest;
    
    /** Creates new SarURLConnection */
    public SarURLConnection( URL url ) throws MalformedURLException
    {
        super( url );
        parseSpec();
    }
    
    /**
     * Get the specs for a given url out of the cache, and compute and
     * cache them if they're not there.
     */
    private void parseSpec() throws MalformedURLException
    {
        final String spec = url.getFile();
        
        int separator = spec.lastIndexOf( SEPARATOR );
        if (separator == -1)
        {
            throw new MalformedURLException( "no " + SEPARATOR +
            "/ found in url spec:" + spec );
        }
        
        m_nestedURL = new URL(spec.substring(0, separator++));
        
        /* if separator is the last char of the nestedURL, entryName is null */
        if ( ++separator < spec.length() )
        {
            m_entryName = spec.substring( separator, spec.length() );
        }
    }
    
    public void connect() throws IOException
    {        
        if (connected) return;
        
        m_input = new JarInputStream( m_nestedURL.openStream() );
        m_manifest = m_input.getManifest();
        
        if (m_entryName == null)
        {            
            while ( (m_entry = m_input.getNextJarEntry()) != null )
            {
                m_entryNames.add( m_entry.getName() );
            }
        } else
        {            
            while ( ( m_entry = m_input.getNextJarEntry() ) != null )
            {
                if ( m_entryName.equals( m_entry.getName() ) )
                {
                    connected = true;
                    return;
                }
            }
        }
    }
    
    public InputStream getInputStream() throws IOException
    {
        connect();
        return m_input;
    }
    
    public Manifest getManifest() throws IOException
    {
        connect();
        return m_manifest;
    }
    
    public JarEntry getEntry() throws IOException
    {
        connect();
        return m_entry;
    }
    
    public String[] getEntryNames() throws IOException
    {
        connect();
        return (String[]) m_entryNames.toArray( new String[0] );
    }
}
