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

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

Introduction

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

Prototype

public int getReplyCode() 

Source Link

Document

Returns the integer value of the reply code of the last FTP reply.

Usage

From source file:gr.interamerican.bo2.utils.ftp.TestFtpSession.java

/**
 * Creates a mock FTPClient that throws a SocketException
 * on connect()./*from   ww  w.  j  a  v a  2s  .c  o  m*/
 * 
 * @return Returns an FtpSession object.
 * @throws IOException 
 */
FTPClient socketExMockFtpClient() throws IOException {
    FTPClient client = mock(FTPClient.class);
    when(client.login(anyString(), anyString())).thenReturn(true);
    when(client.getReplyCode()).thenReturn(250);
    when(client.storeFile(anyString(), (InputStream) anyObject())).thenReturn(true);
    when(client.retrieveFile(anyString(), (OutputStream) anyObject())).thenReturn(true);
    when(client.getReplyString()).thenReturn("Mock FTP reply string"); //$NON-NLS-1$
    doThrow(SocketException.class).when(client).connect("ftp.host.com", 21); //$NON-NLS-1$
    return client;
}

From source file:EscribirCorreo.java

private void SubirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SubirActionPerformed
    //Codigo para subir archivo         
    String localfile = subir1Field.getText();
    String server = "51.254.137.26";
    String username = "proyecto";
    String password = "proyecto";
    String destinationfile = nombre;
    try {//from w  w w.  ja v  a  2 s.c  o  m
        FTPClient ftp = new FTPClient();
        ftp.connect(server);
        if (!ftp.login(username, password)) {
            ftp.logout();
        }
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }
        InputStream in = new FileInputStream(localfile);
        ftp.setFileType(ftp.BINARY_FILE_TYPE);
        ftp.storeFile(destinationfile, in);
        JOptionPane.showMessageDialog(null, "Archivo subido correctamente", "Subido!",
                JOptionPane.INFORMATION_MESSAGE);
        if (archivos == null) {
            archivos = "http://51.254.137.26/proyecto/" + destinationfile;
        } else {
            archivos = archivos + "#http://51.254.137.26/proyecto/" + destinationfile;
        }
        in.close();
        ftp.logout();
        ftp.disconnect();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:gr.interamerican.bo2.utils.ftp.TestFtpSession.java

/**
 * Creates a mock FTPClient that does not need an FTP server.
 * /*from w w w  .  j a  v a2  s. c  o  m*/
 * @param succeedOnLogin 
 *        Specifies if this FTP client mocks its login method by
 *        imitating a successful or a failed login.
 * @param succedOnUploadDownload
 *        Specifies if this FTP client mocks the upload and download
 *        operations by imitating successful or failed operations.   
 * 
 * @return Returns an FtpSession object.
 * @throws IOException 
 */
FTPClient mockFtpClient(boolean succeedOnLogin, boolean succedOnUploadDownload) throws IOException {
    FTPClient client = mock(FTPClient.class);
    when(client.login(anyString(), anyString())).thenReturn(succeedOnLogin);
    when(client.getReplyCode()).thenReturn(250);
    when(client.storeFile(anyString(), (InputStream) anyObject())).thenReturn(succedOnUploadDownload);
    when(client.retrieveFile(anyString(), (OutputStream) anyObject())).thenReturn(succedOnUploadDownload);
    when(client.getReplyString()).thenReturn("Mock FTP reply string"); //$NON-NLS-1$
    return client;
}

From source file:com.seajas.search.contender.service.modifier.AbstractModifierService.java

/**
 * Retrieve the FTP client belonging to the given URI.
 * //w w  w.ja  va2  s  . co m
 * @param uri
 * @return FTPClient
 */
protected FTPClient retrieveFtpClient(final URI uri) {
    // Create the FTP client

    FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient();

    try {
        ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21);

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not connect to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        if (StringUtils.hasText(uri.getUserInfo())) {
            if (uri.getUserInfo().contains(":"))
                ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")),
                        uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1));
            else
                ftpClient.login(uri.getUserInfo(), "");
        }

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not login to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        // Switch to PASV and BINARY mode

        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        return ftpClient;
    } catch (IOException e) {
        logger.error("Could not close input stream during archive processing", e);
    }

    return null;
}

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

