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

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

Introduction

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

Prototype

public boolean login(String username, String password) throws IOException 

Source Link

Document

Login to the FTP server using the provided username and password.

Usage

From source file:patcher.FXMLDocumentController.java

private FTPClient ftpConnect(String url) throws IOException {
    //new ftp client
    FTPClient ftp = new FTPClient();
    //Try to connect
    try {// ww  w  . j av  a2  s.  c  o  m
        ftp.connect(url);
    } catch (IOException object) {
        return null;
    }

    ftp.enterLocalPassiveMode();
    ftp.login("anonymous", "");
    return ftp;
}

From source file:pl.psnc.synat.wrdz.zmd.download.adapters.FtpDownloadAdapter.java

/**
 * Performs login operation to log to the server or throws exceptions if any problems with logging in occur.
 * /*from  www  . ja  v a 2 s  .c  o  m*/
 * @param ftpClient
 *            client instance to operate on.
 * @throws DownloadAdapterException
 *             should any problems occur.
 */
private void loginToFtp(FTPClient ftpClient) throws DownloadAdapterException {
    try {
        if (ftpClient.login(connectionInfo.getUsername(), connectionInfo.getPassword())) {
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            throw new DownloadAdapterException("Unable to login to the server, authentication failed.");
        }
    } catch (IOException e) {
        throw new DownloadAdapterException("Exception while trying to login to the server.", e);
    }
}

From source file:Proiect.uploadFTP.java

