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

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

Introduction

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

Prototype

public void connect(InetAddress host, int port) throws SocketException, IOException 

Source Link

Document

Opens a Socket connected to a remote host at the specified port and originating from the current host at a system assigned port.

Usage

From source file:org.mockftpserver.core.server.AbstractFtpServer_StartTest.java

/**
 * Test setting a non-default port number for the StubFtpServer control connection socket.
 *//*from   www  .  j a v  a 2  s  .  co  m*/
public void testCustomServerControlPort() throws Exception {
    final int SERVER_CONTROL_PORT = 9187;

    ftpServer.setServerControlPort(SERVER_CONTROL_PORT);
    ftpServer.start();

    try {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(SERVER, SERVER_CONTROL_PORT);
    } finally {
        ftpServer.stop();
    }
}

From source file:org.mockftpserver.stub.example.FtpWorkingDirectory.java

/**
 * Return the current working directory for the FTP account on the server
 * @return the current working directory
 * @throws SocketException/*from  w  ww.j  a  v  a  2s.co  m*/
 * @throws IOException
 */
public String getWorkingDirectory() throws SocketException, IOException {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(server, port);
    return ftpClient.printWorkingDirectory();
}

From source file:org.mockftpserver.stub.example.RemoteFile.java

public String readFile(String filename) throws SocketException, IOException {

    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(server, port);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    boolean success = ftpClient.retrieveFile(filename, outputStream);
    ftpClient.disconnect();/*from   w w  w.  j av a  2  s . c o m*/

    if (!success) {
        throw new IOException("Retrieve file failed: " + filename);
    }
    return outputStream.toString();
}

From source file:org.mockftpserver.stub.StubFtpServer_StartTest.java

/**
 * Test setting a non-default port number for the StubFtpServer control connection socket. 
 *//*  w w  w .j  ava  2 s.c om*/
public void testCustomServerControlPort() throws Exception {
    final int SERVER_CONTROL_PORT = 9187;
    final String DIR = "abc 1234567";
    PwdCommandHandler pwd = new PwdCommandHandler();
    pwd.setDirectory(DIR);

    stubFtpServer = new StubFtpServer();
    stubFtpServer.setServerControlPort(SERVER_CONTROL_PORT);
    stubFtpServer.setCommandHandler(CommandNames.PWD, pwd);

    stubFtpServer.start();

    try {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(SERVER, SERVER_CONTROL_PORT);

        assertEquals("pwd", DIR, ftpClient.printWorkingDirectory());
    } finally {
        stubFtpServer.stop();
    }
}

From source file:org.mule.modules.FtpUtils.java

public static FTPClient createSession(FtpLiteConnectorConfig config, String userName, String hostName,
        String port, String password) {
    FTPClient ftp = new FTPClient();
    ftp.setControlEncoding(config.getEncoding());
    try {/*from ww  w . j  a  v a2 s  .  c  om*/
        ftp.connect(hostName, Integer.parseInt(port));
        ftp.login(userName, password);
    } catch (NumberFormatException e) {
        throw new FtpLiteHostException("Port was incorrect and could not be parsed");
    } catch (SocketException e) {
        throw new FtpLiteHostException("Error connecting. " + e.toString());
    } catch (IOException e) {
        throw new FtpLiteHostException("Error connecting. " + e.toString());
    }
    return ftp;
}

From source file:org.mule.transport.ftp.FtpConnectionFactory.java

public Object makeObject() throws Exception {
    FTPClient client = new FTPClient();
    if (uri.getPort() > 0) {
        client.connect(uri.getHost(), uri.getPort());
    } else {/* ww w.ja  v a2s  .c o m*/
        client.connect(uri.getHost());
    }
    if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
        throw new IOException("Ftp connect failed: " + client.getReplyCode());
    }
    if (!client.login(uri.getUser(), uri.getPassword())) {
        throw new IOException("Ftp login failed: " + client.getReplyCode());
    }
    if (!client.setFileType(FTP.BINARY_FILE_TYPE)) {
        throw new IOException("Ftp error. Couldn't set BINARY transfer type: " + client.getReplyCode());
    }
    return client;
}

