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

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

Introduction

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

Prototype

public boolean storeFile(String remote, InputStream local) throws IOException 

Source Link

Document

Stores a file on the server using the given name and taking input from the given InputStream.

Usage

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

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

From source file:main.TestManager.java

/**
 * Deletes all files on the server and uploads all the
 * tests from the local directory.//from  w ww.  j  av  a 2 s . co  m
 */
public static void syncServerWithTest() {
    FTPClient ftp = new FTPClient();
    boolean error = false;
    try {
        int reply;
        String server = "zajicek.endora.cz";
        ftp.connect(server, 21);

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

        //Not connected successfully - inform the user
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            Debugger.println("FTP server refused connection.");
            ErrorInformer.failedSyncing();
            return;
        }
        // LOGIN
        boolean success = ftp.login("plakato", "L13nK4");
        Debugger.println("Login successful: " + success);
        if (success == false) {
            ftp.disconnect();
            ErrorInformer.failedSyncing();
            return;
        }
        ftp.enterLocalPassiveMode();
        // Get all files from the server
        FTPFile[] files = ftp.listFiles();
        System.out.println("Got files! Count: " + files.length);
        // Delete all current tests on the server to be replaced with 
        // actualized version from local directory
        for (FTPFile f : files) {
            if (f.getName() == "." || f.getName() == "..") {
                continue;
            }
            if (f.isFile()) {
                ftp.deleteFile(f.getName());
            }
        }
        // Copy the files from local folder to server
        File localFolder = new File("src/tests/");
        File[] localFiles = localFolder.listFiles();
        int failed = 0;
        for (File f : localFiles) {
            if (f.getName() == "." || f.getName() == "..") {
                continue;
            }
            if (f.isFile()) {
                Debugger.println(f.getName());
                File file = new File("src/tests/" + f.getName());
                InputStream input = new FileInputStream(file);
                if (!ftp.storeFile(f.getName(), input))
                    failed++;
                input.close();
            }
        }
        // If we failed to upload some file, inform the user
        if (failed != 0) {
            ftp.disconnect();
            ErrorInformer.failedSyncing();
            return;
        }
        // Disconnect ftp client or resolve the potential error
        ftp.logout();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
        if (error) {
            ErrorInformer.failedSyncing();
            return;
        }
    }
    Alert alert = new Alert(AlertType.INFORMATION);
    alert.setTitle("Upload hotov");
    alert.setHeaderText(null);
    alert.setContentText("spene sa podarilo skoprova vetky testy na server!");

    alert.showAndWait();
    alert.close();
}

From source file:adams.scripting.connection.FTPConnection.java

/**
 * Sends the command to the specified sscripting engine.
 *
 * @param cmd      the command to send/*w  ww.  j av  a  2  s. c  o m*/
 * @param processor    for formatting/parsing
 * @return      null if successfully sent, otherwise error message
 */
protected String doSend(RemoteCommand cmd, RemoteCommandProcessor processor) {
    String result;
    FTPClient client;
    File tmpfile;
    String remotefile;
    FileInputStream fis;
    BufferedInputStream stream;
    MessageCollection errors;

    result = null;

    // save command to tmp file
    tmpfile = TempUtils.createTempFile("remote", ".rc");
    errors = new MessageCollection();
    if (!processor.write(cmd, tmpfile, errors))
        result = "Failed to write command to: " + tmpfile + "\n" + errors;

    // send tmp file via FTP
    if (result == null) {
        remotefile = TempUtils.createTempFile(new PlaceholderDirectory(m_RemoteDir), "remote", ".rc")
                .getAbsolutePath();
        client = getFTPClient();
        stream = null;
        fis = null;
        try {
            if (isLoggingEnabled())
                getLogger().info("Uploading " + tmpfile + " to " + remotefile);
            fis = new FileInputStream(tmpfile.getAbsoluteFile());
            stream = new BufferedInputStream(fis);
            if (!client.storeFile(remotefile, stream))
                result = "Failed to upload file, check console for error message!";
        } catch (Exception e) {
            result = Utils.handleException(this,
                    "Failed to upload file '" + tmpfile + "' to '" + remotefile + "': ", e);
        } finally {
            FileUtils.closeQuietly(stream);
            FileUtils.closeQuietly(fis);
        }
    }

    return result;
}

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

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

From source file: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;/*w  ww . j  a  va 2 s  . c  om*/

    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:convcao.com.agent.ConvcaoNeptusInteraction.java

