Example usage for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE

List of usage examples for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE

Introduction

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

Prototype

int BINARY_FILE_TYPE

To view the source code for org.apache.commons.net.ftp FTP BINARY_FILE_TYPE.

Click Source Link

Document

A constant used to indicate the file(s) being transfered should be treated as a binary image, i.e., no translations should be performed.

Usage

From source file:com.glaf.core.util.FtpUtils.java

/**
 * ?//  w  ww  . j  av  a2  s. c  om
 * 
 * @param remoteFile
 *            FTP"/"
 * @param localFile
 *            
 */
public static boolean upload(String remoteFile, String localFile) {
    if (!remoteFile.startsWith("/")) {
        throw new RuntimeException(" path must start with '/'");
    }
    InputStream input = null;
    try {

        mkdirs(remoteFile.substring(0, remoteFile.lastIndexOf("/")));

        if (remoteFile.startsWith("/") && remoteFile.indexOf("/") > 0) {
            changeToDirectory(remoteFile);
            remoteFile = remoteFile.substring(remoteFile.lastIndexOf("/") + 1, remoteFile.length());
        }

        getFtpClient().setFileType(FTP.BINARY_FILE_TYPE);
        getFtpClient().enterLocalPassiveMode();
        getFtpClient().setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
        File file = new File(localFile);
        input = new FileInputStream(file);
        boolean flag = getFtpClient().storeFile(remoteFile, input);
        if (flag) {
            logger.info("upload success");
        } else {
            logger.info("upload failure");
        }
        return flag;
    } catch (IOException ex) {
        ex.printStackTrace();
        logger.error("upload error", ex);
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(input);
    }
}

From source file:com.bdaum.zoom.net.core.ftp.FtpAccount.java

/**
 * Login into a account/*from w w w.  ja v a  2s . c  o  m*/
 *
 * @return FTPClient object or null
 * @throws IOException
 */
public FTPClient login() throws IOException {
    int reply = 0;
    FTPClient ftp = new FTPClient();
    try {
        if (port != 0)
            ftp.connect(getHost(), getPort());
        else
            ftp.connect(getHost());
        if (isAnonymous())
            ftp.login(ANONYMOUS, GUEST);
        else if (getSubAccount() != null && !getSubAccount().isEmpty())
            ftp.login(getLogin(), getPassword(), getSubAccount());
        else
            ftp.login(getLogin(), getPassword());
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply))
            throw new IOException(NLS.bind(Messages.FtpAccount_ftp_server_refused, ftp.getReplyString()));
        if (isPassiveMode())
            ftp.enterLocalPassiveMode();
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
        throw e;
    }
    return ftp;
}

From source file:edu.lternet.pasta.dml.download.DownloadHandler.java

/**
 * Gets content from given source and writes it to DataStorageInterface 
 * to store them. This method will be called by run()
 * /*from   w  w w. j  ava  2s.c  o m*/
 * @param resourceName  the URL to the source data to be retrieved
 */