/**
 * Upload directory or file.//from  w w  w.  j a v a 2 s.  c o m
 *
 * @param host the host
 * @param port the port
 * @param userName the user name
 * @param password the password
 * @param fromLocalDirOrFile the local dir
 * @param toRemoteDirOrFile the remote dir
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
public String uploadDirectoryOrFile(final String host, final int port, final String userName,
        final String password, final String fromLocalDirOrFile, final String toRemoteDirOrFile)
        throws IOException {

    final FTPClient ftpClient = new FTPClient();
    String responseMessage = Constants.EMPTY;
    try {
        // Connect and login to get the session
        ftpClient.connect(host, port);
        final int replyCode = ftpClient.getReplyCode();

        if (FTPReply.isPositiveCompletion(replyCode)) {
            final boolean loginSuccess = ftpClient.login(userName, password);
            if (loginSuccess) {
                LOG.debug("Connected to remote host!");
                //Use local passive mode to pass fire-wall
                //In this mode a data connection is made by opening a port on the server for the client to connect 
                //and this is not blocked by fire-wall.
                ftpClient.enterLocalPassiveMode();
                final File localDirOrFileObj = new File(fromLocalDirOrFile);
                if (localDirOrFileObj.isFile()) {
                    LOG.debug("Uploading file: " + fromLocalDirOrFile);
                    uploadFile(ftpClient, fromLocalDirOrFile,
                            toRemoteDirOrFile + FILE_SEPERATOR_LINUX + localDirOrFileObj.getName());
                } else {
                    uploadDirectory(ftpClient, toRemoteDirOrFile, fromLocalDirOrFile, EMPTY);
                }
                responseMessage = "Upload completed successfully!";
            } else {
                responseMessage = "Could not login to the remote host!";
            }
            //Log out and disconnect from the server once FTP operation is completed.
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.logout();
                } catch (IOException ignored) {
                    LOG.error("Ignoring the exception while logging out from remote host: ", ignored);
                }
                try {
                    ftpClient.disconnect();
                    LOG.debug("Disconnected from remote host!");
                } catch (IOException ignored) {
                    LOG.error("Ignoring the exception while disconnecting from remote host: ", ignored);
                }
            }
        } else {
            responseMessage = "Host connection failed!";
        }
        LOG.debug("ResponseMessage:=> " + responseMessage);
    } catch (IOException ioexcp) {
        LOG.error("IOException occured in uploadDirectoryOrFile(..): ", ioexcp);
        throw ioexcp;
    }
    return responseMessage;
}

From source file:com.dinochiesa.edgecallouts.FtpPut.java

public ExecutionResult execute(MessageContext messageContext, ExecutionContext execContext) {
    FtpCalloutResult info = new FtpCalloutResult();
    try {//from w w w .  j a v a  2  s. c om
        // The executes in the IO thread!
        String sourceVar = getSourceVar(messageContext);
        InputStream src = null;
        boolean wantBase64Decode = getWantBase64Decode(messageContext);
        if (sourceVar == null) {
            src = messageContext.getMessage().getContentAsStream();
            // conditionally wrap a decoder around it
            if (wantBase64Decode) {
                src = new Base64InputStream(src);
            }
        } else {
            info.addMessage("Retrieving data from " + sourceVar);
            String sourceData = messageContext.getVariable(sourceVar);
            byte[] b = (wantBase64Decode) ? Base64.decodeBase64(sourceData)
                    : sourceData.getBytes(StandardCharsets.UTF_8);
            src = new ByteArrayInputStream(b);
        }
        String remoteName = getRemoteFileName(messageContext);
        remoteName = remoteName.replaceAll(":", "").replaceAll("/", "-");

        String ftpServer = getFtpServer(messageContext);
        int ftpPort = getFtpPort(messageContext);
        String user = getFtpUser(messageContext);
        String password = getFtpPassword(messageContext);

        info.addMessage("connecting to server " + ftpServer);
        FTPClient ftp = new FTPClient();
        ftp.addProtocolCommandListener(new FtpCommandListener(info));
        ftp.connect(ftpServer, ftpPort);
        ftp.enterLocalPassiveMode();
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            info.setStatus("FAIL");
            info.addMessage("The FTP server refused the connection.");
            messageContext.setVariable(varName("result"), info.toJsonString());
            return ExecutionResult.ABORT;
        }

        if (!ftp.login(user, password)) {
            ftp.disconnect();
            info.setStatus("FAIL");
            info.addMessage("Login failure");
            messageContext.setVariable(varName("result"), info.toJsonString());
            return ExecutionResult.ABORT;
        }
        info.addMessage("logged in as " + user);

        String initialDirectory = getInitialDirectory(messageContext);
        if ((initialDirectory != null) && (!initialDirectory.equals(""))) {
            ftp.changeWorkingDirectory(initialDirectory);
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        OutputStream os = ftp.storeFileStream(remoteName);
        if (os == null) {
            // cannot open output stream
            info.addMessage("cannot open output stream to " + remoteName);
            info.setStatus("FAIL");
        } else {
            byte[] buf = new byte[2048];
            int n;
            while ((n = src.read(buf)) > 0) {
                os.write(buf, 0, n);
            }
            os.close();
            src.close();
            boolean completed = ftp.completePendingCommand();
            info.addMessage("transfer completed: " + completed);
            info.setStatus("OK");
        }

        ftp.disconnect();
        info.addMessage("All done.");
        messageContext.setVariable(varName("result"), info.toJsonString());
    } catch (java.lang.Exception exc1) {
        if (getDebug()) {
            System.out.println(ExceptionUtils.getStackTrace(exc1));
        }
        String error = exc1.toString();
        messageContext.setVariable(varName("exception"), error);
        info.setStatus("FAIL");
        info.addMessage(error);
        messageContext.setVariable(varName("result"), info.toJsonString());
        int ch = error.lastIndexOf(':');
        if (ch >= 0) {
            messageContext.setVariable(varName("error"), error.substring(ch + 2).trim());
        } else {
            messageContext.setVariable(varName("error"), error);
        }
        messageContext.setVariable(varName("stacktrace"), ExceptionUtils.getStackTrace(exc1));
        return ExecutionResult.ABORT;
    }

    return ExecutionResult.SUCCESS;
}

From source file:adams.gui.chooser.FtpRemoteDirectorySetup.java

/**
 * Returns a new client for the host/port defined in the options.
 *
 * @return      the client/*ww  w  .  ja va2s .com*/
 */
