/*
 * WebFile.java
 *
 * Created on 26 de Outubro de 2004, 22:15
 */

import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;

/**
 *
 * @author  Bruno
 */
public class WebFile {
    
    /** Lista o conteudo de uma directoria dado o URL */       
    public static Vector list(URL url) {
        Vector files = new Vector(); 
        
        try {
            URLConnection urlConn = url.openConnection();             
            
            InputStream in = urlConn.getInputStream();
     
            BufferedReader fromServer = new BufferedReader(new InputStreamReader(in));
            
            String str;
            while((str=fromServer.readLine()) != null ) {
                files.addAll(parseFilename(str));
            }
             
            fromServer.close();
            in.close(); 
        }
        catch(java.io.IOException e) {
            System.err.println(e.toString());
        }
        return files;
    }
    
    /** Le a linha que contem os nomes dos ficheiros e filtra pelas imagens */
    private static Vector parseFilename(String src) {    
        Vector files = new Vector(); 
        StringTokenizer stk = new StringTokenizer(src, "<>");
        
        String str;
        while(stk.hasMoreTokens()) {
            str = stk.nextToken();
            
            // Filtra os ficheiros 
            if(str.endsWith(".jpg") || str.endsWith(".gif") || str.endsWith(".png"))
                files.add(str);
        }
        return files;
    }
    
    /** */
    public static byte[] download(URL url) {
        byte[] imagedata = null;
        
        try {
            URLConnection urlConn = url.openConnection();             
            
            InputStream in = urlConn.getInputStream();

            int size = urlConn.getContentLength();
            imagedata = new byte[size];
            
            for(int i=0; i<size; i++)
                imagedata[i] = (byte) in.read();
                    
            in.close(); 
        }
        catch(java.io.IOException e) {
            System.err.println(e.toString());
        }
                
        return imagedata;
    }
   
}
