Example usage for org.apache.commons.net.ftp FTPClient connect

List of usage examples for org.apache.commons.net.ftp FTPClient connect

Introduction

In this page you can find the example usage for org.apache.commons.net.ftp FTPClient connect.

Prototype

public void connect(InetAddress host) throws SocketException, IOException 

Source Link

Document

Opens a Socket connected to a remote host at the current default port and originating from the current host at a system assigned port.

Usage

From source file:s32a.Server.Startup.FTPHandler.java

/**
 * Registers/*from  w ww .  j a v a  2s .  co m*/
 *
 * @param input The server info to be registered
 * @return The url that should be used as java for codebase purposes
 */
public String registerServer(ServerInfo input) {
    File infoFile = this.saveInfoToFile(input);
    if (infoFile == null || infoFile.length() == 0) {
        showDialog("Error", "No file to store: " + infoFile.getAbsolutePath());
        //System.out.println("No file to store: " + infoFile.getAbsolutePath());
        return null;
    }

    FTPClient client = null;
    FileInputStream fis = null;
    FileOutputStream fos = null;
    String output = null;

    if (SSL) {
        client = new FTPSClient(false);
    } else {
        client = new FTPClient();
    }

    try {
        System.out.println("connecting");
        client.connect(ftpServer);
        boolean login = client.login(this.username, this.password);
        System.out.println("login: " + login);
        client.enterLocalPassiveMode();

        fis = new FileInputStream(infoFile);
        this.ftpRefLocation = "/Airhockey/Servers/" + input.getIP() + "-" + input.getBindingName() + ".server";
        client.storeFile(this.ftpRefLocation, fis);

        File codebase = new File("codebase.properties");
        fos = new FileOutputStream(codebase.getAbsolutePath());
        client.retrieveFile("/Airhockey/Codebase/codebase.properties", fos);
        fos.close();
        output = this.readCodebaseInfo(codebase);

        client.logout();
    } catch (IOException ex) {
        showDialog("Error", "FTP: IOException " + ex.getMessage());
        //            System.out.println("IOException: " + ex.getMessage());
        //            ex.printStackTrace();
    } catch (Exception ex) {
        showDialog("Error", "FTP: Exception: " + ex.getMessage());
        //System.out.println("exception caught: " + ex.getMessage());
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
            client.disconnect();
            infoFile.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return output;
}

From source file:s32a.Server.Startup.FTPHandler.java

/**
 * Unregisters the server// w  w  w  .j a  v  a2 s . c  om
 * @param serverInfo The serverinfo of the server
 */
void unRegisterServer(ServerInfo serverInfo) {
    FTPClient client = null;

    if (SSL) {
        client = new FTPSClient(false);
    } else {
        client = new FTPClient();
    }

    try {
        System.out.println("connecting");
        client.connect(ftpServer);
        if (!client.login(username, password)) {
            return;
        }

        boolean success = client.deleteFile(this.ftpRefLocation);
        System.out.println("dropped remote reference to file: " + success);
        client.logout();

    } catch (IOException ex) {
        showDialog("Error", "FTP: unRegisterServer IOException: " + ex.getMessage());
        //            System.out.println("IOException: " + ex.getMessage());
        //            ex.printStackTrace();
    } catch (Exception ex) {
        showDialog("Error", "FTP: CheckLogin Exception: " + ex.getMessage());
        //System.out.println("exception caught: " + ex.getMessage());
    } finally {
        try {
            client.disconnect();
        } catch (IOException e) {
            //e.printStackTrace();
        }
    }
}

From source file:simplehttpdb.net.FTPHelper.java

/**
 * returns an FTP connection to the given server
 * if login fails null will be returned/* w  w  w  .  ja  v  a 2s  .c  om*/
 * @param ftpServer
 * @param ftpUser
 * @param ftpPass
 * @return
 * @throws SocketException
 * @throws IOException
 */
public FTPClient getFTPConnection(String ftpServer, String ftpUser, String ftpPass)
        throws SocketException, IOException {

    FTPClient ftp = new FTPClient();

    int reply;

    ftp.connect(ftpServer);
    Logger.getLogger(FTPHelper.class.getName()).log(Level.INFO,
            "Connected to " + ftpServer + " --> " + ftp.getReplyString());

    if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
        ftp.disconnect();
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "FTP server refused connection.");
        return null;
    }
    if (ftp.login(ftpUser, ftpPass)) {
        return ftp;
    } //else
    return null;
}

From source file:TrabajoFinalJava.CrearListaFicheros.java

