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

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

Introduction

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

Prototype

@Override
public void disconnect() throws IOException 

Source Link

Document

Closes the connection to the FTP server and restores connection parameters to the default values.

Usage

From source file:simplehttpdb.DBAccessWorker.java

/**
 * write a key-value pair to the given server
 * in case hexKey != null the value will be encrypted by use of the given key
 * in case no update is required the function won't write to the server
 *
 * FIXME: switching between encrypted and plain text is not supported yet
 * FIXME: using different keys for the same server is not supported yet
 *
 * @param webURL/*www. ja va 2 s .  c  o m*/
 * @param ftpServer
 * @param ftpUser
 * @param ftpPass
 * @param rootDir
 * @param hexKey
 * @param name
 * @param value
 * @return
 * @throws DecodingExeption
 * @throws EncodingExeption
 */
public int write(String webURL, String ftpServer, String ftpUser, String ftpPass, String rootDir, String hexKey,
        String name, String value) throws DecodingExeption, EncodingExeption {

    Logger.getLogger(DBAccessWorker.class.getName()).log(Level.INFO,
            "\n\nwrite:\n" + "webURL: " + webURL + "\nftpServer: " + ftpServer + "\nftpUser: " + ftpUser
                    + "\nrootDir: " + rootDir + "\nhexKey: " + hexKey + "\nname: " + name + "\nvalue: " + value
                    + "\n");

    int result = -1;
    String relPath = http.findLocationOfName(webURL, name);
    FTPClient ftpClient = null;
    try {

        Logger.getLogger(DBAccessWorker.class.getName()).log(Level.INFO, "relpath=" + relPath);

        if (relPath == null) { //entry doesn't exist yet
            if (hexKey == null) {
                relPath = "free/";
            } else {
                relPath = "crypt/";
            }
            ftpClient = ftp.getFTPConnection(ftpServer, ftpUser, ftpPass);
            relPath = ftp.findFileToAddNewEntry(ftpClient, rootDir, relPath);
        } else {
            //we got the name of the file
        }
        Logger.getLogger(DBAccessWorker.class.getName()).log(Level.INFO, "relpath(2)=" + relPath);

        //handling files
        Entries localList = http.getListFromUrl(webURL + relPath, hexKey);
        //if file is not existing we just continue with the empty list

        //check if value changed after all
        String oldValue = localList.getValue(name);
        if ((oldValue == null) || (!oldValue.equals(value))) { //ok, we have to write to ftp

            localList.put(new Entry(name, value));

            if (ftpClient == null) { //for performace issues, ftp only got initialized in case
                                     //there was no entry found in the index already
                                     //so it might be required to initialize it here
                ftpClient = ftp.getFTPConnection(ftpServer, ftpUser, ftpPass);
            }
            if (ftp.storeFileAndUpdateIndex(webURL, rootDir, ftpClient, name, relPath, localList, hexKey)) {
                result = 0;
            }
        } else {
            //no update was necessary
            result = 0;
        }

        //Logger.getLogger(DBAccessWorker.class.getName()).log(Level.INFO, "logout");
        if (ftpClient != null) {
            ftpClient.logout();
        }
    } catch (SocketException ex) {
        Logger.getLogger(DBAccessWorker.class.getName()).log(Level.SEVERE, null, ex);
        return -1;
    } catch (IOException ex) {
        Logger.getLogger(DBAccessWorker.class.getName()).log(Level.SEVERE, null, ex);
        return -1;
    } finally {
        if ((ftpClient != null) && (ftpClient.isConnected())) {
            try {
                //Logger.getLogger(DBAccessWorker.class.getName()).log(Level.INFO, "disconnect");
                ftpClient.disconnect();
            } catch (IOException ex) {
                return -1;
            }
        }

    }
    return result;
}

From source file:simplehttpdb.net.FTPHelper.java

/**
 * returns an FTP connection to the given server
 * if login fails null will be returned/*from   w ww.j a  v a 2s .com*/
 * @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:smilehouse.opensyncro.defaultcomponents.ftp.FTPDestination.java