From source file:org.mule.transport.ftp.server.ServerTest.java

/**
 * Sanity test that the embedded ftp server is working. Useful as a first step if
 * the ftp transport tests are failing.// w ww.  j  a v a 2  s.  c  o  m
 *
 * @throws Exception
 */
@Test
public void testServerLogin() throws Exception {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect("localhost", dynamicPort.getNumber());
    ftpClient.login("admin", "admin");
}

From source file:org.nmdp.service.epitope.task.URLProcessor.java

public long getFtpLastModifiedTime(URL url) {
    FTPClient ftpClient = new FTPClient();
    try {/* w  w w  .  j  a  v  a 2  s  .  c om*/
        ftpClient.connect(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort());
        ftpClient.login("anonymous", "anonymous");
        ftpClient.enterLocalPassiveMode();
        String filePath = url.getPath();
        String time = ftpClient.getModificationTime(filePath);
        //logger.debug("server replied: " + time);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String timePart = time.split(" ")[1];
        Date modificationTime = dateFormat.parse(timePart);
        //logger.debug("parsed time: " + modificationTime);
        return modificationTime.getTime();
    } catch (Exception e) {
        logger.error("failed to parse time for url: " + url, e);
        return 0;
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

From source file:org.ow2.proactive.scheduler.examples.FTPConnector.java

/**
 * @see JavaExecutable#execute(TaskResult[])
 *///  ww w . j  ava2s.  c o  m
@Override
public Serializable execute(TaskResult... results) throws IOException {
    List<String> filesRelativePathName;
    FTPClient ftpClient = new FTPClient();

    try {
        //connect to the server
        ftpClient.connect(ftpHostname, ftpPort);
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            throw new IOException("Exception in connecting to FTP Server");
        }
        //login to the server
        if (!ftpClient.login(ftpUsername, ftpPassword)) {
            throw new IOException("Logging refused. check the FTP_USERNAME and FTP_PASSWORD values.");
        }

        // use local passive mode to pass firewall
        ftpClient.enterLocalPassiveMode();

        getOut().println("Connected");

        switch (ftpMode) {
        //FTP mode is GET
        case GET:
            filesRelativePathName = ftpGet(ftpClient);
            break;

        //FTP mode is PUT
        case "PUT":
            filesRelativePathName = ftpPut(ftpClient);
            break;

        default:
            throw new IllegalArgumentException("FTP MODE can only be " + PUT + " or " + GET);

        }
    } finally {
        // log out and disconnect from the server
        ftpClient.logout();
        ftpClient.disconnect();
        getOut().println("Disconnected");
    }
    return (Serializable) filesRelativePathName;
}

From source file:org.pepstock.jem.node.resources.impl.ftp.FtpFactory.java

/**
 * Creates and configures a FtpClient instance based on the
 * given properties./*from  w  w w  . j a  v a 2s .  com*/
 * 
 * @param properties the ftp client configuration properties
 * @return remote input/output steam
 * @throws JNDIException if an error occurs creating the ftp client
 */
private Object createFtpClient(Properties properties) throws JNDIException {
    // URL is mandatory
    String ftpUrlString = properties.getProperty(CommonKeys.URL);
    if (ftpUrlString == null) {
        throw new JNDIException(NodeMessage.JEMC136E, CommonKeys.URL);
    }

    // creates URL objects
    // from URL string
    URL ftpUrl;
    try {
        ftpUrl = new URL(ftpUrlString);
    } catch (MalformedURLException e) {
        throw new JNDIException(NodeMessage.JEMC233E, e, ftpUrlString);
    }
    // checks scheme
    // if SSL, activates a FTPS
    if (!ftpUrl.getProtocol().equalsIgnoreCase(FTP_PROTOCOL)
            && !ftpUrl.getProtocol().equalsIgnoreCase(FTPS_PROTOCOL)) {
        throw new JNDIException(NodeMessage.JEMC137E, ftpUrl.getProtocol());
    }

    // gets port the host (from URL)
    int port = ftpUrl.getPort();
    String server = ftpUrl.getHost();

    // User id is mandatory
    String username = properties.getProperty(CommonKeys.USERID);
    if (username == null) {
        throw new JNDIException(NodeMessage.JEMC136E, CommonKeys.USERID);
    }

    // password is mandatory
    String password = properties.getProperty(CommonKeys.PASSWORD);
    if (password == null) {
        throw new JNDIException(NodeMessage.JEMC136E, CommonKeys.PASSWORD);
    }

    // checks if as input stream or not
    boolean asInputStream = Parser
            .parseBoolean(properties.getProperty(FtpResourceKeys.AS_INPUT_STREAM, "false"), false);

    String remoteFile = null;
    String accessMode = null;
    if (asInputStream) {
        // remote file is mandatory
        // it must be set by a data description
        remoteFile = properties.getProperty(FtpResourceKeys.REMOTE_FILE);
        if (remoteFile == null) {
            throw new JNDIException(NodeMessage.JEMC136E, FtpResourceKeys.REMOTE_FILE);
        }
        // access mode is mandatory
        // it must be set by a data description
        accessMode = properties.getProperty(FtpResourceKeys.ACTION_MODE, FtpResourceKeys.ACTION_READ);
    }

    // creates a FTPclient 
    FTPClient ftp = ftpUrl.getProtocol().equalsIgnoreCase(FTP_PROTOCOL) ? new FTPClient() : new FTPSClient();

    // checks if binary
    boolean binaryTransfer = Parser.parseBoolean(properties.getProperty(FtpResourceKeys.BINARY, "false"),
            false);

    // checks if must be restarted
    long restartOffset = Parser.parseLong(properties.getProperty(FtpResourceKeys.RESTART_OFFSET, "-1"), -1);

    // checks and sets buffer size
    int bufferSize = Parser.parseInt(properties.getProperty(FtpResourceKeys.BUFFER_SIZE, "-1"), -1);

    try {
        // reply code instance
        int reply;
        // connect to server
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }

        // After connection attempt, you should check the reply code to
        // verify
        // success.
        reply = ftp.getReplyCode();
        // if not connected for error, EXCEPTION
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new JNDIException(NodeMessage.JEMC138E, reply);
        }
        // login!!
        if (!ftp.login(username, password)) {
            ftp.logout();
        }
        // set all ftp properties
        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        }

        // sets restart offset if has been set
        if (restartOffset >= 0) {
            ftp.setRestartOffset(restartOffset);
        }

        // sets buffer size
        if (bufferSize >= 0) {
            ftp.setBufferSize(bufferSize);
        }

        // if is not related to a data descritpion,
        // returns a FTP object
        if (!asInputStream) {
            return new Ftp(ftp);
        }

        // checks if is in WRITE mode
        if (accessMode.equalsIgnoreCase(FtpResourceKeys.ACTION_WRITE)) {
            // gets outputstream
            // using the file name passed by data descritpion
            OutputStream os = ftp.storeFileStream(remoteFile);
            if (os == null) {
                reply = ftp.getReplyCode();
                throw new JNDIException(NodeMessage.JEMC206E, remoteFile, reply);
            }
            // returns outputstream
            return new FtpOutputStream(os, ftp);
        } else {
            // gest inputstream
            // using the file name passed by data descritpion
            InputStream is = ftp.retrieveFileStream(remoteFile);
            if (is == null) {
                reply = ftp.getReplyCode();
                throw new JNDIException(NodeMessage.JEMC206E, remoteFile, reply);
            }
            // returns inputstream 
            return new FtpInputStream(is, ftp);
        }
    } catch (SocketException e) {
        throw new JNDIException(NodeMessage.JEMC234E, e);
    } catch (IOException e) {
        throw new JNDIException(NodeMessage.JEMC234E, e);
    }
}