public void actionFTP() {
    adressf.addCaretListener(new CaretListener() {
        public void caretUpdate(CaretEvent e) {
            InetAddress thisIp;/* www  . ja  va2s  . c  om*/
            try {
                thisIp = InetAddress.getLocalHost();
                titleFTP.setText("Connection: " + thisIp.getHostAddress() + " -> " + adressf.getText());
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            }
        }
    });

    exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            saveState();
            uploadFTP.dispose();
            tree.dispose();
        }
    });

    connect.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            FTPClient client = new FTPClient();
            FileInputStream fis = null;
            String pass = String.valueOf(passf.getPassword());
            try {
                if (filename == null) {
                    status.setText("File does not exist!");
                } else {
                    // Server address
                    client.connect(adressf.getText());
                    // Login credentials
                    client.login(userf.getText(), pass);
                    if (client.isConnected()) {
                        status.setText("Succesfull transfer!");
                        // File type
                        client.setFileType(FTP.BINARY_FILE_TYPE);
                        // File location
                        File file = new File(filepath);
                        fis = new FileInputStream(file);
                        // Change the folder on the server
                        client.changeWorkingDirectory(folderf.getText());
                        // Save the file on the server
                        client.storeFile(filename, fis);
                    } else {
                        status.setText("Transfer failed!");
                    }
                }
                client.logout();
            } catch (IOException e1) {
                Encrypter.printException(e1);
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    client.disconnect();
                } catch (IOException e1) {
                    Encrypter.printException(e1);
                }
            }
        }
    });

    browsef.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            int retval = chooserf.showOpenDialog(chooserf);
            if (retval == JFileChooser.APPROVE_OPTION) {
                status.setText("");
                filename = chooserf.getSelectedFile().getName().toString();
                filepath = chooserf.getSelectedFile().getPath();
                filenf.setText(chooserf.getSelectedFile().getName().toString());
            }
        }
    });

    adv.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            tree.setSize(220, uploadFTP.getHeight());
            tree.setLocation(uploadFTP.getX() + 405, uploadFTP.getY());
            tree.setResizable(false);
            tree.setIconImage(Toolkit.getDefaultToolkit()
                    .getImage(getClass().getClassLoader().getResource("assets/ico.png")));
            tree.setUndecorated(true);
            tree.getRootPane().setBorder(BorderFactory.createLineBorder(Encrypter.color_black, 2));
            tree.setVisible(true);
            tree.setLayout(new BorderLayout());

            JLabel labeltree = new JLabel("Server documents");
            labeltree.setOpaque(true);
            labeltree.setBackground(Encrypter.color_light);
            labeltree.setBorder(BorderFactory.createMatteBorder(8, 10, 10, 0, Encrypter.color_light));
            labeltree.setForeground(Encrypter.color_blue);
            labeltree.setFont(Encrypter.font16);

            JButton refresh = new JButton("");
            ImageIcon refresh_icon = getImageIcon("assets/icons/refresh.png");
            refresh.setIcon(refresh_icon);
            refresh.setBackground(Encrypter.color_light);
            refresh.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));
            refresh.setForeground(Encrypter.color_black);
            refresh.setFont(Encrypter.font16);
            refresh.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

            final FTPClient client = new FTPClient();
            DefaultMutableTreeNode top = new DefaultMutableTreeNode(adressf.getText());
            DefaultMutableTreeNode files = null;
            DefaultMutableTreeNode leaf = null;

            final JTree tree_view = new JTree(top);
            tree_view.setForeground(Encrypter.color_black);
            tree_view.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
            tree_view.putClientProperty("JTree.lineStyle", "None");
            tree_view.setBackground(Encrypter.color_light);
            JScrollPane scrolltree = new JScrollPane(tree_view);
            scrolltree.setBackground(Encrypter.color_light);
            scrolltree.getVerticalScrollBar().setPreferredSize(new Dimension(0, 0));

            UIManager.put("Tree.textBackground", Encrypter.color_light);
            UIManager.put("Tree.selectionBackground", Encrypter.color_blue);
            UIManager.put("Tree.selectionBorderColor", Encrypter.color_blue);

            tree_view.updateUI();

            final String pass = String.valueOf(passf.getPassword());
            try {
                client.connect(adressf.getText());
                client.login(userf.getText(), pass);
                client.enterLocalPassiveMode();
                if (client.isConnected()) {
                    try {
                        FTPFile[] ftpFiles = client.listFiles();
                        for (FTPFile ftpFile : ftpFiles) {
                            files = new DefaultMutableTreeNode(ftpFile.getName());
                            top.add(files);
                            if (ftpFile.getType() == FTPFile.DIRECTORY_TYPE) {
                                FTPFile[] ftpFiles1 = client.listFiles(ftpFile.getName());
                                for (FTPFile ftpFile1 : ftpFiles1) {
                                    leaf = new DefaultMutableTreeNode(ftpFile1.getName());
                                    files.add(leaf);
                                }
                            }
                        }
                    } catch (IOException e1) {
                        Encrypter.printException(e1);
                    }
                    client.disconnect();
                } else {
                    status.setText("Failed connection!");
                }
            } catch (IOException e1) {
                Encrypter.printException(e1);
            } finally {
                try {
                    client.disconnect();
                } catch (IOException e1) {
                    Encrypter.printException(e1);
                }
            }

            tree.add(labeltree, BorderLayout.NORTH);
            tree.add(scrolltree, BorderLayout.CENTER);
            tree.add(refresh, BorderLayout.SOUTH);

            uploadFTP.addComponentListener(new ComponentListener() {

                public void componentMoved(ComponentEvent e) {
                    tree.setLocation(uploadFTP.getX() + 405, uploadFTP.getY());
                }

                public void componentShown(ComponentEvent e) {
                }

                public void componentResized(ComponentEvent e) {
                }

                public void componentHidden(ComponentEvent e) {
                }
            });

            uploadFTP.addWindowListener(new WindowListener() {
                public void windowActivated(WindowEvent e) {
                    tree.toFront();
                }

                public void windowOpened(WindowEvent e) {
                }

                public void windowIconified(WindowEvent e) {
                }

                public void windowDeiconified(WindowEvent e) {
                }

                public void windowDeactivated(WindowEvent e) {
                }

                public void windowClosing(WindowEvent e) {
                }

                public void windowClosed(WindowEvent e) {
                }
            });

            refresh.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    tree.dispose();
                    tree.setVisible(true);
                }
            });
        }
    });

}

