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:com.limegroup.gnutella.archive.ArchiveContribution.java

/**
 * /*from  w ww.j a va 2 s . com*/
 * @param fileName
 * @param input
 *         The input stream (not necessarily buffered).
 *        This stream will be closed by this method
 */
private void uploadFile(String remoteFileName, InputStream input, FTPClient ftp)
        throws InterruptedIOException, IOException {
    fileStarted(remoteFileName);
    final InputStream fileStream = new BufferedInputStream(new UploadMonitorInputStream(input, this));

    try {
        if (isCancelled()) {
            throw new InterruptedIOException();
        }

        ftp.storeFile(remoteFileName, fileStream);
    } finally {
        fileStream.close();
    }

    if (isCancelled()) {
        throw new InterruptedIOException();
    }
    fileCompleted();
}

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

/**
 * ?FTP?.//from  w  w  w  .j a  v a 2s. c  om
 * 
 * @param path
 *            FTP??
 * @param filename
 *            FTP???
 * @param input
 *            ?
 * @return ?true?false
 */
public boolean ftpUploadFile(String path, String filename, InputStream input) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    ftp.setControlEncoding("UTF-8");
    try {
        int reply;
        ftp.connect(url, port);
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        // 
        ftp.changeWorkingDirectory(path);
        ftp.setBufferSize(1024);
        ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
        // 
        ftp.storeFile(filename, input);
        input.close();
        ftp.logout();
        success = true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return success;
}

From source file:eu.prestoprime.plugin.fprint.FPrintTasks.java

@WfService(name = "fprint_upload", version = "0.8.0")
public void upload(Map<String, String> sParams, Map<String, String> dParamsString,
        Map<String, File> dParamsFile) throws TaskExecutionFailedException {

    logger.debug("Called " + this.getClass().getName());

    // prepare dynamic variables
    String id = dParamsString.get("id");
    String targetName = id + ".webm";
    String fileLocation = null;/*w  ww .  j a v a  2s .co  m*/

    // prepare static variables
    String host = sParams.get("host");
    int port = Integer.parseInt(sParams.get("port"));
    String username = sParams.get("username");
    String password = sParams.get("password");
    String workdir = sParams.get("workdir");

    // retrieve AIP
    try {
        DIP dip = P4DataManager.getInstance().getDIPByID(id);
        List<String> fLocatList = dip.getAVMaterial("video/webm", "FILE");
        fileLocation = fLocatList.get(0);
    } catch (DataException | IPException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("Unable to retrieve the fileLocation of the Master Quality...");
    }

    logger.debug("Found video/webm location: " + fileLocation);

    // send to remote FTP folder
    FTPClient client = new FTPClient();
    try {
        client.connect(host, port);
        if (FTPReply.isPositiveCompletion(client.getReplyCode())) {
            if (client.login(username, password)) {
                client.setFileType(FTP.BINARY_FILE_TYPE);
                if (client.changeWorkingDirectory(workdir)) {
                    // TODO add behavior if file name is already present in
                    // remote ftp folder
                    // now OVERWRITES
                    File file = new File(fileLocation);
                    if (file.isFile()) {
                        if (client.storeFile(targetName, new FileInputStream(file))) {
                            logger.info("Stored file on server " + host + ":" + port + workdir);
                        } else {
                            throw new TaskExecutionFailedException("Cannot store file on server");
                        }
                    } else {
                        throw new TaskExecutionFailedException("Local file doesn't exist or is not acceptable");
                    }
                } else {
                    throw new TaskExecutionFailedException("Cannot browse directory " + workdir + " on server");
                }
            } else {
                throw new TaskExecutionFailedException("Username and Password not accepted by the server");
            }
        } else {
            throw new TaskExecutionFailedException(
                    "Cannot establish connection with server " + host + ":" + port);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new TaskExecutionFailedException("General exception with FTPClient");
    }

    logger.debug("Executed without errors " + this.getClass().getName());
}

From source file:edu.stanford.epad.common.util.FTPUtil.java

public boolean sendFile(String filePath, boolean delete) throws Exception {

    String fileName = filePath;//  ww  w  . j  a va  2 s  .  c o  m
    int slash = fileName.lastIndexOf("/");
    if (slash != -1)
        fileName = fileName.substring(slash + 1);
    slash = fileName.lastIndexOf("\\");
    if (slash != -1)
        fileName = fileName.substring(slash + 1);
    boolean success = true;
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(ftpHost, ftpPort);
        int reply = ftp.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            if (ftp.login(ftpUser, ftpPassword)) {
                if (ftpFolder != null && ftpFolder.trim().length() > 0) {
                    ftp.cwd(ftpFolder);
                    System.out.print("ftp cd: " + ftp.getReplyString());
                }
                ftp.setFileType(FTP.ASCII_FILE_TYPE);
                FileInputStream in = new FileInputStream(filePath);
                success = ftp.storeFile(fileName, in);
                in.close();
                if (delete) {
                    File file = new File(filePath);
                    file.delete();
                }
            } else
                success = false;
        }
    } finally {
        ftp.disconnect();
    }

    return success;
}

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

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

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

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

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

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

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

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

    return null;
}

