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

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

Introduction

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

Prototype

public boolean setFileType(int fileType) throws IOException 

Source Link

Document

Sets the file type to be transferred.

Usage

From source file:com.nostra13.universalimageloader.core.download.BaseImageDownloader.java

protected InputStream getStreamFromFTPNetwork(String imageUri, Object extra) throws IOException {
    int indexUrl = imageUri.indexOf("//") + 1;
    int indexUrlFinal = imageUri.lastIndexOf(":");
    int slash = imageUri.lastIndexOf("/");
    String ip = imageUri.substring(indexUrl + 1, indexUrlFinal);
    FTPClient client = new FTPClient();
    client.connect(ip, 20000);//from  ww w . j  a v a 2  s .  c  o  m
    client.login("anonymous", "");
    client.setFileType(FTP.BINARY_FILE_TYPE);
    client.enterLocalPassiveMode();

    InputStream imageStream = null;
    FTPFile[] directories = client.listFiles();
    long fileLength = (int) getFile(directories, imageUri.substring(slash + 1)).getSize();
    try {
        imageStream = client.retrieveFileStream(imageUri.substring(slash + 1));
    } catch (IOException e) {
        // Read all data to allow reuse connection (http://bit.ly/1ad35PY)
        IoUtils.readAndCloseStream(imageStream);
        throw e;
    }
    return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), fileLength);
}

From source file:br.com.tiagods.util.FTPUpload.java

public boolean uploadFile(File arquivo, String novoNome) {
    FTPConfig cf = FTPConfig.getInstance();

    FTPClient ftp = new FTPClient();
    try {//  w ww. j  a v  a  2  s. co  m
        ftp.connect(cf.getValue("host"), Integer.parseInt(cf.getValue("port")));
        ftp.login(cf.getValue("user"), cf.getValue("pass"));
        //ftp.connect(server,port);
        //ftp.login(user,pass);
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        boolean done;
        try (InputStream stream = new FileInputStream(arquivo)) {
            String remoteFile = novoNome;
            System.out.println("Start uploading first file");
            done = ftp.storeFile(cf.getValue("dirFTP") + "/" + remoteFile, stream);
            stream.close();
        }
        if (done) {
            JOptionPane.showMessageDialog(null, "Arquivo enviado com sucesso!");
            return true;
        }
        return false;
    } catch (IOException e) {
        System.out.println("Erro = " + e.getMessage());
        return false;
    } finally {
        try {
            if (ftp.isConnected()) {
                ftp.logout();
                ftp.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.alexkasko.netty.ftp.FtpServerTest.java

@Test
public void test() throws IOException, InterruptedException {
    final DefaultCommandExecutionTemplate defaultCommandExecutionTemplate = new DefaultCommandExecutionTemplate(
            new ConsoleReceiver());
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override//from  w  w  w.  j  ava2 s .  c  o m
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipe = ch.pipeline();
                    pipe.addLast("decoder", new CrlfStringDecoder());
                    pipe.addLast("handler", new FtpServerHandler(defaultCommandExecutionTemplate));
                }

            });
    b.localAddress(2121).bind();
    FTPClient client = new FTPClient();
    //        https://issues.apache.org/jira/browse/NET-493

    client.setBufferSize(0);
    client.connect("127.0.0.1", 2121);
    assertEquals(230, client.user("anonymous"));

    // active
    assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE));
    assertEquals("/", client.printWorkingDirectory());
    assertTrue(client.changeWorkingDirectory("/foo"));
    assertEquals("/foo", client.printWorkingDirectory());
    assertTrue(client.listFiles("/foo").length == 0);
    assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes())));
    assertTrue(client.rename("bar", "baz"));
    //  assertTrue(client.deleteFile("baz"));

    // passive
    assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE));
    client.enterLocalPassiveMode();
    assertEquals("/foo", client.printWorkingDirectory());
    assertTrue(client.changeWorkingDirectory("/foo"));
    assertEquals("/foo", client.printWorkingDirectory());

    //TODO make a virtual filesystem that would work with directory
    //assertTrue(client.listFiles("/foo").length==1);

    assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes())));
    assertTrue(client.rename("bar", "baz"));
    // client.deleteFile("baz");

    assertEquals(221, client.quit());
    try {
        client.noop();
        fail("Should throw exception");
    } catch (IOException e) {
        //expected;
    }

}

From source file:com.bbytes.jfilesync.sync.ftp.FTPClientFactory.java

/**
 * Get {@link FTPClient} with initialized connects to server given in properties file
 * @return//from w w  w.  j  a  v a2  s.  co m
 */
