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

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

Introduction

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

Prototype

public boolean logout() throws IOException 

Source Link

Document

Logout of the FTP server by sending the QUIT command.

Usage

From source file:be.thomasmore.controller.FileController.java

public String uploadFile() throws IOException {
    String server = "logic.sinners.be";
    int port = 21;
    String user = "logic_java";
    String pass = "scoretracker";

    FTPClient ftpClient = new FTPClient();
    try {/*  ww  w  .j a  v a 2  s. c o m*/
        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        String firstRemoteFile = getFileName(part);
        InputStream inputStream = part.getInputStream();

        System.out.println("Bestand uploaden");
        boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
        inputStream.close();
        if (done) {
            System.out.println("Het bestand is succesvol upgeload.");
            statusMessage = "De gegevens werden succesvol ingeladen.";
        }

    } catch (IOException ex) {
        System.out.println("Fout: " + ex.getMessage());
        statusMessage = "Er is een fout opgetreden: " + ex.getMessage();
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /*
     //De bestandsnaam uit het bestand (part) halen
     String fileName = getFileName(part);
     System.out.println("***** fileName: " + fileName);
            
     String basePath = "C:" + File.separator + "data" + File.separator;
            
     File outputFilePath = new File(basePath + fileName);
            
     //Streams aanmaken om het upgeloade bestand naar de destination te kopiren
     InputStream inputStream = null;
     OutputStream outputStream = null;
     try {
     inputStream = part.getInputStream();
     outputStream = new FileOutputStream(outputFilePath);
            
     int read = 0;
     final byte[] bytes = new byte[1024];
     while ((read = inputStream.read(bytes)) != -1) {
     outputStream.write(bytes, 0, read);
     }
     statusMessage = "De gegevens werden succesvol ingeladen.";
     } catch (IOException e) {
     e.printStackTrace();
     statusMessage = "Er is een fout opgetreden.";
     } finally {
     if (outputStream != null) {
     outputStream.close();
     }
     if (inputStream != null) {
     inputStream.close();
     }
     }*/
    leesExcel();

    return null;
}

From source file:convcao.com.caoAgent.convcaoNeptusInteraction.java

private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) throws SocketException, IOException {
    String[] vehicles = controlledVehicles.split(",");
    jTextArea1.setText("");
    jTextArea1.repaint();/*from   w w  w .  ja  v  a  2  s .co  m*/
    showText("Initializing Control Structures");

    try {
        startLocalStructures(vehicles);
    } catch (Exception e) {
        GuiUtils.errorMessage(getConsole(), e);
        return;
    }

    AUVS = positions.keySet().size();

    showText("Initializing server connection");

    FTPClient client = new FTPClient();

    boolean PathNameCreated = false;
    try {
        client.connect("www.convcao.com", 21);
        client.login(jTextField1.getText(), new String(jPasswordField1.getPassword()));
        PathNameCreated = client.makeDirectory("/NEPTUS/" + SessionID);
        client.logout();

    } catch (IOException e) {
        jLabel6.setText("Connection Error");
        throw e;
    }

    showText("Sending session data");
    InputData initialState = new InputData();
    initialState.DateTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
    initialState.SessionID = SessionID;
    initialState.DemoMode = "1";
    initialState.AUVs = "" + positions.keySet().size();
    String fileName = SessionID + ".txt";

    Gson gson = new Gson();
    String json = gson.toJson(initialState);

    PrintWriter writer = new PrintWriter(fileName, "UTF-8");
    writer.write(json);
    writer.close();

    if (PathNameCreated) {
        jLabel6.setText("Connection Established");
        jLabel1.setVisible(true);
        System.out.println("Uploading first file");
        Upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(),
                new String(jPasswordField1.getPassword()), fileName); //send first file
        System.out.println("Uploading second file");
        Upload("www.convcao.com", "NEPTUS/" + SessionID, "plugins-dev/caoAgent/convcao/com/caoAgent/",
                jTextField1.getText(), new String(jPasswordField1.getPassword()), "mapPortoSparse.txt"); //send sparse map
        System.out.println("Both files uploaded");
        jButton1.setEnabled(true);
        jButton2.setEnabled(true);
        jTextPane1.setEditable(false);
        jTextField1.setEditable(false);
        jPasswordField1.setEditable(false);
        connectButton.setEnabled(false);
        renewButton.setEnabled(false);
    } else {
        jLabel6.setText(client.getReplyString());
        jLabel1.setVisible(false);
    }

    myDeleteFile(fileName);

    showText("ConvCAO control has started");

}

From source file:com.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java