From source file:ca.rmen.android.networkmonitor.app.speedtest.SpeedTestUpload.java

public static SpeedTestResult upload(SpeedTestUploadConfig uploadConfig) {
    Log.v(TAG, "upload " + uploadConfig);
    // Make sure we have a file to upload
    if (!uploadConfig.file.exists())
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);

    FTPClient ftp = new FTPClient();
    // For debugging, we'll log all the ftp commands
    if (BuildConfig.DEBUG) {
        PrintCommandListener printCommandListener = new PrintCommandListener(System.out);
        ftp.addProtocolCommandListener(printCommandListener);
    }/* w  w  w . jav a  2 s .  c o  m*/
    InputStream is = null;
    try {
        // Set buffer size of FTP client
        ftp.setBufferSize(1048576);
        // Open a connection to the FTP server
        ftp.connect(uploadConfig.server, uploadConfig.port);
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }
        // Login to the FTP server
        if (!ftp.login(uploadConfig.user, uploadConfig.password)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.AUTH_FAILURE);
        }
        // Try to change directories
        if (!TextUtils.isEmpty(uploadConfig.path) && !ftp.changeWorkingDirectory(uploadConfig.path)) {
            Log.v(TAG, "Upload: could not change path to " + uploadConfig.path);
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);
        }

        // set the file type to be read as a binary file
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        // Upload the file
        is = new FileInputStream(uploadConfig.file);
        long before = System.currentTimeMillis();
        long txBytesBefore = TrafficStats.getTotalTxBytes();
        if (!ftp.storeFile(uploadConfig.file.getName(), is)) {
            ftp.disconnect();
            Log.v(TAG, "Upload: could not store file to " + uploadConfig.path + ". Error code: "
                    + ftp.getReplyCode() + ", error string: " + ftp.getReplyString());
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }

        // Calculate stats
        long after = System.currentTimeMillis();
        long txBytesAfter = TrafficStats.getTotalTxBytes();
        ftp.logout();
        ftp.disconnect();
        Log.v(TAG, "Upload complete");
        return new SpeedTestResult(txBytesAfter - txBytesBefore, uploadConfig.file.length(), after - before,
                SpeedTestStatus.SUCCESS);
    } catch (SocketException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } catch (IOException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } finally {
        IoUtil.closeSilently(is);
    }
}

From source file:dk.netarkivet.common.distribute.IntegrityTestsFTP.java

