Search in sources :

Example 46 with FTPClient

use of org.apache.commons.net.ftp.FTPClient in project structr by structr.

the class FtpFilesTest method test06OverwriteFile.

@Test
public void test06OverwriteFile() {
    FTPClient ftp = setupFTPClient("ftpuser1");
    final String name1 = "file1";
    try (final Tx tx = app.tx()) {
        FTPFile[] files = ftp.listFiles();
        assertNotNull(files);
        assertEquals(0, files.length);
        ftp.setFileType(FTP.ASCII_FILE_TYPE);
        ftp.setAutodetectUTF8(true);
        // Store a file
        InputStream in = IOUtils.toInputStream("Initial Content");
        ftp.storeFile(name1, in);
        in.close();
        tx.success();
    } catch (IOException | FrameworkException ex) {
        logger.warn("", ex);
        fail("Unexpected exception: " + ex.getMessage());
    }
    try (final Tx tx = app.tx()) {
        // Store a file
        InputStream in = IOUtils.toInputStream("Overwritten Content");
        ftp.storeFile(name1, in);
        in.close();
        tx.success();
    } catch (IOException | FrameworkException ex) {
        logger.warn("", ex);
        fail("Unexpected exception: " + ex.getMessage());
    }
    try (final Tx tx = app.tx()) {
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        final FTPFile[] files = ftp.listFiles();
        assertNotNull(files);
        assertEquals(1, files.length);
        assertEquals(name1, files[0].getName());
        ftp.retrieveFile(files[0].getName(), os);
        final byte[] data = os.toByteArray();
        final String content = new String(data, 0, data.length);
        assertEquals("Invalid content for overwritten file", "Overwritten Content", content);
        ftp.disconnect();
        tx.success();
    } catch (IOException | FrameworkException ex) {
        logger.warn("", ex);
        fail("Unexpected exception: " + ex.getMessage());
    }
}
Also used : Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) InputStream(java.io.InputStream) FTPFile(org.apache.commons.net.ftp.FTPFile) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FTPClient(org.apache.commons.net.ftp.FTPClient) FtpTest(org.structr.web.files.FtpTest) Test(org.junit.Test)

Example 47 with FTPClient

use of org.apache.commons.net.ftp.FTPClient in project structr by structr.

the class FtpFilesTest method test00StoreFile.

@Test
public void test00StoreFile() {
    FTPClient ftp = setupFTPClient("ftpuser1");
    final String name1 = "file1";
    final String name2 = "file2";
    try (final Tx tx = app.tx()) {
        FTPFile[] files = ftp.listFiles();
        assertNotNull(files);
        assertEquals(0, files.length);
        ftp.setFileType(FTP.ASCII_FILE_TYPE);
        ftp.setAutodetectUTF8(true);
        // Store a file
        InputStream in = IOUtils.toInputStream("Test Content");
        ftp.storeFile(name1, in);
        in.close();
        tx.success();
    } catch (IOException | FrameworkException ex) {
        logger.warn("", ex);
        fail("Unexpected exception: " + ex.getMessage());
    }
    String[] fileNames = null;
    try (final Tx tx = app.tx()) {
        fileNames = ftp.listNames();
        assertNotNull(fileNames);
        assertEquals(1, fileNames.length);
        assertEquals(name1, fileNames[0]);
        // Create second file in /
        createFTPFile(null, name2);
        tx.success();
    } catch (IOException | FrameworkException ex) {
        logger.warn("", ex);
        fail("Unexpected exception: " + ex.getMessage());
    }
    try (final Tx tx = app.tx()) {
        fileNames = ftp.listNames();
        assertNotNull(fileNames);
        assertEquals(2, fileNames.length);
        assertEquals(name1, fileNames[0]);
        assertEquals(name2, fileNames[1]);
        ftp.disconnect();
        tx.success();
    } catch (IOException | FrameworkException ex) {
        logger.warn("", ex);
        fail("Unexpected exception: " + ex.getMessage());
    }
}
Also used : Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) InputStream(java.io.InputStream) FTPFile(org.apache.commons.net.ftp.FTPFile) IOException(java.io.IOException) FTPClient(org.apache.commons.net.ftp.FTPClient) FtpTest(org.structr.web.files.FtpTest) Test(org.junit.Test)

Example 48 with FTPClient

use of org.apache.commons.net.ftp.FTPClient in project structr by structr.

the class FtpTest method setupFTPClient.

/**
 * Creates an FTP client, a backend user and logs this user in.
 *
 * @param username
 * @return
 */