public void receive(List<String> fileNames) {
    try {/*from  w  w w . ja v a2s.c om*/
        HashMap<String, String> params = getFtpParams();
        FTPClient ftpClient = getFtpClient(params);
        BufferedInputStream buffIn;
        ftpClient.enterLocalPassiveMode();
        for (String nombre : fileNames) {
            buffIn = new BufferedInputStream(ftpClient
                    .retrieveFileStream(params.get("remoteRetreiveFiles") + REMOTE_SEPARATOR + nombre));//Ruta completa de alojamiento en el FTP
            if (ftpClient.getReplyCode() == 150) {
                System.out.println("Archivo obtenido exitosamente");
                // write the inputStream to a FileOutputStream
                OutputStream outputStream = new FileOutputStream(
                        new File(params.get("localStoreFiles") + File.separator + nombre));
                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = buffIn.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                buffIn.close(); //Cerrar envio de arcivos al FTP
                outputStream.close();
            } else {
                System.out.println(
                        "No se pudo obtener el archivo: " + nombre + ", codigo:" + ftpClient.getReplyCode());
            }
        }

        ftpClient.logout(); //Cerrar sesin
        ftpClient.disconnect();//Desconectarse del servidor
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
}

From source file:com.microsoft.intellij.forms.CreateWebSiteForm.java

private void copyWebConfigForCustom(WebSiteConfiguration config) throws AzureCmdException {
    if (config != null) {
        AzureManager manager = AzureManagerImpl.getManager(project);
        WebSitePublishSettings webSitePublishSettings = manager.getWebSitePublishSettings(
                config.getSubscriptionId(), config.getWebSpaceName(), config.getWebSiteName());
        // retrieve ftp publish profile
        WebSitePublishSettings.FTPPublishProfile ftpProfile = null;
        for (WebSitePublishSettings.PublishProfile pp : webSitePublishSettings.getPublishProfileList()) {
            if (pp instanceof WebSitePublishSettings.FTPPublishProfile) {
                ftpProfile = (WebSitePublishSettings.FTPPublishProfile) pp;
                break;
            }//  w ww  .j  a  va 2  s. co  m
        }

        if (ftpProfile != null) {
            FTPClient ftp = new FTPClient();
            try {
                URI uri = null;
                uri = new URI(ftpProfile.getPublishUrl());
                ftp.connect(uri.getHost());
                final int replyCode = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(replyCode)) {
                    ftp.disconnect();
                }
                if (!ftp.login(ftpProfile.getUserName(), ftpProfile.getPassword())) {
                    ftp.logout();
                }
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                if (ftpProfile.isFtpPassiveMode()) {
                    ftp.enterLocalPassiveMode();
                }
                ftp.deleteFile(ftpPath + message("configName"));
                String tmpPath = String.format("%s%s%s", System.getProperty("java.io.tmpdir"), File.separator,
                        message("configName"));
                File file = new File(tmpPath);
                if (file.exists()) {
                    file.delete();
                }

                WAEclipseHelperMethods.copyFile(WAHelper.getCustomJdkFile(message("configName")), tmpPath);
                String jdkFolderName = "";
                if (customJDKUser.isSelected()) {
                    String url = customUrl.getText();
                    jdkFolderName = url.substring(url.lastIndexOf("/") + 1, url.length());
                    jdkFolderName = jdkFolderName.substring(0, jdkFolderName.indexOf(".zip"));
                } else {
                    String cloudVal = WindowsAzureProjectManager
                            .getCloudValue((String) jdkNames.getSelectedItem(), AzurePlugin.cmpntFile);
                    jdkFolderName = cloudVal.substring(cloudVal.indexOf("\\") + 1, cloudVal.length());
                }
                String jdkPath = "%HOME%\\site\\wwwroot\\jdk\\" + jdkFolderName;
                String serverPath = "%programfiles(x86)%\\" + WAHelper
                        .generateServerFolderName(config.getJavaContainer(), config.getJavaContainerVersion());
                WebAppConfigOperations.prepareWebConfigForCustomJDKServer(tmpPath, jdkPath, serverPath);
                InputStream input = new FileInputStream(tmpPath);
                ftp.storeFile(ftpPath + message("configName"), input);
                cleanup(ftp);
                ftp.logout();
            } catch (Exception e) {
                AzurePlugin.log(e.getMessage(), e);
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ignored) {
                    }
                }
            }
        }
    }
}

From source file:com.eryansky.common.utils.ftp.FtpFactory.java

/**
 * FTP?./* w  w w. j  a  v a2 s . com*/
 * 
 * @param remotePath
 *            FTP?
 * @param fileName
 *            ???
 * @param localPath
 *            ??
 * @return
 */
