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) throws SocketException, IOException 

Source Link

Document

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

Usage

From source file:Proiect.uploadFTP.java

public void actionFTP() {
    adressf.addCaretListener(new CaretListener() {
        public void caretUpdate(CaretEvent e) {
            InetAddress thisIp;/*ww  w.  j  ava 2  s .  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;/*from  w ww .j ava 2s  .  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 va  2s.c om*/
    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[] 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 {/*ww  w  . ja v  a  2  s  .com*/
        // 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:s32a.Client.Startup.FTPHandler.java

/**
 * Checks whether client was able to login with given info.
 *
 * @return//from  ww  w.java2  s.c om
 */
public boolean checkLogin() {
    boolean success = false;
    FTPClient client = null;
    try {
        if (SSL) {
            client = new FTPSClient(false);
        } else {
            client = new FTPClient();
        }

        client.connect(this.ftpServer);
        success = client.login(username, password);
    } catch (IOException ex) {
        success = false;
        Logger.getLogger(FTPHandler.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (client != null) {
            try {
                client.logout();
            } catch (IOException ex) {
                Logger.getLogger(FTPHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return success;
}

From source file:s32a.Client.Startup.FTPHandler.java

/**
 * Retrieves server and codebase info from FTP server.
 * Codebase will need to be queried separately afterwards.
 * @return // ww  w.  ja va2s.c  o m
 */
public List<ServerInfo> getFTPData() {
    FTPClient client = null;
    FileInputStream fis = null;
    FileOutputStream fos = null;
    List<ServerInfo> output = new ArrayList<>();

    if (SSL) {
        client = new FTPSClient(false);
    } else {
        client = new FTPClient();
    }

    try {
        System.out.println("connecting");
        client.connect(ftpServer);
        boolean login = client.login(this.username, this.password);
        System.out.println("login: " + login);
        client.enterLocalPassiveMode();

        // Reads codebase file from server
        File codebase = new File("codebase.properties");
        fos = new FileOutputStream(codebase.getAbsolutePath());
        client.retrieveFile("/Airhockey/Codebase/codebase.properties", fos);
        fos.close();
        this.codebaseURL = this.readCodebaseInfo(codebase);

        // Retrieves all currently active files from server
        File server = null;
        for (FTPFile f : client.listFiles("/Airhockey/Servers")) {
            server = new File(f.getName());
            fos = new FileOutputStream(server);
            client.retrieveFile("/Airhockey/Servers/" + f.getName(), fos);
            fos.close();
            output.add(this.readServerFile(server));
        }
        //Removes null entries
        output.remove(null);

        client.logout();
    } catch (IOException ex) {
        System.out.println("IOException: " + ex.getMessage());
        ex.printStackTrace();
    } catch (Exception ex) {
        System.out.println("exception caught: " + ex.getMessage());
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return output;
}

From source file:s32a.CodebaseDeployer.java

/**
 * Uploads given files to ftp server./*from   w w  w  .  ja  va2  s.c om*/
 *
 * @param input key: desired name on server, Value: file to upload.
 */
private void uploadFiles(Map<String, File> input) {

    FTPClient client = null;
    if (SSL) {
        client = new FTPSClient(false);
    } else {
        client = new FTPClient();
    }
    FileInputStream fis = null;
    FileOutputStream fos = null;

    try {
        System.out.println("connecting");
        client.connect(ftpServer);
        boolean login = client.login(this.userName, this.password);
        System.out.println("login: " + login);
        client.enterLocalPassiveMode();

        //            client.setFileType(FTP.ASCII_FILE_TYPE);

        //Creates all directories required on the server
        System.out.println("creating directories");
        client.makeDirectory("Airhockey");
        client.makeDirectory("Airhockey/Codebase");
        client.makeDirectory("Airhockey/Servers");
        client.makeDirectory("Airhockey/Codebase/s32a");
        System.out.println("default directories made");
        for (String s : directories) {
            client.makeDirectory(s);
        }

        //Uploads codebase URL
        fis = new FileInputStream(this.codebaseFile);
        boolean stored = client.storeFile("Airhockey/Codebase/codebase.properties", fis);
        //            client.completePendingCommand();
        System.out.println("Stored codebase file: " + stored);
        fis.close();

        // Removes references to all servers
        for (FTPFile f : client.listFiles("Airhockey/Servers")) {
            if (f.isFile()) {
                System.out.println("Deleting Server Listing: " + f.getName());
                client.deleteFile("/Airhockey/Servers/" + f.getName());
            }
        }

        // Uploads all class files
        System.out.println("Uploading classes");
        String defaultLoc = fs + "Airhockey" + fs + "Codebase" + fs;
        for (String dest : input.keySet()) {
            fis = new FileInputStream(input.get(dest));
            if (!client.storeFile(defaultLoc + dest, fis)) {
                System.out.println("unable to save: " + defaultLoc + dest);
            }
            fis.close();
            //                client.completePendingCommand();
        }

        client.logout();
    } catch (IOException ex) {
        System.out.println("IOException: " + ex.getMessage());
        ex.printStackTrace();
    } catch (Exception ex) {
        System.out.println("exception caught: " + ex.getMessage());
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
            client.disconnect();
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:s32a.FTPTest.java

public FTPTest(boolean login) {

    FTPClient client = new FTPClient();
    FileInputStream fis = null;//from w ww.ja  v a  2 s  .c  om
    FileOutputStream fos = null;

    try {
        client.connect("s32a.Airhockey.org");
        client.login("testey", "test");
        client.enterLocalPassiveMode();
        client.setFileType(FTP.ASCII_FILE_TYPE);

        client.makeDirectory("/testey");

        //        String filename = "testey.txt";
        //        File file = new File(filename);
        //        file.createNewFile();
    } catch (IOException ex) {
        Logger.getLogger(FTPTest.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
            client.disconnect();
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:s32a.FTPTest.java

public FTPTest() {
    FTPClient client = new FTPSClient(false);
    FileInputStream fis = null;/*from  www .  ja v a  2s.  co  m*/
    FileOutputStream fos = null;

    try {
        System.out.println("connecting");
        client.connect("athena.fhict.nl");
        boolean login = client.login("i293443", "ifvr2edfh101");
        System.out.println("login: " + login);
        client.enterLocalPassiveMode();
        System.out.println("connected: " + client.isConnected() + ", available: " + client.isAvailable());

        client.setFileType(FTP.ASCII_FILE_TYPE);
        //
        // Create an InputStream of the file to be uploaded
        //
        String filename = ".gitattributes";
        File file = new File(filename);
        file.createNewFile();
        System.out.println(file.length());
        fis = new FileInputStream(file.getAbsolutePath());
        client.makeDirectory("/Airhockey/Codebase/test");
        client.makeDirectory("\\Airhockey\\Codebase\\testey");

        //
        // Store file to server
        //
        String desiredName = "s32a\\Server\\.gitattributes";
        System.out.println("storefile: " + file.getAbsolutePath() + " - "
                + client.storeFile("/Airhockey/" + desiredName, fis));
        System.out.println("file stored");

        //            File output = new File("colors.json");
        //            fos = new FileOutputStream(output.getAbsolutePath());
        //            client.retrieveFile("/colors.json", fos);
        client.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception ex) {
        System.out.println("exception caught: " + ex.getMessage());
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
            client.disconnect();
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:s32a.Server.Startup.FTPHandler.java

/**
 * Checks whether client was able to login with given info.
 *
 * @return Returns a boolean indicating whether the client has been
 * successfully logged in//w w w.  ja  v  a2 s  . c o m
 */
public boolean checkLogin() {
    boolean success = false;
    FTPClient client = null;
    try {
        if (SSL) {
            client = new FTPSClient(false);
        } else {
            client = new FTPClient();
        }

        client.connect(this.ftpServer);
        success = client.login(username, password);
    } catch (IOException ex) {
        success = false;
        showDialog("Error", "FTP: CheckLogin IOException: " + ex.getMessage());
        //Logger.getLogger(FTPHandler.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (client != null) {
            try {
                client.logout();
            } catch (IOException ex) {
                showDialog("Error", "FTP: CheckLogin Logout IOException: " + ex.getMessage());
                //Logger.getLogger(FTPHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return success;
}