jueves, 13 de febrero de 2014

Programa para Descargar archivos desde un FTP

Como estoy haciendo un proyecto de una aplicación para el móvil que descarga directorios de un FTP
he decidido publicar mis avances y si alguno lo lee y sabe quizás puede alguien me ayude.

Aquí esta la librería que lista y descarga el directorio
//    DOwnload Gui User 0.5
//
//
//    This file is part of Dogu.
//    Dogu is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    at your option) any later version.
//
//    Foobar is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Foobar.  If not, see .
//    
//
//    Jaime Velasco Garcia << Salajadin98@gmail.com >>
//  
//    








public class FTPUtil {

public static void downloadDirectory(FTPClient ftpClient, String parentDir,
        String currentDir, String saveDir) throws IOException {
    String dirToList = parentDir;
    if (!currentDir.equals("")) {
        dirToList += "/" + currentDir;
    }

    FTPFile[] subFiles = ftpClient.listFiles(dirToList);

    if (subFiles != null && subFiles.length > 0) {
        for (FTPFile aFile : subFiles) {
            String currentFileName = aFile.getName();
            if (currentFileName.equals(".") || currentFileName.equals("..")) {
                continue;
            }
            String filePath = parentDir + "/" + currentDir + "/"
                    + currentFileName;
            if (currentDir.equals("")) {
                filePath = parentDir + "/" + currentFileName;
            }

            String newDirPath = saveDir + parentDir + File.separator
                    + currentDir + File.separator + currentFileName;
            if (currentDir.equals("")) {
                newDirPath = saveDir + parentDir + File.separator
                          + currentFileName;
            }

            if (aFile.isDirectory()) {
                File newDir = new File(newDirPath);
                boolean created = newDir.mkdirs();
                if (created) {
                    System.out.println("Creado el directorio: " + newDirPath);
                } else {
                    System.out.println("No se pudo crear el directorio: " + newDirPath);
                }

                downloadDirectory(ftpClient, dirToList, currentFileName,
                        saveDir);
            } else {
                boolean success = downloadSingleFile(ftpClient, filePath,
                        newDirPath);
                if (success) {
                    System.out.println("Archivo descargado: " + filePath);
                } else {
                    System.out.println("Error al descargar Archivo: "
                            + filePath);
                }
            }
        }
}

public static boolean downloadSingleFile(FTPClient ftpClient,
        String remoteFilePath, String savePath) throws IOException {
    File downloadFile = new File(savePath);
     
    File parentDir = downloadFile.getParentFile();
    if (!parentDir.exists()) {
        parentDir.mkdir();
    }
         
    OutputStream outputStream = new BufferedOutputStream(
            new FileOutputStream(downloadFile));
    try {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        return ftpClient.retrieveFile(remoteFilePath, outputStream);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

Y aquí el Main:



//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//
//  Jaime Velasco Garcia << Salajadin98@gmail.com >>

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see .
import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;

public class Dogu {

    public static void main(String[] args) {
        String server = "ponerserver";
        int port = 21;
        String user = "poneruser";
        String pass = "ponerpass";
        String codigo;
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        System.out.print(“Escribe El Codigo Proporcionado: “);
        codigo = br.readLine();
        FTPClient ftpClient = new FTPClient();

        try {
            ftpClient.connect(server, port);
            ftpClient.login(user, pass);

            ftpClient.enterLocalPassiveMode();

            System.out.println("Conectado");

            String remoteDirPath = "Poner Raiz" + codigo;
            String saveDirPath = "Raiz donde Descargar";

            FTPUtil.downloadDirectory(ftpClient, remoteDirPath, "", saveDirPath);

            ftpClient.logout();
            ftpClient.disconnect();

            System.out.println("Desconectado");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}




Ahora estoy aprendiendo a hacer la GUI de android

viernes, 7 de febrero de 2014

Apagar PC Windows en red LAN

Aburrido en clase hice un pequeño Script en bat que apagaba o al menos eso intentaba pero estaban protegidos contra este tipo de ataques :(
set /A x=1
:1
shutdown -r -f -m //poner primeros 3 grupos de ip .%x% -t 3 -c "tonto" ::
set /A x+=1
if x=100
goto 1 
Lo guardamos como .bat y listo

jueves, 6 de febrero de 2014

Cluster de Raspberry pi

Navegando por youtube encontré un cluster hecho con Raspberry pi y bueno estoy flipando la cantidad de codigo que han tenido que hacer suponiendo que quieren prescindir del SO para aprovechar a tope el procesador, ya que hay que programar las conexiones entre ellas, el repartir la tarea y mas cosas que se me escapa a mi compresion,

También la cantidad de cables Ethernet, switch que se necesitan para alcanzar la potencia de un Intel Xeón o dos como mucho, aunque de hobby esta bien.

lunes, 3 de febrero de 2014

Colaborar con el Software Libre y con la comunidad científica




Tras las palabras de Marijn Dekkers delegado de la farmacéutica de Bayer  "Fabricamos medicamentos para personas que puedan permitírselo."  
Tras estas palabras me ha confirmado porque no se elaboran medicamentos que curen enfermedades de países subdesarrollados. 
Tras esto decidí hacer esta entrada de como colaborar con la gente que realmente hace las cosas por altruismo y por mejorar el mundo no por ganar dinero.
Empezare como colaborar con la comunidad científica ya que produce efectos mas visibles en la sociedad.
Principalmente podéis ayudar difundiendo cada noticia. Otra forma es (ya que estamos en una sociedad con muchos ordenadores) donar procesamiento de vuestro pc, smartphone, tablet a los diferentes grupos de científicos que lo necesitan. Realmente yo creo que es lo mejor que se puede hacer, nadie utiliza un       cuad-core a tope y así estamos ayudando bastante a estas personas.
Podéis utilizar el programa Boinc
BOINC Logo custom.png
Es bastante sencillo de utilizar y tiene una app para android y iOS y en wikipedia  teneis un listado de bastante proyectos que lo utilizan.


Con el software libre podéis colaborar: promoviéndolo, traduciendo sus programas, testeandolo, y evidentemente escribiendo código.

Sin conocimientos se puede hacer un mundo mejor