Ir al contenido principal

Clase Download alpha


En esta ocasión quiero entregarles uno de los códigos mas interesantes del siguiente ejercicio, el administrador de descargar.

Este administrador de descargas al estilo del viejo FlashGet, nos muestra una primera clase; Download.

Esta clase primeramente nos muestra su "signature", es un objeto observable y puede ser corrido paralelamente.

Seguidamente nos muestra el tamaño máximo que el buffer va leer, 1 kb por lectura para el "stream".

Después vemos el Status, muy auto descriptivo.

Y las propiedades de la clase, el url a descargar, el tamaño del archivo remoto a descargar, "downloaded" almacena la cantidad de bytes leídos, el estado actual de la descarga y por ultimo un valor opcional "baseDirectory" que se refiere al directorio base de donde almacenar los archivos a descargar.

A continuación, encontraremos una serie de métodos que nos develan el estado o disparan nuevos estado a la descarga.

Una vez creada la descarga, se puede invocar al método "startDownload" cuando desee iniciar la descarga.

Por ultimo el método "run" propio de la clase "Runnable" tiene la mayoría de la lógica, en general se crea un archivo de acceso aleatorio (que nos permite escribir en cualquier parte del archivo local) y establecemos una conexion (indicando en el caso de una reanudación, desde donde iniciar la descarga, ver método "setRangeBytes", del archivo remoto). Por ultimo se lee el contenido completo o restante del archivo y se guarda localmente.

Como podes ver es extremadamente sencillo, en particular un punto de mejora para la clase es utilizar un ThreadPool y una actividad futura, para no solicitar un hilo de manera abrupta, les dejo el código y un ejemplito trivial probado :)



package cap4;

import javax.naming.spi.DirectoryManager;
import java.io.*;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Observable;

/**
 * Ckase encargada de descargar un archivo, de forma paralela y con soporte de progreso y eventos.
 *
 * User: jsanca
 * Date: 4/17/13
 * Time: 11:27 PM
 * @author jsanca
 */
public class Download extends Observable implements Runnable, Serializable {


    // Tamano del bloque de descarga un kb
    private static final int MAX_BUFFER_SIZE = 1024;

    public enum Status {

        UNSTARTED,
        DOWNLOADING,
        PAUSED,
        COMPLETE,
        CANCELLED,
        ERROR
    } // Status.
    
    // URL a descargar.
    private URL url;

    // Tamano del archivo a descargar.
    private int fileSize;

    // Cantidad de bytes descargados.
    private int downloaded;

    // Estatus actual de la descarga.
    private Status status;
    
    private File baseDirectory;

    /**
     * Constructor.
     * @param url
     */
    public Download(final String url) throws MalformedURLException {

       this (new URL(url));
    } // Download.


    /**
     * Constructor.
     * @param url
     */
    public Download(final URL url) {

        this.url = url;
        this.fileSize = -1;
        this.downloaded = 0;
        this.baseDirectory = null;
        this.status = Status.UNSTARTED;
    } // Download.

    /**
     * Obtiene el porcentaje de progreso (de 1 a 100)
     * @return float
     */
    public float getProgress () {
        
        return (float) (this.downloaded / this.fileSize) * 100f;
    } // getProgress.

    /**
     * Pause la descarga actual.
     * Solo si esta se encuentra en descarga.
     */
    public void pause() {

        if (Status.DOWNLOADING == this.status) {

            this.status = Status.PAUSED;
            this.stateChanged();
        }
    } // pause.

    /**
     * Reanuda la descarga.
     * Solo si esta se encuentra pausada.
     */
    public void resume() {

        if (Status.PAUSED == this.status) {

            this.status = Status.DOWNLOADING;
            this.stateChanged();
            this.download();
        }
    } // resume.

    /**
     * Cancela la descarga, si y solo si, esta no esta descarga o en pausa
     */
    public void cancel() {

        if (Status.DOWNLOADING == this.status || Status.PAUSED == this.status) {

            this.status = Status.CANCELLED;
            this.stateChanged();
        }
    } // cancel.

    /**
     *  Se invoca cuando la descarga fracasa.
     */
    protected void error() {

        this.status = Status.ERROR;
        this.stateChanged();
    } // error.

