List of usage examples for org.apache.commons.net.ftp FTPClient enterLocalPassiveMode
public void enterLocalPassiveMode()
PASSIVE_LOCAL_DATA_CONNECTION_MODE
. From source file:Proiect.uploadFTP.java
public void actionFTP() { adressf.addCaretListener(new CaretListener() { public void caretUpdate(CaretEvent e) { InetAddress thisIp;//from ww w. j av a 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:rapture.ftp.common.FTPConnection.java
@Override public boolean connectAndLogin() { if (isLocal()) { log.info("In local mode - not connecting"); return true; }//from w ww . ja va 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 {// w w w . j a v a2 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 . ja va 2 s. c o m // 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: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 av a 2 s. com*/ 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 {//w w w . ja va2 s . co m // 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; } }
From source file:ru.in360.FTPUploader.java
public boolean upload(File src, URI dest) { FTPClient ftpClient = new FTPClient(); try {/* w w w .j a va 2 s.co m*/ // connect and login to the server ftpClient.connect(server, port); ftpClient.login(user, pass); // use local passive mode to pass firewall ftpClient.enterLocalPassiveMode(); //ftpClient.makeDirectory(remoteProject); String path = ""; for (String dir : (remoteProject + dest.getPath()).split("/")) { ftpClient.makeDirectory(path + "/" + dir); path = path + "/" + dir; } System.out.println("Connected"); System.out.println(remoteProject + dest.getPath()); FTPUtil.saveFilesToServer(ftpClient, remoteProject + dest.getPath(), 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; } }
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 //w ww .j a v a 2s .com */ 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./* w w w .java2 s. co m*/ * * @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 ww w. j a v a 2 s .c o m*/ 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(); } } }