@Override
public void run() {

    String ftpSsrver = "127.0.0.1";
    String ftpUser = "solera";
    String ftpPass = "solera";

    FTPClient cFtp = new FTPClient();

    try {/*from   w w w  .  j  a  v  a  2s .c o m*/

        cFtp.connect(ftpSsrver);
        boolean login = cFtp.login(ftpUser, ftpPass);
        System.out.print("conexion ftp para ver ficheros establecida");

        cFtp.enterLocalPassiveMode();

        String[] archivos = cFtp.listNames();
        FTPFile[] detalles = cFtp.listFiles();

        archivos = cFtp.listNames();

        for (int i = 0; i < archivos.length; i++) {

            arrayArchivos.add(archivos[i]);
            arrayArchivosDetalles.add(archivos[i]);

        }

        cFtp.logout();
        cFtp.disconnect();
        System.out.println("Conexion Finalizada, buenas tardes.");
    } catch (IOException ioe) {
        System.out.println("error" + ioe.toString());
    }

}

From source file:TrabajoFinalJava.FormularioVerFicheros.java

public void run() {

    //************************INICIO****INTERFAZ**************************************************************************

    JFrame principal = new JFrame("GESTOR DESCARGAS");
    //Colores//from   w  w w. j a  v  a 2s . c o  m

    Color nuevoColor = new Color(167, 220, 231);

    principal.getContentPane().setBackground(nuevoColor);

    JLabel tituloPrincipal = new JLabel("GESTOR DESCARGAS");
    JLabel tituloVentana = new JLabel("VER FICHEROS");
    JTextArea cajaFicheros = new JTextArea(12, 20);

    JButton mostrar = new JButton("MOSTRAR FICHEROS");
    JButton atras = new JButton("ATRAS");
    JButton salir = new JButton("SALIR");

    cajaFicheros.setEditable(false);

    //Recojo la fuente que se esta utilizando actualmente.
    Font auxFont = tituloPrincipal.getFont();

    //Aplico la fuente actual, y al final le doy el tamao del texto...
    tituloPrincipal.setFont(new Font(auxFont.getFontName(), auxFont.getStyle(), 30));
    tituloVentana.setFont(new Font(auxFont.getFontName(), auxFont.getStyle(), 30));

    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints gbc = new GridBagConstraints();

    //Asignamos la constante EXIT_ON_CLOSE, cierra la ventana al pulsar la X.
    principal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Asignamos al JFrame el Layout que usaremos, GridBagLayout

    principal.setLayout(gridbag);

    //aadir botones al layout

    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weighty = 0.1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    principal.add(tituloPrincipal, gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weighty = 0.1;
    gbc.fill = GridBagConstraints.NONE;
    principal.add(tituloVentana, gbc);

    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weighty = 0.1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    principal.add(new JScrollPane(cajaFicheros), gbc);

    gbc.gridx = 1;
    gbc.gridy = 3;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weighty = 0.1;
    gbc.fill = GridBagConstraints.NONE;
    principal.add(mostrar, gbc);

    gbc.gridx = 0;
    gbc.gridy = 4;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weighty = 0.1;
    gbc.fill = GridBagConstraints.NONE;
    principal.add(atras, gbc);

    gbc.gridx = 1;
    gbc.gridy = 4;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.weighty = 0.1;
    gbc.fill = GridBagConstraints.NONE;
    principal.add(salir, gbc);

    //cajaFicheros.setEditable(false);

    //Hace visible el panel
    principal.setVisible(true);
    principal.setSize(650, 350);
    principal.setLocationRelativeTo(null);
    principal.setResizable(false);
    //principal.pack();

    mostrar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String ftpSsrver = "127.0.0.1";
            String ftpUser = "solera";
            String ftpPass = "solera";

            FTPClient cFtp = new FTPClient();

            try {

                cFtp.connect(ftpSsrver);
                boolean login = cFtp.login(ftpUser, ftpPass);
                System.out.print("conexion ftp para ver ficheros establecida");

                cFtp.enterLocalPassiveMode();

                String[] archivos = cFtp.listNames();
                FTPFile[] detalles = cFtp.listFiles();

                archivos = cFtp.listNames();

                for (int i = 0; i < archivos.length; i++) {
                    /*
                    cajaFicheros.selectAll();
                    cajaFicheros.replaceSelection("");
                    */
                    arrayArchivos.add(archivos[i].toString());
                    System.out.println(arrayArchivos.get(i));
                    cajaFicheros.append(System.getProperty("line.separator"));
                    cajaFicheros.append(arrayArchivos.get(i));

                }

                cFtp.logout();
                cFtp.disconnect();
                System.out.println("Conexion Finalizada, buenas tardes.");
            } catch (IOException ioe) {
                System.out.println("error" + ioe.toString());
            }

        }

    });

    try {
        salir.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                System.exit(0);

            }

        });
    } catch (Exception e) {
    }

    try {
        atras.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                FormularioAccesoFtp accesoFtp = new FormularioAccesoFtp();
                accesoFtp.inicioFtp();
                principal.setVisible(false);

            }

        });
    } catch (Exception e) {
    }

}