    /**
     * Es invocado para disparar o reanudar la descarga de forma asincronica.
     */
    protected void download () {
        
        final Thread thread = new Thread(this);
        thread.start();
    } // download.

    /**
     * Invoque este metodo para iniciar la descarga.
     */
    public Download startDownload () {

        if (Status.UNSTARTED == this.status) {

            this.status = Status.DOWNLOADING;
            this.download();
        }

        return this;
    } // startDownload.

    /**
     * Get the file name (without the path) from the url.
     * @param aUrl URL
     * @return String
     */
    protected String getFileName (final URL aUrl) {

        String pathFileName = null;
        final String fileName = url.getFile();

        if (null != fileName) {

            pathFileName = fileName.substring(fileName.lastIndexOf('/') + 1);

            if (null != this.baseDirectory) {

                pathFileName = this.baseDirectory.getAbsolutePath() + "/" + pathFileName;
            }
        }

        if (null == fileName) {

            pathFileName = "unnamed" + System.currentTimeMillis();
        }

        return pathFileName;
    } // getFileName.

    public void run() {

        RandomAccessFile randomAccessFile = null;
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        int contentLength = 0;
        byte [] buffer;
        int readBytes;
        
        try {

            httpURLConnection =
                    (HttpURLConnection)this.url.openConnection();

            this.setRangeBytes(httpURLConnection, this.downloaded);

            httpURLConnection.connect();

            contentLength = this.checkErrors(httpURLConnection);

            // si el tamano no ha sido establecido, lo hago.
            if (-1 == this.fileSize) {

                this.fileSize = contentLength;
                this.stateChanged();
            }

            randomAccessFile =
                    new RandomAccessFile(this.getFileName(this.url), "rw");

            randomAccessFile.seek(this.downloaded);

            inputStream = httpURLConnection.getInputStream();

            while (Status.DOWNLOADING == this.status) {

                 buffer =
                         (this.fileSize - this.downloaded > MAX_BUFFER_SIZE)?
                                 new byte[MAX_BUFFER_SIZE]:
                                 new byte[this.fileSize - this.downloaded];

                 readBytes = inputStream.read(buffer);
                if (-1 == readBytes) {

                    break;
                }

                randomAccessFile.write(buffer, 0, readBytes);
                this.downloaded += readBytes;
                
                this.stateChanged();
            }

            // Marco la descarga como terminada.
            if (Status.DOWNLOADING == this.status) {
                
                this.status = Status.COMPLETE;
                this.stateChanged();
            }
        } catch (FileNotFoundException e) {

            error();
        } catch (IOException e) {

            error();
        } catch (DownloadErrorException e) {

            error();
        } finally {

            if (null != randomAccessFile) {

                try {

                    randomAccessFile.close();
                } catch (IOException e) {

                   // Quiet,
                }
            }

            if (null != inputStream) {

                try {

                    inputStream.close();
                } catch (IOException e) {

                    // Quiet,
                }
            }
        }
    } // run.

    private int checkErrors(final HttpURLConnection httpURLConnection) throws IOException {

        int contentLength;

        if (this.isAnErrorCode (httpURLConnection.getResponseCode())) {

            throw new DownloadErrorException("Response error = " + httpURLConnection.getResponseCode());
        }

        contentLength = httpURLConnection.getContentLength();

        if (contentLength < 1) {

            throw new DownloadErrorException("Content length invalid, length = " + contentLength);
        }
        return contentLength;
    } // checkErrors.

    /**
     * Determina si el codigo de respuesta esta en el rango de 200.
     * @param responseCode int
     * @return boolean
     */
    private boolean isAnErrorCode(final int responseCode) {

        return responseCode / 100 != 2;
    } // isAnErrorCode.

    /**
     * Especifica desde donde se iniciara la descarga del archivo (por ejemplo se puede iniciar desde la mitad) o reanudar una rescarga
     * @param connection HttpURLConnection
     * @param bytesSeek int
     */
    protected void setRangeBytes(final HttpURLConnection connection, final int bytesSeek) {

        connection.setRequestProperty("Range",
                new StringBuilder("bytes=").append(bytesSeek).append("-").toString());
    } // setRangeBytes.

