private void mkdirs(String path) throws Exception { // sftp.cd("/"); //change to the root dir // String dirs[] = splitPath(path); String cwd = sftp.pwd(); // System.out.println("CWD: " + cwd); while (!path.startsWith(cwd)) { System.out.println(cwd + " " + path); sftp.cd(".."); // should throw exception if can't cdup System.out.println("CDUP!"); cwd = sftp.pwd(); } String mkPath = path.substring(cwd.length(), path.length()); System.out.println("DIRS TO MAKE: " + mkPath); String dirs[] = splitPath(mkPath); for (int i = 0; i < dirs.length; i++) { System.out.println("mkdir " + dirs[i]); logger.info("mkdir " + dirs[i]); // swallow exception that results from trying to // make a dir that already exists try { sftp.mkdir(dirs[i]); } catch (Exception ex) { } // change to the new dir // throws an exception if something went wrong sftp.cd(dirs[i]); } }
/** Creates this file as a folder. */ public void createFolder(String foldername) throws KettleJobException { try { c.mkdir(foldername); } catch (SftpException e) { throw new KettleJobException(e); } }
private boolean buildDirectoryChunks(String dirName) throws IOException, SftpException { final StringBuilder sb = new StringBuilder(dirName.length()); final String[] dirs = dirName.split("/|\\\\"); boolean success = false; for (String dir : dirs) { sb.append(dir).append('/'); // must normalize the directory name String directory = endpoint.getConfiguration().normalizePath(sb.toString()); // do not try to build root folder (/ or \) if (!(directory.equals("/") || directory.equals("\\"))) { try { LOG.trace("Trying to build remote directory by chunk: {}", directory); channel.mkdir(directory); success = true; } catch (SftpException e) { // ignore keep trying to create the rest of the path } } } return success; }
private void mkdirs(String directory, ChannelSftp c) throws IOException, SftpException { try { SftpATTRS att = c.stat(directory); if (att != null) { if (att.isDir()) { return; } } } catch (SftpException ex) { if (directory.indexOf('/') != -1) { mkdirs(directory.substring(0, directory.lastIndexOf('/')), c); } c.mkdir(directory); } }
public boolean buildDirectory(String directory, boolean absolute) throws GenericFileOperationFailedException { // must normalize directory first directory = endpoint.getConfiguration().normalizePath(directory); LOG.trace("buildDirectory({},{})", directory, absolute); // ignore absolute as all dirs are relative with FTP boolean success = false; String originalDirectory = getCurrentDirectory(); try { // maybe the full directory already exists try { channel.cd(directory); success = true; } catch (SftpException e) { // ignore, we could not change directory so try to create it instead } if (!success) { LOG.debug("Trying to build remote directory: {}", directory); try { channel.mkdir(directory); success = true; } catch (SftpException e) { // we are here if the server side doesn't create intermediate folders // so create the folder one by one success = buildDirectoryChunks(directory); } } } catch (IOException e) { throw new GenericFileOperationFailedException("Cannot build directory: " + directory, e); } catch (SftpException e) { throw new GenericFileOperationFailedException("Cannot build directory: " + directory, e); } finally { // change back to original directory if (originalDirectory != null) { changeCurrentDirectory(originalDirectory); } } return success; }
// src原文件; dst 目标目录 public static void putDirectory(String src, String dst, ChannelSftp chSftp, String contain) throws SftpException { // 如果服务器目录不存在,需要创建目录 try { chSftp.cd(dst); } catch (SftpException sException) { // sException.printStackTrace(); if (ChannelSftp.SSH_FX_NO_SUCH_FILE == sException.id) { chSftp.mkdir(dst); } } // File file = new File(src); File[] dir = file.listFiles(); // file是文件 if (dir == null) { String f_type = getFileType(src); // 匹配上传文件类型 if (contain.indexOf(f_type) > -1) { System.out.println(src + " >>> " + dst); // 上传 // long fileSize = file.length(); // chSftp.put(src, dst, new FileProgressMonitor(fileSize), // ChannelSftp.OVERWRITE); chSftp.put(src, dst, ChannelSftp.OVERWRITE); } return; } // 目录 for (int i = 0; i < dir.length; i++) { File sub_file = dir[i]; File[] sub_dir = sub_file.listFiles(); // 文件 if (sub_dir == null) { putDirectory(sub_file.getPath(), dst, chSftp, contain); continue; } // 目录 需要取目录名 String sub_name = sub_file.getName(); putDirectory(src + sub_name + "\\", dst + sub_name + "/", chSftp, contain); // System.out.println("subDitr:"+subDir); } }
@Override public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException { if (!(dir instanceof SFTPPath)) { throw new IllegalArgumentException(dir.toString()); } SFTPHost sftpHost = (SFTPHost) dir.getFileSystem(); String username = sftpHost.getUserName(); String host = sftpHost.getHost(); int port = sftpHost.getPort(); Session session; try { session = jsch.getSession(username, host, port); UserInfo userinfo = new SFTPUserInfo(sftpHost.getPassword()); session.setUserInfo(userinfo); session.connect(); ChannelSftp sftp = (ChannelSftp) session.openChannel(SFTP); sftp.connect(); SFTPPath sftpPath = (SFTPPath) dir; String dirString = sftpPath.getPathString(); try { sftp.mkdir(dirString); } catch (SftpException e) { throw new IOException(dirString, e); } sftp.quit(); session.disconnect(); // throw new UnsupportedOperationException(); } catch (JSchException e) { throw new FileSystemException(e.getMessage()); } }
public static String loadFilesFromSFTP( String fileName, String localDirectory, String username, String password, String serverPath, int port) throws Exception { int i = 1; if (i == 1) throw new Exception(); try { String[] strArray = splitHostNameAndDirectory(serverPath); if (!((strArray[0].length() > 0) && (strArray[1].length() > 0))) { return "F+Invalid server path.+" + "Error Occurred in loadFilesFromSFTP(): " + errorMessage; } String strHost = strArray[0]; String strServerDirectory = strArray[1]; setProperties(strServerDirectory, localDirectory, username, password, strHost, port); boolean validConnection = getConnection(username, password, strHost, port); if (validConnection) { boolean isAccessible = goToServerDirectory(); if (isAccessible) { if (!isDirecotryExist(processedDirectory)) sftpChannel.mkdir(processedDirectory); getIVRSTrialList(); if (fileName.matches( "\\x2A\\x2E(([\\p{Alnum}]{3,4})|(\\x2A))")) // pattern for [*.txt] or [*.html] // // [*->42(Ox2A) and .->46(Ox2E)] { int dotPos = fileName.toLowerCase().lastIndexOf('.', fileName.length()); String fileType = fileName.toLowerCase().substring(dotPos, fileName.length()); downloadAllFiles(fileType); } else { totalFileCount = 1; downloadFileByName(fileName); } } disconnectFromSFTP(); errorMessageFurnishing(); if ((totalFileCount == 0) && (downloadedFileCount == 0)) { logMessage = "T+" + "Server has no files to download.+" + errorMessage; } else if (totalFileCount != downloadedFileCount) { logMessage = "T+" + downloadedFileCount + " file(s) downloaded out of " + totalFileCount + " files.+" + errorMessage; } else if (totalFileCount == downloadedFileCount) { logMessage = "T+Successfully " + downloadedFileCount + " file(s) downloaded.+" + errorMessage; } } else { logMessage = "F+Connection Error Occurred.+" + errorMessage; } return logMessage; } catch (Exception e) { disconnectFromSFTP(); System.out.println("Exception in loadFilesFromSFTP(): " + e.toString()); errorMessage += "Exception in loadFilesFromSFTP(): " + e.toString(); return "F+Error Occurred in loadFilesFromSFTP()+" + errorMessage; } }
/** * This method should only be run when a new version of the Manager will be released. It tries to * make the process more automatic. Currently: - Writes in the Version file in LOCAL DISK (Dropbox * folder, so Dropbox must be running!) - Uploads the file to the correct folder tree in the * SourceForge project, creating all needed folder on the way. */ public static void main(String[] args) throws ZipException, IOException, JSchException { /* * IMPORTANT * * Before releasing a new version of the Manager, please, follow these instructions: * 0 - Update the Changelog.txt and Version.txt files * 1 - Check if the older version is fully compatible with this one after an update. managerOptions.xml shall not be lost by any reasons. * 2 - Check if the file paths below are correct. * 3 - Clean and build the project, then Package-for-store the Manager.jar * 4 - Goto Sourceforge.net and update the LABEL and the OS supported for the new Manager file. * 5 - Update in the HoN forums page (changelog, topic title and version in first line) */ // First step is to get the version we want to release. String targetVersion = ManagerOptions.getInstance().getVersion(); // Get the old jar File oldJarVersion = new File( "C:\\Users\\Shirkit\\Dropbox\\HonModManager\\Dropbox\\Public\\versions\\Manager.jar"); // And the newly generated one File newJarVersion = new File("store\\Manager.jar"); // Target output for where the differences will be generated String verionsFile = "C:\\Users\\Shirkit\\Dropbox\\HonModManager\\Dropbox\\Public\\versions.txt"; File rootVersionsFolder = new File("C:\\Users\\Shirkit\\Dropbox\\HonModManager\\Dropbox\\Public\\versions\\"); File output = new File(rootVersionsFolder, targetVersion + ".jar"); System.out.println("Version to be released=" + targetVersion); System.out.println("Old version file=" + oldJarVersion.getAbsolutePath()); System.out.println("New version file=" + newJarVersion.getAbsolutePath()); System.out.println(); if (calculate(oldJarVersion, newJarVersion, output.getAbsolutePath())) { System.out.println( "Output file generated.\nPath=" + output.getAbsolutePath() + "\nSize=" + output.length() / 1024 + "KB"); // Read the current versions file and store it for later FileInputStream fis = new FileInputStream(verionsFile); ByteArrayOutputStream baos = new ByteArrayOutputStream(); copyInputStream(fis, baos); String s = baos.toString(); fis.close(); baos.close(); System.out.println(s); if (!s.trim().isEmpty()) { if (s.contains("\n")) { System.out.println("Older version=" + s.substring(0, s.indexOf("\n"))); } else { System.out.println("Older version=" + s); } s = targetVersion + "\n" + s; } else { System.out.println("First version!"); s = targetVersion; } if (JOptionPane.showConfirmDialog( null, "Confirm upload?", "Confirmation", JOptionPane.YES_NO_OPTION) != 0) { System.exit(0); } // Write new versions file with the new released version FileWriter fw = new FileWriter(verionsFile); fw.write(s); fw.flush(); fw.close(); System.out.println("Versions file written with sucess!"); fis = new FileInputStream(newJarVersion); FileOutputStream fos = new FileOutputStream(rootVersionsFolder + File.separator + "Manager.jar"); copyInputStream(fis, fos); fis.close(); fos.close(); System.out.println("Manager.jar file written!"); System.out.println(); } else { System.err.println("No differences file. Output file not generated."); System.exit(0); } JSch jsch = new JSch(); Session session = null; try { System.out.println("Connecting to SF"); session = jsch.getSession( JOptionPane.showInputDialog("SourceForge Username") + ",all-inhonmodman", "frs.sourceforge.net", 22); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(JOptionPane.showInputDialog("SourceForge Password")); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; System.out.println("Connected!"); String root = "/home/frs/project/a/al/all-inhonmodman"; sftpChannel.cd(root); StringTokenizer versionTokens = new StringTokenizer(targetVersion, " "); boolean flag = true; while (versionTokens.hasMoreTokens()) { String s = versionTokens.nextToken(); if (!cdExists(sftpChannel, s)) { sftpChannel.mkdir(s); flag = false; } sftpChannel.cd(s); } if (flag) { System.err.println("Version already exists!"); sftpChannel.exit(); session.disconnect(); System.exit(0); } System.out.println("Uploading file"); OutputStream out = sftpChannel.put("Manager.jar"); FileInputStream fis = new FileInputStream(newJarVersion); copyInputStream(fis, out); out.close(); fis.close(); System.out.println("Upload complete"); sftpChannel.exit(); session.disconnect(); System.out.println("SUCESS!"); } catch (JSchException e) { e.printStackTrace(); } catch (SftpException e) { e.printStackTrace(); } System.exit(0); }
@Test(groups = "spring") public void testMkDir() throws JSchException, SftpException { sftpChannel.mkdir("./moodir"); sftpChannel.cd("./moodir"); }