CreatingImages&METAFileAndPushingToSFTPorFTP

config.properties
----------------------
# Folder location where images exists
ReceiptsRootFolder=C:/Users/sivaleti/Pictures/10122019
#ExpenseReportNumber to Which Images in the ReceiptsFolder Will Add as Receipts
DocumentNumbers=N001000111112040002
# 1 for SFTP 2 for FTP
protocaltype = 2
# SFTP/FTP HostName
hostname=10.140.1.122
#sftp01.
# SFTP/FTP Host Username
username=lowesftpuser
#input
#SFTP/FTP Host Password
password=password
#sreehari

AddImagesToReports.java
---------------------------------

package com.hari.test;

import java.util.List;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;

import javax.imageio.ImageIO;

import com.ftp.FTPUploaderImpl;
import com.sftp.SFTPUploaderImpl;
import com.sftp.interf.SFTPUploader;

public class AddImagesToReports {

public void addImages(String arg) throws Exception {

InputStream inputStream = null;

String configFileName = arg;
Properties prop = new Properties();
//configFileName = "config.properties";

List<String> filenamesForFtp = new ArrayList<String>();

inputStream = getClass().getClassLoader().getResourceAsStream(configFileName);

if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + configFileName + "' not found in the classpath");
}

String documentNumbers = prop.getProperty("DocumentNumbers");
String directoryName = prop.getProperty("ReceiptsRootFolder");
String protocaltype = prop.getProperty("protocaltype").trim();
String hostname = prop.getProperty("hostname").trim();
String username = prop.getProperty("username");
String password = prop.getProperty("password");

String generatedFileDir = "FTP1";
File outputDirFile = new File("Tmp"); // it needed to generate the temp file name

if (!new File(directoryName).exists()) {
System.out.println("Source Folder " + directoryName + " Not Exists. Terminating Program");
return;
}

if (!outputDirFile.exists()) {
outputDirFile.mkdir();
}

// System.out.println("Destination Folder " + generatedFileDir + " Not Exists.
// Terminating Program");
File tmp1 = new File(generatedFileDir);
tmp1.mkdir();
generatedFileDir = tmp1.getAbsolutePath();
//System.out.println(generatedFileDir);

SFTPUploader impl = null;
if (1 == Integer.parseInt(protocaltype))
impl = new SFTPUploaderImpl();

if (2 == Integer.parseInt(protocaltype))
impl = new FTPUploaderImpl();

String[] documentNumArray = documentNumbers.split(",");
File folder = new File(directoryName);

File[] listOfFiles = folder.listFiles();
int reportidindex = 0;

for (int i = 0; i < listOfFiles.length; i++) {
try {
String fileExtension = getFileExtension(listOfFiles[i]);
if (fileExtension.length() > 3 || fileExtension.equalsIgnoreCase("svg"))
continue;
String documentNumber = documentNumArray[reportidindex++];
// System.out.println(documentNumber);
if (reportidindex == documentNumArray.length)
reportidindex = 0;
String barcode = documentNumber;
File outputTiffFile = File.createTempFile(documentNumber + '_', "." + fileExtension, outputDirFile);
String tifFilename = outputTiffFile.getName();
String rootFilename = tifFilename.substring(0, tifFilename.length() - 4);
outputTiffFile.delete();
// System.out.println(rootFilename);
// System.out.println(listOfFiles[i].getName());

File imagefile = new File(listOfFiles[i].getAbsolutePath());

BufferedImage image = null;

image = ImageIO.read(imagefile);

ImageIO.write(image, fileExtension, new File(generatedFileDir + "/" + tifFilename));

String xmlFilename = rootFilename + ".xml";
File xmlFile = new File(generatedFileDir, xmlFilename);

generateXml(xmlFile, documentNumber, barcode);

filenamesForFtp.add(tifFilename);
filenamesForFtp.add(xmlFilename);

impl.uploadFiles(filenamesForFtp, generatedFileDir, hostname,username,
password);

} catch (Exception e) {
// System.out.println("failed for image "+ listOfFiles[i].getAbsolutePath() );
e.printStackTrace();
// System.out.println(e);
}

}