public FTPClient getClientInstance() {

    ExecutorService ftpclientConnThreadPool = Executors.newSingleThreadExecutor();
    Future<FTPClient> future = ftpclientConnThreadPool.submit(new Callable<FTPClient>() {

        FTPClient ftpClient = new FTPClient();

        boolean connected;

        public FTPClient call() throws Exception {

            try {
                while (!connected) {
                    try {
                        ftpClient.connect(host, port);
                        if (!ftpClient.login(username, password)) {
                            ftpClient.logout();
                        }
                        connected = true;
                        return ftpClient;
                    } catch (Exception e) {
                        connected = false;
                    }

                }

                int reply = ftpClient.getReplyCode();
                // FTPReply stores a set of constants for FTP reply codes.
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                }

                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            return ftpClient;
        }
    });

    FTPClient ftpClient = new FTPClient();
    try {
        // wait for 100 secs for acquiring conn else terminate
        ftpClient = future.get(100, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        log.info("FTP client Conn wait thread terminated!");
    } catch (InterruptedException e) {
        log.error(e.getMessage(), e);
    } catch (ExecutionException e) {
        log.error(e.getMessage(), e);
    }

    ftpclientConnThreadPool.shutdownNow();
    return ftpClient;

}

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;//from w ww. j  a  v  a 2s.  com

    // 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:com.dp2345.plugin.ftp.FtpPlugin.java

@Override
public List<FileInfo> browser(String path) {
    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    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");
        String urlPrefix = pluginConfig.getAttribute("urlPrefix");
        FTPClient ftpClient = new FTPClient();
        try {//from   w w  w.j  a va  2  s  .c o  m
            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())
                    && ftpClient.changeWorkingDirectory(path)) {
                for (FTPFile ftpFile : ftpClient.listFiles()) {
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setName(ftpFile.getName());
                    fileInfo.setUrl(urlPrefix + path + ftpFile.getName());
                    fileInfo.setIsDirectory(ftpFile.isDirectory());
                    fileInfo.setSize(ftpFile.getSize());
                    fileInfo.setLastModified(ftpFile.getTimestamp().getTime());
                    fileInfos.add(fileInfo);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
    return fileInfos;
}

From source file:com.buzz.buzzdata.MongoBuzz.java

private InputStream getFTPInputStream(String ftp_location) {
    InputStream retval = null;/*from   w  ww . j  a va  2  s  .co m*/

    String server = "162.219.245.61";
    int port = 21;
    String user = "jelastic-ftp";
    String pass = "HeZCHxeefB";
    FTPClient ftpClient = new FTPClient();

    try {
        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
        retval = ftpClient.retrieveFileStream(ftp_location);
    } catch (IOException ex) {
        Logger.getLogger(MongoBuzz.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            Logger.getLogger(MongoBuzz.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return retval;
}

From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java

@Override
public List<FileInfo> browser(String path) {
    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    // PluginConfig pluginConfig = getPluginConfig();
    // if (pluginConfig != null) {
    Map<String, String> ftpInfo = getFtpInfo("all");
    String urlPrefix = DataConfig.getConfig("IMGFTPROOT");
    FTPClient ftpClient = new FTPClient();
    try {/*from   w  w  w.j a  v a  2 s.  c  o m*/
        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();
        if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()) && ftpClient.changeWorkingDirectory(path)) {
            for (FTPFile ftpFile : ftpClient.listFiles()) {
                FileInfo fileInfo = new FileInfo();
                fileInfo.setName(ftpFile.getName());
                fileInfo.setUrl(urlPrefix + path + ftpFile.getName());
                fileInfo.setIsDirectory(ftpFile.isDirectory());
                fileInfo.setSize(ftpFile.getSize());
                fileInfo.setLastModified(ftpFile.getTimestamp().getTime());
                fileInfos.add(fileInfo);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
            }
        }
    }
    // }
    return fileInfos;
}

From source file:com.shigeodayo.ardrone.utils.ARDroneInfo.java

private boolean connectToDroneThroughFtp() {
    FTPClient client = new FTPClient();
    BufferedOutputStream bos = null;

    try {/*from   w w  w .j a v a 2 s .  co  m*/
        client.connect(ARDroneConstants.IP_ADDRESS, ARDroneConstants.FTP_PORT);

        if (!client.login("anonymous", "")) {
            ARDrone.error("Login failed", this);
            return false;
        }

        client.setFileType(FTP.BINARY_FILE_TYPE);

        bos = new BufferedOutputStream(new OutputStream() {

            @Override
            public void write(int arg0) throws IOException {
                //System.out.println("aa:" + (char)arg0);
                switch (count) {
                case 0:
                    major = arg0 - '0';
                    break;
                case 2:
                    minor = arg0 - '0';
                    break;
                case 4:
                    revision = arg0 - '0';
                    break;
                default:
                    break;
                }
                count++;
            }
        });

        if (!client.retrieveFile("/" + VERSION_FILE_NAME, bos)) {
            ARDrone.error("Cannot find \"" + VERSION_FILE_NAME + "\"", this);
            return false;
        }

        bos.flush();

        //System.out.print("major:" + major);
        //System.out.print(" minor:" + minor);
        //System.out.println(" revision:" + revision);

        //System.out.println("done");
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (bos != null) {
                bos.flush();
                bos.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    return true;
}

From source file:com.jmeter.alfresco.utils.FtpUtils.java

/**
 * Upload file.//from  w  ww. j  a v  a2  s  .  c o  m
 *
 * @param ftpClient the ftp client
 * @param frmLocalFilePath the frm local file path
 * @param toRemoteFilePath the to remote file path
 * @return true, if successful
 * @throws IOException Signals that an I/O exception has occurred.
 */
private boolean uploadFile(final FTPClient ftpClient, final String frmLocalFilePath,
        final String toRemoteFilePath) throws IOException {

    final File localFile = new File(frmLocalFilePath);
    final InputStream inputStream = new FileInputStream(localFile);
    try {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        final boolean isFileUploaded = ftpClient.storeFile(toRemoteFilePath, inputStream);
        final int replyCode = ftpClient.getReplyCode();
        //If reply code is 550 then,Requested action not taken. File unavailable (e.g., file not found, no access).
        //If reply code is 150 then,File status okay (e.g., File found)
        //If reply code is 226 then,Closing data connection. 
        //If reply code is 426 then,Connection closed; transfer aborted. 
        LOG.debug("Reply code from remote host after storeFile(..) call: " + replyCode);
        return isFileUploaded;
    } finally {
        inputStream.close();
    }
}