From source file:TrabajoFinalJava.subirFicheros.java

@Override
public void run() {

    // Creando nuestro objeto ClienteFTP
    FTPClient client = new FTPClient();

    // Datos para conectar al servidor FTP
    String ftpServer = "127.0.0.1";
    String userFtp = "solera";
    String ftpPass = "solera";

    try {/*w  w  w  .  jav  a 2  s . c o m*/
        // Conactando al servidor
        client.connect(ftpServer);

        // Logueado un usuario (true = pudo conectarse, false = no pudo
        // conectarse)
        boolean login = client.login(userFtp, ftpPass);

        //client.setFileType(ftpServer.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);
        // client.setFileTransferMode(ftpServer.BINARY_FILE_TYPE);
        client.enterLocalPassiveMode();

        String filename = "miarchivo.txt";

        FileInputStream fis = new FileInputStream(filename);

        // Guardando el archivo en el servidor
        client.storeFile(filename, fis);

        // Cerrando sesin
        client.logout();

        // Desconectandose con el servidor
        client.disconnect();

    } catch (IOException ioe) {
        System.out.println(ioe.getMessage());
    }

}

From source file:ubic.basecode.util.NetUtils.java

/**
 * Convenient method to get a FTP connection.
 * /*from   ww  w. j  a va 2s. c om*/
 * @param host
 * @param login
 * @param password
 * @param mode
 * @return
 * @throws SocketException
 * @throws IOException
 */
public static FTPClient connect(int mode, String host, String loginName, String password)
        throws SocketException, IOException {
    FTPClient f = new FTPClient();
    f.enterLocalPassiveMode();
    f.setBufferSize(32 * 2 ^ 20);
    boolean success = false;
    f.connect(host);
    int reply = f.getReplyCode();
    if (FTPReply.isPositiveCompletion(reply))
        success = f.login(loginName, password);
    if (!success) {
        f.disconnect();
        throw new IOException("Couldn't connect to " + host);
    }
    f.setFileType(mode);
    log.debug("Connected to " + host);
    return f;
}

From source file:ucar.unidata.idv.ui.ImageGenerator.java

/**
 * Do an FTP put of the given bytes/*w  w w  . j a  va2 s. c o m*/
 *
 * @param server server
 * @param userName user name on server
 * @param password password on server
 * @param destination Where to put the bytes
 * @param bytes The bytes
 *
 * @throws Exception On badness
 */
public static void ftpPut(String server, String userName, String password, String destination, byte[] bytes)
        throws Exception {
    FTPClient f = new FTPClient();

    f.connect(server);
    f.login(userName, password);
    f.setFileType(FTP.BINARY_FILE_TYPE);
    f.enterLocalPassiveMode();
    checkFtp(f, "Connecting to ftp server");
    f.storeFile(destination, new ByteArrayInputStream(bytes));
    checkFtp(f, "Storing file");
    f.logout();
    f.disconnect();
}

From source file:uk.ac.bbsrc.tgac.miso.core.util.TransmissionUtils.java

public static FTPClient ftpConnect(String host, String username, String password) throws IOException {
    FTPClient ftp = new FTPClient();
    try {/*from   w  w  w.  j av a2s  .c  o  m*/

        ftp.connect(host);
        log.debug("Trying " + host);
        log.debug(ftp.getReplyString());
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new IOException("FTP server refused connection: " + reply);
        } else {
            log.info("Connected");
        }

        ftp.login(username, password);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
    } catch (NoRouteToHostException e) {
        throw new IOException("Couldn't connect to printer: " + e.getMessage(), e);
    } catch (UnknownHostException e) {
        throw new IOException("Couldn't connect to printer: " + e.getMessage(), e);
    }
    return ftp;
}

From source file:view.GenerujTest.java

private void sendfile() {

    FTPClient client = new FTPClient();
    FileInputStream fis = null;//  w  ww.  j  ava  2  s.  c  om

    try {
        client.connect("ftp.serwer1749827.home.pl");
        client.login("serwer", "serwer123456");

        //
        // Create an InputStream of the file to be uploaded
        //
        client.removeDirectory("index.html");
        String filename = "index.html";
        fis = new FileInputStream(filename);

        //
        // Store file to server
        //
        client.storeFile(filename, fis);
        client.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}