inputStream.close();
removeFiles(filenamesForFtp, generatedFileDir);

outputDirFile.delete();
new File(generatedFileDir).delete();
}

public static void main(String[] args) {
try {
System.out.println("Program Started to add receipts to given document numbers");
new AddImagesToReports().addImages("config.properties");
System.out.println("Program ended");
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}

private static String getFileExtension(File file) {
String fileName = file.getName();
if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
return fileName.substring(fileName.lastIndexOf(".") + 1);
else
return "";
}

private static void generateXml(File xmlFile, String documentNumber, String barcode) {

String drawer = "Cybershift Test";
String username = "cybershifttest";
try {
KwikTagUpload.createXmlFile(xmlFile, documentNumber, barcode, drawer, username, null);
} catch (Exception e) {

System.out.println("Exception while generating " + xmlFile);
}

}

protected void removeFiles(List<String> filenames, String dir) {
for (String filename : filenames) {
try {
File file = new File(dir, filename);
if (file.exists() && file.isFile()) {
file.delete();
}
} catch (Exception e) {
// If cleanup fails, there is nothing to do but report it
// and continue.
e.printStackTrace();
}
}
filenames.clear();
}

}


KwikTagUpload.java
-----------------------------
package com.hari.test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;


public class KwikTagUpload {

public static final String EXPENSE_TYPE   = "expenseType";
public static final String SPENT_DATE     = "spentDate";
public static final String SPENT_AMOUNT   = "spentAmount";
    private static String loggerName = KwikTagUpload.class.getName();
    
    private static final String xmlBeforeBarcode =
        "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
        "<KwikTag>\n" +
        "<DocumentList>\n" +
        "<Document barcode=\"";
    private static final String xmlBeforeDrawer =
        "\" drawer=\"";
    private static final String xmlBeforeUsername =
        "\" username=\"";
    private static final String xmlBeforeReportId =
        "\">\n" +
        "<FieldList type=\"meta\">\n" +
        "<TagField name=\"ReportID\">";
    private static final String xmlBeforeSource =
        "</TagField>\n" +
        "<TagField name=\"Source\">File Upload</TagField>\n";
    private static final String xmlBeforeExpenseType =
        "<TagField name=\"Expense Type\">";
    private static final String xmlBeforeSpentDate =
        "</TagField>\n" +
        "<TagField name=\"Spent Date\">";
    private static final String xmlBeforeSpentAmount =
        "</TagField>\n" +
        "<TagField name=\"Spent Amount\">";
    private static final String xmlEnd =
        "</TagField>\n" +
        "</FieldList>\n" +
        "<VersionList>\n"+
        "<Version>\n"+
        "<TagField name=\"scannedpagecount\">1</TagField>\n"+
        "</Version>\n"+
        "</VersionList>\n"+
        "</Document>\n" +
        "</DocumentList>\n" +
        "</KwikTag>\n";

