List of usage examples for org.apache.commons.net.ftp FTPClient storeFile
public boolean storeFile(String remote, InputStream local) throws IOException
From source file:com.ephesoft.dcma.util.FTPUtil.java
/** * API for uploading a directory on FTP server. Uploading any file requires uploading following a directory structure. * //from w w w . j a v a 2 s . c om * @param sourceDirectoryPath the directory to be uploaded * @param destDirName the path on ftp where directory will be uploaded * @param numberOfRetryCounter number of attempts to be made for uploading the directory * @throws FTPDataUploadException if an error occurs while uploading the file * @throws IOException if an error occurs while making the ftp connection * @throws SocketException if an error occurs while making the ftp connection */ public static void uploadDirectory(final FTPInformation ftpInformation, boolean deleteExistingFTPData) throws FTPDataUploadException, SocketException, IOException { boolean isValid = true; if (ftpInformation.getSourceDirectoryPath() == null) { isValid = false; LOGGER.error(VAR_SOURCE_DIR); throw new FTPDataUploadException(VAR_SOURCE_DIR); } if (ftpInformation.getDestDirName() == null) { isValid = false; LOGGER.error(VAR_SOURCE_DES); throw new FTPDataUploadException(VAR_SOURCE_DES); } if (isValid) { FTPClient client = new FTPClient(); String destDirName = ftpInformation.getDestDirName(); String destinationDirectory = ftpInformation.getUploadBaseDir(); if (destDirName != null && !destDirName.isEmpty()) { String uploadBaseDir = ftpInformation.getUploadBaseDir(); if (uploadBaseDir != null && !uploadBaseDir.isEmpty()) { destinationDirectory = EphesoftStringUtil.concatenate(uploadBaseDir, File.separator, destDirName); } else { destinationDirectory = destDirName; } } FileInputStream fis = null; try { createConnection(client, ftpInformation.getFtpServerURL(), ftpInformation.getFtpUsername(), ftpInformation.getFtpPassword(), ftpInformation.getFtpDataTimeOut()); int reply = client.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { LOGGER.info("Starting File Upload..."); } else { LOGGER.info("Invalid Connection to FTP server. Disconnecting Client"); client.disconnect(); isValid = false; throw new FTPDataUploadException("Invalid Connection to FTP server. Disconnecting Client"); } if (isValid) { // code changed for keeping the control connection busy. client.setControlKeepAliveTimeout(300); client.setFileType(FTP.BINARY_FILE_TYPE); createFtpDirectoryTree(client, destinationDirectory); // client.makeDirectory(destinationDirectory); if (deleteExistingFTPData) { deleteExistingFTPData(client, destinationDirectory, deleteExistingFTPData); } File file = new File(ftpInformation.getSourceDirectoryPath()); if (file.isDirectory()) { String[] fileList = file.list(); for (String fileName : fileList) { String inputFile = EphesoftStringUtil .concatenate(ftpInformation.getSourceDirectoryPath(), File.separator, fileName); File checkFile = new File(inputFile); if (checkFile.isFile()) { LOGGER.info(EphesoftStringUtil.concatenate("Transferring file :", fileName)); fis = new FileInputStream(inputFile); try { client.storeFile(fileName, fis); } catch (IOException e) { int retryCounter = ftpInformation.getNumberOfRetryCounter(); LOGGER.info(EphesoftStringUtil.concatenate("Retrying upload Attempt#-", (retryCounter + 1))); if (retryCounter < ftpInformation.getNumberOfRetries()) { retryCounter = retryCounter + 1; uploadDirectory(ftpInformation, deleteExistingFTPData); } else { LOGGER.error("Error in uploading the file to FTP server"); } } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { LOGGER.info(EphesoftStringUtil .concatenate("Could not close stream for file.", inputFile)); } } } } } } } catch (FileNotFoundException e) { LOGGER.error("File does not exist.."); } finally { try { client.disconnect(); } catch (IOException e) { LOGGER.error("Disconnecting from FTP server....", e); } } } }
From source file:com.cws.esolutions.core.utils.NetworkUtils.java
/** * Creates a connection to a target host and then executes an FTP * request to send or receive a file to or from the target. This is fully * key-based, as a result, a keyfile is required for the connection to * successfully authenticate.//from w ww . j a v a2 s.c om * * @param sourceFile - The full path to the source file to transfer * @param targetFile - The full path (including file name) of the desired target file * @param targetHost - The target server to perform the transfer to * @param isUpload - <code>true</code> is the transfer is an upload, <code>false</code> if it * is a download * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing */ public static final synchronized void executeFtpConnection(final String sourceFile, final String targetFile, final String targetHost, final boolean isUpload) throws UtilityException { final String methodName = NetworkUtils.CNAME + "#executeFtpConnection(final String sourceFile, final String targetFile, final String targetHost, final boolean isUpload) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", sourceFile); DEBUGGER.debug("Value: {}", targetFile); DEBUGGER.debug("Value: {}", targetHost); DEBUGGER.debug("Value: {}", isUpload); } final FTPClient client = new FTPClient(); final FTPConfig ftpConfig = appBean.getConfigData().getFtpConfig(); if (DEBUG) { DEBUGGER.debug("FTPClient: {}", client); DEBUGGER.debug("FTPConfig: {}", ftpConfig); } try { client.connect(targetHost); if (DEBUG) { DEBUGGER.debug("FTPClient: {}", client); } if (!(client.isConnected())) { throw new IOException("Failed to authenticate to remote host with the provided information"); } boolean isAuthenticated = false; if (StringUtils.isNotBlank(ftpConfig.getFtpAccount())) { isAuthenticated = client.login( (StringUtils.isNotEmpty(ftpConfig.getFtpAccount())) ? ftpConfig.getFtpAccount() : System.getProperty("user.name"), PasswordUtils.decryptText(ftpConfig.getFtpPassword(), ftpConfig.getFtpSalt(), secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(), secBean.getConfigData().getSecurityConfig().getIterations(), secBean.getConfigData().getSecurityConfig().getKeyBits(), secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(), secBean.getConfigData().getSecurityConfig().getEncryptionInstance(), appBean.getConfigData().getSystemConfig().getEncoding())); } else { isAuthenticated = client.login(ftpConfig.getFtpAccount(), null); } if (DEBUG) { DEBUGGER.debug("isAuthenticated: {}", isAuthenticated); } if (!(isAuthenticated)) { throw new IOException("Failed to connect to FTP server: " + targetHost); } client.enterLocalPassiveMode(); if (!(FileUtils.getFile(sourceFile).exists())) { throw new IOException("File " + sourceFile + " does not exist. Skipping"); } if (isUpload) { client.storeFile(targetFile, new FileInputStream(FileUtils.getFile(sourceFile))); } else { client.retrieveFile(sourceFile, new FileOutputStream(targetFile)); } if (DEBUG) { DEBUGGER.debug("Reply: {}", client.getReplyCode()); DEBUGGER.debug("Reply: {}", client.getReplyString()); } } catch (IOException iox) { throw new UtilityException(iox.getMessage(), iox); } finally { try { if (client.isConnected()) { client.completePendingCommand(); client.disconnect(); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } }
From source file:madkitgroupextension.export.Export.java
public static void updateFTP(FTPClient ftpClient, String _directory_dst, File _directory_src, File _current_file_transfert) throws IOException, TransfertException { ftpClient.changeWorkingDirectory("./"); FTPListParseEngine ftplpe = ftpClient.initiateListParsing(_directory_dst); FTPFile files[] = ftplpe.getFiles(); File current_file_transfert = _current_file_transfert; try {/*from w w w . jav a 2 s. c om*/ for (File f : _directory_src.listFiles()) { if (f.isDirectory()) { if (!f.getName().equals("./") && !f.getName().equals("../")) { if (_current_file_transfert != null) { if (!_current_file_transfert.getCanonicalPath().startsWith(f.getCanonicalPath())) continue; else _current_file_transfert = null; } boolean found = false; for (FTPFile ff : files) { if (f.getName().equals(ff.getName())) { if (ff.isFile()) { ftpClient.deleteFile(_directory_dst + ff.getName()); } else found = true; break; } } if (!found) { ftpClient.changeWorkingDirectory("./"); if (!ftpClient.makeDirectory(_directory_dst + f.getName() + "/")) System.err.println( "Impossible to create directory " + _directory_dst + f.getName() + "/"); } updateFTP(ftpClient, _directory_dst + f.getName() + "/", f, _current_file_transfert); } } else { if (_current_file_transfert != null) { if (!_current_file_transfert.equals(f.getCanonicalPath())) continue; else _current_file_transfert = null; } current_file_transfert = _current_file_transfert; FTPFile found = null; for (FTPFile ff : files) { if (f.getName().equals(ff.getName())) { if (ff.isDirectory()) { FileTools.removeDirectory(ftpClient, _directory_dst + ff.getName()); } else found = ff; break; } } if (found == null || (found.getTimestamp().getTimeInMillis() - f.lastModified()) < 0 || found.getSize() != f.length()) { FileInputStream fis = new FileInputStream(f); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!ftpClient.storeFile(_directory_dst + f.getName(), fis)) System.err.println("Impossible to send file: " + _directory_dst + f.getName()); fis.close(); for (FTPFile ff : ftplpe.getFiles()) { if (f.getName().equals(ff.getName())) { f.setLastModified(ff.getTimestamp().getTimeInMillis()); break; } } } } } } catch (IOException e) { throw new TransfertException(current_file_transfert, null, e); } for (FTPFile ff : files) { if (!ff.getName().equals(".") && !ff.getName().equals("..")) { boolean found = false; for (File f : _directory_src.listFiles()) { if (f.getName().equals(ff.getName()) && f.isDirectory() == ff.isDirectory()) { found = true; break; } } if (!found) { if (ff.isDirectory()) { FileTools.removeDirectory(ftpClient, _directory_dst + ff.getName()); } else { ftpClient.deleteFile(_directory_dst + ff.getName()); } } } } }
From source file:jenkins.plugins.publish_over_ftp.jenkins.IntegrationTest.java
@Test public void testIntegration() throws Exception { final FTPClient mockFTPClient = mock(FTPClient.class); final int port = 21; final int timeout = 3000; final BapFtpHostConfiguration testHostConfig = new BapFtpHostConfiguration("testConfig", "testHostname", "testUsername", TEST_PASSWORD, "/testRemoteRoot", port, timeout, false, null, false, false) { @Override//w w w . ja v a 2 s .c o m public FTPClient createFTPClient() { return mockFTPClient; } }; new JenkinsTestHelper().setGlobalConfig(testHostConfig); final String dirToIgnore = "target"; final BapFtpTransfer transfer = new BapFtpTransfer("**/*", null, "sub-home", dirToIgnore, true, false, false, false, false, false, null); final ArrayList transfers = new ArrayList(Collections.singletonList(transfer)); final BapFtpPublisher publisher = new BapFtpPublisher(testHostConfig.getName(), false, transfers, false, false, null, null, null); final ArrayList publishers = new ArrayList(Collections.singletonList(publisher)); final BapFtpPublisherPlugin plugin = new BapFtpPublisherPlugin(publishers, false, false, false, "master", null); final FreeStyleProject project = createFreeStyleProject(); project.getPublishersList().add(plugin); final String buildDirectory = "build-dir"; final String buildFileName = "file.txt"; project.getBuildersList().add(new TestBuilder() { @Override public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { final FilePath dir = build.getWorkspace().child(dirToIgnore).child(buildDirectory); dir.mkdirs(); dir.child(buildFileName).write("Helloooooo", "UTF-8"); build.setResult(Result.SUCCESS); return true; } }); when(mockFTPClient.getReplyCode()).thenReturn(FTPReply.SERVICE_READY); when(mockFTPClient.login(testHostConfig.getUsername(), TEST_PASSWORD)).thenReturn(true); when(mockFTPClient.changeWorkingDirectory(testHostConfig.getRemoteRootDir())).thenReturn(true); when(mockFTPClient.setFileType(FTPClient.ASCII_FILE_TYPE)).thenReturn(true); when(mockFTPClient.changeWorkingDirectory(transfer.getRemoteDirectory())).thenReturn(false) .thenReturn(true); when(mockFTPClient.makeDirectory(transfer.getRemoteDirectory())).thenReturn(true); when(mockFTPClient.changeWorkingDirectory(buildDirectory)).thenReturn(false).thenReturn(true); when(mockFTPClient.makeDirectory(buildDirectory)).thenReturn(true); when(mockFTPClient.storeFile(eq(buildFileName), (InputStream) anyObject())).thenReturn(true); assertBuildStatusSuccess(project.scheduleBuild2(0).get()); verify(mockFTPClient).connect(testHostConfig.getHostname(), testHostConfig.getPort()); verify(mockFTPClient).storeFile(eq(buildFileName), (InputStream) anyObject()); verify(mockFTPClient).setDefaultTimeout(testHostConfig.getTimeout()); verify(mockFTPClient).setDataTimeout(testHostConfig.getTimeout()); }
From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java
/** * auto find the time difference between local and remote * @param ftp handle to ftp client//w w w. j a v a 2 s . co m * @return number of millis to add to remote time to make it comparable to local time * @since ant 1.6 */ private long getTimeDiff(FTPClient ftp) { long returnValue = 0; File tempFile = findFileName(ftp); try { // create a local temporary file FILE_UTILS.createNewFile(tempFile); long localTimeStamp = tempFile.lastModified(); BufferedInputStream instream = new BufferedInputStream(new FileInputStream(tempFile)); ftp.storeFile(tempFile.getName(), instream); instream.close(); boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode()); if (success) { FTPFile[] ftpFiles = ftp.listFiles(tempFile.getName()); if (ftpFiles.length == 1) { long remoteTimeStamp = ftpFiles[0].getTimestamp().getTime().getTime(); returnValue = localTimeStamp - remoteTimeStamp; } ftp.deleteFile(ftpFiles[0].getName()); } // delegate the deletion of the local temp file to the delete task // because of race conditions occuring on Windows Delete mydelete = new Delete(); mydelete.bindToOwner(this); mydelete.setFile(tempFile.getCanonicalFile()); mydelete.execute(); } catch (Exception e) { throw new BuildException(e, getLocation()); } return returnValue; }
From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java
/** * Sends a single file to the remote host. <code>filename</code> may * contain a relative path specification. When this is the case, <code>sendFile</code> * will attempt to create any necessary parent directories before sending * the file. The file will then be sent using the entire relative path * spec - no attempt is made to change directories. It is anticipated that * this may eventually cause problems with some FTP servers, but it * simplifies the coding.//from w w w.ja v a 2 s . co m * @param ftp ftp client * @param dir base directory of the file to be sent (local) * @param filename relative path of the file to be send * locally relative to dir * remotely relative to the remotedir attribute * @throws IOException in unknown circumstances * @throws BuildException in unknown circumstances */ protected void sendFile(FTPClient ftp, String dir, String filename) throws IOException, BuildException { InputStream instream = null; try { // XXX - why not simply new File(dir, filename)? File file = getProject().resolveFile(new File(dir, filename).getPath()); if (newerOnly && isUpToDate(ftp, file, resolveFile(filename))) { return; } if (verbose) { log("transferring " + file.getAbsolutePath()); } instream = new BufferedInputStream(new FileInputStream(file)); createParents(ftp, filename); ftp.storeFile(resolveFile(filename), instream); boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode()); if (!success) { String s = "could not put file: " + ftp.getReplyString(); if (skipFailedTransfers) { log(s, Project.MSG_WARN); skipped++; } else { throw new BuildException(s); } } else { // see if we should issue a chmod command if (chmod != null) { doSiteCommand(ftp, "chmod " + chmod + " " + resolveFile(filename)); } log("File " + file.getAbsolutePath() + " copied to " + server, Project.MSG_VERBOSE); transferred++; } } finally { FileUtils.close(instream); } }
From source file:com.microsoft.intellij.forms.CreateWebSiteForm.java
private void copyWebConfigForCustom(WebSiteConfiguration config) throws AzureCmdException { if (config != null) { AzureManager manager = AzureManagerImpl.getManager(project); WebSitePublishSettings webSitePublishSettings = manager.getWebSitePublishSettings( config.getSubscriptionId(), config.getWebSpaceName(), config.getWebSiteName()); // retrieve ftp publish profile WebSitePublishSettings.FTPPublishProfile ftpProfile = null; for (WebSitePublishSettings.PublishProfile pp : webSitePublishSettings.getPublishProfileList()) { if (pp instanceof WebSitePublishSettings.FTPPublishProfile) { ftpProfile = (WebSitePublishSettings.FTPPublishProfile) pp; break; }/*from www. j a v a 2 s. c o m*/ } if (ftpProfile != null) { FTPClient ftp = new FTPClient(); try { URI uri = null; uri = new URI(ftpProfile.getPublishUrl()); ftp.connect(uri.getHost()); final int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); } if (!ftp.login(ftpProfile.getUserName(), ftpProfile.getPassword())) { ftp.logout(); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (ftpProfile.isFtpPassiveMode()) { ftp.enterLocalPassiveMode(); } ftp.deleteFile(ftpPath + message("configName")); String tmpPath = String.format("%s%s%s", System.getProperty("java.io.tmpdir"), File.separator, message("configName")); File file = new File(tmpPath); if (file.exists()) { file.delete(); } WAEclipseHelperMethods.copyFile(WAHelper.getCustomJdkFile(message("configName")), tmpPath); String jdkFolderName = ""; if (customJDKUser.isSelected()) { String url = customUrl.getText(); jdkFolderName = url.substring(url.lastIndexOf("/") + 1, url.length()); jdkFolderName = jdkFolderName.substring(0, jdkFolderName.indexOf(".zip")); } else { String cloudVal = WindowsAzureProjectManager .getCloudValue((String) jdkNames.getSelectedItem(), AzurePlugin.cmpntFile); jdkFolderName = cloudVal.substring(cloudVal.indexOf("\\") + 1, cloudVal.length()); } String jdkPath = "%HOME%\\site\\wwwroot\\jdk\\" + jdkFolderName; String serverPath = "%programfiles(x86)%\\" + WAHelper .generateServerFolderName(config.getJavaContainer(), config.getJavaContainerVersion()); WebAppConfigOperations.prepareWebConfigForCustomJDKServer(tmpPath, jdkPath, serverPath); InputStream input = new FileInputStream(tmpPath); ftp.storeFile(ftpPath + message("configName"), input); cleanup(ftp); ftp.logout(); } catch (Exception e) { AzurePlugin.log(e.getMessage(), e); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ignored) { } } } } } }
From source file:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java
@Override public void publishWebArchiveArtifact(@NotNull String subscriptionId, @NotNull String webSpaceName, @NotNull String webSiteName, @NotNull String artifactPath, @NotNull boolean isDeployRoot, @NotNull String artifactName) throws AzureCmdException { WebSitePublishSettings webSitePublishSettings = getWebSitePublishSettings(subscriptionId, webSpaceName, webSiteName);/*from w w w . j av a 2 s . co m*/ WebSitePublishSettings.FTPPublishProfile publishProfile = null; for (PublishProfile pp : webSitePublishSettings.getPublishProfileList()) { if (pp instanceof FTPPublishProfile) { publishProfile = (FTPPublishProfile) pp; break; } } if (publishProfile == null) { throw new AzureCmdException("Unable to retrieve FTP credentials to publish web site"); } URI uri; try { uri = new URI(publishProfile.getPublishUrl()); } catch (URISyntaxException e) { throw new AzureCmdException("Unable to parse FTP Publish Url information", e); } final FTPClient ftp = new FTPClient(); try { ftp.connect(uri.getHost()); final int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); throw new AzureCmdException("Unable to connect to FTP server"); } if (!ftp.login(publishProfile.getUserName(), publishProfile.getPassword())) { ftp.logout(); throw new AzureCmdException("Unable to login to FTP server"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (publishProfile.isFtpPassiveMode()) { ftp.enterLocalPassiveMode(); } String targetDir = getAbsolutePath(uri.getPath()); targetDir += "/webapps"; InputStream input = new FileInputStream(artifactPath); if (isDeployRoot) { ftp.storeFile(targetDir + "/ROOT.war", input); } else { ftp.storeFile(targetDir + "/" + artifactName + ".war", input); } input.close(); ftp.logout(); } catch (IOException e) { throw new AzureCmdException("Unable to connect to the FTP server", e); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ignored) { } } } }
From source file:com.claim.controller.FileTransferController.java
public boolean uploadMutiFilesWithFTP(ObjFileTransfer ftpObj) throws Exception { FTPClient ftpClient = new FTPClient(); int replyCode; boolean completed = false; try {/* w w w. java 2 s . c o m*/ FtpProperties properties = new ResourcesProperties().loadFTPProperties(); try { ftpClient.connect(properties.getFtp_server(), properties.getFtp_port()); FtpUtil.showServerReply(ftpClient); } catch (ConnectException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("ConnectException: " + ex.getMessage()); ex.printStackTrace(); } catch (SocketException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("SocketException: " + ex.getMessage()); ex.printStackTrace(); } catch (UnknownHostException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("UnknownHostException: " + ex.getMessage()); ex.printStackTrace(); } replyCode = ftpClient.getReplyCode(); FtpUtil.showServerReply(ftpClient); if (!FTPReply.isPositiveCompletion(replyCode)) { FtpUtil.showServerReply(ftpClient); ftpClient.disconnect(); Console.LOG("Exception in connecting to FTP Serve ", 0); throw new Exception("Exception in connecting to FTP Server"); } else { FtpUtil.showServerReply(ftpClient); Console.LOG("Success in connecting to FTP Serve ", 1); } try { boolean success = ftpClient.login(properties.getFtp_username(), properties.getFtp_password()); FtpUtil.showServerReply(ftpClient); if (!success) { throw new Exception("Could not login to the FTP server."); } else { Console.LOG("login to the FTP server. Successfully ", 1); } //ftpClient.enterLocalPassiveMode(); } catch (FTPConnectionClosedException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory(); // APPROACH #2: uploads second file using an OutputStream File files = new File(ftpObj.getFtp_directory_path()); String workingDirectoryReportType = properties.getFtp_remote_directory() + File.separator + ftpObj.getFtp_report_type(); FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryReportType); FtpUtil.showServerReply(ftpClient); String workingDirectoryStmp = workingDirectoryReportType + File.separator + ftpObj.getFtp_stmp(); FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryStmp); FtpUtil.showServerReply(ftpClient); for (File file : files.listFiles()) { if (file.isFile()) { System.out.println("file ::" + file.getName()); InputStream in = new FileInputStream(file); ftpClient.changeWorkingDirectory(workingDirectoryStmp); completed = ftpClient.storeFile(file.getName(), in); in.close(); Console.LOG( " " + file.getName() + " ", 1); FtpUtil.showServerReply(ftpClient); } } Console.LOG(" ?... ", 1); //completed = ftpClient.completePendingCommand(); FtpUtil.showServerReply(ftpClient); completed = true; ftpClient.disconnect(); } catch (IOException ex) { Console.LOG(ex.getMessage(), 0); FtpUtil.showServerReply(ftpClient); System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { FtpUtil.showServerReply(ftpClient); Console.LOG(ex.getMessage(), 0); ex.printStackTrace(); } } return completed; }
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 {/*from w ww.ja va2s . c o 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(); } }