Example usage for org.apache.commons.net.ftp FTPReply USER_LOGGED_IN

List of usage examples for org.apache.commons.net.ftp FTPReply USER_LOGGED_IN

Introduction

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

Prototype

int USER_LOGGED_IN

To view the source code for org.apache.commons.net.ftp FTPReply USER_LOGGED_IN.

Click Source Link

Usage

From source file:net.sf.webphotos.sync.FTP.SyncObject.java

/**
 * Conecta ao servidor FTP. Retorna uma confirmao da conexo atravs de um
 * boolean. TODO: remontar a funo para que use somente dados externos a
 * classe//from   www.j a  v a2  s.  c o m
 *
 * @return Valor lgico que confirma a conexo.
 */
@Override
public boolean connect() {
    boolean conectado = false;

    ftpHost = Util.getProperty("servidorFTP");
    ftpPort = Util.getConfig().getInt("FTPport");

    String ftpProxyHost = Util.getProperty("FTPproxyHost");
    int ftpProxyPort;
    try {
        ftpProxyPort = Util.getConfig().getInt("FTPproxyPort");
    } catch (Exception e) {
        ftpProxyPort = 0;
    }

    Util.log("Iniciando conexo com " + ftpHost);
    try {
        //TODO: Preparar o suporte a mltiplas lnguas
        FTPClientConfig auxConfig = new FTPClientConfig(FTPClientConfig.SYST_NT);
        configure(auxConfig);
        Util.out.println("Timeout (antes): " + getDefaultTimeout());
        setDefaultTimeout(25000);
        Util.out.println("Timeout (depois): " + getDefaultTimeout());

        //TODO: Testar o acesso via Proxy
        //      usando System.getProperties().put()
        //      http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html
        if (ftpProxyHost == null && ftpProxyPort != 0) {
            System.getProperties().put("ftp.proxyHost", ftpProxyHost);
            System.getProperties().put("ftp.proxyPort", ftpProxyPort);
        }

        super.connect(ftpHost, ftpPort);
        reply = getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            disconnect("[FtpClient.connect]/ERRO: no foi possivel conectar");
            return false;
        }
        Util.log("ok " + ftpHost + " encontrado.. autenticando..");

        SyncEvent ev = null;
        if (syncListener != null) {
            ev = new SyncEvent(this);
        }
        reply = FTPReply.NOT_LOGGED_IN;
        do {

            if (syncListener != null && ev != null) {
                syncListener.logonStarted(ev);
            }
            Util.log("servidor: " + ftpHost + " em " + ftpRoot + "\nsolicitando conexo...");

            login(usuario, new String(senha));
            Util.log("usurio: " + usuario + " senha: ***");
            reply = getReplyCode();
            retry--;

        } while (reply != FTPReply.USER_LOGGED_IN && retry >= 0);

        if (reply != FTPReply.USER_LOGGED_IN) {
            disconnect("[FtpClient.connect]/ERRO: login/senha incorreto.");
            return conectado;
        } else {
            // conexo bem sucedida... armazenamos o nome/login
            BancoImagem.getBancoImagem().setUserFTP(getUsuario());
            BancoImagem.getBancoImagem().setPasswordFTP(getSenha());
        }

        Util.log("ok conexo aceita..");
        // autenticao ok..

        setFileType(FTPClient.BINARY_FILE_TYPE);
        //ftp.enterRemotePassiveMode();
        // TODO: Achar uma alternativa para realizar o logging do FTP
        //ftp.setLogFile("ftp.log");

        // tenta ir ao diretrio FTPRoot... caso no consiga, tenta criar
        changeWorkingDirectory(ftpRoot);
        if (getReplyCode() != FTPReply.CODE_250) {
            Util.log(ftpRoot + " no existe..criando");
            if (makeDirectory(ftpRoot)) {
                Util.log("[FtpClient.connect]/ERRO: no foi possvel criar diretrio " + ftpRoot + " Retorno: "
                        + reply);
                disconnect("no foi possvel criar diretrio");
                return conectado;
            }
            changeWorkingDirectory(ftpRoot);
            reply = getReplyCode();
            if (reply != FTPReply.CODE_250) {
                disconnect("[FtpClient.connect]/ERRO: no foi possvel entrar no diretrio " + ftpRoot
                        + " que foi recm criado.");
                return conectado;
            }
        }
        conectado = true;
        getSyncListener().connected(new SyncEvent(this));
    } catch (Exception e) {
        conectado = false;
        log.error(e);
        disconnect("[FtpClient.connect]/ERRO: no foi possivel manter esta conexo");
    }

    return conectado;

}

From source file:org.structr.web.common.FtpTest.java

/**
 * Creates an FTP client, a backend user and logs this user in.
 *
 * @return//from   w w w  .  j a  v  a2  s  . co  m
 */
protected FTPClient setupFTPClient() {

    FTPClient ftp = new FTPClient();

    try {

        ftp.connect("localhost", ftpPort);
        logger.log(Level.INFO, "Reply from FTP server:", ftp.getReplyString());

        int reply = ftp.getReplyCode();
        assertTrue(FTPReply.isPositiveCompletion(reply));

        String username = "ftpuser1";
        String password = "ftpuserpw1";

        try (final Tx tx = StructrApp.getInstance(securityContext).tx()) {
            ftpUser = createFTPUser(username, password);
            tx.success();
        } catch (FrameworkException fex) {
            logger.log(Level.SEVERE, "Unable to create FTP user", fex);
        }
        boolean loginSuccess = ftp.login(username, password);
        logger.log(Level.INFO, "Try to login as " + username + "/" + password + ": ", loginSuccess);
        assertTrue(loginSuccess);

        reply = ftp.getReplyCode();
        assertEquals(FTPReply.USER_LOGGED_IN, reply);

    } catch (IOException ex) {
        logger.log(Level.SEVERE, "Error in FTP test", ex);
        fail("Unexpected exception: " + ex.getMessage());
    }

    return ftp;

}

From source file:org.structr.web.files.FtpTest.java

/**
 * Creates an FTP client, a backend user and logs this user in.
 *
 * @param username/*w  w  w .j  ava  2 s  .c om*/
 * @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;

}