private void upload(String ftpServer, String pathDirectory, String sourcePathDirectory, String userName,
        String password, String filename) {

    FTPClient client = new FTPClient();
    FileInputStream fis = null;//from   w  w  w.  ja  v a2s .co m

    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:com.hibo.bas.fileplugin.file.FtpPlugin.java

@Override
public void upload(String path, File file, String contentType) {
    Map<String, String> ftpInfo = getFtpInfo(contentType);
    if (!"".equals(ftpInfo.get("host")) && !"".equals(ftpInfo.get("username"))
            && !"".equals(ftpInfo.get("password"))) {
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {// w  w  w .ja  v a2  s.  c  o  m
            inputStream = new FileInputStream(file);
            ftpClient.connect(ftpInfo.get("host"), 21);
            ftpClient.login(ftpInfo.get("username"), ftpInfo.get("password"));
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            path = ftpInfo.get("path") + path;
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:com.rvl.android.getnzb.LocalNZB.java

public void uploadLocalFileFTP(String filename) {
    UPLOADFILENAME = filename;//  w  w w.  jav  a  2 s  .c  o  m

    UPLOADDIALOG = ProgressDialog.show(this, "Please wait...", "Uploading '" + filename + "' to FTP server.");

    SharedPreferences prefs = GetNZB.preferences;
    if (prefs.getString("FTPHostname", "") == "") {
        uploadDialogHandler.sendEmptyMessage(0);
        Toast.makeText(this, "Upload to FTP server not possible. Please check FTP preferences.",
                Toast.LENGTH_LONG).show();
        return;
    }

    new Thread() {

        public void run() {
            SharedPreferences prefs = GetNZB.preferences;
            FTPClient ftp = new FTPClient();

            String replycode = "";
            String FTPHostname = prefs.getString("FTPHostname", "");
            String FTPUsername = prefs.getString("FTPUsername", "anonymous");
            String FTPPassword = prefs.getString("FTPPassword", "my@email.address");
            String FTPPort = prefs.getString("FTPPort", "21");
            String FTPUploadPath = prefs.getString("FTPUploadPath", "~/");
            if (!FTPUploadPath.matches("$/")) {
                Log.d(Tags.LOG, "Adding trailing slash");
                FTPUploadPath += "/";
            }
            String targetFile = FTPUploadPath + UPLOADFILENAME;

            try {

                ftp.connect(FTPHostname, Integer.parseInt(FTPPort));
                if (ftp.login(FTPUsername, FTPPassword)) {

                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                    ftp.enterLocalPassiveMode();
                    File file = new File(getFilesDir() + "/" + UPLOADFILENAME);
                    BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream(file));
                    Log.d(Tags.LOG, "Saving file to:" + targetFile);
                    if (ftp.storeFile(targetFile, buffIn)) {
                        Log.d(Tags.LOG, "FTP: File should be uploaded. Replycode: "
                                + Integer.toString(ftp.getReplyCode()));

                        isUploadedFTP = true;
                    } else {
                        Log.d(Tags.LOG, "FTP: Could not upload file  Replycode: "
                                + Integer.toString(ftp.getReplyCode()));
                        FTPErrorCode = Integer.toString(ftp.getReplyCode());
                        isUploadedFTP = false;
                    }

                    buffIn.close();
                    ftp.logout();
                    ftp.disconnect();

                } else {
                    Log.d(Tags.LOG, "No ftp login");
                }
            } catch (SocketException e) {
                Log.d(Tags.LOG, "ftp(): " + e.getMessage());
                return;
            } catch (IOException e) {
                Log.d(Tags.LOG, "ftp(): " + e.getMessage());
                return;
            }
            if (isUploadedFTP) {
                removeLocalNZBFile(UPLOADFILENAME);
            }

            UPLOADFILENAME = "";
            uploadDialogHandlerFTP.sendEmptyMessage(0);
        }

    }.start();
}

From source file:com.tumblr.maximopro.iface.router.FTPHandler.java

@Override
public byte[] invoke(Map<String, ?> metaData, byte[] data) throws MXException {
    byte[] encodedData = super.invoke(metaData, data);
    this.metaData = metaData;

    FTPClient ftp;
    if (enableSSL()) {
        FTPSClient ftps = new FTPSClient(isImplicit());
        ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        ftp = ftps;/*from ww  w .j av  a 2  s  .c o  m*/
    } else {
        ftp = new FTPClient();
    }

    InputStream is = null;
    try {

        if (getTimeout() > 0) {
            ftp.setDefaultTimeout(getTimeout());
        }

        if (getBufferSize() > 0) {
            ftp.setBufferSize(getBufferSize());
        }

        if (getNoDelay()) {
            ftp.setTcpNoDelay(getNoDelay());
        }

        ftp.connect(getHostname(), getPort());

        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }

        if (!ftp.login(getUsername(), getPassword())) {
            ftp.logout();
            ftp.disconnect();
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        if (enableActive()) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        is = new ByteArrayInputStream(encodedData);

        String remoteFileName = getFileName(metaData);

        ftp.changeWorkingDirectory("/");
        if (createDirectoryStructure(ftp, getDirName().split("/"))) {
            ftp.storeFile(remoteFileName, is);
        } else {
            throw new MXApplicationException("iface", "cannotcreatedir");
        }

        ftp.logout();
    } catch (MXException e) {
        throw e;
    } catch (SocketException e) {
        throw new MXApplicationException("iface", "ftpsocketerror", e);
    } catch (IOException e) {
        throw new MXApplicationException("iface", "ftpioerror", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                throw new MXApplicationException("iface", "ftpioerror", e);
            }
        }

        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                throw new MXApplicationException("iface", "ftpioerror", e);
            }
        }
    }

    return null;
}

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 {// ww w .  j a va 2  s. c om
        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;
}