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

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

Introduction

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

Prototype

public FTPClient() 

Source Link

Document

Default FTPClient constructor.

Usage

From source file:facturacion.ftp.FtpServer.java

public static int sendImgFile(String fileNameServer, String hostDirServer, InputStream localFile) {
    FTPClient ftpClient = new FTPClient();
    boolean success = false;
    BufferedInputStream buffIn = null;
    try {//from  w  w w  .j  a v a 2  s  .  c om
        ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken),
                Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken)));
        ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken),
                Config.getInstance().getProperty(Config.PassFtpToken));
        ftpClient.enterLocalPassiveMode();
        /*ftpClient.connect("127.0.0.1", 21);
          ftpClient.login("erpftp", "Tribut@2014");*/
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftpClient.getReplyCode();

        System.out.println("Respuesta recibida de conexin FTP:" + reply);

        if (!FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Imposible conectarse al servidor");
            return -1;
        }

        buffIn = new BufferedInputStream(localFile);//Ruta del archivo para enviar
        ftpClient.enterLocalPassiveMode();
        //crear directorio
        success = ftpClient.makeDirectory(hostDirServer);
        System.out.println("sucess 1 = " + success);
        success = ftpClient.makeDirectory(hostDirServer + "/img");
        System.out.println("sucess 233 = " + success);
        success = ftpClient.storeFile(hostDirServer + "/img/" + fileNameServer, buffIn);
        System.out.println("sucess 3 = " + success);
    } catch (IOException ex) {

    } finally {
        try {
            if (ftpClient.isConnected()) {
                buffIn.close(); //Cerrar envio de arcivos al FTP
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            return -1;
            //ex.printStackTrace();
        }
    }
    return (success) ? 1 : 0;
}

From source file:ConnectionInfo.java

/**
 * @param parentShell//from w w w.ja  va  2 s. c  o  m
 */
public FTPWindow(Shell parentShell) {
    super(parentShell);

    createActions();

    addStatusLine();
    //addCoolBar(SWT.FLAT | SWT.RIGHT);
    addToolBar(SWT.FLAT);
    addMenuBar();

    ftp = new FTPClient();
    ftp.addProtocolCommandListener(new ProtocolCommandListener() {
        public void protocolCommandSent(ProtocolCommandEvent e) {
            logMessage("> " + e.getCommand(), false);
        }

        public void protocolReplyReceived(ProtocolCommandEvent e) {
            logMessage("< " + e.getMessage(), false);
        }
    });

}

From source file:GestoSAT.GestoSAT.java

