Many small fixes

This commit is contained in:
Ziver Koc 2013-12-17 19:18:14 +00:00
parent 8a930b361d
commit 9a0142c06c
18 changed files with 376 additions and 499 deletions

View file

@ -22,23 +22,19 @@
package zutil.converters; 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 zutil.io.DynamicByteArrayStream;
import java.io.*;
import java.util.BitSet;
public class Converter { public class Converter {
private Converter(){} private Converter(){}
/** /**
* Converts an object to an array of bytes. * Converts an object to an array of bytes.
* *
* @param object the object to convert. * @param object the object to convert.
* @return the associated byte array. * @return the associated byte array.
*/ */
public static byte[] toBytes(Object object) throws IOException{ public static byte[] toBytes(Object object) throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
@ -55,7 +51,7 @@ public class Converter {
* Converts a Integer to an byte array * Converts a Integer to an byte array
* *
* @param num is the number to convert * @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){ public static byte[] toBytes(int num){
return new byte[]{ return new byte[]{
@ -69,7 +65,7 @@ public class Converter {
* Converts a Integer to a byte * Converts a Integer to a byte
* *
* @param num is the number to convert * @param num is the number to convert
* @return an byte * @return a byte value of the integer
*/ */
public static byte toByte(int num){ public static byte toByte(int num){
return (byte)(num & 0xff); return (byte)(num & 0xff);
@ -78,9 +74,9 @@ public class Converter {
/** /**
* Converts hex chars to a byte * Converts hex chars to a byte
* *
* @param quad1 is the first hex value * @param quad1 is the first hex value
* @param quad2 is the second hex value * @param quad2 is the second hex value
* @return a byte that corresponds to the hex * @return a byte that corresponds to the hex
*/ */
public static int hexToByte( char quad1, char quad2){ public static int hexToByte( char quad1, char quad2){
byte b = hexToByte( quad2 ); byte b = hexToByte( quad2 );
@ -91,8 +87,8 @@ public class Converter {
/** /**
* Converts a hex chars to a byte * Converts a hex chars to a byte
* *
* @param quad1 is the hex value * @param hex is the hex value
* @return a byte that corresponds to the hex * @return a byte that corresponds to the hex
*/ */
public static byte hexToByte( char hex ){ public static byte hexToByte( char hex ){
switch( Character.toLowerCase(hex) ){ switch( Character.toLowerCase(hex) ){
@ -120,8 +116,8 @@ public class Converter {
* Converts an array of bytes back to its constituent object. The * Converts an array of bytes back to its constituent object. The
* input array is assumed to have been created from the original object. * input array is assumed to have been created from the original object.
* *
* @param bytes the byte array to convert. * @param bytes the byte array to convert.
* @return the associated object. * @return the associated object.
*/ */
public static Object toObject(byte[] bytes) throws Exception{ public static Object toObject(byte[] bytes) throws Exception{
Object object = null; Object object = null;
@ -137,8 +133,8 @@ public class Converter {
* Converts an array of bytes back to its constituent object. The * Converts an array of bytes back to its constituent object. The
* input array is assumed to have been created from the original object. * input array is assumed to have been created from the original object.
* *
* @param bytes the byte array to convert. * @param bytes the byte array to convert.
* @return the associated object. * @return the associated object.
*/ */
public static Object toObject(DynamicByteArrayStream bytes) throws Exception{ public static Object toObject(DynamicByteArrayStream bytes) throws Exception{
Object object = null; Object object = null;
@ -153,9 +149,9 @@ public class Converter {
/** /**
* Checks if the given interface is implemented in the object * Checks if the given interface is implemented in the object
* *
* @param object the object to look for the interface * @param object the object to look for the interface
* @param interf the interface to look for * @param interf the interface to look for
* @return true if the interface is implemented else false * @return true if the interface is implemented else false
*/ */
public static boolean isInstanceOf(Object object, Class<?> interf){ public static boolean isInstanceOf(Object object, Class<?> interf){
Class<?>[] objectInterf = object.getClass().getInterfaces(); Class<?>[] objectInterf = object.getClass().getInterfaces();
@ -172,8 +168,8 @@ public class Converter {
/** /**
* Converts a byte Array to a Hex String * Converts a byte Array to a Hex String
* *
* @param raw the byte array to convert * @param raw the byte array to convert
* @return a Hex String * @return a hex String
*/ */
public static String toHexString(byte[][] raw){ public static String toHexString(byte[][] raw){
StringBuffer ret = new StringBuffer(); StringBuffer ret = new StringBuffer();
@ -204,8 +200,8 @@ public class Converter {
/** /**
* Converts a byte Array to a Hex String * Converts a byte Array to a Hex String
* *
* @param raw the byte array to convert * @param raw the byte array to convert
* @return a Hex String * @return a hex String
*/ */
public static String toHexString(byte[] raw){ public static String toHexString(byte[] raw){
StringBuffer ret = new StringBuffer(); StringBuffer ret = new StringBuffer();
@ -221,8 +217,8 @@ public class Converter {
/** /**
* Converts a byte to a Hex String * Converts a byte to a Hex String
* *
* @param raw the byte to convert * @param raw the byte to convert
* @return a Hex String * @return a hex String
*/ */
public static String toHexString(byte raw){ public static String toHexString(byte raw){
String ret = ""+HEX_CHARS[(int) (raw >>> 0x04)& 0x0F ]; 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 * Converts the given byte to a String with 1's and 0's
* *
* @param raw the byte to convert * @param raw the byte to convert
* @return a String with 1's and 0's * @return a String with 1's and 0's
*/ */
public static String toString(byte raw){ public static String toString(byte raw){
StringBuffer ret = new StringBuffer(); 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 * Converts the given byte array to a String with 1's and 0's
* *
* @param raw the byte array to convert * @param raw the byte array to convert
* @return a String with 1's and 0's * @return a String with 1's and 0's
*/ */
public static String toString(byte[] raw){ public static String toString(byte[] raw){
StringBuffer ret = new StringBuffer(); StringBuffer ret = new StringBuffer();
@ -264,8 +260,8 @@ public class Converter {
/** /**
* Converts a BitSet to a Integer * Converts a BitSet to a Integer
* *
* @param bits the BitSet to convert * @param bits the BitSet to convert
* @return a Integer * @return a Integer
*/ */
public static int toInt(BitSet bits){ public static int toInt(BitSet bits){
int ret = 0; 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 * Converts a boolean array(bit sequence whit most significant bit at index 0) to a Integer
* *
* @param bits the boolean array to convert * @param bits the boolean array to convert
* @return a Integer * @return a Integer
*/ */
public static int toInt(boolean[] bits){ public static int toInt(boolean[] bits){
int ret = 0; int ret = 0;
@ -296,8 +292,8 @@ public class Converter {
/** /**
* Converts a byte to a integer * Converts a byte to a integer
* *
* @param num is the byte to convert * @param b is the byte to convert
* @return an integer * @return the integer value of the byte
*/ */
public static int toInt(byte b){ public static int toInt(byte b){
return (int)(b & 0xff); return (int)(b & 0xff);
@ -306,8 +302,8 @@ public class Converter {
/** /**
* Converts a Integer to a BitSet * Converts a Integer to a BitSet
* *
* @param i the Integer to convert * @param num the Integer to convert
* @return a BitSet object * @return a BitSet object
*/ */
public static BitSet toBitSet(int num){ public static BitSet toBitSet(int num){
BitSet ret = new BitSet(); BitSet ret = new BitSet();
@ -323,10 +319,10 @@ public class Converter {
/** /**
* Converts a given String to a specified class * Converts a given String to a specified class
* *
* @param <T> is the resulting class * @param <T> is the resulting class
* @param data is the String data to be converted * @param data is the String data to be converted
* @param c is the class to convert to * @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 * @return a instance of the class with the value in the string or null if there was an problem
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T fromString(String data, Class<T> c){ public static <T> T fromString(String data, Class<T> c){

View file

@ -22,6 +22,9 @@
package zutil.db; package zutil.db;
import zutil.converters.Converter;
import zutil.io.MultiPrintStream;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@ -30,31 +33,28 @@ import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.Queue; 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. * data in a mysql table.
* The table should look like this: * The table should look like this:
* <PRE>
* CREATE TABLE `queue` ( * CREATE TABLE `queue` (
* `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , * `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
* `data` BINARY NOT NULL * `data` BINARY NOT NULL
* ); * );
* </PRE>
* @author Ziver * @author Ziver
* *
*/ */
public class DBQueue<E> implements Queue<E>{ public class DBQueue<E> implements Queue<E>{
// GO TO KNOW = SELECT LAST_INSERT_ID() as pos_id
private DBConnection db; private DBConnection db;
private String table; private String table;
/** /**
* Initiates the queue.<br> * Initiates the queue.<br>
* <b>WARNING!!<b> this will erase all rows in the table
* *
* @param db is the connection to the DB * @param db is the connection to the DB
* @param table is the name of the table * @param table is the name of the table
*/ */
public DBQueue(DBConnection db, String table){ public DBQueue(DBConnection db, String table){
this.db = db; this.db = db;
@ -63,8 +63,9 @@ public class DBQueue<E> implements Queue<E>{
public boolean add(Object arg0){ public boolean add(Object arg0){
try { try {
PreparedStatement sql = db.getPreparedStatement("INSERT INTO "+table+" (data) VALUES(?)"); PreparedStatement sql = db.getPreparedStatement("INSERT INTO ? (data) VALUES(?)");
sql.setObject(1, arg0); sql.setObject(1, table);
sql.setObject(2, arg0);
DBConnection.exec(sql); DBConnection.exec(sql);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(MultiPrintStream.out); e.printStackTrace(MultiPrintStream.out);
@ -81,7 +82,6 @@ public class DBQueue<E> implements Queue<E>{
return add(arg0); return add(arg0);
} }
@SuppressWarnings("unchecked")
public synchronized E peek() { public synchronized E peek() {
try { try {
return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler<E>(){ return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler<E>(){
@ -101,7 +101,6 @@ public class DBQueue<E> implements Queue<E>{
return null; return null;
} }
@SuppressWarnings("unchecked")
public synchronized E poll() { public synchronized E poll() {
try { try {
return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler<E>(){ return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler<E>(){
@ -207,7 +206,6 @@ public class DBQueue<E> implements Queue<E>{
return null; return null;
} }
@SuppressWarnings("unchecked")
public E[] toArray(Object[] arg0) { public E[] toArray(Object[] arg0) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;

View file

@ -42,7 +42,7 @@ import zutil.db.bean.DBBean.DBLinkTable;
import zutil.log.LogUtil; import zutil.log.LogUtil;
public class DBBeanSQLResultHandler<T> implements SQLResultHandler<T>{ public class DBBeanSQLResultHandler<T> implements SQLResultHandler<T>{
public static final Logger logger = LogUtil.getLogger(); private static final Logger logger = LogUtil.getLogger();
/** This is the time to live for the cached items **/ /** This is the time to live for the cached items **/
public static final long CACHE_TTL = 1000*60*5; // 5 min in ms public static final long CACHE_TTL = 1000*60*5; // 5 min in ms
/** A cache for detecting recursion **/ /** A cache for detecting recursion **/

View file

@ -29,13 +29,13 @@ import java.util.ArrayList;
public class DynamicByteArrayStream extends InputStream{ public class DynamicByteArrayStream extends InputStream{
/** The byte array container */ /** The byte array container */
private ArrayList<byte[]> bytes; private ArrayList<byte[]> bytes;
/** The current size of the stream */ /** Current virtual size of the stream */
private int size; private int size;
/** points to the current index in the ArrayList */ /** Points the current byte array index */
private int byteArrayIndex; private int arrayIndex;
/** points locally in the current index in the ArrayList */ /** Points to a local index in the current byte array */
private int localPointer; private int arrayLocalIndex;
/** The current position */ /** Current virtual position of the stream */
private int pos; private int pos;
/** /**
@ -44,8 +44,8 @@ public class DynamicByteArrayStream extends InputStream{
public DynamicByteArrayStream(){ public DynamicByteArrayStream(){
bytes = new ArrayList<byte[]>(); bytes = new ArrayList<byte[]>();
size = 0; size = 0;
byteArrayIndex = 0; arrayIndex = 0;
localPointer = 0; arrayLocalIndex = 0;
pos = 0; pos = 0;
} }
@ -61,7 +61,7 @@ public class DynamicByteArrayStream extends InputStream{
/** /**
* Append an byte array to the stream. * 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 b is the byte array to add
* @param offset is the offset in the byte array * @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){ public synchronized void append(byte[] b, int offset, int length){
byte[] new_b = new byte[length]; byte[] new_b = new byte[length];
System.arraycopy(b, offset, new_b, 0, length); System.arraycopy(b, offset, new_b, 0, length);
bytes.add(b); bytes.add(new_b);
size += length; size += length;
} }
@ -78,12 +78,12 @@ public class DynamicByteArrayStream extends InputStream{
public synchronized int read() throws IOException { public synchronized int read() throws IOException {
if(pos >= size) return -1; if(pos >= size) return -1;
int ret = bytes.get(byteArrayIndex)[localPointer] & 0xff; int ret = bytes.get(arrayIndex)[arrayLocalIndex] & 0xff;
pos++; pos++;
localPointer++; arrayLocalIndex++;
if(localPointer >= bytes.get(byteArrayIndex).length){ if(arrayLocalIndex >= bytes.get(arrayIndex).length){
byteArrayIndex++; arrayIndex++;
localPointer = 0; arrayLocalIndex = 0;
} }
return ret; return ret;
} }
@ -92,26 +92,26 @@ public class DynamicByteArrayStream extends InputStream{
if(len <= 0) return 0; if(len <= 0) return 0;
if(pos >= size) return -1; if(pos >= size) return -1;
int bytes_read = 0; int bytes_read=0;
if(pos+len >= size) len = size - pos; if(pos+len >= size) len = size - pos;
for(int i=0; i<len ;i++){ for(; bytes_read<len ;bytes_read++){
byte[] src = bytes.get(byteArrayIndex); byte[] src = bytes.get(arrayIndex);
if(localPointer+len-i >= src.length){ // Read length is LONGER than local array
int length = src.length-localPointer; if(arrayLocalIndex +len-bytes_read >= src.length){
System.arraycopy(src, localPointer, b, off+i, length); int length = src.length- arrayLocalIndex;
System.arraycopy(src, arrayLocalIndex, b, off+bytes_read, length);
localPointer = 0; arrayLocalIndex = 0;
byteArrayIndex++; arrayIndex++;
bytes_read += length; bytes_read += length;
i += length;
} }
// Read length is SHORTER than local array
else{ else{
int length = len-i; int length = len-bytes_read;
System.arraycopy(src, localPointer, b, off+i, length); System.arraycopy(src, arrayLocalIndex, b, off+bytes_read, length);
localPointer += length; arrayLocalIndex += length;
bytes_read += length; bytes_read += length;
i += length;
} }
} }
pos += len; pos += len;
@ -132,8 +132,8 @@ public class DynamicByteArrayStream extends InputStream{
} }
public synchronized void reset() { public synchronized void reset() {
byteArrayIndex = 0; arrayIndex = 0;
localPointer = 0; arrayLocalIndex = 0;
pos = 0; pos = 0;
} }
@ -144,7 +144,7 @@ public class DynamicByteArrayStream extends InputStream{
/** /**
* @return all of the buffers content as a byte array. * @return all of the buffers content as a byte array.
*/ */
public byte[] getByte(){ public byte[] getBytes(){
byte[] data = new byte[size]; byte[] data = new byte[size];
this.read(data, 0, size); this.read(data, 0, size);
return data; return data;
@ -154,10 +154,9 @@ public class DynamicByteArrayStream extends InputStream{
/** /**
* WARNING: This function might return a malformed String. * 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(){ public String toString(){
String data = new String( this.getByte() ); return new String( this.getBytes() );
return data;
} }
} }

View file

@ -22,10 +22,7 @@
package zutil.io; package zutil.io;
import java.io.BufferedReader; import java.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/** /**
* Utility class for streams and general IO stuff * Utility class for streams and general IO stuff
@ -36,23 +33,30 @@ import java.io.InputStreamReader;
public class IOUtil { public class IOUtil {
/** /**
* Reads and returns the content of a file as a String. * Reads and returns all the contents of a stream.
* Or use FileUtils.readFileToString(file);
* *
* @param stream is the file stream to read * @param stream
* @return The file content * @return the stream contents
* @throws IOException
*/ */
public static String getContent(InputStream stream) throws IOException{ public static byte[] getContent(InputStream stream) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(stream)); DynamicByteArrayStream dyn_buff = new DynamicByteArrayStream();
StringBuffer ret = new StringBuffer(); byte[] buff = new byte[256];
int tmp; int len = 0;
while((len = stream.read(buff)) != -1){
while((tmp=in.read()) != -1){ dyn_buff.append(buff, 0, len);
ret.append((char)tmp);
} }
in.close(); return dyn_buff.getBytes();
return ret.toString();
} }
/**
* 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);
}
}
} }

View file

@ -22,12 +22,9 @@
package zutil.io; package zutil.io;
import java.io.File; import zutil.Dumpable;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.*;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.Reader;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
@ -35,8 +32,6 @@ import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import zutil.Dumpable;
/** /**
* @author Ziver * @author Ziver
* this class can print strings to multiple PrintStreams * 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 * 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){ public MultiPrintStream(PrintStream[] streams){
super(streams[0]); super(streams[0]);
@ -83,7 +78,7 @@ public class MultiPrintStream extends PrintStream {
/** /**
* This constructor takes a array of PrintStreams to be used * 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){ public static void makeInstance(MultiPrintStream instanceStream){
out = instanceStream; out = instanceStream;
@ -99,7 +94,7 @@ public class MultiPrintStream extends PrintStream {
/** /**
* Remove a PrintStream from the list * 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){ public void removePrintStream(PrintStream p){
streams.remove(p); streams.remove(p);
@ -107,7 +102,7 @@ public class MultiPrintStream extends PrintStream {
/** /**
* Remove a PrintStream from the list * 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){ public void removePrintStream(int p){
streams.remove(p); streams.remove(p);
@ -206,8 +201,8 @@ public class MultiPrintStream extends PrintStream {
* <br>- Reader content (Prints out until the end of the reader) * <br>- Reader content (Prints out until the end of the reader)
* <br>- Instance variables of a Object * <br>- Instance variables of a Object
* *
* @param o is the Object to dump * @param o is the Object to dump
* @return A String with all the printed data * @return a String with all the printed data
*/ */
public String dumpToString( Object o) { public String dumpToString( Object o) {
return dumpToString(o, ""); return dumpToString(o, "");
@ -222,8 +217,8 @@ public class MultiPrintStream extends PrintStream {
* <br>- Reader content (Prints out until the end of the reader) * <br>- Reader content (Prints out until the end of the reader)
* <br>- Instance variables of a Object * <br>- Instance variables of a Object
* *
* @param o is the Object to dump * @param o is the Object to dump
* @param head is the string that will be put in front of every line * @param head is the string that will be put in front of every line
* @return A String with all the printed data * @return A String with all the printed data
*/ */

View file

@ -45,7 +45,7 @@ import zutil.log.LogUtil;
* @author Ziver * @author Ziver
*/ */
public class FileUtil { 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 * 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. * Reads and returns the content of a file as a String.
* Or use FileUtils.readFileToString(file); * Or use FileUtils.readFileToString(file);
* *
* @param file is the file to read * @param file
* @return The file content * @return the file content
* @throws IOException
*/ */
public static String getFileContent(File file) throws IOException{ 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. * Reads and returns the content of a file as a String.
* Or use FileUtils.readFileToString(file); * Or use FileUtils.readFileToString(file);
* *
* @param url is the url to read * @param url
* @return The file content * @return the file content
* @throws IOException
*/ */
public static String getContent(URL url) throws IOException{ 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;
} }
/** /**

View file

@ -24,23 +24,12 @@ package zutil.math;
public class Tick { 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) * Ticks a given string(increments the string with one)
* *
* @param ts The string to tick * @param ts is the string to tick
* @param maxChar The maximum number of characters in the string * @param maxChar is the maximum number of characters in the string
* @return The ticked string * @return the ticked string
*/ */
public static String tick(String ts, int maxChar){ public static String tick(String ts, int maxChar){
StringBuffer ret = new StringBuffer(ts.trim()); StringBuffer ret = new StringBuffer(ts.trim());
@ -72,17 +61,17 @@ public class Tick {
/** /**
* Increments the char with one after the swedish alfabet * Increments the char with one after the swedish alfabet
* *
* @param c The char to increment * @param c is the char to increment
* @return The incremented char in lowercase 0 if it reached the end * @return the incremented char in lowercase 0 if it reached the end
*/ */
public static char increment(char c){ public static char increment(char c){
switch(Character.toLowerCase(c)){ switch(Character.toLowerCase(c)){
case 'z': return 'å'; case 'z': return (char)134;
case 'å': return 'ä'; case (char)134: return (char)132;
case 'ä': return 'ö'; case (char)132: return (char)148;
} }
c = (char)(Character.toLowerCase(c) + 1); c = (char)(Character.toLowerCase(c) + 1);
if(isAlfa(c)){ if(isAlphabetic(c)){
return c; return c;
} }
return 0; return 0;
@ -90,12 +79,12 @@ public class Tick {
/** /**
* Checks if the char is a valid character in * Checks if the char is a valid character in
* the Swedish alfabet * the Swedish alphabet
* *
* @param c The char to check * @param c is the char to check
* @return True if the char is a valid letter * @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)){ switch(Character.toLowerCase(c)){
case 'a': case 'a':
case 'b': case 'b':
@ -123,10 +112,12 @@ public class Tick {
case 'x': case 'x':
case 'y': case 'y':
case 'z': case 'z':
case 'å': case (char)134:
case 'ä': case (char)132:
case 'ö': return true; case (char)148:
default: return false; return true;
default:
return false;
} }
} }
} }

View file

@ -22,20 +22,13 @@
package zutil.net; package zutil.net;
import java.io.BufferedReader; import zutil.io.IOUtil;
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 javax.security.auth.login.AccountException; import javax.security.auth.login.AccountException;
import java.io.*;
import zutil.io.MultiPrintStream; import java.net.Socket;
import java.net.UnknownHostException;
import java.util.regex.Pattern;
/** /**
* A simple FTP client class * A simple FTP client class
@ -49,82 +42,71 @@ import zutil.io.MultiPrintStream;
* TODO: file info, rename, Active mode * TODO: file info, rename, Active mode
*/ */
public class FTPClient extends Thread{ public class FTPClient extends Thread{
public static boolean DEBUG = true; 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_ACTIVE = 0; public static enum FTPConnectionType{
public static final int FTP_PASSIVE = 1; ACTIVE,
public static final int FTP_PORT = 21; PASSIVE
public static final int FTP_DATA_PORT = 20; }
public static final int FTP_NOOP_INT = 120;
//************** FTP Return Codes ****************** public static enum FTPReturnCode{
public static final int FTPC_USER_OK = 331; UNKNOWN ( -1 ),
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; USER_OK ( 331 ),
public static final int FTPC_FILE_ACTION_OK = 250; NEED_PASS ( 331 ),
public static final int FTPC_PATH_CREATED = 257; 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 BufferedReader in;
private PrintStream out; private Writer out;
private Socket socket; private Socket socket;
private long last_sent; 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<String[]> 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 * Creates a FTP connection and logs in
* *
* @param url The address to server * @param url the address to server
* @param port Port number * @param port port number
* @param user User name * @param user login username
* @param pass Password * @param pass password
* @param connection_type Pasive or Active * @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); socket = new Socket(url, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 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); sendCommand("USER "+user);
sendNoReplyCommand("PASS "+pass, DEBUG); sendNoReplyCommand("PASS "+pass);
if(DEBUG)System.out.println("PASS ***"); String tmp = readCommand();
String tmp = readMultipleCommands(DEBUG); if(parseReturnCode(tmp) == FTPReturnCode.LOGIN_NO){
if(parseReturnCode(tmp) == FTPC_LOGIN_NO){
close(); close();
throw new AccountException(tmp); throw new AccountException(tmp);
} }
@ -132,221 +114,152 @@ public class FTPClient extends Thread{
start(); start();
} }
//**************************************************************************************
//************************************************************************************** //**************************************************************************************
//********************************* Command channel ************************************ //********************************* Command channel ************************************
/** /**
* Sends the given line to the server and returns a status integer * Sends the given command to the server and returns a status integer
* *
* @param cmd The command to send * @return last line received from the server
* @return The return code from the server
* @throws IOException
*/ */
public synchronized int sendCommand(String cmd) throws IOException{ private FTPReturnCode sendCommand(String cmd) throws IOException{
return parseReturnCode(sendCommand(cmd, DEBUG)); sendNoReplyCommand(cmd);
return parseReturnCode( readCommand( ) );
} }
/** /**
* Sends the given line to the server and returns the last line * Sends a command and don't cares about the reply
*
* @param cmd The command to send
* @param print To print out the received lines
* @return Last String line from the server
* @throws IOException
*/ */
private synchronized String sendCommand(String cmd, boolean print) throws IOException{ private void sendNoReplyCommand(String cmd) throws IOException{
sendNoReplyCommand(cmd, print); last_sent = System.currentTimeMillis();
return readCommand(print); 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 * Reads from the command channel until there are nothing
* left to read and returns the last line * left to read and returns the last line
* *
* @param print To print out the received lines * @return last line received by the server
* @return The last received line
* @throws IOException
*/ */
private synchronized String readMultipleCommands(boolean print) throws IOException{ private String readCommand() throws IOException{
String tmp = readCommand(print);
while(!tmp.substring(3, 4).equalsIgnoreCase(" ")){
tmp = readCommand(print);
}
/*
String tmp = in.readLine(); String tmp = in.readLine();
if(print)System.out.println(tmp); while(!Character.isWhitespace(tmp.charAt(3))){
try{ Thread.sleep(500); }catch(Exception e){}
while(in.ready()){
tmp = in.readLine(); tmp = in.readLine();
if(print)System.out.println(tmp); if(parseReturnCode(tmp).isError()) throw new IOException(tmp);
try{ Thread.sleep(500); }catch(Exception e){}
} }
*/
return tmp; return tmp;
} }
/** /**
* Parses the return line from the server and returns the status code * Parses the return line from the server and returns the status code
* *
* @param msg The message from the server * @param msg message String from the server
* @return The status code * @return a status code response
* @throws IOException
*/ */
private synchronized int parseReturnCode(String msg){ private FTPReturnCode parseReturnCode(String msg){
return Integer.parseInt(msg.substring(0, 3)); return FTPReturnCode.fromCode(Integer.parseInt(msg.substring(0, 3)));
} }
//**************************************************************************************
//************************************************************************************** //**************************************************************************************
//****************************** File system actions ************************************ //****************************** File system actions ************************************
/** /**
* Returns a LinkedList with the names of all the files in the directory * Returns a LinkedList with names of all the files in the directory
* *
* @param path Path to the files to be listed * @deprecated
* @return LinkedList whit filenames * @return List with filenames
* @throws IOException
*/ */
public LinkedList<String> getFileList(String path) throws IOException{ public String[] getFileList(String path) throws IOException{
LinkedList<String> list = new LinkedList<String>(); BufferedInputStream data_in = getDataInputStream();
sendCommand("NLST "+path);
BufferedReader data_in = getDataInputStream(); String data = new String(IOUtil.getContent(data_in));
sendCommand("NLST "+path, DEBUG);
String tmp = "";
while((tmp = data_in.readLine()) != null){
list.add(tmp);
}
data_in.close(); data_in.close();
readCommand(DEBUG); readCommand();
return list; return data.split("[\n\r]");
} }
/** /**
* Returns information about the file or directory * Returns information about a file or directory
* *
* @deprecated * @deprecated
* @param path The path and filename of a file or a directory * @return a List of Strings with information
* @return A List of Strings with information
* @throws IOException
*/ */
public ArrayList<String[]> getFileInfo(String path) throws IOException{ public String getFileInfo(String path) throws IOException{
Pattern regex = Pattern.compile("\\s{1,}"); Pattern regex = Pattern.compile("\\s{1,}");
ArrayList<String[]> info = new ArrayList<String[]>();
BufferedReader data_in = getDataInputStream(); BufferedInputStream data_in = getDataInputStream();
sendCommand("LIST "+path, DEBUG); sendCommand("LIST "+path);
String tmp = ""; String data = new String(IOUtil.getContent(data_in));
while((tmp = data_in.readLine()) != null){
System.err.println(tmp);
info.add(regex.split(tmp));
}
data_in.close(); data_in.close();
readCommand(DEBUG); readCommand();
return info; 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 path filepath
* @param data The data to put in the file * @param data data to put in the file
* @throws IOException
*/ */
public void sendFile(String path, String data) throws IOException{ public void sendFile(String path, String data) throws IOException{
PrintStream data_out = getDataOutputStream(); BufferedOutputStream data_out = getDataOutputStream();
sendCommand("STOR "+path, DEBUG); sendCommand("STOR "+path);
data_out.println(data);
byte[] byte_data = data.getBytes();
data_out.write(byte_data, 0, byte_data.length);
data_out.close(); 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 * @param path The path to the directory
* @throws IOException
*/ */
public boolean createDir(String path) 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 true;
return false; return false;
} }
/** /**
* Returns a BufferedReader with the file data * Returns a InputStream for a file on the server
* WARNING: you must run readCommand(true); after you close the stream * WARNING: you must run readCommand(); after you close the stream
* *
* @param path The path and filename * @return a stream with file data
* @return Stream with the file
* @throws IOException
*/ */
private BufferedReader getFile(String path) throws IOException{ private BufferedInputStream getFileInputStream(String path) throws IOException{
BufferedReader ret = getDataInputStream(); BufferedInputStream input = getDataInputStream();
sendCommand("RETR "+path, DEBUG); sendCommand("RETR "+path);
return ret; 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 source source file on the server
* @param destination The local file to save to * @param destination local destination file
* @throws IOException
*/ */
public void getFile(String source, String destination) throws IOException{ public void getFile(String source, String destination) throws IOException{
BufferedReader file_in = getFile(source); BufferedInputStream ext_file_in = getFileInputStream(source);
PrintStream file_out = new PrintStream(new File(destination)); BufferedOutputStream local_file_out = new BufferedOutputStream(new FileOutputStream(new File(destination)));
String tmp = ""; IOUtil.copyStream(ext_file_in, local_file_out);
while((tmp = file_in.readLine()) != null){ readCommand();
file_out.println(tmp);
}
readCommand(DEBUG);
} }
/** /**
* Removes a file from the FTP server * Remove 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, false otherwise
* @return True if the command was successful or false otherwise
* @throws IOException
*/ */
public boolean removeFile(String path) throws IOException{ 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 true;
return false; return false;
} }
@ -354,136 +267,63 @@ public class FTPClient extends Thread{
/** /**
* Removes a directory from the FTP server * 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 * @return True if the command was successful or false otherwise
* @throws IOException
*/ */
public boolean removeDir(String path) 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 true;
return false; return false;
} }
//**************************************************************************************
//************************************************************************************** //**************************************************************************************
//******************************** Data Connection ************************************* //******************************** Data Connection *************************************
/** /**
* Starts a connection to the server. It automatically handles * Start a data connection to the server.
* passive or active mode
* *
* @return The PrintStream for the channel * @return a PrintStream for the channel
* @throws IOException
*/ */
public synchronized PrintStream getDataOutputStream() throws IOException{ public BufferedOutputStream getDataOutputStream() throws IOException{
int port = getDataConnectionPortType(); if(connectionType == FTPConnectionType.PASSIVE){ // Passive Mode
if(port < 0){ // Active Mode int port = setPassiveMode();
port *= -1; Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port);
return getActiveDataOutputStream(port); return new BufferedOutputStream(data_socket.getOutputStream());
} }
else{ else{ // Active Mode
System.out.println("port: "+port); return null;
return getPassiveDataOutputStream(port);
} }
} }
/** /**
* Starts a connection to the server. It automatically handles * Start a data connection to the server.
* passive or active mode
* *
* @return The BufferedReader for the channel * @return a BufferedReader for the data channel
* @throws IOException
*/ */
public synchronized BufferedReader getDataInputStream() throws IOException{ public BufferedInputStream getDataInputStream() throws IOException{
int port = getDataConnectionPortType(); if(connectionType == FTPConnectionType.PASSIVE){ // Passive Mode
if(port < 0){ // Active Mode int port = setPassiveMode();
port *= -1; Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port);
return getActiveDataInputStream(port); return new BufferedInputStream(data_socket.getInputStream());
} }
else{ else{ // Active Mode
return getPassiveDataInputStream(port); return null;
} }
} }
/**
* This method chooses the appropriate data connection type
* to the server (Passive or Active) and returns the port number
*
* @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 * Sets Passive mode to the server
* *
* @param port The port to connect to * @return a port number for data channel
* @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
*/ */
private int setPassiveMode() throws IOException{ private int setPassiveMode() throws IOException{
String tmp = sendCommand("PASV", DEBUG); sendNoReplyCommand("PASV");
if(parseReturnCode(tmp) != FTPC_ENTERING_PASSIVE){ String ret_msg = readCommand();
throw new IOException(tmp); 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(')')); ret_msg = ret_msg.substring(ret_msg.indexOf('(')+1, ret_msg.indexOf(')'));
String[] tmpArray = tmp.split("[,]"); String[] tmpArray = ret_msg.split("[,]");
if(tmpArray.length <= 1) if(tmpArray.length <= 1)
return Integer.parseInt(tmpArray[0]); 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(){ public void run(){
try { try {
@ -512,15 +352,12 @@ public class FTPClient extends Thread{
/** /**
* Close the FTP connection * Close the FTP connection
*
* @throws IOException
*/ */
@SuppressWarnings("deprecation")
public void close() throws IOException{ public void close() throws IOException{
sendCommand("QUIT", DEBUG); sendCommand("QUIT");
in.close(); in.close();
out.close(); out.close();
socket.close(); socket.close();
this.stop(); this.interrupt();
} }
} }

View file

@ -48,7 +48,7 @@ import zutil.net.threaded.ThreadedTCPNetworkServerThread;
* @author Ziver * @author Ziver
*/ */
public class HttpServer extends ThreadedTCPNetworkServer{ 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 String SERVER_VERSION = "Ziver HttpServer 1.0";
public static final int COOKIE_TTL = 200; public static final int COOKIE_TTL = 200;
public static final int SESSION_TTL = 10*60*1000; // in milliseconds public static final int SESSION_TTL = 10*60*1000; // in milliseconds

View file

@ -81,7 +81,7 @@ import zutil.parser.wsdl.WSDLWriter;
* @author Ziver * @author Ziver
*/ */
public class SOAPHttpPage implements HttpPage{ 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 **/ /** The object that the functions will be invoked from **/
private WebServiceDef wsDef; private WebServiceDef wsDef;

View file

@ -44,7 +44,7 @@ import zutil.net.threaded.ThreadedUDPNetworkThread;
* @author Ziver * @author Ziver
*/ */
public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetworkThread{ 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 // Contains all the received services
private HashMap<String, LinkedList<SSDPServiceInfo>> services_st; private HashMap<String, LinkedList<SSDPServiceInfo>> services_st;
private HashMap<String, SSDPServiceInfo> services_usn; private HashMap<String, SSDPServiceInfo> services_usn;

View file

@ -64,7 +64,7 @@ import zutil.net.threaded.ThreadedUDPNetwork;
* NTS: same as Man but for Notify messages * NTS: same as Man but for Notify messages
*/ */
public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetworkThread{ 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 String SERVER_INFO = "SSDP Java Server by Ziver Koc";
public static final int DEFAULT_CACHE_TIME = 60*30; // 30 min public static final int DEFAULT_CACHE_TIME = 60*30; // 30 min
public static final int BUFFER_SIZE = 512; public static final int BUFFER_SIZE = 512;

View file

@ -43,7 +43,7 @@ import zutil.log.LogUtil;
* *
*/ */
public class UpdateClient{ public class UpdateClient{
public static final Logger logger = LogUtil.getLogger(); private static final Logger logger = LogUtil.getLogger();
private String path; private String path;
private Socket socket; private Socket socket;

View file

@ -36,7 +36,7 @@ import zutil.net.threaded.ThreadedTCPNetworkServer;
import zutil.net.threaded.ThreadedTCPNetworkServerThread; import zutil.net.threaded.ThreadedTCPNetworkServerThread;
public class UpdateServer extends ThreadedTCPNetworkServer{ public class UpdateServer extends ThreadedTCPNetworkServer{
public static final Logger logger = LogUtil.getLogger(); private static final Logger logger = LogUtil.getLogger();
private FileListMessage fileList; private FileListMessage fileList;

View file

@ -106,11 +106,11 @@ public class Base64Decoder {
} }
public String toString(){ public String toString(){
return output.getString(); return output.toString();
} }
public byte[] getByte(){ public byte[] getByte(){
return output.getByte(); return output.getBytes();
} }
public void clear(){ public void clear(){

View file

@ -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());
}
}

View file

@ -29,7 +29,7 @@ import zutil.log.LogUtil;
import zutil.log.net.NetLogServer; import zutil.log.net.NetLogServer;
public class NetLogServerTest { public class NetLogServerTest {
public static final Logger logger = LogUtil.getLogger(); private static final Logger logger = LogUtil.getLogger();
public static void main(String[] args){ public static void main(String[] args){
LogUtil.setGlobalLevel(Level.FINEST); LogUtil.setGlobalLevel(Level.FINEST);