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:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java

@Override
public void publishWebArchiveArtifact(@NotNull String subscriptionId, @NotNull String webSpaceName,
        @NotNull String webSiteName, @NotNull String artifactPath, @NotNull boolean isDeployRoot,
        @NotNull String artifactName) throws AzureCmdException {
    WebSitePublishSettings webSitePublishSettings = getWebSitePublishSettings(subscriptionId, webSpaceName,
            webSiteName);//w w  w .  jav a2  s . c  o m
    WebSitePublishSettings.FTPPublishProfile publishProfile = null;
    for (PublishProfile pp : webSitePublishSettings.getPublishProfileList()) {
        if (pp instanceof FTPPublishProfile) {
            publishProfile = (FTPPublishProfile) pp;
            break;
        }
    }

    if (publishProfile == null) {
        throw new AzureCmdException("Unable to retrieve FTP credentials to publish web site");
    }

    URI uri;

    try {
        uri = new URI(publishProfile.getPublishUrl());
    } catch (URISyntaxException e) {
        throw new AzureCmdException("Unable to parse FTP Publish Url information", e);
    }

    final FTPClient ftp = new FTPClient();

    try {
        ftp.connect(uri.getHost());
        final int replyCode = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftp.disconnect();
            throw new AzureCmdException("Unable to connect to FTP server");
        }

        if (!ftp.login(publishProfile.getUserName(), publishProfile.getPassword())) {
            ftp.logout();
            throw new AzureCmdException("Unable to login to FTP server");
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        if (publishProfile.isFtpPassiveMode()) {
            ftp.enterLocalPassiveMode();
        }

        String targetDir = getAbsolutePath(uri.getPath());
        targetDir += "/webapps";

        InputStream input = new FileInputStream(artifactPath);
        if (isDeployRoot) {
            ftp.storeFile(targetDir + "/ROOT.war", input);
        } else {
            ftp.storeFile(targetDir + "/" + artifactName + ".war", input);
        }
        input.close();
        ftp.logout();
    } catch (IOException e) {
        throw new AzureCmdException("Unable to connect to the FTP server", e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downDesitin() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {/*from w  w  w.j av  a  2  s  .  c  om*/
        FileInputStream access = new FileInputStream(Constants.DIR_DESITIN + "/access.ami.csv");
        BufferedReader br = new BufferedReader(new InputStreamReader(access, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            // Semicolon is used as a separator
            String[] gln = line.split(";");
            if (gln.length > 2) {
                if (gln[0].equals("ftp_amiko")) {
                    fl = gln[0];
                    fp = gln[1];
                    fs = gln[2];
                }
            }
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FTPClient ftp_client = new FTPClient();
    try {
        ftp_client.connect(fs, 21);
        ftp_client.login(fl, fp);
        ftp_client.enterLocalPassiveMode();
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        System.out.println("- Connected to server " + fs + "...");

        // Set working directory
        String working_dir = "ywesee_in";
        ftp_client.changeWorkingDirectory(working_dir);
        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }
        // Get list of filenames
        FTPFile[] ftpFiles = ftp_client.listFiles();
        if (ftpFiles != null && ftpFiles.length > 0) {
            // ... then download all csv files
            for (FTPFile f : ftpFiles) {
                String remote_file = f.getName();
                if (remote_file.endsWith("csv")) {
                    String local_file = remote_file;
                    if (remote_file.startsWith("Kunden"))
                        local_file = Constants.FILE_CUST_DESITIN;
                    if (remote_file.startsWith("Artikel"))
                        local_file = Constants.FILE_ARTICLES_DESITIN;
                    OutputStream os = new FileOutputStream(Constants.DIR_DESITIN + "/" + local_file);
                    System.out.print("- Downloading " + remote_file + " from server " + fs + "... ");
                    boolean done = ftp_client.retrieveFile(remote_file, os);
                    if (done)
                        System.out.println("success.");
                    else
                        System.out.println("error.");
                    os.close();
                }
            }
        }
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

public void downZurRose() {
    String fl = "";
    String fp = "";
    String fs = "";
    try {/*w ww .  j a va  2s.co  m*/
        FileInputStream access = new FileInputStream(Constants.DIR_ZURROSE + "/access.ami.csv");
        BufferedReader br = new BufferedReader(new InputStreamReader(access, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            // Semicolon is used as a separator
            String[] gln = line.split(";");
            if (gln.length > 2) {
                if (gln[0].equals("P_ywesee")) {
                    fl = gln[0];
                    fp = gln[1];
                    fs = gln[2];
                }
            }
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FTPClient ftp_client = new FTPClient();
    try {
        ftp_client.connect(fs, 21);
        ftp_client.login(fl, fp);
        ftp_client.enterLocalPassiveMode();
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        System.out.println("- Connected to server " + fs + "...");

        String[] working_dir = { "ywesee out", "../ywesee in" };

        for (int i = 0; i < working_dir.length; ++i) {
            // Set working directory
            ftp_client.changeWorkingDirectory(working_dir[i]);
            int reply = ftp_client.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp_client.disconnect();
                System.err.println("FTP server refused connection.");
                return;
            }
            // Get list of filenames
            FTPFile[] ftpFiles = ftp_client.listFiles();
            if (ftpFiles != null && ftpFiles.length > 0) {
                // ... then download all csv files
                for (FTPFile f : ftpFiles) {
                    String remote_file = f.getName();
                    if (remote_file.endsWith("csv")) {
                        String local_file = remote_file;
                        if (remote_file.startsWith("Artikelstamm"))
                            local_file = Constants.CSV_FILE_DISPO_ZR;
                        OutputStream os = new FileOutputStream(Constants.DIR_ZURROSE + "/" + local_file);
                        System.out.print("- Downloading " + remote_file + " from server " + fs + "... ");
                        boolean done = ftp_client.retrieveFile(remote_file, os);
                        if (done)
                            System.out.println("success.");
                        else
                            System.out.println("error.");
                        os.close();
                    }
                }
            }
        }
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.peter.javaautoupdater.JavaAutoUpdater.java

public static void run(String ftpHost, int ftpPort, String ftpUsername, String ftpPassword,
        boolean isLocalPassiveMode, boolean isRemotePassiveMode, String basePath, String softwareName,
        String args[]) {//from  ww  w  . j av a2  s  .  c o m
    System.out.println("jarName=" + jarName);
    for (String arg : args) {
        if (arg.toLowerCase().trim().equals("-noautoupdate")) {
            return;
        }
    }
    JavaAutoUpdater.basePath = basePath;
    JavaAutoUpdater.softwareName = softwareName;
    JavaAutoUpdater.args = args;

    if (!jarName.endsWith(".jar") || jarName.startsWith("JavaAutoUpdater-")) {
        if (isDebug) {
            jarName = "test.jar";
        } else {
            return;
        }
    }
    JProgressBarDialog d = new JProgressBarDialog(new JFrame(), "Auto updater", true);

    d.progressBar.setIndeterminate(true);
    d.progressBar.setStringPainted(true);
    d.progressBar.setString("Updating");
    //      d.addCancelEventListener(this);
    Thread longRunningThread = new Thread() {
        public void run() {
            d.progressBar.setString("checking latest version");
            System.out.println("checking latest version");

            FTPClient ftp = new FTPClient();
            try {
                ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
                ftp.connect(ftpHost, ftpPort);
                int reply = ftp.getReplyCode();
                System.out.println("reply=" + reply + ", " + FTPReply.isPositiveCompletion(reply));
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    JOptionPane.showMessageDialog(null, "FTP server refused connection", "error",
                            JOptionPane.ERROR_MESSAGE);
                }
                d.progressBar.setString("connected to ftp");
                System.out.println("connected to ftp");
                boolean success = ftp.login(ftpUsername, ftpPassword);
                if (!success) {
                    ftp.disconnect();
                    JOptionPane.showMessageDialog(null, "FTP login fail, can't update software", "error",
                            JOptionPane.ERROR_MESSAGE);
                }
                if (isLocalPassiveMode) {
                    ftp.enterLocalPassiveMode();
                }
                if (isRemotePassiveMode) {
                    ftp.enterRemotePassiveMode();
                }
                FTPFile[] ftpFiles = ftp.listFiles(basePath, new FTPFileFilter() {
                    @Override
                    public boolean accept(FTPFile file) {
                        if (file.getName().startsWith(softwareName)) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                });
                if (ftpFiles.length > 0) {
                    FTPFile targetFile = ftpFiles[ftpFiles.length - 1];
                    System.out.println("targetFile : " + targetFile.getName() + " , " + targetFile.getSize()
                            + "!=" + new File(jarName).length());
                    if (!targetFile.getName().equals(jarName)
                            || targetFile.getSize() != new File(jarName).length()) {
                        int r = JOptionPane.showConfirmDialog(null,
                                "Confirm to update to " + targetFile.getName(), "Question",
                                JOptionPane.YES_NO_OPTION);
                        if (r == JOptionPane.YES_OPTION) {
                            //ftp.enterRemotePassiveMode();
                            d.progressBar.setString("downloading " + targetFile.getName());
                            ftp.setFileType(FTP.BINARY_FILE_TYPE);
                            ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);

                            d.progressBar.setIndeterminate(false);
                            d.progressBar.setMaximum(100);
                            CopyStreamAdapter streamListener = new CopyStreamAdapter() {

                                @Override
                                public void bytesTransferred(long totalBytesTransferred, int bytesTransferred,
                                        long streamSize) {
                                    int percent = (int) (totalBytesTransferred * 100 / targetFile.getSize());
                                    d.progressBar.setValue(percent);
                                }
                            };
                            ftp.setCopyStreamListener(streamListener);
                            try (FileOutputStream fos = new FileOutputStream(targetFile.getName())) {
                                ftp.retrieveFile(basePath + "/" + targetFile.getName(), fos);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            d.progressBar.setString("restarting " + targetFile.getName());
                            restartApplication(targetFile.getName());
                        }
                    }

                }
                ftp.logout();
                ftp.disconnect();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };
    d.thread = longRunningThread;
    d.setVisible(true);
}

From source file:de.ep3.ftpc.controller.portal.CrawlerDownloadController.java

@Override
public void mouseClicked(MouseEvent e) {
    CrawlerResultsItem.PreviewPanel previewPanel = (CrawlerResultsItem.PreviewPanel) e.getSource();
    CrawlerResult crawlerResult = previewPanel.getCrawlerResult();
    CrawlerFile crawlerFile = crawlerResult.getFile();

    FTPClient ftpClient = crawlerResult.getFtpClient();

    if (ftpClient.isConnected()) {
        JOptionPane.showMessageDialog(portalFrame, i18n.translate("crawlerDownloadWhileConnected"), null,
                JOptionPane.ERROR_MESSAGE);
        return;//from  w  ww.j ava2 s .  c  o  m
    }

    String fileExtension = crawlerFile.getExtension();

    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter chooserFilter = new FileNameExtensionFilter(
            i18n.translate("fileType", fileExtension.toUpperCase()), crawlerFile.getExtension());

    chooser.setApproveButtonText(i18n.translate("buttonSave"));
    chooser.setDialogTitle(i18n.translate("fileDownloadTo"));
    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
    chooser.setFileFilter(chooserFilter);
    chooser.setSelectedFile(new File(crawlerFile.getName()));

    int selection = chooser.showSaveDialog(portalFrame);

    if (selection == JFileChooser.APPROVE_OPTION) {
        File fileToSave = chooser.getSelectedFile();

        Server relatedServer = crawlerResult.getServer();

        try {
            ftpClient.connect(relatedServer.need("server.ip"),
                    Integer.parseInt(relatedServer.need("server.port")));

            int replyCode = ftpClient.getReplyCode();

            if (!FTPReply.isPositiveCompletion(replyCode)) {
                throw new IOException(i18n.translate("crawlerServerRefused"));
            }

            if (relatedServer.has("user.name")) {
                String userName = relatedServer.get("user.name");
                String userPassword = "";

                if (relatedServer.hasTemporary("user.password")) {
                    userPassword = relatedServer.getTemporary("user.password");
                }

                boolean loggedIn = ftpClient.login(userName, userPassword);

                if (!loggedIn) {
                    throw new IOException(i18n.translate("crawlerServerAuthFail"));
                }
            }

            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            /* Download file */

            InputStream is = ftpClient.retrieveFileStream(crawlerFile.getFullName());

            if (is != null) {

                byte[] rawFile = new byte[(int) crawlerFile.getSize()];

                int i = 0;

                while (true) {
                    int b = is.read();

                    if (b == -1) {
                        break;
                    }

                    rawFile[i] = (byte) b;
                    i++;

                    /* Occasionally update the download progress */

                    if (i % 1024 == 0) {
                        int progress = Math.round((((float) i) / crawlerFile.getSize()) * 100);

                        status.add(i18n.translate("crawlerDownloadProgress", progress));
                    }
                }

                is.close();
                is = null;

                if (!ftpClient.completePendingCommand()) {
                    throw new IOException();
                }

                Files.write(fileToSave.toPath(), rawFile);
            }

            /* Logout and disconnect */

            ftpClient.logout();

            tryDisconnect(ftpClient);

            status.add(i18n.translate("crawlerDownloadDone"));
        } catch (IOException ex) {
            tryDisconnect(ftpClient);

            JOptionPane.showMessageDialog(portalFrame, i18n.translate("crawlerDownloadFailed", ex.getMessage()),
                    null, JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:com.o6Systems.utils.net.FTPModule.java

private int executeFtpCommand(String[] args) throws UnknownHostException {
    boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;//w w w .j  av a2  s  .  c om
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;

    int base = 0;

    // Print the command

    System.out.println("----------FTP MODULE CALL----------");

    for (int i = 0; i < args.length; i++) {
        System.out.println(args[i]);
    }

    System.out.println("--------------------");
    //

    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        } else if (args[base].equals("-b")) {
            binaryTransfer = true;
        } else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            return 1;
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        return 1;
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftp.storeFile(remote, input);

            input.close();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }

            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                        Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                  Command listener has already printed the output
                //                    for(String s : ftp.getReplyStrings()) {
                //                        System.out.println(s);
                //                    }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftp.retrieveFile(remote, output);

            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    return error ? 1 : 0;
}

From source file:com.netpace.aims.controller.application.WapApplicationHelper.java

public static boolean wapFTPZipFile(File transferFile) throws AimsException {

    log.debug("wapFTPZipFile FTP Start. FileName: " + transferFile.getName());
    boolean loginStatus = false;
    boolean dirChanged = false;

    FileInputStream transferStream = null;
    FTPClient ftpClient = new FTPClient();

    ConfigEnvProperties envProperties = ConfigEnvProperties.getInstance();
    //ftp server config
    String ftpServerAddress = envProperties.getProperty("wap.images.ftp.server.address");
    String ftpUser = envProperties.getProperty("wap.images.ftp.user.name");
    String ftpPassword = envProperties.getProperty("wap.images.ftp.user.password");
    String ftpWorkingDirectory = envProperties.getProperty("wap.images.ftp.working.dir");

    //general exception for ftp transfer
    AimsException aimsException = new AimsException("Error");
    aimsException.addException(new AimsException("error.wap.app.ftp.transfer"));

    String errorMessage = "";

    boolean transfered = false;
    try {/*from  w  ww. j a va2s .c o  m*/
        ftpClient.connect(ftpServerAddress);
        loginStatus = ftpClient.login(ftpUser, ftpPassword);
        log.debug("Connection to server " + ftpServerAddress + " " + (loginStatus ? "success" : "failure"));
        if (loginStatus) {
            dirChanged = ftpClient.changeWorkingDirectory(ftpWorkingDirectory);
            log.debug("change remote directory to " + ftpWorkingDirectory + ": " + dirChanged);
            if (dirChanged) {
                transferStream = new FileInputStream(transferFile);
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                transfered = ftpClient.storeFile(transferFile.getName(), transferStream);
                log.debug(transferFile.getName() + " transfered: " + transfered + " on server: "
                        + ftpServerAddress);
                if (!transfered) {
                    errorMessage = "File: " + transferFile.getName() + " not transfered to "
                            + (ftpServerAddress + "/" + ftpServerAddress);
                    System.out.println("Error in FTP Transfer: " + errorMessage);
                    sendFTPErrorMail(errorMessage);
                    throw aimsException;
                }
            } else {
                errorMessage = "Directory: " + ftpWorkingDirectory + " not found in " + ftpServerAddress;
                System.out.println("Error in FTP Transfer: " + errorMessage);
                sendFTPErrorMail(errorMessage);
                throw aimsException;
            }
        } //end loginstatus
        else {
            errorMessage = "FTP Authentication failed. \n\nServer: " + ftpServerAddress + "\nUserID: " + ftpUser
                    + "\nPassword: " + ftpPassword;
            System.out.println("Error in FTP Transfer: " + errorMessage);
            sendFTPErrorMail(errorMessage);
            throw aimsException;
        }
    } //end try
    catch (FileNotFoundException e) {
        System.out.println("Exception: " + transferFile.getName() + " not found in temp directory");
        e.printStackTrace();//zip file not found
        throw aimsException;
    } catch (IOException ioe) {
        System.out.println("Exception: Error in connection " + ftpServerAddress);
        ioe.printStackTrace();
        sendFTPErrorMail("Error in connection to : " + ftpServerAddress + "\n\n"
                + MiscUtils.getExceptionStackTraceInfo(ioe));
        throw aimsException;
    } finally {
        try {
            //close stream
            if (transferStream != null) {
                transferStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    //logout. Issues QUIT command
                    ftpClient.logout();
                } catch (IOException ioex) {
                    ioex.printStackTrace();
                } finally {
                    try {
                        //disconnect ftp session
                        ftpClient.disconnect();
                    } catch (IOException ioexc) {
                        ioexc.printStackTrace();
                    }
                }
            }
        }

    }
    log.debug("wapFTPZipFile FTP end. FileName: " + transferFile.getName() + "\t transfered: " + transfered);
    return transfered;
}

From source file:com.ut.healthelink.service.impl.transactionOutManagerImpl.java

/**
 * The 'FTPTargetFile' function will get the FTP details and send off the generated file
 *
 * @param batchId The id of the batch to FTP the file for
 */// ww  w  .j  ava  2 s  .  com
private void FTPTargetFile(int batchId, configurationTransport transportDetails) throws Exception {

    try {

        /* Update the status of the batch to locked */
        transactionOutDAO.updateBatchStatus(batchId, 22);

        List<transactionTarget> targets = transactionOutDAO.getTransactionsByBatchDLId(batchId);

        if (!targets.isEmpty()) {

            for (transactionTarget target : targets) {

                /* Need to update the uploaded batch status */
                transactionInManager.updateBatchStatus(target.getbatchUploadId(), 22, "");

                /* Need to update the uploaded batch transaction status */
                transactionInManager.updateTransactionStatus(target.getbatchUploadId(),
                        target.gettransactionInId(), 0, 37);

                /* Update the downloaded batch transaction status */
                transactionOutDAO.updateTargetTransasctionStatus(target.getbatchDLId(), 37);

            }

        }

        /* get the batch details */
        batchDownloads batchFTPFileInfo = transactionOutDAO.getBatchDetails(batchId);

        /* Get the FTP Details */
        configurationFTPFields ftpDetails = configurationTransportManager
                .getTransportFTPDetailsPush(transportDetails.getId());

        if ("SFTP".equals(ftpDetails.getprotocol())) {

            JSch jsch = new JSch();
            Session session = null;
            ChannelSftp channel = null;
            FileInputStream localFileStream = null;

            String user = ftpDetails.getusername();
            int port = ftpDetails.getport();
            String host = ftpDetails.getip();

            Organization orgDetails = organizationManager.getOrganizationById(
                    configurationManager.getConfigurationById(transportDetails.getconfigId()).getorgId());

            if (ftpDetails.getcertification() != null && !"".equals(ftpDetails.getcertification())) {

                File newFile = null;

                fileSystem dir = new fileSystem();
                dir.setDir(orgDetails.getcleanURL(), "certificates");

                jsch.addIdentity(new File(dir.getDir() + ftpDetails.getcertification()).getAbsolutePath());
                session = jsch.getSession(user, host, port);
            } else if (ftpDetails.getpassword() != null && !"".equals(ftpDetails.getpassword())) {
                session = jsch.getSession(user, host, port);
                session.setPassword(ftpDetails.getpassword());
            }

            session.setConfig("StrictHostKeyChecking", "no");
            session.setTimeout(2000);

            session.connect();

            channel = (ChannelSftp) session.openChannel("sftp");

            channel.connect();

            if (ftpDetails.getdirectory() != null && !"".equals(ftpDetails.getdirectory())) {
                channel.cd(ftpDetails.getdirectory());

                String fileName = null;

                int findExt = batchFTPFileInfo.getoutputFIleName().lastIndexOf(".");

                if (findExt >= 0) {
                    fileName = batchFTPFileInfo.getoutputFIleName();
                } else {
                    fileName = new StringBuilder().append(batchFTPFileInfo.getoutputFIleName()).append(".")
                            .append(transportDetails.getfileExt()).toString();
                }

                //Set the directory to save the brochures to
                fileSystem dir = new fileSystem();

                String filelocation = transportDetails.getfileLocation();
                filelocation = filelocation.replace("/bowlink/", "");
                dir.setDirByName(filelocation);

                File file = new File(dir.getDir() + fileName);

                if (file.exists()) {
                    FileInputStream fileInput = new FileInputStream(file);

                    channel.put(fileInput, fileName);
                }

            }

            channel.disconnect();
            session.disconnect();

        } else {
            FTPClient ftp;

            if ("FTP".equals(ftpDetails.getprotocol())) {
                ftp = new FTPClient();
            } else {
                FTPSClient ftps;
                ftps = new FTPSClient(true);

                ftp = ftps;
                ftps.setTrustManager(null);
            }

            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            ftp.setDefaultTimeout(3000);
            ftp.setConnectTimeout(3000);

            if (ftpDetails.getport() > 0) {
                ftp.connect(ftpDetails.getip(), ftpDetails.getport());
            } else {
                ftp.connect(ftpDetails.getip());
            }

            int reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
            } else {
                ftp.login(ftpDetails.getusername(), ftpDetails.getpassword());

                ftp.enterLocalPassiveMode();

                String fileName = null;

                int findExt = batchFTPFileInfo.getoutputFIleName().lastIndexOf(".");

                if (findExt >= 0) {
                    fileName = batchFTPFileInfo.getoutputFIleName();
                } else {
                    fileName = new StringBuilder().append(batchFTPFileInfo.getoutputFIleName()).append(".")
                            .append(transportDetails.getfileExt()).toString();
                }

                //Set the directory to save the brochures to
                fileSystem dir = new fileSystem();

                String filelocation = transportDetails.getfileLocation();
                filelocation = filelocation.replace("/bowlink/", "");
                dir.setDirByName(filelocation);

                File file = new File(dir.getDir() + fileName);

                FileInputStream fileInput = new FileInputStream(file);

                ftp.changeWorkingDirectory(ftpDetails.getdirectory());
                ftp.storeFile(fileName, fileInput);
                ftp.logout();
                ftp.disconnect();

            }
        }

        // we should delete file now that we ftp'ed the file
        try {
            fileSystem dir = new fileSystem();
            String filelocation = transportDetails.getfileLocation();
            filelocation = filelocation.replace("/bowlink/", "");
            dir.setDirByName(filelocation);

            File sourceFile = new File(dir.getDir() + batchFTPFileInfo.getoutputFIleName());
            if (sourceFile.exists()) {
                sourceFile.delete();
            }

            transactionOutDAO.updateBatchStatus(batchId, 23);

            for (transactionTarget target : targets) {

                /* Need to update the uploaded batch status */
                transactionInManager.updateBatchStatus(target.getbatchUploadId(), 23, "");

                /* Need to update the uploaded batch transaction status */
                transactionInManager.updateTransactionStatus(target.getbatchUploadId(),
                        target.gettransactionInId(), 0, 20);

                /* Update the downloaded batch transaction status */
                transactionOutDAO.updateTargetTransasctionStatus(target.getbatchDLId(), 20);

            }

        } catch (Exception e) {
            throw new Exception(
                    "Error occurred during FTP - delete file and update statuses. batchId: " + batchId, e);

        }
    } catch (Exception e) {
        throw new Exception("Error occurred trying to FTP a batch target. batchId: " + batchId, e);
    }

}

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 w  w  . j  a  v  a 2  s. c om
        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:GestoSAT.GestoSAT.java

public boolean actualizarConfiguracion(Vector<String> mySQL, Vector<String> confSeg, int iva, String logo)
        throws Exception {
    FileReader file;/*from  w w w.  ja  v  a2 s  .c  om*/
    try {
        this.iva = Math.abs(iva);

        BufferedImage image = null;
        byte[] imageByte;

        BASE64Decoder decoder = new BASE64Decoder();
        imageByte = decoder.decodeBuffer(logo.split(",")[1]);
        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        image = ImageIO.read(bis);
        bis.close();

        // write the image to a file
        File outputfile = new File("logo");
        String formato = logo.split("/")[1].split(";")[0];
        ImageIO.write(image, formato, outputfile);

        // MySQL
        if (mySQL.elementAt(0).equals(this.mySQL.elementAt(0))) {
            if (!mySQL.elementAt(1).equals(this.mySQL.elementAt(1))
                    && !mySQL.elementAt(2).equals(this.mySQL.elementAt(2))
                    && (!mySQL.elementAt(3).equals(this.mySQL.elementAt(3))
                            || !mySQL.elementAt(0).equals(""))) {
                Class.forName("com.mysql.jdbc.Driver");
                this.con.close();
                this.con = DriverManager.getConnection("jdbc:mysql://" + mySQL.elementAt(0) + ":"
                        + Math.abs(Integer.parseInt(mySQL.elementAt(1))) + "/gestosat?user="
                        + mySQL.elementAt(2) + "&password=" + mySQL.elementAt(3));

                this.mySQL.set(0, mySQL.elementAt(0));
                this.mySQL.set(1, Math.abs(Integer.parseInt(mySQL.elementAt(1))) + "");
                this.mySQL.set(2, mySQL.elementAt(2));
                this.mySQL.set(3, mySQL.elementAt(3));
            }
        } else {
            // Comprobar que pass != ""
            Process pGet = Runtime.getRuntime()
                    .exec("mysqldump -u " + this.mySQL.elementAt(2) + " -p" + this.mySQL.elementAt(3) + " -h "
                            + this.mySQL.elementAt(0) + " -P " + this.mySQL.elementAt(1) + " gestosat");

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

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

            Class.forName("com.mysql.jdbc.Driver");
            this.con.close();
            this.con = DriverManager.getConnection(
                    "jdbc:mysql://" + mySQL.elementAt(0) + ":" + Math.abs(Integer.parseInt(mySQL.elementAt(1)))
                            + "/gestosat?user=" + mySQL.elementAt(2) + "&password=" + mySQL.elementAt(3));

            this.mySQL.set(0, mySQL.elementAt(0));
            this.mySQL.set(1, Math.abs(Integer.parseInt(mySQL.elementAt(1))) + "");
            this.mySQL.set(2, mySQL.elementAt(2));
            this.mySQL.set(3, mySQL.elementAt(3));

            Process pPut = Runtime.getRuntime()
                    .exec("mysql -u " + mySQL.elementAt(2) + " -p" + mySQL.elementAt(3) + " -h "
                            + mySQL.elementAt(0) + " -P " + Math.abs(Integer.parseInt(mySQL.elementAt(1)))
                            + " gestosat");

            OutputStream os = pPut.getOutputStream();
            FileInputStream fis = new FileInputStream("backupGestoSAT.sql");
            byte[] bufferIn = new byte[1000];

            int escrito = fis.read(bufferIn);
            while (escrito > 0) {
                os.write(bufferIn, 0, leido);
                escrito = fis.read(bufferIn);
            }

            os.flush();
            os.close();
            fis.close();
        }

        // FTP

        FTPClient cliente = new FTPClient();
        if (!confSeg.elementAt(3).equals("")) {
            cliente.connect(confSeg.elementAt(0), Integer.parseInt(confSeg.elementAt(1)));

            if (cliente.login(confSeg.elementAt(2), confSeg.elementAt(3))) {
                cliente.setFileType(FTP.BINARY_FILE_TYPE);
                BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream("backupGestoSAT.sql"));
                cliente.enterLocalPassiveMode();
                cliente.storeFile("backupGestoSAT.sql", buffIn);
                buffIn.close();
                cliente.logout();
                cliente.disconnect();

                this.confSeg = confSeg;
            } else
                return false;
        }

        File archConf = new File("confGestoSAT");
        BufferedWriter bw = new BufferedWriter(new FileWriter(archConf));
        bw.write(this.mySQL.elementAt(0) + ";" + Math.abs(Integer.parseInt(this.mySQL.elementAt(1))) + ";"
                + this.mySQL.elementAt(2) + ";" + this.mySQL.elementAt(3) + ";" + this.confSeg.elementAt(0)
                + ";" + Math.abs(Integer.parseInt(this.confSeg.elementAt(1))) + ";" + this.confSeg.elementAt(2)
                + ";" + this.confSeg.elementAt(3) + ";" + Math.abs(iva));
        bw.close();

        return true;
    } catch (Exception ex) {
        file = new FileReader("confGestoSAT");
        BufferedReader b = new BufferedReader(file);
        String cadena;
        cadena = b.readLine();
        String[] valores = cadena.split(";");

        this.mySQL.add(valores[0]);
        this.mySQL.add(Math.abs(Integer.parseInt(valores[1])) + "");
        this.mySQL.add(valores[2]);
        this.mySQL.add(valores[3]);
        con.close();
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager
                .getConnection("jdbc:mysql://" + this.mySQL.elementAt(0) + ":" + this.mySQL.elementAt(1)
                        + "/gestosat?user=" + this.mySQL.elementAt(2) + "&password=" + this.mySQL.elementAt(3));

        this.confSeg.add(valores[4]);
        this.confSeg.add(Math.abs(Integer.parseInt(valores[5])) + "");
        this.confSeg.add(valores[6]);
        this.confSeg.add(valores[7]);

        file.close();
        Logger.getLogger(GestoSAT.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
}