    /**
     * Create an XML file to be sent to Kwiktag, in which the barcode element is set to the value of input parameter barcode
     * and the custom field ReportID is set to the value of input parameter reportId.
     * 
     * @param xmlFile  XML file to be created. 
     * @param reportId the value of custom field ReportID in the XML file. 
     * It can be the expense report number that identifies an expense report.
     * @param barcode the value of barcode field in the XML file. 
     * It can be any unique number that identifies the expense line to which the image will be associated.
     * @param drawer the value of drawer field in the XML file
     * @param username the value of username filed in the XML file
     * @param expenseInfo hash map with expense info
     * @throws IOException
     */
    public static void createXmlFile(File xmlFile, String reportId, String barcode,
            String drawer, String username, Map<String,String> expenseInfo) throws IOException {
        FileWriter fw = null;
        try {
            fw = new FileWriter(xmlFile);
            fw.write(xmlBeforeBarcode);
            fw.write(barcode);
            fw.write(xmlBeforeDrawer);
            fw.write(drawer);
            fw.write(xmlBeforeUsername);
            fw.write(username);
            fw.write(xmlBeforeReportId);
            fw.write(reportId);
            fw.write(xmlBeforeSource);
            fw.write(xmlBeforeExpenseType);
            fw.write(getExpenseValue(expenseInfo, EXPENSE_TYPE));
            fw.write(xmlBeforeSpentDate);
            fw.write(getExpenseValue(expenseInfo, SPENT_DATE));
            fw.write(xmlBeforeSpentAmount);
            fw.write(getExpenseValue(expenseInfo, SPENT_AMOUNT));
            fw.write(xmlEnd);
        } finally {
            if (fw != null) fw.close();
        }
    }
    
    
    /**
     * Read xml escaped key value from expense info hash map
     * @param expenseInfo hash map with expense info
     * @param key key of the requested value
     * @return xml escaped key value
     */
    private static String getExpenseValue(Map<String,String> expenseInfo, String key) {
    String value = "-";
    if (null != expenseInfo) {
    String element = expenseInfo.get(key);
    if (null != element) {
    //value = StringEscapeUtils.escapeXml(element);
    if ((null == value) || ("".equals(value))) {
    value = "-";
    }
    }
    }
    return value;
    }

    /**
     * Returns the full pathname of the shared directory used to pass files
     * to the KwikTag image server.  To prevent users from entering wrong
     * directories, the user enters only the middle section of the path, and
     * the rest is hard-coded.
     * @param fileShareLocation The user-entered portion of the path
     * @return
     */
    public static String getFileSharePath(String fileShareLocation) {
        return fileShareLocation;
    }
    
    public static boolean fileShareLocationIsValid(String fileShareLocation) {
        String fileSharePath = getFileSharePath(fileShareLocation);
        File file = new File(fileSharePath);
        if (!file.exists()) {
            logWarning(fileSharePath, "");
            // It may not exist or it may not be readable or it may not be accessible
            // because a directory in the path may not be readable.
            return false;
        }
        if (!file.isDirectory()) {
            // It exists but is a file.
            return false;
        }
        if (!file.canWrite()) {
            // It is a directory but is not writable.
            return false;
        }
        return true;
    }
    private static void logWarning(String fileSharePath, String warning) {
       System.out.println( "Invalid CyberShift hosting File Share Location " +
                '"' + fileSharePath + "\": " + warning);
    }
}


SFTPUploaderImpl.java
------------------------------
package com.sftp;


import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileSystemOptions; 
import org.apache.commons.vfs.Selectors;
import org.apache.commons.vfs.impl.StandardFileSystemManager;
import org.apache.commons.vfs.provider.sftp.SftpFileSystemConfigBuilder;

import com.necho.platform.service.sftp.SFTPFileSystemAttributes;
import com.sftp.interf.SFTPUploader;



