// -------------------------------------------------------------------------------
// CLASS: FTPManager
// Use : This class was modeled to be used publisher/SiteManager.
// The peocess to send a file via FTP, has four steps.
// Step 1: Configure Ftp Settings: Host, User Name, password, mode & Connection Mode.
// Mode and Connection mode has a default value: BINARY and PASV respectivly.
// Step 2: Use Stack methodos to tell path and filename of file to be sent.
// OBS: To send a directory the path must be finished with "\". ex: c:\bla\
// Step 3: use addChange to say what changes the publication will do. ex:
// addChanges(".dev.",".demo.");
// Step 4: call copyFiles();
// Notes:
// This class is a OBJ COM, to refresh the produc uses reg.bat (check if it's well configurated)
//
// Author:
// Walter D'Avila Neto
// ----------------------------------------------------------------------------------
package com.util.ftp;
//import com.util.publisher.FTPClient; // FTP LIBRARY this class uses all other classes needed.
import java.io.IOException;
import java.util.Vector;
import java.util.Stack; // The Stack on this class is used to push and pop fileNames
import java.util.Hashtable; // Hash table of what must be changed to what (on makeChange)
import java.util.Enumeration;
import java.io.File; // ------------------------------------------
import java.io.FileReader; //
import java.io.FileWriter; // those Classes Will make Os interface.
import java.io.BufferedReader; //
import java.io.BufferedWriter; // ------------------------------------------
// ***************************************************************************************************
// CLASS
// ***************************************************************************************************
public class FTPManager {
// ------------------------------------------------------------------------------
// Connection Properties
// ------------------------------------------------------------------------------
private FTPClient ftp ;
private String host ; // ex: "sites.demo.bowneglobal.com.br"
private String userName ;
private String password ;
private String directory; // Base OS Directory ex:"C:\\"
private String mode ; // BINARY or ASCII
private String connMode ; // PASIVE or ACTIVE
private String currentDirectory;
private String initialDirectory;// This is the minimum os directory ex "c:\"
private String rootFTPDirectory;// This is the minimum FTP directory ex "/sites_test/"
private String temporaryFolder; // This is the tmo folder for temp files "C:\\_mirror\\sitemanager\\tmp\\"
private String errorMessage; // this make Exception interface for Asp.
private Vector errorList; // This is a 'list' of Publication Errors
// ------------------------------------------------------------------------------
private Stack stackFiles;
private Hashtable changes;
// ------------------------------------------------------------------------------
// CONSTRUCTOR WITH DEFAILT PARAMETERS
// ------------------------------------------------------------------------------
public FTPManager (){
// DEFAULT FOR A WHILE : ))
host = new String("sites.demo.bowneglobal.com.br"); // FIXME IT CANT HAVE A DEFAULT !!
userName = new String("immersant/administrator"); // FIXME IT CANT HAVE A DEFAULT !!
password = new String("2612imm"); // FIXME IT CANT HAVE A DEFAULT !!
directory = new String(".");
mode = new String("BINARY"); // BINARY or ASCII
connMode = new String("PASV"); // PASV or ACTIVE
stackFiles = new Stack();
initialDirectory = new String("G:\\sites"); // ex: "G:\\sites"
currentDirectory = new String(".");
rootFTPDirectory = new String("/sites_demo/"); // ex: "/sites_demo/"
temporaryFolder = new String("G:\\sites\\publisher\\tmp\\");// ex: "G:\\sites\\publisher\\tmp\\"
errorMessage = new String("");
changes = new Hashtable();
errorList = new Vector();
}
// ------------------------------------------------------------------------------
// GETERS
// ------------------------------------------------------------------------------
public String getUserName () { return this.userName;}
public String getDirectory() { return this.currentDirectory;}
public String getMode () { return this.mode ;}
public String getConnMode () { return this.connMode;}
public String getErrorMessage() { return this.errorMessage;}
public String[] getErrorList() {
String[] stringList = new String[errorList.size()] ;
errorList.copyInto(stringList); // -- For sun jdk
return stringList;
}
// ------------------------------------------------------------------------------
public boolean setTemporaryFolder(String aTemporaryFolder){
if (! aTemporaryFolder.equals("")) {
this.temporaryFolder = new String(aTemporaryFolder);
try {
File auxFile = new File(this.temporaryFolder);
if (auxFile.isDirectory()) {
return true;
}
this.errorMessage = "
Temporary Folder is a Non folder FileClass";
return false;
} catch (java.lang.SecurityException e) {
this.errorMessage = "
:> (setTemporaryFolder)" + e.getMessage() ;
return false;
}
}
this.errorMessage = "
Invalid temporaryFolder Name";
return false;
}
// ------------------------------------------------------------------------------
public boolean setInitialDirectory (String aInitialDirectory ){
if (! aInitialDirectory.equals("") ) {
this.initialDirectory = new String(aInitialDirectory);
try {
File auxFile = new File(this.initialDirectory);
if (auxFile.isDirectory()) {
return true;
}
this.errorMessage = "
Initial Directory is a Non folder FileClass";
return false;
} catch (java.lang.SecurityException e) {
this.errorMessage = "
:> (setInitialDirectory)" + e.getMessage() ;
return false;
}
}
this.errorMessage = "
Invalid Initial Directory Name";
return false;
}
// ------------------------------------------------------------------------------
public boolean setHost (String aHost) {
if (! aHost.equalsIgnoreCase("")) {
this.host = aHost ;
return true;
}
this.errorMessage = "
Invalid Host Name";
return false;
}
// ------------------------------------------------------------------------------
public boolean setUserName (String aUserName) {
if (! aUserName.equalsIgnoreCase("")) {
this.userName = aUserName ;
return true;
}
this.errorMessage = "
Invalid User Name";
return false;
}
// ------------------------------------------------------------------------------
public boolean setMode (String aMode) {
if (! aMode.equalsIgnoreCase("")) {
this.mode = aMode;
return true;
}
this.mode = "BINARY";
this.errorMessage = "
Invalid mode. Default Mode Set to BINARY";
return false;
}
// ------------------------------------------------------------------------------
public boolean setConnMode (String aConnMode) {
if (! aConnMode.equalsIgnoreCase("")) {
this.connMode = new String(aConnMode);
return true;
}
this.connMode = "PASV";
this.errorMessage = "
Invalid Connection Mode. Default Connection Mode Set to PASV";
return false;
}
// ------------------------------------------------------------------------------
public void setPassword (String aPassword) { this.password = aPassword ;}
// ------------------------------------------------------------------------------
public void setRootFTPDirectory (String aRootFTPDirectory) {
this.rootFTPDirectory = "/" + aRootFTPDirectory;
}
// ------------------------------------------------------------------------------
public boolean setDirectory(String aDirectory) {
this.currentDirectory = new String(aDirectory);
try {
ftp.chdir(currentDirectory);
} catch (IOException e) {
//System.out.println("Caught exception: (setDirectory)" + e.getMessage() + "\n Creatinf Directory");
//this.errorMessage = "
Caught exception: (setDirectory)" + e.getMessage() + "\n Creating Directory";
return false;
} catch (FTPException e) {
//this.errorMessage = "
Caught exception: (setDirectory)" + e.getMessage() + "\n Creating Directory";
//System.out.println("Caught exception: (setDirectory)" + e.getMessage());
return false;
}
return true;
}
// ------------------------------------------------------------------------------
// Open the Ftp Connection with all needed setting declared. (Look Connection Steps)
// ------------------------------------------------------------------------------
public boolean openConnection() {
String strReturn = new String();
try {
// connect again
ftp = new FTPClient(host,21); // OR Just with one parameter (host)
// switch on debug of responses
// Careful on choose this option! It will show IO Passord and Connection settings!
//ftp.debugResponses(true); // AND it will raise the IOException as COM OBJECT!
ftp.login(userName, password);
// Set Mode Type of Connection
if (mode.equalsIgnoreCase("BINARY")) {
ftp.setType(FTPTransferType.BINARY);
} else if (mode.equalsIgnoreCase("ASCII")) {
ftp.setType(FTPTransferType.ASCII);
} else {
this.errorMessage = "
Unknow Mode Type";
return false;
}
// Set Connection Mode
if (connMode.equalsIgnoreCase("PASV")) {
ftp.setConnectMode(FTPConnectMode.PASV);
} else if (mode.equalsIgnoreCase("ACTIVE")) {
ftp.setConnectMode(FTPConnectMode.ACTIVE);
} else {
this.errorMessage = "
Unknown Connection Mode: ";
return false;
}
}
catch (IOException ex) {
//System.out.println("Caught exception: " + ex.getMessage());
this.errorMessage = "
Caught exception: " + ex.getMessage();
return false;
} catch (FTPException ex) {
//System.out.println("Caught exception: " + ex.getMessage());
this.errorMessage = "
Caught exception: " + ex.getMessage();
return false;
}
return true ; //vecReturn.toString();
}
// ------------------------------------------------------------------------------
// Close the Ftp Connection
// ------------------------------------------------------------------------------
public boolean closeConnection() {
try {
ftp.quit();
} catch (IOException ex) {
//System.out.println("Caught exception: (closeConnection)" + ex.getMessage());
this.errorMessage = "
Caught exception: (closeConnection)" + ex.getMessage();
return false;
} catch (FTPException ex) {
//System.out.println("Caught exception: (closeConnection)" + ex.getMessage());
this.errorMessage = "
Caught exception: (closeConnection)" + ex.getMessage();
return false;
}
return true;
}
// ------------------------------------------------------------------------------
// This method returns an array of string with FTP current directory
// ------------------------------------------------------------------------------
public String[] dir() {
String[] listings;
listings = safeDir();
for (int i=0 ;i < 10 ; i ++) {
if (listings!= null) {
return listings;
}
}
return listings;
}
// ------------------------------------------------------------------------------
// Descritive array of FTP Current Directory List
// ------------------------------------------------------------------------------
public String[] listDirectory() {
String[] listings;
try {
// test that dir() works in full mode
listings = ftp.dir(currentDirectory, true); // for detailed directory listenings
} catch (IOException ex) {
//System.out.println("Caught exception: (listDirectory)" + ex.getMessage());
this.errorMessage = "
Caught exception: (listDirectory)" + ex.getMessage();
return null;
} catch (FTPException ex) {
//listings = new String[0] ;
//listings[0] = "Caught exception: (listDirectory)" + ex.getMessage();
//System.out.println("Caught exception: (listDirectory)" + ex.getMessage());
this.errorMessage = "
Caught exception: (listDirectory)" + ex.getMessage();
return null;
}
return listings;
}
// ------------------------------------------------------------------------------
// STACK METHODOES !!!
// Just as a normal Stack
// ------------------------------------------------------------------------------
public boolean push(String anItemName) {
if (! anItemName.equals("")) {
stackFiles.push( new String(anItemName));
return true;
}
this.errorMessage = "
Caught exception: Invalid File Name!" ;
return false;
}
public String pop() {
return (String)stackFiles.pop();
}
public boolean empty(){
return stackFiles.empty();
}
public void addChanges(String toChange, String changeTo){
this.changes.put(new String(toChange),new String(changeTo));
}
// ------------------------------------------------------------------------------
// PUBLIC METHOD OF COPY FILES
// ------------------------------------------------------------------------------
public boolean copyFiles(){
String file = new String();
boolean isCopyfilesOk = true;
while (! stackFiles.empty()) {
file = (String)stackFiles.pop();
if (isBinary(file)) {
setFTPPath(file);
if (! copyBinaryFile(file)) {
this.errorMessage += "
Error on " + file.toString();
isCopyfilesOk = false;
}
} else {
setFTPPath(file);
if (!makeChanges(file)) {
this.errorMessage += "
Error on " + file.toString();
isCopyfilesOk = false;
}
}
}
return isCopyfilesOk;
}
// *******************************************************************************
// *******************************************************************************
// PRIVATE METHODOS !!!
// *******************************************************************************
// *******************************************************************************
// ------------------------------------------------------------------------------
// Copy Binary Files
// ------------------------------------------------------------------------------
private boolean copyBinaryFile (String aFile) {
try {
ftp.put(aFile,parseFileName(aFile));
} catch (java.lang.SecurityException e) {
this.errorMessage = "
Caught exception: (copyBinaryFile)" + e.getMessage();
return false;
} catch (IOException e) {
//System.out.println("Caught exception: (copyBinaryFile)" + e.getMessage());
this.errorMessage = "
Caught exception: (copyBinaryFile)" + e.getMessage();
//this.errorList.addElement(this.errorMessage);
return false;
} catch (FTPException e){
//System.out.println("Caught exception: (copyBinaryFile)" + e.getMessage());
this.errorMessage = "
Caught exception: (copyBinaryFile)" + e.getMessage();
//this.errorList.addElement(this.errorMessage);
return false;
}
return true;
}
// ------------------------------------------------------------------------------
// Copy Text Files
// ------------------------------------------------------------------------------
private boolean setFTPPath (String aFile) {
String tempDirectoryName = new String(this.rootFTPDirectory);
String filePathAndName = aFile.substring(this.initialDirectory.length());
String[] arrayDirectories = splitPath(filePathAndName.replace('\\','/')); // can't has \ at end of string!
setDirectory(tempDirectoryName) ;
// Check if directory exists and create if needed
for (int i=0 ; i < arrayDirectories.length-1 ; i++) {
tempDirectoryName += arrayDirectories[i];
if (!setDirectory( tempDirectoryName)) {
try {
ftp.mkdir( tempDirectoryName);
} catch (IOException e) {
//System.out.println("Caught exception: (setFTPPath) " + e.getMessage());
this.errorMessage = "
Caught exception: (setFTPPath) " + e.getMessage();
//this.errorList.addElement(this.errorMessage);
return false;
} catch (FTPException e) {
//System.out.println("Caught exception: (setFTPPath)" + e.getMessage());
this.errorMessage = "
Caught exception: (setFTPPath) " + e.getMessage();
//this.errorList.addElement(this.errorMessage);
return false;
}
}
}
setDirectory(tempDirectoryName);
return true;
}
// ------------------------------------------------------------------------------
// Private: Make changes
// Get a Text file, create a temporary files with all parsed changes and put it FTP
// ------------------------------------------------------------------------------
private boolean makeChanges(String aFile){
String temporaryFolderAndName = new String(temporaryFolder + parseFileName(aFile));
String lineContent = new String();
try {
BufferedReader content = new BufferedReader ( new FileReader(aFile));
BufferedWriter newContent = new BufferedWriter ( new FileWriter( temporaryFolderAndName));
lineContent = content.readLine();
while (lineContent != null) {
Enumeration enumeratedKeys = changes.keys() ;
while ( enumeratedKeys.hasMoreElements() ) {
Object key = enumeratedKeys.nextElement();
lineContent = StringUtil.replace(lineContent, (String)key, (String)changes.get(key));
}
newContent.write(lineContent, 0, lineContent.length() );
newContent.newLine();
lineContent = content.readLine();
}
content.close(); // here we drop fileReader
newContent.flush(); // Flush the Stream
newContent.close(); // here we drop content
File tmpFile = new File(temporaryFolderAndName); // Create temporary file
ftp.put(temporaryFolderAndName,tmpFile.getName()); // Put file to FTP Current directory
tmpFile.delete(); // Delete File
} catch (java.lang.IndexOutOfBoundsException e) {
this.errorMessage = "
Caught exception: (makeChanges)" + e.getMessage();
return false;
} catch (java.lang.SecurityException e) {
this.errorMessage = "
Caught exception: (makeChanges)" + e.getMessage();
return false;
} catch (IOException e) {
//System.out.println(":> (makeChanges)" + e + "readFile method!");
this.errorMessage = "
Caught exception:> (makeChanges)" + e.getMessage() + "readFile method!";
//this.errorList.addElement(this.errorMessage);
return false;
} catch (FTPException e){
//System.out.println("FTP catch: (makeChanges)" + e);
this.errorMessage = "
Caught exception:> (makeChanges)" + e.getMessage() + "readFile method!";
//this.errorList.addElement(this.errorMessage);
return false;
}
return true;
}
// ------------------------------------------------------------------------------
// Just as Dir public interface but put exception on error message.
// ------------------------------------------------------------------------------
private String[] safeDir() {
String[] listings;
try {
// test that dir() works in full mode
ftp.system();
ftp.pwd();
listings = ftp.dir(currentDirectory); // StringArray of file Names
return listings;
} catch (IOException ex) {
//System.out.println("Caught exception: (dir)" + ex.getMessage());
this.errorMessage = "
Caught exception: (dir/SafeDir)" + ex.getMessage();
//this.errorList.addElement(this.errorMessage);
return null;
} catch (FTPException ex) {
//System.out.println("Caught exception: (dir)" + ex.getMessage());
this.errorMessage = "
Caught exception: (dir/SafeDir)" + ex.getMessage();
//this.errorList.addElement(this.errorMessage);
return null;
}
}
// ------------------------------------------------------------------------------
// Copy All Directory Files recursively
// ------------------------------------------------------------------------------
private String[] copyAllDirectoryFiles (String aPath) {
File fileSys = new File(aPath); // Create File Object and set it to a Path
String[] lstFiles = fileSys.list(); // List dis Directory path
Vector returnLstFiles = new Vector(); // This is a Vector of FileNames auxiliary to return Stirng[]
// get all Files (Recursive)
for (int index = 0; index < lstFiles.length ; index++) {
if (isDirectory(lstFiles[index])) {
Vector auxLstFile = recursiveDir(aPath + lstFiles[index] + "\\");
for (int auxIndex=0 ; auxIndex < auxLstFile.size(); auxIndex++) {
returnLstFiles.addElement(auxLstFile.elementAt(auxIndex));
}
}
else {
returnLstFiles.addElement(aPath + lstFiles[index]);
}
}
String[] returnStringList = new String[returnLstFiles.size()]; // Retruen variable
// Copy files if Binary or make changes if text file.
for (int index=0; index < returnLstFiles.size() ; index++) {
String tmpString = (String)returnLstFiles.elementAt(index) ;
returnStringList[index] = tmpString;
if (isBinary(tmpString)) {
setFTPPath(tmpString);
copyBinaryFile(tmpString);
//System.out.println(returnStringList[index]);
}
else{
setFTPPath(tmpString);
makeChanges(tmpString);
//System.out.println(returnStringList[index]);
}
}
//System.out.println("FILES:>" + returnStringList.length);
return returnStringList;
}
// ------------------------------------------------------------------------------
// this is used on Copy all files (this is the recursive function)
// ------------------------------------------------------------------------------
private Vector recursiveDir (String aPath) {
File fileSys = new File(aPath);
String[] lstFiles = fileSys.list();
Vector returnLstFiles = new Vector();
if (fileSys.isDirectory()) {
for (int index = 0; index < lstFiles.length ; index++) {
if (isDirectory(lstFiles[index])) {
Vector auxLstFile = recursiveDir(aPath + lstFiles[index] + "\\");
for (int auxIndex=0 ; auxIndex < auxLstFile.size(); auxIndex++) {
returnLstFiles.addElement( auxLstFile.elementAt(auxIndex));
}
}
else {
returnLstFiles.addElement(aPath + lstFiles[index]);
}
}
}
return returnLstFiles;
}
// ------------------------------------------------------------------------------
// PARSE UTIL METHODS
// ------------------------------------------------------------------------------
private String parseFileName (String aFile ){
int lastPositionBar = 0;
for (int i = aFile.length() -1 ; i > 0;i-- )
if (aFile.charAt(i) == '\\' || aFile.charAt(i) == '/')
return aFile.substring(i+1,aFile.length() ); // substring( int inclusive , int exlusive)
return "";
}
// ------------------------------------------------------------------------------
private String parseDirectory (String aFile ){
int lastPositionBar = 0;
for (int i = aFile.length() -1 ; i > 0;i-- )
if (aFile.charAt(i) == '\\' || aFile.charAt(i) == '/')
return aFile.substring(0,i )+"\\"; // substring( int inclusive , int exlusive)
return "";
}
// ------------------------------------------------------------------------------
private boolean isBinary(String aFile){
if (aFile.toLowerCase().endsWith(".asp") || aFile.toLowerCase().endsWith(".txt") || aFile.toLowerCase().endsWith(".inc")
|| aFile.toLowerCase().endsWith(".php") || aFile.toLowerCase().endsWith(".htm") || aFile.toLowerCase().endsWith(".html")
|| aFile.toLowerCase().endsWith(".vbs") || aFile.toLowerCase().endsWith(".log") || aFile.toLowerCase().endsWith(".js")
|| aFile.toLowerCase().endsWith(".java")|| aFile.toLowerCase().endsWith(".pl") || aFile.toLowerCase().endsWith(".py")
|| aFile.toLowerCase().endsWith(".inc") || aFile.toLowerCase().endsWith(".phtml")|| aFile.toLowerCase().endsWith(".bat")) {
return false;
}
return true;
}
// ------------------------------------------------------------------------------
private String[] splitPath(String str )
{
int barcounter=0;
for (int x=0;x