    /**
     * Notifica a quien este viendo los cambios de estatos
     */
    protected void stateChanged() {

        this.setChanged();
        this.notifyObservers();
    } // stateChanged.


    /**
     * Asigna el directorio base para salvar el archivo.
     * En caso de ser nulo salva en el espacio de trabajo actual.
     * @param baseDirectory String
     */
    public void setBaseDirectory(final String baseDirectory) {

        this.setBaseDirectory(new File(baseDirectory));
    } // setBaseDirectory.

    /**
     * Asigna el directorio base para salvar el archivo.
     * En caso de ser nulo salva en el espacio de trabajo actual.
     * @param baseDirectory File
     */
    public void setBaseDirectory(final File baseDirectory) {

        if (null != baseDirectory && baseDirectory.exists()) {

            this.baseDirectory = baseDirectory;
        }
    } // setBaseDirectory.
} // E:O:F:Download.



El ejemplito Cambie "https://......jpg", por la direccion del archivo a descargar y /home/mydirectorio al archivo base al cual queremos descargar localmente.

public class Main {

    public static void main(String args[])
            throws java.io.IOException {

        Download download = new Download("https://......jpg");

        download.setBaseDirectory("/home/mydirectorio");

        download.startDownload();

    }
} // Main.

Comentarios

Entradas más populares de este blog

Pasos para remover Postgresql 8.3 en MAC OS

Tomado de: http://forums.enterprisedb.com/posts/list/1437.page In Mac OSX: (Assuming Default Locations) Via uninstaller: 1) In the installation directory, there will be a uninstall-postgresql.app file will be there, executing (double clicking) that will uninstall the postgresql installation. Manual Uninstallation: 1) Stop the server sudo /sbin/SystemStarter stop postgresql-8.3 2) Remove menu shortcuts: sudo rm -rf /Applications/PostgreSQL 8.3 3) Remove the ini file sudo rm -rf /etc/postgres-reg.ini 4) Removing Startup Items sudo rm -rf /Library/StartupItems/postgresql-8.3 5) Remove the data and installed files sudo rm -rf /Library/PostgreSQL/8.3 6) Delete the user postgres sudo dscl . delete /users/postgres

Validaciones con HTML5 sin necesidad de form.submit

Como parte de HTML5 existe la posibilidad de agregar información a los inputs de un form, para realizar validaciones; podemos indicar si queremos que sea requerido, con el tipo de datos; number, email, etc restringimos los valores que pueden ser agregados, podemos usar alguna mascara para validaciones, colocar mensajes de error custom, etc (en la red existen muchos ejemplos acerca de como customizar formularios). Ahora bien pongamos en contexto, tengo un formulario como este: <form name="managerForm"  id="managerForm">              <p>                  Name:                 <input id="managerNameText" required="required" placeholder="Write here the new manager name" size="40"/>              </p>             <p>                 Email:                 <input id="emailText" required="required" placeholder="myemail@myserver.com" type="email" />

Inventario anual de bebidas

Hola gente, Solo quería compartir mi inventario anual de bebidas (así conocer gustos), excluyendo algunas cervecillas que tengo por ahí guardadas, este es mi inventario: Ron: Flor de Cana 1 botella 5 anos. 2 botellas 7 anos una pacha 7 anos 2 botellas 12 anos 1 botella 18 anos Ron Zacapa 15 anos Centenario pachita 7 anos Centanario pachita 12 anos Bacardi limon Bacardi Razz Ron abuelo 7 anos Bacardi superior 1862 Ron Boltran XL Ron Centenario Garrafon Ron Jamaica Appleton 7 anos Ron Jamaica Appleton 12 anos (muchisimas gracias a Mayra :) Capitan Morgan Rum Jumbie, coconnut splash Ron coconut Malibu Ron Tequila Milagro Silver (muchisimas gracias a Pablito :) Sauza Gold Sauza Reposado Don Julio Reposado Vino Luigi Borer Malbec 2006 Casillero del Diablo, Caberut Sauviguon 2009 Vodka 2 botellas smirnoff y una smirnoff con sabor cranberry Cremas y otro licores Cahuita pacha Amaretto Barinet Licor de menta Licor de agave Rancho Escondido Bayleys 2 botellas (muchisimas gracias a Brian B :) Li