public void testWrongChecksumThrowsError() throws Exception {
    Settings.set(CommonSettings.REMOTE_FILE_CLASS, "dk.netarkivet.common.distribute.FTPRemoteFile");
    RemoteFile rf = RemoteFileFactory.getInstance(testFile2, true, false, true);
    // upload error to ftp server
    File temp = File.createTempFile("foo", "bar");
    FTPClient client = new FTPClient();
    client.connect(Settings.get(CommonSettings.FTP_SERVER_NAME),
            Integer.parseInt(Settings.get(CommonSettings.FTP_SERVER_PORT)));
    client.login(Settings.get(CommonSettings.FTP_USER_NAME), Settings.get(CommonSettings.FTP_USER_PASSWORD));
    Field field = FTPRemoteFile.class.getDeclaredField("ftpFileName");
    field.setAccessible(true);// ww w  .j  a  va 2  s.  c o  m
    String filename = (String) field.get(rf);
    client.storeFile(filename, new ByteArrayInputStream("foo".getBytes()));
    client.logout();
    try {
        rf.copyTo(temp);
        fail("Should throw exception on wrong checksum");
    } catch (IOFailure e) {
        // expected
    }
    assertFalse("Destination file should not exist", temp.exists());
}

From source file:it.zero11.acme.example.FTPChallengeListener.java

private boolean createChallengeFiles(String token, String challengeBody) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    try {/*www . ja v  a2s.  c o m*/
        ftp.connect(host);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            return false;
        }

        ftp.login(username, password);
        ftp.changeWorkingDirectory(webroot);
        ftp.makeDirectory(".well-known");
        ftp.changeWorkingDirectory(".well-known");
        ftp.makeDirectory("acme-challenge");
        ftp.changeWorkingDirectory("acme-challenge");
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE, FTPClient.BINARY_FILE_TYPE);
        ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        success = ftp.storeFile(token, new ByteArrayInputStream(challengeBody.getBytes()));
        if (!success)
            System.err.println("FTP error uploading file: " + ftp.getReplyCode() + ": " + ftp.getReplyString());
        ftp.logout();
    } catch (IOException e) {
        throw new AcmeException(e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }

    return success;
}

From source file:br.com.atmatech.painel.util.EnviaLogs.java

public void enviarBD(File file, String enderecoFTP, String login, String senha) throws IOException {
    String nomeArquivo = null;/*from ww  w.  ja v  a  2  s .  c o  m*/
    FTPClient ftp = new FTPClient();
    ftp.connect(enderecoFTP);
    //verifica se conectou com sucesso! 

    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
        ftp.login(login, senha);
    } else {
        //erro ao se conectar  
        ftp.disconnect();
    }
    ftp.changeWorkingDirectory("/atmatech.com.br/ErroLogsPainelFX/");
    //abre um stream com o arquivo a ser enviado              
    InputStream is = new FileInputStream(file);
    //pega apenas o nome do arquivo             
    int idx = file.getName().lastIndexOf(File.separator);
    if (idx < 0)
        idx = 0;
    else
        idx++;
    nomeArquivo = file.getName().substring(idx, file.getName().length());
    //ajusta o tipo do arquivo a ser enviado  
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
    //faz o envio do arquivo  
    ftp.storeFile(nomeArquivo, is);
    ftp.disconnect();

}

From source file:ftp_server.FileUpload.java

public void uploading() {
    FTPClient client = new FTPClient();
    FileInputStream fis = null;//from   ww w .j  a va 2 s. c o  m
    try {
        client.connect("shamalmahesh.net78.net");
        client.login("a9959679", "9P3IckDo");
        client.setFileType(FTP.BINARY_FILE_TYPE);
        int reply = client.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Uploading....");
        } else {
            System.out.println("Failed connect to the server!");
        }
        //            String filename = "DownloadedLook1.txt";
        String path = "D:\\jpg\\";
        //            String filename = "1.jpg";
        String filename = "appearance.jpg";
        System.out.println(path + filename);
        fis = new FileInputStream(path + filename);
        System.out.println(fis.toString());
        boolean status = client.storeFile("/public_html/testing/" + filename, fis);
        System.out.println("Status : " + status);
        System.out.println("Done!");
        client.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}