From source file:projetocsv.framePrincipal.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    Oracle conexao = new Oracle("localhost", "winston", "winston");
    if (conexao.connect()) {
        JOptionPane.showMessageDialog(null, "Conectado");

        //ExportCSV csv = new ExportCSV();
        //csv.gerar("teste.csv", conexao);
        CSVWriter writer = null;/*  www.j  a  v  a 2  s. c  om*/
        try {
            writer = new CSVWriter(new FileWriter("teste.csv"), '\t', ';');
        } catch (IOException ex) {
            Logger.getLogger(framePrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }
        Boolean includeHeaders = false;

        java.sql.ResultSet myResultSet = conexao.executar("select * from testtable");

        try {
            writer.writeAll(myResultSet, includeHeaders);

        } catch (SQLException ex) {
            Logger.getLogger(framePrincipal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(framePrincipal.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            JOptionPane.showMessageDialog(null, "Gerao finalizada");
            conexao.disconnect();
        }

        try {
            writer.close();
            FTPClient ftp = new FTPClient();
            try {
                ftp.connect("ftp.testeftpm.xp3.biz");
                ftp.login("testeftpm.xp3.biz ", "passftp");
                System.out.println("Ftp conectado");
            } catch (Exception e) {
                System.out.println("Erro ao conectar");
            }

            FileInputStream arqEnviar = new FileInputStream("teste.csv");
            if (ftp.storeFile("teste.csv", arqEnviar)) {
                System.out.println("Arquivo enviado com sucesso!");
                JOptionPane.showMessageDialog(null, "Arquivo enviado com sucesso!");
            } else {
                System.out.println("Erro ao enviar arquivo.");
            }

        } catch (IOException ex) {
            Logger.getLogger(framePrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }

    } else {
        JOptionPane.showMessageDialog(null, "Erro ao estabelecer conexo");
    }

}

From source file:rapture.ftp.common.FTPConnection.java

@Override
public boolean connectAndLogin() {
    if (isLocal()) {
        log.info("In local mode - not connecting");
        return true;
    }//from   w  w  w.  ja  v a  2 s.c  o m
    return FTPService.runWithRetry("Could not login to " + config.getAddress() + " as " + config.getLoginId(),
            this, false, new FTPAction<Boolean>() {
                @Override
                public Boolean run(int attemptNum) throws IOException {
                    FTPClient ftpClient = getFtpClient();
                    log.debug(String.format("Connecting to %s. Attempt %s of %s", config.getAddress(),
                            1 + attemptNum, config.getRetryCount()));
                    try {
                        ftpClient.connect(config.getAddress());
                    } catch (UnknownHostException e) {
                        log.info(ExceptionToString.summary(e));
                        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                                "Unknown host " + config.getAddress());
                    }
                    int reply = ftpClient.getReplyCode();
                    if (!FTPReply.isPositiveCompletion(reply)) {
                        log.debug("Got non-positive reply of " + reply);
                        logoffAndDisconnect();
                        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                                "Could not connect to: " + config.getAddress());
                    }
                    log.debug("Logging in user: " + config.getLoginId());
                    if (!ftpClient.login(config.getLoginId(), config.getPassword())) {
                        log.info("Could not login to " + config.getAddress() + " as " + config.getLoginId());
                        ftpClient.logout();
                        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                                "Could not login to " + config.getAddress() + " as " + config.getLoginId());
                    }
                    isLoggedIn = true;
                    log.debug("Entering local passive mode");
                    ftpClient.enterLocalPassiveMode();
                    log.info("Connected and logged in to: " + config.getAddress());
                    ftpClient.setSoTimeout(1000 * config.getTimeout());
                    return true;
                }
            });
}

From source file:rems.Global.java

