You are viewing a plain text version of this content. The canonical link for it is here.
Posted to cvs@avalon.apache.org by ra...@apache.org on 2002/03/06 14:42:57 UTC
cvs commit: jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util DateUtils.java EncryptUtils.java RegularExpr.java AsciiOutputStream.java AsyncMessageQueue.java BaseProperties.java FileRegularFilter.java IoUtils.java PropertiesException.java Queue.java VirtualDirectory.java AsciiInputStream.java
rana_b 02/03/06 05:42:57
Modified: ftpserver/src/java/org/apache/avalon/ftpserver/util
AsciiOutputStream.java AsyncMessageQueue.java
BaseProperties.java FileRegularFilter.java
IoUtils.java PropertiesException.java Queue.java
VirtualDirectory.java
Added: ftpserver/src/java/org/apache/avalon/ftpserver/util
DateUtils.java EncryptUtils.java RegularExpr.java
Removed: ftpserver/src/java/org/apache/avalon/ftpserver/util
AsciiInputStream.java
Log:
second stage of refactoring
Revision Changes Path
1.4 +45 -30 jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/AsciiOutputStream.java
Index: AsciiOutputStream.java
===================================================================
RCS file: /home/cvs/jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/AsciiOutputStream.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- AsciiOutputStream.java 10 Nov 2001 21:34:04 -0000 1.3
+++ AsciiOutputStream.java 6 Mar 2002 13:42:57 -0000 1.4
@@ -8,82 +8,97 @@
package org.apache.avalon.ftpserver.util;
+
import java.io.*;
+import java.io.IOException;
+import java.io.OutputStream;
/**
- * Write ASCII data. It filters non-ascii character.
- *
+ * Write ASCII data. Before writing it filters the data.
+ *
* @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
*/
public
-class AsciiOutputStream extends FilterOutputStream {
-
- protected long mlActualByteWritten = 0;
- protected boolean mbIgnoreNonAscii = true;
-
+class AsciiOutputStream extends OutputStream {
+
+ private long mlActualByteWritten = 0;
+ private boolean mbIgnoreNonAscii = true;
+ private OutputStream mOutputStream;
+
/**
* Constructor.
- *
* @param os <code>java.io.OutputStream</code> to be filtered.
*/
public AsciiOutputStream(OutputStream os) {
- super(os);
+ mOutputStream = os;
}
-
+
/**
- * Write a single byte.
+ * Write a single byte.
* ASCII characters are defined to be
* the lower half of an eight-bit code set (i.e., the most
* significant bit is zero). Change "\n" to "\r\n".
*/
public void write(int i) throws IOException {
-
- i = i & 0xFF;
-
- // ignore character if necessary
- if ( (i>0x7F) && (mbIgnoreNonAscii) ) {
+
+ if (mbIgnoreNonAscii && (i > 0x7F) ) {
return;
}
-
- byte b = (byte)(i & 0x7F);
- if(b == '\r') {
+
+ if (i == '\r') {
return;
}
- if(b == '\n') {
+ if (i == '\n') {
actualWrite('\r');
}
- actualWrite(b);
+ actualWrite(i);
+
+ }
+
+ /**
+ * Close stream
+ */
+ public void close() throws IOException {
+ mOutputStream.close();
}
-
+
+ /**
+ * Flush stream data
+ */
+ public void flush() throws IOException {
+ mOutputStream.flush();
+ }
+
/**
* write actual data.
*/
private void actualWrite(int b) throws IOException {
- out.write(b);
+ mOutputStream.write(b);
++mlActualByteWritten;
}
-
+
/**
* Get actual byte written.
*/
public long getByteWritten() {
return mlActualByteWritten;
}
-
+
/**
- * Is non ascii character ignored.
+ * Is non ascii character ignored.
* If true don't write non-ascii character.
- * Else first convert it to ascii by ANDing with 0x7F.
+ * Else first convert it to ascii by ANDing with 0x7F.
*/
public boolean getIsIgnoreNonAscii() {
return mbIgnoreNonAscii;
}
-
+
/**
* Set non-ascii ignore boolean value.
*/
public void setIsIgnoreNonAscii(boolean ig) {
- mbIgnoreNonAscii = ig;
+ mbIgnoreNonAscii = ig;
}
-}
+
+}
1.3 +1 -1 jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/AsyncMessageQueue.java
Index: AsyncMessageQueue.java
===================================================================
RCS file: /home/cvs/jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/AsyncMessageQueue.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- AsyncMessageQueue.java 10 Nov 2001 21:34:04 -0000 1.2
+++ AsyncMessageQueue.java 6 Mar 2002 13:42:57 -0000 1.3
@@ -76,4 +76,4 @@
return mbStopRequest;
}
-}
+}
\ No newline at end of file
1.4 +12 -3 jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/BaseProperties.java
Index: BaseProperties.java
===================================================================
RCS file: /home/cvs/jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/BaseProperties.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- BaseProperties.java 14 Dec 2001 01:22:04 -0000 1.3
+++ BaseProperties.java 6 Mar 2002 13:42:57 -0000 1.4
@@ -20,7 +20,7 @@
* @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
*/
public
-class BaseProperties extends Properties implements Serializable{
+class BaseProperties extends Properties {
/**
@@ -35,7 +35,16 @@
public BaseProperties(Properties prop) {
super(prop);
}
-
+
+ /**
+ * Load properties from file
+ */
+ public BaseProperties(File fl) throws IOException {
+ FileInputStream fis = new FileInputStream(fl);
+ load(fis);
+ fis.close();
+ }
+
/**
* Load properties from <code>InputStream</code>
*/
@@ -371,4 +380,4 @@
setProperty(key, val.getName());
}
-}
+}
\ No newline at end of file
1.4 +13 -135 jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/FileRegularFilter.java
Index: FileRegularFilter.java
===================================================================
RCS file: /home/cvs/jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/FileRegularFilter.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- FileRegularFilter.java 10 Nov 2001 21:34:04 -0000 1.3
+++ FileRegularFilter.java 6 Mar 2002 13:42:57 -0000 1.4
@@ -8,7 +8,9 @@
package org.apache.avalon.ftpserver.util;
-import java.io.*;
+import java.io.File;
+import java.io.FilenameFilter;
+import org.apache.avalon.ftpserver.util.RegularExpr;
/**
* This is regular expression filename filter.
@@ -18,14 +20,19 @@
public
class FileRegularFilter implements FilenameFilter {
- private char[] mcPattern;
+ private RegularExpr mRegularExpr = null;
/**
* Constructor.
* @param pattern regular expression
*/
public FileRegularFilter(String pattern) {
- mcPattern = pattern.toCharArray();
+ if ((pattern == null) || pattern.equals("") || pattern.equals("*")) {
+ mRegularExpr = null;
+ }
+ else {
+ mRegularExpr = new RegularExpr(pattern);
+ }
}
/**
@@ -34,138 +41,9 @@
* @param name - the name of the file.
*/
public boolean accept(File dir, String name) {
- return isMatch(name.toCharArray(), 0, 0);
- }
-
- /**
- * Compare the file with the regular expression.
- */
- private boolean isMatch(char[] fileName, int fileIndex, int patternIndex) {
-
- while(true) {
-
- // no more pattern characters
- // if no more fileName characters - return true
- if(patternIndex >= mcPattern.length) {
- return fileIndex == fileName.length;
- }
-
- char pc = mcPattern[patternIndex++];
- switch(pc) {
-
- // Match a single character in the range
- // If no more fileName character - return false
- case '[' :
- if(fileIndex >= fileName.length) {
- return false;
- }
- char fc = fileName[fileIndex++];
- char lastc = 0;
- boolean bMatch = false;
- boolean bNegete = false;
- boolean bFirst = true;
- while(true) {
-
- // no more pattern character - not properly
- // terminated - return false;
- if(patternIndex>=mcPattern.length) {
- return false;
- }
- pc = mcPattern[patternIndex++];
-
- // end character - break out the loop
- // if end bracket is the first character - return false
- if(pc == ']') {
- if(!bFirst) {
- break;
- }
- return false;
- }
-
- // if already matched - just read the rest
- if(bMatch) {
- continue;
- }
-
- // if the first character is the negete
- // character - inverse the matching condition
- if((pc == '^') && bFirst) {
- bNegete = true;
- continue;
- }
-
- bFirst = false;
-
- // '-' range check
- if(pc == '-') {
- if(patternIndex>=mcPattern.length) {
- return false;
- }
- pc = mcPattern[patternIndex++];
- if( (fc>=lastc) && (fc<=pc) ) {
- bMatch = true;
- if(bNegete) {
- return false;
- }
- continue;
- }
- lastc = pc;
- }
-
- // other - character match check
- else {
- lastc = pc;
- if(pc == fc) {
- bMatch = true;
- if(bNegete) {
- return false;
- }
- continue;
- }
- }
- }
-
- // no match - return false.
- if(!bMatch) {
- return false;
- }
- break;
-
-
- // * - skip zero or more characters
- // No more patern character - return true
- // Increment fileIndex till the rest of the pattern matches.
- case '*' :
- if(patternIndex >= mcPattern.length) {
- return true;
- }
- do {
- if(isMatch(fileName, fileIndex++, patternIndex)) {
- return true;
- }
- }
- while(fileIndex < fileName.length);
- return false;
-
-
- // ? - skip one character - increment fileIndex.
- // If no more fileName character - return false.
- case '?' :
- if(fileIndex >= fileName.length) {
- return false;
- }
- fileIndex++;
- break;
-
-
- // match one character.
- default:
- if( (fileIndex>=fileName.length) || (fileName[fileIndex++]!=pc) ) {
- return false;
- }
- break;
- }
+ if (mRegularExpr == null) {
+ return true;
}
+ return mRegularExpr.isMatch(name);
}
-
}
1.2 +49 -9 jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/IoUtils.java
Index: IoUtils.java
===================================================================
RCS file: /home/cvs/jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/IoUtils.java,v
retrieving revision 1.1
retrieving revision 1.2
diff -u -r1.1 -r1.2
--- IoUtils.java 28 Aug 2001 17:21:56 -0000 1.1
+++ IoUtils.java 6 Mar 2002 13:42:57 -0000 1.2
@@ -9,6 +9,7 @@
package org.apache.avalon.ftpserver.util;
import java.io.*;
+import java.util.Random;
/**
* IO utility methods.
@@ -17,7 +18,13 @@
*/
public
class IoUtils {
-
+
+ /**
+ * Random number generator to make unique file name
+ */
+ private final static Random RANDOM_GEN = new Random(System.currentTimeMillis());
+
+
/**
* Get a <code>BufferedInputStream</code>.
*/
@@ -31,7 +38,7 @@
}
return bin;
}
-
+
/**
* Get a <code>BufferedOutputStream</code>.
*/
@@ -45,7 +52,7 @@
}
return bout;
}
-
+
/**
* Get <code>BufferedReader</code>.
*/
@@ -59,7 +66,7 @@
}
return br;
}
-
+
/**
* Get <code>BufferedWriter</code>.
*/
@@ -74,7 +81,21 @@
return bw;
}
-
+ /**
+ * Get unique file object.
+ */
+ public static File getUniqueFile(File oldFile) {
+ File newFile = oldFile;
+ while (true) {
+ if (!newFile.exists()) {
+ break;
+ }
+ newFile = new File(oldFile.getAbsolutePath() + '.' + Math.abs(RANDOM_GEN.nextLong()));
+ }
+ return newFile;
+ }
+
+
/**
* No exception <code>InputStream</code> close method.
*/
@@ -82,8 +103,8 @@
if(is != null) {
try { is.close(); } catch(Exception ex) {}
}
- }
-
+ }
+
/**
* No exception <code>OutputStream</code> close method.
*/
@@ -92,7 +113,7 @@
try { os.close(); } catch(Exception ex) {}
}
}
-
+
/**
* No exception <code>java.io.Reader</code> close method.
*/
@@ -101,7 +122,7 @@
try { rd.close(); } catch(Exception ex) {}
}
}
-
+
/**
* No exception <code>java.io.Writer</code> close method.
*/
@@ -110,4 +131,23 @@
try { wr.close(); } catch(Exception ex) {}
}
}
+
+ /**
+ * Get exception stack trace.
+ */
+ public static String getStackTrace(Throwable ex) {
+ String result = "";
+ try {
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = new PrintWriter(sw);
+ ex.printStackTrace(pw);
+ pw.close();
+ sw.close();
+ result = sw.toString();
+ }
+ catch(Exception e) {
+ e.printStackTrace();
+ }
+ return result;
+ }
}
1.4 +0 -6 jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/PropertiesException.java
Index: PropertiesException.java
===================================================================
RCS file: /home/cvs/jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/PropertiesException.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -u -r1.3 -r1.4
--- PropertiesException.java 10 Nov 2001 21:34:04 -0000 1.3
+++ PropertiesException.java 6 Mar 2002 13:42:57 -0000 1.4
@@ -8,12 +8,6 @@
package org.apache.avalon.ftpserver.util;
-/**
- * This exception class is used by <code>BaseProperties</code> class.
- *
- * @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
- */
-
public
class PropertiesException extends Exception {
1.3 +1 -1 jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/Queue.java
Index: Queue.java
===================================================================
RCS file: /home/cvs/jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/Queue.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- Queue.java 10 Nov 2001 21:34:04 -0000 1.2
+++ Queue.java 6 Mar 2002 13:42:57 -0000 1.3
@@ -88,4 +88,4 @@
public synchronized void clear() {
mList.clear();
}
-}
+}
\ No newline at end of file
1.3 +270 -260 jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/VirtualDirectory.java
Index: VirtualDirectory.java
===================================================================
RCS file: /home/cvs/jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/VirtualDirectory.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- VirtualDirectory.java 8 Sep 2001 05:17:19 -0000 1.2
+++ VirtualDirectory.java 6 Mar 2002 13:42:57 -0000 1.3
@@ -9,9 +9,12 @@
package org.apache.avalon.ftpserver.util;
-import java.io.*;
-import java.text.*;
-import java.util.*;
+import java.io.File;
+import java.io.Serializable;
+import java.io.Writer;
+import java.io.IOException;
+import java.util.Date;
+import java.util.StringTokenizer;
/**
* This class is responsible to handle all virtual directory activities.
@@ -21,40 +24,21 @@
public
class VirtualDirectory implements Serializable {
- private final static String EMPTY = "";
private final static String NEWLINE = "\r\n";
private final static String DELIM = " ";
-
- private final static DecimalFormat TWO_DEC = new DecimalFormat("00");
- private final static TimeZone GMT_TZ = TimeZone.getTimeZone("GMT");
-
- private final static String[] MONTHS = {
- "Jan",
- "Feb",
- "Mar",
- "Apr",
- "May",
- "Jun",
- "Jul",
- "Aug",
- "Sep",
- "Oct",
- "Nov",
- "Dec"
- };
- private String mstRoot = "/";
+ private String mstRoot = "/";
private String mstCurrDir = "/";
private boolean mbWritePerm = false;
+
/**
* Default constructor does nothing
*/
public VirtualDirectory() {
}
-
-
+
/**
* Set write permission.
*/
@@ -63,7 +47,8 @@
}
/**
- * Set root directory.
+ * Set root directory. Root directory string will always
+ * end with '/'.
*/
public void setRootDirectory(File root) {
@@ -71,14 +56,30 @@
root = new File("/");
}
mstRoot = normalizeSeparateChar(root.getAbsolutePath());
-
- if(mstRoot.charAt(mstRoot.length() -1) != '/') {
+
+ // if not ends with '/' - add one
+ if(mstRoot.charAt(mstRoot.length()-1) != '/') {
+ mstRoot = mstRoot + '/';
+ }
+ mstCurrDir = "/";
+ }
+
+ /**
+ * Set root directory.
+ */
+ public void setRootDirectory(String root) throws IOException {
+ //File rootFile = new File(root).getCanonicalFile();
+ //setRootDirectory(rootFile);
+
+ mstRoot = normalizeSeparateChar(root);
+
+ // if not ends with '/' - add one
+ if(mstRoot.charAt(mstRoot.length()-1) != '/') {
mstRoot = mstRoot + '/';
}
mstCurrDir = "/";
}
-
/**
* Get write permission in this system
*/
@@ -103,103 +104,78 @@
/**
- * Change directory.
- * @param dirName change the current working directory.
- * @return true if success
+ * Get physical name (wrt the machine root).
*/
- public boolean changeDirectory(String dirName) {
-
- String dirIn = getAbsoluteDirectoryName(dirName);
- if(!dirIn.startsWith(mstRoot)) {
- return false;
- }
-
- File dirFl = new File(dirIn);
- if(dirFl.exists() && dirFl.isDirectory()) {
- mstCurrDir = dirIn.substring(mstRoot.length() - 1).trim();
- if(mstCurrDir.equals(EMPTY)) {
- mstCurrDir = "/";
- }
- return true;
- }
- return false;
+ public String getPhysicalName(String virtualName) {
+ virtualName = normalizeSeparateChar(virtualName);
+ return replaceDots(virtualName);
}
/**
- * Get file object.
+ * Get virtual name (wrt the virtual root).
+ * The return value will never end with '/' unless it is '/'.
*/
- public File getFileObject(String fileName) {
- String absname = getAbsoluteFileName(fileName);
- return new File(absname);
+ public String getAbsoluteName(String virtualName) {
+ virtualName = normalizeSeparateChar(virtualName);
+ String physicalName = replaceDots(virtualName);
+
+ String absoluteName = physicalName.substring(mstRoot.length()-1).trim();
+ return removeLastSlash(absoluteName);
}
/**
- * Get directory name (wrt the machine root).
+ * Get virtual name (wrt the virtual root). The virtual
+ * name will never end with '/' unless it is '/'.
*/
- public String getAbsoluteDirectoryName(String input) {
- String output = normalizeSeparateChar(input);
- output = replaceDots(output);
-
- if(output.charAt(output.length() - 1) != '/') {
- output = output + '/';
+ public String getVirtualName(String physicalName) {
+ physicalName = normalizeSeparateChar(physicalName);
+ if (!physicalName.startsWith(mstRoot)) {
+ return null;
}
- return output;
- }
-
-
- /**
- * Get file name (wrt the machine root).
- */
- public String getAbsoluteFileName(String input) {
- input = normalizeSeparateChar(input);
- input = replaceDots(input);
- return input;
- }
-
-
- /**
- * Get file name (wrt the root).
- */
- public String getVirtualFileName(String input) {
- String output = getAbsoluteFileName(input);
- output = output.substring(mstRoot.length() - 1).trim();
- return output;
- }
-
-
- /**
- * Get file owner.
- */
- public String getOwner(File fl) {
- return "user";
+
+ String virtualName = physicalName.substring(mstRoot.length()-1).trim();
+ return removeLastSlash(virtualName);
}
/**
- * Get group name
+ * Change directory. The current directory will never have '/'
+ * at the end unless it is '/'.
+ * @param dirName change the current working directory.
+ * @return true if success
*/
- public String getGroup(File fl) {
- return "group";
+ public boolean changeDirectory(String virtualDir) {
+
+ String physcialDir = getPhysicalName(virtualDir);
+ if (physcialDir.equals("")) {
+ physcialDir = "/";
+ }
+
+ File dirFl = new File(physcialDir);
+ if (dirFl.exists() && dirFl.isDirectory()) {
+ mstCurrDir = physcialDir.substring(mstRoot.length() - 1).trim();
+ mstCurrDir = removeLastSlash(mstCurrDir);
+ return true;
+ }
+
+ return false;
}
-
+
/**
* Check read permission.
*/
- public boolean hasReadPermission(String fileName, boolean bAbs) {
-
- if(!bAbs) {
- fileName = getAbsoluteFileName(fileName);
+ public boolean hasReadPermission(String fileName, boolean bPhysical) {
+ if(bPhysical) {
+ fileName = normalizeSeparateChar(fileName);
}
else {
- fileName = normalizeSeparateChar(fileName);
+ fileName = getPhysicalName(fileName);
}
- // not in directory - no permission
- String root = getRootDirectory();
- if(!fileName.startsWith(root)) {
+ if(!fileName.startsWith(mstRoot)) {
return false;
}
@@ -210,23 +186,22 @@
/**
* Chech file write/delete permission.
*/
- public boolean hasWritePermission(String fileName, boolean bAbs) {
+ public boolean hasWritePermission(String fileName, boolean bPhysical) {
// no write permission
if(!mbWritePerm) {
return false;
}
-
- if(!bAbs) {
- fileName = getAbsoluteFileName(fileName);
+
+ // if virtual name - get the physical name
+ if(bPhysical) {
+ fileName = normalizeSeparateChar(fileName);
}
else {
- fileName = normalizeSeparateChar(fileName);
+ fileName = getPhysicalName(fileName);
}
- // not in root directory
- String root = getRootDirectory();
- if(!fileName.startsWith(root)) {
+ if(!fileName.startsWith(mstRoot)) {
return false;
}
@@ -237,109 +212,30 @@
/**
* Check file create permission.
*/
- public boolean hasCreatePermission(String fileName, boolean bAbs) {
-
+ public boolean hasCreatePermission(String fileName, boolean bPhysical) {
+
// no write permission
if(!mbWritePerm) {
return false;
}
-
- if(!bAbs) {
- fileName = getAbsoluteFileName(fileName);
- }
- else {
+
+ // if virtual name - get the physical name
+ if(bPhysical) {
fileName = normalizeSeparateChar(fileName);
}
-
- // not in root directory
- String root = getRootDirectory();
- return fileName.startsWith(root);
- }
-
-
- /**
- * Get link count
- */
- public String getLinkCount(File fl) {
- if(fl.isDirectory()) {
- return String.valueOf(3);
- }
else {
- return String.valueOf(1);
- }
- }
-
-
- /**
- * Get size
- */
- public String getLength(File fl) {
- String initStr = " ";
- long sz = 0;
- if(fl.isFile()) {
- sz = fl.length();
- }
- String szStr = String.valueOf(sz);
- if(szStr.length() > initStr.length()) {
- return szStr;
- }
- return initStr.substring(0, initStr.length() - szStr.length()) + szStr;
- }
-
-
- /**
- * Get last modified date string.
- */
- public String getLastModified(File fl) {
- long modTime = fl.lastModified();
- GregorianCalendar gc = new GregorianCalendar();
- gc.setTimeZone(GMT_TZ);
- gc.setTime(new Date(modTime));
-
- long currTime = System.currentTimeMillis();
- boolean bYear = false;
- if(((currTime - modTime)/(24*60*60*1000)) > 200) {
- bYear = true;
- }
-
- StringBuffer sb = new StringBuffer();
- sb.append(MONTHS[gc.get(Calendar.MONTH) - Calendar.JANUARY]).
- append(' ').
- append( TWO_DEC.format(gc.get(Calendar.DAY_OF_MONTH)) );
-
- if(bYear) {
- sb.append(" ").
- append(gc.get(Calendar.YEAR));
- }
- else {
- sb.append(' ').
- append(TWO_DEC.format(gc.get(Calendar.HOUR_OF_DAY))).
- append(':').
- append(TWO_DEC.format(gc.get(Calendar.MINUTE)));
- }
-
- return sb.toString();
- }
-
- /**
- * Get file name.
- */
- public String getName(File fl) {
- String flName = fl.getName();
- flName = normalizeSeparateChar(flName);
-
- int lastIndex = flName.lastIndexOf("/");
- if(lastIndex == -1) {
- return flName;
- }
- else {
- return flName.substring(lastIndex + 1);
+ fileName = getPhysicalName(fileName);
}
+
+ return fileName.startsWith(mstRoot);
}
/**
* Print file list. Detail listing.
+ * <pre>
+ * -a : display all (including hidden files)
+ * </pre>
* @return true if success
*/
public boolean printList(String argument, Writer out) throws IOException {
@@ -351,13 +247,14 @@
// get options, directory name and pattern
if(argument != null) {
argument = argument.trim();
- StringBuffer optionsSb = new StringBuffer(16);
+ StringBuffer optionsSb = new StringBuffer(4);
StringTokenizer st = new StringTokenizer(argument, " ");
while(st.hasMoreTokens()) {
String token = st.nextToken();
if(token.charAt(0) == '-') {
- optionsSb.append(token);
- optionsSb.append(' ');
+ if (token.length() > 1) {
+ optionsSb.append(token.substring(1));
+ }
}
else {
lsDirName = token;
@@ -365,22 +262,20 @@
}
options = optionsSb.toString();
}
- lsDirName = normalizeSeparateChar(lsDirName);
- lsDirName = replaceDots(lsDirName);
- if(lsDirName.charAt(lsDirName.length()-1) != '/') {
- File tempFile = new File(lsDirName);
- if(!tempFile.isDirectory() ) {
- int slashIndex = lsDirName.lastIndexOf('/');
- if(slashIndex != -1) {
- pattern = lsDirName.substring(slashIndex+1);
- lsDirName = lsDirName.substring(0, slashIndex+1);
- }
- }
- }
+
+ // check options
boolean bAll = options.indexOf('a') != -1;
- boolean bDetail = options.indexOf('l') != -1;
-
- // now list the directory
+ boolean bDetail = options.indexOf('l') != -1;
+
+ // check pattern
+ lsDirName = getPhysicalName(lsDirName);
+ int slashIndex = lsDirName.lastIndexOf('/');
+ if( (slashIndex != -1) && (slashIndex != (lsDirName.length() -1)) ) {
+ pattern = lsDirName.substring(slashIndex+1);
+ lsDirName = lsDirName.substring(0, slashIndex+1);
+ }
+
+ // check directory
File lstDirObj = new File(lsDirName);
if(!lstDirObj.exists()) {
return false;
@@ -388,9 +283,20 @@
if(!lstDirObj.isDirectory()) {
return false;
}
- File flLst[] = lstDirObj.listFiles(new FileRegularFilter(pattern));
+
+ // now print
+ File flLst[];
+ if ( (pattern == null) || pattern.equals("*") || pattern.equals("") ) {
+ flLst = lstDirObj.listFiles();
+ }
+ else {
+ flLst = lstDirObj.listFiles(new FileRegularFilter(pattern));
+ }
for(int i=0; i<flLst.length; i++) {
- printLine(lsDirName, flLst[i], out);
+ if ( (!bAll) && flLst[i].isHidden() ) {
+ continue;
+ }
+ printLine(flLst[i], out);
out.write(NEWLINE);
}
return true;
@@ -399,10 +305,14 @@
/**
* Print file list.
+ * <pre>
+ * -l : detail listing
+ * -a : display all (including hidden files)
+ * </pre>
* @return true if success
*/
public boolean printNList(String argument, Writer out) throws IOException {
-
+
String lsDirName = "./";
String options = "";
String pattern = "*";
@@ -410,13 +320,14 @@
// get options, directory name and pattern
if(argument != null) {
argument = argument.trim();
- StringBuffer optionsSb = new StringBuffer(16);
+ StringBuffer optionsSb = new StringBuffer(4);
StringTokenizer st = new StringTokenizer(argument, " ");
while(st.hasMoreTokens()) {
String token = st.nextToken();
if(token.charAt(0) == '-') {
- optionsSb.append(token);
- optionsSb.append(' ');
+ if (token.length() > 1) {
+ optionsSb.append(token.substring(1));
+ }
}
else {
lsDirName = token;
@@ -424,22 +335,20 @@
}
options = optionsSb.toString();
}
- lsDirName = normalizeSeparateChar(lsDirName);
- lsDirName = replaceDots(lsDirName);
- if(lsDirName.charAt(lsDirName.length()-1) != '/') {
- File tempFile = new File(lsDirName);
- if(!tempFile.isDirectory() ) {
- int slashIndex = lsDirName.lastIndexOf('/');
- if(slashIndex != -1) {
- pattern = lsDirName.substring(slashIndex+1);
- lsDirName = lsDirName.substring(0, slashIndex+1);
- }
- }
- }
+
+ // check options
boolean bAll = options.indexOf('a') != -1;
boolean bDetail = options.indexOf('l') != -1;
- // now list the directory
+ // check pattern
+ lsDirName = getPhysicalName(lsDirName);
+ int slashIndex = lsDirName.lastIndexOf('/');
+ if( (slashIndex != -1) && (slashIndex != (lsDirName.length() -1)) ) {
+ pattern = lsDirName.substring(slashIndex+1);
+ lsDirName = lsDirName.substring(0, slashIndex+1);
+ }
+
+ // check directory
File lstDirObj = new File(lsDirName);
if(!lstDirObj.exists()) {
return false;
@@ -447,10 +356,21 @@
if(!lstDirObj.isDirectory()) {
return false;
}
- File flLst[] = lstDirObj.listFiles(new FileRegularFilter(pattern));
+
+ // now print
+ File flLst[];
+ if ( (pattern == null) || pattern.equals("*") || pattern.equals("") ) {
+ flLst = lstDirObj.listFiles();
+ }
+ else {
+ flLst = lstDirObj.listFiles(new FileRegularFilter(pattern));
+ }
for(int i=0; i<flLst.length; i++) {
+ if ( (!bAll) && flLst[i].isHidden() ) {
+ continue;
+ }
if(bDetail) {
- printLine(lsDirName, flLst[i], out);
+ printLine(flLst[i], out);
}
else {
out.write(getName(flLst[i]));
@@ -460,38 +380,103 @@
return true;
}
+ /**
+ * Get file owner.
+ */
+ private String getOwner(File fl) {
+ return "user";
+ }
+
+
+ /**
+ * Get group name
+ */
+ private String getGroup(File fl) {
+ return "group";
+ }
+
/**
- * Get permission string.
+ * Get link count
*/
- private String getPermission(String dirName, File fl) {
+ private String getLinkCount(File fl) {
+ if(fl.isDirectory()) {
+ return String.valueOf(3);
+ }
+ else {
+ return String.valueOf(1);
+ }
+ }
+
+
+ /**
+ * Get size
+ */
+ private String getLength(File fl) {
+ String initStr = " ";
+ long sz = 0;
+ if(fl.isFile()) {
+ sz = fl.length();
+ }
+ String szStr = String.valueOf(sz);
+ if(szStr.length() > initStr.length()) {
+ return szStr;
+ }
+ return initStr.substring(0, initStr.length() - szStr.length()) + szStr;
+ }
+
+
+ /**
+ * Get last modified date string.
+ */
+ private String getLastModified(File fl) {
+ long modTime = fl.lastModified();
+ Date date = new Date(modTime);
+ return DateUtils.getUnixDate(date);
+ }
- // add slash if necessary
- if(dirName.charAt(dirName.length() - 1) != '/') {
- dirName += '/';
+ /**
+ * Get file name.
+ */
+ private String getName(File fl) {
+ String flName = fl.getName();
+ flName = normalizeSeparateChar(flName);
+
+ int lastIndex = flName.lastIndexOf("/");
+ if(lastIndex == -1) {
+ return flName;
+ }
+ else {
+ return flName.substring(lastIndex + 1);
}
- String fileName = dirName + getName(fl);
+ }
+
+
+ /**
+ * Get permission string.
+ */
+ private String getPermission(File fl) {
- StringBuffer sb = new StringBuffer(10);
+ StringBuffer sb = new StringBuffer(13);
if(fl.isDirectory()) {
sb.append('d');
}
else {
sb.append('-');
}
-
- if(hasReadPermission(fileName, true)) {
- sb.append('r');
+
+ if (fl.canRead()) {
+ sb.append('r');
}
else {
- sb.append('-');
+ sb.append('-');
}
-
- if(hasWritePermission(fileName, true)) {
- sb.append('w');
+
+ if (mbWritePerm && fl.canWrite()) {
+ sb.append('w');
}
else {
- sb.append('-');
+ sb.append('-');
}
sb.append("-------");
return sb.toString();
@@ -509,10 +494,11 @@
/**
- * Replace dots. Returns machine absolute path.
+ * Replace dots. Returns physical name.
+ * @param inArg the virtaul name
*/
private String replaceDots(String inArg) {
-
+
// get the starting directory
String resArg;
if(inArg.charAt(0) != '/') {
@@ -520,11 +506,14 @@
}
else {
resArg = mstRoot;
- }
+ }
+
+ // strip last '/'
if(resArg.charAt(resArg.length() -1) == '/') {
- resArg = resArg.substring(0, resArg.length() -1);
+ resArg = resArg.substring(0, resArg.length()-1);
}
-
+
+ // replace ., ~ and ..
StringTokenizer st = new StringTokenizer(inArg, "/");
while(st.hasMoreTokens()) {
@@ -545,7 +534,13 @@
}
continue;
}
-
+
+ // ~ => home directory (in this case /)
+ if (tok.equals("~")) {
+ resArg = mstRoot.substring(0, mstRoot.length()-1).trim();
+ continue;
+ }
+
resArg = resArg + '/' + tok;
}
@@ -554,6 +549,11 @@
resArg = resArg + '/';
}
+ // final check
+ if (resArg.length() < mstRoot.length()) {
+ resArg = mstRoot;
+ }
+
return resArg;
}
@@ -561,8 +561,8 @@
/**
* Get each directory line.
*/
- private void printLine(String dirName, File fl, Writer out) throws IOException {
- out.write(getPermission(dirName, fl));
+ private void printLine(File fl, Writer out) throws IOException {
+ out.write(getPermission(fl));
out.write(DELIM);
out.write(DELIM);
out.write(DELIM);
@@ -577,6 +577,16 @@
out.write(getLastModified(fl));
out.write(DELIM);
out.write(getName(fl));
+ }
+
+ /**
+ * If the string is not '/', remove last slash.
+ */
+ private String removeLastSlash(String str) {
+ if ( (str.length()>1) && (str.charAt(str.length()-1)=='/') ) {
+ str = str.substring(0, str.length()-1);
+ }
+ return str;
}
}
1.1 jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/DateUtils.java
Index: DateUtils.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*/
package org.apache.avalon.ftpserver.util;
import java.util.*;
import java.text.*;
/**
* This is a timezone conversion utility class.
*
* @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
*/
public class DateUtils {
private final static String[] MONTHS = {
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
};
private final static DateFormat AFTER_SIX = new SimpleDateFormat(" yyyy");
private final static DateFormat BEFORE_SIX = new SimpleDateFormat("HH:mm");
/**
* Get unix style date string
*/
public static String getUnixDate(Date date) {
long dateTime = date.getTime();
if (dateTime < 0) {
return "------------";
}
Calendar cal = new GregorianCalendar();
cal.setTime(date);
String firstPart = MONTHS[cal.get(Calendar.MONTH)] + ' ';
String dateStr = String.valueOf(cal.get(Calendar.DATE));
if (dateStr.length() == 1) {
dateStr = " " + dateStr;
}
firstPart += dateStr + ' ';
long nowTime = System.currentTimeMillis();
if ( Math.abs(nowTime - dateTime) > 183L * 24L * 60L * 60L * 1000L) {
return firstPart + AFTER_SIX.format(date);
}
else {
return firstPart + BEFORE_SIX.format(date);
}
}
/**
* Get the timezone specific string.
*/
public static String getString(Date dt, DateFormat df, TimeZone to) {
df.setTimeZone(to);
return df.format(dt);
}
/**
* Get the timezone specific calendar.
*/
public static Calendar getCalendar(Date dt, TimeZone to) {
Calendar cal = Calendar.getInstance(to);
cal.setTime(dt);
return cal;
}
/**
* Get date object.
*/
public static Date getDate(String str, DateFormat df, TimeZone from)
throws java.text.ParseException {
df.setTimeZone(from);
return df.parse(str);
}
/**
* Get date difference => d1 - d2.
*/
public static String getDifference(Date d1, Date d2) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(d2);
int year2 = calendar.get(Calendar.YEAR);
int day2 = calendar.get(Calendar.DAY_OF_YEAR);
int hour2 = calendar.get(Calendar.HOUR_OF_DAY);
int min2 = calendar.get(Calendar.MINUTE);
calendar.setTime(d1);
int year1 = calendar.get(Calendar.YEAR);
int day1 = calendar.get(Calendar.DAY_OF_YEAR);
int hour1 = calendar.get(Calendar.HOUR_OF_DAY);
int min1 = calendar.get(Calendar.MINUTE);
int leftDays = (day1-day2)+(year1-year2)*365;
int leftHours = hour1-hour2;
int leftMins = min1 - min2;
if(leftMins < 0) {
leftMins += 60;
--leftHours;
}
if(leftHours < 0) {
leftHours += 24;
--leftDays;
}
String interval = "";
if(leftDays > 0) {
interval = leftDays + " Days";
}
else if((leftHours > 0) && (leftDays == 0)) {
interval = leftHours + " Hours";
}
else if((leftMins > 0) && (leftHours == 0) && (leftDays == 0)) {
interval = leftMins + " Minutes";
}
else {
interval = "";
}
return interval;
}
}
1.1 jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/EncryptUtils.java
Index: EncryptUtils.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*/
package org.apache.avalon.ftpserver.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* String encryption utility methods.
*
* @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
*/
public
class EncryptUtils {
/**
* Encrypt byte array.
*/
public static byte[] encrypt(byte[] source, String algorithm) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.reset();
md.update(source);
return md.digest();
}
/**
* Encrypt string
*/
public static String encrypt(String source, String algorithm) throws NoSuchAlgorithmException {
byte[] resByteArray = encrypt(source.getBytes(), algorithm);
return toHexString(resByteArray);
}
/**
* Get hex string
*/
public static String toHexString(byte[] res) {
StringBuffer sb = new StringBuffer();
for(int i=0; i<res.length; i++) {
sb.append(Integer.toHexString(0xFF & res[i]));
}
return sb.toString().toUpperCase();
}
/**
* Encrypt string using MD5 algorithm
*/
public static String encryptMD5(String source) {
if (source == null) {
source = "";
}
String result = "";
try {
result = encrypt(source, "MD5");
}
catch(NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return result;
}
/**
* Encrypt string using SHA algorithm
*/
public static String encryptSHA(String source) {
if (source == null) {
source = "";
}
String result = "";
try {
result = encrypt(source, "SHA");
}
catch(NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return result;
}
}
1.1 jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util/RegularExpr.java
Index: RegularExpr.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*/
package org.apache.avalon.ftpserver.util;
/**
* This is a simplified regular character mattching class.
* Supports *?^[]- pattern characters.
*
* @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
*/
public
class RegularExpr {
private char[] mcPattern;
/**
* Constructor.
* @param pattern regular expression
*/
public RegularExpr(String pattern) {
mcPattern = pattern.toCharArray();
}
/**
* Compare string with a regular expression.
*/
public boolean isMatch(String name) {
return isMatch(name.toCharArray(), 0, 0);
}
/**
* Is a match?
*/
private boolean isMatch(char[] strName, int strIndex, int patternIndex) {
while(true) {
// no more pattern characters
// if no more strName characters - return true
if(patternIndex >= mcPattern.length) {
return strIndex == strName.length;
}
char pc = mcPattern[patternIndex++];
switch(pc) {
// Match a single character in the range
// If no more strName character - return false
case '[' :
// no more string character - returns false
// example : pattern = ab[^c] and string = ab
if(strIndex >= strName.length) {
return false;
}
char fc = strName[strIndex++];
char lastc = 0;
boolean bMatch = false;
boolean bNegete = false;
boolean bFirst = true;
while(true) {
// single character match
// no more pattern character - error condition.
if(patternIndex>=mcPattern.length) {
return false;
}
pc = mcPattern[patternIndex++];
// end character - break out the loop
// if end bracket is the first character - always a match.
// example pattern - [], [^]
if(pc == ']') {
if (bFirst) {
bMatch = true;
}
break;
}
// if already matched - just read the rest till we get ']'.
if(bMatch) {
continue;
}
// if the first character is the negete
// character - inverse the matching condition
if((pc == '^') && bFirst) {
bNegete = true;
continue;
}
bFirst = false;
// '-' range check
if(pc == '-') {
// pattern string is [a- error condition.
if(patternIndex>=mcPattern.length) {
return false;
}
// read the high range character and compare.
pc = mcPattern[patternIndex++];
bMatch = (fc>=lastc) && (fc<=pc);
if (bNegete) {
bMatch = !bMatch;
}
lastc = pc;
}
// Single character match check. It might also be the
// low range character.
else {
lastc = pc;
bMatch = pc == fc;
if (bNegete) {
bMatch = !bMatch;
}
}
}
// no match - return false.
if(!bMatch) {
return false;
}
break;
// * - skip zero or more characters
// No more patern character - return true
// Increment strIndex till the rest of the pattern matches.
case '*' :
// no more string character remaining - returns true
if(patternIndex >= mcPattern.length) {
return true;
}
// compare rest of the string
do {
if(isMatch(strName, strIndex++, patternIndex)) {
return true;
}
}
while(strIndex < strName.length);
// Example pattern is (a*b) and the string is (adfdc).
return false;
// ? - skip one character - increment strIndex.
// If no more strName character - return false.
case '?' :
// already at the end - no more character - returns false
if(strIndex >= strName.length) {
return false;
}
strIndex++;
break;
// match character.
default:
// already at the end - no match
if (strIndex >= strName.length) {
return false;
}
// the characters are not equal - no match
if(strName[strIndex++] != pc) {
return false;
}
break;
}
}
}
}
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>
Re: cvs commit: jakarta-avalon-apps/ftpserver/src/java/org/apache/avalon/ftpserver/util DateUtils.java EncryptUtils.java RegularExpr.java AsciiOutputStream.java AsyncMessageQueue.java BaseProperties.java FileRegularFilter.java IoUtils.java PropertiesException.java Queue.java VirtualDirectory.java AsciiInputStream.java
Posted by Peter Donald <pe...@apache.org>.
Welcome back!
On Thu, 7 Mar 2002 00:42, rana_b@apache.org wrote:
> rana_b 02/03/06 05:42:57
>
> Modified: ftpserver/src/java/org/apache/avalon/ftpserver/util
> AsciiOutputStream.java AsyncMessageQueue.java
> BaseProperties.java FileRegularFilter.java
> IoUtils.java PropertiesException.java Queue.java
> VirtualDirectory.java
> Added: ftpserver/src/java/org/apache/avalon/ftpserver/util
> DateUtils.java EncryptUtils.java RegularExpr.java
> Removed: ftpserver/src/java/org/apache/avalon/ftpserver/util
> AsciiInputStream.java
> Log:
> second stage of refactoring
--
Cheers,
Pete
-----------------------------------------------
"Only two things are infinite, the universe and
human stupidity, and I'm not sure about the
former." -Albert Einstein
-----------------------------------------------
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>