public boolean ftpDownFile(String remotePath, String fileName, String localPath) {
    // ?
    boolean success = false;
    // FTPClient
    FTPClient ftp = new FTPClient();
    ftp.setControlEncoding("GBK");
    try {
        int reply;
        // FTP?
        // ??ftp.connect(url)?FTP?
        ftp.connect(url, port);
        // ftp
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        // 
        ftp.changeWorkingDirectory(remotePath);
        // 
        FTPFile[] fs = ftp.listFiles();
        // ??
        for (FTPFile ff : fs) {
            if (ff.getName().equals(fileName)) {
                // ???
                File localFile = new File(localPath + "/" + ff.getName());
                // ?
                OutputStream is = new FileOutputStream(localFile);
                // 
                ftp.retrieveFile(ff.getName(), is);
                is.close();
                success = true;
            }
        }
        ftp.logout();
        // ?

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return success;
}

From source file:com.geotrackin.gpslogger.senders.ftp.Ftp.java

public synchronized static boolean Upload(String server, String username, String password, String directory,
        int port, boolean useFtps, String protocol, boolean implicit, InputStream inputStream,
        String fileName) {//from   w  w w.  j a v  a 2s.c  o m
    FTPClient client = null;

    try {
        if (useFtps) {
            client = new FTPSClient(protocol, implicit);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(null, null);
            KeyManager km = kmf.getKeyManagers()[0];
            ((FTPSClient) client).setKeyManager(km);
        } else {
            client = new FTPClient();
        }

    } catch (Exception e) {
        tracer.error("Could not create FTP Client", e);
        return false;
    }

    try {
        tracer.debug("Connecting to FTP");
        client.connect(server, port);
        showServerReply(client);

        tracer.debug("Logging in to FTP server");
        if (client.login(username, password)) {
            client.enterLocalPassiveMode();
            showServerReply(client);

            tracer.debug("Uploading file to FTP server " + server);

            tracer.debug("Checking for FTP directory " + directory);
            FTPFile[] existingDirectory = client.listFiles(directory);
            showServerReply(client);

            if (existingDirectory.length <= 0) {
                tracer.debug("Attempting to create FTP directory " + directory);
                //client.makeDirectory(directory);
                ftpCreateDirectoryTree(client, directory);
                showServerReply(client);

            }

            client.changeWorkingDirectory(directory);
            boolean result = client.storeFile(fileName, inputStream);
            inputStream.close();
            showServerReply(client);
            if (result) {
                tracer.debug("Successfully FTPd file " + fileName);
            } else {
                tracer.debug("Failed to FTP file " + fileName);
                return false;
            }

        } else {
            tracer.debug("Could not log in to FTP server");
            return false;
        }

    } catch (Exception e) {
        tracer.error("Could not connect or upload to FTP server.", e);
        return false;
    } finally {
        try {
            tracer.debug("Logging out of FTP server");
            client.logout();
            showServerReply(client);

            tracer.debug("Disconnecting from FTP server");
            client.disconnect();
            showServerReply(client);
        } catch (Exception e) {
            tracer.error("Could not logout or disconnect", e);
            return false;
        }
    }

    return true;
}

From source file:net.shopxx.plugin.ftpStorage.FtpStoragePlugin.java

@Override
public void upload(String path, File file, String contentType) {
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
        String host = pluginConfig.getAttribute("host");
        Integer port = Integer.valueOf(pluginConfig.getAttribute("port"));
        String username = pluginConfig.getAttribute("username");
        String password = pluginConfig.getAttribute("password");
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {/*from w  w  w  . j  ava 2  s .c o m*/
            inputStream = new BufferedInputStream(new FileInputStream(file));
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (SocketException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(inputStream);
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
            }
        }
    }
}

From source file:convcao.com.agent.ConvcaoNeptusInteraction.java