protected boolean getContentFromSource(String resourceName) {
    boolean successFlag = false;
    QualityCheck onlineURLsQualityCheck = null;
    boolean onlineURLsException = false; // used to determine status of onlineURLs quality check

    if (resourceName != null) {
        resourceName = resourceName.trim();
    }

    if (resourceName != null && (resourceName.startsWith("http://") || resourceName.startsWith("https://")
            || resourceName.startsWith("file://") || resourceName.startsWith("ftp://"))) {
        // get the data from a URL
        int responseCode = 0;
        String responseMessage = null;

        try {
            URL url = new URL(resourceName);
            boolean isFTP = false;

            if (entity != null) {
                String contentType = null;

                // Find the right MIME type and set it as content type
                if (resourceName.startsWith("http")) {
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("HEAD");
                    httpURLConnection.connect();
                    contentType = httpURLConnection.getContentType();
                    responseCode = httpURLConnection.getResponseCode();
                    responseMessage = httpURLConnection.getResponseMessage();
                } else if (resourceName.startsWith("file")) {
                    URLConnection urlConnection = url.openConnection();
                    urlConnection.connect();
                    contentType = urlConnection.getContentType();
                } else { // FTP
                    isFTP = true;
                    contentType = "application/octet-stream";
                }

                entity.setUrlContentType(contentType);
            }

            if (!isFTP) { // HTTP(S) or FILE
                InputStream filestream = url.openStream();

                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    filestream.close();
                }
            } else { // FTP
                String[] urlParts = resourceName.split("/");
                String address = urlParts[2];
                String dir = "/";
                for (int i = 3; i < urlParts.length - 1; i++) {
                    dir += urlParts[i] + "/";
                }
                String fileName = urlParts[urlParts.length - 1];
                FTPClient ftpClient = new FTPClient();
                ftpClient.connect(address);
                ftpClient.login(ANONYMOUS, anonymousFtpPasswd);
                ftpClient.changeWorkingDirectory(dir);
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode(); // necessary to avoid firewall blocking
                InputStream filestream = ftpClient.retrieveFileStream(fileName);
                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    try {
                        filestream.close();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(String
                                .format("Error closing local file '%s': %s", resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }

                // logout and disconnect if FTP session
                if (resourceName.startsWith("ftp") && ftpClient != null) {
                    try {
                        ftpClient.enterLocalActiveMode();
                        ftpClient.logout();
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(
                                String.format("Error disconnecting from FTP with resource '%s': %s",
                                        resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }
            }
        } catch (MalformedURLException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            onlineURLsException = true;
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is a malformed URL: %s", resourceName, eMessage));
        } catch (IOException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            if (responseCode > 0) {
                eMessage = String.format("Response Code: %d %s; %s", responseCode, responseMessage, eMessage);
            }
            onlineURLsException = true;
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is not reachable: %s", resourceName, eMessage));
        }

        // Initialize the "Online URLs are live" quality check
        String qualityCheckIdentifier = "onlineURLs";
        QualityCheck qualityCheckTemplate = QualityReport.getQualityCheckTemplate(qualityCheckIdentifier);
        onlineURLsQualityCheck = new QualityCheck(qualityCheckIdentifier, qualityCheckTemplate);

        if (QualityCheck.shouldRunQualityCheck(entity, onlineURLsQualityCheck)) {
            String resourceNameEscaped = embedInCDATA(resourceName);

            if (!onlineURLsException) {
                onlineURLsQualityCheck.setStatus(Status.valid);
                onlineURLsQualityCheck.setFound("true");
                onlineURLsQualityCheck.setExplanation("Succeeded in accessing URL: " + resourceNameEscaped);
            } else {
                onlineURLsQualityCheck.setFailedStatus();
                onlineURLsQualityCheck.setFound("false");
                String explanation = "Failed to access URL: " + resourceNameEscaped;
                explanation = explanation + "; " + embedInCDATA(exception.getMessage());
                onlineURLsQualityCheck.setExplanation(explanation);
            }

            entity.addQualityCheck(onlineURLsQualityCheck);
        }

        return successFlag;
    } else if (resourceName != null && resourceName.startsWith("ecogrid://")) {
        // get the docid from url
        int start = resourceName.indexOf("/", 11) + 1;
        //log.debug("start: " + start);
        int end = resourceName.indexOf("/", start);

        if (end == -1) {
            end = resourceName.length();
        }

        //log.debug("end: " + end);
        String ecogridIdentifier = resourceName.substring(start, end);
        // pass this docid and get data item
        //System.out.println("the endpoint is "+ECOGRIDENDPOINT);
        //System.out.println("The identifier is "+ecogridIdentifier);
        //return false;
        return getContentFromEcoGridSource(ecogridEndPoint, ecogridIdentifier);
    } else if (resourceName != null && resourceName.startsWith("srb://")) {
        // get srb docid from the url
        String srbIdentifier = transformSRBurlToDocid(resourceName);
        // reset endpoint for srb (This is hack we need to figure ou
        // elegent way to do this
        //mEndPoint = Config.getValue("//ecogridService/srb/endPoint");
        // pass this docid and get data item
        //log.debug("before get srb data");
        return getContentFromEcoGridSource(SRBENDPOINT, srbIdentifier);
    } else {
        successFlag = false;
        return successFlag;
    }
}

From source file:madkitgroupextension.export.Export.java

public static void updateFTP(FTPClient ftpClient, String _directory_dst, File _directory_src,
        File _current_file_transfert) throws IOException, TransfertException {
    ftpClient.changeWorkingDirectory("./");
    FTPListParseEngine ftplpe = ftpClient.initiateListParsing(_directory_dst);
    FTPFile files[] = ftplpe.getFiles();

    File current_file_transfert = _current_file_transfert;

    try {/*from  w ww  .ja  v a 2 s  .  co m*/
        for (File f : _directory_src.listFiles()) {
            if (f.isDirectory()) {
                if (!f.getName().equals("./") && !f.getName().equals("../")) {
                    if (_current_file_transfert != null) {
                        if (!_current_file_transfert.getCanonicalPath().startsWith(f.getCanonicalPath()))
                            continue;
                        else
                            _current_file_transfert = null;
                    }
                    boolean found = false;
                    for (FTPFile ff : files) {
                        if (f.getName().equals(ff.getName())) {
                            if (ff.isFile()) {
                                ftpClient.deleteFile(_directory_dst + ff.getName());
                            } else
                                found = true;
                            break;
                        }
                    }

                    if (!found) {
                        ftpClient.changeWorkingDirectory("./");
                        if (!ftpClient.makeDirectory(_directory_dst + f.getName() + "/"))
                            System.err.println(
                                    "Impossible to create directory " + _directory_dst + f.getName() + "/");
                    }
                    updateFTP(ftpClient, _directory_dst + f.getName() + "/", f, _current_file_transfert);
                }
            } else {
                if (_current_file_transfert != null) {
                    if (!_current_file_transfert.equals(f.getCanonicalPath()))
                        continue;
                    else
                        _current_file_transfert = null;
                }
                current_file_transfert = _current_file_transfert;
                FTPFile found = null;
                for (FTPFile ff : files) {
                    if (f.getName().equals(ff.getName())) {
                        if (ff.isDirectory()) {
                            FileTools.removeDirectory(ftpClient, _directory_dst + ff.getName());
                        } else
                            found = ff;
                        break;
                    }
                }
                if (found == null || (found.getTimestamp().getTimeInMillis() - f.lastModified()) < 0
                        || found.getSize() != f.length()) {
                    FileInputStream fis = new FileInputStream(f);
                    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                    if (!ftpClient.storeFile(_directory_dst + f.getName(), fis))
                        System.err.println("Impossible to send file: " + _directory_dst + f.getName());
                    fis.close();
                    for (FTPFile ff : ftplpe.getFiles()) {
                        if (f.getName().equals(ff.getName())) {
                            f.setLastModified(ff.getTimestamp().getTimeInMillis());
                            break;
                        }
                    }
                }
            }

        }
    } catch (IOException e) {
        throw new TransfertException(current_file_transfert, null, e);
    }
    for (FTPFile ff : files) {
        if (!ff.getName().equals(".") && !ff.getName().equals("..")) {
            boolean found = false;
            for (File f : _directory_src.listFiles()) {
                if (f.getName().equals(ff.getName()) && f.isDirectory() == ff.isDirectory()) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                if (ff.isDirectory()) {
                    FileTools.removeDirectory(ftpClient, _directory_dst + ff.getName());
                } else {
                    ftpClient.deleteFile(_directory_dst + ff.getName());
                }
            }
        }
    }
}

From source file:de.ipk_gatersleben.ag_nw.graffiti.services.GUIhelper.java

private static boolean processDownload(final BackgroundTaskStatusProviderSupportingExternalCallImpl status,
        String downloadURL, String targetFileName, ObjectRef lastStatus, final int thisRun, String server,
        String remote, final FTPClient ftp) {
    String username;//from   w ww .  ja  v  a2 s  . c  o  m
    String password;
    String local;
    username = "anonymous@" + server;
    password = "anonymous";
    local = targetFileName;

    final ObjectRef myoutputstream = new ObjectRef();

    ftp.addProtocolCommandListener(new ProtocolCommandListener() {
        public void protocolCommandSent(ProtocolCommandEvent arg0) {
            // System.out.print("out: " + arg0.getMessage());
            status.setCurrentStatusText1("Command: " + arg0.getMessage());
        }

        public void protocolReplyReceived(ProtocolCommandEvent arg0) {
            // System.out.print("in : " + arg0.getMessage());
            status.setCurrentStatusText2("Message: " + arg0.getMessage());
            if (myoutputstream.getObject() != null) {
                String msg = arg0.getMessage();
                if (msg.indexOf("Opening BINARY mode") >= 0) {
                    if (msg.indexOf("(") > 0) {
                        msg = msg.substring(msg.indexOf("(") + "(".length());
                        if (msg.indexOf(" ") > 0) {
                            msg = msg.substring(0, msg.indexOf(" "));
                            try {
                                long max = Long.parseLong(msg);
                                MyOutputStream os = (MyOutputStream) myoutputstream.getObject();
                                os.setMaxBytes(max);
                            } catch (Exception e) {
                                System.out.println(
                                        "Could not determine file length for detailed progress information");
                            }
                        }
                    }
                }
            }
        }
    });

    System.out.println("FTP DOWNLOAD: " + downloadURL);

    try {
        if (ftp.isConnected()) {
            status.setCurrentStatusText2("Using open FTP connection");
            System.out.println("Reusing open FTP connection");
        } else {
            ftp.connect(server);
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                status.setCurrentStatusText1("Can't connect to FTP server");
                status.setCurrentStatusText2("ERROR");
                return false;
            }
            if (!ftp.login("anonymous", "anonymous")) {
                if (!ftp.login(username, password)) {
                    ftp.disconnect();
                    status.setCurrentStatusText1("Can't login to FTP server");
                    status.setCurrentStatusText2("ERROR");
                    return false;
                }
            }
            status.setCurrentStatusText1("Set Binary Transfer Mode");
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            status.setCurrentStatusText2("Activate Passive Transfer Mode");
            ftp.enterLocalPassiveMode();
        }
        status.setCurrentStatusText1("Start download...");
        status.setCurrentStatusText2("Please Wait.");

        // ftp.listFiles(pathname);

        OutputStream output = new MyOutputStream(lastStatus, status, new FileOutputStream(local));
        myoutputstream.setObject(output);
        ftp.setRemoteVerificationEnabled(false);
        long tA = System.currentTimeMillis();
        boolean result = ftp.retrieveFile(remote, output);
        output.close();
        long tB = System.currentTimeMillis();
        if (!result) {
            new File(local).delete();
            MainFrame.showMessage("Can't download " + downloadURL + ". File not available.", MessageType.INFO);
        } else {
            File f = new File(local);
            System.out.println("Download completed (" + f.getAbsolutePath() + ", " + (f.length() / 1024)
                    + " KB, " + (int) ((f.length() / 1024d / (tB - tA) * 1000d)) + " KB/s).");
        }
        BackgroundTaskHelper.executeLaterOnSwingTask(10000, new Runnable() {
            public void run() {
                try {
                    synchronized (GUIhelper.class) {
                        if (runIdx == thisRun) {
                            System.out.println("Disconnect FTP connection");
                            ftp.disconnect();
                        }
                    }
                } catch (Exception err) {
                    ErrorMsg.addErrorMessage(err);
                }
            }
        });
        return result;
    } catch (Exception err) {
        System.out.println("ERROR: FTP DOWNLOAD ERROR: " + err.getMessage());
        if (ftp != null && ftp.isConnected()) {
            try {
                System.out.println("Disconnect FTP connection (following error condition)");
                ftp.disconnect();
            } catch (Exception err2) {
                ErrorMsg.addErrorMessage(err2);
            }
        }
        return false;
    }
}

From source file:it.baywaylabs.jumpersumo.twitter.TwitterListener.java

/**
 * @param host FTP Host name./*from w  w w  . j ava 2 s.com*/
 * @param port FTP port.
 * @param user FTP User.
 * @param pswd FTP Password.
 * @param c    Context
 * @return Downloaded name file or blank list if something was going wrong.
 */
private String FTPDownloadFile(String host, Integer port, String user, String pswd, Context c) {
    String result = "";
    FTPClient mFTPClient = null;

    try {
        mFTPClient = new FTPClient();
        // connecting to the host
        mFTPClient.connect(host, port);

        // Now check the reply code, if positive mean connection success
        if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {

            // Login using username & password
            boolean status = mFTPClient.login(user, pswd);
            mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
            mFTPClient.enterLocalPassiveMode();

            mFTPClient.changeWorkingDirectory(Constants.DIR_ROBOT_MEDIA);
            FTPFile[] fileList = mFTPClient.listFiles();
            long timestamp = 0l;
            String nameFile = "";
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isFile() && fileList[i].getTimestamp().getTimeInMillis() > timestamp) {
                    timestamp = fileList[i].getTimestamp().getTimeInMillis();
                    nameFile = fileList[i].getName();
                }
            }
            Log.d(TAG, "File da scaricare: " + nameFile);

            mFTPClient.enterLocalActiveMode();
            File folder = new File(Constants.DIR_ROBOT_IMG);
            OutputStream outputStream = null;
            boolean success = true;
            if (!folder.exists()) {
                success = folder.mkdir();
            }

            try {
                outputStream = new FileOutputStream(folder.getAbsolutePath() + "/" + nameFile);
                success = mFTPClient.retrieveFile(nameFile, outputStream);
            } catch (Exception e) {
                return e.getMessage();
            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }
            }
            if (success) {
                result = nameFile;
                mFTPClient.deleteFile(nameFile);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    } finally {
        if (mFTPClient != null) {
            try {
                mFTPClient.logout();
                mFTPClient.disconnect();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

    return result;
}

From source file:madkitgroupextension.export.Export.java

private static void sendToWebSite() throws IOException {
    System.out.println("Enter your password :");
    byte b[] = new byte[100];
    int l = System.in.read(b);
    String pwd = new String(b, 0, l);

    boolean reconnect = true;
    long time = System.currentTimeMillis();
    File current_file_transfert = null;
    File current_directory_transfert = null;

    while (reconnect) {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(FTPURL, 21);//from  ww w.  jav a  2 s. c om
        try {
            if (ftpClient.isConnected()) {
                System.out.println("Connected to server " + FTPURL + " (Port: " + FTPPORT + ") !");
                if (ftpClient.login(FTPLOGIN, pwd)) {
                    ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
                    System.out.println("Logged as " + FTPLOGIN + " !");
                    System.out.print("Updating...");

                    FTPFile files[] = ftpClient.listFiles("");
                    FTPFile downloadroot = null;
                    FTPFile docroot = null;

                    for (FTPFile f : files) {
                        if (f.getName().equals("downloads")) {
                            downloadroot = f;
                            if (docroot != null)
                                break;
                        }
                        if (f.getName().equals("doc")) {
                            docroot = f;
                            if (downloadroot != null)
                                break;
                        }
                    }
                    if (downloadroot == null) {
                        //ftpClient.changeWorkingDirectory("/");
                        if (!ftpClient.makeDirectory("downloads")) {
                            System.err.println("Impossible to create directory: downloads");
                        }
                    }
                    if (docroot == null) {
                        //ftpClient.changeWorkingDirectory("/");
                        if (!ftpClient.makeDirectory("doc")) {
                            System.err.println("Impossible to create directory: doc");
                        }
                    }

                    updateFTP(ftpClient, "downloads/", new File(ExportPathFinal), current_file_transfert,
                            current_directory_transfert);
                    updateFTP(ftpClient, "doc/", new File("./doc"), current_file_transfert,
                            current_directory_transfert);
                    reconnect = false;

                    System.out.println("[OK]");
                    if (ftpClient.logout()) {
                        System.out.println("Logged out from " + FTPLOGIN + " succesfull !");
                    } else
                        System.err.println("Logged out from " + FTPLOGIN + " FAILED !");
                } else
                    System.err.println("Impossible to log as " + FTPLOGIN + " !");

                ftpClient.disconnect();
                System.out.println("Disconnected from " + FTPURL + " !");
            } else {
                System.err.println("Impossible to get a connection to the server " + FTPURL + " !");
            }
            reconnect = false;
        } catch (TransfertException e) {
            if (System.currentTimeMillis() - time > 30000) {
                System.err.println("A problem occured during the transfert...");
                System.out.println("Reconnection in progress...");
                try {
                    ftpClient.disconnect();
                } catch (Exception e2) {
                }
                current_file_transfert = e.current_file_transfert;
                current_directory_transfert = e.current_directory_transfert;
                time = System.currentTimeMillis();
            } else {
                System.err.println("A problem occured during the transfert. Transfert aborded.");
                throw e.original_exception;
            }
        }
    }
}

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

private void Upload(String ftpServer, String pathDirectory, String SourcePathDirectory, String userName,
        String password, String filename) {

    FTPClient client = new FTPClient();
    FileInputStream fis = null;//  ww  w.ja  v a  2  s.  com

    try {
        client.connect(ftpServer);
        client.login(userName, password);
        client.enterLocalPassiveMode();
        client.setFileType(FTP.BINARY_FILE_TYPE);
        fis = new FileInputStream(SourcePathDirectory + filename);
        client.changeWorkingDirectory("/" + pathDirectory);

        client.storeFile(filename, fis);

        System.out.println(
                "The file " + SourcePathDirectory + " was stored to " + "/" + pathDirectory + "/" + filename);
        client.logout();

        //Report = "File: " + filename + " Uploaded Successfully ";
    } catch (Exception exp) {
        exp.printStackTrace();
        Report = "Server Error";
        jLabel6.setText(Report);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java

/**
 * @see it.greenvulcano.util.remotefs.RemoteManager#put(String, String,
 *      String, String, java.util.Map)//from w  w  w  .  jav a  2 s  .  c  o  m
 */
@Override
public boolean put(String localDirectory, String localFile, String remoteDirectory, String remoteFile,
        Map<String, String> optProperties) throws RemoteManagerException {
    checkConnected();

    boolean result = false;
    FileInputStream input = null;
    try {
        File localPathname = new File(localDirectory, localFile);
        if (!localPathname.isAbsolute()) {
            throw new RemoteManagerException("Local pathname (" + localPathname + ") is NOT absolute.");
        }

        input = new FileInputStream(localPathname);
        logger.debug("Uploading local file " + localPathname
                + (remoteDirectory != null ? " to remote directory " + remoteDirectory
                        : " to current remote working directory")
                + "...");

        if (remoteFile != null) {
            logger.debug("Renaming remote file to " + remoteFile);
        }

        if (remoteDirectory != null) {
            changeWorkingDirectory(remoteDirectory);
        }
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.storeFile((remoteFile != null ? remoteFile : localFile), input);

        int reply = ftpClient.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            logger.debug("Local file " + localPathname + " uploaded.");
            result = true;
        } else {
            logger.warn("FTP Server NEGATIVE response: ");
            logServerReply(Level.WARN);
        }
        return result;
    } catch (IOException exc) {
        throw new RemoteManagerException("I/O error", exc);
    } catch (Exception exc) {
        throw new RemoteManagerException("Generic error", exc);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException exc) {
                logger.warn("Error while closing local file input stream", exc);
            }
        }
        if (isAutoconnect()) {
            disconnect();
        }
    }
}

From source file:it.greenvulcano.util.remotefs.ftp.FTPManager.java

/**
 * @see it.greenvulcano.util.remotefs.RemoteManager#put(InputStream, String,
 *      String, java.util.Map)//from w ww.j  a  v a 2s .c om
 */
@Override
public boolean put(InputStream inputDataStream, String remoteDirectory, String remoteFile,
        Map<String, String> optProperties) throws RemoteManagerException {
    checkConnected();

    boolean result = false;
    try {
        logger.debug("Uploading stream " + (remoteDirectory != null ? " to remote directory " + remoteDirectory
                : " to current remote working directory") + "...");

        if (remoteFile != null) {
            logger.debug("Renaming remote file to " + remoteFile);
        }

        if (remoteDirectory != null) {
            changeWorkingDirectory(remoteDirectory);
        }
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.storeFile(remoteFile, inputDataStream);

        int reply = ftpClient.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            logger.debug("Stream uploaded.");
            result = true;
        } else {
            logger.warn("FTP Server NEGATIVE response: ");
            logServerReply(Level.WARN);
        }
        return result;
    } catch (IOException exc) {
        throw new RemoteManagerException("I/O error", exc);
    } catch (Exception exc) {
        throw new RemoteManagerException("Generic error", exc);
    } finally {
        if (isAutoconnect()) {
            disconnect();
        }
    }
}