@Schedule(dayOfWeek = "Sun-Sat", month = "*", hour = "22", dayOfMonth = "*", year = "*", minute = "0", second = "0", persistent = true)
public void generarCopia() {

    // http://chuwiki.chuidiang.org/index.php?title=Backup_de_MySQL_con_Java
    try {//from   w  ww  .  j  a  v  a2  s  .  co  m
        Process p = Runtime.getRuntime().exec("mysqldump -u " + mySQL.elementAt(2) + " -p" + mySQL.elementAt(3)
                + " -h " + mySQL.elementAt(0) + " -P " + mySQL.elementAt(1) + " gestosat");

        InputStream is = p.getInputStream();
        FileOutputStream fos = new FileOutputStream("backupGestoSAT.sql");
        byte[] buffer = new byte[1000];

        int leido = is.read(buffer);
        while (leido > 0) {
            fos.write(buffer, 0, leido);
            leido = is.read(buffer);
        }
        fos.close();

        //http://www.javamexico.org/blogs/lalo200/pequeno_ejemplo_para_subir_un_archivo_ftp_con_la_libreria_commons_net
        FTPClient clienteFTP = new FTPClient();

        // Lanza excepcin si el servidor no existe
        clienteFTP.connect(confSeg.elementAt(0), Integer.parseInt(confSeg.elementAt(1)));

        if (clienteFTP.login(confSeg.elementAt(2), confSeg.elementAt(3))) {

            clienteFTP.setFileType(FTP.BINARY_FILE_TYPE);
            BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream("backupGestoSAT.sql"));
            clienteFTP.enterLocalPassiveMode();
            clienteFTP.storeFile("backupGestoSAT.sql", buffIn);
            buffIn.close();
            clienteFTP.logout();
            clienteFTP.disconnect();
        } else
            System.out.println("Error de conexin FTP");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.quadrillenschule.azocamsyncd.ftpservice.FTPConnection.java

public void deleteFiles(int remainingNumber, LocalStorage localStorage) {
    if (remainingNumber < 0) {
        return;/*from  w w  w  . ja  va2 s .co m*/
    }
    if (ftpclient != null) {
        close();
    }
    ftpclient = new FTPClient();

    ftpclient.setDefaultTimeout(TIMEOUT);
    try {

        ftpclient.connect(getLastWorkingConnection());
        LinkedList<AZoFTPFile> afs = discoverRemoteFiles("/", false);
        int todelete = afs.size() - remainingNumber;
        if (todelete > 0) {
            notify(FTPConnectionStatus.DELETING_FILES, "", -1);
            int i = 0;
            Collections.sort(afs, new Comparator<AZoFTPFile>() {

                @Override
                public int compare(AZoFTPFile o1, AZoFTPFile o2) {
                    return o1.ftpFile.getTimestamp().compareTo(o2.ftpFile.getTimestamp());
                }
            });
            close();
            LinkedList<String> deleteables = new LinkedList();
            for (AZoFTPFile af : afs) {
                i++;
                if (localStorage.isFileSynced(af)) {
                    //   deleteSingleFile(lastWorkingConnection)
                    deleteables.add((af.dir + af.ftpFile.getName()));
                    //    System.out.println("Would delete"+af.ftpFile.getName());
                }
                if (i >= todelete) {
                    break;
                }
            }
            simplyConnect(FTP.ASCII_FILE_TYPE);
            for (String s : deleteables) {
                ftpclient.deleteFile(s);

            }
            //   remountSD(deleteables);
            notify(FTPConnectionStatus.SUCCESS, "", -1);

        } else {
            close();
        }

    } catch (IOException ex) {
        close();
    }
    close();
}

From source file:com.jason.thrift.TransmitHandler.java

/**
 * Description: ?FTP?// www . j  a va 2s. c o  m
 * 
 * @Version1.0 Jul 27, 2008 4:31:09 PM by ?cuihongbao@d-heaven.com
 * @param url
 *            FTP?hostname
 * @param port
 *            FTP??
 * @param username
 *            FTP?
 * @param password
 *            FTP?
 * @param path
 *            FTP??
 * @param filename
 *            FTP???
 * @param input
 *            ?
 * @return ?true?false
 */
public static boolean uploadFile(String url, int port, String username, String password, String path,
        String filename, InputStream input) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {
        int reply;
        ftp.connect(url, port);// FTP?
        // ??ftp.connect(url)?FTP?
        ftp.login(username, password);// 
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        ftp.changeWorkingDirectory(path);
        ftp.storeFile(filename, input);

        input.close();
        ftp.logout();
        success = true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return success;
}

From source file:com.microsoft.azure.management.appservice.samples.ManageWebAppSourceControl.java

private static void uploadFileToFtp(PublishingProfile profile, String fileName, InputStream file)
        throws Exception {
    FTPClient ftpClient = new FTPClient();
    String[] ftpUrlSegments = profile.ftpUrl().split("/", 2);
    String server = ftpUrlSegments[0];
    String path = "./site/wwwroot/webapps";
    ftpClient.connect(server);//  w  ww.  j av a  2  s.  com
    ftpClient.login(profile.ftpUsername(), profile.ftpPassword());
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    ftpClient.changeWorkingDirectory(path);
    ftpClient.storeFile(fileName, file);
    ftpClient.disconnect();
}

From source file:jsfml1.NewJFrame.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    try {//  w w w . j a v  a2 s .  com
        // TODO add your handling code here:

        File f = new File(date + ".html");
        FileWriter fw = new FileWriter(f);
        fw.write("<!--" + date + " " + ose + " " + username + " is good ! -->");
        fw.write("<head>");
        fw.write("<style>");
        fw.write("body {");
        fw.write("background: #121212;");
        fw.write("color: white;");
        fw.write("text-align: center;");
        fw.write("}");
        fw.write("</style>");
        fw.write("<title>Listening on</title>");
        fw.write("</head>");
        fw.write("<body>");
        fw.write("Listening on: <br/><br/>");
        fw.write("<audio controls=\"controls\"> <source src=\"" + date + ".wav\"> </audio>");
        fw.write("</body>");
        fw.close();

        JOptionPane jop = new JOptionPane();
        jButton4.setText("Uploaded fine !");
        FTPClient ftp = new FTPClient();
        ftp.connect("ftp.cluster1.easy-hebergement.net", 21);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.user("toNSite");
        ftp.pass("tonMotDePasse");
        InputStream is0 = new FileInputStream(date + ".html");
        InputStream is = new FileInputStream(date + ".wav");
        ftp.storeFile("/uploads/" + date + ".html", is0);
        ftp.storeFile("/uploads/" + date + ".wav", is);
        is.close();
        Desktop.getDesktop().browse(new URI("http://focaliser.fr/uploads/" + date + ".html"));
    } catch (MalformedURLException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (URISyntaxException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ddf.test.itests.catalog.TestFtp.java

private FTPClient createInsecureClient() throws Exception {
    FTPClient ftp = new FTPClient();

    int attempts = 0;
    while (true) {
        try {// w  w  w .  jav a  2 s  .  c o m
            ftp.connect(FTP_SERVER, Integer.parseInt(FTP_PORT.getPort()));
            break;
        } catch (SocketException e) {
            // a socket exception can be thrown if the ftp server is still in the process of coming up
            // or down
            Thread.sleep(1000);
            if (attempts++ > 30) {
                throw e;
            }
        }
    }

    showServerReply(ftp);
    int connectionReply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(connectionReply)) {
        fail("FTP server refused connection: " + connectionReply);
    }

    boolean success = ftp.login(USERNAME, PASSWORD);
    showServerReply(ftp);
    if (!success) {
        fail("Could not log in to the FTP server.");
    }

    ftp.enterLocalPassiveMode();
    ftp.setControlKeepAliveTimeout(300);
    ftp.setFileType(FTP.BINARY_FILE_TYPE);

    return ftp;
}

From source file:com.jsystem.j2autoit.AutoItAgent.java

private static void getFileFtp(String user, String password, String host, int port, String fileName,
        String location) throws Exception {
    Log.info("\nretrieve " + fileName + NEW_LINE);
    FTPClient client = new FTPClient();

    client.connect(host, port); //connect to the management ftp server
    int reply = client.getReplyCode(); // check connection

    if (!FTPReply.isPositiveCompletion(reply)) {
        throw new Exception("FTP fail to connect");
    }//ww  w  .  j  a va 2  s  .c  o  m

    if (!client.login(user, password)) { //check login
        throw new Exception("FTP fail to login");
    }

    //      FileOutputStream fos = null;
    try {
        File locationFile = new File(location);
        File dest = new File(locationFile, fileName);
        if (dest.exists()) {
            dest.delete();
        } else {
            locationFile.mkdirs();
        }
        boolean status = client.changeWorkingDirectory("/");
        Log.info("chdir-status:" + status + NEW_LINE);
        client.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        client.setFileType(FTPClient.BINARY_FILE_TYPE);
        client.enterLocalActiveMode();

        InputStream in = client.retrieveFileStream(fileName);
        if (in == null) {
            Log.error("Input stream is null\n");
            throw new Exception("Fail to retrieve file " + fileName);
        }
        Thread.sleep(3000);
        saveInputStreamToFile(in, new File(location, fileName));
    } finally {
        client.disconnect();
    }

}

From source file:facturacion.ftp.FtpServer.java

public static InputStream getFileInputStream(String remote_file_ruta) {
    FTPClient ftpClient = new FTPClient();
    try {//from  w ww.j av  a  2s . com
        ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken),
                Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken)));
        ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken),
                Config.getInstance().getProperty(Config.PassFtpToken));
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        //ftpClient.enterLocalPassiveMode();
        // crear directorio
        //OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(file_ruta));
        //System.out.println("File #1 has been downloaded successfully. 1");
        //FileInputStream fis = new FileInputStream("C:\\Users\\aaguerra\\Desktop\\firmado2.p12");
        //InputStream is = fis;
        System.out.println("File ruta=" + "1/" + remote_file_ruta);
        InputStream is = ftpClient.retrieveFileStream(remote_file_ruta);

        if (is == null)
            System.out.println("File #1 es null");
        else
            System.out.println("File #1 no es null");

        //return ftpClient.retrieveFileStream(remote_file_ruta);
        return is;
    } catch (IOException ex) {
        System.out.println("File #1 has been downloaded successfully. 222");
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            System.out.println("File #1 has been downloaded successfully. 3");
            return null;
            //ex.printStackTrace();
        }
    }
    return null;
}