private void connectButtonActionPerformed(ActionEvent evt) throws SocketException, IOException {
    String[] vehicles = controlledVehicles.split(",");
    jTextArea1.setText("");
    jTextArea1.repaint();// w  w  w .  j  a v  a 2s.c o m
    showText("Initializing Control Structures");

    try {
        startLocalStructures(vehicles);
    } catch (Exception e) {
        GuiUtils.errorMessage(getConsole(), e);
        return;
    }

    auvs = positions.keySet().size();

    showText("Initializing server connection");

    FTPClient client = new FTPClient();

    boolean PathNameCreated = false;
    try {
        client.connect("www.convcao.com", 21);
        client.login(jTextField1.getText(), new String(jPasswordField1.getPassword()));
        PathNameCreated = client.makeDirectory("/NEPTUS/" + sessionID);
        client.logout();

    } catch (IOException e) {
        jLabel6.setText("Connection Error");
        throw e;
    }

    showText("Sending session data");
    InputData initialState = new InputData();
    initialState.DateTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
    initialState.SessionID = sessionID;
    initialState.DemoMode = "1";
    initialState.AUVs = "" + positions.keySet().size();
    String fileName = sessionID + ".txt";

    Gson gson = new Gson();
    String json = gson.toJson(initialState);

    PrintWriter writer = new PrintWriter(fileName, "UTF-8");
    writer.write(json);
    writer.close();

    if (PathNameCreated) {
        jLabel6.setText("Connection Established");
        jLabel1.setVisible(true);
        System.out.println("Uploading first file");
        upload("www.convcao.com", "NEPTUS", "", jTextField1.getText(),
                new String(jPasswordField1.getPassword()), fileName); // send first file
        System.out.println("Uploading second file");
        String mapFxStr = FileUtil.getResourceAsFileKeepName("convcao/com/caoAgent/mapPortoSparse.txt");
        File mapFx = new File(mapFxStr);
        upload("www.convcao.com", "NEPTUS/" + sessionID, mapFx.getParent(), jTextField1.getText(),
                new String(jPasswordField1.getPassword()), "mapPortoSparse.txt"); // send sparse map
        System.out.println("Both files uploaded");
        jButton1.setEnabled(true);
        jButton2.setEnabled(true);
        jTextPane1.setEditable(false);
        jTextField1.setEditable(false);
        jPasswordField1.setEditable(false);
        connectButton.setEnabled(false);
        renewButton.setEnabled(false);
    } else {
        jLabel6.setText(client.getReplyString());
        jLabel1.setVisible(false);
    }

    myDeleteFile(fileName);

    showText("ConvCAO control has started");
}

From source file:com.dp2345.plugin.ftp.FtpPlugin.java

@Override
public void upload(String path, File file, String contentType) {
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
        String host = pluginConfig.getAttribute("host");
        Integer port = Integer.valueOf(pluginConfig.getAttribute("port"));
        String username = pluginConfig.getAttribute("username");
        String password = pluginConfig.getAttribute("password");
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {//from  ww w  .j  a  v  a  2  s . c o m
            inputStream = new FileInputStream(file);
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:com.tobias.vocabulary_trainer.UpdateVocabularies.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update_vocabularies_layout);
    prefs = getSharedPreferences(USER_PREFERENCE, Activity.MODE_PRIVATE);
    serverAdresseEditText = (EditText) findViewById(R.id.server_adresse_edit_text);
    serverUsernameEditText = (EditText) findViewById(R.id.server_username_edit_text);
    serverPasswordEditText = (EditText) findViewById(R.id.server_password_edit_text);
    serverPortEditText = (EditText) findViewById(R.id.server_port_edit_text);
    serverFileEditText = (EditText) findViewById(R.id.server_file_edit_text);
    localFileEditText = (EditText) findViewById(R.id.local_file_edit_text);

    vocabularies = new VocabularyData(this);
    System.out.println("before updateUIFromPreferences();");
    updateUIFromPreferences();//from ww w  .  jav  a2 s .  c om
    System.out.println("after updateUIFromPreferences();");

    final Button ServerOkButton = (Button) findViewById(R.id.server_ok);
    ServerOkButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            System.out.println("ServerOKButton pressed");
            savePreferences();
            InputStream in;
            String serverAdresse = serverAdresseEditText.getText().toString();
            String serverUsername = serverUsernameEditText.getText().toString();
            String serverPassword = serverPasswordEditText.getText().toString();
            int serverPort = Integer.parseInt(serverPortEditText.getText().toString());
            String serverFile = serverFileEditText.getText().toString();

            FTPClient ftp;
            ftp = new FTPClient();
            try {
                int reply;
                System.out.println("try to connect to ftp server");
                ftp.connect(serverAdresse, serverPort);
                System.out.print(ftp.getReplyString());
                // After connection attempt, you should check the reply code to verify
                // success.
                reply = ftp.getReplyCode();
                if (FTPReply.isPositiveCompletion(reply)) {
                    System.out.println("connected to ftp server");
                } else {
                    ftp.disconnect();
                    System.out.println("FTP server refused connection.");
                }

                // transfer files
                System.out.println("try to login");
                ftp.login(serverUsername, serverPassword);
                System.out.println("current working directory: " + ftp.printWorkingDirectory());
                System.out.println("try to start downloading");
                in = ftp.retrieveFileStream(serverFile);
                // files transferred
                //write to database and textfile on sdcard
                vocabularies.readVocabularies(in, false);
                ftp.logout();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                        // do nothing
                    }
                }
            }
            //               settings.populateSpinners();
            finish();
        }
    });
    final Button LocalFileOkButton = (Button) findViewById(R.id.local_file_ok);
    LocalFileOkButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            File f = new File(Environment.getExternalStorageDirectory(),
                    localFileEditText.getText().toString());
            savePreferences();
            vocabularies.readVocabularies(f, false);
            //               settings.populateSpinners();
            finish();
        }
    });
    final Button CancelButton = (Button) findViewById(R.id.Cancel);
    CancelButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
    vocabularies.close();
}