protected FTPClient setupFTPClient(final String username) {
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect("localhost", ftpPort);
        logger.info("Reply from FTP server:", ftp.getReplyString());
        int reply = ftp.getReplyCode();
        assertTrue(FTPReply.isPositiveCompletion(reply));
        String password = "ftpuserpw1";
        try (final Tx tx = StructrApp.getInstance(securityContext).tx()) {
            ftpUser = createFTPUser(username, password);
            tx.success();
        } catch (FrameworkException fex) {
            logger.error("Unable to create FTP user", fex);
        }
        boolean loginSuccess = ftp.login(username, password);
        logger.info("Tried to login as {}/{}: {}", new Object[] { username, password, loginSuccess });
        assertTrue(loginSuccess);
        reply = ftp.getReplyCode();
        assertEquals(FTPReply.USER_LOGGED_IN, reply);
    } catch (IOException ex) {
        logger.error("Error in FTP test", ex);
        fail("Unexpected exception: " + ex.getMessage());
    }
    return ftp;
}
Also used : Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) IOException(java.io.IOException) FTPClient(org.apache.commons.net.ftp.FTPClient)

Example 49 with FTPClient

use of org.apache.commons.net.ftp.FTPClient in project network-monitor by caarmen.

the class SpeedTestUpload method upload.

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();
    ftp.setConnectTimeout(TIMEOUT);
    ftp.setDataTimeout(TIMEOUT);
    ftp.setDefaultTimeout(TIMEOUT);
    // For debugging, we'll log all the ftp commands
    if (BuildConfig.DEBUG) {
        PrintCommandListener printCommandListener = new PrintCommandListener(System.out);
        ftp.addProtocolCommandListener(printCommandListener);
    }
    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);
    }
}
Also used : SocketException(java.net.SocketException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) PrintCommandListener(org.apache.commons.net.PrintCommandListener) IOException(java.io.IOException) FTPClient(org.apache.commons.net.ftp.FTPClient) FileInputStream(java.io.FileInputStream)

Example 50 with FTPClient

use of org.apache.commons.net.ftp.FTPClient in project Java by Everything1sPossible.

the class FTPClientUtil method downloadFromFTP.

/**
 * 从ftp文件服务器下载文件
 *
 * @param ip
 *            ftp 地址
 * @param port
 *            端口号
 * @param username
 *            ftp 登录用户名
 * @param password
 *            ftp 登录密码
 * @param ftpGoalDir
 *            要下载的文件路径
 * @param renameFileName
 *            要下载的文件名称
 * @param sourceFileUrl
 *            下载文件保存路径,可包含文件名
 * @return 下载成功则返回 1,否则返回0
 */
public static void downloadFromFTP(String ip, int port, String userName, String passWord, String ftpGoalDir, String renameFileName, String sourceFileUrl) {
    FTPClient ftpClient = new FTPClient();
    FileOutputStream fos = null;
    try {
        File dir = new File(sourceFileUrl);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        System.out.println("FTP链接开始....");
        // 设置30s
        ftpClient.setConnectTimeout(30 * 1000);
        ftpClient.setControlEncoding("UTF-8");
        ftpClient.connect(ip, port);
        ftpClient.login(userName, passWord);
        System.out.println("FTP链接成功....");
        String remoteFileName = ftpGoalDir;
        fos = new FileOutputStream(sourceFileUrl + File.separator + renameFileName);
        ftpClient.setBufferSize(1024);
        System.out.println("remoteFileName:" + sourceFileUrl + File.separator + renameFileName);
        // 设置文件类型(二进制)
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        // 10分钟
        ftpClient.setDataTimeout(600 * 1000);
        // 开始本地被动模式 (linux下必须设置)
        ftpClient.enterLocalPassiveMode();
        ftpClient.retrieveFile(remoteFileName + File.separator + renameFileName, fos);
        System.out.println("successful!");
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("FTP客户端出错!", e);
    } finally {
        IOUtils.closeQuietly(fos);
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("关闭FTP连接发生异常!", e);
        }
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File) FTPClient(org.apache.commons.net.ftp.FTPClient)

Aggregations

FTPClient (org.apache.commons.net.ftp.FTPClient)128 IOException (java.io.IOException)78 FTPFile (org.apache.commons.net.ftp.FTPFile)36 Test (org.junit.Test)25 InputStream (java.io.InputStream)20 FrameworkException (org.structr.common.error.FrameworkException)20 Tx (org.structr.core.graph.Tx)20 FtpTest (org.structr.web.files.FtpTest)20 File (java.io.File)13 ByteArrayInputStream (java.io.ByteArrayInputStream)10 FileInputStream (java.io.FileInputStream)10 FileOutputStream (java.io.FileOutputStream)8 OutputStream (java.io.OutputStream)5 UnknownHostException (java.net.UnknownHostException)5 ConnectException (java.net.ConnectException)4 PrintCommandListener (org.apache.commons.net.PrintCommandListener)4 FTPSClient (org.apache.commons.net.ftp.FTPSClient)4 FTPUtils (com.cas.sim.tis.util.FTPUtils)3 FileNotFoundException (java.io.FileNotFoundException)3 MalformedURLException (java.net.MalformedURLException)3