public static String UploadFile(InetAddress ftpserverurl, String serverAppDirectory, String PureFileName,
        String fullLocFileUrl, String userName, String password) {
    // get an ftpClient object  
    FTPClient ftpClient = new FTPClient();
    FileInputStream inputStream = null;
    String responsTxt = "";
    try {/*from w  w w.  ja va 2s  .c  o  m*/
        // pass directory path on server to connect
        // pass username and password, returned true if authentication is  
        // successful  
        ftpClient.connect(ftpserverurl, 21);
        boolean login = ftpClient.login(userName, password);
        ftpClient.setKeepAlive(false);
        ftpClient.setPassiveNatWorkaround(true);
        if (login) {
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            File firstLocalFile = new File(fullLocFileUrl);
            inputStream = new FileInputStream(firstLocalFile);
            //inputStream.reset();
            boolean uploaded = ftpClient.storeFile(serverAppDirectory + PureFileName, inputStream);
            inputStream.close();
            responsTxt = ftpClient.getReplyString();
            if (uploaded) {
                responsTxt += "File uploaded successfully !";
            } else {
                responsTxt += "Error in uploading file !::" + serverAppDirectory + PureFileName;
            }

            Global.updateLogMsg(Global.logMsgID, "\r\n\r\n\r\nUpload Response ==>\r\n" + responsTxt,
                    Global.logTbl, Global.gnrlDateStr, Global.rnUser_ID);
            // logout the user, returned true if logout successfully  
            boolean logout = ftpClient.logout();
            if (logout) {
                //System.out.println("Connection close...");
            }
        } else {
            Global.errorLog += "Connection Failed..." + responsTxt;
            Global.updateLogMsg(Global.logMsgID,
                    "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                    Global.gnrlDateStr, Global.rnUser_ID);
            Global.writeToLog();
        }
        return responsTxt;
    } catch (SocketException e) {
        Global.errorLog += e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace());
        Global.updateLogMsg(Global.logMsgID,
                "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                Global.gnrlDateStr, Global.rnUser_ID);
        Global.writeToLog();
    } catch (IOException e) {
        Global.errorLog += e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace());
        Global.updateLogMsg(Global.logMsgID,
                "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                Global.gnrlDateStr, Global.rnUser_ID);
        Global.writeToLog();
    } finally {
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            Global.errorLog += e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace());
            Global.updateLogMsg(Global.logMsgID,
                    "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                    Global.gnrlDateStr, Global.rnUser_ID);
            Global.writeToLog();
        } finally {

        }
    }
    return "";
}

From source file:rems.Global.java