public void take(String data, DestinationInfo info, MessageLogger logger)
        throws FailTransferException, AbortTransferException {

    FTPClient ftp = new FTPClient();

    try {/*from  w  w  w . j av a 2s  .c  om*/
        // -----------------
        // Try to connect...
        // -----------------
        String host = this.data.getAttribute(HOST_ATTR);
        int port = -1;
        String portStr = this.data.getAttribute(PORT_ATTR);
        if (portStr != null && portStr.length() > 0) {
            try {
                port = Integer.parseInt(portStr);
            } catch (NumberFormatException nfe) {
                logger.logMessage("Invalid value '" + portStr + "' for port.", this, MessageLogger.ERROR);
                PipeComponentUtils.failTransfer();
            }
        }
        int reply;

        try {
            if (port != -1) {
                ftp.connect(host, port);
            } else {
                ftp.connect(host);
            }
        } catch (SocketException e) {
            logger.logMessage("SocketException while connecting to host " + host + ", aborting", this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        } catch (IOException e) {
            logger.logMessage("IOException while connecting to host " + host + ", aborting", this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                /**
                 * ftp.disconnect() is called only as additional clean-up here, so we choose to
                 * ignore possible exceptions
                 */
            }
            logger.logMessage("Couldn't connect to the FTP server: " + ftp.getReplyString(), this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // -----------
        // Then log in
        // -----------

        try {
            if (!ftp.login(this.data.getAttribute(USER_ATTR), this.data.getAttribute(PASSWORD_ATTR))) {
                logger.logMessage("Could not log in, check your username and password settings.", this,
                        MessageLogger.ERROR);
                ftp.logout();

                PipeComponentUtils.failTransfer();
            }
        } catch (IOException e) {
            logger.logMessage("IOException while logging in to FTP server", this, MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // Use passive mode
        ftp.enterLocalPassiveMode();

        // -----------------
        // ASCII or binary ?
        // -----------------
        boolean fileTypeSetOk = false;

        try {
            switch (getFileType()) {
            case FILE_TYPE_ASCII:
                fileTypeSetOk = ftp.setFileType(FTP.ASCII_FILE_TYPE);
                break;
            case FILE_TYPE_BINARY:
                fileTypeSetOk = ftp.setFileType(FTP.BINARY_FILE_TYPE);
            }
            if (!fileTypeSetOk) {
                logger.logMessage("Could not set file type: " + ftp.getReplyString(), this,
                        MessageLogger.WARNING);
            }
        } catch (IOException e) {
            logger.logMessage("IOException while setting file transfer type parameter", this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // -------------
        // Send the data
        // -------------
        String fileName = getFileName();
        logger.logMessage("Storing file: " + fileName, this, MessageLogger.DEBUG);
        String charSet = this.data.getAttribute(CHARSET_ATTR);
        if (charSet == null || charSet.length() == 0)
            charSet = DEFAULT_CHARSET;
        InputStream dataStream = null;
        try {
            dataStream = new ByteArrayInputStream(data.getBytes(charSet));
        } catch (UnsupportedEncodingException e1) {

            logger.logMessage(charSet + " charset not supported", this, MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }
        try {
            if (!ftp.storeFile(fileName, dataStream)) {
                logger.logMessage("Could not store file '" + fileName + "': " + ftp.getReplyString(), this,
                        MessageLogger.ERROR);
                PipeComponentUtils.failTransfer();
            }
        } catch (IOException e) {
            logger.logMessage("IOException while uploading the file to FTP server", this, MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }
}

From source file:smilehouse.opensyncro.defaultcomponents.ftp.FTPSource.java

public String[] give(SourceInfo info, MessageLogger logger)
        throws FailTransferException, AbortTransferException {

    // This component does not support iteration, so we output all our data
    // once (and only once)
    if (this.allDataOutput == true)
        return null;
    else/*from   ww  w.jav  a 2 s . c om*/
        this.allDataOutput = true;

    String[] dataArray = new String[1];
    FTPClient ftp = new FTPClient();

    try {
        // -----------------
        // Try to connect...
        // -----------------
        String host = this.data.getAttribute(HOST_ATTR);
        int port = -1;
        String portStr = this.data.getAttribute(PORT_ATTR);
        if (portStr != null && portStr.length() > 0) {
            try {
                port = Integer.parseInt(portStr);
            } catch (NumberFormatException nfe) {
                logger.logMessage("Invalid value '" + portStr + "' for port.", this, MessageLogger.ERROR);
                PipeComponentUtils.failTransfer();
            }
        }
        int reply;

        try {

            if (port != -1) {
                ftp.connect(host, port);
            } else {
                ftp.connect(host);
            }

        } catch (SocketException e) {
            logger.logMessage("SocketException while connecting to host " + host + ", aborting", this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        } catch (IOException e) {
            logger.logMessage("IOException while connecting to host " + host + ", aborting", this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                /**
                 * ftp.disconnect() is called only as additional clean-up here, so we choose to
                 * ignore possible exceptions
                 */
            }
            logger.logMessage("Couldn't connect to the FTP server: " + ftp.getReplyString(), this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // -----------
        // Then log in
        // -----------
        try {
            if (!ftp.login(this.data.getAttribute(USER_ATTR), this.data.getAttribute(PASSWORD_ATTR))) {
                logger.logMessage("Could not log in, check your username and password settings.", this,
                        MessageLogger.ERROR);
                ftp.logout();

                PipeComponentUtils.failTransfer();
            }

        } catch (IOException e) {
            logger.logMessage("IOException while logging in to FTP server", this, MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // Use passive mode
        ftp.enterLocalPassiveMode();

        // -----------------
        // ASCII or binary ?
        // -----------------
        boolean fileTypeSetOk = false;
        try {
            switch (getFileType()) {
            case FILE_TYPE_ASCII:
                fileTypeSetOk = ftp.setFileType(FTP.ASCII_FILE_TYPE);
                break;
            case FILE_TYPE_BINARY:
                fileTypeSetOk = ftp.setFileType(FTP.BINARY_FILE_TYPE);
            }
            if (!fileTypeSetOk) {
                logger.logMessage("Could not set file type: " + ftp.getReplyString(), this,
                        MessageLogger.WARNING);
            }
        } catch (IOException e) {
            logger.logMessage("IOException while setting file transfer type parameter", this,
                    MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }

        // -----------------
        // Retrieve the data
        // -----------------
        String fileName = getFileName(logger);
        logger.logMessage("Retrieving file: " + fileName, this, MessageLogger.DEBUG);
        OutputStream dataStream = new ByteArrayOutputStream();
        try {
            if (!ftp.retrieveFile(fileName, dataStream)) {
                logger.logMessage("Could not retrieve file '" + fileName + "': " + ftp.getReplyString(), this,
                        MessageLogger.WARNING);
                PipeComponentUtils.abortTransfer();
            }
            String charSet = this.data.getAttribute(CHARSET_ATTR);
            if (charSet == null || charSet.length() == 0)
                charSet = DEFAULT_CHARSET;
            dataArray[0] = ((ByteArrayOutputStream) dataStream).toString(charSet);
        } catch (IOException e) {
            logger.logMessage("IOException while downloading file from FTP server", this, MessageLogger.ERROR);
            PipeComponentUtils.failTransfer();
        }
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }
    return dataArray;
}

From source file:srv.update.java

public void getVersao(View view) {
    String server = "ftp.atmatech.com.br";
    int port = 21;
    String user = "atmatech";
    String pass = "ftpp2015";
    FTPClient ftpClient = new FTPClient();
    try {//  w  w 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);
        ftpClient.changeWorkingDirectory("/atmatech.com.br/atualizacaosac/");

        // APPROACH #1: using retrieveFile(String, OutputStream)
        String[] arq = ftpClient.listNames();
        for (String f : arq) {
            if (!f.equals(".")) {
                if (!f.equals("..")) {
                    if (f.contains(".")) {
                        view.jLprogresso.setText(f);
                        String remoteFile1 = "/atmatech.com.br/atualizacaosac/" + f;
                        String destino = ".\\" + f;
                        File downloadFile1 = new File(destino);
                        OutputStream outputStream1 = new BufferedOutputStream(
                                new FileOutputStream(downloadFile1));
                        boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
                        outputStream1.close();
                        if (!success) {
                            JOptionPane.showMessageDialog(null, "Erro Em Baixar Verso");
                            System.exit(0);
                        }
                    } else {
                        ftpClient.changeWorkingDirectory("/atmatech.com.br/atualizacaosac/" + f);
                        String[] arq2 = ftpClient.listNames();
                        for (String f2 : arq2) {
                            if (!f2.equals(".")) {
                                if (!f2.equals("..")) {
                                    view.jLprogresso.setText(f2);
                                    File diretorio = new File(".\\" + f);
                                    if (!diretorio.exists()) {
                                        diretorio.mkdirs(); //mkdir() cria somente um diretrio, mkdirs() cria diretrios e subdiretrios.
                                    }
                                    String remoteFile1 = "/atmatech.com.br/atualizacaosac/" + f + "/" + f2;
                                    String destino = ".\\" + f + "\\" + f2;
                                    File downloadFile1 = new File(destino);
                                    OutputStream outputStream1 = new BufferedOutputStream(
                                            new FileOutputStream(downloadFile1));
                                    boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
                                    outputStream1.close();
                                    if (!success) {
                                        JOptionPane.showMessageDialog(null, "Erro Em Baixar Verso");
                                        System.exit(0);
                                    }
                                }
                            }
                        }

                    }

                }
            }
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Erro \n" + ex);
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Erro \n" + ex);
        }
    }
}

From source file:testing.FTPClientExample.java

public static final void main(String[] args) {
    boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;/*from www. j  a  va 2  s .c  o  m*/
    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;

    args = new String[100];

    args[0] = "-d";
    args[1] = "localhost";
    args[2] = "adminroot";
    args[3] = "adminroot";

    args[4] = "RSAPrivate.key";
    args[5] = ".\\FTPServer2\\RSAPrivate.key";

    int base = 0;
    OUTER: for (base = 0; base < args.length; base++) {
        switch (args[base]) {
        case "-s":
            storeFile = true;
            break;
        case "-a":
            localActive = true;
            break;
        case "-b":
            binaryTransfer = true;
            break;
        case "-c":
            doCommand = args[++base];
            minParams = 3;
            break;
        case "-d":
            mlsd = true;
            minParams = 3;
            break;
        case "-e":
            useEpsvWithIPv4 = true;
            break;
        case "-f":
            feat = true;
            minParams = 3;
            break;
        case "-h":
            hidden = true;
            break;
        case "-k":
            keepAliveTimeout = Long.parseLong(args[++base]);
            break;
        case "-l":
            listFiles = true;
            minParams = 3;
            break;
        case "-L":
            lenient = true;
            break;
        case "-n":
            listNames = true;
            minParams = 3;
            break;
        case "-p":
            protocol = args[++base];
            break;
        case "-t":
            mlst = true;
            minParams = 3;
            break;
        case "-w":
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
            break;
        case "-T":
            trustmgr = args[++base];
            break;
        case "-PrH":
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
            break;
        case "-PrU":
            proxyUser = args[++base];
            break;
        case "-PrP":
            proxyPassword = args[++base];
            break;
        case "-#":
            printHash = true;
            break;
        default:
            break OUTER;
        }
    }

    int remain = args.length - base;
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    String username = args[base++];
    String 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.");
            System.exit(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();
        System.exit(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);
        }

        // 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
            }
        }
    }

    System.exit(error ? 1 : 0);
}

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 ww .jav  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 ww  . j  av  a2s .c om*/

    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 {/*from  w w w  . ja v a  2s  .  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:tufts.oki.dr.fedora.DR.java

public osid.shared.Id ingest(String fileName, String templateFileName, String fileType, File file,
        Properties properties) throws osid.dr.DigitalRepositoryException, java.net.SocketException,
        java.io.IOException, osid.shared.SharedException, javax.xml.rpc.ServiceException {
    long sTime = System.currentTimeMillis();
    if (DEBUG)//w  w  w  .j ava  2  s  .c o m
        System.out
                .println("INGESTING FILE TO FEDORA:fileName =" + fileName + "fileType =" + fileType + "t = 0");
    // this part transfers file to a ftp server.  this is required since the content management part of fedora server needs object to be on web server
    String host = FedoraUtils.getFedoraProperty(this, "admin.ftp.address");
    String url = FedoraUtils.getFedoraProperty(this, "admin.ftp.url");
    int port = Integer.parseInt(FedoraUtils.getFedoraProperty(this, "admin.ftp.port"));
    String userName = FedoraUtils.getFedoraProperty(this, "admin.ftp.username");
    String password = FedoraUtils.getFedoraProperty(this, "admin.ftp.password");
    String directory = FedoraUtils.getFedoraProperty(this, "admin.ftp.directory");
    FTPClient client = new FTPClient();
    client.connect(host, port);
    client.login(userName, password);
    client.changeWorkingDirectory(directory);
    client.setFileType(FTP.BINARY_FILE_TYPE);
    client.storeFile(fileName, new FileInputStream(file.getAbsolutePath().replaceAll("%20", " ")));
    client.logout();
    client.disconnect();
    if (DEBUG)
        System.out.println(
                "INGESTING FILE TO FEDORA: Writting to FTP Server:" + (System.currentTimeMillis() - sTime));
    fileName = url + fileName;
    // this part does the creation of METSFile
    int BUFFER_SIZE = 10240;
    StringBuffer sb = new StringBuffer();
    String s = new String();
    BufferedInputStream fis = new BufferedInputStream(
            new FileInputStream(new File(getResource(templateFileName).getFile().replaceAll("%20", " "))));
    //FileInputStream fis = new FileInputStream(new File(templateFileName));
    //DataInputStream in = new DataInputStream(fis);
    byte[] buf = new byte[BUFFER_SIZE];
    int ch;
    int len;
    while ((len = fis.read(buf)) > 0) {
        s = s + new String(buf);
    }
    fis.close();
    if (DEBUG)
        System.out.println("INGESTING FILE TO FEDORA: Read Mets File:" + (System.currentTimeMillis() - sTime));

    //in.close();
    //  s = sb.toString();
    //String r =  s.replaceAll("%file.location%", fileName).trim();
    String r = updateMetadata(s, fileName, file.getName(), fileType, properties);
    if (DEBUG)
        System.out.println(
                "INGESTING FILE TO FEDORA: Resplaced Metadata:" + (System.currentTimeMillis() - sTime));

    //writing the to outputfile
    File METSfile = File.createTempFile("vueMETSMap", ".xml");
    FileOutputStream fos = new FileOutputStream(METSfile);
    fos.write(r.getBytes());
    fos.close();

    //  AutoIngestor a = new AutoIngestor(address.getHost(), address.getPort(),FedoraUtils.getFedoraProperty(this,"admin.fedora.username"),FedoraUtils.getFedoraProperty(this,"admin.fedora.username"));
    //THIS WILL NOT WORK IN NEWER VERSION OF FEDORA
    // String pid =  AutoIngestor.ingestAndCommit(new FileInputStream(METSfile),"foxml1.","Test Ingest");
    if (DEBUG)
        System.out.println("INGESTING FILE TO FEDORA: Ingest complete:" + (System.currentTimeMillis() - sTime));
    String pid = "Method Not Supported any more";
    System.out.println(" METSfile= " + METSfile.getPath() + " PID = " + pid);
    return new PID(pid);
}