List of usage examples for org.apache.commons.net.ftp FTPClient FTPClient
public FTPClient()
From source file:primarydatamanager.mirrorupdater.data.FtpDataTarget.java
private void reset() throws UpdateException { if (mFTPClient != null && mFTPClient.isConnected()) { try {/*from ww w . j a v a 2 s . c o m*/ mFTPClient.disconnect(); } catch (IOException e) { // ignore } } // Connect to the server mFTPClient = new FTPClient(); try { mFTPClient.connect(mServerUrl, mPort); mLog.fine("Connected to " + mServerUrl + ":" + mPort); mFTPClient.setSoTimeout(30000); checkReplyCode(); } catch (Exception exc) { if (mFTPClient.isConnected()) { try { mFTPClient.disconnect(); } catch (IOException exc2) { // do nothing } } throw new UpdateException("Could not connect to server '" + mServerUrl + "'", exc); } // Log in try { boolean success = mFTPClient.login(mUser, mPassword); checkReplyCode(); if (!success) { throw new UpdateException("Login failed"); } } catch (Exception exc) { throw new UpdateException( "Login using user='" + mUser + "' and password=(" + mPassword.length() + " characters) failed", exc); } // Set the file type to binary try { boolean success = mFTPClient.setFileType(FTP.BINARY_FILE_TYPE); checkReplyCode(); if (!success) { throw new UpdateException("Setting file type to binary failed"); } } catch (Exception exc) { throw new UpdateException("Setting file type to binary failed", exc); } // Change directory try { boolean success = mFTPClient.changeWorkingDirectory(mPath); checkReplyCode(); if (!success) { throw new UpdateException("Could not change to directory '" + mPath + "'"); } } catch (Exception exc) { throw new UpdateException("Could not change to directory '" + mPath + "'", exc); } mLog.fine("Changed to directory " + mPath); }
From source file:Proiect.uploadFTP.java
public void actionFTP() { adressf.addCaretListener(new CaretListener() { public void caretUpdate(CaretEvent e) { InetAddress thisIp;// ww w . jav a 2 s . c o m 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;// w w w . ja v a 2 s. co m 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:proyectoftp.modelo.ClienteFTP.java
public ClienteFTP() { clienteFtp = new FTPClient(); }
From source file:rapture.ftp.common.FTPConnection.java
public FTPConnection(FTPConnectionConfig config) { ftpClient = new FTPClient(); this.config = config; }
From source file:rapture.ftp.common.FTPConnection.java
public FTPConnection(String configUri) { String configDoc = Kernel.getDoc().getDoc(ContextFactory.getKernelUser(), configUri); this.config = (configDoc == null) ? new FTPConnectionConfig() : JacksonUtil.objectFromJson(configDoc, FTPConnectionConfig.class); ftpClient = new FTPClient(); }
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 {/*ww w .j a va2 s .c om*/ // 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 {/* w w w.j a va 2 s. com*/ // 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 ww w . j av a 2s . c o m // 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 ww w .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; }