public static String DownloadFile(InetAddress ftpserverurl, String serverAppDirectory, String PureFileName,
        String fullLocFileUrl, String userName, String password) {

    File f = new File(fullLocFileUrl);
    // get an ftpClient object  
    FTPClient ftpClient = new FTPClient();
    String responsTxt = "";
    try {/*from   www  .  ja va 2s . c  om*/
        // pass directory path on server to connect  
        ftpClient.connect(ftpserverurl, 21);
        // pass username and password, returned true if authentication is  
        // successful  
        boolean login = ftpClient.login(userName, password);
        if (login) {
            ftpClient.enterLocalPassiveMode();
            //ftpClient.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(f));
            boolean download = ftpClient.retrieveFile(serverAppDirectory + PureFileName, outputStream1);
            outputStream1.close();

            //fos = new FileOutputStream(fullLocFileUrl);
            //boolean download = ftpClient.retrieveFile(serverAppDirectory + PureFileName, fos);
            responsTxt = ftpClient.getReplyString();
            if (download) {
                responsTxt += "File downloaded successfully !";
            } else {
                responsTxt += "Error in downloading file !::" + serverAppDirectory + PureFileName;
            }
            Global.updateLogMsg(Global.logMsgID, "\r\n\r\nDownload Response ==>\r\n" + responsTxt,
                    Global.logTbl, Global.gnrlDateStr, Global.rnUser_ID);
            Global.writeToLog();
            // logout the user, returned true if logout successfully  
            boolean logout = ftpClient.logout();
            if (logout) {
                //System.out.println("Connection close...");
            }
        } else {
            Global.errorLog += "Connection Failed..." + responsTxt;
            Global.updateLogMsg(Global.logMsgID,
                    "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                    Global.gnrlDateStr, Global.rnUser_ID);
            Global.writeToLog();
        }
        return responsTxt;
    } catch (SocketException e) {
        Global.errorLog += Arrays.toString(e.getStackTrace());
        Global.updateLogMsg(Global.logMsgID,
                "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                Global.gnrlDateStr, Global.rnUser_ID);
        Global.writeToLog();
    } catch (IOException e) {
        Global.errorLog += Arrays.toString(e.getStackTrace());
        Global.updateLogMsg(Global.logMsgID,
                "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                Global.gnrlDateStr, Global.rnUser_ID);
        Global.writeToLog();
    } finally {
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            Global.errorLog += Arrays.toString(e.getStackTrace());
            Global.updateLogMsg(Global.logMsgID,
                    "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                    Global.gnrlDateStr, Global.rnUser_ID);
            Global.writeToLog();
        } finally {

        }
    }
    Global.updateLogMsg(Global.logMsgID, "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + responsTxt,
            Global.logTbl, Global.gnrlDateStr, Global.rnUser_ID);
    return responsTxt;
}

From source file:rems.Global.java

public static String[] GetFileList(InetAddress ftpServerAddrs, String serverAppDirectory, String dirName,
        String userName, String password) {
    String[] downloadFiles = new String[1];
    StringBuilder result = new StringBuilder();
    FTPClient ftpClient = new FTPClient();
    try {/*from w  ww.j  av  a  2  s  .  c om*/
        // pass directory path on server to connect  
        ftpClient.connect(ftpServerAddrs);
        // pass username and password, returned true if authentication is  
        // successful  
        boolean login = ftpClient.login(userName, password);
        if (login) {
            //System.out.println("Connection established...");
            // get all files from server and store them in an array of  
            // FTPFiles  
            FTPFile[] files = ftpClient.listFiles();
            for (FTPFile file : files) {
                if (file.getType() == FTPFile.FILE_TYPE) {
                    result.append(file.getName());
                    result.append("\n");
                }
            }
            result.replace(result.toString().lastIndexOf("\n"), result.toString().length(), "");
            // logout the user, returned true if logout successfully  
            boolean logout = ftpClient.logout();
            if (logout) {
                System.out.println("Connection close...");
            }
        } else {
            System.out.println("Connection fail...");
        }
        return result.toString().split("\\\n");
    } catch (SocketException e) {
        Global.errorLog += Arrays.toString(e.getStackTrace());
        Global.writeToLog();
    } catch (IOException e) {
        Global.errorLog += Arrays.toString(e.getStackTrace());
        Global.writeToLog();
    } finally {
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            Global.errorLog += Arrays.toString(e.getStackTrace());
            Global.writeToLog();
        }
    }
    return downloadFiles;
}

From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java

public <X> X connect(URI remoteHostUri, String username, String password, String remoteHost, int remotePort,
        String options) throws Exception {
    long startTime = new Date().getTime();
    X abstractConnection = null;/*from   w ww  . j a  va 2 s  . c  o  m*/
    FTPClient ftpConnection = new FTPClient();
    try {
        remotePort = (remotePort == -1) ? (int) 21 : remotePort;
        ftpConnection.setDefaultTimeout(60 * 1000);
        ftpConnection.setRemoteVerificationEnabled(false);
        // FTPconnection.setSoTimeout( 60 * 1000 );
        // FTPconnection.setDataTimeout( 60 * 1000 );
        ftpConnection.connect(remoteHost, remotePort);
        ftpConnection.login(username, password);
        ftpConnection.enterLocalPassiveMode();
        ftpConnection.setFileType(FTPClient.BINARY_FILE_TYPE);
        // FTPconnection.setControlKeepAliveTimeout(300);
        // Check reply code for success
        int reply = ftpConnection.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpConnection.disconnect();
            throw new Exception(ErrorMessages.err_FTC005);
        } else {
            abstractConnection = (X) ftpConnection;
        }
    } catch (IOException se) {
        if (ftpConnection.isConnected()) {
            try {
                ftpConnection.disconnect();
            } catch (IOException ioe) {
                throw new Exception(ErrorMessages.err_FTC005);
            }
        }
    }
    log.info("The FTP sub-module connected to '" + remoteHostUri + "' in " + (new Date().getTime() - startTime)
            + " ms.");
    return abstractConnection;
}

From source file:ru.in360.FTPUploader.java

public boolean uploadFolder(File src, URI dest) {
    FTPClient ftpClient = new FTPClient();

    try {//from  w  w  w.  ja  va  2 s . com
        // connect and login to the server
        ftpClient.connect(server, port);
        ftpClient.login(user, pass);

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

        System.out.println("Connected");

        String remoteDirPath = "/Upload";
        String localDirPath = "E:/winhex";

        FTPUtil.saveFilesToServer(ftpClient, remoteProject, src);

        // log out and disconnect from the server
        ftpClient.logout();
        ftpClient.disconnect();

        System.out.println("Disconnected");
        return true;
    } catch (IOException ex) {
        ex.printStackTrace();
        return false;
    }
}