public class SFTPUploaderImpl implements SFTPUploader{
private static String INVALID_URI = "vfs.provider/invalid-absolute-uri.error";
private static String FILE_MISSING = "vfs.provider/copy-missing-file.error";
private static String FILE_READ_ONLY = "vfs.provider/copy-file.error";
private static String SFTP_FILE_SEPARATOR = "/";

/**
* Builds the uri string in the format : sftp://[ username [: password ]@] hostname [: port ][absolute-path ]
* Example : sftp://myusername:mypassword@somehost/pub/downloads/somefile.tgz
* @param sftpHostName
* @param userName
* @param password
* @return
* @throws Exception
* @throws Exception
* @throws SFTPHostNameMissingException
*/
private String getURI(String sftpHostName, String userName,
String password) throws Exception{ 
// Get default encoding 
Charset encoding = java.nio.charset.Charset.defaultCharset();
// Check whether host name was specified.
if ((sftpHostName == null) || (sftpHostName.trim().equals(""))) {
System.out.println("FTP Host Name not specified");
// Throw exception if host name not specified
throw new Exception();
}
StringBuffer sftpUri = new StringBuffer("sftp://");
if ((userName != null) && (!userName.trim().equals(""))) {
userName = URLEncoder.encode(userName, encoding.name());
sftpUri.append(userName);
if ((password != null) && (!password.trim().equals(""))) {
sftpUri.append(":");
password = URLEncoder.encode(password, encoding.name());
sftpUri.append(password);
} else {
// Throw exception if  password not specified
System.out.println("Password not specified for SFTP host server.");
throw new Exception();
}
} else {
// Throw exception if user name not specified
System.out.println("User Name not specified for SFTP host server.");
throw new Exception();
}
if ((sftpHostName != null) && (!sftpHostName.trim().equals(""))) {
if (sftpUri.length() != 0) {
sftpUri.append("@");
}
sftpUri.append(sftpHostName);
return sftpUri.toString();
}

/**
* Processes thrown exception to extract the cause root of the problem and throws an SFTPConnectionException
* @param e
* @throws SFTPGenericConnectionException
* @throws SFTPAuthenticationException
* @throws Exception
*/ 
private static void processFileSystemException(FileSystemException e)
throws Exception {
System.out.println(e.getMessage());
String message = e.getCode();
Exception causeException = (Exception) e.getCause();
if (null != causeException) {
if (null != causeException.getCause()) {
causeException = (Exception) causeException.getCause();
if (null != causeException.getCause()) {
causeException = (Exception) causeException.getCause();
}
}
}
if (causeException instanceof java.net.UnknownHostException) {
throw new Exception();
} /*else if (causeException instanceof com.jcraft.jsch.JSchException) {
if (causeException.getMessage().equalsIgnoreCase("Auth fail")) {
throw new SFTPAuthenticationException();
} else {
throw new SFTPGenericConnectionException();
}
} else if (message.equals(INVALID_URI)) {
throw new Exception();
} else {
throw new SFTPGenericConnectionException();
}*/
}

/**
* Initializes necessary objects for sftp connection 
* @param sftpHostName
* @param userName
* @param password
* @return
* @throws SFTPGenericConnectionException
* @throws Exception
* @throws Exception
* @throws SFTPHostNameMissingException
* @throws SFTPAuthenticationException
* @throws Exception
*/
private  SFTPFileSystemAttributes prepareConnection(String sftpHostName,
String userName, String password)
throws  Exception
{

StandardFileSystemManager manager = new StandardFileSystemManager();
SFTPFileSystemAttributes attributes = null;
try {
String sftpUri = getURI(sftpHostName, userName, password);
FileSystemOptions options = new FileSystemOptions();
SftpFileSystemConfigBuilder instance = SftpFileSystemConfigBuilder.getInstance();
instance.setStrictHostKeyChecking(
options, "no");
manager.init();
attributes = new SFTPFileSystemAttributes(manager, options, sftpUri);
}

catch (Exception e) {
throw new Exception();
return attributes;
}

/**
* Uploads a list of files in a specific directory to an sftp site. Throws exceptions in case of errors.
* @param fileNameList
* @param dirName
* @param sftpHostName
* @param userName
* @param password
* @throws SFTPGenericConnectionException
* @throws Exception
* @throws Exception
* @throws SFTPHostNameMissingException
* @throws SFTPAuthenticationException
* @throws Exception
* @throws SFTPNoFileException
* @throws SFTPFileUploadException
* @throws SFTPFileNotExistException
* @throws SFTPFileReadOnlyException
*/
public  void uploadFiles(List fileNameList, String dirName,
String sftpHostName, String userName, String password)
throws Exception {

SFTPFileSystemAttributes attributes = null;
int index = -1;
try {
if (fileNameList.isEmpty()) {
throw new Exception();
}
attributes = prepareConnection(sftpHostName, userName, password);
for (index = 0; index < fileNameList.size(); index++) {
String fileName = (String) fileNameList.get(index);
FileObject fileObject = attributes.getManager().resolveFile(
attributes.getUri() + SFTP_FILE_SEPARATOR + fileName,
attributes.getOptions());
FileObject localFileObject = attributes.getManager()
.resolveFile(dirName + File.separator + fileName);
fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF);
}
}  catch (FileSystemException e) {
Object o = new Integer(index);
if (FILE_MISSING.equals(e.getCode())) {
System.out.println(e.getMessage());
throw new Exception();
} else if (FILE_READ_ONLY.equals(e.getCode())) {
System.out.println(e.getMessage());
throw new Exception();
} else {
// throw new SFTPFileUploadException(o);
//throw new SFTPFileUploadException(o);
processFileSystemException(e);
}
} catch (Exception e) {
System.out.println(e.getMessage());
throw new Exception();
} finally {
if ((null != attributes) && (null != attributes.getManager())) {
attributes.getManager().close();
}
}
}

/**
* Test sftp connection. Throws an exception with a descriptive error code in case of failure
* @param sftpHostName
* @param userName
* @param password
* @throws SFTPGenericConnectionException
* @throws Exception 
* @throws Exception
* @throws SFTPHostNameMissingException
* @throws SFTPAuthenticationException
* @throws Exception
*/
public  void testConnection(String sftpHostName, String userName,
String password) throws 
Exception {

SFTPFileSystemAttributes attributes = null;
try {
attributes = prepareConnection(sftpHostName, userName, password);
attributes.getManager().resolveFile(attributes.getUri(),
attributes.getOptions());
System.out.println("FTP connection to server: " + sftpHostName
+ "established successfully");
} catch (FileSystemException e) {
processFileSystemException(e);
} catch (Exception e) {
System.out.println(e.getMessage());
throw new Exception();
} finally {
if ((null != attributes) && (null != attributes.getManager())) {
attributes.getManager().close();
}
}
}
/**
* Uploads all files within a specific directory to an sftp site. Throws exceptions in case of errors.
* @param dirName
* @param sftpHostName
* @param userName
* @param password
* @throws SFTPGenericConnectionException
* @throws Exception
* @throws Exception
* @throws SFTPHostNameMissingException
* @throws SFTPAuthenticationException
* @throws Exception
* @throws SFTPNoFileException
* @throws SFTPFileUploadException
* @throws SFTPFileNotExistException
* @throws SFTPFileReadOnlyException
*/
public void uploadFiles(String dirName,
String sftpHostName, String userName, String password)
throws Exception{

SFTPFileSystemAttributes attributes = null;
int index = -1;
try {
attributes = prepareConnection(sftpHostName, userName, password);
FileObject fileObject = attributes.getManager().resolveFile(
attributes.getUri(),
attributes.getOptions());
System.out.println("FTP connection to server: " + sftpHostName
+ "established successfully");
FileObject localFileObject = attributes.getManager()
.resolveFile(dirName);
// Copy all files in specified folder
fileObject.copyFrom(localFileObject, Selectors.EXCLUDE_SELF);
catch (FileSystemException e) {
Object o = new Integer(index);
if (FILE_MISSING.equals(e.getCode())) {
System.out.println(e.getMessage());
throw new Exception(e);
} else if (FILE_READ_ONLY.equals(e.getCode())) {
System.out.println(e.getMessage());
throw new Exception(e);
} else {
//throw new SFTPFileUploadException(o);
//processFileSystemException(e);
}
} catch (Exception e) {
System.out.println(e.getMessage());
throw new Exception();
} finally {
if ((null != attributes) && (null != attributes.getManager())) {
attributes.getManager().close();
}
}
 

}


FTPUploaderImpl.java
-------------------------------
package com.ftp;


import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileSystemOptions; 
import org.apache.commons.vfs.Selectors;
import org.apache.commons.vfs.impl.StandardFileSystemManager;
import org.apache.commons.vfs.provider.sftp.SftpFileSystemConfigBuilder;

import com.necho.platform.service.sftp.SFTPFileSystemAttributes;
import com.sftp.interf.SFTPUploader;



public class FTPUploaderImpl implements SFTPUploader {
private static String INVALID_URI = "vfs.provider/invalid-absolute-uri.error";
private static String FILE_MISSING = "vfs.provider/copy-missing-file.error";
private static String FILE_READ_ONLY = "vfs.provider/copy-file.error";
private static String SFTP_FILE_SEPARATOR = "/";

/**
* Builds the uri string in the format : sftp://[ username [: password ]@] hostname [: port ][absolute-path ]
* Example : sftp://myusername:mypassword@somehost/pub/downloads/somefile.tgz
* @param sftpHostName
* @param userName
* @param password
* @return
* @throws Exception
* @throws Exception
* @throws SFTPHostNameMissingException
*/
private String getURI(String sftpHostName, String userName,
String password) throws Exception{ 
// Get default encoding 
Charset encoding = java.nio.charset.Charset.defaultCharset();
// Check whether host name was specified.
if ((sftpHostName == null) || (sftpHostName.trim().equals(""))) {
System.out.println("FTP Host Name not specified");
// Throw exception if host name not specified
throw new Exception();
}
StringBuffer sftpUri = new StringBuffer("ftp://");
if ((userName != null) && (!userName.trim().equals(""))) {
userName = URLEncoder.encode(userName, encoding.name());
sftpUri.append(userName);
if ((password != null) && (!password.trim().equals(""))) {
sftpUri.append(":");
password = URLEncoder.encode(password, encoding.name());
sftpUri.append(password);
} else {
// Throw exception if  password not specified
System.out.println("Password not specified for SFTP host server.");
throw new Exception();
}
} else {
// Throw exception if user name not specified
System.out.println("User Name not specified for SFTP host server.");
throw new Exception();
}
if ((sftpHostName != null) && (!sftpHostName.trim().equals(""))) {
if (sftpUri.length() != 0) {
sftpUri.append("@");
}
sftpUri.append(sftpHostName);
return sftpUri.toString();
}

/**
* Processes thrown exception to extract the cause root of the problem and throws an SFTPConnectionException
* @param e
* @throws SFTPGenericConnectionException
* @throws SFTPAuthenticationException
* @throws Exception
*/ 
private static void processFileSystemException(FileSystemException e)
throws Exception {
System.out.println(e.getMessage());
String message = e.getCode();
Exception causeException = (Exception) e.getCause();
if (null != causeException) {
if (null != causeException.getCause()) {
causeException = (Exception) causeException.getCause();
if (null != causeException.getCause()) {
causeException = (Exception) causeException.getCause();
}
}
}
if (causeException instanceof java.net.UnknownHostException) {
throw new Exception();
} /*else if (causeException instanceof com.jcraft.jsch.JSchException) {
if (causeException.getMessage().equalsIgnoreCase("Auth fail")) {
throw new SFTPAuthenticationException();
} else {
throw new SFTPGenericConnectionException();
}
} else if (message.equals(INVALID_URI)) {
throw new Exception();
} else {
throw new SFTPGenericConnectionException();
}*/
}

/**
* Initializes necessary objects for sftp connection 
* @param sftpHostName
* @param userName
* @param password
* @return
* @throws SFTPGenericConnectionException
* @throws Exception
* @throws Exception
* @throws SFTPHostNameMissingException
* @throws SFTPAuthenticationException
* @throws Exception
*/
private  SFTPFileSystemAttributes prepareConnection(String sftpHostName,
String userName, String password)
throws  Exception
{

StandardFileSystemManager manager = new StandardFileSystemManager();
SFTPFileSystemAttributes attributes = null;
try {
String sftpUri = getURI(sftpHostName, userName, password);
FileSystemOptions options = new FileSystemOptions();
SftpFileSystemConfigBuilder instance = SftpFileSystemConfigBuilder.getInstance();
instance.setStrictHostKeyChecking(
options, "no");
manager.init();
attributes = new SFTPFileSystemAttributes(manager, options, sftpUri);
}

catch (Exception e) {
throw new Exception();
return attributes;
}

/**
* Uploads a list of files in a specific directory to an sftp site. Throws exceptions in case of errors.
* @param fileNameList
* @param dirName
* @param sftpHostName
* @param userName
* @param password
* @throws SFTPGenericConnectionException
* @throws Exception
* @throws Exception
* @throws SFTPHostNameMissingException
* @throws SFTPAuthenticationException
* @throws Exception
* @throws SFTPNoFileException
* @throws SFTPFileUploadException
* @throws SFTPFileNotExistException
* @throws SFTPFileReadOnlyException
*/
public  void uploadFiles(List fileNameList, String dirName,
String sftpHostName, String userName, String password)
throws Exception {

SFTPFileSystemAttributes attributes = null;
int index = -1;
try {
if (fileNameList.isEmpty()) {
throw new Exception();
}
attributes = prepareConnection(sftpHostName, userName, password);
for (index = 0; index < fileNameList.size(); index++) {
String fileName = (String) fileNameList.get(index);
FileObject fileObject = attributes.getManager().resolveFile(
attributes.getUri() + SFTP_FILE_SEPARATOR + fileName,
attributes.getOptions());
FileObject localFileObject = attributes.getManager()
.resolveFile(dirName + File.separator + fileName);
fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF);
}
}  catch (FileSystemException e) {
Object o = new Integer(index);
if (FILE_MISSING.equals(e.getCode())) {
System.out.println(e.getMessage());
throw new Exception();
} else if (FILE_READ_ONLY.equals(e.getCode())) {
System.out.println(e.getMessage());
throw new Exception();
} else {
// throw new SFTPFileUploadException(o);
//throw new SFTPFileUploadException(o);
processFileSystemException(e);
}
} catch (Exception e) {
System.out.println(e.getMessage());
throw new Exception();
} finally {
if ((null != attributes) && (null != attributes.getManager())) {
attributes.getManager().close();
}
}
}

/**
* Test sftp connection. Throws an exception with a descriptive error code in case of failure
* @param sftpHostName
* @param userName
* @param password
* @throws SFTPGenericConnectionException
* @throws Exception 
* @throws Exception
* @throws SFTPHostNameMissingException
* @throws SFTPAuthenticationException
* @throws Exception
*/
public  void testConnection(String sftpHostName, String userName,
String password) throws 
Exception {

SFTPFileSystemAttributes attributes = null;
try {
attributes = prepareConnection(sftpHostName, userName, password);
attributes.getManager().resolveFile(attributes.getUri(),
attributes.getOptions());
System.out.println("FTP connection to server: " + sftpHostName
+ "established successfully");
} catch (FileSystemException e) {
processFileSystemException(e);
} catch (Exception e) {
System.out.println(e.getMessage());
throw new Exception();
} finally {
if ((null != attributes) && (null != attributes.getManager())) {
attributes.getManager().close();
}
}
}
/**
* Uploads all files within a specific directory to an sftp site. Throws exceptions in case of errors.
* @param dirName
* @param sftpHostName
* @param userName
* @param password
* @throws SFTPGenericConnectionException
* @throws Exception
* @throws Exception
* @throws SFTPHostNameMissingException
* @throws SFTPAuthenticationException
* @throws Exception
* @throws SFTPNoFileException
* @throws SFTPFileUploadException
* @throws SFTPFileNotExistException
* @throws SFTPFileReadOnlyException
*/
public void uploadFiles(String dirName,
String sftpHostName, String userName, String password)
throws Exception{

SFTPFileSystemAttributes attributes = null;
int index = -1;
try {
attributes = prepareConnection(sftpHostName, userName, password);
FileObject fileObject = attributes.getManager().resolveFile(
attributes.getUri(),
attributes.getOptions());
System.out.println("FTP connection to server: " + sftpHostName
+ "established successfully");
FileObject localFileObject = attributes.getManager()
.resolveFile(dirName);
// Copy all files in specified folder
fileObject.copyFrom(localFileObject, Selectors.EXCLUDE_SELF);
catch (FileSystemException e) {
Object o = new Integer(index);
if (FILE_MISSING.equals(e.getCode())) {
System.out.println(e.getMessage());
throw new Exception(e);
} else if (FILE_READ_ONLY.equals(e.getCode())) {
System.out.println(e.getMessage());
throw new Exception(e);
} else {
//throw new SFTPFileUploadException(o);
//processFileSystemException(e);
}
} catch (Exception e) {
System.out.println(e.getMessage());
throw new Exception();
} finally {
if ((null != attributes) && (null != attributes.getManager())) {
attributes.getManager().close();
}
}
 

}


SFTPUploader.java
------------------------

package com.sftp.interf;

import java.util.List;




public interface SFTPUploader {

/**
* Uploads a list of files in a specific directory to an sftp site. Returns the result of the upload process
* @param fileNameList
* @param dirName
* @param sftpHostName
* @param userName
* @param password
* @throws SFTPGenericConnectionException
* @throws SFTPUserNameMissingException
* @throws SFTPPasswordMissingException
* @throws SFTPHostNameMissingException
* @throws SFTPAuthenticationException
* @throws SFTPHostNameException
* @throws SFTPNoFileException
* @throws SFTPFileUploadException
* @throws SFTPFileNotExistException
* @throws SFTPFileReadOnlyException
*/
public void uploadFiles(List fileNameList, String dirName,
String sftpHostName, String userName, String password)
throws Exception;

/**
* Test sftp connection. Throws an exception with a descriptive error code in case of failure
* @param sftpHostName
* @param userName
* @param password
* @throws SFTPGenericConnectionException
* @throws SFTPUserNameMissingException
* @throws SFTPPasswordMissingException
* @throws SFTPHostNameMissingException
* @throws SFTPAuthenticationException
* @throws SFTPHostNameException
*/
public  void testConnection(String sftpHostName, String userName,
String password) throws Exception ;
/**
* Uploads all files within a specific directory to an sftp site. Throws exceptions in case of errors.
* @param dirName
* @param sftpHostName
* @param userName
* @param password
* @throws SFTPGenericConnectionException
* @throws SFTPUserNameMissingException
* @throws SFTPPasswordMissingException
* @throws SFTPHostNameMissingException
* @throws SFTPAuthenticationException
* @throws SFTPHostNameException
* @throws SFTPNoFileException
* @throws SFTPFileUploadException
* @throws SFTPFileNotExistException
* @throws SFTPFileReadOnlyException
*/
public void uploadFiles(String dirName,
String sftpHostName, String userName, String password)
throws Exception;
}


Lib:
-------

commons_net.jar
commons-beanutils-1.7.0.jar
commons-beanutils-1.8.3.jar
commons-codec-1.6.jar
commons-collections.jar
commons-digester.jar
commons-fileupload-1.2.jar
commons-lang-2.1.jar
commons-logging.jar
commons-validator.jar
commons-vfs-1.0.jar
jsch-0.1.43-jdk14.jar


Comments

Popular posts from this blog

CSM Quiz -2

Enabling WL-Proxy-SSL HTTP header in WebLogic

CSM Quiz -1