/** File: UtilCM.java */
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.net.URL;
import java.text.NumberFormat;
import java.util.*;
import O2PlibSS.gui.*;
/**
* Collection of utility functions used by various other classes.
*
* List of Methods
* clearDebugNameValuePairs() - clear DEBUG (name,value) list
* setDebugNameValue() - set DEBUG (name,value) pair.
* testDebugValue - test if str is indexOf() value if name is debug(name,value).
* testDebugValue - test DEBUG value is indexOf(str) if name is debug(name,value).
* logMsg() - print a message
* setReportTextArea() - assign report text area in popup report GUI window
* setReportStatusLineTextField() - assign report status line GUI text field
* setReportStatusLineLabel() - assign report status line label in GUI
* appendPRmsg() - append message to report text area in GUI window
* updateReportStatusLine() - set status line message if text field in GUI
* dateStr() - return the current date stamp
* timeStr() - return the current time stamp
* getCurTimeStr() - return current time string in the format of HHMMSS.
* mapCRLF2space() - map CRLFs in the string to spaces
* mapCRLForCR2LF() - map all CRLF or CR(not LF) to LF
* mapComma2Tab() - map "," to "\t" in the string
* mapIllegalChars() - map illegal characters to '_'
* mapSpaceToMinus() - map " " to "-"
* removeQuotes() - remove '\"' characters from string
* isEmptyArray() - test if array consists of empty data elements
* isNumber() - test if a string is a number (i.e., Double)
* cvf2s() - convert float to string with precision # of digits
* cvd2s() - convert double to string with precision # of digits
* cvs2d() - convert String to double
* cvs2f() - convert String to float
* cvs2i() - convert String to int
* cvs2long() - convert String to long
* cvb2s() - convert boolean String
* cvs2l() - convert String to long
* cvs2b() - convert String to boolean
* cvs2ArrayNullFill() - cvt arg list "1,4,3,6,..." to "," fill nulls.
* cvs2Array() - cvt arg list "1,4,3,6,..." to "," - delim String[].
* rightSizeArray() - extend or shrink an array to requiredSize.
* cloneString() - clone a copy of a String array
* lookupDataIdx() - lookup index of element if exists in a strData[].
* isListInAnotherList() - test if all listA in listB order independent.
* mapAllkeywords() - map data from 'keyword' to 'toString' lists.
* rmvRtnChars() - remove return chars. Map '\r' or "\r\n" to '\n' chars.
* rmvSpecifiedChar() - remove specified character from string.
* rmvEnclosingWhitespace() - remove enclosing whitespace from string
* trimArrayEnclWhitespace() - trim (clean) enclosing white space in 1D array.
* removeEmptyStringsFromArray() - remove nulls and empty Strings in 1D array.
* getCleanArgList() - convert string arg list delimited by "", "," or "\n" to array
* replaceSpaceWithCommaSpaceDelim() - replace " "-delimited list with ", " list
* replaceSubstrInString() - recursively replace oldToken w/newToken in str
* changeWorkingDirectory() - change the working directory
* cvDeltaTime2str() - convert a delta epoch time msec to a string
* off_timer() - Compute the time banner String
* on_timer() - Get the current time (in milliseconds)
* sleepMsec() - sleep for mSec.
* appendElementToArray() - Append String element to String array.
* startsWithIgnoreCase() - test if str starts with startStr ignoring case
* endsWithIgnoreCase() - test if str ends with endsStr ignoring case
* indexOfIgnoreCase() - indexOf subStr of str ignoring case.
* cvtHTMLcolorNameToHex() - map HTML color name to HEX value string
* updateJarFile() - update .jar file from URL into program install area.
* copyFile() - binary copy of one file or URL to a local file
* readBytesFromURL() - read binary data from URL into byte[] array.
* deleteLocalFile() - delete local file.
*
*
* This code is available at the HTMLtools project on SourceForge at
* http://htmltools.sourceforge.net/
* under the "Common Public License Version 1.0"
*
* http://www.opensource.org/licenses/cpl1.0.php.
*
* It was derived and refactored from the open source
* MAExplorer (http://maexplorer.sourceforge.net/), and
* Open2Dprot (http://Open2Dprot.sourceforge.net/) Table modules.
*
* $Date: 2009/11/26 11:45:56 $ $Revision: 1.38 $
*
* Copyright 2008, 2009 by Peter Lemkin
* E-Mail: lemkin@users.sourceforge.net
* http://lemkingroup.com/
*/
public class UtilCM
{
/** Default value of int for cvs2i() calls */
public static int
defaultInt= 0;
/** Default value of float for cvs2f() calls */
public static float
defaultFloat= 0.0F;
/** Local logging flag. If set, then logMsg() output is also
* printed to System.out */
public static boolean
loggingFlag;
/** logging String if loggingFlag enabled */
public volatile static String
loggingStr;
/* ---------------------------------------------------------- */
/* Report Window Text area state */
/* ---------------------------------------------------------- */
/** Report text area will output appendPRmsg if not null.
* This is set with setReportTextArea().
*/
public volatile static JTextArea
rptTextArea= null;
/** Optional Big Report PopupTextViewer text area will output appendPRmsg
* if not null. This is set with setBigReportTextViewer().
*/
public volatile static PopupTextViewer
ptViewer= null;
/** Report text field will output updateReportStatusLine if not null.
* This is set with setReportStatusLineTextField().
*/
public volatile static JTextField
rptStatusLineTextField= null;
/** Report Label will output updateReportStatusLine if not null.
* This is set with setReportStatusLineLabel().
*/
public volatile static JLabel
rptStatusLineLabel= null;
/* ------------------ DEBUG facility ------------------- */
/** Maximum number of debug(name,value) pairs */
final public static int
MAX_DEBUGS= 10;
/** Current number of debug(name,value) pairs */
public static int
nDebugPairs= 0;
/** Name list for Debug facility of (name,value) pairs */
public static String
debugName[]= null;
/** Value list for Debug facility of (name,value) pairs */
public static String
debugValue[]= null;
/**
* UtilCM() - constructor for setup utility pkg for additional
* UtilCM instances. NOTE: you should call the logging version
* of the Constructor first or make a call to setLogMsgs that
* otherwise.
* @param loggingFlag
*/
public UtilCM()
{ /* UtilCM */
if(debugName==null)
clearDebugNameValuePairs();
} /* UtilCM */
/**
* UtilCM() - constructor for setup utility pkg
* @param loggingFlag
*/
public UtilCM(boolean loggingFlag)
{ /* UtilCM */
UtilCM.loggingFlag= loggingFlag;
UtilCM.loggingStr= "";
if(debugName==null)
clearDebugNameValuePairs();
} /* UtilCM */
/**
* clearDebugNameValuePairs() - clear DEBUG (name,value) list
*/
public static void clearDebugNameValuePairs()
{ /* clearDebugNameValuePairs */
debugName= new String[MAX_DEBUGS];
debugValue= new String[MAX_DEBUGS];
nDebugPairs= 0;
} /* clearDebugNameValuePairs */
/**
* setDebugNameValue() - set DEBUG (name,value) pair.
* @param name of the debug pair.
* @param value to associate with debug name pair.
* @return true if successful
* @see #getDebugValue
*/
public static boolean setDebugNameValue(String name, String value)
{ /* setDebugNameValue */
int n= -1;
for(int i= 0;i to LF
* @param rawData raw data representing string table to analyze
* @return mapped string
*/
public static String mapCRLForCR2LF(String rawData)
{ /* mapCRLForCR2LF */
if(rawData==null || rawData.length()==0)
return(rawData);
char
ch= 0,
chP1= 0, /* look ahead +1 */
inputBuf[]= rawData.toCharArray();
int
xStart= 0, /* input buffer pointer */
xOut= 0, /* output buffer pointer */
bufSize= inputBuf.length;
char
outBuf[]= new char[bufSize];
/* [1] Process: look for CRLF or CR to map to LF */
while(xStart < bufSize)
{ /* look for blank line */
ch= inputBuf[xStart];
/* Test if double character line terminator */
if(ch == '\r' && ((xStart - 1) < bufSize))
{ /* found CR - analyze further */
chP1= inputBuf[xStart + 1]; /* look ahead */
if(chP1 == '\n') /* CRLF */
{ /* found CRLF - skip 2nd char, LF, since in CRLF pair */
xStart++;
}
xStart++;
outBuf[xOut++]= '\n'; /* Map both CR or CRLF to LF */
} /* found CR - analyze further */
else
{ /* Not CR, so just copy it */
xStart++;
outBuf[xOut++]= ch; /* Map both CR or CRLF to LF */
}
} /* look for blank line */
String sOut= new String(outBuf, 0, xOut);
return (sOut);
} /* mapCRLForCR2LF */
/**
* mapComma2Tab() - map "," to "\t" in the string
* @param s input string to map
* @return mapped string
*/
public static String mapComma2Tab(String s)
{ /* mapComma2Tab */
if(s==null)
return(null);
String sR= "";
char
ch, /* current character */
sBuf[]= s.toCharArray(); /* cvt input string to char[]*/
int
sSize= s.length(), /* size of input buffer */
sCtr= 0; /* working input buffer index */
while(sCtr=0;i--)
{
ch= str.charAt(i);
if(ch==' ' ||ch=='\t' || ch==':' || ch==';' || ch=='\"' ||
ch==',' || ch=='@' || ch=='*' || ch=='=' || ch=='\'')
ch= '_';
cBuf[i]= ch;
}
sR= new String(cBuf);
return(sR);
} /* mapIllegalChars */
/**
* mapSpaceToMinus() - map " " to "-"
* @param str to map
* @return mapped string
*/
public static String mapSpaceToMinus(String str)
{ /* mapSpaceToMinus */
if(str==null)
return(null);
String sR= "";
char
ch, /* current character */
sBuf[]= str.toCharArray(); /* cvt input string to char[]*/
int
sSize= str.length(), /* size of input buffer */
sCtr= 0; /* working input buffer index */
while(sCtr0)
return(false);
return(true);
} /* isEmptyArray */
/**
* isNumber() - test if a string is a number (i.e., Double)
* @param str is the string to test if it is a number
* @return value of string
*/
public static boolean isNumber(String str)
{ /* isNumber */
double d; /* not used directly, but need to trap NaN exception */
try
{
Double D= new Double(str);
d= D.doubleValue(); /* force exception if NaN */
}
catch(NumberFormatException e)
{ return(false); }
return(true);
} /* isNumber */
/**
* cvf2s() - convert float to string with precision # of digits
* If precision > 0 then limit # of digits in fraction
* @param v is the value to convert
* @param precision is the # of digits to display
* @return string approximating "%0.pd"
*/
public static String cvf2s(float v, int precision)
{/* cvf2s */
NumberFormat nf= NumberFormat.getInstance();
nf.setMaximumFractionDigits(precision);
nf.setGroupingUsed(false);
String s= nf.format(v);
return(s);
}/* cvf2s */
/**
* cvd2s() - convert double to string with precision # of digits
* If precision > 0 then limit # of digits in fraction
* @param v is the value to convert
* @param precision is the # of digits to display
* @return string approximating "%0.pd"
*/
public static String cvd2s(double v, int precision)
{/* cvf2s */
NumberFormat nf= NumberFormat.getInstance();
nf.setMaximumFractionDigits(precision);
nf.setGroupingUsed(false);
String s= nf.format(v);
return(s);
}/* cvd2s */
/**
* cvs2d() - convert String to double
* @param str is the string to convert to a number
* @return value of string
*/
public static double cvs2d(String str)
{ /*cvs2d */
double d;
try
{
Double D= new Double(str);
d= D.doubleValue();
}
catch(NumberFormatException e)
{ d= (double)defaultFloat; }
return(d);
} /*cvs2d */
/**
* cvs2f() - convert String to float
* @param str is the string to convert to a number
* @return value of string
*/
public static float cvs2f(String str)
{ /* cvs2f */
float f;
try
{
Float F= new Float(str);
f= F.floatValue();
}
catch(NumberFormatException e)
{ f= defaultFloat; }
return(f);
} /* cvs2f */
/**
* cvs2f() - convert String to float
* @param str is the string to convert to a number
* @param defVal is the explicit default value
* @return value of string
*/
public static float cvs2f(String str, float defVal)
{ /* cvs2f */
float f;
try
{
Float F= new Float(str);
f= F.floatValue();
}
catch(NumberFormatException e)
{ f= defVal; }
return(f);
} /* cvs2f */
/**
* cvs2i() - convert String to int
* @param str is the string to convert to a number
* @return value of string
*/
public static int cvs2i(String str)
{ /* cvs2i */
int i;
try
{
i= java.lang.Integer.parseInt(str);
}
catch(NumberFormatException e)
{ i= defaultInt; }
return(i);
} /* cvs2i */
/**
* cvs2i() - convert String to int
* @param str is the string to convert to a number
* @param defVal is the explicit default value
* @return value of string
*/
public static int cvs2i(String str, int defVal)
{ /* cvs2i */
int i;
try
{
i= java.lang.Integer.parseInt(str);
}
catch(NumberFormatException e)
{ i= defVal; }
return(i);
} /* cvs2i */
/**
* cvs2long() - convert String to long
* @param str is the string to convert to a long number
* @return value of string
*/
public static long cvs2long(String str)
{ /* cvs2long */
long i;
try
{
i= java.lang.Long.parseLong(str);
}
catch(NumberFormatException e)
{ i= defaultInt; }
return(i);
} /* cvs2long */
/**
* cvb2s() - convert boolean String
* @param b is boolean input to convert
* @return output string as either "true" or "false"
*/
public static String cvb2s(boolean b)
{ /* cvb2s */
if(b)
return("true");
else
return("false");
} /* cvb2s */
/**
* cvs2l() - convert String to long
* @param str containing integer to convert to long
* @return converted number else defaultLong if illegal number.
*/
public static long cvs2l(String str, long defaultLong)
{ /* cvs2l */
if(str==null)
return(defaultLong);
long lV= defaultLong;
if(str != null)
{
try
{
Long L= new Long(str);
lV= L.longValue();
}
catch(NumberFormatException e)
{lV= defaultLong;}
return(lV);
}
return(lV);
} /* cvs2l */
/**
* cvs2b() - convert String to boolean
* @param str containing either "true" or "false"
* @return converted boolean else false if illegal boolean name.
*/
public static boolean cvs2b(String str, boolean defaultBool)
{ /* cvs2i */
if(str==null)
return(defaultBool);
boolean b= defaultBool;
if(str.equals("TRUE") || str.equals("true") ||
str.equals("T") || str.equals("t") || str.equals("1"))
b= true;
return(b);
} /* cvs2b */
/**
* cvs2ArrayNullFill() - cvt arg list "1,4,3,6,..." to "," fill nulls.
* Also, if the delimiter is not "\r" remove all "\r"s, and if
* the delimiter is not "\n" remove all "\n"s.
* Ignore delimiters within "..." quotes, and don't include the '\"'
* character in the token.
* If the nullFillStr is not null, then replace all null strings
* with the nullFillStr.
* @param str string containing a list of Strings
* @param delimChr delimiter to be used
* @param nullFillStr is the string to replace all null strings
* if not null.
* @return array of Strings else null if problem
*/
public static String[] cvs2ArrayNullFill(String str, String delimChr,
String nullFillStr)
{ /* cvs2ArrayNullFill */
String tokArray[]= cvs2Array(str, delimChr);
if(tokArray==null || nullFillStr==null)
return(tokArray);
/* Replace nulls with nullFillStr */
int nTokens= tokArray.length;
for(int i=0;i=(tokBufSize-1))
{ /* grow it first */
int newTokBufSize= (int)(2.0*tokBufSize);
char newTokBuf[]= new char[newTokBufSize];
for(int k=0;k0) /* i.e. only save non-null tokens */
tokArray[nTokens++]= token; /* i.e. save tokens */
if(bufCtrnTokens)
{ /* resize the array */
String newTokArray[]= new String[nTokens];
for(int i=0;i 0)
{ /* make sure all unmodified fields are in reordered list */
for(int i= 0; i < lthA; i++)
{ /* Check for order independent exact contents match */
String strA= listA[i];
if(lookupDataIdx(strA, listB, lthB) == -1)
{
flag= false;
break;
}
} /* Check for order independent exact contents match */
} /* make sure all unmodified fields are in reordered list */
return (flag);
} /* isListInAnotherList */
/**
* mapAllkeywords() - map data from 'keyword' to 'toString' lists.
* Do this for all instances in the mapping list.
* @param str input string containing possible keywords.
* @param keyList is list of keywords to look for when map string
* @param toStrList is list of replacement strings when map string
* @param nMaps is size of the keyList[] and toStrList[] data
* @return true if succeed
*/
public static String mapAllkeywords(String str, String keyList[],
String toStrList[], int nMaps)
{ /* mapAllkeywords */
if(str==null || nMaps==0)
return(str);
String
sPreface= null,
sKeyword= null,
sRest= null,
sToString= null,
sOld= "",
sR= str;
int
keywordLth= 0,
prefaceIdx= -1,
restIdx= -1;
/* See if the keyword is in the list */
while(!sOld.equals(sR))
{ /* keep mapping until no change */
sOld= sR;
/* Look for 'keyword' and extract */
for(int i= 0; i < nMaps; i++)
{ /* check each keyword */
sKeyword= keyList[i];
/* Look for 'keyword' and extract */
prefaceIdx= sR.indexOf(sKeyword);
if(prefaceIdx == -1)
continue; /* not found */
keywordLth= sKeyword.length();
/* Move past the keyword */
restIdx= prefaceIdx + keywordLth;
if(restIdx >= sR.length())
sRest= ""; /* keyword found at the end of the string */
else
sRest= sR.substring(restIdx);
/* replace keyword with toString[i] */
sPreface= sR.substring(0, prefaceIdx);
sToString= toStrList[i];
sR= sPreface + sToString + sRest;
} /* check each keyword */
} /* keep mapping until no change */
return(sR);
} /* mapAllkeywords */
/**
* rmvRtnChars() - remove return chars. Map '\r' or "\r\n" to '\n' chars.
* @param String str to process
* @return String with '\r' removed.
*/
final public static String rmvRtnChars(String str)
{ /* rmvRtnChars */
if(str==null)
return(null);
int
lthOut= 0,
lthIn= str.length(),
lastIdx= lthIn-1;
char
ch,
chLA,
cOut[]= new char[lthIn],
cIn[]= str.toCharArray();
int i= 0;
while(i then map to \n */
chLA= (i==lastIdx) ? 0 : cIn[i+1];
if(chLA=='\n')
i += 1; /* Move past the \n in \r\n */
cOut[lthOut++]= '\n';
}
} /* process all characters */
String sR= new String(cOut,0,lthOut); /* make exact length */
return(sR);
} /* rmvRtnChars */
/**
* rmvSpecifiedChar() - remove specified character from string.
* @param str to process
* @param rmvChar to remove
* @return String with all instances of the specified character removed.
*/
final public static String rmvSpecifiedChar(String str, char rmvChar)
{ /* rmvSpecifiedChar */
if(str==null)
return(null);
if(rmvChar=='\0')
return(str);
int
lthOut= 0,
lthIn= str.length();
char
ch,
cOut[]= new char[lthIn],
cIn[]= str.toCharArray();
int i= 0;
while(i-1;i--)
{ /* find first trailing non-blank character */
if(cIn[i]==' ')
continue;
endingFirstNonBlankIdx= i+1;
break;
}
String sR= str;
if(leadingFirstNonBlankIdx!=-1 && endingFirstNonBlankIdx!=-1)
sR= str.substring(leadingFirstNonBlankIdx,
endingFirstNonBlankIdx);
return(sR);
} /* rmvEnclosingWhitespace */
/**
* trimArrayEnclWhitespace() - trim (clean) enclosing white space in 1D array.
* It goes element by element to try to remove white space. If an element
* is cleaned, it replaces the element string, otherwise the element
* string is not replaced.
* @param rowData - row of data. Trim all non-null elements of the array
* @return the row with non-null elements trimmed.
*/
final public static String[] trimArrayEnclWhitespace(String rowData[])
{ /* trimArrayEnclWhitespace */
if(rowData!=null)
{ /* clean the row */
int lth= rowData.length;
for(int c=0;c0)
{ /* replace mapTok in the sUrl with cell */
int idxOldToken= str.indexOf(oldToken);
if(idxOldToken!=-1)
{ /* replace it */
int idxRestOfStr= idxOldToken+oldToken.length();
frontOfStr= str.substring(0,idxOldToken);
restOfStr= str.substring(idxRestOfStr);
sR = frontOfStr + newToken + restOfStr;
/* Call it recursively in case more than one instance */
sR= replaceSubstrInString(sR, oldToken,newToken);
}
} /* replace mapTok in the sUrl with cell */
return(sR);
} /* replaceSubstrInString */
/**
* changeWorkingDirectory() - change the working directory
* @param newDir to change the user.dir to.
* @return the new conanocalPath of the directory if succeed,
* else null
*/
public static String changeWorkingDirectory(String newDir)
{ /* changeWorkingDirectory */
try
{
String oldDir= System.getProperty("user.dir");
System.setProperty("user.dir", newDir);
File cur = new File(".");
String newDirCanonical= cur.getCanonicalPath();
String curDir= System.getProperty("user.dir");
return(newDirCanonical);
}
catch(Exception e)
{
return(null);
}
} /* changeWorkingDirectory */
/**
* cvDeltaTime2str() - convert a delta epoch time msec to a string
* "00:01:30 (H:M:S) or 90.0 seconds"
* @param deltaTimeMsec is the runtime (end-start) in msec.
* @param fullCvtFlag to generate a full conversion with H:M:S
* "00:01:30 (H:M:S) or 90.0 seconds"
* else generate
* "90.0 seconds"
* @returns program run time in H:M:S and 1/10 seconds.
*/
public static String cvDeltaTime2str(long deltaTimeMsec,
boolean fullCvtFlag)
{ /* cvDeltaTime2str */
int
run= (int)(deltaTimeMsec/1000),
Rhours= run/3600,
Rminutes= (run-(Rhours*3600))/60,
Rseconds= (run-(Rhours*3600)-(Rminutes*60));
float
runMsec= (float)deltaTimeMsec,
totRseconds= runMsec/1000.0F;
String
secR= cvf2s(totRseconds,1)+" seconds",
sR= secR;
if(fullCvtFlag)
sR= Rhours+":"+Rminutes+":"+Rseconds+" (H:M:S) or "+secR;
return(sR);
} /* cvDeltaTime2str */
/**
* off_timer() - Compute the time banner String assuming that a
* on_timer(cpuTime,runTime) was done previously.
* EXAMPLE:
* "00:01:30 (H:M:S) or 90.0 seconds"
* @param startT is the starting times runtime
* @returns program run time (endTime-startTime) in H:M:S and 1/10
* seconds
*/
public static String off_timer(long startT)
{ /* off_timer */
long
endTime= on_timer(), /* current time */
deltaTimeMsec= (endTime - startT);
String sR= "Run time ="+cvDeltaTime2str(deltaTimeMsec,true)+"\n";
return(sR);
} /* off_timer */
/**
* on_timer() - Get the current time (in milliseconds)
* @return runtime
*/
public static long on_timer()
{ /* on_timer */
Date dateObj= new Date();
long time= dateObj.getTime();
return(time);
} /* on_timer */
/**
* sleepMsec() - sleep for mSec.
* @param mSec
*/
public synchronized static void sleepMsec(int mSec)
{ /* sleepMsec */
try
{ Thread.sleep(mSec); }
catch (InterruptedException e)
{}
} /* sleepMsec */
/**
* appendElementToArray() - Append String element to String array.
* If the array is null, create the array, else extend it 1 element.
* @param sArray - is array to append element to.
* @param sElement to append
* @return extended array.
*/
public static String[] appendElementToArray(String sArray[], String sElement)
{ /* appendElementToArray */
int n;
if(sArray==null)
{
sArray= new String[1];
n= 1;
}
else
{ /* grow by 1 element */
n= sArray.length;
String tmp[]= new String[n+1];
for(int i=0;i
* [1] Define directory for .jar path and other file and URL names.
* [2] Backup the old {pgmName}.jar as {pgmName}.jar.bkup
* [3] Open the url: from urlJarFile and read the file from
* the Web into local file {pgmName}+".jar.tmp"
* [4] Move the {pgmName}+".jar.tmp" file into {pgmName}+".jar" in the
* program directory
*
* @param pgmName - base name of the program (no extension)
* @param urlJarFile - full URL for file on the server
* @param localJarFilePath - full path for the target file
* @return true if succeed
* @see #copyFile
* @see #deleteLocalFile
*/
public static boolean updateJarFile(String pgmName, String urlJarFile,
String localJarFilePath)
{ /* updateJarFile */
/* [1] Define directory for {pgmName}.jar path and other file
* and URL names.
*/
String
fileSep= System.getProperty("file.separator"),
userDir= System.getProperty("user.dir")+fileSep,
localJarFile= userDir + pgmName+".jar",
localJarFileBkup= userDir + pgmName+".jar.bkup",
localJarFileTmp= userDir + pgmName+".jar.tmp";
/* [2] Backup the old Flicker.jar as Flicker.jar.bkup if it exists
* (it won't if you are running from the debugger!).
* But first, delete old backup if it exists.
*/
deleteLocalFile(localJarFileBkup);
boolean ok= copyFile(localJarFile, localJarFileBkup, null,0);
if(!ok)
return(false);
/* [3] Open the url: jarURL and read the file from the Web into
* localJarFileTmp
*/
String updateMsg= "Updating your "+pgmName+".jar file from "+
urlJarFile+ " server.\n";
File f= new File(localJarFileBkup);
int estInputFileLth= (f!=null) ? (int)f.length() : 0;
if(! copyFile(urlJarFile,localJarFileTmp, updateMsg, estInputFileLth))
return(false);
/* [4] Move the localJarFileTmp file into localJarFile in the
* program directory where it was installed.
*/
if(! deleteLocalFile(localJarFile))
return(false);
if(! copyFile(localJarFileTmp, localJarFile, null,0))
return(false);
return(true);
} /* updateJarFile */
/**
* copyFile() - binary copy of one file or URL to a local file
* @param srcName is either a full path local file name or
* a http:// prefixed URL string of the source file.
* @param dstName is the full path of the local destination file name
* @param optUpdateMsg (opt) will display message in showMsg() and
* increasing ... in showMsg2(). One '.' for every 10K bytes read.
* This only is used when reading a URL. Set to null if not used.
* @param optEstInputFileLth is the estimate size of the input file if
* known else 0. Used in progress bar.
* @return true if succeed.
*/
public static boolean copyFile(String srcName, String dstName,
String optUpdateMsg,
int optEstInputFileLth)
{ /* copyFile */
try
{ /* copy data from input to output file */
FileOutputStream dstFOS= new FileOutputStream(new File(dstName));
FileInputStream srcFIS= null;
int
bufSize= 100000,
nBytesRead= 0,
nBytesWritten= 0;
byte buf[]= new byte[bufSize];
boolean isURL= (srcName.startsWith("http://") || srcName.startsWith("file://"));
if(isURL)
{ /* Copy the file from Web site */
if(optUpdateMsg!=null)
logMsg(optUpdateMsg);
String sDots= "";
URL url= new URL(srcName);
InputStream urlIS= url.openStream();
int nTotBytesRead= 0;
while(true)
{ /* read-write loop */
if(optUpdateMsg!=null)
{ /* show progress every read */
sDots += ".";
String
sPct= (optEstInputFileLth>0)
? ((int)((100*nTotBytesRead)/optEstInputFileLth))+"% "
: "",
sProgress= "Copying " + sPct + sDots+"\n";
logMsg(sProgress);
}
nBytesRead= urlIS.read(buf);
nTotBytesRead += nBytesRead;
if(nBytesRead==-1)
break; /* end of data */
else
{
dstFOS.write(buf,0,nBytesRead);
nBytesWritten += nBytesRead;
}
} /* read-write loop */
dstFOS.close();
if(optUpdateMsg!=null)
{
logMsg("\n");
}
}
else
{ /* copy the file on the local file system */
srcFIS= new FileInputStream(new File(srcName));
while(true)
{ /* read-write loop */
nBytesRead= srcFIS.read(buf);
if(nBytesRead==-1)
break; /* end of data */
else
{
dstFOS.write(buf,0,nBytesRead);
nBytesWritten += nBytesRead;
}
} /* read-write loop */
srcFIS.close();
dstFOS.close();
} /* copy the file on the local file system */
} /* copy data from input to output file */
catch(Exception e1)
{ /* just fail if any problems at all! */
return(false);
}
return(true);
} /* copyFile */
/**
* readBytesFromURL() - read binary data from URL into byte[] array.
* @param srcName is either a full path local file name or
* a http:// prefixed URL string of the source file.
* @param optUpdateMsg (opt) will display message in showMsg() and
* increasing ... in showMsg2(). One '.' for every 10K bytes read.
* This only is used when reading a URL. Set to null if not used.
* @return a byte[] if succeed, else null.
*/
public static byte[] readBytesFromURL(String srcName, String optUpdateMsg)
{ /* readBytesFromURL */
if(!srcName.startsWith("http://") && !srcName.startsWith("file://"))
return(null);
int
bufSize= 20000,
nBytesRead= 0,
nBytesWritten= 0,
oByteSize= bufSize;
byte
buf[]= null,
oBuf[]= null;
try
{ /* copy data from input to output file */
buf= new byte[bufSize];
oBuf= new byte[bufSize];
/* Copy the file from Web site */
if(optUpdateMsg!=null)
logMsg(optUpdateMsg);
String sDots= "";
URL url= new URL(srcName);
InputStream urlIS= url.openStream();
logMsg("Reading " + sDots);
while(true)
{ /* read-write loop */
if(optUpdateMsg!=null)
{ /* show progress every read */
logMsg(".");
}
nBytesRead= urlIS.read(buf);
if(nBytesRead==-1)
break; /* end of data */
else
{ /* copy buf to end of oBuf */
if(nBytesRead+nBytesWritten >= oByteSize)
{ /* regrow oBuf by bufSize */
byte tmp[]= new byte[oByteSize+bufSize];
for(int i=0;i