SftpUtils
package com.msc.tourop.util;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;
import java.util.Vector;
import org.apache.log4j.Logger;
import com.estar.tourop.utils.TextUtil;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.msc.tourop.action.manifest.FlightManifestAction;
import com.msc.tourop.common.TourOpConstants;
import com.msc.tourop.servlet.TourOpConfigServlet;
public class SftpUtils {
static final Logger logger = Logger.getLogger(SftpUtils.class);
TextUtil textGuy = new TextUtil();
static Date d1 ;
/**
* Get the connection to ftp2
* @return
*/
public static ChannelSftp getSFTPConnection() throws Exception{
TextUtil textGuy = new TextUtil();
String ftpHost = "";// hostname
int ftpPort =22;
String ftpUserName ="";//username
String ftpPassword ="";//password
/*if(TourOpConfigServlet.getComputerName().equals(TourOpConstants.PROD_BOX_NAME) || TourOpConfigServlet.getComputerName().equals(TourOpConstants.STAGE_BOX_NAME)){
ftpHost = "";// hostname
ftpUserName ="";//username
ftpPassword ="";//password
} else if (TourOpConfigServlet.getComputerName().equals(TourOpConstants.TEST_BOX_NAME)) {
ftpHost = "sftp.suncountry.com";// hostname
ftpUserName ="jreddy";//username //jreddy
ftpPassword ="proof-told";//password //proof-told
} else {*/
ftpHost = "sftp.suncountry.com";// hostname
ftpUserName ="touropmantest";//username //jreddy
ftpPassword ="test1ngM@n";//password //proof-told
//}
displayLogs("Creating session.");
ChannelSftp channelsftp= null;
try {
JSch jsch = new JSch();
Session session = null;
Channel channel = null;
// Create a session sending through our username and password
session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
displayLogs("Session created."+new Timestamp(new java.util.Date().getTime()));
session.setPassword(ftpPassword);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
//session.setTimeout(20000);
session.connect();
displayLogs("Session connected.");
//
// Open the SFTP channel
//
displayLogs("Opening Channel.");
channel = session.openChannel("sftp");
channel.connect();
channelsftp = (ChannelSftp)channel;
} catch (Exception exc) {
exc.printStackTrace();
System.err.println("Unable to disconnect from FTP server. " + exc.toString());
textGuy.createMessage("getSFTPConnection", exc);
}
return channelsftp;
}
/**
* Getting the list of file from sftp by passing sftp path
*/
public List getFilesListFromSftpPath(ChannelSftp channel,String mainFestFilePath)throws Exception{
displayLogs(" getFilesListFromSftpPath started at :"+new Timestamp( new java.util.Date().getTime()));
List filesList = new Vector();
try {
System.out.println("mainFestFilePath:"+mainFestFilePath);
channel.cd(mainFestFilePath);
filesList = channel.ls(mainFestFilePath);
System.out.println(""+filesList.toString());
} catch (SftpException e) {
e.printStackTrace();
textGuy.createMessage("getSFTPConnection", e);
throw new Exception("Unable to download.");
} finally {
displayLogs("Channel closed for downloaded :"+new Timestamp(new java.util.Date().getTime()));
// if(channel != null) clearSftpConnection(channel);
}
displayLogs(" getFilesListFromSftpPath ended at :"+new Timestamp( new java.util.Date().getTime()));
return filesList;
}
/**
* Downloading the files from ftp2 to local path
* @param c
* @param despath
* @param sourcepath
*/
public static void download(ChannelSftp c ,String despath, String sourcepath,String fileName)throws Exception{
displayLogs(" download started at :"+new Timestamp( new java.util.Date().getTime()));
TextUtil textGuy = new TextUtil();
try {
displayLogs("despath :"+despath+" ,sourcepath:"+sourcepath);
// Change to the remote directory
c.cd(despath);
// Get the list of files in the remote server directory
Vector files = c.ls(despath);
displayLogs("files :"+despath+" ,sourcepath:"+sourcepath);
// Log if we have nothing to download
if (files.size() == 0) {
displayLogs("No files are available for download.");
} else {
File createDir = new File(sourcepath);
if (!createDir.exists()) {
createDir.mkdir();
}
for (int i = 0; i < files.size(); i++) {
com.jcraft.jsch.ChannelSftp.LsEntry lsEntry = (com.jcraft.jsch.ChannelSftp.LsEntry) files.get(i);
// displayLogs("lsEntry.getAttrs().getMtimeString() ::"+lsEntry.getAttrs().isDir()+"----"+lsEntry.getFilename()+"----------"+lsEntry.getAttrs().getSize()/1024);
if (!lsEntry.getFilename().equals(".")
&& !lsEntry.getFilename().equals("..")
&& lsEntry.getFilename().equals(fileName)) {// for
// Directory
if (lsEntry.getAttrs().isDir()) {
String output = sourcepath+lsEntry.getFilename();
File f = new File(output);
f.mkdir();
download(c,despath+lsEntry.getFilename()+"/",sourcepath+lsEntry.getFilename()+"/",fileName);
} else { //for file
c.cd(despath);
String outputFileName = sourcepath+ lsEntry.getFilename();
File f = new File(outputFileName);
f.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(f);
c.get(lsEntry.getFilename(), fileOutputStream);
//displayLogs("Downloaded file :"+lsEntry.getFilename());
fileOutputStream.close();
}
}
}
}
} catch (Exception e){
displayLogs("Exception :While Downloading the files to lacal path :"+e.getMessage());
e.printStackTrace();
textGuy.createMessage("download : ", e);
throw new Exception("Unable to download the file from sftp.");
}
displayLogs(" download ended at :"+new Timestamp( new java.util.Date().getTime()));
}
public static void upload(ChannelSftp c ,String destuploadpath, String destdeletepath,String sourcepath)throws Exception{
displayLogs(" upload started at :"+new Timestamp( new java.util.Date().getTime()));
TextUtil textGuy = new TextUtil();
try{
c.cd(destuploadpath);
File f = new File(sourcepath);
c.put(sourcepath, destuploadpath);
displayLogs("uploaded file :"+f.getName());
c.rm(destdeletepath);
f.delete(); // deleting the loacl files
//displayLogs("Deleted file :"+f.getName());
} catch (Exception e){
e.printStackTrace();
textGuy.createMessage("upload : ", e);
throw new Exception("Unable to upload the file to ftp.");
} finally {
displayLogs("Channel closed for uploaded :"+new Timestamp(new java.util.Date().getTime()));
// if(c != null) clearSftpConnection(c);
}
displayLogs(" upload ended at :"+new Timestamp( new java.util.Date().getTime()));
}
public static void rename(ChannelSftp c ,String destuploadpath,String oldfilename,String newfilename)throws Exception{
displayLogs(" rename started at :"+new Timestamp( new java.util.Date().getTime()));
List filesList = null;
SftpUtils sftpUtils = new SftpUtils();
boolean checkStatus = false;
try{
c.cd(destuploadpath);
filesList = sftpUtils.getFilesListFromSftpPath(c, destuploadpath);
if( filesList != null)
for (int x = 0; x < filesList.size(); x++) {
com.jcraft.jsch.ChannelSftp.LsEntry lsEntry = (com.jcraft.jsch.ChannelSftp.LsEntry) filesList.get(x);
if (lsEntry.getFilename().equals(newfilename)) {
c.rm(newfilename);
c.rename(oldfilename,newfilename);
checkStatus = true;
}
}
if(!checkStatus)
c.rename(oldfilename,newfilename);
} catch (Exception e){
e.printStackTrace();
throw new Exception("Unable to rename the file.");
} finally {
displayLogs("Channel closed for uploaded :"+new Timestamp(new java.util.Date().getTime()));
// if (c != null) clearSftpConnection(c);
}
displayLogs(" rename ended at :"+new Timestamp( new java.util.Date().getTime()));
}
public static void clearSftpConnection(ChannelSftp channel ){
try{
//if (channel != null && channel.getSession() != null )channel.getSession().disconnect();
displayLogs(" clearSftpConnection started at :"+new Timestamp( new java.util.Date().getTime()));
if (channel != null )channel.quit();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
TextUtil textGuy = new TextUtil();
SftpUtils sftputils = new SftpUtils();
ChannelSftp channel = null;
try {
System.out.println("Testing for return flights file .........");
channel = sftputils.getSFTPConnection();
sftputils.getFilesListFromSftpPath(channel,"/touropmanifests/");
} catch (Exception e) {
e.printStackTrace();
textGuy.createMessage("download : ", e);
} finally {
clearSftpConnection(channel);
}
}
static void displayLogs(String message) {
logger.info(message);
System.out.println(message);
}
}
Comments
Post a Comment