List of usage examples for org.apache.commons.net.ftp FTPClient changeWorkingDirectory
public boolean changeWorkingDirectory(String pathname) throws IOException
From source file:ru.in360.FTPUtil.java
public static void upload(File src, FTPClient ftp) throws IOException { if (src.isDirectory()) { ftp.makeDirectory(src.getName()); ftp.changeWorkingDirectory(src.getName()); for (File file : src.listFiles()) { upload(file, ftp);/*from ww w .j a va2 s . co m*/ } ftp.changeToParentDirectory(); } else { InputStream srcStream = null; try { srcStream = src.toURI().toURL().openStream(); ftp.storeFile(src.getName(), srcStream); } finally { IOUtils.closeQuietly(srcStream); } } }
From source file:se.natusoft.maven.plugin.ftp.FTPMojo.java
/** * Executes the mojo./*from w w w .j a va 2 s . c om*/ * * @throws MojoExecutionException */ public void execute() throws MojoExecutionException { FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(this.targetHost, this.targetPort); if (!ftpClient.login(this.userName, this.password)) { throw new MojoExecutionException("Failed to login user '" + this.userName + "'!"); } this.getLog() .info("FTP: Connected to '" + this.targetHost + ":" + this.targetPort + "':" + this.targetPath); ftpClient.setFileTransferMode(FTP.COMPRESSED_TRANSFER_MODE); ftpClient.setBufferSize(1024 * 60); SourcePaths sourcePaths = new SourcePaths(new File(this.baseDir), this.files); this.getLog().info("Files to upload: " + sourcePaths.getSourceFiles().size()); int fileNo = 0; for (File transferFile : sourcePaths.getSourceFiles()) { String relPath = this.targetPath + transferFile.getParentFile().getAbsolutePath().substring(this.baseDir.length()); boolean havePath = ftpClient.changeWorkingDirectory(relPath); if (!havePath) { if (!mkdir(ftpClient, relPath)) { throw new MojoExecutionException("Failed to create directory '" + relPath + "'!"); } if (!ftpClient.changeWorkingDirectory(relPath)) { throw new MojoExecutionException( "Failed to change to '" + relPath + "' after its been created OK!"); } } FileInputStream sendFileStream = new FileInputStream(transferFile); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.storeFile(transferFile.getName(), sendFileStream); sendFileStream.close(); this.getLog().info( "Transferred [" + ++fileNo + "]: " + relPath + File.separator + transferFile.getName()); } this.getLog().info("All files transferred!"); } catch (IOException ioe) { throw new MojoExecutionException(ioe.getMessage(), ioe); } finally { try { ftpClient.disconnect(); } catch (IOException ioe) { this.getLog().error("Failed to disconnect from FTP site! [" + ioe.getMessage() + "]", ioe); } } }
From source file:se.natusoft.maven.plugin.ftp.FTPMojo.java
/** * Create a full path directory by creating one part at a time. * * @param ftpClient A connected FTPClient instance. * @param dir The directory to create.//from ww w . j a va 2 s . c om * * @return true on success. * * @throws IOException on failure. */ private boolean mkdir(FTPClient ftpClient, String dir) throws IOException { boolean result = true; for (String part : dir.split("/")) { if (!ftpClient.changeWorkingDirectory(part)) { result = ftpClient.makeDirectory(part); if (!result) return result; result = ftpClient.changeWorkingDirectory(part); if (!result) return result; } } return result; }
From source file:se.vgregion.webbisar.helpers.FileHandler.java
public void writeTempFile(String fileName, String sessionId, InputStream is) throws FTPException { FTPClient ftp = connect(); try {/* w w w .j a va 2 s . co m*/ ftp.makeDirectory("temp"); ftp.changeWorkingDirectory("temp"); ftp.makeDirectory(sessionId); ftp.changeWorkingDirectory(sessionId); ftp.storeFile(fileName, is); ftp.logout(); } catch (IOException e) { LOGGER.error("Could not write tempfile " + fileName, e); } finally { try { ftp.disconnect(); } catch (IOException e) { // Empty... } } }
From source file:srv.update.java
public void getVersao(View view) { String server = "ftp.atmatech.com.br"; int port = 21; String user = "atmatech"; String pass = "ftpp2015"; FTPClient ftpClient = new FTPClient(); try {/*from w w w .j av a 2 s .co m*/ ftpClient.connect(server, port); ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.changeWorkingDirectory("/atmatech.com.br/atualizacaosac/"); // APPROACH #1: using retrieveFile(String, OutputStream) String[] arq = ftpClient.listNames(); for (String f : arq) { if (!f.equals(".")) { if (!f.equals("..")) { if (f.contains(".")) { view.jLprogresso.setText(f); String remoteFile1 = "/atmatech.com.br/atualizacaosac/" + f; String destino = ".\\" + f; File downloadFile1 = new File(destino); OutputStream outputStream1 = new BufferedOutputStream( new FileOutputStream(downloadFile1)); boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1); outputStream1.close(); if (!success) { JOptionPane.showMessageDialog(null, "Erro Em Baixar Verso"); System.exit(0); } } else { ftpClient.changeWorkingDirectory("/atmatech.com.br/atualizacaosac/" + f); String[] arq2 = ftpClient.listNames(); for (String f2 : arq2) { if (!f2.equals(".")) { if (!f2.equals("..")) { view.jLprogresso.setText(f2); File diretorio = new File(".\\" + f); if (!diretorio.exists()) { diretorio.mkdirs(); //mkdir() cria somente um diretrio, mkdirs() cria diretrios e subdiretrios. } String remoteFile1 = "/atmatech.com.br/atualizacaosac/" + f + "/" + f2; String destino = ".\\" + f + "\\" + f2; File downloadFile1 = new File(destino); OutputStream outputStream1 = new BufferedOutputStream( new FileOutputStream(downloadFile1)); boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1); outputStream1.close(); if (!success) { JOptionPane.showMessageDialog(null, "Erro Em Baixar Verso"); System.exit(0); } } } } } } } } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Erro \n" + ex); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Erro \n" + ex); } } }
From source file:tufts.oki.dr.fedora.DR.java
public osid.shared.Id ingest(String fileName, String templateFileName, String fileType, File file, Properties properties) throws osid.dr.DigitalRepositoryException, java.net.SocketException, java.io.IOException, osid.shared.SharedException, javax.xml.rpc.ServiceException { long sTime = System.currentTimeMillis(); if (DEBUG)/* w w w .ja va 2 s .co m*/ System.out .println("INGESTING FILE TO FEDORA:fileName =" + fileName + "fileType =" + fileType + "t = 0"); // this part transfers file to a ftp server. this is required since the content management part of fedora server needs object to be on web server String host = FedoraUtils.getFedoraProperty(this, "admin.ftp.address"); String url = FedoraUtils.getFedoraProperty(this, "admin.ftp.url"); int port = Integer.parseInt(FedoraUtils.getFedoraProperty(this, "admin.ftp.port")); String userName = FedoraUtils.getFedoraProperty(this, "admin.ftp.username"); String password = FedoraUtils.getFedoraProperty(this, "admin.ftp.password"); String directory = FedoraUtils.getFedoraProperty(this, "admin.ftp.directory"); FTPClient client = new FTPClient(); client.connect(host, port); client.login(userName, password); client.changeWorkingDirectory(directory); client.setFileType(FTP.BINARY_FILE_TYPE); client.storeFile(fileName, new FileInputStream(file.getAbsolutePath().replaceAll("%20", " "))); client.logout(); client.disconnect(); if (DEBUG) System.out.println( "INGESTING FILE TO FEDORA: Writting to FTP Server:" + (System.currentTimeMillis() - sTime)); fileName = url + fileName; // this part does the creation of METSFile int BUFFER_SIZE = 10240; StringBuffer sb = new StringBuffer(); String s = new String(); BufferedInputStream fis = new BufferedInputStream( new FileInputStream(new File(getResource(templateFileName).getFile().replaceAll("%20", " ")))); //FileInputStream fis = new FileInputStream(new File(templateFileName)); //DataInputStream in = new DataInputStream(fis); byte[] buf = new byte[BUFFER_SIZE]; int ch; int len; while ((len = fis.read(buf)) > 0) { s = s + new String(buf); } fis.close(); if (DEBUG) System.out.println("INGESTING FILE TO FEDORA: Read Mets File:" + (System.currentTimeMillis() - sTime)); //in.close(); // s = sb.toString(); //String r = s.replaceAll("%file.location%", fileName).trim(); String r = updateMetadata(s, fileName, file.getName(), fileType, properties); if (DEBUG) System.out.println( "INGESTING FILE TO FEDORA: Resplaced Metadata:" + (System.currentTimeMillis() - sTime)); //writing the to outputfile File METSfile = File.createTempFile("vueMETSMap", ".xml"); FileOutputStream fos = new FileOutputStream(METSfile); fos.write(r.getBytes()); fos.close(); // AutoIngestor a = new AutoIngestor(address.getHost(), address.getPort(),FedoraUtils.getFedoraProperty(this,"admin.fedora.username"),FedoraUtils.getFedoraProperty(this,"admin.fedora.username")); //THIS WILL NOT WORK IN NEWER VERSION OF FEDORA // String pid = AutoIngestor.ingestAndCommit(new FileInputStream(METSfile),"foxml1.","Test Ingest"); if (DEBUG) System.out.println("INGESTING FILE TO FEDORA: Ingest complete:" + (System.currentTimeMillis() - sTime)); String pid = "Method Not Supported any more"; System.out.println(" METSfile= " + METSfile.getPath() + " PID = " + pid); return new PID(pid); }
From source file:ubicrypt.core.provider.ftp.FTProvider.java
private Observable<FTPClient> connect() { return Observable.<FTPClient>create(subscriber -> { final FTPClient client = new FTPClient(); try {// w w w. j av a 2 s . c o m client.connect(conf.getHost(), getConf().getPort() == -1 ? 21 : getConf().getPort()); final int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { log.error("FTP server refused connection:" + client.getReplyString()); if (client.isConnected()) { client.disconnect(); } subscriber.onError( new RuntimeException("FTP server refused connection:" + client.getReplyString())); return; } if (!getConf().isAnonymous()) { if (!client.login(getConf().getUsername(), new String(getConf().getPassword()))) { client.disconnect(); log.warn("FTP wrong credentials:" + client.getReplyString()); subscriber.onError(new RuntimeException("FTP wrong credentials")); } } client.setFileType(FTP.BINARY_FILE_TYPE); client.setBufferSize(1 << 64); client.enterLocalPassiveMode(); client.setControlKeepAliveTimeout(60 * 60); //1h if (!isEmpty(conf.getFolder())) { final String directory = startsWith("/", conf.getFolder()) ? conf.getFolder() : "/" + conf.getFolder(); if (!client.changeWorkingDirectory(directory)) { if (!client.makeDirectory(directory)) { disconnect(client); subscriber.onError(new ProviderException(showServerReply(client))); return; } if (!client.changeWorkingDirectory(directory)) { disconnect(client); subscriber.onError(new ProviderException(showServerReply(client))); return; } } } subscriber.onNext(client); subscriber.onCompleted(); } catch (final IOException e) { disconnect(client); subscriber.onError(e); } }).subscribeOn(Schedulers.io()); }
From source file:uk.ac.bbsrc.tgac.miso.core.util.TransmissionUtils.java
public static boolean ftpPut(FTPClient ftp, String path, List<File> files, boolean autoLogout, boolean autoMkdir) throws IOException { boolean error = false; FileInputStream fis = null;/*from ww w .ja v a 2 s . c o m*/ try { if (ftp == null || !ftp.isConnected()) { error = true; throw new IOException( "FTP client isn't connected. Please supply a client that has connected to the host."); } if (path != null) { if (autoMkdir) { if (!ftp.makeDirectory(path)) { error = true; throw new IOException("Cannot create desired path on the server."); } } if (!ftp.changeWorkingDirectory(path)) { error = true; throw new IOException("Desired path does not exist on the server"); } } log.info("All OK - transmitting " + files.size() + " file(s)"); for (File f : files) { fis = new FileInputStream(f); if (!ftp.storeFile(f.getName(), fis)) { error = true; log.error("Error storing file: " + f.getName()); } boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode()); if (!success) { error = true; log.error("Error storing file: " + f.getName() + " (" + success + ")"); } } if (autoLogout) { ftp.logout(); } } catch (IOException e) { error = true; log.error("ftp", e); } finally { try { if (fis != null) { fis.close(); } if (autoLogout) { if (ftp != null && ftp.isConnected()) { ftp.disconnect(); } } } catch (IOException ioe) { log.error("ftp", ioe); } } // return inverse error boolean, just to make downstream conditionals easier return !error; }
From source file:uk.ac.bbsrc.tgac.miso.core.util.TransmissionUtils.java
public static boolean ftpPutListen(FTPClient ftp, String path, File file, boolean autoLogout, boolean autoMkdir, CopyStreamListener listener) throws IOException { boolean error = false; FileInputStream fis = null;/*ww w . jav a 2 s. c o m*/ log.info("ftpPutListen has been called for file:" + file.getName()); try { if (ftp == null || !ftp.isConnected()) { error = true; throw new IOException( "FTP client isn't connected. Please supply a client that has connected to the host."); } if (path != null) { if (autoMkdir) { if (!ftp.makeDirectory(path)) { error = true; throw new IOException("Cannot create desired path on the server."); } } log.info("Working dir =" + ftp.printWorkingDirectory()); if (!ftp.changeWorkingDirectory(path)) { error = true; throw new IOException("Desired path does not exist on the server"); } } fis = new FileInputStream(file); OutputStream ops = new BufferedOutputStream(ftp.storeFileStream(file.getName()), ftp.getBufferSize()); log.info("TransmissionUtils putListen: FTP server responded: " + ftp.getReplyString()); copyStream(fis, ops, ftp.getBufferSize(), file.length(), listener); ops.close(); fis.close(); log.info("TransmissionUtils putListen: FTP server responded: " + ftp.getReplyString()); if (autoLogout) { ftp.logout(); } } catch (IOException e) { error = true; log.error("ftp put listen", e); } finally { try { log.info("TransmissionUtils putListen:finally: " + ftp.getReplyString()); if (fis != null) { fis.close(); } if (autoLogout) { if (ftp != null && ftp.isConnected()) { ftp.disconnect(); } } } catch (IOException ioe) { log.error("ftp put listen close", ioe); } } // return inverse error boolean, just to make downstream conditionals easier log.info("result of transmissionutils.putListen:", !error); return !error; }
From source file:websync2.SyncDesign.java
public void copyFileFTP(File temp, File servF) { InputStream inputStream = null; try {//from w ww .ja v a 2s. co m FTPClient ftpclient = ftp.getFtpClient(); ftpclient.changeToParentDirectory(); String firstRemoteFile = servF.getAbsolutePath(); String[] pathA = firstRemoteFile.split("/"); if (pathA != null) { for (int i = 0; i < pathA.length - 1; i++) { if ("".equals(pathA[i])) { continue; } InputStream is = ftpclient.retrieveFileStream(pathA[i]); int retCode = ftpclient.getReplyCode(); if (retCode == 550) { ftpclient.makeDirectory(pathA[i]); } ftpclient.changeWorkingDirectory(pathA[i]); } inputStream = new FileInputStream(temp); boolean done = ftpclient.storeFile(pathA[pathA.length - 1], inputStream); if (done) { System.out.println("The first file is uploaded successfully."); } } } catch (FileNotFoundException ex) { Logger.getLogger(SyncDesign.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(SyncDesign.class.getName()).log(Level.SEVERE, null, ex); } finally { try { inputStream.close(); } catch (IOException ex) { Logger.getLogger(SyncDesign.class.getName()).log(Level.SEVERE, null, ex); } } }