List of usage examples for org.apache.commons.net.ftp FTPClient enterLocalPassiveMode
public void enterLocalPassiveMode()
PASSIVE_LOCAL_DATA_CONNECTION_MODE
. From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String FTPGetFile(String sServer, String sSrcFileName, String sDstFileName, OutputStream out) { byte[] buffer = new byte[4096]; int nRead = 0; long lTotalRead = 0; String sRet = sErrorPrefix + "FTP Get failed for " + sSrcFileName; String strRet = ""; int reply = 0; FileOutputStream outStream = null; String sTmpDstFileName = fixFileName(sDstFileName); FTPClient ftp = new FTPClient(); try {/*from w w w. j av a2 s.c o m*/ ftp.connect(sServer); reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { ftp.login("anonymous", "b@t.com"); reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { ftp.enterLocalPassiveMode(); if (ftp.setFileType(FTP.BINARY_FILE_TYPE)) { File dstFile = new File(sTmpDstFileName); outStream = new FileOutputStream(dstFile); FTPFile[] ftpFiles = ftp.listFiles(sSrcFileName); if (ftpFiles.length > 0) { long lFtpSize = ftpFiles[0].getSize(); if (lFtpSize <= 0) lFtpSize = 1; InputStream ftpIn = ftp.retrieveFileStream(sSrcFileName); while ((nRead = ftpIn.read(buffer)) != -1) { lTotalRead += nRead; outStream.write(buffer, 0, nRead); strRet = "\r" + lTotalRead + " of " + lFtpSize + " bytes received " + ((lTotalRead * 100) / lFtpSize) + "% completed"; out.write(strRet.getBytes()); out.flush(); } ftpIn.close(); @SuppressWarnings("unused") boolean bRet = ftp.completePendingCommand(); outStream.flush(); outStream.close(); strRet = ftp.getReplyString(); reply = ftp.getReplyCode(); } else { strRet = sRet; } } ftp.logout(); ftp.disconnect(); sRet = "\n" + strRet; } else { ftp.disconnect(); System.err.println("FTP server refused login."); } } else { ftp.disconnect(); System.err.println("FTP server refused connection."); } } catch (SocketException e) { sRet = e.getMessage(); strRet = ftp.getReplyString(); reply = ftp.getReplyCode(); sRet += "\n" + strRet; e.printStackTrace(); } catch (IOException e) { sRet = e.getMessage(); strRet = ftp.getReplyString(); reply = ftp.getReplyCode(); sRet += "\n" + strRet; e.printStackTrace(); } return (sRet); }
From source file:GestoSAT.GestoSAT.java
@Schedule(dayOfWeek = "Sun-Sat", month = "*", hour = "22", dayOfMonth = "*", year = "*", minute = "0", second = "0", persistent = true) public void generarCopia() { // http://chuwiki.chuidiang.org/index.php?title=Backup_de_MySQL_con_Java try {/* w ww .j a v a 2s .co m*/ Process p = Runtime.getRuntime().exec("mysqldump -u " + mySQL.elementAt(2) + " -p" + mySQL.elementAt(3) + " -h " + mySQL.elementAt(0) + " -P " + mySQL.elementAt(1) + " gestosat"); InputStream is = p.getInputStream(); FileOutputStream fos = new FileOutputStream("backupGestoSAT.sql"); byte[] buffer = new byte[1000]; int leido = is.read(buffer); while (leido > 0) { fos.write(buffer, 0, leido); leido = is.read(buffer); } fos.close(); //http://www.javamexico.org/blogs/lalo200/pequeno_ejemplo_para_subir_un_archivo_ftp_con_la_libreria_commons_net FTPClient clienteFTP = new FTPClient(); // Lanza excepcin si el servidor no existe clienteFTP.connect(confSeg.elementAt(0), Integer.parseInt(confSeg.elementAt(1))); if (clienteFTP.login(confSeg.elementAt(2), confSeg.elementAt(3))) { clienteFTP.setFileType(FTP.BINARY_FILE_TYPE); BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream("backupGestoSAT.sql")); clienteFTP.enterLocalPassiveMode(); clienteFTP.storeFile("backupGestoSAT.sql", buffIn); buffIn.close(); clienteFTP.logout(); clienteFTP.disconnect(); } else System.out.println("Error de conexin FTP"); } catch (Exception e) { e.printStackTrace(); } }
From source file:GestoSAT.GestoSAT.java
public boolean actualizarConfiguracion(Vector<String> mySQL, Vector<String> confSeg, int iva, String logo) throws Exception { FileReader file;/*from w ww .ja v a2 s. c o m*/ try { this.iva = Math.abs(iva); BufferedImage image = null; byte[] imageByte; BASE64Decoder decoder = new BASE64Decoder(); imageByte = decoder.decodeBuffer(logo.split(",")[1]); ByteArrayInputStream bis = new ByteArrayInputStream(imageByte); image = ImageIO.read(bis); bis.close(); // write the image to a file File outputfile = new File("logo"); String formato = logo.split("/")[1].split(";")[0]; ImageIO.write(image, formato, outputfile); // MySQL if (mySQL.elementAt(0).equals(this.mySQL.elementAt(0))) { if (!mySQL.elementAt(1).equals(this.mySQL.elementAt(1)) && !mySQL.elementAt(2).equals(this.mySQL.elementAt(2)) && (!mySQL.elementAt(3).equals(this.mySQL.elementAt(3)) || !mySQL.elementAt(0).equals(""))) { Class.forName("com.mysql.jdbc.Driver"); this.con.close(); this.con = DriverManager.getConnection("jdbc:mysql://" + mySQL.elementAt(0) + ":" + Math.abs(Integer.parseInt(mySQL.elementAt(1))) + "/gestosat?user=" + mySQL.elementAt(2) + "&password=" + mySQL.elementAt(3)); this.mySQL.set(0, mySQL.elementAt(0)); this.mySQL.set(1, Math.abs(Integer.parseInt(mySQL.elementAt(1))) + ""); this.mySQL.set(2, mySQL.elementAt(2)); this.mySQL.set(3, mySQL.elementAt(3)); } } else { // Comprobar que pass != "" Process pGet = Runtime.getRuntime() .exec("mysqldump -u " + this.mySQL.elementAt(2) + " -p" + this.mySQL.elementAt(3) + " -h " + this.mySQL.elementAt(0) + " -P " + this.mySQL.elementAt(1) + " gestosat"); InputStream is = pGet.getInputStream(); FileOutputStream fos = new FileOutputStream("backupGestoSAT.sql"); byte[] bufferOut = new byte[1000]; int leido = is.read(bufferOut); while (leido > 0) { fos.write(bufferOut, 0, leido); leido = is.read(bufferOut); } fos.close(); Class.forName("com.mysql.jdbc.Driver"); this.con.close(); this.con = DriverManager.getConnection( "jdbc:mysql://" + mySQL.elementAt(0) + ":" + Math.abs(Integer.parseInt(mySQL.elementAt(1))) + "/gestosat?user=" + mySQL.elementAt(2) + "&password=" + mySQL.elementAt(3)); this.mySQL.set(0, mySQL.elementAt(0)); this.mySQL.set(1, Math.abs(Integer.parseInt(mySQL.elementAt(1))) + ""); this.mySQL.set(2, mySQL.elementAt(2)); this.mySQL.set(3, mySQL.elementAt(3)); Process pPut = Runtime.getRuntime() .exec("mysql -u " + mySQL.elementAt(2) + " -p" + mySQL.elementAt(3) + " -h " + mySQL.elementAt(0) + " -P " + Math.abs(Integer.parseInt(mySQL.elementAt(1))) + " gestosat"); OutputStream os = pPut.getOutputStream(); FileInputStream fis = new FileInputStream("backupGestoSAT.sql"); byte[] bufferIn = new byte[1000]; int escrito = fis.read(bufferIn); while (escrito > 0) { os.write(bufferIn, 0, leido); escrito = fis.read(bufferIn); } os.flush(); os.close(); fis.close(); } // FTP FTPClient cliente = new FTPClient(); if (!confSeg.elementAt(3).equals("")) { cliente.connect(confSeg.elementAt(0), Integer.parseInt(confSeg.elementAt(1))); if (cliente.login(confSeg.elementAt(2), confSeg.elementAt(3))) { cliente.setFileType(FTP.BINARY_FILE_TYPE); BufferedInputStream buffIn = new BufferedInputStream(new FileInputStream("backupGestoSAT.sql")); cliente.enterLocalPassiveMode(); cliente.storeFile("backupGestoSAT.sql", buffIn); buffIn.close(); cliente.logout(); cliente.disconnect(); this.confSeg = confSeg; } else return false; } File archConf = new File("confGestoSAT"); BufferedWriter bw = new BufferedWriter(new FileWriter(archConf)); bw.write(this.mySQL.elementAt(0) + ";" + Math.abs(Integer.parseInt(this.mySQL.elementAt(1))) + ";" + this.mySQL.elementAt(2) + ";" + this.mySQL.elementAt(3) + ";" + this.confSeg.elementAt(0) + ";" + Math.abs(Integer.parseInt(this.confSeg.elementAt(1))) + ";" + this.confSeg.elementAt(2) + ";" + this.confSeg.elementAt(3) + ";" + Math.abs(iva)); bw.close(); return true; } catch (Exception ex) { file = new FileReader("confGestoSAT"); BufferedReader b = new BufferedReader(file); String cadena; cadena = b.readLine(); String[] valores = cadena.split(";"); this.mySQL.add(valores[0]); this.mySQL.add(Math.abs(Integer.parseInt(valores[1])) + ""); this.mySQL.add(valores[2]); this.mySQL.add(valores[3]); con.close(); Class.forName("com.mysql.jdbc.Driver"); con = DriverManager .getConnection("jdbc:mysql://" + this.mySQL.elementAt(0) + ":" + this.mySQL.elementAt(1) + "/gestosat?user=" + this.mySQL.elementAt(2) + "&password=" + this.mySQL.elementAt(3)); this.confSeg.add(valores[4]); this.confSeg.add(Math.abs(Integer.parseInt(valores[5])) + ""); this.confSeg.add(valores[6]); this.confSeg.add(valores[7]); file.close(); Logger.getLogger(GestoSAT.class.getName()).log(Level.SEVERE, null, ex); return false; } }
From source file:com.o6Systems.utils.net.FTPModule.java
private int executeFtpCommand(String[] args) throws UnknownHostException { boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false, hidden = false;//from ww w .j a va 2 s .c om boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false; boolean mlst = false, mlsd = false; boolean lenient = false; long keepAliveTimeout = -1; int controlKeepAliveReplyTimeout = -1; int minParams = 5; // listings require 3 params String protocol = null; // SSL protocol String doCommand = null; String trustmgr = null; String proxyHost = null; int proxyPort = 80; String proxyUser = null; String proxyPassword = null; String username = null; String password = null; int base = 0; // Print the command System.out.println("----------FTP MODULE CALL----------"); for (int i = 0; i < args.length; i++) { System.out.println(args[i]); } System.out.println("--------------------"); // for (base = 0; base < args.length; base++) { if (args[base].equals("-s")) { storeFile = true; } else if (args[base].equals("-a")) { localActive = true; } else if (args[base].equals("-A")) { username = "anonymous"; password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName(); } else if (args[base].equals("-b")) { binaryTransfer = true; } else if (args[base].equals("-c")) { doCommand = args[++base]; minParams = 3; } else if (args[base].equals("-d")) { mlsd = true; minParams = 3; } else if (args[base].equals("-e")) { useEpsvWithIPv4 = true; } else if (args[base].equals("-f")) { feat = true; minParams = 3; } else if (args[base].equals("-h")) { hidden = true; } else if (args[base].equals("-k")) { keepAliveTimeout = Long.parseLong(args[++base]); } else if (args[base].equals("-l")) { listFiles = true; minParams = 3; } else if (args[base].equals("-L")) { lenient = true; } else if (args[base].equals("-n")) { listNames = true; minParams = 3; } else if (args[base].equals("-p")) { protocol = args[++base]; } else if (args[base].equals("-t")) { mlst = true; minParams = 3; } else if (args[base].equals("-w")) { controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]); } else if (args[base].equals("-T")) { trustmgr = args[++base]; } else if (args[base].equals("-PrH")) { proxyHost = args[++base]; String parts[] = proxyHost.split(":"); if (parts.length == 2) { proxyHost = parts[0]; proxyPort = Integer.parseInt(parts[1]); } } else if (args[base].equals("-PrU")) { proxyUser = args[++base]; } else if (args[base].equals("-PrP")) { proxyPassword = args[++base]; } else if (args[base].equals("-#")) { printHash = true; } else { break; } } int remain = args.length - base; if (username != null) { minParams -= 2; } String server = args[base++]; int port = 0; String parts[] = server.split(":"); if (parts.length == 2) { server = parts[0]; port = Integer.parseInt(parts[1]); } if (username == null) { username = args[base++]; password = args[base++]; } String remote = null; if (args.length - base > 0) { remote = args[base++]; } String local = null; if (args.length - base > 0) { local = args[base++]; } final FTPClient ftp; if (protocol == null) { if (proxyHost != null) { System.out.println("Using HTTP proxy server: " + proxyHost); ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword); } else { ftp = new FTPClient(); } } else { FTPSClient ftps; if (protocol.equals("true")) { ftps = new FTPSClient(true); } else if (protocol.equals("false")) { ftps = new FTPSClient(false); } else { String prot[] = protocol.split(","); if (prot.length == 1) { // Just protocol ftps = new FTPSClient(protocol); } else { // protocol,true|false ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1])); } } ftp = ftps; if ("all".equals(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else if ("valid".equals(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); } else if ("none".equals(trustmgr)) { ftps.setTrustManager(null); } } if (printHash) { ftp.setCopyStreamListener(createListener()); } if (keepAliveTimeout >= 0) { ftp.setControlKeepAliveTimeout(keepAliveTimeout); } if (controlKeepAliveReplyTimeout >= 0) { ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout); } ftp.setListHiddenFiles(hidden); // suppress login details ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); try { int reply; if (port > 0) { ftp.connect(server, port); } else { ftp.connect(server); } System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort())); // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return 1; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server."); e.printStackTrace(); return 1; } __main: try { if (!ftp.login(username, password)) { ftp.logout(); error = true; break __main; } System.out.println("Remote system is " + ftp.getSystemType()); if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } else { // in theory this should not be necessary as servers should default to ASCII // but they don't all do so - see NET-500 ftp.setFileType(FTP.ASCII_FILE_TYPE); } // Use passive mode as default because most of us are // behind firewalls these days. if (localActive) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } ftp.setUseEPSVwithIPv4(useEpsvWithIPv4); if (storeFile) { InputStream input; input = new FileInputStream(local); ftp.storeFile(remote, input); input.close(); } else if (listFiles) { if (lenient) { FTPClientConfig config = new FTPClientConfig(); config.setLenientFutureDates(true); ftp.configure(config); } for (FTPFile f : ftp.listFiles(remote)) { System.out.println(f.getRawListing()); System.out.println(f.toFormattedString()); } } else if (mlsd) { for (FTPFile f : ftp.mlistDir(remote)) { System.out.println(f.getRawListing()); System.out.println(f.toFormattedString()); } } else if (mlst) { FTPFile f = ftp.mlistFile(remote); if (f != null) { System.out.println(f.toFormattedString()); } } else if (listNames) { for (String s : ftp.listNames(remote)) { System.out.println(s); } } else if (feat) { // boolean feature check if (remote != null) { // See if the command is present if (ftp.hasFeature(remote)) { System.out.println("Has feature: " + remote); } else { if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { System.out.println("FEAT " + remote + " was not detected"); } else { System.out.println("Command failed: " + ftp.getReplyString()); } } // Strings feature check String[] features = ftp.featureValues(remote); if (features != null) { for (String f : features) { System.out.println("FEAT " + remote + "=" + f + "."); } } else { if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { System.out.println("FEAT " + remote + " is not present"); } else { System.out.println("Command failed: " + ftp.getReplyString()); } } } else { if (ftp.features()) { // Command listener has already printed the output } else { System.out.println("Failed: " + ftp.getReplyString()); } } } else if (doCommand != null) { if (ftp.doCommand(doCommand, remote)) { // Command listener has already printed the output // for(String s : ftp.getReplyStrings()) { // System.out.println(s); // } } else { System.out.println("Failed: " + ftp.getReplyString()); } } else { OutputStream output; output = new FileOutputStream(local); ftp.retrieveFile(remote, output); output.close(); } ftp.noop(); // check that control connection is working OK ftp.logout(); } catch (FTPConnectionClosedException e) { error = true; System.err.println("Server closed connection."); e.printStackTrace(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } } return error ? 1 : 0; }
From source file:com.github.goldin.org.apache.tools.ant.taskdefs.optional.net.FTP.java
/** * Runs the task./* w w w .j a v a2 s .com*/ * * @throws BuildException if the task fails or is not configured * correctly. */ public void execute() throws BuildException { checkAttributes(); FTPClient ftp = null; try { log("Opening FTP connection to " + server, Project.MSG_VERBOSE); /** * "verbose" version of <code>FTPClient</code> prints progress indicator * See http://evgeny-goldin.com/blog/2010/08/18/ant-ftp-task-progress-indicator-timeout/ */ ftp = (verbose ? new com.github.goldin.org.apache.tools.ant.taskdefs.optional.net.FTPClient(getProject()) : new org.apache.commons.net.ftp.FTPClient()); ftp.setDataTimeout(5 * 60 * 1000); // 5 minutes if (this.isConfigurationSet) { ftp = FTPConfigurator.configure(ftp, this); } ftp.setRemoteVerificationEnabled(enableRemoteVerification); ftp.connect(server, port); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("FTP connection failed: " + ftp.getReplyString()); } log("connected", Project.MSG_VERBOSE); log("logging in to FTP server", Project.MSG_VERBOSE); if ((this.account != null && !ftp.login(userid, password, account)) || (this.account == null && !ftp.login(userid, password))) { throw new BuildException("Could not login to FTP server"); } log("login succeeded", Project.MSG_VERBOSE); if (binary) { ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } else { ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } if (passive) { log("entering passive mode", Project.MSG_VERBOSE); ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not enter into passive " + "mode: " + ftp.getReplyString()); } } // If an initial command was configured then send it. // Some FTP servers offer different modes of operation, // E.G. switching between a UNIX file system mode and // a legacy file system. if (this.initialSiteCommand != null) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, FTP.this.initialSiteCommand); } }, "initial site command: " + this.initialSiteCommand); } // For a unix ftp server you can set the default mask for all files // created. if (umask != null) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, "umask " + umask); } }, "umask " + umask); } // If the action is MK_DIR, then the specified remote // directory is the directory to create. if (action == MK_DIR) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { makeRemoteDir(lftp, remotedir); } }, remotedir); } else if (action == SITE_CMD) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, FTP.this.siteCommand); } }, "Site Command: " + this.siteCommand); } else { if (remotedir != null) { log("changing the remote directory to " + remotedir, Project.MSG_VERBOSE); ftp.changeWorkingDirectory(remotedir); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not change remote " + "directory: " + ftp.getReplyString()); } } if (newerOnly && timeDiffAuto) { // in this case we want to find how much time span there is between local // and remote timeDiffMillis = getTimeDiff(ftp); } log(ACTION_STRS[action] + " " + ACTION_TARGET_STRS[action]); transferFiles(ftp); } } catch (IOException ex) { throw new BuildException("error during FTP transfer: " + ex, ex); } finally { if (ftp != null && ftp.isConnected()) { try { log("disconnecting", Project.MSG_VERBOSE); ftp.logout(); ftp.disconnect(); } catch (IOException ex) { // ignore it } } } }
From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java
/** * Runs the task./*from w ww . j a v a2s . c om*/ * * @throws BuildException if the task fails or is not configured * correctly. */ public void execute() throws BuildException { checkAttributes(); FTPClient ftp = null; try { log("Opening FTP connection to " + server, Project.MSG_VERBOSE); /** * "verbose" version of <code>FTPClient</code> prints progress indicator * See http://evgeny-goldin.com/blog/2010/08/18/ant-ftp-task-progress-indicator-timeout/ */ ftp = (verbose ? new com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTPClient(getProject()) : new org.apache.commons.net.ftp.FTPClient()); ftp.setDataTimeout(5 * 60 * 1000); // 5 minutes if (this.isConfigurationSet) { ftp = FTPConfigurator.configure(ftp, this); } ftp.setRemoteVerificationEnabled(enableRemoteVerification); ftp.connect(server, port); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("FTP connection failed: " + ftp.getReplyString()); } log("connected", Project.MSG_VERBOSE); log("logging in to FTP server", Project.MSG_VERBOSE); if ((this.account != null && !ftp.login(userid, password, account)) || (this.account == null && !ftp.login(userid, password))) { throw new BuildException("Could not login to FTP server"); } log("login succeeded", Project.MSG_VERBOSE); if (binary) { ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } else { ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } if (passive) { log("entering passive mode", Project.MSG_VERBOSE); ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not enter into passive " + "mode: " + ftp.getReplyString()); } } // If an initial command was configured then send it. // Some FTP servers offer different modes of operation, // E.G. switching between a UNIX file system mode and // a legacy file system. if (this.initialSiteCommand != null) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, FTP.this.initialSiteCommand); } }, "initial site command: " + this.initialSiteCommand); } // For a unix ftp server you can set the default mask for all files // created. if (umask != null) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, "umask " + umask); } }, "umask " + umask); } // If the action is MK_DIR, then the specified remote // directory is the directory to create. if (action == MK_DIR) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { makeRemoteDir(lftp, remotedir); } }, remotedir); } else if (action == SITE_CMD) { RetryHandler h = new RetryHandler(this.retriesAllowed, this); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, FTP.this.siteCommand); } }, "Site Command: " + this.siteCommand); } else { if (remotedir != null) { log("changing the remote directory to " + remotedir, Project.MSG_VERBOSE); ftp.changeWorkingDirectory(remotedir); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not change remote " + "directory: " + ftp.getReplyString()); } } if (newerOnly && timeDiffAuto) { // in this case we want to find how much time span there is between local // and remote timeDiffMillis = getTimeDiff(ftp); } log(ACTION_STRS[action] + " " + ACTION_TARGET_STRS[action]); transferFiles(ftp); } } catch (IOException ex) { throw new BuildException("error during FTP transfer: " + ex, ex); } finally { if (ftp != null && ftp.isConnected()) { try { log("disconnecting", Project.MSG_VERBOSE); ftp.logout(); ftp.disconnect(); } catch (IOException ex) { // ignore it } } } }
From source file:fr.acxio.tools.agia.ftp.DefaultFtpClientFactory.java
public FTPClient getFtpClient() throws IOException { FTPClient aClient = new FTPClient(); // Debug output // aClient.addProtocolCommandListener(new PrintCommandListener(new // PrintWriter(System.out), true)); if (activeExternalIPAddress != null) { aClient.setActiveExternalIPAddress(activeExternalIPAddress); }/*from w ww.j a va 2 s . c o m*/ if (activeMinPort != null && activeMaxPort != null) { aClient.setActivePortRange(activeMinPort, activeMaxPort); } if (autodetectUTF8 != null) { aClient.setAutodetectUTF8(autodetectUTF8); } if (bufferSize != null) { aClient.setBufferSize(bufferSize); } if (charset != null) { aClient.setCharset(charset); } if (connectTimeout != null) { aClient.setConnectTimeout(connectTimeout); } if (controlEncoding != null) { aClient.setControlEncoding(controlEncoding); } if (controlKeepAliveReplyTimeout != null) { aClient.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout); } if (controlKeepAliveTimeout != null) { aClient.setControlKeepAliveTimeout(controlKeepAliveTimeout); } if (dataTimeout != null) { aClient.setDataTimeout(dataTimeout); } if (defaultPort != null) { aClient.setDefaultPort(defaultPort); } if (defaultTimeout != null) { aClient.setDefaultTimeout(defaultTimeout); } if (fileStructure != null) { aClient.setFileStructure(fileStructure); } if (keepAlive != null) { aClient.setKeepAlive(keepAlive); } if (listHiddenFiles != null) { aClient.setListHiddenFiles(listHiddenFiles); } if (parserFactory != null) { aClient.setParserFactory(parserFactory); } if (passiveLocalIPAddress != null) { aClient.setPassiveLocalIPAddress(passiveLocalIPAddress); } if (passiveNatWorkaround != null) { aClient.setPassiveNatWorkaround(passiveNatWorkaround); } if (proxy != null) { aClient.setProxy(proxy); } if (receieveDataSocketBufferSize != null) { aClient.setReceieveDataSocketBufferSize(receieveDataSocketBufferSize); } if (receiveBufferSize != null) { aClient.setReceiveBufferSize(receiveBufferSize); } if (remoteVerificationEnabled != null) { aClient.setRemoteVerificationEnabled(remoteVerificationEnabled); } if (reportActiveExternalIPAddress != null) { aClient.setReportActiveExternalIPAddress(reportActiveExternalIPAddress); } if (sendBufferSize != null) { aClient.setSendBufferSize(sendBufferSize); } if (sendDataSocketBufferSize != null) { aClient.setSendDataSocketBufferSize(sendDataSocketBufferSize); } if (strictMultilineParsing != null) { aClient.setStrictMultilineParsing(strictMultilineParsing); } if (tcpNoDelay != null) { aClient.setTcpNoDelay(tcpNoDelay); } if (useEPSVwithIPv4 != null) { aClient.setUseEPSVwithIPv4(useEPSVwithIPv4); } if (systemKey != null) { FTPClientConfig aClientConfig = new FTPClientConfig(systemKey); if (defaultDateFormat != null) { aClientConfig.setDefaultDateFormatStr(defaultDateFormat); } if (recentDateFormat != null) { aClientConfig.setRecentDateFormatStr(recentDateFormat); } if (serverLanguageCode != null) { aClientConfig.setServerLanguageCode(serverLanguageCode); } if (shortMonthNames != null) { aClientConfig.setShortMonthNames(shortMonthNames); } if (serverTimeZoneId != null) { aClientConfig.setServerTimeZoneId(serverTimeZoneId); } aClient.configure(aClientConfig); } if (LOGGER.isInfoEnabled()) { LOGGER.info("Connecting to : {}", host); } if (port == null) { aClient.connect(host); } else { aClient.connect(host, port); } int aReplyCode = aClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(aReplyCode)) { aClient.disconnect(); throw new IOException("Cannot connect to " + host + ". Returned code : " + aReplyCode); } try { if (localPassiveMode) { aClient.enterLocalPassiveMode(); } boolean aIsLoggedIn = false; if (account == null) { aIsLoggedIn = aClient.login(username, password); } else { aIsLoggedIn = aClient.login(username, password, account); } if (!aIsLoggedIn) { throw new IOException(aClient.getReplyString()); } } catch (IOException e) { aClient.disconnect(); throw e; } if (fileTransferMode != null) { aClient.setFileTransferMode(fileTransferMode); } if (fileType != null) { aClient.setFileType(fileType); } return aClient; }
From source file:base.BasePlayer.Main.java
static String getNewFile(String server, String folder, String oldfile) { String minfile = ""; try {//from w ww . j a va 2 s. c o m String filename = oldfile; FTPClient f = new FTPClient(); f.connect(server); f.enterLocalPassiveMode(); f.login("anonymous", ""); FTPFile[] files = f.listFiles(folder); int left = 0, right = filename.length() - 1, distance = 0; int mindistance = 100; for (int i = 0; i < files.length; i++) { if (files[i].getName().endsWith(".gff3.gz")) { distance = 0; right = Math.min(filename.length(), files[i].getName().length()); left = 0; while (left < right) { if (filename.charAt(left) != files[i].getName().charAt(left)) { distance++; } left++; } distance += Math.abs(filename.length() - files[i].getName().length()); if (distance < mindistance) { mindistance = distance; minfile = files[i].getName(); } } } } catch (Exception ex) { ex.printStackTrace(); } return minfile; }
From source file:com.ibm.cics.ca1y.Emit.java
/** * Get the contents of a file from an FTP server. * //from ww w .j a va 2 s. c om * @param filename * - * @param server * - * @param useraname * - * @param userpassword * - * @param transfer * - * @param mode * - * @param epsv * - * @param protocol * - * @param trustmgr * - * @param datatimeout * - * @param proxyserver * - * @param proxyusername * - * @param proxypassword * - * @param anonymouspassword * - * @return byte[] representing the retrieved file, null otherwise. */ private static byte[] getFileUsingFTP(String filename, String server, String username, String userpassword, String transfer, String mode, String epsv, String protocol, String trustmgr, String datatimeout, String proxyserver, String proxyusername, String proxypassword, String anonymouspassword) { FTPClient ftp; if (filename == null || server == null) return null; int port = 0; if (server != null) { String parts[] = server.split(":"); if (parts.length == 2) { server = parts[0]; try { port = Integer.parseInt(parts[1]); } catch (Exception _ex) { } } } int proxyport = 0; if (proxyserver != null) { String parts[] = proxyserver.split(":"); if (parts.length == 2) { proxyserver = parts[0]; try { proxyport = Integer.parseInt(parts[1]); } catch (Exception _ex) { } } } if (username == null) { username = "anonymous"; if (userpassword == null) userpassword = anonymouspassword; } if (protocol == null) { if (proxyserver != null) ftp = new FTPHTTPClient(proxyserver, proxyport, proxyusername, proxypassword); else ftp = new FTPClient(); } else { FTPSClient ftps = null; if ("true".equalsIgnoreCase(protocol)) { ftps = new FTPSClient(true); } else if ("false".equalsIgnoreCase(protocol)) { ftps = new FTPSClient(false); } else if (protocol != null) { String parts[] = protocol.split(","); if (parts.length == 1) ftps = new FTPSClient(protocol); else ftps = new FTPSClient(parts[0], Boolean.parseBoolean(parts[1])); } ftp = ftps; if ("all".equalsIgnoreCase(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else if ("valid".equalsIgnoreCase(trustmgr)) { ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); } else if ("none".equalsIgnoreCase(trustmgr)) { ftps.setTrustManager(null); } } if (datatimeout != null) { try { ftp.setDataTimeout(Integer.parseInt(datatimeout)); } catch (Exception _ex) { ftp.setDataTimeout(-1); } } if (port <= 0) { port = ftp.getDefaultPort(); } if (logger.isLoggable(Level.FINE)) { StringBuilder sb = new StringBuilder(); sb.append(Emit.messages.getString("FTPAboutToGetFileFromServer")).append(" - ").append("file name:") .append(filename).append(",server:").append(server).append(":").append(port) .append(",username:").append(username).append(",userpassword:") .append(userpassword != null && !"anonymous".equals(username) ? "<obscured>" : userpassword) .append(",transfer:").append(transfer).append(",mode:").append(mode).append(",epsv:") .append(epsv).append(",protocol:").append(protocol).append(",trustmgr:").append(trustmgr) .append(",datatimeout:").append(datatimeout).append(",proxyserver:").append(proxyserver) .append(":").append(proxyport).append(",proxyusername:").append(proxyusername) .append(",proxypassword:").append(proxypassword != null ? "<obscured>" : null); logger.fine(sb.toString()); } try { if (port > 0) { ftp.connect(server, port); } else { ftp.connect(server); } int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); logger.warning(Emit.messages.getString("FTPCouldNotConnectToServer")); return null; } } catch (IOException _ex) { logger.warning(Emit.messages.getString("FTPCouldNotConnectToServer")); if (ftp.isConnected()) try { ftp.disconnect(); } catch (IOException _ex2) { } return null; } ByteArrayOutputStream output; try { if (!ftp.login(username, userpassword)) { ftp.logout(); logger.warning(Emit.messages.getString("FTPServerRefusedLoginCredentials")); return null; } if ("binary".equalsIgnoreCase(transfer)) { ftp.setFileType(2); } else { ftp.setFileType(0); } if ("localactive".equalsIgnoreCase(mode)) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } ftp.setUseEPSVwithIPv4("true".equalsIgnoreCase(epsv)); output = new ByteArrayOutputStream(); ftp.retrieveFile(filename, output); output.close(); ftp.noop(); ftp.logout(); } catch (IOException _ex) { logger.warning(Emit.messages.getString("FTPFailedToTransferFile")); if (ftp.isConnected()) try { ftp.disconnect(); } catch (IOException _ex2) { } return null; } return output.toByteArray(); }
From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java
public Thread videoUploadToFTPserver(final Activity activity, final Handler handler, final String latestVideoFile_filename, final String latestVideoFile_absolutepath, final String emailAddress, final long sdrecord_id) { Log.d(TAG, "doVideoFTP starting"); // Make the progress bar view visible. ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_FTP); final Resources res = activity.getResources(); Thread t = new Thread(new Runnable() { public void run() { // Do background task. // FTP; connect preferences here! ///*from w w w.j a v a 2s.com*/ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext()); String ftpHostName = prefs.getString("defaultFTPhostPreference", null); String ftpUsername = prefs.getString("defaultFTPusernamePreference", null); String ftpPassword = prefs.getString("defaultFTPpasswordPreference", null); // use name of local file. String ftpRemoteFtpFilename = latestVideoFile_filename; // FTP FTPClient ftpClient = new FTPClient(); InetAddress uploadhost = null; try { uploadhost = InetAddress.getByName(ftpHostName); } catch (UnknownHostException e1) { // If DNS resolution fails then abort immediately - show // dialog to // inform user first. e1.printStackTrace(); Log.e(TAG, " got exception resolving " + ftpHostName + " - video uploading failed."); uploadhost = null; } if (uploadhost == null) { // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); new AlertDialog.Builder(activity).setMessage(R.string.cant_find_upload_host) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).show(); } }, 0); return; } boolean connected = false; try { ftpClient.connect(uploadhost); connected = true; } catch (SocketException e) { e.printStackTrace(); connected = false; } catch (UnknownHostException e) { // e.printStackTrace(); connected = false; } catch (IOException e) { // e.printStackTrace(); connected = false; } if (!connected) { // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).show(); } }, 0); return; } boolean reply = false; try { reply = ftpClient.login(ftpUsername, ftpPassword); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on ftp.login - video uploading failed."); } // check the reply code here // If we cant login, abort after showing user a dialog. if (!reply) { try { ftpClient.disconnect(); } catch (IOException e) { // e.printStackTrace(); } // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); new AlertDialog.Builder(activity).setMessage(R.string.cant_login_upload_host) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }).show(); } }, 0); return; } // Set File type to binary try { ftpClient.setFileType(FTP.BINARY_FILE_TYPE); } catch (IOException e) { // e.printStackTrace(); // keep going?! } // BEYOND HERE DONT USE DIALOGS! // Construct the input stream to send to Ftp server, from the // local // video file on the sd card BufferedInputStream buffIn = null; File file = new File(latestVideoFile_absolutepath); try { buffIn = new BufferedInputStream(new FileInputStream(file)); } catch (FileNotFoundException e) { // e.printStackTrace(); Log.e(TAG, " got exception on local video file - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); // This is a bad error, lets abort. // user dialog ?! shouldnt happen, but still... return; } ftpClient.enterLocalPassiveMode(); try { // UPLOAD THE LOCAL VIDEO FILE. ftpClient.storeFile(ftpRemoteFtpFilename, buffIn); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on storeFile - video uploading failed."); // This is a bad error, lets abort. // user dialog ?! shouldnt happen, but still... // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } try { buffIn.close(); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on buff.close - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } try { ftpClient.logout(); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on ftp logout - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } try { ftpClient.disconnect(); } catch (IOException e) { // e.printStackTrace(); Log.e(TAG, " got exception on ftp disconnect - video uploading failed."); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); handler.postDelayed(new Runnable() { public void run() { // Update UI // Hide the progress bar ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_failed_)); } }, 0); return; } if (emailAddress != null && ftpHostName != null) { // EmailSender through IR controlled gmail system. SSLEmailSender sender = new SSLEmailSender( activity.getString(R.string.automatic_email_username), activity.getString(R.string.automatic_email_password)); // consider // this // public // knowledge. try { sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(), activity.getString(R.string.url_of_hosted_video_is_) + " " + ftpHostName, // body.getText().toString(), activity.getString(R.string.automatic_email_from), // from.getText().toString(), emailAddress // to.getText().toString() ); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } } // Log record of this URL in POSTs table dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, ftpHostName, ftpHostName, ""); mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FTP); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((VidiomActivity) activity).finishedUploading(true); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_ftp_host_succeeded_)); } }, 0); } }); t.start(); return t; }