diff --git a/src/zutil/converters/Converter.java b/src/zutil/converters/Converter.java index 3dd009c..ea95092 100644 --- a/src/zutil/converters/Converter.java +++ b/src/zutil/converters/Converter.java @@ -22,23 +22,19 @@ package zutil.converters; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.util.BitSet; - import zutil.io.DynamicByteArrayStream; +import java.io.*; +import java.util.BitSet; + public class Converter { private Converter(){} /** * Converts an object to an array of bytes. * - * @param object the object to convert. - * @return the associated byte array. + * @param object the object to convert. + * @return the associated byte array. */ public static byte[] toBytes(Object object) throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -55,7 +51,7 @@ public class Converter { * Converts a Integer to an byte array * * @param num is the number to convert - * @return an byte array of four bytes + * @return a byte array of four bytes */ public static byte[] toBytes(int num){ return new byte[]{ @@ -69,7 +65,7 @@ public class Converter { * Converts a Integer to a byte * * @param num is the number to convert - * @return an byte + * @return a byte value of the integer */ public static byte toByte(int num){ return (byte)(num & 0xff); @@ -78,9 +74,9 @@ public class Converter { /** * Converts hex chars to a byte * - * @param quad1 is the first hex value - * @param quad2 is the second hex value - * @return a byte that corresponds to the hex + * @param quad1 is the first hex value + * @param quad2 is the second hex value + * @return a byte that corresponds to the hex */ public static int hexToByte( char quad1, char quad2){ byte b = hexToByte( quad2 ); @@ -91,8 +87,8 @@ public class Converter { /** * Converts a hex chars to a byte * - * @param quad1 is the hex value - * @return a byte that corresponds to the hex + * @param hex is the hex value + * @return a byte that corresponds to the hex */ public static byte hexToByte( char hex ){ switch( Character.toLowerCase(hex) ){ @@ -120,8 +116,8 @@ public class Converter { * Converts an array of bytes back to its constituent object. The * input array is assumed to have been created from the original object. * - * @param bytes the byte array to convert. - * @return the associated object. + * @param bytes the byte array to convert. + * @return the associated object. */ public static Object toObject(byte[] bytes) throws Exception{ Object object = null; @@ -137,8 +133,8 @@ public class Converter { * Converts an array of bytes back to its constituent object. The * input array is assumed to have been created from the original object. * - * @param bytes the byte array to convert. - * @return the associated object. + * @param bytes the byte array to convert. + * @return the associated object. */ public static Object toObject(DynamicByteArrayStream bytes) throws Exception{ Object object = null; @@ -153,9 +149,9 @@ public class Converter { /** * Checks if the given interface is implemented in the object * - * @param object the object to look for the interface - * @param interf the interface to look for - * @return true if the interface is implemented else false + * @param object the object to look for the interface + * @param interf the interface to look for + * @return true if the interface is implemented else false */ public static boolean isInstanceOf(Object object, Class interf){ Class[] objectInterf = object.getClass().getInterfaces(); @@ -172,8 +168,8 @@ public class Converter { /** * Converts a byte Array to a Hex String * - * @param raw the byte array to convert - * @return a Hex String + * @param raw the byte array to convert + * @return a hex String */ public static String toHexString(byte[][] raw){ StringBuffer ret = new StringBuffer(); @@ -204,8 +200,8 @@ public class Converter { /** * Converts a byte Array to a Hex String * - * @param raw the byte array to convert - * @return a Hex String + * @param raw the byte array to convert + * @return a hex String */ public static String toHexString(byte[] raw){ StringBuffer ret = new StringBuffer(); @@ -221,8 +217,8 @@ public class Converter { /** * Converts a byte to a Hex String * - * @param raw the byte to convert - * @return a Hex String + * @param raw the byte to convert + * @return a hex String */ public static String toHexString(byte raw){ String ret = ""+HEX_CHARS[(int) (raw >>> 0x04)& 0x0F ]; @@ -234,8 +230,8 @@ public class Converter { /** * Converts the given byte to a String with 1's and 0's * - * @param raw the byte to convert - * @return a String with 1's and 0's + * @param raw the byte to convert + * @return a String with 1's and 0's */ public static String toString(byte raw){ StringBuffer ret = new StringBuffer(); @@ -248,8 +244,8 @@ public class Converter { /** * Converts the given byte array to a String with 1's and 0's * - * @param raw the byte array to convert - * @return a String with 1's and 0's + * @param raw the byte array to convert + * @return a String with 1's and 0's */ public static String toString(byte[] raw){ StringBuffer ret = new StringBuffer(); @@ -264,8 +260,8 @@ public class Converter { /** * Converts a BitSet to a Integer * - * @param bits the BitSet to convert - * @return a Integer + * @param bits the BitSet to convert + * @return a Integer */ public static int toInt(BitSet bits){ int ret = 0; @@ -280,8 +276,8 @@ public class Converter { /** * Converts a boolean array(bit sequence whit most significant bit at index 0) to a Integer * - * @param bits the boolean array to convert - * @return a Integer + * @param bits the boolean array to convert + * @return a Integer */ public static int toInt(boolean[] bits){ int ret = 0; @@ -296,8 +292,8 @@ public class Converter { /** * Converts a byte to a integer * - * @param num is the byte to convert - * @return an integer + * @param b is the byte to convert + * @return the integer value of the byte */ public static int toInt(byte b){ return (int)(b & 0xff); @@ -306,8 +302,8 @@ public class Converter { /** * Converts a Integer to a BitSet * - * @param i the Integer to convert - * @return a BitSet object + * @param num the Integer to convert + * @return a BitSet object */ public static BitSet toBitSet(int num){ BitSet ret = new BitSet(); @@ -323,10 +319,10 @@ public class Converter { /** * Converts a given String to a specified class * - * @param is the resulting class - * @param data is the String data to be converted - * @param c is the class to convert to - * @return a instance of the class with the value in the string or null if there was an problem + * @param is the resulting class + * @param data is the String data to be converted + * @param c is the class to convert to + * @return a instance of the class with the value in the string or null if there was an problem */ @SuppressWarnings("unchecked") public static T fromString(String data, Class c){ diff --git a/src/zutil/db/DBQueue.java b/src/zutil/db/DBQueue.java index e3f6d87..ca8fec4 100644 --- a/src/zutil/db/DBQueue.java +++ b/src/zutil/db/DBQueue.java @@ -22,6 +22,9 @@ package zutil.db; +import zutil.converters.Converter; +import zutil.io.MultiPrintStream; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -30,31 +33,28 @@ import java.util.Collection; import java.util.Iterator; import java.util.Queue; -import zutil.converters.Converter; -import zutil.io.MultiPrintStream; - /** - * This class creates a queue that stors the + * This class creates a queue that stores the * data in a mysql table. * The table should look like this: + *
  * CREATE TABLE `queue` (
  * 		`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
  * 		`data` BINARY NOT NULL
  * 	);
+ * 	
* @author Ziver * */ public class DBQueue implements Queue{ - // GO TO KNOW = SELECT LAST_INSERT_ID() as pos_id private DBConnection db; private String table; /** * Initiates the queue.
- * WARNING!! this will erase all rows in the table * - * @param db is the connection to the DB - * @param table is the name of the table + * @param db is the connection to the DB + * @param table is the name of the table */ public DBQueue(DBConnection db, String table){ this.db = db; @@ -63,8 +63,9 @@ public class DBQueue implements Queue{ public boolean add(Object arg0){ try { - PreparedStatement sql = db.getPreparedStatement("INSERT INTO "+table+" (data) VALUES(?)"); - sql.setObject(1, arg0); + PreparedStatement sql = db.getPreparedStatement("INSERT INTO ? (data) VALUES(?)"); + sql.setObject(1, table); + sql.setObject(2, arg0); DBConnection.exec(sql); } catch (Exception e) { e.printStackTrace(MultiPrintStream.out); @@ -81,7 +82,6 @@ public class DBQueue implements Queue{ return add(arg0); } - @SuppressWarnings("unchecked") public synchronized E peek() { try { return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler(){ @@ -101,7 +101,6 @@ public class DBQueue implements Queue{ return null; } - @SuppressWarnings("unchecked") public synchronized E poll() { try { return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler(){ @@ -207,7 +206,6 @@ public class DBQueue implements Queue{ return null; } - @SuppressWarnings("unchecked") public E[] toArray(Object[] arg0) { // TODO Auto-generated method stub return null; diff --git a/src/zutil/db/bean/DBBeanSQLResultHandler.java b/src/zutil/db/bean/DBBeanSQLResultHandler.java index 7696d3b..2b9a09a 100644 --- a/src/zutil/db/bean/DBBeanSQLResultHandler.java +++ b/src/zutil/db/bean/DBBeanSQLResultHandler.java @@ -42,7 +42,7 @@ import zutil.db.bean.DBBean.DBLinkTable; import zutil.log.LogUtil; public class DBBeanSQLResultHandler implements SQLResultHandler{ - public static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); /** This is the time to live for the cached items **/ public static final long CACHE_TTL = 1000*60*5; // 5 min in ms /** A cache for detecting recursion **/ diff --git a/src/zutil/io/DynamicByteArrayStream.java b/src/zutil/io/DynamicByteArrayStream.java index 72593a7..8bc1a6a 100644 --- a/src/zutil/io/DynamicByteArrayStream.java +++ b/src/zutil/io/DynamicByteArrayStream.java @@ -29,13 +29,13 @@ import java.util.ArrayList; public class DynamicByteArrayStream extends InputStream{ /** The byte array container */ private ArrayList bytes; - /** The current size of the stream */ + /** Current virtual size of the stream */ private int size; - /** points to the current index in the ArrayList */ - private int byteArrayIndex; - /** points locally in the current index in the ArrayList */ - private int localPointer; - /** The current position */ + /** Points the current byte array index */ + private int arrayIndex; + /** Points to a local index in the current byte array */ + private int arrayLocalIndex; + /** Current virtual position of the stream */ private int pos; /** @@ -44,8 +44,8 @@ public class DynamicByteArrayStream extends InputStream{ public DynamicByteArrayStream(){ bytes = new ArrayList(); size = 0; - byteArrayIndex = 0; - localPointer = 0; + arrayIndex = 0; + arrayLocalIndex = 0; pos = 0; } @@ -61,7 +61,7 @@ public class DynamicByteArrayStream extends InputStream{ /** * Append an byte array to the stream. - * WARNING: This function will copy data. + * NOTE: This function will copy data. * * @param b is the byte array to add * @param offset is the offset in the byte array @@ -70,7 +70,7 @@ public class DynamicByteArrayStream extends InputStream{ public synchronized void append(byte[] b, int offset, int length){ byte[] new_b = new byte[length]; System.arraycopy(b, offset, new_b, 0, length); - bytes.add(b); + bytes.add(new_b); size += length; } @@ -78,12 +78,12 @@ public class DynamicByteArrayStream extends InputStream{ public synchronized int read() throws IOException { if(pos >= size) return -1; - int ret = bytes.get(byteArrayIndex)[localPointer] & 0xff; + int ret = bytes.get(arrayIndex)[arrayLocalIndex] & 0xff; pos++; - localPointer++; - if(localPointer >= bytes.get(byteArrayIndex).length){ - byteArrayIndex++; - localPointer = 0; + arrayLocalIndex++; + if(arrayLocalIndex >= bytes.get(arrayIndex).length){ + arrayIndex++; + arrayLocalIndex = 0; } return ret; } @@ -91,27 +91,27 @@ public class DynamicByteArrayStream extends InputStream{ public synchronized int read(byte b[], int off, int len) { if(len <= 0) return 0; if(pos >= size) return -1; - - int bytes_read = 0; + + int bytes_read=0; if(pos+len >= size) len = size - pos; - for(int i=0; i= src.length){ - int length = src.length-localPointer; - System.arraycopy(src, localPointer, b, off+i, length); + for(; bytes_read= src.length){ + int length = src.length- arrayLocalIndex; + System.arraycopy(src, arrayLocalIndex, b, off+bytes_read, length); - localPointer = 0; - byteArrayIndex++; + arrayLocalIndex = 0; + arrayIndex++; bytes_read += length; - i += length; } + // Read length is SHORTER than local array else{ - int length = len-i; - System.arraycopy(src, localPointer, b, off+i, length); + int length = len-bytes_read; + System.arraycopy(src, arrayLocalIndex, b, off+bytes_read, length); - localPointer += length; + arrayLocalIndex += length; bytes_read += length; - i += length; } } pos += len; @@ -132,8 +132,8 @@ public class DynamicByteArrayStream extends InputStream{ } public synchronized void reset() { - byteArrayIndex = 0; - localPointer = 0; + arrayIndex = 0; + arrayLocalIndex = 0; pos = 0; } @@ -144,7 +144,7 @@ public class DynamicByteArrayStream extends InputStream{ /** * @return all of the buffers content as a byte array. */ - public byte[] getByte(){ + public byte[] getBytes(){ byte[] data = new byte[size]; this.read(data, 0, size); return data; @@ -154,10 +154,9 @@ public class DynamicByteArrayStream extends InputStream{ /** * WARNING: This function might return a malformed String. * - * @return all of the buffers content as a String. + * @return all the contents of the buffers as a String. */ - public String getString(){ - String data = new String( this.getByte() ); - return data; + public String toString(){ + return new String( this.getBytes() ); } } diff --git a/src/zutil/io/IOUtil.java b/src/zutil/io/IOUtil.java index 077d51d..f0ad345 100644 --- a/src/zutil/io/IOUtil.java +++ b/src/zutil/io/IOUtil.java @@ -22,10 +22,7 @@ package zutil.io; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.io.*; /** * Utility class for streams and general IO stuff @@ -36,23 +33,30 @@ import java.io.InputStreamReader; public class IOUtil { /** - * Reads and returns the content of a file as a String. - * Or use FileUtils.readFileToString(file); + * Reads and returns all the contents of a stream. * - * @param stream is the file stream to read - * @return The file content - * @throws IOException + * @param stream + * @return the stream contents */ - public static String getContent(InputStream stream) throws IOException{ - BufferedReader in = new BufferedReader(new InputStreamReader(stream)); - StringBuffer ret = new StringBuffer(); - int tmp; - - while((tmp=in.read()) != -1){ - ret.append((char)tmp); + public static byte[] getContent(InputStream stream) throws IOException{ + DynamicByteArrayStream dyn_buff = new DynamicByteArrayStream(); + byte[] buff = new byte[256]; + int len = 0; + while((len = stream.read(buff)) != -1){ + dyn_buff.append(buff, 0, len); } - - in.close(); - return ret.toString(); + + return dyn_buff.getBytes(); } + + /** + * Copies all data from the input stream to the output stream + */ + public static void copyStream(InputStream in, OutputStream out) throws IOException { + byte[] buff = new byte[256]; + int len; + while((len = in.read(buff)) > 0){ + out.write(buff, 0, len); + } + } } diff --git a/src/zutil/io/MultiPrintStream.java b/src/zutil/io/MultiPrintStream.java index 2495102..ae1a507 100644 --- a/src/zutil/io/MultiPrintStream.java +++ b/src/zutil/io/MultiPrintStream.java @@ -22,12 +22,9 @@ package zutil.io; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.io.Reader; +import zutil.Dumpable; + +import java.io.*; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.ArrayList; @@ -35,8 +32,6 @@ import java.util.Collection; import java.util.Iterator; import java.util.Map; -import zutil.Dumpable; - /** * @author Ziver * this class can print strings to multiple PrintStreams @@ -71,7 +66,7 @@ public class MultiPrintStream extends PrintStream { /** * This constructor takes a array of PrintStreams to be used - * @param streams is a array of the streams that will be used + * @param streams is a array of the streams that will be used */ public MultiPrintStream(PrintStream[] streams){ super(streams[0]); @@ -83,7 +78,7 @@ public class MultiPrintStream extends PrintStream { /** * This constructor takes a array of PrintStreams to be used - * @param streams is a array of the streams that will be used + * @param instanceStream is a array of the streams that will be used */ public static void makeInstance(MultiPrintStream instanceStream){ out = instanceStream; @@ -99,7 +94,7 @@ public class MultiPrintStream extends PrintStream { /** * Remove a PrintStream from the list - * @param p is the PrintStream to remove + * @param p is the PrintStream to remove */ public void removePrintStream(PrintStream p){ streams.remove(p); @@ -107,7 +102,7 @@ public class MultiPrintStream extends PrintStream { /** * Remove a PrintStream from the list - * @param p is the index of the PrintStream to remove + * @param p is the index of the PrintStream to remove */ public void removePrintStream(int p){ streams.remove(p); @@ -206,8 +201,8 @@ public class MultiPrintStream extends PrintStream { *
- Reader content (Prints out until the end of the reader) *
- Instance variables of a Object * - * @param o is the Object to dump - * @return A String with all the printed data + * @param o is the Object to dump + * @return a String with all the printed data */ public String dumpToString( Object o) { return dumpToString(o, ""); @@ -222,8 +217,8 @@ public class MultiPrintStream extends PrintStream { *
- Reader content (Prints out until the end of the reader) *
- Instance variables of a Object * - * @param o is the Object to dump - * @param head is the string that will be put in front of every line + * @param o is the Object to dump + * @param head is the string that will be put in front of every line * @return A String with all the printed data */ diff --git a/src/zutil/io/file/FileUtil.java b/src/zutil/io/file/FileUtil.java index 7917e17..f421476 100644 --- a/src/zutil/io/file/FileUtil.java +++ b/src/zutil/io/file/FileUtil.java @@ -45,7 +45,7 @@ import zutil.log.LogUtil; * @author Ziver */ public class FileUtil { - public static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); /** * Returns a String with a relative path from the given path @@ -123,24 +123,28 @@ public class FileUtil { * Reads and returns the content of a file as a String. * Or use FileUtils.readFileToString(file); * - * @param file is the file to read - * @return The file content - * @throws IOException + * @param file + * @return the file content */ public static String getFileContent(File file) throws IOException{ - return IOUtil.getContent( new FileInputStream(file) ); + InputStream in = new FileInputStream(file); + String data = new String(IOUtil.getContent( in )); + in.close(); + return data; } /** * Reads and returns the content of a file as a String. * Or use FileUtils.readFileToString(file); * - * @param url is the url to read - * @return The file content - * @throws IOException + * @param url + * @return the file content */ public static String getContent(URL url) throws IOException{ - return IOUtil.getContent( url.openStream() ); + InputStream in = url.openStream(); + String data = new String(IOUtil.getContent( in )); + in.close(); + return data; } /** diff --git a/src/zutil/math/Tick.java b/src/zutil/math/Tick.java index 87c76ac..9421699 100644 --- a/src/zutil/math/Tick.java +++ b/src/zutil/math/Tick.java @@ -24,23 +24,12 @@ package zutil.math; public class Tick { - /** - * TEST - */ - public static void main(String[] args){ - String temp = "a"; - while(true){ - temp = tick(temp,3); - System.out.println(temp); - } - } - /** * Ticks a given string(increments the string with one) * - * @param ts The string to tick - * @param maxChar The maximum number of characters in the string - * @return The ticked string + * @param ts is the string to tick + * @param maxChar is the maximum number of characters in the string + * @return the ticked string */ public static String tick(String ts, int maxChar){ StringBuffer ret = new StringBuffer(ts.trim()); @@ -72,17 +61,17 @@ public class Tick { /** * Increments the char with one after the swedish alfabet * - * @param c The char to increment - * @return The incremented char in lowercase 0 if it reached the end + * @param c is the char to increment + * @return the incremented char in lowercase 0 if it reached the end */ public static char increment(char c){ switch(Character.toLowerCase(c)){ - case 'z': return 'å'; - case 'å': return 'ä'; - case 'ä': return 'ö'; + case 'z': return (char)134; + case (char)134: return (char)132; + case (char)132: return (char)148; } c = (char)(Character.toLowerCase(c) + 1); - if(isAlfa(c)){ + if(isAlphabetic(c)){ return c; } return 0; @@ -90,12 +79,12 @@ public class Tick { /** * Checks if the char is a valid character in - * the Swedish alfabet + * the Swedish alphabet * - * @param c The char to check - * @return True if the char is a valid letter + * @param c is the char to check + * @return true if the char is a valid letter */ - public static boolean isAlfa(char c){ + public static boolean isAlphabetic(char c){ switch(Character.toLowerCase(c)){ case 'a': case 'b': @@ -123,10 +112,12 @@ public class Tick { case 'x': case 'y': case 'z': - case 'å': - case 'ä': - case 'ö': return true; - default: return false; + case (char)134: + case (char)132: + case (char)148: + return true; + default: + return false; } } } diff --git a/src/zutil/net/FTPClient.java b/src/zutil/net/FTPClient.java index b6ccfed..ca2ece0 100644 --- a/src/zutil/net/FTPClient.java +++ b/src/zutil/net/FTPClient.java @@ -22,20 +22,13 @@ package zutil.net; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.net.Socket; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.regex.Pattern; +import zutil.io.IOUtil; import javax.security.auth.login.AccountException; - -import zutil.io.MultiPrintStream; +import java.io.*; +import java.net.Socket; +import java.net.UnknownHostException; +import java.util.regex.Pattern; /** * A simple FTP client class @@ -49,82 +42,71 @@ import zutil.io.MultiPrintStream; * TODO: file info, rename, Active mode */ public class FTPClient extends Thread{ - public static boolean DEBUG = true; - - public static final int FTP_ACTIVE = 0; - public static final int FTP_PASSIVE = 1; - public static final int FTP_PORT = 21; - public static final int FTP_DATA_PORT = 20; - public static final int FTP_NOOP_INT = 120; + public static final int FTP_PORT = 21; + public static final int FTP_DATA_PORT = 20; + public static final int FTP_NOOP_INT = 120; - //************** FTP Return Codes ****************** - public static final int FTPC_USER_OK = 331; - public static final int FTPC_NEED_PASS = 331; - public static final int FTPC_LOGIN_NO = 530; - public static final int FTPC_LOGIN_OK = 230; - - public static final int FTPC_ENTERING_PASSIVE = 227; - public static final int FTPC_FILE_ACTION_OK = 250; - public static final int FTPC_PATH_CREATED = 257; + public static enum FTPConnectionType{ + ACTIVE, + PASSIVE + } + + public static enum FTPReturnCode{ + UNKNOWN ( -1 ), + + USER_OK ( 331 ), + NEED_PASS ( 331 ), + LOGIN_NO ( 530 ), + LOGIN_OK ( 230 ), + + ENTERING_PASSIVE ( 227 ), + FILE_ACTION_OK ( 250 ), + PATH_CREATED ( 257 ); + + private int code; + private FTPReturnCode(int code){ + this.code = code; + } + + public boolean isError(){ + return code >= 400; + } + + public static FTPReturnCode fromCode(int code){ + for(FTPReturnCode type : FTPReturnCode.values()){ + if(code == type.code) return type; + } + return UNKNOWN; + } + } //*************************************************** + private FTPConnectionType connectionType; private BufferedReader in; - private PrintStream out; + private Writer out; private Socket socket; private long last_sent; - public static void main(String[] args){ - try { - FTPClient client = new FTPClient("213.180.86.135", 21, "administrator", "geineZ2K", FTP_PASSIVE); - /* - client.createDir("./ziver/lol"); - client.removeDir("./ziver/lol"); - - MultiPrintStream.out.dump(client.getFileList("./ziver")); - client.sendFile("./ziver/test.txt", "lol"); - MultiPrintStream.out.dump(client.getFileList("./ziver")); - - MultiPrintStream.out.dump(client.getFile("./ziver/test.txt")); - client.readCommand(DEBUG); - - MultiPrintStream.out.println(client.getFileInfo("./ziver/test.txt")); - - MultiPrintStream.out.dump(client.getFileList("./ziver")); - client.removeFile("./ziver/test.txt"); - MultiPrintStream.out.dump(client.getFileList("./ziver")); - */ - ArrayList tmp = client.getFileInfo(""); - MultiPrintStream.out.println("****************"); - MultiPrintStream.out.dump(tmp); - MultiPrintStream.out.println(tmp.size()); - MultiPrintStream.out.println("****************"); - client.close(); - } catch (Exception e) { - e.printStackTrace(); - System.exit(1); - } - } - /** * Creates a FTP connection and logs in * - * @param url The address to server - * @param port Port number - * @param user User name - * @param pass Password - * @param connection_type Pasive or Active + * @param url the address to server + * @param port port number + * @param user login username + * @param pass password + * @param conn_type connection type */ - public FTPClient(String url, int port, String user, String pass, int connection_type) throws UnknownHostException, IOException, AccountException{ + public FTPClient(String url, int port, String user, String pass, FTPConnectionType conn_type) throws UnknownHostException, IOException, AccountException{ socket = new Socket(url, port); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); - out = new PrintStream(socket.getOutputStream()); + out = new OutputStreamWriter(socket.getOutputStream()); + connectionType = conn_type; - readCommand(DEBUG); + readCommand(); sendCommand("USER "+user); - sendNoReplyCommand("PASS "+pass, DEBUG); - if(DEBUG)System.out.println("PASS ***"); - String tmp = readMultipleCommands(DEBUG); - if(parseReturnCode(tmp) == FTPC_LOGIN_NO){ + sendNoReplyCommand("PASS "+pass); + String tmp = readCommand(); + if(parseReturnCode(tmp) == FTPReturnCode.LOGIN_NO){ close(); throw new AccountException(tmp); } @@ -132,358 +114,216 @@ public class FTPClient extends Thread{ start(); } -//************************************************************************************** //************************************************************************************** //********************************* Command channel ************************************ /** - * Sends the given line to the server and returns a status integer - * - * @param cmd The command to send - * @return The return code from the server - * @throws IOException + * Sends the given command to the server and returns a status integer + * + * @return last line received from the server */ - public synchronized int sendCommand(String cmd) throws IOException{ - return parseReturnCode(sendCommand(cmd, DEBUG)); + private FTPReturnCode sendCommand(String cmd) throws IOException{ + sendNoReplyCommand(cmd); + return parseReturnCode( readCommand( ) ); } /** - * Sends the given line to the server and returns the last line - * - * @param cmd The command to send - * @param print To print out the received lines - * @return Last String line from the server - * @throws IOException + * Sends a command and don't cares about the reply */ - private synchronized String sendCommand(String cmd, boolean print) throws IOException{ - sendNoReplyCommand(cmd, print); - return readCommand(print); + private void sendNoReplyCommand(String cmd) throws IOException{ + last_sent = System.currentTimeMillis(); + out.append(cmd).append('\n'); } - - /** - * Sends a given command and don't cares about the reply - * - * @param cmd The command - * @param print If it should print to System.out - * @throws IOException - */ - private synchronized void sendNoReplyCommand(String cmd, boolean print) throws IOException{ - out.println(cmd); - last_sent = System.currentTimeMillis(); - if(print)System.out.println(cmd); - } - - /** - * Reads on line from the command channel - * - * @param print If the method should print the input line - * @return The input line - * @throws IOException - */ - public synchronized String readCommand(boolean print) throws IOException{ - String tmp = in.readLine(); - if(print)System.out.println(tmp); - if(parseReturnCode(tmp) >= 400 ) throw new IOException(tmp); - - return tmp; - } - + /** * Reads from the command channel until there are nothing * left to read and returns the last line - * - * @param print To print out the received lines - * @return The last received line - * @throws IOException + * + * @return last line received by the server */ - private synchronized String readMultipleCommands(boolean print) throws IOException{ - String tmp = readCommand(print); - while(!tmp.substring(3, 4).equalsIgnoreCase(" ")){ - tmp = readCommand(print); - } - - /* + private String readCommand() throws IOException{ String tmp = in.readLine(); - if(print)System.out.println(tmp); - try{ Thread.sleep(500); }catch(Exception e){} - while(in.ready()){ + while(!Character.isWhitespace(tmp.charAt(3))){ tmp = in.readLine(); - if(print)System.out.println(tmp); - try{ Thread.sleep(500); }catch(Exception e){} + if(parseReturnCode(tmp).isError()) throw new IOException(tmp); } - */ return tmp; } /** * Parses the return line from the server and returns the status code * - * @param msg The message from the server - * @return The status code - * @throws IOException + * @param msg message String from the server + * @return a status code response */ - private synchronized int parseReturnCode(String msg){ - return Integer.parseInt(msg.substring(0, 3)); + private FTPReturnCode parseReturnCode(String msg){ + return FTPReturnCode.fromCode(Integer.parseInt(msg.substring(0, 3))); } -//************************************************************************************** //************************************************************************************** //****************************** File system actions ************************************ /** - * Returns a LinkedList with the names of all the files in the directory - * - * @param path Path to the files to be listed - * @return LinkedList whit filenames - * @throws IOException + * Returns a LinkedList with names of all the files in the directory + * + * @deprecated + * @return List with filenames */ - public LinkedList getFileList(String path) throws IOException{ - LinkedList list = new LinkedList(); - - BufferedReader data_in = getDataInputStream(); - sendCommand("NLST "+path, DEBUG); - - String tmp = ""; - while((tmp = data_in.readLine()) != null){ - list.add(tmp); - } + public String[] getFileList(String path) throws IOException{ + BufferedInputStream data_in = getDataInputStream(); + sendCommand("NLST "+path); + + String data = new String(IOUtil.getContent(data_in)); data_in.close(); - readCommand(DEBUG); - return list; + readCommand(); + return data.split("[\n\r]"); } /** - * Returns information about the file or directory + * Returns information about a file or directory * * @deprecated - * @param path The path and filename of a file or a directory - * @return A List of Strings with information - * @throws IOException + * @return a List of Strings with information */ - public ArrayList getFileInfo(String path) throws IOException{ + public String getFileInfo(String path) throws IOException{ Pattern regex = Pattern.compile("\\s{1,}"); - ArrayList info = new ArrayList(); - - BufferedReader data_in = getDataInputStream(); - sendCommand("LIST "+path, DEBUG); - - String tmp = ""; - while((tmp = data_in.readLine()) != null){ - System.err.println(tmp); - info.add(regex.split(tmp)); - } + BufferedInputStream data_in = getDataInputStream(); + sendCommand("LIST "+path); + + String data = new String(IOUtil.getContent(data_in)); + data_in.close(); - readCommand(DEBUG); - return info; + readCommand(); + return data; } /** - * Creates a file at the server with the given data + * Creates a file in the server with the given data * - * @param path The path and filename - * @param data The data to put in the file - * @throws IOException + * @param path filepath + * @param data data to put in the file */ public void sendFile(String path, String data) throws IOException{ - PrintStream data_out = getDataOutputStream(); - sendCommand("STOR "+path, DEBUG); - data_out.println(data); + BufferedOutputStream data_out = getDataOutputStream(); + sendCommand("STOR "+path); + + byte[] byte_data = data.getBytes(); + data_out.write(byte_data, 0, byte_data.length); data_out.close(); - readCommand(DEBUG); + + readCommand(); } /** - * Creates a directory at the server + * Creates a directory in the server * * @param path The path to the directory - * @throws IOException */ public boolean createDir(String path) throws IOException{ - if(sendCommand("MKD "+path) == FTPC_PATH_CREATED) + if(sendCommand("MKD "+path) == FTPReturnCode.PATH_CREATED) return true; return false; } /** - * Returns a BufferedReader with the file data - * WARNING: you must run readCommand(true); after you close the stream - * - * @param path The path and filename - * @return Stream with the file - * @throws IOException + * Returns a InputStream for a file on the server + * WARNING: you must run readCommand(); after you close the stream + * + * @return a stream with file data */ - private BufferedReader getFile(String path) throws IOException{ - BufferedReader ret = getDataInputStream(); - sendCommand("RETR "+path, DEBUG); - return ret; + private BufferedInputStream getFileInputStream(String path) throws IOException{ + BufferedInputStream input = getDataInputStream(); + sendCommand("RETR "+path); + return input; } /** - * Downloads a file from the FTP server to a local file + * Download a file from the server to a local file * - * @param source The source file on the server - * @param destination The local file to save to - * @throws IOException + * @param source source file on the server + * @param destination local destination file */ public void getFile(String source, String destination) throws IOException{ - BufferedReader file_in = getFile(source); - PrintStream file_out = new PrintStream(new File(destination)); - - String tmp = ""; - while((tmp = file_in.readLine()) != null){ - file_out.println(tmp); - } - readCommand(DEBUG); + BufferedInputStream ext_file_in = getFileInputStream(source); + BufferedOutputStream local_file_out = new BufferedOutputStream(new FileOutputStream(new File(destination))); + + IOUtil.copyStream(ext_file_in, local_file_out); + readCommand(); } /** - * Removes a file from the FTP server - * - * @param path The path and filename of the file to be deleted - * @return True if the command was successful or false otherwise - * @throws IOException + * Remove a file from the FTP server + * + * @return true if the command was successful, false otherwise */ public boolean removeFile(String path) throws IOException{ - if(sendCommand("DELE "+path) == FTPC_FILE_ACTION_OK) + if(sendCommand("DELE "+path) == FTPReturnCode.FILE_ACTION_OK) return true; return false; } /** * Removes a directory from the FTP server - * - * @param path The path of the directory to be deleted + * * @return True if the command was successful or false otherwise - * @throws IOException */ public boolean removeDir(String path) throws IOException{ - if(sendCommand("RMD "+path) == FTPC_FILE_ACTION_OK) + if(sendCommand("RMD "+path) == FTPReturnCode.FILE_ACTION_OK) return true; return false; } -//************************************************************************************** //************************************************************************************** //******************************** Data Connection ************************************* /** - * Starts a connection to the server. It automatically handles - * passive or active mode + * Start a data connection to the server. * - * @return The PrintStream for the channel - * @throws IOException + * @return a PrintStream for the channel */ - public synchronized PrintStream getDataOutputStream() throws IOException{ - int port = getDataConnectionPortType(); - if(port < 0){ // Active Mode - port *= -1; - return getActiveDataOutputStream(port); + public BufferedOutputStream getDataOutputStream() throws IOException{ + if(connectionType == FTPConnectionType.PASSIVE){ // Passive Mode + int port = setPassiveMode(); + Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port); + return new BufferedOutputStream(data_socket.getOutputStream()); } - else{ - System.out.println("port: "+port); - return getPassiveDataOutputStream(port); + else{ // Active Mode + return null; } } /** - * Starts a connection to the server. It automatically handles - * passive or active mode + * Start a data connection to the server. * - * @return The BufferedReader for the channel - * @throws IOException + * @return a BufferedReader for the data channel */ - public synchronized BufferedReader getDataInputStream() throws IOException{ - int port = getDataConnectionPortType(); - if(port < 0){ // Active Mode - port *= -1; - return getActiveDataInputStream(port); + public BufferedInputStream getDataInputStream() throws IOException{ + if(connectionType == FTPConnectionType.PASSIVE){ // Passive Mode + int port = setPassiveMode(); + Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port); + return new BufferedInputStream(data_socket.getInputStream()); } - else{ - return getPassiveDataInputStream(port); + else{ // Active Mode + return null; } } + /** - * This method chooses the appropriate data connection type - * to the server (Passive or Active) and returns the port number + * Sets Passive mode to the server * - * @return A port number. If port > 0 = Passive AND port < 0 Active - * @throws IOException - */ - private int getDataConnectionPortType() throws IOException{ - return setPassiveMode(); - } - - /** - * Connects to the data port on the server and returns the InputStream - * - * @param port The port to connect to - * @return The InputStream for the data channel - * @throws IOException - */ - private BufferedReader getPassiveDataInputStream(int port) throws IOException{ - Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port); - BufferedReader data_in = new BufferedReader(new InputStreamReader(data_socket.getInputStream())); - - return data_in; - } - - /** - * Connects to the data port on the server and returns the OutputStream - * - * @param port The port to connect to - * @return The OutputStream for the data channel - * @throws IOException - */ - private PrintStream getPassiveDataOutputStream(int port) throws IOException{ - Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port); - PrintStream data_out = new PrintStream(data_socket.getOutputStream()); - - return data_out; - } - - /** - * Listens on a local port for a connection from the server - * and returns with the InputStream of the connection from the server - * - * @param port The port to listen to - * @return The InputStream for the data channel - * @throws IOException - */ - private BufferedReader getActiveDataInputStream(int port) throws IOException{ - // TODO: - return null; - } - - /** - * Listens on a local port for a connection from the server - * and returns with the OutputStream of the connection from the server - * - * @param port The port to listen to - * @return The OutputStream for the data channel - * @throws IOException - */ - private PrintStream getActiveDataOutputStream(int port) throws IOException{ - // TODO: - return null; - } - - /** - * Sets Passive mode at the server and returns the port number - * for the data channel - * - * @return Port number for data channel - * @throws IOException + * @return a port number for data channel */ private int setPassiveMode() throws IOException{ - String tmp = sendCommand("PASV", DEBUG); - if(parseReturnCode(tmp) != FTPC_ENTERING_PASSIVE){ - throw new IOException(tmp); + sendNoReplyCommand("PASV"); + String ret_msg = readCommand(); + if(parseReturnCode(ret_msg) != FTPReturnCode.ENTERING_PASSIVE){ + throw new IOException("Passive mode rejected by server: "+ret_msg); } - tmp = tmp.substring(tmp.indexOf('(')+1, tmp.indexOf(')')); - String[] tmpArray = tmp.split("[,]"); + ret_msg = ret_msg.substring(ret_msg.indexOf('(')+1, ret_msg.indexOf(')')); + String[] tmpArray = ret_msg.split("[,]"); if(tmpArray.length <= 1) return Integer.parseInt(tmpArray[0]); @@ -495,7 +335,7 @@ public class FTPClient extends Thread{ //************************************************************************************** /** - * To keep the connection alive + * Keep the connection alive */ public void run(){ try { @@ -512,15 +352,12 @@ public class FTPClient extends Thread{ /** * Close the FTP connection - * - * @throws IOException */ - @SuppressWarnings("deprecation") public void close() throws IOException{ - sendCommand("QUIT", DEBUG); + sendCommand("QUIT"); in.close(); out.close(); socket.close(); - this.stop(); + this.interrupt(); } } diff --git a/src/zutil/net/http/HttpServer.java b/src/zutil/net/http/HttpServer.java index 5336b80..fa2945b 100644 --- a/src/zutil/net/http/HttpServer.java +++ b/src/zutil/net/http/HttpServer.java @@ -48,7 +48,7 @@ import zutil.net.threaded.ThreadedTCPNetworkServerThread; * @author Ziver */ public class HttpServer extends ThreadedTCPNetworkServer{ - public static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); public static final String SERVER_VERSION = "Ziver HttpServer 1.0"; public static final int COOKIE_TTL = 200; public static final int SESSION_TTL = 10*60*1000; // in milliseconds diff --git a/src/zutil/net/http/soap/SOAPHttpPage.java b/src/zutil/net/http/soap/SOAPHttpPage.java index 7174490..dcd1b5c 100644 --- a/src/zutil/net/http/soap/SOAPHttpPage.java +++ b/src/zutil/net/http/soap/SOAPHttpPage.java @@ -81,7 +81,7 @@ import zutil.parser.wsdl.WSDLWriter; * @author Ziver */ public class SOAPHttpPage implements HttpPage{ - public static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); /** The object that the functions will be invoked from **/ private WebServiceDef wsDef; diff --git a/src/zutil/net/ssdp/SSDPClient.java b/src/zutil/net/ssdp/SSDPClient.java index 06d91ac..ad1fd03 100644 --- a/src/zutil/net/ssdp/SSDPClient.java +++ b/src/zutil/net/ssdp/SSDPClient.java @@ -44,7 +44,7 @@ import zutil.net.threaded.ThreadedUDPNetworkThread; * @author Ziver */ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetworkThread{ - public static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); // Contains all the received services private HashMap> services_st; private HashMap services_usn; diff --git a/src/zutil/net/ssdp/SSDPServer.java b/src/zutil/net/ssdp/SSDPServer.java index 033f264..1804e59 100644 --- a/src/zutil/net/ssdp/SSDPServer.java +++ b/src/zutil/net/ssdp/SSDPServer.java @@ -64,7 +64,7 @@ import zutil.net.threaded.ThreadedUDPNetwork; * NTS: same as Man but for Notify messages */ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetworkThread{ - public static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); public static final String SERVER_INFO = "SSDP Java Server by Ziver Koc"; public static final int DEFAULT_CACHE_TIME = 60*30; // 30 min public static final int BUFFER_SIZE = 512; diff --git a/src/zutil/net/update/UpdateClient.java b/src/zutil/net/update/UpdateClient.java index a222af8..54d975f 100644 --- a/src/zutil/net/update/UpdateClient.java +++ b/src/zutil/net/update/UpdateClient.java @@ -43,7 +43,7 @@ import zutil.log.LogUtil; * */ public class UpdateClient{ - public static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); private String path; private Socket socket; diff --git a/src/zutil/net/update/UpdateServer.java b/src/zutil/net/update/UpdateServer.java index 54b6deb..54f84ce 100644 --- a/src/zutil/net/update/UpdateServer.java +++ b/src/zutil/net/update/UpdateServer.java @@ -36,7 +36,7 @@ import zutil.net.threaded.ThreadedTCPNetworkServer; import zutil.net.threaded.ThreadedTCPNetworkServerThread; public class UpdateServer extends ThreadedTCPNetworkServer{ - public static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); private FileListMessage fileList; diff --git a/src/zutil/parser/Base64Decoder.java b/src/zutil/parser/Base64Decoder.java index dbe9c73..584bd77 100644 --- a/src/zutil/parser/Base64Decoder.java +++ b/src/zutil/parser/Base64Decoder.java @@ -106,11 +106,11 @@ public class Base64Decoder { } public String toString(){ - return output.getString(); + return output.toString(); } public byte[] getByte(){ - return output.getByte(); + return output.getBytes(); } public void clear(){ diff --git a/src/zutil/test/DynamicByteArrayStreamTest.java b/src/zutil/test/DynamicByteArrayStreamTest.java new file mode 100644 index 0000000..fcef5df --- /dev/null +++ b/src/zutil/test/DynamicByteArrayStreamTest.java @@ -0,0 +1,53 @@ +/******************************************************************************* + * Copyright (c) 2013 Ziver + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + ******************************************************************************/ + +package zutil.test; + +import org.junit.Test; +import zutil.io.DynamicByteArrayStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * User: Ziver + */ +public class DynamicByteArrayStreamTest { + + @Test + public void emptyArray(){ + DynamicByteArrayStream out = new DynamicByteArrayStream(); + assertEquals(0, out.available()); + assertEquals(0, out.getBytes().length); + assertTrue(out.toString().isEmpty()); + } + + @Test + public void oneByteArray(){ + byte[] b = new byte[]{0x01,0x02,0x03,0x04}; + + DynamicByteArrayStream out = new DynamicByteArrayStream(); + out.append(b); + + assertEquals(b, out.getBytes()); + } +} diff --git a/src/zutil/test/NetLogServerTest.java b/src/zutil/test/NetLogServerTest.java index 2490eed..848aa7f 100644 --- a/src/zutil/test/NetLogServerTest.java +++ b/src/zutil/test/NetLogServerTest.java @@ -29,7 +29,7 @@ import zutil.log.LogUtil; import zutil.log.net.NetLogServer; public class NetLogServerTest { - public static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); public static void main(String[] args){ LogUtil.setGlobalLevel(Level.FINEST);