public FTPClient newClient() {
    FTPClient result;
    int reply;

    try {
        result = new FTPClient();
        result.addProtocolCommandListener(this);
        result.connect(m_Host);
        reply = result.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            getLogger().severe("FTP server refused connection: " + reply);
        } else {
            if (!result.login(m_User, m_Password.getValue())) {
                getLogger().severe("Failed to connect to '" + m_Host + "' as user '" + m_User + "'");
            } else {
                if (m_UsePassiveMode)
                    result.enterLocalPassiveMode();
                if (m_UseBinaryMode)
                    result.setFileType(FTPClient.BINARY_FILE_TYPE);
            }
        }
    } catch (Exception e) {
        Utils.handleException(this, "Failed to connect to '" + m_Host + "' as user '" + m_User + "': ", e);
        result = null;
    }

    return result;
}

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  . jav a  2s.c  om
            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:egovframework.com.ext.jfile.sample.SampleFileUploadCluster.java

public void uploadCompleted(String fileId, String sourceRepositoryPath, String maskingFileName,
        String originalFileName) {
    if (logger.isDebugEnabled()) {
        logger.debug("SampleUploadCluster.process called");
    }/*  www  .  j  av  a2  s.c om*/
    FTPClient ftp = new FTPClient();
    OutputStream out = null;
    File file = new File(sourceRepositoryPath + "/" + maskingFileName);
    FileInputStream fin = null;
    BufferedInputStream bin = null;
    String storeFileName = null;
    String server = "?IP";//??  ? . ex) 210.25.3.21
    try {
        ftp.connect(server);
        if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            storeFileName = maskingFileName
                    + originalFileName.substring(originalFileName.lastIndexOf("."), originalFileName.length());
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            ftp.login("testId",
                    "testPassword" + server.substring(server.lastIndexOf(".") + 1, server.length()));
            if (logger.isDebugEnabled()) {
                logger.debug(server + " connect success !!! ");
            }
            ftp.changeWorkingDirectory("/testdir1/testsubdir2/testupload/");
            out = ftp.storeFileStream(storeFileName);
            FileCopyUtils.copy(fin, out);
            if (logger.isDebugEnabled()) {
                logger.debug(" cluster success !!! ");
            }
        } else {
            ftp.disconnect();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null)
                out.close();
            if (bin != null)
                bin.close();
            ftp.logout();
            out = null;
            bin = null;
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
}

From source file:com.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java

public List<String> getFilesExists(List<String> fileNames) {
    List<String> ret = new ArrayList<String>();
    try {/*from ww w.j  av a  2 s. co m*/
        HashMap<String, String> params = getFtpParams();
        FTPClient ftpClient = getFtpClient(params);
        BufferedInputStream buffIn;
        ftpClient.enterLocalPassiveMode();
        for (String nombre : fileNames) {
            buffIn = new BufferedInputStream(ftpClient
                    .retrieveFileStream(params.get("remoteRetreiveFiles") + REMOTE_SEPARATOR + nombre));//Ruta completa de alojamiento en el FTP
            if (ftpClient.getReplyCode() == 150) {
                System.out.println("Archivo obtenido exitosamente");
                buffIn.close();
                ret.add(nombre);
            } else {
                System.out.println(
                        "No se pudo obtener el archivo: " + nombre + ", codigo:" + ftpClient.getReplyCode());
            }
        }

        ftpClient.logout(); //Cerrar sesin
        ftpClient.disconnect();//Desconectarse del servidor
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
    return ret;
}