diff --git a/.gitignore b/.gitignore index 84c048a..df5faf1 100755 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ +Zutil.jar /build/ diff --git a/src/zutil/Hasher.java b/src/zutil/Hasher.java old mode 100644 new mode 100755 index 1585882..75cf704 --- a/src/zutil/Hasher.java +++ b/src/zutil/Hasher.java @@ -24,7 +24,7 @@ package zutil; -import zutil.converters.Converter; +import zutil.converter.Converter; import javax.crypto.Mac; import javax.crypto.SecretKeyFactory; diff --git a/src/zutil/StringUtil.java b/src/zutil/StringUtil.java index 791be0d..75c2988 100755 --- a/src/zutil/StringUtil.java +++ b/src/zutil/StringUtil.java @@ -24,7 +24,7 @@ package zutil; -import zutil.converters.Converter; +import zutil.converter.Converter; import java.util.ArrayList; import java.util.Iterator; diff --git a/src/zutil/converters/Converter.java b/src/zutil/converter/Converter.java similarity index 96% rename from src/zutil/converters/Converter.java rename to src/zutil/converter/Converter.java index f58ae0c..15a76c3 100755 --- a/src/zutil/converters/Converter.java +++ b/src/zutil/converter/Converter.java @@ -1,460 +1,460 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.converters; - -import zutil.io.DynamicByteArrayStream; -import zutil.parser.Base64Decoder; - -import java.io.*; -import java.util.BitSet; -import java.util.Iterator; -import java.util.Map; - -public class Converter { - private Converter(){} - - /** - * Converts an object to an array of bytes. - * - * @param object the object to convert. - * @return the associated byte array. - */ - public static byte[] toBytes(Object object) throws IOException{ - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(object); - oos.flush(); - oos.close(); - - return baos.toByteArray(); - } - - /** - * Converts a Integer to an byte array - * - * @param num is the number to convert - * @return a byte array of four bytes - */ - public static byte[] toBytes(int num){ - return new byte[]{ - (byte)(num & 0xff), - (byte)((num >> 8)& 0xff), - (byte)((num >> 16)& 0xff), - (byte)((num >> 24)& 0xff)}; - } - - /** - * Converts a Integer to a byte - * - * @param num is the number to convert - * @return a byte value of the integer - */ - public static byte toByte(int num){ - return (byte)(num & 0xff); - } - - /** - * Converts hex string to a byte array - * - * @param hex a String containing data coded in hex - * @return a byte array - */ - public static byte[] hexToByte(String hex){ - if(hex == null) - return null; - if(hex.startsWith("0x")) - hex = hex.substring(2); - byte[] b = new byte[(int)Math.ceil(hex.length()/2.0)]; - for(int i=hex.length()-1; i>=0; i-=2){ - if(i-1 < 0) - b[(hex.length()-i-1)/2] = hexToByte(hex.charAt(i)); - else - b[(hex.length()-i-1)/2] = hexToByte(hex.charAt(i-1), hex.charAt(i)); - } - return b; - } - - /** - * 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 - */ - public static byte hexToByte( char quad1, char quad2){ - byte b = hexToByte( quad2 ); - b |= hexToByte( quad1 ) << 4; - return b; - } - - /** - * Converts a hex chars to a byte - * - * @param hex is the hex value - * @return a byte that corresponds to the hex - */ - public static byte hexToByte( char hex ){ - switch( Character.toLowerCase(hex) ){ - case '0': return 0x00; - case '1': return 0x01; - case '2': return 0x02; - case '3': return 0x03; - case '4': return 0x04; - case '5': return 0x05; - case '6': return 0x06; - case '7': return 0x07; - case '8': return 0x08; - case '9': return 0x09; - case 'a': return 0x0a; - case 'b': return 0x0b; - case 'c': return 0x0c; - case 'd': return 0x0d; - case 'e': return 0x0e; - case 'f': return 0x0f; - } - return (byte)0; - } - - /** - * 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. - */ - public static Object toObject(byte[] bytes) throws Exception{ - Object object = null; - - ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); - object = ois.readObject(); - ois.close(); - - return object; - } - - /** - * 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. - */ - public static Object toObject(DynamicByteArrayStream bytes) throws Exception{ - Object object = null; - - ObjectInputStream ois = new ObjectInputStream(bytes); - object = ois.readObject(); - ois.close(); - - return object; - } - - - /** array needed for byteToHex */ - private static char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; - /** - * Converts a byte Array to a Hex String - * - * @param raw the byte array to convert - * @return a hex String - */ - public static String toHexString(byte[][] raw){ - StringBuffer ret = new StringBuffer(); - - for(byte[] a : raw){ - for(byte b : a){ - ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]); - ret.append(HEX_CHARS[(int) b & 0x0F ]); - } - } - - return ret.toString(); - } - - public static String toHexStringByColumn(byte[][] raw){ - StringBuffer ret = new StringBuffer(); - - for(int col=0; col>> 0x04)& 0x0F ]); - ret.append(HEX_CHARS[(int) raw[row][col] & 0x0F ]); - } - } - - return ret.toString(); - } - - /** - * Converts a byte Array to a Hex String - * - * @param raw the byte array to convert - * @return a hex String - */ - public static String toHexString(byte[] raw){ - StringBuffer ret = new StringBuffer(); - - for(byte b : raw){ - ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]); - ret.append(HEX_CHARS[(int) b & 0x0F ]); - } - - return ret.toString(); - } - - /** - * Converts a byte to 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 ]; - ret += ""+HEX_CHARS[(int) raw & 0x0F ]; - - return ret; - } - - /** - * 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 - */ - public static String toString(byte raw){ - StringBuffer ret = new StringBuffer(); - for(int i=128; i>0 ;i=( i<1 ? i=0 : i/2 ) ){ - ret.append(( (raw & i) == 0 ? '0' : '1')); - } - return ret.toString(); - } - - /** - * 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 - */ - public static String toString(byte[] raw){ - StringBuffer ret = new StringBuffer(); - for(byte b : raw){ - for(int i=128; i>0 ;i=( i<1 ? i=0 : i/2 ) ){ - ret.append(( (b & i) == 0 ? '0' : '1')); - } - } - return ret.toString(); - } - - /** - * Generates a comma separated string with key and value pairs - * - * @return a comma separated String - */ - public static String toString(Map map){ - StringBuilder tmp = new StringBuilder(); - tmp.append("{"); - Iterator it = map.keySet().iterator(); - while(it.hasNext()){ - Object key = it.next(); - Object value = map.get(key); - tmp.append(key); - if (value != null) { - if (value instanceof String) - tmp.append(": \"").append(value).append("\""); - else - tmp.append(value); - } - else - tmp.append("null"); - - if(it.hasNext()) - tmp.append(", "); - } - tmp.append('}'); - return tmp.toString(); - } - - /** - * Converts a BitSet to a Integer - * - * @param bits the BitSet to convert - * @return a Integer - */ - public static int toInt(BitSet bits){ - int ret = 0; - - for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i+1)) { - ret += Math.pow(2, i); - } - - return ret; - } - - /** - * 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 - */ - public static int toInt(boolean[] bits){ - int ret = 0; - - for (int i = bits.length-1; i >= 0; i--) { - if(bits[i])ret += Math.pow(2, bits.length-i-1); - } - - return ret; - } - - /** - * Converts a byte to a 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); - } - - /** - * Converts a dynamic sized byte array to a integer - * - * @param b is the byte array of size 1-4 - * @return the int value of the byte array - */ - public static int toInt(byte[] b){ - int i = 0; - switch (b.length){ - default: - case 4: - i |= 0xFF000000 & (b[0] << 24); - i |= 0x00FF0000 & (b[1] << 16); - i |= 0x0000FF00 & (b[2] << 8); - i |= 0x000000FF & b[3]; - break; - case 3: - i |= 0x00FF0000 & (b[0] << 16); - i |= 0x0000FF00 & (b[1] << 8); - i |= 0x000000FF & b[2]; - break; - case 2: - i |= 0x0000FF00 & (b[0] << 8); - i |= 0x000000FF & b[1]; - break; - case 1: - i |= 0x000000FF & b[0]; - break; - case 0: break; - } - return i; - } - - /** - * Converts a Integer to a BitSet - * - * @param num the Integer to convert - * @return a BitSet object - */ - public static BitSet toBitSet(int num){ - BitSet ret = new BitSet(); - String tmp = Integer.toBinaryString(num); - - for(int i=0; i 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){ - if(data == null || data.isEmpty()) - return null; - try{ - if( c == String.class) return (T) data; - else if(c == Integer.class) return (T) new Integer(data); - else if(c == int.class) return (T) new Integer(data); - else if(c == Long.class) return (T) new Long(data); - else if(c == long.class) return (T) new Long(data); - else if(c == Float.class) return (T) new Float(data); - else if(c == float.class) return (T) new Float(data); - else if(c == Double.class) return (T) new Double(data); - else if(c == double.class) return (T) new Double(data); - else if(c == Boolean.class) return (T) new Boolean(data); - else if(c == boolean.class) return (T) new Boolean(data); - else if(c == Byte.class) return (T) new Byte(data); - else if(c == byte.class) return (T) new Byte(data); - else if(byte[].class.isAssignableFrom(c)) - return (T) Base64Decoder.decode(data); - }catch(Exception e){ - e.printStackTrace(); - } - return null; - } - - /** - * Replaces reserved and unsafe characters in URLs with hex values - */ - public static String urlEncode( String str ){ - StringBuilder out = new StringBuilder(); - for( char c : str.toCharArray() ){ - if( c>='0' && c<='9' || c>='A' && c<='Z' || c>='a' && c<='z' || - c=='$' || c=='-' || c=='_' || c=='.' || c=='+' || c=='!' || - c=='*' || c=='\'' || c=='(' || c==')' || c==',' ) - out.append( c ); - else{ - out.append( '%' ).append( toHexString((byte)c) ); - } - } - - return out.toString(); - } - - /** - * Replaces hex values from a URL with the proper characters - */ - public static String urlDecode( String str ){ - StringBuilder out = new StringBuilder(); - char[] array = str.toCharArray(); - for( int i=0; i> 8)& 0xff), + (byte)((num >> 16)& 0xff), + (byte)((num >> 24)& 0xff)}; + } + + /** + * Converts a Integer to a byte + * + * @param num is the number to convert + * @return a byte value of the integer + */ + public static byte toByte(int num){ + return (byte)(num & 0xff); + } + + /** + * Converts hex string to a byte array + * + * @param hex a String containing data coded in hex + * @return a byte array + */ + public static byte[] hexToByte(String hex){ + if(hex == null) + return null; + if(hex.startsWith("0x")) + hex = hex.substring(2); + byte[] b = new byte[(int)Math.ceil(hex.length()/2.0)]; + for(int i=hex.length()-1; i>=0; i-=2){ + if(i-1 < 0) + b[(hex.length()-i-1)/2] = hexToByte(hex.charAt(i)); + else + b[(hex.length()-i-1)/2] = hexToByte(hex.charAt(i-1), hex.charAt(i)); + } + return b; + } + + /** + * 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 + */ + public static byte hexToByte( char quad1, char quad2){ + byte b = hexToByte( quad2 ); + b |= hexToByte( quad1 ) << 4; + return b; + } + + /** + * Converts a hex chars to a byte + * + * @param hex is the hex value + * @return a byte that corresponds to the hex + */ + public static byte hexToByte( char hex ){ + switch( Character.toLowerCase(hex) ){ + case '0': return 0x00; + case '1': return 0x01; + case '2': return 0x02; + case '3': return 0x03; + case '4': return 0x04; + case '5': return 0x05; + case '6': return 0x06; + case '7': return 0x07; + case '8': return 0x08; + case '9': return 0x09; + case 'a': return 0x0a; + case 'b': return 0x0b; + case 'c': return 0x0c; + case 'd': return 0x0d; + case 'e': return 0x0e; + case 'f': return 0x0f; + } + return (byte)0; + } + + /** + * 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. + */ + public static Object toObject(byte[] bytes) throws Exception{ + Object object = null; + + ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); + object = ois.readObject(); + ois.close(); + + return object; + } + + /** + * 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. + */ + public static Object toObject(DynamicByteArrayStream bytes) throws Exception{ + Object object = null; + + ObjectInputStream ois = new ObjectInputStream(bytes); + object = ois.readObject(); + ois.close(); + + return object; + } + + + /** array needed for byteToHex */ + private static char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; + /** + * Converts a byte Array to a Hex String + * + * @param raw the byte array to convert + * @return a hex String + */ + public static String toHexString(byte[][] raw){ + StringBuffer ret = new StringBuffer(); + + for(byte[] a : raw){ + for(byte b : a){ + ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]); + ret.append(HEX_CHARS[(int) b & 0x0F ]); + } + } + + return ret.toString(); + } + + public static String toHexStringByColumn(byte[][] raw){ + StringBuffer ret = new StringBuffer(); + + for(int col=0; col>> 0x04)& 0x0F ]); + ret.append(HEX_CHARS[(int) raw[row][col] & 0x0F ]); + } + } + + return ret.toString(); + } + + /** + * Converts a byte Array to a Hex String + * + * @param raw the byte array to convert + * @return a hex String + */ + public static String toHexString(byte[] raw){ + StringBuffer ret = new StringBuffer(); + + for(byte b : raw){ + ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]); + ret.append(HEX_CHARS[(int) b & 0x0F ]); + } + + return ret.toString(); + } + + /** + * Converts a byte to 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 ]; + ret += ""+HEX_CHARS[(int) raw & 0x0F ]; + + return ret; + } + + /** + * 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 + */ + public static String toString(byte raw){ + StringBuffer ret = new StringBuffer(); + for(int i=128; i>0 ;i=( i<1 ? i=0 : i/2 ) ){ + ret.append(( (raw & i) == 0 ? '0' : '1')); + } + return ret.toString(); + } + + /** + * 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 + */ + public static String toString(byte[] raw){ + StringBuffer ret = new StringBuffer(); + for(byte b : raw){ + for(int i=128; i>0 ;i=( i<1 ? i=0 : i/2 ) ){ + ret.append(( (b & i) == 0 ? '0' : '1')); + } + } + return ret.toString(); + } + + /** + * Generates a comma separated string with key and value pairs + * + * @return a comma separated String + */ + public static String toString(Map map){ + StringBuilder tmp = new StringBuilder(); + tmp.append("{"); + Iterator it = map.keySet().iterator(); + while(it.hasNext()){ + Object key = it.next(); + Object value = map.get(key); + tmp.append(key); + if (value != null) { + if (value instanceof String) + tmp.append(": \"").append(value).append("\""); + else + tmp.append(value); + } + else + tmp.append("null"); + + if(it.hasNext()) + tmp.append(", "); + } + tmp.append('}'); + return tmp.toString(); + } + + /** + * Converts a BitSet to a Integer + * + * @param bits the BitSet to convert + * @return a Integer + */ + public static int toInt(BitSet bits){ + int ret = 0; + + for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i+1)) { + ret += Math.pow(2, i); + } + + return ret; + } + + /** + * 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 + */ + public static int toInt(boolean[] bits){ + int ret = 0; + + for (int i = bits.length-1; i >= 0; i--) { + if(bits[i])ret += Math.pow(2, bits.length-i-1); + } + + return ret; + } + + /** + * Converts a byte to a 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); + } + + /** + * Converts a dynamic sized byte array to a integer + * + * @param b is the byte array of size 1-4 + * @return the int value of the byte array + */ + public static int toInt(byte[] b){ + int i = 0; + switch (b.length){ + default: + case 4: + i |= 0xFF000000 & (b[0] << 24); + i |= 0x00FF0000 & (b[1] << 16); + i |= 0x0000FF00 & (b[2] << 8); + i |= 0x000000FF & b[3]; + break; + case 3: + i |= 0x00FF0000 & (b[0] << 16); + i |= 0x0000FF00 & (b[1] << 8); + i |= 0x000000FF & b[2]; + break; + case 2: + i |= 0x0000FF00 & (b[0] << 8); + i |= 0x000000FF & b[1]; + break; + case 1: + i |= 0x000000FF & b[0]; + break; + case 0: break; + } + return i; + } + + /** + * Converts a Integer to a BitSet + * + * @param num the Integer to convert + * @return a BitSet object + */ + public static BitSet toBitSet(int num){ + BitSet ret = new BitSet(); + String tmp = Integer.toBinaryString(num); + + for(int i=0; i 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){ + if(data == null || data.isEmpty()) + return null; + try{ + if( c == String.class) return (T) data; + else if(c == Integer.class) return (T) new Integer(data); + else if(c == int.class) return (T) new Integer(data); + else if(c == Long.class) return (T) new Long(data); + else if(c == long.class) return (T) new Long(data); + else if(c == Float.class) return (T) new Float(data); + else if(c == float.class) return (T) new Float(data); + else if(c == Double.class) return (T) new Double(data); + else if(c == double.class) return (T) new Double(data); + else if(c == Boolean.class) return (T) new Boolean(data); + else if(c == boolean.class) return (T) new Boolean(data); + else if(c == Byte.class) return (T) new Byte(data); + else if(c == byte.class) return (T) new Byte(data); + else if(byte[].class.isAssignableFrom(c)) + return (T) Base64Decoder.decode(data); + }catch(Exception e){ + e.printStackTrace(); + } + return null; + } + + /** + * Replaces reserved and unsafe characters in URLs with hex values + */ + public static String urlEncode( String str ){ + StringBuilder out = new StringBuilder(); + for( char c : str.toCharArray() ){ + if( c>='0' && c<='9' || c>='A' && c<='Z' || c>='a' && c<='z' || + c=='$' || c=='-' || c=='_' || c=='.' || c=='+' || c=='!' || + c=='*' || c=='\'' || c=='(' || c==')' || c==',' ) + out.append( c ); + else{ + out.append( '%' ).append( toHexString((byte)c) ); + } + } + + return out.toString(); + } + + /** + * Replaces hex values from a URL with the proper characters + */ + public static String urlDecode( String str ){ + StringBuilder out = new StringBuilder(); + char[] array = str.toCharArray(); + for( int i=0; i 2){ - sec = Float.parseFloat(tmp[2]); - } - } - // 3444.0000S 13521.0000E - else if(coordinate.matches("[0-9]{4,5}.[0-9]*[NSEW]{1}")){ - coordinate = coordinate.replaceAll("[NS EW]", ""); - float tmpf = Float.parseFloat(coordinate); - deg = (int)(tmpf/100); - min = tmpf-(deg*100); - } - // 55.0 68.99999 - else if(coordinate.matches("\\-?[0-9]{2,3}.[0-9]*")){ - return Float.parseFloat(coordinate); - } - - return neg*(deg + min/60 + sec/3600); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.converter; + +public class WGS84Converter { + public static void main(String[] args){ + System.out.println(toWGS84Decimal("N 59� 47' 43\"")+" "+toWGS84Decimal(" E 17� 42' 55\"")); + System.out.println(toWGS84Decimal("55� 0' 0\"")+" "+toWGS84Decimal("68� 59' 59,999\"")); + System.out.println(toWGS84Decimal("55� 0.001'")+" "+toWGS84Decimal("68� 59.999'")); + System.out.println(toWGS84Decimal("3444.0000S")+" "+toWGS84Decimal("13521.0000E")); + System.out.println(toWGS84Decimal("-44.0001")+" "+toWGS84Decimal("521.0001")); + } + + /** + * Converts an WGS84 coordinate to an WGS84 decimal coordinate + * + * @param coordinate is the coordinate to convert + * @return the new coordinate in decimal degrees, returns 0 if conversions fails + */ + public static float toWGS84Decimal(String coordinate){ + float deg=0, min=0, sec=0, neg=1; + coordinate = coordinate.trim().replaceAll(",", ".").toUpperCase(); + if(coordinate.contains("S") || coordinate.contains("W")) + neg = -1; + + // 55� 0' 68� 59,999 or 55� 0' 0" 68� 59' 59,999" + if(coordinate.matches("[NSWE ]? ?[0-9]{1,3}� [0-9]{1,2}.?[0-9]*'[ 0-9.\\\"]*")){ + coordinate = coordinate.replaceAll("[NSEW�'\\\"]", "").trim(); + String[] tmp = coordinate.split(" "); + deg = Float.parseFloat(tmp[0]); + min = Float.parseFloat(tmp[1]); + if(tmp.length > 2){ + sec = Float.parseFloat(tmp[2]); + } + } + // 3444.0000S 13521.0000E + else if(coordinate.matches("[0-9]{4,5}.[0-9]*[NSEW]{1}")){ + coordinate = coordinate.replaceAll("[NS EW]", ""); + float tmpf = Float.parseFloat(coordinate); + deg = (int)(tmpf/100); + min = tmpf-(deg*100); + } + // 55.0 68.99999 + else if(coordinate.matches("\\-?[0-9]{2,3}.[0-9]*")){ + return Float.parseFloat(coordinate); + } + + return neg*(deg + min/60 + sec/3600); + } +} diff --git a/src/zutil/db/DBQueue.java b/src/zutil/db/DBQueue.java old mode 100644 new mode 100755 index bcab42c..d4c72d9 --- a/src/zutil/db/DBQueue.java +++ b/src/zutil/db/DBQueue.java @@ -24,7 +24,7 @@ package zutil.db; -import zutil.converters.Converter; +import zutil.converter.Converter; import zutil.io.MultiPrintStream; import java.sql.PreparedStatement; diff --git a/src/zutil/image/filters/BlurFilter.java b/src/zutil/image/filter/BlurFilter.java old mode 100644 new mode 100755 similarity index 96% rename from src/zutil/image/filters/BlurFilter.java rename to src/zutil/image/filter/BlurFilter.java index e917da7..0edaeda --- a/src/zutil/image/filters/BlurFilter.java +++ b/src/zutil/image/filter/BlurFilter.java @@ -1,117 +1,117 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.image.filters; - -import zutil.image.ImageFilterProcessor; -import zutil.image.RAWImageUtil; -import zutil.math.ZMath; - -import java.awt.image.BufferedImage; - -public class BlurFilter extends ImageFilterProcessor{ - private int blurValue; - - /** - * Creates a blur effect on the image - * @param img The image to blur - */ - public BlurFilter(BufferedImage img){ - this(img, 10); - } - - /** - * Creates a blur effect on the image - * @param img The image to blur - * @param blur The amount to blur - */ - public BlurFilter(BufferedImage img, int blur){ - super(img); - blurValue = blur; - } - - @Override - public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { - int inputPeak = RAWImageUtil.getPeakValue(data); - - int[][][] tmpData = new int[data.length][data[0].length][4]; - int[][][] output = RAWImageUtil.copyArray(data); - //Perform the convolution one or more times in succession - int redSum, greenSum, blueSum, outputPeak; - for(int i=0; i 1) redScale = 1; - else if(redScale < 0) redScale = 0; - - if(greenScale > 1) greenScale = 1; - else if(greenScale < 0) greenScale = 0; - - if(blueScale > 1) blueScale = 1; - else if(blueScale < 0) blueScale = 0; - - // Applying the color intensity to the image - for(int y=startY; y 1) redScale = 1; + else if(redScale < 0) redScale = 0; + + if(greenScale > 1) greenScale = 1; + else if(greenScale < 0) greenScale = 0; + + if(blueScale > 1) blueScale = 1; + else if(blueScale < 0) blueScale = 0; + + // Applying the color intensity to the image + for(int y=startY; y Alpha data - * Red data - * Green data - * 4 -> Blue data - */ - public DitheringFilter(BufferedImage img, int[][] palette){ - super(img); - this.palette = palette; - } - - @Override - public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { - int error, index; - int[] currentPixel; - int[][][] output = RAWImageUtil.copyArray(data); - - for(int y=startY; y 0) - output[y+1][x-1][i] = RAWImageUtil.clip( output[y+1][x-1][i] + (error*3)/16 ); - output[y+1][x+0][i] = RAWImageUtil.clip( output[y+1][x+0][i] + (error*5)/16 ); - if (x + 1 < data[0].length) - output[y+1][x+1][i] = RAWImageUtil.clip( output[y+1][x+1][i] + (error*1)/16 ); - } - } - } - } - - return output; - } - - private static int findNearestColor(int[] color, int[][] palette) { - int minDistanceSquared = 255*255 + 255*255 + 255*255 + 1; - int bestIndex = 0; - for (byte i = 0; i < palette.length; i++) { - int Rdiff = color[1] - palette[i][0]; - int Gdiff = color[2] - palette[i][1]; - int Bdiff = color[3] - palette[i][2]; - int distanceSquared = Rdiff*Rdiff + Gdiff*Gdiff + Bdiff*Bdiff; - if (distanceSquared < minDistanceSquared) { - minDistanceSquared = distanceSquared; - bestIndex = i; - } - } - return bestIndex; - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.image.filter; + +import zutil.image.ImageFilterProcessor; +import zutil.image.RAWImageUtil; +import zutil.math.ZMath; + +import java.awt.image.BufferedImage; + + +public class DitheringFilter extends ImageFilterProcessor{ + // default palette is black and white + private int[][] palette = { + {255,0,0,0}, + {255,255,255,255} + }; + + + /** + * Sets up a default DitheringEffect + */ + public DitheringFilter(BufferedImage img){ + super(img); + } + + /** + * Creates a Dithering Effect object + * @param img The image to apply the effect on + * @param palette The palette to use on the image + * int[colorCount][4] + * 0 -> Alpha data + * Red data + * Green data + * 4 -> Blue data + */ + public DitheringFilter(BufferedImage img, int[][] palette){ + super(img); + this.palette = palette; + } + + @Override + public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { + int error, index; + int[] currentPixel; + int[][][] output = RAWImageUtil.copyArray(data); + + for(int y=startY; y 0) + output[y+1][x-1][i] = RAWImageUtil.clip( output[y+1][x-1][i] + (error*3)/16 ); + output[y+1][x+0][i] = RAWImageUtil.clip( output[y+1][x+0][i] + (error*5)/16 ); + if (x + 1 < data[0].length) + output[y+1][x+1][i] = RAWImageUtil.clip( output[y+1][x+1][i] + (error*1)/16 ); + } + } + } + } + + return output; + } + + private static int findNearestColor(int[] color, int[][] palette) { + int minDistanceSquared = 255*255 + 255*255 + 255*255 + 1; + int bestIndex = 0; + for (byte i = 0; i < palette.length; i++) { + int Rdiff = color[1] - palette[i][0]; + int Gdiff = color[2] - palette[i][1]; + int Bdiff = color[3] - palette[i][2]; + int distanceSquared = Rdiff*Rdiff + Gdiff*Gdiff + Bdiff*Bdiff; + if (distanceSquared < minDistanceSquared) { + minDistanceSquared = distanceSquared; + bestIndex = i; + } + } + return bestIndex; + } +} diff --git a/src/zutil/image/filters/GaussianBlurFilter.java b/src/zutil/image/filter/GaussianBlurFilter.java old mode 100644 new mode 100755 similarity index 95% rename from src/zutil/image/filters/GaussianBlurFilter.java rename to src/zutil/image/filter/GaussianBlurFilter.java index 616c08e..0cb4733 --- a/src/zutil/image/filters/GaussianBlurFilter.java +++ b/src/zutil/image/filter/GaussianBlurFilter.java @@ -1,71 +1,71 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.image.filters; - -import java.awt.image.BufferedImage; - -/** - * Blurs an image whit the Gaussian blur algorithm - * - * @author Ziver - */ -public class GaussianBlurFilter extends ConvolutionFilter{ - private int size; - private double sigma; - - public GaussianBlurFilter(BufferedImage img) { - this(img, 5, 1.4); - } - - public GaussianBlurFilter(BufferedImage img, int size, double sigma) { - super(img); - this.size = size; - this.sigma = sigma; - } - - protected double[][] generateKernel(){ - return gaussianFunction(size, size, sigma); - } - - /** - * Generates the kernel from the specified values - */ - public static double[][] gaussianFunction(int size_x, int size_y, double sigma){ - double[][] kernel; - int center_x = size_x/2; - int center_y = size_y/2; - - kernel = new double[size_y][size_x]; - for(int y=0; y= 0 && y+fy-edgeY < data.length && x+fx-edgeX >= 0 && x+fx-edgeX < data[0].length){ - //colorArray[fx][fy] := pixelvalue[x + fx - edgex][y + fy - edgey] - if(channels[0]) tmpArray[0][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][0] ) ]++; - if(channels[1]) tmpArray[1][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][1] ) ]++; - if(channels[2]) tmpArray[2][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][2] ) ]++; - if(channels[3]) tmpArray[3][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][3] ) ]++; - pixelCount++; - } - } - } - - if(channels[0]) tmpData[y][x][0] = findMedian(tmpArray[0], pixelCount/2); - if(channels[1]) tmpData[y][x][1] = findMedian(tmpArray[1], pixelCount/2); - if(channels[2]) tmpData[y][x][2] = findMedian(tmpArray[2], pixelCount/2); - if(channels[3]) tmpData[y][x][3] = findMedian(tmpArray[3], pixelCount/2); - } - } - - return tmpData; - } - - private int getMedianIndex(int i){ - if(i < 0) return Math.abs(i); - else return i+256; - } - - private int findMedian(int[] median, int medianCount){ - int sum = 0; - int ret = 0; - for(int i=0; i= medianCount && ret == 0){ - ret = i-256; - } - } - - return ret; - } - - - class SortableARGB implements SortableDataList{ - private int[][][] data; - private int cols; - private int rows; - private int channel; - - public SortableARGB(int[][][] data, int cols, int rows, int channel){ - this.data = data; - this.cols = cols; - this.rows = rows; - this.channel = channel; - } - - public int compare(int a, int b) { - return compare(a, data[ getY(b) ][ getX(b) ][ channel ]); - } - - public int compare(int a, Integer b) { - return ((Integer)data[ getY(a) ][ getX(a) ][ channel ]).compareTo(b); - } - - public Integer get(int i) { - return data[ getY(i) ][ getX(i) ][ channel ]; - } - - public void set(int i, Integer o){ - data[ getY(i) ][ getX(i) ][ channel ] = o; - } - - public int size() { - return cols * rows; - } - - public void swap(int a, int b) { - int tmp = data[ getY(a) ][ getX(a) ][ channel ]; - data[ getY(a) ][ getX(a) ][ channel ] = data[ getY(b) ][ getX(b) ][ channel ]; - data[ getY(b) ][ getX(b) ][ channel ] = tmp; - } - - - private int getX(int a){ - return a % cols; - } - - private int getY(int a){ - return a / cols; - } - - } - -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.image.filter; + +import zutil.algo.sort.sortable.SortableDataList; +import zutil.image.ImageFilterProcessor; +import zutil.image.RAWImageUtil; +import zutil.math.ZMath; + +import java.awt.image.BufferedImage; + +/** + * The MedianFilter is used for noise reduction and things + * + * @author Ziver + */ +public class MedianFilter extends ImageFilterProcessor{ + private int windowSize; + private boolean[] channels; + + /** + * Setup a default MedianFilter + * + * @param img The image to process + */ + public MedianFilter(BufferedImage img) { + this(img, 10); + } + + /** + * Setup a default MedianFilter + * + * @param img The image to process + * @param pixels The size of the window + */ + public MedianFilter(BufferedImage img, int pixels) { + this(img, pixels, new boolean[]{true,true,true,true}); + } + + /** + * Setup a default MedianFilter + * + * @param img The image to process + * @param pixels The size of the window + * @param channels Is a 4 element array for witch channels to use the filter on + */ + public MedianFilter(BufferedImage img, int pixels, boolean[] channels) { + super(img); + this.windowSize = pixels; + this.channels = channels; + } + + /* + edgex := (window width / 2) rounded down + edgey := (window height / 2) rounded down + for x from edgex to image width - edgex: + for y from edgey to image height - edgey: + colorArray[window width][window height]; + for fx from 0 to window width: + for fy from 0 to window height: + colorArray[fx][fy] := pixelvalue[x + fx - edgex][y + fy - edgey] + Sort colorArray[][]; + pixelValue[x][y] := colorArray[window width / 2][window height / 2]; + */ + @Override + public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { + int[][][] tmpData = RAWImageUtil.copyArray(data); + + int edgeX = windowSize / 2; + int edgeY = windowSize / 2; + + int[][] tmpArray = new int[4][256*2]; + int pixelCount = 0; + for(int y=startY; y= 0 && y+fy-edgeY < data.length && x+fx-edgeX >= 0 && x+fx-edgeX < data[0].length){ + //colorArray[fx][fy] := pixelvalue[x + fx - edgex][y + fy - edgey] + if(channels[0]) tmpArray[0][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][0] ) ]++; + if(channels[1]) tmpArray[1][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][1] ) ]++; + if(channels[2]) tmpArray[2][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][2] ) ]++; + if(channels[3]) tmpArray[3][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][3] ) ]++; + pixelCount++; + } + } + } + + if(channels[0]) tmpData[y][x][0] = findMedian(tmpArray[0], pixelCount/2); + if(channels[1]) tmpData[y][x][1] = findMedian(tmpArray[1], pixelCount/2); + if(channels[2]) tmpData[y][x][2] = findMedian(tmpArray[2], pixelCount/2); + if(channels[3]) tmpData[y][x][3] = findMedian(tmpArray[3], pixelCount/2); + } + } + + return tmpData; + } + + private int getMedianIndex(int i){ + if(i < 0) return Math.abs(i); + else return i+256; + } + + private int findMedian(int[] median, int medianCount){ + int sum = 0; + int ret = 0; + for(int i=0; i= medianCount && ret == 0){ + ret = i-256; + } + } + + return ret; + } + + + class SortableARGB implements SortableDataList{ + private int[][][] data; + private int cols; + private int rows; + private int channel; + + public SortableARGB(int[][][] data, int cols, int rows, int channel){ + this.data = data; + this.cols = cols; + this.rows = rows; + this.channel = channel; + } + + public int compare(int a, int b) { + return compare(a, data[ getY(b) ][ getX(b) ][ channel ]); + } + + public int compare(int a, Integer b) { + return ((Integer)data[ getY(a) ][ getX(a) ][ channel ]).compareTo(b); + } + + public Integer get(int i) { + return data[ getY(i) ][ getX(i) ][ channel ]; + } + + public void set(int i, Integer o){ + data[ getY(i) ][ getX(i) ][ channel ] = o; + } + + public int size() { + return cols * rows; + } + + public void swap(int a, int b) { + int tmp = data[ getY(a) ][ getX(a) ][ channel ]; + data[ getY(a) ][ getX(a) ][ channel ] = data[ getY(b) ][ getX(b) ][ channel ]; + data[ getY(b) ][ getX(b) ][ channel ] = tmp; + } + + + private int getX(int a){ + return a % cols; + } + + private int getY(int a){ + return a / cols; + } + + } + +} diff --git a/src/zutil/image/filters/ResizeImage.java b/src/zutil/image/filter/ResizeImage.java old mode 100644 new mode 100755 similarity index 96% rename from src/zutil/image/filters/ResizeImage.java rename to src/zutil/image/filter/ResizeImage.java index 174eacf..232f4c4 --- a/src/zutil/image/filters/ResizeImage.java +++ b/src/zutil/image/filter/ResizeImage.java @@ -1,87 +1,87 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.image.filters; - -import zutil.image.ImageFilterProcessor; -import zutil.math.ZMath; - -import java.awt.image.BufferedImage; - -public class ResizeImage extends ImageFilterProcessor{ - private int width; - private int height; - - private int[][][] newData; - - /** - * Will create a ResizeImage object and fix the height with the aspect - * of the width - * - * @param img The image to resize - * @param w The new width - */ - public ResizeImage(BufferedImage img, int w){ - this(img, w, -1); - } - - /** - * Will create a ResizeImage object - * - * @param img The image to resize - * @param w The new width if -1 then it will be scaled whit aspect of the hight - * @param h The new height if -1 then it will be scaled whit aspect of the width - */ - public ResizeImage(BufferedImage img, int w, int h){ - super(img); - width = w; - height = h; - } - - @Override - public int[][][] process(final int[][][] data, int startX, int startY, int stopX, int stopY) { - if(width < 1){ - height = (int)(((double)width/(stopX-startX))*(stopY-startY)); - } - else if(height < 1){ - width = (int)(((double)height/(stopY-startY))*(stopX-startY)); - } - - newData = new int[height][width][4]; - double xScale = ((double)(stopX-startX)/width); - double yScale = ((double)(stopY-startY)/height); - - for(int y=0; y radius){ - scale = 0; - } - else{ - scale = 1-(distance/radius); - } - - output[y][x][0] = data[y][x][0]; - output[y][x][1] = RAWImageUtil.clip((int)(scale * data[y][x][1])); - output[y][x][2] = RAWImageUtil.clip((int)(scale * data[y][x][2])); - output[y][x][3] = RAWImageUtil.clip((int)(scale * data[y][x][3])); - } - } - return output; - } - -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.image.filter; + +import zutil.image.ImageFilterProcessor; +import zutil.image.RAWImageUtil; +import zutil.math.ZMath; + +import java.awt.image.BufferedImage; + +public class SpotLightFilter extends ImageFilterProcessor{ + private int radius; + private int xPos; + private int yPos; + + /** + * Sets up a default spotlight effect in + * the middle of the image + */ + public SpotLightFilter(BufferedImage img){ + this(img, 100, -1, -1); + } + + /** + * Sets up a custom spotlight + * @param r The radius of the spotlight in pixels + */ + public SpotLightFilter(BufferedImage img, int r){ + this(img, r, -1, -1); + } + + /** + * Sets up a custom spotlight + * @param r The radius of the spotlight in pixels + * @param x The x position of the spotlight, if -1 then it will be centered + * @param y The y position of the spotlight, if -1 then it will be centered + */ + public SpotLightFilter(BufferedImage img, int r, int x, int y){ + super(img); + radius = r; + xPos = x; + yPos = y; + } + + @Override + public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { + if(xPos < 0) xPos = data[0].length/2; + if(yPos < 0) yPos = data.length/2; + + int[][][] output = new int[data.length][data[0].length][4]; + + double scale, dx, dy, distance; + for(int y=startY; y radius){ + scale = 0; + } + else{ + scale = 1-(distance/radius); + } + + output[y][x][0] = data[y][x][0]; + output[y][x][1] = RAWImageUtil.clip((int)(scale * data[y][x][1])); + output[y][x][2] = RAWImageUtil.clip((int)(scale * data[y][x][2])); + output[y][x][3] = RAWImageUtil.clip((int)(scale * data[y][x][3])); + } + } + return output; + } + +} diff --git a/src/zutil/net/http/HttpHeader.java b/src/zutil/net/http/HttpHeader.java index cbf6efc..c062684 100755 --- a/src/zutil/net/http/HttpHeader.java +++ b/src/zutil/net/http/HttpHeader.java @@ -24,7 +24,7 @@ package zutil.net.http; -import zutil.converters.Converter; +import zutil.converter.Converter; import java.util.HashMap; import java.util.Iterator; diff --git a/src/zutil/net/http/HttpPrintStream.java b/src/zutil/net/http/HttpPrintStream.java index 83e68b4..74dec8b 100755 --- a/src/zutil/net/http/HttpPrintStream.java +++ b/src/zutil/net/http/HttpPrintStream.java @@ -24,7 +24,7 @@ package zutil.net.http; -import zutil.converters.Converter; +import zutil.converter.Converter; import java.io.IOException; import java.io.OutputStream; diff --git a/src/zutil/net/http/pages/HttpFilePage.java b/src/zutil/net/http/page/HttpFilePage.java similarity index 99% rename from src/zutil/net/http/pages/HttpFilePage.java rename to src/zutil/net/http/page/HttpFilePage.java index b7922b6..d098e0d 100755 --- a/src/zutil/net/http/pages/HttpFilePage.java +++ b/src/zutil/net/http/page/HttpFilePage.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package zutil.net.http.pages; +package zutil.net.http.page; import zutil.io.IOUtil; import zutil.io.file.FileUtil; diff --git a/src/zutil/net/nio/NioNetwork.java b/src/zutil/net/nio/NioNetwork.java old mode 100644 new mode 100755 index 1f24457..5e36f08 --- a/src/zutil/net/nio/NioNetwork.java +++ b/src/zutil/net/nio/NioNetwork.java @@ -25,7 +25,7 @@ package zutil.net.nio; import zutil.Encrypter; -import zutil.converters.Converter; +import zutil.converter.Converter; import zutil.io.DynamicByteArrayStream; import zutil.io.MultiPrintStream; import zutil.log.LogUtil; diff --git a/src/zutil/net/upnp/services/BrowseRetObj.java b/src/zutil/net/upnp/service/BrowseRetObj.java old mode 100644 new mode 100755 similarity index 95% rename from src/zutil/net/upnp/services/BrowseRetObj.java rename to src/zutil/net/upnp/service/BrowseRetObj.java index 7d510e0..e87a022 --- a/src/zutil/net/upnp/services/BrowseRetObj.java +++ b/src/zutil/net/upnp/service/BrowseRetObj.java @@ -1,39 +1,39 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.net.upnp.services; - -import zutil.net.ws.WSReturnObject; - - -public class BrowseRetObj extends WSReturnObject{ - @WSValueName("Result") - public String Result; - @WSValueName("NumberReturned") - public int NumberReturned; - @WSValueName("TotalMatches") - public int TotalMatches; - @WSValueName("UpdateID") - public int UpdateID; - } +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net.upnp.service; + +import zutil.net.ws.WSReturnObject; + + +public class BrowseRetObj extends WSReturnObject{ + @WSValueName("Result") + public String Result; + @WSValueName("NumberReturned") + public int NumberReturned; + @WSValueName("TotalMatches") + public int TotalMatches; + @WSValueName("UpdateID") + public int UpdateID; + } diff --git a/src/zutil/net/upnp/services/UPnPContentDirectory.java b/src/zutil/net/upnp/service/UPnPContentDirectory.java similarity index 99% rename from src/zutil/net/upnp/services/UPnPContentDirectory.java rename to src/zutil/net/upnp/service/UPnPContentDirectory.java index 863d9c4..1214198 100755 --- a/src/zutil/net/upnp/services/UPnPContentDirectory.java +++ b/src/zutil/net/upnp/service/UPnPContentDirectory.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package zutil.net.upnp.services; +package zutil.net.upnp.service; import org.dom4j.DocumentException; import zutil.io.file.FileUtil; diff --git a/src/zutil/net/ws/rest/RestHttpPage.java b/src/zutil/net/ws/rest/RestHttpPage.java index 506ed74..33dbbb4 100755 --- a/src/zutil/net/ws/rest/RestHttpPage.java +++ b/src/zutil/net/ws/rest/RestHttpPage.java @@ -24,7 +24,7 @@ package zutil.net.ws.rest; -import zutil.converters.Converter; +import zutil.converter.Converter; import zutil.io.StringOutputStream; import zutil.net.http.HttpHeader; import zutil.net.http.HttpPage; diff --git a/src/zutil/net/ws/soap/SOAPHttpPage.java b/src/zutil/net/ws/soap/SOAPHttpPage.java index fd0099d..16bf24c 100755 --- a/src/zutil/net/ws/soap/SOAPHttpPage.java +++ b/src/zutil/net/ws/soap/SOAPHttpPage.java @@ -31,9 +31,9 @@ import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.xml.sax.SAXException; -import zutil.converters.Converter; +import zutil.converter.Converter; import zutil.log.LogUtil; -import zutil.net.http.HttpHeader; +import zutil.net.http.HttpHeader; import zutil.net.http.HttpPage; import zutil.net.http.HttpPrintStream; import zutil.net.ws.*; @@ -113,7 +113,7 @@ public class SOAPHttpPage implements HttpPage{ public void respond(HttpPrintStream out, - HttpHeader headers, + HttpHeader headers, Map session, Map cookie, Map request) { diff --git a/src/zutil/parser/Base64Decoder.java b/src/zutil/parser/Base64Decoder.java index ec82e20..1455a94 100755 --- a/src/zutil/parser/Base64Decoder.java +++ b/src/zutil/parser/Base64Decoder.java @@ -24,7 +24,7 @@ package zutil.parser; -import zutil.converters.Converter; +import zutil.converter.Converter; import zutil.io.DynamicByteArrayStream; public class Base64Decoder { diff --git a/src/zutil/parser/URLDecoder.java b/src/zutil/parser/URLDecoder.java index 0bd3103..dc20564 100755 --- a/src/zutil/parser/URLDecoder.java +++ b/src/zutil/parser/URLDecoder.java @@ -24,7 +24,7 @@ package zutil.parser; -import zutil.converters.Converter; +import zutil.converter.Converter; import java.io.UnsupportedEncodingException; diff --git a/src/zutil/parser/binary/BinaryStructParser.java b/src/zutil/parser/binary/BinaryStructParser.java index 549b7ba..5eeabc2 100755 --- a/src/zutil/parser/binary/BinaryStructParser.java +++ b/src/zutil/parser/binary/BinaryStructParser.java @@ -25,7 +25,7 @@ package zutil.parser.binary; import zutil.ByteUtil; -import zutil.converters.Converter; +import zutil.converter.Converter; import zutil.parser.binary.BinaryStruct.BinaryField; import java.lang.reflect.Field; diff --git a/src/zutil/ui/wizard/pages/SummaryPage.java b/src/zutil/ui/wizard/page/SummaryPage.java old mode 100644 new mode 100755 similarity index 95% rename from src/zutil/ui/wizard/pages/SummaryPage.java rename to src/zutil/ui/wizard/page/SummaryPage.java index bc23067..0a73eb8 --- a/src/zutil/ui/wizard/pages/SummaryPage.java +++ b/src/zutil/ui/wizard/page/SummaryPage.java @@ -1,70 +1,70 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.ui.wizard.pages; - -import zutil.ui.wizard.WizardPage; - -import javax.swing.*; -import java.util.HashMap; - -/** - * This class will show a summary of all the values - * in the wizard - * - * @author Ziver - * - */ -public class SummaryPage extends WizardPage{ - private static final long serialVersionUID = 1L; - - public SummaryPage(HashMap values){ - this.setFinalPage( true ); - - JTextArea summary = new JTextArea(); - summary.setEditable(false); - summary.setEnabled(false); - this.add( summary ); - - StringBuffer tmp = new StringBuffer(); - for(String key : values.keySet()){ - tmp.append(key); - tmp.append(": "); - tmp.append(values.get( key )); - tmp.append("\n"); - } - summary.setText( tmp.toString() ); - } - - @Override - public WizardPage getNextPage(HashMap values) { - return null; - } - - @Override - public String getPageDescription() { - return "Summary"; - } - -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.ui.wizard.page; + +import zutil.ui.wizard.WizardPage; + +import javax.swing.*; +import java.util.HashMap; + +/** + * This class will show a summary of all the values + * in the wizard + * + * @author Ziver + * + */ +public class SummaryPage extends WizardPage{ + private static final long serialVersionUID = 1L; + + public SummaryPage(HashMap values){ + this.setFinalPage( true ); + + JTextArea summary = new JTextArea(); + summary.setEditable(false); + summary.setEnabled(false); + this.add( summary ); + + StringBuffer tmp = new StringBuffer(); + for(String key : values.keySet()){ + tmp.append(key); + tmp.append(": "); + tmp.append(values.get( key )); + tmp.append("\n"); + } + summary.setText( tmp.toString() ); + } + + @Override + public WizardPage getNextPage(HashMap values) { + return null; + } + + @Override + public String getPageDescription() { + return "Summary"; + } + +} diff --git a/test/zutil/test/ByteUtilTest.java b/test/zutil/ByteUtilTest.java similarity index 97% rename from test/zutil/test/ByteUtilTest.java rename to test/zutil/ByteUtilTest.java index 0084193..96a560b 100755 --- a/test/zutil/test/ByteUtilTest.java +++ b/test/zutil/ByteUtilTest.java @@ -22,13 +22,13 @@ * THE SOFTWARE. */ -package zutil.test; +package zutil; import org.junit.Test; -import zutil.ByteUtil; import static org.junit.Assert.assertEquals; + /** * Created by Ziver on 2016-01-31. */ diff --git a/test/zutil/test/EncrypterTest.java b/test/zutil/EncrypterTest.java similarity index 95% rename from test/zutil/test/EncrypterTest.java rename to test/zutil/EncrypterTest.java index ea985be..40352e0 100755 --- a/test/zutil/test/EncrypterTest.java +++ b/test/zutil/EncrypterTest.java @@ -1,73 +1,73 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.Encrypter; -import zutil.Encrypter.Algorithm; - -import static org.junit.Assert.assertEquals; - -public class EncrypterTest { - public static final String data = "Hello there, wats yor name, my is a secret, 123456789"; - public static final String key = "abcdefghijklmnopqrstuvwxyz"; - - - @Test - public void encryptDES() throws Exception { - Encrypter.randomizeSalt(); - Encrypter encrypter = new Encrypter(key, Algorithm.DES); - Encrypter decrypter = new Encrypter(key, Algorithm.DES); - - assertEquals(data, encryptDecrypt(encrypter, decrypter, data)); - } - - @Test - public void encryptBLOWFISH() throws Exception { - Encrypter.randomizeSalt(); - Encrypter encrypter = new Encrypter(Algorithm.Blowfish); - Encrypter.randomizeSalt(); - Encrypter decrypter = new Encrypter(encrypter.getKey()); - - assertEquals(data, encryptDecrypt(encrypter, decrypter, data)); - } - - @Test - public void encryptAES() throws Exception { - Encrypter.randomizeSalt(); - Encrypter encrypter = new Encrypter(key, Algorithm.AES); - Encrypter decrypter = new Encrypter(key, Algorithm.AES); - - assertEquals(data, encryptDecrypt(encrypter, decrypter, data)); - } - - - - public static String encryptDecrypt(Encrypter encrypter, Encrypter decrypter, String data){ - byte[] encrypted = encrypter.encrypt(data.getBytes()); - byte[] decrypted = decrypter.decrypt(encrypted); - return new String(decrypted); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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; + +import org.junit.Test; +import zutil.Encrypter.Algorithm; + +import static org.junit.Assert.assertEquals; + + +public class EncrypterTest { + public static final String data = "Hello there, wats yor name, my is a secret, 123456789"; + public static final String key = "abcdefghijklmnopqrstuvwxyz"; + + + @Test + public void encryptDES() throws Exception { + Encrypter.randomizeSalt(); + Encrypter encrypter = new Encrypter(key, Algorithm.DES); + Encrypter decrypter = new Encrypter(key, Algorithm.DES); + + assertEquals(data, encryptDecrypt(encrypter, decrypter, data)); + } + + @Test + public void encryptBLOWFISH() throws Exception { + Encrypter.randomizeSalt(); + Encrypter encrypter = new Encrypter(Algorithm.Blowfish); + Encrypter.randomizeSalt(); + Encrypter decrypter = new Encrypter(encrypter.getKey()); + + assertEquals(data, encryptDecrypt(encrypter, decrypter, data)); + } + + @Test + public void encryptAES() throws Exception { + Encrypter.randomizeSalt(); + Encrypter encrypter = new Encrypter(key, Algorithm.AES); + Encrypter decrypter = new Encrypter(key, Algorithm.AES); + + assertEquals(data, encryptDecrypt(encrypter, decrypter, data)); + } + + + + public static String encryptDecrypt(Encrypter encrypter, Encrypter decrypter, String data){ + byte[] encrypted = encrypter.encrypt(data.getBytes()); + byte[] decrypted = decrypter.decrypt(encrypted); + return new String(decrypted); + } +} diff --git a/test/zutil/test/HasherTest.java b/test/zutil/HasherTest.java similarity index 95% rename from test/zutil/test/HasherTest.java rename to test/zutil/HasherTest.java index 9dee772..03a54d4 100755 --- a/test/zutil/test/HasherTest.java +++ b/test/zutil/HasherTest.java @@ -1,52 +1,51 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.Hasher; - -import static org.junit.Assert.assertEquals; - - -public class HasherTest { - - @Test - public void MD5Test(){ - assertEquals(Hasher.MD5("AAAABBBB"), "9da4fc50e09e5eeb8ae8149ef4f23792"); - assertEquals(Hasher.MD5("qwerty12345"), "85064efb60a9601805dcea56ec5402f7"); - assertEquals(Hasher.MD5("123456789"), "25f9e794323b453885f5181f1b624d0b"); - //assertEquals(Hasher.MD5(".,<>|!#�%&/()=?"), "20d5cda029514fa49a8bbe854a539847"); - assertEquals(Hasher.MD5("Test45"), "fee43a4c9d88769e14ec6a1d8b80f2e7"); - } - - @Test - public void SHA1Test(){ - assertEquals(Hasher.SHA1("AAAABBBB"), "7cd188ef3a9ea7fa0ee9c62c168709695460f5c0"); - assertEquals(Hasher.SHA1("qwerty12345"), "4e17a448e043206801b95de317e07c839770c8b8"); - assertEquals(Hasher.SHA1("123456789"), "f7c3bc1d808e04732adf679965ccc34ca7ae3441"); - //assertEquals(Hasher.SHA1(".,<>|!#�%&/()=?"), "6b3de029cdb367bb365d5154a197294ee590a77a"); - assertEquals(Hasher.SHA1("Test45"), "9194c6e64a6801e24e63a924d5843a46428d2b3a"); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + + +public class HasherTest { + + @Test + public void MD5Test(){ + assertEquals(Hasher.MD5("AAAABBBB"), "9da4fc50e09e5eeb8ae8149ef4f23792"); + assertEquals(Hasher.MD5("qwerty12345"), "85064efb60a9601805dcea56ec5402f7"); + assertEquals(Hasher.MD5("123456789"), "25f9e794323b453885f5181f1b624d0b"); + //assertEquals(Hasher.MD5(".,<>|!#�%&/()=?"), "20d5cda029514fa49a8bbe854a539847"); + assertEquals(Hasher.MD5("Test45"), "fee43a4c9d88769e14ec6a1d8b80f2e7"); + } + + @Test + public void SHA1Test(){ + assertEquals(Hasher.SHA1("AAAABBBB"), "7cd188ef3a9ea7fa0ee9c62c168709695460f5c0"); + assertEquals(Hasher.SHA1("qwerty12345"), "4e17a448e043206801b95de317e07c839770c8b8"); + assertEquals(Hasher.SHA1("123456789"), "f7c3bc1d808e04732adf679965ccc34ca7ae3441"); + //assertEquals(Hasher.SHA1(".,<>|!#�%&/()=?"), "6b3de029cdb367bb365d5154a197294ee590a77a"); + assertEquals(Hasher.SHA1("Test45"), "9194c6e64a6801e24e63a924d5843a46428d2b3a"); + } +} diff --git a/test/zutil/test/StringUtilTest.java b/test/zutil/StringUtilTest.java similarity index 97% rename from test/zutil/test/StringUtilTest.java rename to test/zutil/StringUtilTest.java index 4fba0e3..3b6cfe2 100755 --- a/test/zutil/test/StringUtilTest.java +++ b/test/zutil/StringUtilTest.java @@ -1,104 +1,105 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.StringUtil; - -import java.util.Arrays; - -import static org.junit.Assert.assertEquals; - -public class StringUtilTest { - - @Test - public void formatByteSizeToStringTest() { - assertEquals( "100.0 B", StringUtil.formatByteSizeToString(100) ); - assertEquals( "9.7 kB", StringUtil.formatByteSizeToString(10000) ); - } - - @Test - public void formatTimeToStringTest() { - assertEquals( "1 sec ", StringUtil.formatTimeToString( 1000 ) ); - assertEquals( "1 month 1 day 1 hour 1 min 1 sec 1 milisec ", - StringUtil.formatTimeToString( 2629743830l+86400000+3600000+60000+1000+1 ) ); - assertEquals( "2 months 2 days 2 hours 2 min 2 sec 2 milisec ", - StringUtil.formatTimeToString( (2629743830l+86400000+3600000+60000+1000+1)*2 ) ); - } - - @Test - public void trimTest() { - assertEquals( "", StringUtil.trim("", ' ') ); - assertEquals( "aa", StringUtil.trim(" aa ", ' ') ); - assertEquals( "aa", StringUtil.trim("aa ", ' ') ); - assertEquals( "aa", StringUtil.trim(" aa", ' ') ); - assertEquals( "", StringUtil.trim(" aa ", 'a') ); - assertEquals( "aa", StringUtil.trim("\u0010 aa ", ' ') ); - assertEquals( "aa", StringUtil.trim("\n\naa\n\t", ' ') ); - assertEquals( "aa", StringUtil.trim("\"aa\"", '\"') ); - } - - @Test - public void trimQuotesTest() { - assertEquals( "", StringUtil.trimQuotes("") ); - assertEquals( "\"", StringUtil.trimQuotes("\"") ); - assertEquals( "", StringUtil.trimQuotes("\"\"") ); - assertEquals( "\"aa", StringUtil.trimQuotes("\"aa") ); - assertEquals( "aa\"", StringUtil.trimQuotes("aa\"") ); - assertEquals( "aa", StringUtil.trimQuotes("\"aa\"") ); - } - - @Test - public void formatBytesToStringTest(){ - byte[] data = new byte[1]; - assertEquals("000 00 '. '", - StringUtil.formatBytesToString(data)); - - data[0] = 65; - assertEquals("000 41 'A '", - StringUtil.formatBytesToString(data)); - - byte[] data2 = new byte[8]; - data2[4] = 65; - assertEquals("000 00 00 00 00 41 00 00 00 '....A...'", - StringUtil.formatBytesToString(data2)); - - byte[] data3 = new byte[32]; - data3[4] = 65; - assertEquals("000 00 00 00 00 41 00 00 00 '....A...'\n"+ - "008 00 00 00 00 00 00 00 00 '........'\n"+ - "016 00 00 00 00 00 00 00 00 '........'\n"+ - "024 00 00 00 00 00 00 00 00 '........'", - StringUtil.formatBytesToString(data3)); - } - - @Test - public void joinTest(){ - assertEquals("", StringUtil.join(Arrays.asList(), ",")); - assertEquals("1,2,3,4,5", StringUtil.join(Arrays.asList(1,2,3,4,5), ",")); - assertEquals("animal,monkey,dog", StringUtil.join(Arrays.asList("animal", "monkey", "dog"), ",")); - assertEquals("12345", StringUtil.join(Arrays.asList(1,2,3,4,5), "")); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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; + +import org.junit.Test; +import zutil.StringUtil; + +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; + + +public class StringUtilTest { + + @Test + public void formatByteSizeToStringTest() { + assertEquals( "100.0 B", StringUtil.formatByteSizeToString(100) ); + assertEquals( "9.7 kB", StringUtil.formatByteSizeToString(10000) ); + } + + @Test + public void formatTimeToStringTest() { + assertEquals( "1 sec ", StringUtil.formatTimeToString( 1000 ) ); + assertEquals( "1 month 1 day 1 hour 1 min 1 sec 1 milisec ", + StringUtil.formatTimeToString( 2629743830l+86400000+3600000+60000+1000+1 ) ); + assertEquals( "2 months 2 days 2 hours 2 min 2 sec 2 milisec ", + StringUtil.formatTimeToString( (2629743830l+86400000+3600000+60000+1000+1)*2 ) ); + } + + @Test + public void trimTest() { + assertEquals( "", StringUtil.trim("", ' ') ); + assertEquals( "aa", StringUtil.trim(" aa ", ' ') ); + assertEquals( "aa", StringUtil.trim("aa ", ' ') ); + assertEquals( "aa", StringUtil.trim(" aa", ' ') ); + assertEquals( "", StringUtil.trim(" aa ", 'a') ); + assertEquals( "aa", StringUtil.trim("\u0010 aa ", ' ') ); + assertEquals( "aa", StringUtil.trim("\n\naa\n\t", ' ') ); + assertEquals( "aa", StringUtil.trim("\"aa\"", '\"') ); + } + + @Test + public void trimQuotesTest() { + assertEquals( "", StringUtil.trimQuotes("") ); + assertEquals( "\"", StringUtil.trimQuotes("\"") ); + assertEquals( "", StringUtil.trimQuotes("\"\"") ); + assertEquals( "\"aa", StringUtil.trimQuotes("\"aa") ); + assertEquals( "aa\"", StringUtil.trimQuotes("aa\"") ); + assertEquals( "aa", StringUtil.trimQuotes("\"aa\"") ); + } + + @Test + public void formatBytesToStringTest(){ + byte[] data = new byte[1]; + assertEquals("000 00 '. '", + StringUtil.formatBytesToString(data)); + + data[0] = 65; + assertEquals("000 41 'A '", + StringUtil.formatBytesToString(data)); + + byte[] data2 = new byte[8]; + data2[4] = 65; + assertEquals("000 00 00 00 00 41 00 00 00 '....A...'", + StringUtil.formatBytesToString(data2)); + + byte[] data3 = new byte[32]; + data3[4] = 65; + assertEquals("000 00 00 00 00 41 00 00 00 '....A...'\n"+ + "008 00 00 00 00 00 00 00 00 '........'\n"+ + "016 00 00 00 00 00 00 00 00 '........'\n"+ + "024 00 00 00 00 00 00 00 00 '........'", + StringUtil.formatBytesToString(data3)); + } + + @Test + public void joinTest(){ + assertEquals("", StringUtil.join(Arrays.asList(), ",")); + assertEquals("1,2,3,4,5", StringUtil.join(Arrays.asList(1,2,3,4,5), ",")); + assertEquals("animal,monkey,dog", StringUtil.join(Arrays.asList("animal", "monkey", "dog"), ",")); + assertEquals("12345", StringUtil.join(Arrays.asList(1,2,3,4,5), "")); + } +} diff --git a/test/zutil/test/QuickSelectTest.java b/test/zutil/algo/search/QuickSelectTest.java similarity index 94% rename from test/zutil/test/QuickSelectTest.java rename to test/zutil/algo/search/QuickSelectTest.java index d09df46..b591006 100755 --- a/test/zutil/test/QuickSelectTest.java +++ b/test/zutil/algo/search/QuickSelectTest.java @@ -1,50 +1,53 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.algo.search.QuickSelect; -import zutil.algo.sort.sortable.SortableIntArray; - -import java.util.Arrays; - -public class QuickSelectTest { - public static void main(String[] args){ - int[] array = {1,3,4,6,3,2,98,5,7,8,543,2,4,5,8,9,5,2,3,5,7,5,3,2,6,8,5,324,8,6}; - //int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,17,18,19,20}; - - long time = System.currentTimeMillis(); - int median = (Integer)QuickSelect.find(new SortableIntArray(array), array.length/2); - System.out.println("QuickSelection("+(System.currentTimeMillis()-time)+"ms): "+median); - - time = System.currentTimeMillis(); - Arrays.sort(array); - System.out.println("RightAnswer("+(System.currentTimeMillis()-time)+"ms): "+array[array.length/2]); - - System.out.println("Sorted Array("+array.length+"): "); - for(int i=0; i array[i]){ - error = i; - } - } - - if(error >= 0){ - System.out.println("\nArray not sorted!! ("+array[error-1]+" > "+array[error]+")"); - } - System.out.println("\nTime: "+time+" ms"); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.algo.sort; + +import zutil.algo.sort.MergeSort; +import zutil.algo.sort.sortable.SortableIntArray; + +// TODO: Convert to JUnit +@SuppressWarnings("unused") +public class MergeSortTest { + public static final int SIZE = 10000; + public static final int MAX_INT = 10000; + + public static void main(String[] args){ + int[] array = new int[SIZE]; + + for(int i=0; i array[i]){ + error = i; + } + } + + if(error >= 0){ + System.out.println("\nArray not sorted!! ("+array[error-1]+" > "+array[error]+")"); + } + System.out.println("\nTime: "+time+" ms"); + } +} diff --git a/test/zutil/test/ChartTest.java b/test/zutil/chart/ChartTest.java similarity index 92% rename from test/zutil/test/ChartTest.java rename to test/zutil/chart/ChartTest.java index 4001d76..7cd8e93 100755 --- a/test/zutil/test/ChartTest.java +++ b/test/zutil/chart/ChartTest.java @@ -1,62 +1,61 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.chart.ChartData; -import zutil.chart.LineChart; -import zutil.log.LogUtil; - -import javax.swing.*; -import java.util.logging.Level; - -public class ChartTest extends JFrame{ - private static final long serialVersionUID = 1L; - - public static void main(String[] args) { - LogUtil.setLevel("zutil", Level.FINEST); - ChartTest frame = new ChartTest(); - frame.setVisible(true); - } - - public ChartTest(){ - ChartData data = new ChartData(); - data.addPoint(1,1); - data.addPoint(2,1); - data.addPoint(3,1); - data.addPoint(4,1); - data.addPoint(5,1); - data.addPoint(6,1); - data.addPoint(7,1); - data.addPoint(8,1); - - LineChart chart = new LineChart(); - chart.setChartData( data ); - this.add( chart ); - - this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); - this.setSize(600, 400); - } - -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.chart; + +import zutil.log.LogUtil; + +import javax.swing.*; +import java.util.logging.Level; + + +public class ChartTest extends JFrame{ + private static final long serialVersionUID = 1L; + + public static void main(String[] args) { + LogUtil.setLevel("zutil", Level.FINEST); + ChartTest frame = new ChartTest(); + frame.setVisible(true); + } + + public ChartTest(){ + ChartData data = new ChartData(); + data.addPoint(1,1); + data.addPoint(2,1); + data.addPoint(3,1); + data.addPoint(4,1); + data.addPoint(5,1); + data.addPoint(6,1); + data.addPoint(7,1); + data.addPoint(8,1); + + LineChart chart = new LineChart(); + chart.setChartData( data ); + this.add( chart ); + + this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); + this.setSize(600, 400); + } + +} diff --git a/test/zutil/test/DBConnectionTest.java b/test/zutil/db/DBConnectionTest.java similarity index 94% rename from test/zutil/test/DBConnectionTest.java rename to test/zutil/db/DBConnectionTest.java index 0f28489..147503b 100755 --- a/test/zutil/test/DBConnectionTest.java +++ b/test/zutil/db/DBConnectionTest.java @@ -1,61 +1,61 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.db.DBConnection; -import zutil.db.handler.SimpleSQLResult; - -import java.sql.PreparedStatement; - -public class DBConnectionTest { - - public static void main(String[] args){ - try { - DBConnection db = new DBConnection("koc.se","db","user","password"); - - // Query 1 - PreparedStatement sql = db.getPreparedStatement("SELECT ?"); - sql.setInt(1, 1); - DBConnection.exec(sql); - - // Query 2 - db.exec("UPDATE ..."); - - // Query 3 - String s = db.exec("SELECT hello", new SimpleSQLResult()); - System.out.println( s ); - - // Query 4 - PreparedStatement sql2 = db.getPreparedStatement("SELECT ?"); - sql2.setString(1, "hello"); - String s2 = DBConnection.exec(sql2, new SimpleSQLResult()); - System.out.println( s2 ); - - db.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.db; + +import zutil.db.handler.SimpleSQLResult; + +import java.sql.PreparedStatement; + + +public class DBConnectionTest { + + public static void main(String[] args){ + try { + DBConnection db = new DBConnection("koc.se","db","user","password"); + + // Query 1 + PreparedStatement sql = db.getPreparedStatement("SELECT ?"); + sql.setInt(1, 1); + DBConnection.exec(sql); + + // Query 2 + db.exec("UPDATE ..."); + + // Query 3 + String s = db.exec("SELECT hello", new SimpleSQLResult()); + System.out.println( s ); + + // Query 4 + PreparedStatement sql2 = db.getPreparedStatement("SELECT ?"); + sql2.setString(1, "hello"); + String s2 = DBConnection.exec(sql2, new SimpleSQLResult()); + System.out.println( s2 ); + + db.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/test/zutil/test/SQLQueryTest.java b/test/zutil/db/SQLQueryTest.java similarity index 96% rename from test/zutil/test/SQLQueryTest.java rename to test/zutil/db/SQLQueryTest.java index 0b4d53e..7adf7b5 100755 --- a/test/zutil/test/SQLQueryTest.java +++ b/test/zutil/db/SQLQueryTest.java @@ -1,120 +1,120 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.db.SQLQuery; - -import static org.junit.Assert.assertEquals; - -public class SQLQueryTest { - - @Test - public void selectTest() { - assertEquals( "SELECT * FROM test1", - ""+SQLQuery.SELECT().FROM("test1") ); - assertEquals( "SELECT * FROM test1", - ""+SQLQuery.SELECT("*").FROM("test1") ); - assertEquals( "SELECT test1,test2 FROM test1", - ""+SQLQuery.SELECT("test1","test2").FROM("test1") ); - } - @Test - public void selectJoinTest() { - assertEquals( "SELECT * FROM test1 JOIN test2", - ""+SQLQuery.SELECT("*").FROM("test1").JOIN("test2") ); - assertEquals( "SELECT * FROM test1 NATURAL JOIN test2", - ""+SQLQuery.SELECT("*").FROM("test1").NATURAL_JOIN("test2") ); - assertEquals( "SELECT * FROM test1 UNION test2", - ""+SQLQuery.SELECT("*").FROM("test1").UNION("test2") ); - assertEquals( "SELECT * FROM test1 JOIN test2 NATURAL JOIN test3 UNION test4", - ""+SQLQuery.SELECT("*").FROM("test1").JOIN("test2").NATURAL_JOIN("test3").UNION("test4") ); - - assertEquals( "SELECT * FROM test1 NATURAL JOIN test2 NATURAL JOIN test3 NATURAL JOIN test4", - ""+SQLQuery.SELECT("*").FROM().NATURAL_JOIN("test1","test2","test3","test4") ); - assertEquals( "SELECT * FROM test1 JOIN test2 JOIN test3 JOIN test4", - ""+SQLQuery.SELECT("*").FROM().JOIN("test1","test2","test3","test4") ); - assertEquals( "SELECT * FROM test1 UNION test2 UNION test3 UNION test4", - ""+SQLQuery.SELECT("*").FROM().UNION("test1","test2","test3","test4") ); - } - @Test - public void selectWhereTest() { - assertEquals( "SELECT * FROM test1 WHERE arg=value", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value") ); - } - @Test - public void selectGroupByTest() { - assertEquals( "SELECT * FROM test1 GROUP BY col1", - ""+SQLQuery.SELECT("*").FROM("test1").GROUP_BY("col1") ); - assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1") ); - assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ASC", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ASC() ); - assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 DESC", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").DESC() ); - } - @Test - public void selectOrderByTest() { - assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1") ); - assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1 ASC", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1").ASC() ); - assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1 DESC", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1").DESC() ); - assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ORDER BY col2 DESC", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ORDER_BY("col2").DESC() ); - assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ASC ORDER BY col2 DESC", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ASC().ORDER_BY("col2").DESC() ); - } - @Test - public void selectLimitTest() { - assertEquals( "SELECT * FROM test1 LIMIT 1", - ""+SQLQuery.SELECT("*").FROM("test1").LIMIT(1) ); - assertEquals( "SELECT * FROM test1 LIMIT 1 4", - ""+SQLQuery.SELECT("*").FROM("test1").LIMIT(1).TO(4) ); - assertEquals( "SELECT * FROM test1 WHERE arg=value LIMIT 1", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").LIMIT(1) ); - assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1 DESC LIMIT 1", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1").DESC().LIMIT(1) ); - assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ORDER BY col2 DESC LIMIT 1", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ORDER_BY("col2").DESC().LIMIT(1) ); - } - - - @Test - public void updateTest() { - - } - - - @Test - public void deleteTest() { - - } - - @Test - public void createTest() { - - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.db; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + + +public class SQLQueryTest { + + @Test + public void selectTest() { + assertEquals( "SELECT * FROM test1", + ""+SQLQuery.SELECT().FROM("test1") ); + assertEquals( "SELECT * FROM test1", + ""+SQLQuery.SELECT("*").FROM("test1") ); + assertEquals( "SELECT test1,test2 FROM test1", + ""+SQLQuery.SELECT("test1","test2").FROM("test1") ); + } + @Test + public void selectJoinTest() { + assertEquals( "SELECT * FROM test1 JOIN test2", + ""+SQLQuery.SELECT("*").FROM("test1").JOIN("test2") ); + assertEquals( "SELECT * FROM test1 NATURAL JOIN test2", + ""+SQLQuery.SELECT("*").FROM("test1").NATURAL_JOIN("test2") ); + assertEquals( "SELECT * FROM test1 UNION test2", + ""+SQLQuery.SELECT("*").FROM("test1").UNION("test2") ); + assertEquals( "SELECT * FROM test1 JOIN test2 NATURAL JOIN test3 UNION test4", + ""+SQLQuery.SELECT("*").FROM("test1").JOIN("test2").NATURAL_JOIN("test3").UNION("test4") ); + + assertEquals( "SELECT * FROM test1 NATURAL JOIN test2 NATURAL JOIN test3 NATURAL JOIN test4", + ""+SQLQuery.SELECT("*").FROM().NATURAL_JOIN("test1","test2","test3","test4") ); + assertEquals( "SELECT * FROM test1 JOIN test2 JOIN test3 JOIN test4", + ""+SQLQuery.SELECT("*").FROM().JOIN("test1","test2","test3","test4") ); + assertEquals( "SELECT * FROM test1 UNION test2 UNION test3 UNION test4", + ""+SQLQuery.SELECT("*").FROM().UNION("test1","test2","test3","test4") ); + } + @Test + public void selectWhereTest() { + assertEquals( "SELECT * FROM test1 WHERE arg=value", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value") ); + } + @Test + public void selectGroupByTest() { + assertEquals( "SELECT * FROM test1 GROUP BY col1", + ""+SQLQuery.SELECT("*").FROM("test1").GROUP_BY("col1") ); + assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1") ); + assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ASC", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ASC() ); + assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 DESC", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").DESC() ); + } + @Test + public void selectOrderByTest() { + assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1") ); + assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1 ASC", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1").ASC() ); + assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1 DESC", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1").DESC() ); + assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ORDER BY col2 DESC", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ORDER_BY("col2").DESC() ); + assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ASC ORDER BY col2 DESC", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ASC().ORDER_BY("col2").DESC() ); + } + @Test + public void selectLimitTest() { + assertEquals( "SELECT * FROM test1 LIMIT 1", + ""+SQLQuery.SELECT("*").FROM("test1").LIMIT(1) ); + assertEquals( "SELECT * FROM test1 LIMIT 1 4", + ""+SQLQuery.SELECT("*").FROM("test1").LIMIT(1).TO(4) ); + assertEquals( "SELECT * FROM test1 WHERE arg=value LIMIT 1", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").LIMIT(1) ); + assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1 DESC LIMIT 1", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1").DESC().LIMIT(1) ); + assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ORDER BY col2 DESC LIMIT 1", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ORDER_BY("col2").DESC().LIMIT(1) ); + } + + + @Test + public void updateTest() { + + } + + + @Test + public void deleteTest() { + + } + + @Test + public void createTest() { + + } +} diff --git a/test/zutil/test/ImageProcessorTest.java b/test/zutil/image/ImageProcessorTest.java similarity index 94% rename from test/zutil/test/ImageProcessorTest.java rename to test/zutil/image/ImageProcessorTest.java index cc78144..1b1ea84 100755 --- a/test/zutil/test/ImageProcessorTest.java +++ b/test/zutil/image/ImageProcessorTest.java @@ -1,130 +1,130 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.ProgressListener; -import zutil.image.ImageFilterProcessor; -import zutil.image.filters.GaussianBlurFilter; - -import javax.imageio.ImageIO; -import javax.swing.*; -import java.awt.*; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.image.BufferedImage; -import java.io.BufferedInputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -@SuppressWarnings({ "unused", "rawtypes" }) -public class ImageProcessorTest implements ProgressListener{ - private static String imgPath = "test.gif"; - //private static String imgPath = "test2.jpg"; - - private JLabel processedLabel; - private JLabel orginalLabel; - private JProgressBar progress; - - public static void main(String[] args){ - new ImageProcessorTest(); - } - - @SuppressWarnings("unchecked") - public ImageProcessorTest(){ - JFrame frame = getJFrame(); - BufferedImage img = null; - - try { - // Read from an input stream - InputStream is = new BufferedInputStream(new FileInputStream(imgPath)); - img = ImageIO.read(is); - } catch (IOException e) { - e.printStackTrace(); - System.exit(1); - } - - ImageIcon orginalIcon = new ImageIcon(img); - orginalLabel.setIcon(orginalIcon); - frame.setVisible(true); - frame.pack(); - - BufferedImage procImg = null; - try { - //ImageFilterProcessor processor = new SobelEdgeDetectionFilter(img); - ImageFilterProcessor processor = new GaussianBlurFilter(img); - //ImageFilterProcessor processor = new BlurFilter(img, 100); - //ImageFilterProcessor processor = new ColorIntensityFilter(img, true); - //ImageFilterProcessor processor = new ContrastBrightnessFilter(img); - //ImageFilterProcessor processor = new DitheringFilter(img); - //ImageFilterProcessor processor = new MeanBlurFilter(img); - //ImageFilterProcessor processor = new MedianFilter(img); - //ImageFilterProcessor processor = new ResizeImage(img,100,100); - //ImageFilterProcessor processor = new SpotLightFilter(img,100,100,100); - - processor.setProgressListener(this); - procImg = processor.process(); - } catch (Exception e) { - e.printStackTrace(); - } - ImageIcon processedIcon = new ImageIcon(procImg); - processedLabel.setIcon(processedIcon); - - - frame.pack(); - } - - private JFrame getJFrame() { - processedLabel = new JLabel("Processed"); - orginalLabel = new JLabel("Orginal"); - - progress = new JProgressBar(); - progress.setMaximum(100); - progress.setValue(0); - progress.setIndeterminate(false); - progress.setStringPainted(true); - - JPanel jPanel = new JPanel(); - jPanel.setLayout(new BorderLayout()); - jPanel.add(orginalLabel, BorderLayout.NORTH); - jPanel.add(processedLabel, BorderLayout.CENTER); - jPanel.add(progress, BorderLayout.SOUTH); - - JFrame jFrame = new JFrame("ImageProcessorTest"); - jFrame.setSize(new Dimension(715, 361)); - jFrame.setContentPane(jPanel); - jFrame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - - return jFrame; - } - - public void progressUpdate(Object source, Object info, double percent) { - progress.setValue((int)percent); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.image; + +import zutil.ProgressListener; +import zutil.image.filter.GaussianBlurFilter; + +import javax.imageio.ImageIO; +import javax.swing.*; +import java.awt.*; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.image.BufferedImage; +import java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; + + +@SuppressWarnings({ "unused", "rawtypes" }) +public class ImageProcessorTest implements ProgressListener{ + private static String imgPath = "test.gif"; + //private static String imgPath = "test2.jpg"; + + private JLabel processedLabel; + private JLabel orginalLabel; + private JProgressBar progress; + + public static void main(String[] args){ + new ImageProcessorTest(); + } + + @SuppressWarnings("unchecked") + public ImageProcessorTest(){ + JFrame frame = getJFrame(); + BufferedImage img = null; + + try { + // Read from an input stream + InputStream is = new BufferedInputStream(new FileInputStream(imgPath)); + img = ImageIO.read(is); + } catch (IOException e) { + e.printStackTrace(); + System.exit(1); + } + + ImageIcon orginalIcon = new ImageIcon(img); + orginalLabel.setIcon(orginalIcon); + frame.setVisible(true); + frame.pack(); + + BufferedImage procImg = null; + try { + //ImageFilterProcessor processor = new SobelEdgeDetectionFilter(img); + ImageFilterProcessor processor = new GaussianBlurFilter(img); + //ImageFilterProcessor processor = new BlurFilter(img, 100); + //ImageFilterProcessor processor = new ColorIntensityFilter(img, true); + //ImageFilterProcessor processor = new ContrastBrightnessFilter(img); + //ImageFilterProcessor processor = new DitheringFilter(img); + //ImageFilterProcessor processor = new MeanBlurFilter(img); + //ImageFilterProcessor processor = new MedianFilter(img); + //ImageFilterProcessor processor = new ResizeImage(img,100,100); + //ImageFilterProcessor processor = new SpotLightFilter(img,100,100,100); + + processor.setProgressListener(this); + procImg = processor.process(); + } catch (Exception e) { + e.printStackTrace(); + } + ImageIcon processedIcon = new ImageIcon(procImg); + processedLabel.setIcon(processedIcon); + + + frame.pack(); + } + + private JFrame getJFrame() { + processedLabel = new JLabel("Processed"); + orginalLabel = new JLabel("Orginal"); + + progress = new JProgressBar(); + progress.setMaximum(100); + progress.setValue(0); + progress.setIndeterminate(false); + progress.setStringPainted(true); + + JPanel jPanel = new JPanel(); + jPanel.setLayout(new BorderLayout()); + jPanel.add(orginalLabel, BorderLayout.NORTH); + jPanel.add(processedLabel, BorderLayout.CENTER); + jPanel.add(progress, BorderLayout.SOUTH); + + JFrame jFrame = new JFrame("ImageProcessorTest"); + jFrame.setSize(new Dimension(715, 361)); + jFrame.setContentPane(jPanel); + jFrame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); + + return jFrame; + } + + public void progressUpdate(Object source, Object info, double percent) { + progress.setValue((int)percent); + } +} diff --git a/test/zutil/test/BoundaryBufferedInputStreamTest.java b/test/zutil/io/BoundaryBufferedInputStreamTest.java similarity index 93% rename from test/zutil/test/BoundaryBufferedInputStreamTest.java rename to test/zutil/io/BoundaryBufferedInputStreamTest.java index 48a8b1d..c092adc 100755 --- a/test/zutil/test/BoundaryBufferedInputStreamTest.java +++ b/test/zutil/io/BoundaryBufferedInputStreamTest.java @@ -1,100 +1,99 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.BoundaryBufferedInputStream; -import zutil.io.StringInputStream; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; - -@SuppressWarnings("resource") -public class BoundaryBufferedInputStreamTest { - - @Test - public void testReadB1() throws IOException { - StringInputStream inin = new StringInputStream(); - BoundaryBufferedInputStream in = new BoundaryBufferedInputStream(inin); - inin.add("aaa#aaaaaaaaaaaaaaaa#aaaaaaaaaaaaaaa#"); - - in.setBoundary("#"); - - int n = 0; - for(n=0; in.read() != -1; n++); - assertEquals(3, n); - - in.next(); - n = 0; - for(n=0; in.read() != -1; n++); - assertEquals(16, n); - - in.next(); - n = 0; - for(n=0; in.read() != -1; n++); - assertEquals(15, n); - - in.next(); - assertEquals(-1, in.read()); - - } - - @Test - public void testOnlyBoundaries() throws IOException { - StringInputStream inin = new StringInputStream(); - BoundaryBufferedInputStream in = new BoundaryBufferedInputStream(inin); - inin.add("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); - - in.setBoundary("a"); - - int n; - for(n=1; true; n++){ - assertEquals(-1, in.read()); - assertEquals(-1, in.read()); - in.next(); - if(!in.isBoundary()) - break; - } - assertEquals(35, n); - } - - @Test - public void testNoBounds() throws IOException { - String data = "1234567891011121314151617181920"; - StringInputStream inin = new StringInputStream(); - BoundaryBufferedInputStream in = new BoundaryBufferedInputStream(inin); - inin.add(data); - in.setBoundary("#"); - - int out; - StringBuilder output = new StringBuilder(); - while((out = in.read()) != -1){ - output.append((char)out); - } - assertEquals(data, output.toString()); - } - -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.io; + +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + + +@SuppressWarnings("resource") +public class BoundaryBufferedInputStreamTest { + + @Test + public void testReadB1() throws IOException { + StringInputStream inin = new StringInputStream(); + BoundaryBufferedInputStream in = new BoundaryBufferedInputStream(inin); + inin.add("aaa#aaaaaaaaaaaaaaaa#aaaaaaaaaaaaaaa#"); + + in.setBoundary("#"); + + int n = 0; + for(n=0; in.read() != -1; n++); + assertEquals(3, n); + + in.next(); + n = 0; + for(n=0; in.read() != -1; n++); + assertEquals(16, n); + + in.next(); + n = 0; + for(n=0; in.read() != -1; n++); + assertEquals(15, n); + + in.next(); + assertEquals(-1, in.read()); + + } + + @Test + public void testOnlyBoundaries() throws IOException { + StringInputStream inin = new StringInputStream(); + BoundaryBufferedInputStream in = new BoundaryBufferedInputStream(inin); + inin.add("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + + in.setBoundary("a"); + + int n; + for(n=1; true; n++){ + assertEquals(-1, in.read()); + assertEquals(-1, in.read()); + in.next(); + if(!in.isBoundary()) + break; + } + assertEquals(35, n); + } + + @Test + public void testNoBounds() throws IOException { + String data = "1234567891011121314151617181920"; + StringInputStream inin = new StringInputStream(); + BoundaryBufferedInputStream in = new BoundaryBufferedInputStream(inin); + inin.add(data); + in.setBoundary("#"); + + int out; + StringBuilder output = new StringBuilder(); + while((out = in.read()) != -1){ + output.append((char)out); + } + assertEquals(data, output.toString()); + } + +} diff --git a/test/zutil/test/DynamicByteArrayStreamTest.java b/test/zutil/io/DynamicByteArrayStreamTest.java similarity index 94% rename from test/zutil/test/DynamicByteArrayStreamTest.java rename to test/zutil/io/DynamicByteArrayStreamTest.java index c8e27f9..842b1a4 100755 --- a/test/zutil/test/DynamicByteArrayStreamTest.java +++ b/test/zutil/io/DynamicByteArrayStreamTest.java @@ -1,58 +1,58 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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); - - byte[] result = out.getBytes(); - for(int i=0; i - - - - - - - - -
- - -
-
    -
  • -
    - - Test - -
    -
  • -
- + + + + + + + + + +
+ + +
+
    +
  • +
    + + Test + +
    +
  • +
+ \ No newline at end of file diff --git a/test/zutil/test/NetLogServerTest.java b/test/zutil/log/net/NetLogServerTest.java similarity index 94% rename from test/zutil/test/NetLogServerTest.java rename to test/zutil/log/net/NetLogServerTest.java index 0d7df03..823ab96 100755 --- a/test/zutil/test/NetLogServerTest.java +++ b/test/zutil/log/net/NetLogServerTest.java @@ -1,53 +1,53 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.log.LogUtil; -import zutil.log.net.NetLogServer; - -import java.util.logging.Level; -import java.util.logging.Logger; - -public class NetLogServerTest { - private static final Logger logger = LogUtil.getLogger(); - - public static void main(String[] args){ - LogUtil.setGlobalLevel(Level.FINEST); - LogUtil.addGlobalHandler(new NetLogServer(5050)); - - while(true){ - logger.log(Level.SEVERE, "Test Severe"); - logger.log(Level.WARNING, "Test Warning"); - logger.log(Level.INFO, "Test Info"); - logger.log(Level.FINE, "Test Fine"); - logger.log(Level.FINER, "Test Finer"); - logger.log(Level.FINEST, "Test Finest"); - - logger.log(Level.SEVERE, "Test Exception", new Exception("Test")); - - try{Thread.sleep(3000);}catch(Exception e){} - } - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.log.net; + +import zutil.log.LogUtil; + +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class NetLogServerTest { + private static final Logger logger = LogUtil.getLogger(); + + public static void main(String[] args){ + LogUtil.setGlobalLevel(Level.FINEST); + LogUtil.addGlobalHandler(new NetLogServer(5050)); + + while(true){ + logger.log(Level.SEVERE, "Test Severe"); + logger.log(Level.WARNING, "Test Warning"); + logger.log(Level.INFO, "Test Info"); + logger.log(Level.FINE, "Test Fine"); + logger.log(Level.FINER, "Test Finer"); + logger.log(Level.FINEST, "Test Finest"); + + logger.log(Level.SEVERE, "Test Exception", new Exception("Test")); + + try{Thread.sleep(3000);}catch(Exception e){} + } + } +} diff --git a/test/zutil/test/ServerFindClientTest.java b/test/zutil/net/ServerFindClientTest.java similarity index 96% rename from test/zutil/test/ServerFindClientTest.java rename to test/zutil/net/ServerFindClientTest.java index 9be0ceb..ff04d09 100755 --- a/test/zutil/test/ServerFindClientTest.java +++ b/test/zutil/net/ServerFindClientTest.java @@ -1,40 +1,41 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.net.ServerFindClient; - -import java.io.IOException; - -public class ServerFindClientTest { - public static void main(String[] args){ - try { - ServerFindClient client = new ServerFindClient(2000); - System.out.println(client.find().getHostAddress()); - } catch (IOException e) { - e.printStackTrace(); - } - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net; + +import zutil.net.ServerFindClient; + +import java.io.IOException; + + +public class ServerFindClientTest { + public static void main(String[] args){ + try { + ServerFindClient client = new ServerFindClient(2000); + System.out.println(client.find().getHostAddress()); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/test/zutil/test/ServerFindServerTest.java b/test/zutil/net/ServerFindServerTest.java similarity index 93% rename from test/zutil/test/ServerFindServerTest.java rename to test/zutil/net/ServerFindServerTest.java index a76505c..19bffc5 100755 --- a/test/zutil/test/ServerFindServerTest.java +++ b/test/zutil/net/ServerFindServerTest.java @@ -1,39 +1,38 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.net.ServerFind; - -import java.io.IOException; - -public class ServerFindServerTest { - public static void main(String[] args){ - try { - new ServerFind(2000); - } catch (IOException e) { - e.printStackTrace(); - } - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net; + +import java.io.IOException; + + +public class ServerFindServerTest { + public static void main(String[] args){ + try { + new ServerFind(2000); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/test/zutil/test/HTTPGuessTheNumber.java b/test/zutil/net/http/HTTPGuessTheNumber.java similarity index 92% rename from test/zutil/test/HTTPGuessTheNumber.java rename to test/zutil/net/http/HTTPGuessTheNumber.java index 73b824f..2b509c6 100755 --- a/test/zutil/test/HTTPGuessTheNumber.java +++ b/test/zutil/net/http/HTTPGuessTheNumber.java @@ -1,107 +1,102 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.net.http.HttpHeader; -import zutil.net.http.HttpPage; -import zutil.net.http.HttpPrintStream; -import zutil.net.http.HttpServer; - -import java.io.IOException; -import java.util.Map; - - -public class HTTPGuessTheNumber implements HttpPage{ - - public static void main(String[] args) throws IOException{ - //HttpServer server = new HttpServer("localhost", 443, FileFinder.find("keySSL"), "rootroot");//SSL - HttpServer server = new HttpServer(8080); - server.setDefaultPage(new HTTPGuessTheNumber()); - server.run(); - } - - public void respond(HttpPrintStream out, - HttpHeader client_info, - Map session, - Map cookie, - Map request) throws IOException { - - out.enableBuffering(true); - out.println(""); - out.println("

Welcome To The Number Guess Game!

"); - - if(session.containsKey("random_nummber") && request.containsKey("guess") && !request.get("guess").isEmpty()){ - int guess = Integer.parseInt(request.get("guess")); - int nummber = (Integer)session.get("random_nummber"); - try { - if(guess == nummber){ - session.remove("random_nummber"); - out.println("You Guessed Right! Congrats!"); - out.println(""); - return; - } - else if(guess > nummber){ - out.println("To High
"); - if(Integer.parseInt(cookie.get("high")) > guess){ - out.setCookie("high", ""+guess); - cookie.put("high", ""+guess); - } - } - else{ - out.println("To Low
"); - if(Integer.parseInt(cookie.get("low")) < guess){ - out.setCookie("low", ""+guess); - cookie.put("low", ""+guess); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - else{ - session.put("random_nummber", (int)(Math.random()*99+1)); - try { - out.setCookie("low", "0"); - out.setCookie("high", "100"); - cookie.put("low", "0"); - cookie.put("high", "100"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - out.println("
"); - out.println(cookie.get("low")+" < X < "+cookie.get("high")+"
"); - out.println("Guess a number between 0 and 100:
"); - out.println(""); - out.println(""); - out.println(""); - out.println("
"); - out.println(""); - out.println("DEBUG: nummber="+session.get("random_nummber")+"
"); - out.println(""); - } - -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net.http; + +import java.io.IOException; +import java.util.Map; + + +public class HTTPGuessTheNumber implements HttpPage{ + + public static void main(String[] args) throws IOException{ + //HttpServer server = new HttpServer("localhost", 443, FileFinder.find("keySSL"), "rootroot");//SSL + HttpServer server = new HttpServer(8080); + server.setDefaultPage(new HTTPGuessTheNumber()); + server.run(); + } + + public void respond(HttpPrintStream out, + HttpHeader client_info, + Map session, + Map cookie, + Map request) throws IOException { + + out.enableBuffering(true); + out.println(""); + out.println("

Welcome To The Number Guess Game!

"); + + if(session.containsKey("random_nummber") && request.containsKey("guess") && !request.get("guess").isEmpty()){ + int guess = Integer.parseInt(request.get("guess")); + int nummber = (Integer)session.get("random_nummber"); + try { + if(guess == nummber){ + session.remove("random_nummber"); + out.println("You Guessed Right! Congrats!"); + out.println(""); + return; + } + else if(guess > nummber){ + out.println("To High
"); + if(Integer.parseInt(cookie.get("high")) > guess){ + out.setCookie("high", ""+guess); + cookie.put("high", ""+guess); + } + } + else{ + out.println("To Low
"); + if(Integer.parseInt(cookie.get("low")) < guess){ + out.setCookie("low", ""+guess); + cookie.put("low", ""+guess); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + else{ + session.put("random_nummber", (int)(Math.random()*99+1)); + try { + out.setCookie("low", "0"); + out.setCookie("high", "100"); + cookie.put("low", "0"); + cookie.put("high", "100"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + out.println("
"); + out.println(cookie.get("low")+" < X < "+cookie.get("high")+"
"); + out.println("Guess a number between 0 and 100:
"); + out.println(""); + out.println(""); + out.println(""); + out.println("
"); + out.println(""); + out.println("DEBUG: nummber="+session.get("random_nummber")+"
"); + out.println(""); + } + +} diff --git a/test/zutil/test/HTTPUploaderTest.java b/test/zutil/net/http/HTTPUploaderTest.java similarity index 89% rename from test/zutil/test/HTTPUploaderTest.java rename to test/zutil/net/http/HTTPUploaderTest.java index f032bb1..601957e 100755 --- a/test/zutil/test/HTTPUploaderTest.java +++ b/test/zutil/net/http/HTTPUploaderTest.java @@ -1,62 +1,57 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.net.http.HttpHeader; -import zutil.net.http.HttpPage; -import zutil.net.http.HttpPrintStream; -import zutil.net.http.HttpServer; - -import java.io.IOException; -import java.util.Map; - - -public class HTTPUploaderTest implements HttpPage{ - - public static void main(String[] args) throws IOException{ - HttpServer server = new HttpServer(80); - server.setDefaultPage(new HTTPUploaderTest()); - server.run(); - } - - public void respond(HttpPrintStream out, - HttpHeader client_info, - Map session, - Map cookie, - Map request) throws IOException { - - if(!session.containsKey("file1")){ - out.println("" + - "
" + - "

Please specify a file, or a set of files:
" + - " " + - "

" + - " " + - "
" + - ""); - } - } - -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net.http; + +import java.io.IOException; +import java.util.Map; + + +public class HTTPUploaderTest implements HttpPage{ + + public static void main(String[] args) throws IOException{ + HttpServer server = new HttpServer(80); + server.setDefaultPage(new HTTPUploaderTest()); + server.run(); + } + + public void respond(HttpPrintStream out, + HttpHeader client_info, + Map session, + Map cookie, + Map request) throws IOException { + + if(!session.containsKey("file1")){ + out.println("" + + "
" + + "

Please specify a file, or a set of files:
" + + " " + + "

" + + " " + + "
" + + ""); + } + } + +} diff --git a/test/zutil/test/HttpURLTest.java b/test/zutil/net/http/HttpURLTest.java similarity index 93% rename from test/zutil/test/HttpURLTest.java rename to test/zutil/net/http/HttpURLTest.java index 78f09bd..6e71dc8 100755 --- a/test/zutil/test/HttpURLTest.java +++ b/test/zutil/net/http/HttpURLTest.java @@ -1,75 +1,74 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.net.http.HttpURL; - -import static org.hamcrest.CoreMatchers.allOf; -import static org.hamcrest.CoreMatchers.both; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; - -public class HttpURLTest { - - @Test - public void fullURLTest() { - HttpURL url = new HttpURL(); - url.setProtocol("http"); - assertEquals( "http://127.0.0.1/", url.getURL() ); - - url.setHost("koc.se"); - assertEquals( "http://koc.se/", url.getURL() ); - - url.setPort( 80 ); - assertEquals( "http://koc.se:80/", url.getURL() ); - - url.setPath("test/index.html"); - assertEquals( "http://koc.se:80/test/index.html", url.getURL() ); - - url.setParameter("key", "value"); - assertEquals( "http://koc.se:80/test/index.html?key=value", url.getURL() ); - - url.setAnchor( "anch" ); - assertEquals( "http://koc.se:80/test/index.html?key=value#anch", url.getURL() ); - } - - @Test - public void urlParameterTest() { - HttpURL url = new HttpURL(); - url.setParameter("key1", "value1"); - assertEquals( "key1=value1", url.getParameterString() ); - - url.setParameter("key1", "value1"); - assertEquals( "key1=value1", url.getParameterString() ); - - url.setParameter("key2", "value2"); - assertThat(url.getParameterString(), allOf(containsString("key2=value2"), containsString("key1=value1"))); - - } - - -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net.http; + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; + + +public class HttpURLTest { + + @Test + public void fullURLTest() { + HttpURL url = new HttpURL(); + url.setProtocol("http"); + assertEquals( "http://127.0.0.1/", url.getURL() ); + + url.setHost("koc.se"); + assertEquals( "http://koc.se/", url.getURL() ); + + url.setPort( 80 ); + assertEquals( "http://koc.se:80/", url.getURL() ); + + url.setPath("test/index.html"); + assertEquals( "http://koc.se:80/test/index.html", url.getURL() ); + + url.setParameter("key", "value"); + assertEquals( "http://koc.se:80/test/index.html?key=value", url.getURL() ); + + url.setAnchor( "anch" ); + assertEquals( "http://koc.se:80/test/index.html?key=value#anch", url.getURL() ); + } + + @Test + public void urlParameterTest() { + HttpURL url = new HttpURL(); + url.setParameter("key1", "value1"); + assertEquals( "key1=value1", url.getParameterString() ); + + url.setParameter("key1", "value1"); + assertEquals( "key1=value1", url.getParameterString() ); + + url.setParameter("key2", "value2"); + assertThat(url.getParameterString(), allOf(containsString("key2=value2"), containsString("key1=value1"))); + + } + + +} diff --git a/test/zutil/test/NetworkClientTest.java b/test/zutil/net/nio/NetworkClientTest.java similarity index 95% rename from test/zutil/test/NetworkClientTest.java rename to test/zutil/net/nio/NetworkClientTest.java index ba40b34..e99d145 100755 --- a/test/zutil/test/NetworkClientTest.java +++ b/test/zutil/net/nio/NetworkClientTest.java @@ -1,60 +1,59 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.net.nio.NioClient; -import zutil.net.nio.message.StringMessage; -import zutil.net.nio.response.PrintRsp; - -import java.io.IOException; -import java.net.InetAddress; -import java.security.NoSuchAlgorithmException; - - -@SuppressWarnings("unused") -public class NetworkClientTest { - public static void main(String[] args) throws NoSuchAlgorithmException { - try { - int count = 0; - long time = System.currentTimeMillis()+1000*60; - NioClient client = new NioClient(InetAddress.getByName("localhost"), 6056); - //client.setEncrypter(new Encrypter("lol", Encrypter.PASSPHRASE_DES_ALGO)); - while(time > System.currentTimeMillis()){ - PrintRsp handler = new PrintRsp(); - client.send(handler, new StringMessage("StringMessage: "+count)); - handler.waitForResponse(); - //try {Thread.sleep(100);} catch (InterruptedException e) {} - //System.out.println("sending.."); - count++; - } - - System.out.println("Message Count 1m: "+count); - System.out.println("Message Count 1s: "+count/60); - System.exit(0); - } catch (IOException e) { - e.printStackTrace(); - } - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net.nio; + +import zutil.net.nio.message.StringMessage; +import zutil.net.nio.response.PrintRsp; + +import java.io.IOException; +import java.net.InetAddress; +import java.security.NoSuchAlgorithmException; + + +@SuppressWarnings("unused") +public class NetworkClientTest { + public static void main(String[] args) throws NoSuchAlgorithmException { + try { + int count = 0; + long time = System.currentTimeMillis()+1000*60; + NioClient client = new NioClient(InetAddress.getByName("localhost"), 6056); + //client.setEncrypter(new Encrypter("lol", Encrypter.PASSPHRASE_DES_ALGO)); + while(time > System.currentTimeMillis()){ + PrintRsp handler = new PrintRsp(); + client.send(handler, new StringMessage("StringMessage: "+count)); + handler.waitForResponse(); + //try {Thread.sleep(100);} catch (InterruptedException e) {} + //System.out.println("sending.."); + count++; + } + + System.out.println("Message Count 1m: "+count); + System.out.println("Message Count 1s: "+count/60); + System.exit(0); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/test/zutil/test/NetworkServerTest.java b/test/zutil/net/nio/NetworkServerTest.java similarity index 94% rename from test/zutil/test/NetworkServerTest.java rename to test/zutil/net/nio/NetworkServerTest.java index 61678d5..b987acd 100755 --- a/test/zutil/test/NetworkServerTest.java +++ b/test/zutil/net/nio/NetworkServerTest.java @@ -1,43 +1,41 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.net.nio.NioServer; - -import java.io.IOException; -import java.security.NoSuchAlgorithmException; - - -@SuppressWarnings("unused") -public class NetworkServerTest { - public static void main(String[] args) throws NoSuchAlgorithmException { - try { - NioServer server = new NioServer(6056); - //server.setEncrypter(new Encrypter("lol", Encrypter.PASSPHRASE_DES_ALGO)); - } catch (IOException e) { - e.printStackTrace(); - } - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net.nio; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; + + +@SuppressWarnings("unused") +public class NetworkServerTest { + public static void main(String[] args) throws NoSuchAlgorithmException { + try { + NioServer server = new NioServer(6056); + //server.setEncrypter(new Encrypter("lol", Encrypter.PASSPHRASE_DES_ALGO)); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/test/zutil/test/SSDPClientTest.java b/test/zutil/net/ssdp/SSDPClientTest.java similarity index 96% rename from test/zutil/test/SSDPClientTest.java rename to test/zutil/net/ssdp/SSDPClientTest.java index d58399c..15828cd 100755 --- a/test/zutil/test/SSDPClientTest.java +++ b/test/zutil/net/ssdp/SSDPClientTest.java @@ -1,51 +1,52 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.log.LogUtil; -import zutil.net.ssdp.SSDPClient; - -import java.io.IOException; -import java.util.logging.Level; - -/** - * Created by Ziver on 2015-09-29. - */ -public class SSDPClientTest { - - public static void main(String[] args) throws IOException { - System.out.println(LogUtil.getCallingClass()); - LogUtil.setGlobalLevel(Level.FINEST); - SSDPClient ssdp = new SSDPClient(); - ssdp.requestService("upnp:rootdevice"); - ssdp.start(); - - for(int i=0; true ;++i){ - while( i==ssdp.getServicesCount("upnp:rootdevice") ){ try{Thread.sleep(100);}catch(Exception e){} } - System.out.println("************************" ); - System.out.println("" + ssdp.getServices("upnp:rootdevice").get(i)); - } - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net.ssdp; + +import zutil.log.LogUtil; +import zutil.net.ssdp.SSDPClient; + +import java.io.IOException; +import java.util.logging.Level; + + +/** + * Created by Ziver on 2015-09-29. + */ +public class SSDPClientTest { + + public static void main(String[] args) throws IOException { + System.out.println(LogUtil.getCallingClass()); + LogUtil.setGlobalLevel(Level.FINEST); + SSDPClient ssdp = new SSDPClient(); + ssdp.requestService("upnp:rootdevice"); + ssdp.start(); + + for(int i=0; true ;++i){ + while( i==ssdp.getServicesCount("upnp:rootdevice") ){ try{Thread.sleep(100);}catch(Exception e){} } + System.out.println("************************" ); + System.out.println("" + ssdp.getServices("upnp:rootdevice").get(i)); + } + } +} diff --git a/test/zutil/test/SSDPServerTest.java b/test/zutil/net/ssdp/SSDPServerTest.java similarity index 92% rename from test/zutil/test/SSDPServerTest.java rename to test/zutil/net/ssdp/SSDPServerTest.java index 3978285..d8f85a9 100755 --- a/test/zutil/test/SSDPServerTest.java +++ b/test/zutil/net/ssdp/SSDPServerTest.java @@ -1,54 +1,53 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.log.LogUtil; -import zutil.net.ssdp.SSDPServer; -import zutil.net.ssdp.StandardSSDPInfo; - -import java.io.IOException; -import java.util.logging.Level; - -/** - * Created by Ziver on 2015-09-29. - */ -public class SSDPServerTest { - - public static void main(String[] args) throws IOException { - LogUtil.setGlobalLevel(Level.FINEST); - - StandardSSDPInfo service = new StandardSSDPInfo(); - service.setLocation("nowhere"); - service.setST("zep:discover"); - service.setHeader("Alias", "Desktop"); - service.setHeader("PublicKey", "SuperDesktopKey"); - - - SSDPServer ssdp = new SSDPServer(); - ssdp.addService(service); - ssdp.start(); - System.out.println("SSDP Server running"); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net.ssdp; + +import zutil.log.LogUtil; + +import java.io.IOException; +import java.util.logging.Level; + + +/** + * Created by Ziver on 2015-09-29. + */ +public class SSDPServerTest { + + public static void main(String[] args) throws IOException { + LogUtil.setGlobalLevel(Level.FINEST); + + StandardSSDPInfo service = new StandardSSDPInfo(); + service.setLocation("nowhere"); + service.setST("zep:discover"); + service.setHeader("Alias", "Desktop"); + service.setHeader("PublicKey", "SuperDesktopKey"); + + + SSDPServer ssdp = new SSDPServer(); + ssdp.addService(service); + ssdp.start(); + System.out.println("SSDP Server running"); + } +} diff --git a/test/zutil/test/UpdateClientTest.java b/test/zutil/net/update/UpdateClientTest.java similarity index 92% rename from test/zutil/test/UpdateClientTest.java rename to test/zutil/net/update/UpdateClientTest.java index 6506e69..37b5a75 100755 --- a/test/zutil/test/UpdateClientTest.java +++ b/test/zutil/net/update/UpdateClientTest.java @@ -1,75 +1,73 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.ProgressListener; -import zutil.log.CompactLogFormatter; -import zutil.log.LogUtil; -import zutil.net.update.FileInfo; -import zutil.net.update.UpdateClient; -import zutil.net.update.Zupdater; - -import java.awt.*; -import java.util.logging.Level; - -public class UpdateClientTest implements ProgressListener{ - public static void main(String[] args){ - LogUtil.setLevel("zutil", Level.FINEST); - LogUtil.setFormatter("zutil", new CompactLogFormatter()); - - UpdateClientTest client = new UpdateClientTest(); - client.start(); - } - - public void start(){ - try { - final UpdateClient client = new UpdateClient("localhost", 2000, "C:\\Users\\Ziver\\Desktop\\client"); - client.setProgressListener(new Zupdater()); - - //client.setProgressListener(this); - - EventQueue.invokeLater(new Runnable() { - public void run() { - try { - Zupdater gui = new Zupdater(); - client.setProgressListener(gui); - gui.setVisible(true); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - - client.update(); - client.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void progressUpdate(UpdateClient source, FileInfo info, double percent) { - System.out.println(info+": "+percent+"%"); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net.update; + +import zutil.ProgressListener; +import zutil.log.CompactLogFormatter; +import zutil.log.LogUtil; + +import java.awt.*; +import java.util.logging.Level; + + +public class UpdateClientTest implements ProgressListener{ + public static void main(String[] args){ + LogUtil.setLevel("zutil", Level.FINEST); + LogUtil.setFormatter("zutil", new CompactLogFormatter()); + + UpdateClientTest client = new UpdateClientTest(); + client.start(); + } + + public void start(){ + try { + final UpdateClient client = new UpdateClient("localhost", 2000, "C:\\Users\\Ziver\\Desktop\\client"); + client.setProgressListener(new Zupdater()); + + //client.setProgressListener(this); + + EventQueue.invokeLater(new Runnable() { + public void run() { + try { + Zupdater gui = new Zupdater(); + client.setProgressListener(gui); + gui.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + + client.update(); + client.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void progressUpdate(UpdateClient source, FileInfo info, double percent) { + System.out.println(info+": "+percent+"%"); + } +} diff --git a/test/zutil/test/UpdateServerTest.java b/test/zutil/net/update/UpdateServerTest.java similarity index 93% rename from test/zutil/test/UpdateServerTest.java rename to test/zutil/net/update/UpdateServerTest.java index 963bcce..6065606 100755 --- a/test/zutil/test/UpdateServerTest.java +++ b/test/zutil/net/update/UpdateServerTest.java @@ -1,44 +1,44 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.log.CompactLogFormatter; -import zutil.log.LogUtil; -import zutil.net.update.UpdateServer; - -import java.util.logging.Level; - -public class UpdateServerTest { - public static void main(String[] args){ - try { - LogUtil.setGlobalLevel(Level.FINEST); - LogUtil.setGlobalFormatter(new CompactLogFormatter()); - - new UpdateServer(2000, "C:\\Users\\Ziver\\Desktop\\server"); - }catch (Exception e) { - e.printStackTrace(); - } - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net.update; + +import zutil.log.CompactLogFormatter; +import zutil.log.LogUtil; + +import java.util.logging.Level; + + +public class UpdateServerTest { + public static void main(String[] args){ + try { + LogUtil.setGlobalLevel(Level.FINEST); + LogUtil.setGlobalFormatter(new CompactLogFormatter()); + + new UpdateServer(2000, "C:\\Users\\Ziver\\Desktop\\server"); + }catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/test/zutil/test/UPnPServerTest.java b/test/zutil/net/upnp/UPnPServerTest.java similarity index 92% rename from test/zutil/test/UPnPServerTest.java rename to test/zutil/net/upnp/UPnPServerTest.java index b78eecf..94fef65 100755 --- a/test/zutil/test/UPnPServerTest.java +++ b/test/zutil/net/upnp/UPnPServerTest.java @@ -1,63 +1,63 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.io.MultiPrintStream; -import zutil.net.http.HttpServer; -import zutil.net.ssdp.SSDPServer; -import zutil.net.upnp.UPnPMediaServer; -import zutil.net.upnp.services.UPnPContentDirectory; -import zutil.net.ws.WebServiceDef; -import zutil.net.ws.soap.SOAPHttpPage; - -import java.io.File; -import java.io.IOException; - -public class UPnPServerTest { - - public static void main(String[] args) throws IOException{ - UPnPMediaServer upnp = new UPnPMediaServer("http://192.168.0.60:8080/"); - MultiPrintStream.out.println("UPNP Server running"); - - UPnPContentDirectory cds = new UPnPContentDirectory(new File("C:\\Users\\Ziver\\Desktop\\lan")); - WebServiceDef ws = new WebServiceDef( UPnPContentDirectory.class ); - - HttpServer http = new HttpServer(8080); - //http.setDefaultPage(upnp); - http.setPage("/RootDesc", upnp ); - http.setPage("/SCP/ContentDir", cds ); - SOAPHttpPage soap = new SOAPHttpPage(ws); - soap.setObject( cds ); - soap.enableSession( false ); - http.setPage("/Action/ContentDir", soap ); - http.start(); - MultiPrintStream.out.println("HTTP Server running"); - - SSDPServer ssdp = new SSDPServer(); - ssdp.addService( upnp ); - ssdp.start(); - MultiPrintStream.out.println("SSDP Server running"); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net.upnp; + +import zutil.io.MultiPrintStream; +import zutil.net.http.HttpServer; +import zutil.net.ssdp.SSDPServer; +import zutil.net.upnp.service.UPnPContentDirectory; +import zutil.net.ws.WebServiceDef; +import zutil.net.ws.soap.SOAPHttpPage; + +import java.io.File; +import java.io.IOException; + + +public class UPnPServerTest { + + public static void main(String[] args) throws IOException{ + UPnPMediaServer upnp = new UPnPMediaServer("http://192.168.0.60:8080/"); + MultiPrintStream.out.println("UPNP Server running"); + + UPnPContentDirectory cds = new UPnPContentDirectory(new File("C:\\Users\\Ziver\\Desktop\\lan")); + WebServiceDef ws = new WebServiceDef( UPnPContentDirectory.class ); + + HttpServer http = new HttpServer(8080); + //http.setDefaultPage(upnp); + http.setPage("/RootDesc", upnp ); + http.setPage("/SCP/ContentDir", cds ); + SOAPHttpPage soap = new SOAPHttpPage(ws); + soap.setObject( cds ); + soap.enableSession( false ); + http.setPage("/Action/ContentDir", soap ); + http.start(); + MultiPrintStream.out.println("HTTP Server running"); + + SSDPServer ssdp = new SSDPServer(); + ssdp.addService( upnp ); + ssdp.start(); + MultiPrintStream.out.println("SSDP Server running"); + } +} diff --git a/test/zutil/test/SOAPClientTest.java b/test/zutil/net/ws/soap/SOAPClientTest.java similarity index 93% rename from test/zutil/test/SOAPClientTest.java rename to test/zutil/net/ws/soap/SOAPClientTest.java index 5587010..28bd722 100755 --- a/test/zutil/test/SOAPClientTest.java +++ b/test/zutil/net/ws/soap/SOAPClientTest.java @@ -1,54 +1,55 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.log.CompactLogFormatter; -import zutil.log.LogUtil; -import zutil.net.ws.WSInterface; -import zutil.net.ws.soap.SOAPClientFactory; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.logging.Level; - -public class SOAPClientTest { - - public static void main(String[] args) throws InstantiationException, IllegalAccessException, MalformedURLException { - LogUtil.setGlobalLevel(Level.ALL); - LogUtil.setFormatter("", new CompactLogFormatter()); - - TestClient intf = SOAPClientFactory.createClient(new URL("http://localhost:3289"), TestClient.class); - intf.m(); - intf.c(); - } - - - public interface TestClient extends WSInterface{ - public void m(); - - public void c(); - - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net.ws.soap; + +import zutil.log.CompactLogFormatter; +import zutil.log.LogUtil; +import zutil.net.ws.WSInterface; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.logging.Level; + + +// TODO: COnvert to JUnit +public class SOAPClientTest { + + public static void main(String[] args) throws InstantiationException, IllegalAccessException, MalformedURLException { + LogUtil.setGlobalLevel(Level.ALL); + LogUtil.setFormatter("", new CompactLogFormatter()); + + TestClient intf = SOAPClientFactory.createClient(new URL("http://localhost:3289"), TestClient.class); + intf.m(); + intf.c(); + } + + + public interface TestClient extends WSInterface{ + public void m(); + + public void c(); + + } +} diff --git a/test/zutil/test/SOAPTest.java b/test/zutil/net/ws/soap/SOAPTest.java similarity index 96% rename from test/zutil/test/SOAPTest.java rename to test/zutil/net/ws/soap/SOAPTest.java index 9ac9717..7a815c5 100755 --- a/test/zutil/test/SOAPTest.java +++ b/test/zutil/net/ws/soap/SOAPTest.java @@ -1,156 +1,157 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.dom4j.Document; -import org.dom4j.io.OutputFormat; -import org.dom4j.io.XMLWriter; -import zutil.net.ws.WSInterface; -import zutil.net.ws.WSInterface.WSNamespace; -import zutil.net.ws.WSReturnObject; -import zutil.net.ws.WebServiceDef; -import zutil.net.ws.soap.SOAPHttpPage; -import zutil.parser.wsdl.WSDLWriter; - - -public class SOAPTest { - /************************* TEST CASES ************************/ - public static void main(String[] args){ - new SOAPTest(); - } - - public SOAPTest(){ - WebServiceDef wsDef = new WebServiceDef( MainSOAPClass.class ); - SOAPHttpPage soap = new SOAPHttpPage( wsDef ); - - System.out.println( "****************** WSDL *********************" ); - WSDLWriter wsdl = new WSDLWriter( wsDef ); - wsdl.write(System.out); - - // Response - try { - System.out.println( "\n****************** REQUEST *********************" ); - String request = "\n" + - "\n" + - " \n" + - " \n" + - " IBM\n" + - " \n" + - - " \n" + - " IBM\n" + - " \n" + - " \n" + - ""; - System.out.println(request); - System.out.println( "\n****************** EXECUTION *********************" ); - Document document = soap.genSOAPResponse(request); - System.out.println( "\n****************** RESPONSE *********************" ); - - OutputFormat format = OutputFormat.createPrettyPrint(); - XMLWriter writer = new XMLWriter( System.out, format ); - writer.write( document ); - - System.out.println(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /************************* TEST CLASSES ************************/ - @SuppressWarnings("unused") - public static class SpecialReturnClass extends WSReturnObject{ - @WSValueName(value="otherValue1") - public String param1 = "otherValue1"; - @WSValueName("otherValue2") - public String param2 = "otherValue2"; - public byte[] b = new byte[]{0x12, 0x23}; - public InnerClass inner = new InnerClass(); - } - - @SuppressWarnings("unused") - public static class InnerClass extends WSReturnObject{ - public String innerClassParam1 = "innerClass1"; - public String innerClassParam2 = "innerClass2"; - } - - @SuppressWarnings("unused") - public static class SimpleReturnClass extends WSReturnObject{ - @WSValueName("otherParam1") - public String param1 = "param1"; - public String param2 = "param2"; - } - - @SuppressWarnings("unused") - @WSNamespace("http://test.se:8080/") - public static class MainSOAPClass implements WSInterface{ - public MainSOAPClass(){} - - @WSHeader() - @WSDocumentation("Documentation of method exceptionMethod()") - public void exceptionMethod( - @WSParamName(value="otherParam1", optional=true) int param1, - @WSParamName(value="otherParam2", optional=true) int param2) throws Exception{ - System.out.println("Executing method: exceptionMethod(int param1="+param1+", int param2="+param2+",)"); - throw new Exception("This is an Exception"); - } - - @WSReturnName("stringArray") - @WSParamDocumentation("Documentation of stringArrayMethod()") - public String[][] stringArrayMethod ( - @WSParamName("StringName") String str) throws Exception{ - System.out.println("Executing method: stringArrayMethod(String str='"+str+"')"); - return new String[][]{{"test","test2"},{"test3","test4"}}; - } - - @WSReturnName("specialReturnClass") - @WSParamDocumentation("Documentation of specialReturnMethod()") - public SpecialReturnClass[] specialReturnMethod ( - @WSParamName("StringName2") String str) throws Exception{ - System.out.println("Executing method: specialReturnMethod(String str='"+str+"')"); - return new SpecialReturnClass[]{new SpecialReturnClass(), new SpecialReturnClass()}; - } - - @WSReturnName("SimpleReturnClass") - @WSParamDocumentation("null is the kala") - public SimpleReturnClass simpleReturnClassMethod ( - @WSParamName("byte") String lol) throws Exception{ - System.out.println("Executing method: simpleReturnClassMethod()"); - SimpleReturnClass tmp = new SimpleReturnClass(); - tmp.param1 = "newParam1"; - tmp.param2 = "newParam2"; - return tmp; - } - - @WSParamDocumentation("void method documentation") - public void voidMethod (){ } - - @WSDisabled() - public void disabledMethod(){ } - protected void protectedMethod(){ } - - private void privateMethod(){ } - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.net.ws.soap; + +import org.dom4j.Document; +import org.dom4j.io.OutputFormat; +import org.dom4j.io.XMLWriter; + +import zutil.net.ws.WSInterface; +import zutil.net.ws.WSInterface.WSNamespace; +import zutil.net.ws.WSReturnObject; +import zutil.net.ws.WebServiceDef; +import zutil.parser.wsdl.WSDLWriter; + + +// TODO: Convert to JUnit +public class SOAPTest { + /************************* TEST CASES ************************/ + public static void main(String[] args){ + new SOAPTest(); + } + + public SOAPTest(){ + WebServiceDef wsDef = new WebServiceDef( MainSOAPClass.class ); + SOAPHttpPage soap = new SOAPHttpPage( wsDef ); + + System.out.println( "****************** WSDL *********************" ); + WSDLWriter wsdl = new WSDLWriter( wsDef ); + wsdl.write(System.out); + + // Response + try { + System.out.println( "\n****************** REQUEST *********************" ); + String request = "\n" + + "\n" + + " \n" + + " \n" + + " IBM\n" + + " \n" + + + " \n" + + " IBM\n" + + " \n" + + " \n" + + ""; + System.out.println(request); + System.out.println( "\n****************** EXECUTION *********************" ); + Document document = soap.genSOAPResponse(request); + System.out.println( "\n****************** RESPONSE *********************" ); + + OutputFormat format = OutputFormat.createPrettyPrint(); + XMLWriter writer = new XMLWriter( System.out, format ); + writer.write( document ); + + System.out.println(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /************************* TEST CLASSES ************************/ + @SuppressWarnings("unused") + public static class SpecialReturnClass extends WSReturnObject{ + @WSValueName(value="otherValue1") + public String param1 = "otherValue1"; + @WSValueName("otherValue2") + public String param2 = "otherValue2"; + public byte[] b = new byte[]{0x12, 0x23}; + public InnerClass inner = new InnerClass(); + } + + @SuppressWarnings("unused") + public static class InnerClass extends WSReturnObject{ + public String innerClassParam1 = "innerClass1"; + public String innerClassParam2 = "innerClass2"; + } + + @SuppressWarnings("unused") + public static class SimpleReturnClass extends WSReturnObject{ + @WSValueName("otherParam1") + public String param1 = "param1"; + public String param2 = "param2"; + } + + @SuppressWarnings("unused") + @WSNamespace("http://test.se:8080/") + public static class MainSOAPClass implements WSInterface{ + public MainSOAPClass(){} + + @WSHeader() + @WSDocumentation("Documentation of method exceptionMethod()") + public void exceptionMethod( + @WSParamName(value="otherParam1", optional=true) int param1, + @WSParamName(value="otherParam2", optional=true) int param2) throws Exception{ + System.out.println("Executing method: exceptionMethod(int param1="+param1+", int param2="+param2+",)"); + throw new Exception("This is an Exception"); + } + + @WSReturnName("stringArray") + @WSParamDocumentation("Documentation of stringArrayMethod()") + public String[][] stringArrayMethod ( + @WSParamName("StringName") String str) throws Exception{ + System.out.println("Executing method: stringArrayMethod(String str='"+str+"')"); + return new String[][]{{"test","test2"},{"test3","test4"}}; + } + + @WSReturnName("specialReturnClass") + @WSParamDocumentation("Documentation of specialReturnMethod()") + public SpecialReturnClass[] specialReturnMethod ( + @WSParamName("StringName2") String str) throws Exception{ + System.out.println("Executing method: specialReturnMethod(String str='"+str+"')"); + return new SpecialReturnClass[]{new SpecialReturnClass(), new SpecialReturnClass()}; + } + + @WSReturnName("SimpleReturnClass") + @WSParamDocumentation("null is the kala") + public SimpleReturnClass simpleReturnClassMethod ( + @WSParamName("byte") String lol) throws Exception{ + System.out.println("Executing method: simpleReturnClassMethod()"); + SimpleReturnClass tmp = new SimpleReturnClass(); + tmp.param1 = "newParam1"; + tmp.param2 = "newParam2"; + return tmp; + } + + @WSParamDocumentation("void method documentation") + public void voidMethod (){ } + + @WSDisabled() + public void disabledMethod(){ } + protected void protectedMethod(){ } + + private void privateMethod(){ } + } +} diff --git a/test/zutil/test/ParserTest.java b/test/zutil/parser/BBCodeParserTest.java similarity index 93% rename from test/zutil/test/ParserTest.java rename to test/zutil/parser/BBCodeParserTest.java index 00ebe9a..6b5d20d 100755 --- a/test/zutil/test/ParserTest.java +++ b/test/zutil/parser/BBCodeParserTest.java @@ -1,49 +1,48 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.parser.BBCodeParser; - -import static org.junit.Assert.assertEquals; - - -public class ParserTest{ - - @Test - public void BBCodeParser() { - BBCodeParser parser = new BBCodeParser(); - - assertEquals("1234", parser.read("1234")); - assertEquals("1234", parser.read("[i]1234[/i]")); - assertEquals("[apa]lol[/apa]", parser.read("[apa]lol[/apa]")); - assertEquals("jshdkj lol [apa]lol[/apa]", parser.read("jshdkj [u]lol [apa]lol[/apa]")); - //assertEquals("jshdkj [m]lol[/k] lol", parser.read("jshdkj [m]lol[/k] [i]lol[/i]")); - assertEquals("jshdkj [m", parser.read("jshdkj [m")); - assertEquals("jshdkj [/m", parser.read("jshdkj [/m")); - assertEquals("jshdkj m]", parser.read("jshdkj m]")); - assertEquals("jshdkj
", parser.read("jshdkj
")); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.parser; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + + +public class BBCodeParserTest{ + + @Test + public void BBCodeParser() { + BBCodeParser parser = new BBCodeParser(); + + assertEquals("1234", parser.read("1234")); + assertEquals("1234", parser.read("[i]1234[/i]")); + assertEquals("[apa]lol[/apa]", parser.read("[apa]lol[/apa]")); + assertEquals("jshdkj lol [apa]lol[/apa]", parser.read("jshdkj [u]lol [apa]lol[/apa]")); + //assertEquals("jshdkj [m]lol[/k] lol", parser.read("jshdkj [m]lol[/k] [i]lol[/i]")); + assertEquals("jshdkj [m", parser.read("jshdkj [m")); + assertEquals("jshdkj [/m", parser.read("jshdkj [/m")); + assertEquals("jshdkj m]", parser.read("jshdkj m]")); + assertEquals("jshdkj
", parser.read("jshdkj
")); + } +} diff --git a/test/zutil/test/Base64Test.java b/test/zutil/parser/Base64Test.java similarity index 96% rename from test/zutil/test/Base64Test.java rename to test/zutil/parser/Base64Test.java index 46d1a6d..1d2d3e9 100755 --- a/test/zutil/test/Base64Test.java +++ b/test/zutil/parser/Base64Test.java @@ -1,77 +1,76 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.parser.Base64Decoder; -import zutil.parser.Base64Encoder; - -import java.util.Base64; - -import static org.junit.Assert.assertEquals; - -public class Base64Test { - - @Test - public void decode() { - assertEquals( "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.", - Base64Decoder.decode("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=") - ); - - Base64Decoder decoder = new Base64Decoder(); - decoder.clear(); - decoder.read("YW55IGNhcm5hbCBwbGVhc3VyZQ=="); - assertEquals( "any carnal pleasure", decoder.toString() ); - decoder.clear(); - decoder.read("bGVhc3VyZS4="); - assertEquals( "leasure.", decoder.toString() ); - decoder.clear(); - decoder.read("YW55IGNhcm5hbCBwbGVhc3Vy"); - assertEquals( "any carnal pleasur", decoder.toString() ); - decoder.clear(); - } - - @Test - public void encode() { - assertEquals("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=" , - Base64Encoder.encode("Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.") - ); - - assertEquals("YW55IGNhcm5hbCBwbGVhc3VyZQ==", Base64Encoder.encode("any carnal pleasure")); - assertEquals("bGVhc3VyZS4=", Base64Encoder.encode("leasure.")); - assertEquals("YW55IGNhcm5hbCBwbGVhc3Vy", Base64Encoder.encode("any carnal pleasur")); - } - - @Test - public void encodeJavaUtil() { - assertEquals("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=" , - Base64.getEncoder().encodeToString("Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.".getBytes()) - ); - - assertEquals("YW55IGNhcm5hbCBwbGVhc3VyZQ==", Base64.getEncoder().encodeToString("any carnal pleasure".getBytes())); - assertEquals("bGVhc3VyZS4=", Base64.getEncoder().encodeToString("leasure.".getBytes())); - assertEquals("YW55IGNhcm5hbCBwbGVhc3Vy", Base64.getEncoder().encodeToString("any carnal pleasur".getBytes())); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.parser; + +import org.junit.Test; + +import java.util.Base64; + +import static org.junit.Assert.assertEquals; + + +public class Base64Test { + + @Test + public void decode() { + assertEquals( "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.", + Base64Decoder.decode("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=") + ); + + Base64Decoder decoder = new Base64Decoder(); + decoder.clear(); + decoder.read("YW55IGNhcm5hbCBwbGVhc3VyZQ=="); + assertEquals( "any carnal pleasure", decoder.toString() ); + decoder.clear(); + decoder.read("bGVhc3VyZS4="); + assertEquals( "leasure.", decoder.toString() ); + decoder.clear(); + decoder.read("YW55IGNhcm5hbCBwbGVhc3Vy"); + assertEquals( "any carnal pleasur", decoder.toString() ); + decoder.clear(); + } + + @Test + public void encode() { + assertEquals("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=" , + Base64Encoder.encode("Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.") + ); + + assertEquals("YW55IGNhcm5hbCBwbGVhc3VyZQ==", Base64Encoder.encode("any carnal pleasure")); + assertEquals("bGVhc3VyZS4=", Base64Encoder.encode("leasure.")); + assertEquals("YW55IGNhcm5hbCBwbGVhc3Vy", Base64Encoder.encode("any carnal pleasur")); + } + + @Test + public void encodeJavaUtil() { + assertEquals("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=" , + Base64.getEncoder().encodeToString("Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.".getBytes()) + ); + + assertEquals("YW55IGNhcm5hbCBwbGVhc3VyZQ==", Base64.getEncoder().encodeToString("any carnal pleasure".getBytes())); + assertEquals("bGVhc3VyZS4=", Base64.getEncoder().encodeToString("leasure.".getBytes())); + assertEquals("YW55IGNhcm5hbCBwbGVhc3Vy", Base64.getEncoder().encodeToString("any carnal pleasur".getBytes())); + } +} diff --git a/test/zutil/test/CSVParserTest.java b/test/zutil/parser/CSVParserTest.java similarity index 95% rename from test/zutil/test/CSVParserTest.java rename to test/zutil/parser/CSVParserTest.java index 2e4602c..42bfdf2 100755 --- a/test/zutil/test/CSVParserTest.java +++ b/test/zutil/parser/CSVParserTest.java @@ -1,110 +1,109 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.parser.CSVParser; -import zutil.parser.DataNode; - -import java.io.IOException; -import java.io.StringReader; - -import static org.junit.Assert.assertEquals; - -/** - * Created by ezivkoc on 2015-07-30. - */ -public class CSVParserTest { - - - @Test - public void emptyTest(){ - DataNode node = CSVParser.read(""); - assertEquals(null, node); - } - - @Test - public void simpleTest(){ - DataNode node = CSVParser.read("hello,world,you"); - assertEquals(3, node.size()); - assertEquals("hello", node.get(0).getString()); - assertEquals("world", node.get(1).getString()); - assertEquals("you", node.get(2).getString()); - } - - @Test - public void simpleHeaderTest() throws IOException { - CSVParser parser = new CSVParser(new StringReader("where,what,who\nhello,world,you"), true); - DataNode node = parser.read(); - assertEquals(3, node.size()); - assertEquals("hello", node.get(0).getString()); - assertEquals("world", node.get(1).getString()); - assertEquals("you", node.get(2).getString()); - node = parser.getHeaders(); - assertEquals("where", node.get(0).getString()); - assertEquals("what", node.get(1).getString()); - assertEquals("who", node.get(2).getString()); - } - - @Test - public void simpleMultilineTest() throws IOException { - CSVParser parser = new CSVParser( - new StringReader("hello,world,you\nhello,world,you\nhello,world,you")); - int rows=0; - for(DataNode node = parser.read(); node != null; node=parser.read(), ++rows) { - assertEquals(3, node.size()); - assertEquals("hello", node.get(0).getString()); - assertEquals("world", node.get(1).getString()); - assertEquals("you", node.get(2).getString()); - } - assertEquals(3, rows); - } - - @Test - public void quotedTest(){ - DataNode node = CSVParser.read("\"hello\",\"world\",\"you\""); - assertEquals(3, node.size()); - assertEquals("hello", node.get(0).getString()); - assertEquals("world", node.get(1).getString()); - assertEquals("you", node.get(2).getString()); - } - - @Test - public void quotedIncorrectlyTest(){ - DataNode node = CSVParser.read("hello\",wo\"rl\"d,\"you\""); - assertEquals(3, node.size()); - assertEquals("hello\"", node.get(0).getString()); - assertEquals("wo\"rl\"d", node.get(1).getString()); - assertEquals("you", node.get(2).getString()); - } - - @Test - public void quotedCommaTest(){ - DataNode node = CSVParser.read("hello,\"world,you\""); - assertEquals(2, node.size()); - assertEquals("hello", node.get(0).getString()); - assertEquals("world,you", node.get(1).getString()); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.parser; + +import org.junit.Test; + +import java.io.IOException; +import java.io.StringReader; + +import static org.junit.Assert.assertEquals; + + +/** + * Created by ezivkoc on 2015-07-30. + */ +public class CSVParserTest { + + + @Test + public void emptyTest(){ + DataNode node = CSVParser.read(""); + assertEquals(null, node); + } + + @Test + public void simpleTest(){ + DataNode node = CSVParser.read("hello,world,you"); + assertEquals(3, node.size()); + assertEquals("hello", node.get(0).getString()); + assertEquals("world", node.get(1).getString()); + assertEquals("you", node.get(2).getString()); + } + + @Test + public void simpleHeaderTest() throws IOException { + CSVParser parser = new CSVParser(new StringReader("where,what,who\nhello,world,you"), true); + DataNode node = parser.read(); + assertEquals(3, node.size()); + assertEquals("hello", node.get(0).getString()); + assertEquals("world", node.get(1).getString()); + assertEquals("you", node.get(2).getString()); + node = parser.getHeaders(); + assertEquals("where", node.get(0).getString()); + assertEquals("what", node.get(1).getString()); + assertEquals("who", node.get(2).getString()); + } + + @Test + public void simpleMultilineTest() throws IOException { + CSVParser parser = new CSVParser( + new StringReader("hello,world,you\nhello,world,you\nhello,world,you")); + int rows=0; + for(DataNode node = parser.read(); node != null; node=parser.read(), ++rows) { + assertEquals(3, node.size()); + assertEquals("hello", node.get(0).getString()); + assertEquals("world", node.get(1).getString()); + assertEquals("you", node.get(2).getString()); + } + assertEquals(3, rows); + } + + @Test + public void quotedTest(){ + DataNode node = CSVParser.read("\"hello\",\"world\",\"you\""); + assertEquals(3, node.size()); + assertEquals("hello", node.get(0).getString()); + assertEquals("world", node.get(1).getString()); + assertEquals("you", node.get(2).getString()); + } + + @Test + public void quotedIncorrectlyTest(){ + DataNode node = CSVParser.read("hello\",wo\"rl\"d,\"you\""); + assertEquals(3, node.size()); + assertEquals("hello\"", node.get(0).getString()); + assertEquals("wo\"rl\"d", node.get(1).getString()); + assertEquals("you", node.get(2).getString()); + } + + @Test + public void quotedCommaTest(){ + DataNode node = CSVParser.read("hello,\"world,you\""); + assertEquals(2, node.size()); + assertEquals("hello", node.get(0).getString()); + assertEquals("world,you", node.get(1).getString()); + } +} diff --git a/test/zutil/test/TemplatorTest.java b/test/zutil/parser/TemplatorTest.java similarity index 96% rename from test/zutil/test/TemplatorTest.java rename to test/zutil/parser/TemplatorTest.java index 4bac757..30a171c 100755 --- a/test/zutil/test/TemplatorTest.java +++ b/test/zutil/parser/TemplatorTest.java @@ -1,305 +1,305 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.parser.Templator; - -import java.util.ArrayList; -import java.util.Arrays; - -import static org.junit.Assert.assertEquals; - -/** - * Created by Ziver on 2015-03-23. - */ -public class TemplatorTest { - class TestClass{ - public String attr; - } - class TestSubClass extends TestClass{ - public String subAttr; - } - class TestFuncClass{ - public boolean isTrue(){ - return true; - } - public boolean isFalse(){ - return false; - } - } - - - @Test - public void tagIncorrectTest(){ - assertEquals("{{", - new Templator("{{").compile()); - assertEquals("}}", - new Templator("}}").compile()); - assertEquals("}}", - new Templator("}}").compile()); - assertEquals("{{", - new Templator("{{").compile()); - assertEquals("{", - new Templator("{").compile()); - assertEquals("}", - new Templator("}").compile()); - assertEquals("{}", - new Templator("{}").compile()); - assertEquals("{test}", - new Templator("{test}").compile()); - } - @Test - public void attributeEmptyTest(){ - Templator tmpl = new Templator("{{test}}"); - assertEquals("null", tmpl.compile()); - } - @Test - public void attributeSimpleTest() { - Templator tmpl = new Templator("{{test}}"); - tmpl.set("test", "1234"); - assertEquals("1234", tmpl.compile()); - } - @Test - public void attributeObjectTest(){ - Templator tmpl = new Templator("{{test.attr}}"); - TestClass obj = new TestClass(); - obj.attr = "1234"; - tmpl.set("test", obj); - assertEquals("1234", tmpl.compile()); - } - - - - @Test - public void conditionIncompleteTest(){ - assertEquals("{{#key}}", - new Templator("{{#key}}").compile()); - assertEquals("{{/key}}", - new Templator("{{/key}}").compile()); - assertEquals("", - new Templator("{{#key}}{{/key}}").compile()); - assertEquals("", - new Templator("{{#key}}{{/key}}").compile()); - } - @Test - public void conditionEmptyTest(){ - Templator tmpl = new Templator( - "{{#key}}123456789{{/key}}"); - assertEquals( - "", - tmpl.compile()); - } - @Test - public void conditionSimpleTest(){ - Templator tmpl = new Templator( - "{{#key}}123456789{{/key}}"); - tmpl.set("key", "set"); - assertEquals( - "123456789", - tmpl.compile()); - } - @Test - public void conditionObjectTest(){ - Templator tmpl = new Templator("{{#test.attr}}5678{{/test.attr}}"); - TestClass obj = new TestClass(); - obj.attr = "1234"; - tmpl.set("test", obj); - assertEquals("5678", tmpl.compile()); - - tmpl.clear(); - tmpl.set("test", new TestClass()); - assertEquals("", tmpl.compile()); - } - @Test - public void conditionBooleanTest(){ - Templator tmpl = new Templator( - "{{#key}}123456789{{/key}}"); - tmpl.set("key", true); - assertEquals( - "123456789", tmpl.compile()); - - tmpl.set("key", false); - assertEquals( - "", tmpl.compile()); - } - - - - @Test - public void conditionIteratorEmptyTest(){ - Templator tmpl = new Templator("{{#list}}1234 {{.}} {{/list}}"); - tmpl.set("list", new ArrayList()); - assertEquals( - "", tmpl.compile()); - } - @Test - public void conditionIteratorTest(){ - Templator tmpl = new Templator("{{#list}}{{.}}{{/list}}"); - tmpl.set("list", Arrays.asList(1,2,3,4,5,6,7,8,9)); - assertEquals( - "123456789", tmpl.compile()); - } - @Test - public void conditionArrayTest(){ - Templator tmpl = new Templator("{{#list}}{{.}}{{/list}}"); - tmpl.set("list", new int[]{1,2,3,4,5,6,7,8,9}); - assertEquals( - "123456789", tmpl.compile()); - } - @Test - public void conditionArrayLength(){ - Templator tmpl = new Templator("{{#list.length}}run once{{/list.length}}"); - tmpl.set("list", new int[]{}); - assertEquals( - "", tmpl.compile()); - tmpl.set("list", new int[]{1}); - assertEquals( - "run once", tmpl.compile()); - tmpl.set("list", new int[]{1,2,3,4,5,6,7,8,9}); - assertEquals( - "run once", tmpl.compile()); - } - - - @Test - public void negativeConditionEmptyTest(){ - Templator tmpl = new Templator( - "{{^key}}123456789{{/key}}"); - assertEquals( - "123456789", tmpl.compile()); - } - @Test - public void negativeConditionSetTest(){ - Templator tmpl = new Templator( - "{{^key}}123456789{{/key}}"); - tmpl.set("key", "set"); - assertEquals( - "", tmpl.compile()); - } - @Test - public void negativeConditionObjectTest(){ - Templator tmpl = new Templator("{{^test.attr}}5678{{/test.attr}}"); - TestClass obj = new TestClass(); - obj.attr = "1234"; - tmpl.set("test", obj); - assertEquals("", tmpl.compile()); - - tmpl.clear(); - tmpl.set("test", new TestClass()); - assertEquals("5678", tmpl.compile()); - } - @Test - public void negativeConditionIteratorTest(){ - Templator tmpl = new Templator( - "{{^key}}123456789{{/key}}"); - tmpl.set("key", Arrays.asList(1,2,3,4,5,6,7,8,9)); - assertEquals( - "", tmpl.compile()); - } - @Test - public void negativeConditionIteratorEmptyTest(){ - Templator tmpl = new Templator( - "{{^key}}123456789{{/key}}"); - tmpl.set("key", new ArrayList()); - assertEquals( - "123456789", tmpl.compile()); - } - @Test - public void negativeConditionBooleanTest(){ - Templator tmpl = new Templator( - "{{^key}}123456789{{/key}}"); - tmpl.set("key", true); - assertEquals( - "", tmpl.compile()); - - tmpl.set("key", false); - assertEquals( - "123456789", tmpl.compile()); - } - - - - @Test - public void commentTest(){ - Templator tmpl = new Templator( - "{{! This is a comment}}"); - assertEquals( - "", tmpl.compile()); - } - - - @Test - public void functionCallTest(){ - Templator tmpl = new Templator( - "{{#obj.isTrue()}}it is true{{/obj.isTrue()}}"); - tmpl.set("obj", new TestFuncClass()); - assertEquals( - "it is true", tmpl.compile()); - - tmpl = new Templator( - "{{#obj.isFalse()}}it is true{{/obj.isFalse()}}"); - tmpl.set("obj", new TestFuncClass()); - assertEquals( - "", tmpl.compile()); - } - @Test - public void functionInArrayTest(){ - Templator tmpl = new Templator( - "{{#list}}{{#.isTrue()}}1{{/.isTrue()}}{{/list}}"); - tmpl.set("list", new TestFuncClass[]{ - new TestFuncClass(),new TestFuncClass(),new TestFuncClass() - }); - assertEquals( - "111", tmpl.compile()); - } - - - @Test - public void recursiveTemplateorTest(){ - Templator tmpl2 = new Templator( - "{{value1}},{{value2}}"); - tmpl2.set("value1", "sub1"); - tmpl2.set("value2", "sub2"); - Templator tmpl = new Templator( - "{{parent}}:{{child}}"); - tmpl.set("parent", "super"); - tmpl.set("child", tmpl2); - - assertEquals( - "super:sub1,sub2", tmpl.compile()); - } - - - @Test - public void subClassTest(){ - Templator tmpl = new Templator("{{test.attr}}:{{test.subAttr}}"); - TestSubClass obj = new TestSubClass(); - obj.attr = "1234"; - obj.subAttr = "5678"; - tmpl.set("test", obj); - assertEquals("1234:5678", tmpl.compile()); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.parser; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; + + +/** + * Created by Ziver on 2015-03-23. + */ +public class TemplatorTest { + class TestClass{ + public String attr; + } + class TestSubClass extends TestClass{ + public String subAttr; + } + class TestFuncClass{ + public boolean isTrue(){ + return true; + } + public boolean isFalse(){ + return false; + } + } + + + @Test + public void tagIncorrectTest(){ + assertEquals("{{", + new Templator("{{").compile()); + assertEquals("}}", + new Templator("}}").compile()); + assertEquals("}}", + new Templator("}}").compile()); + assertEquals("{{", + new Templator("{{").compile()); + assertEquals("{", + new Templator("{").compile()); + assertEquals("}", + new Templator("}").compile()); + assertEquals("{}", + new Templator("{}").compile()); + assertEquals("{test}", + new Templator("{test}").compile()); + } + @Test + public void attributeEmptyTest(){ + Templator tmpl = new Templator("{{test}}"); + assertEquals("null", tmpl.compile()); + } + @Test + public void attributeSimpleTest() { + Templator tmpl = new Templator("{{test}}"); + tmpl.set("test", "1234"); + assertEquals("1234", tmpl.compile()); + } + @Test + public void attributeObjectTest(){ + Templator tmpl = new Templator("{{test.attr}}"); + TestClass obj = new TestClass(); + obj.attr = "1234"; + tmpl.set("test", obj); + assertEquals("1234", tmpl.compile()); + } + + + + @Test + public void conditionIncompleteTest(){ + assertEquals("{{#key}}", + new Templator("{{#key}}").compile()); + assertEquals("{{/key}}", + new Templator("{{/key}}").compile()); + assertEquals("", + new Templator("{{#key}}{{/key}}").compile()); + assertEquals("", + new Templator("{{#key}}{{/key}}").compile()); + } + @Test + public void conditionEmptyTest(){ + Templator tmpl = new Templator( + "{{#key}}123456789{{/key}}"); + assertEquals( + "", + tmpl.compile()); + } + @Test + public void conditionSimpleTest(){ + Templator tmpl = new Templator( + "{{#key}}123456789{{/key}}"); + tmpl.set("key", "set"); + assertEquals( + "123456789", + tmpl.compile()); + } + @Test + public void conditionObjectTest(){ + Templator tmpl = new Templator("{{#test.attr}}5678{{/test.attr}}"); + TestClass obj = new TestClass(); + obj.attr = "1234"; + tmpl.set("test", obj); + assertEquals("5678", tmpl.compile()); + + tmpl.clear(); + tmpl.set("test", new TestClass()); + assertEquals("", tmpl.compile()); + } + @Test + public void conditionBooleanTest(){ + Templator tmpl = new Templator( + "{{#key}}123456789{{/key}}"); + tmpl.set("key", true); + assertEquals( + "123456789", tmpl.compile()); + + tmpl.set("key", false); + assertEquals( + "", tmpl.compile()); + } + + + + @Test + public void conditionIteratorEmptyTest(){ + Templator tmpl = new Templator("{{#list}}1234 {{.}} {{/list}}"); + tmpl.set("list", new ArrayList()); + assertEquals( + "", tmpl.compile()); + } + @Test + public void conditionIteratorTest(){ + Templator tmpl = new Templator("{{#list}}{{.}}{{/list}}"); + tmpl.set("list", Arrays.asList(1,2,3,4,5,6,7,8,9)); + assertEquals( + "123456789", tmpl.compile()); + } + @Test + public void conditionArrayTest(){ + Templator tmpl = new Templator("{{#list}}{{.}}{{/list}}"); + tmpl.set("list", new int[]{1,2,3,4,5,6,7,8,9}); + assertEquals( + "123456789", tmpl.compile()); + } + @Test + public void conditionArrayLength(){ + Templator tmpl = new Templator("{{#list.length}}run once{{/list.length}}"); + tmpl.set("list", new int[]{}); + assertEquals( + "", tmpl.compile()); + tmpl.set("list", new int[]{1}); + assertEquals( + "run once", tmpl.compile()); + tmpl.set("list", new int[]{1,2,3,4,5,6,7,8,9}); + assertEquals( + "run once", tmpl.compile()); + } + + + @Test + public void negativeConditionEmptyTest(){ + Templator tmpl = new Templator( + "{{^key}}123456789{{/key}}"); + assertEquals( + "123456789", tmpl.compile()); + } + @Test + public void negativeConditionSetTest(){ + Templator tmpl = new Templator( + "{{^key}}123456789{{/key}}"); + tmpl.set("key", "set"); + assertEquals( + "", tmpl.compile()); + } + @Test + public void negativeConditionObjectTest(){ + Templator tmpl = new Templator("{{^test.attr}}5678{{/test.attr}}"); + TestClass obj = new TestClass(); + obj.attr = "1234"; + tmpl.set("test", obj); + assertEquals("", tmpl.compile()); + + tmpl.clear(); + tmpl.set("test", new TestClass()); + assertEquals("5678", tmpl.compile()); + } + @Test + public void negativeConditionIteratorTest(){ + Templator tmpl = new Templator( + "{{^key}}123456789{{/key}}"); + tmpl.set("key", Arrays.asList(1,2,3,4,5,6,7,8,9)); + assertEquals( + "", tmpl.compile()); + } + @Test + public void negativeConditionIteratorEmptyTest(){ + Templator tmpl = new Templator( + "{{^key}}123456789{{/key}}"); + tmpl.set("key", new ArrayList()); + assertEquals( + "123456789", tmpl.compile()); + } + @Test + public void negativeConditionBooleanTest(){ + Templator tmpl = new Templator( + "{{^key}}123456789{{/key}}"); + tmpl.set("key", true); + assertEquals( + "", tmpl.compile()); + + tmpl.set("key", false); + assertEquals( + "123456789", tmpl.compile()); + } + + + + @Test + public void commentTest(){ + Templator tmpl = new Templator( + "{{! This is a comment}}"); + assertEquals( + "", tmpl.compile()); + } + + + @Test + public void functionCallTest(){ + Templator tmpl = new Templator( + "{{#obj.isTrue()}}it is true{{/obj.isTrue()}}"); + tmpl.set("obj", new TestFuncClass()); + assertEquals( + "it is true", tmpl.compile()); + + tmpl = new Templator( + "{{#obj.isFalse()}}it is true{{/obj.isFalse()}}"); + tmpl.set("obj", new TestFuncClass()); + assertEquals( + "", tmpl.compile()); + } + @Test + public void functionInArrayTest(){ + Templator tmpl = new Templator( + "{{#list}}{{#.isTrue()}}1{{/.isTrue()}}{{/list}}"); + tmpl.set("list", new TestFuncClass[]{ + new TestFuncClass(),new TestFuncClass(),new TestFuncClass() + }); + assertEquals( + "111", tmpl.compile()); + } + + + @Test + public void recursiveTemplateorTest(){ + Templator tmpl2 = new Templator( + "{{value1}},{{value2}}"); + tmpl2.set("value1", "sub1"); + tmpl2.set("value2", "sub2"); + Templator tmpl = new Templator( + "{{parent}}:{{child}}"); + tmpl.set("parent", "super"); + tmpl.set("child", tmpl2); + + assertEquals( + "super:sub1,sub2", tmpl.compile()); + } + + + @Test + public void subClassTest(){ + Templator tmpl = new Templator("{{test.attr}}:{{test.subAttr}}"); + TestSubClass obj = new TestSubClass(); + obj.attr = "1234"; + obj.subAttr = "5678"; + tmpl.set("test", obj); + assertEquals("1234:5678", tmpl.compile()); + } +} diff --git a/test/zutil/test/URLDecoderTest.java b/test/zutil/parser/URLDecoderTest.java similarity index 99% rename from test/zutil/test/URLDecoderTest.java rename to test/zutil/parser/URLDecoderTest.java index 03b0c2c..5a419c2 100755 --- a/test/zutil/test/URLDecoderTest.java +++ b/test/zutil/parser/URLDecoderTest.java @@ -22,7 +22,7 @@ * THE SOFTWARE. */ -package zutil.test; +package zutil.parser; import org.junit.Test; import zutil.parser.URLDecoder; diff --git a/test/zutil/test/BinaryStructTest.java b/test/zutil/parser/binary/BinaryStructTest.java similarity index 97% rename from test/zutil/test/BinaryStructTest.java rename to test/zutil/parser/binary/BinaryStructTest.java index 0ac3c63..f254d2e 100755 --- a/test/zutil/test/BinaryStructTest.java +++ b/test/zutil/parser/binary/BinaryStructTest.java @@ -22,15 +22,14 @@ * THE SOFTWARE. */ -package zutil.test; +package zutil.parser.binary; import org.junit.Test; -import zutil.parser.binary.BinaryStruct; -import zutil.parser.binary.BinaryStructParser; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertFalse; + /** * Created by Ziver on 2016-01-28. */ diff --git a/test/zutil/test/JSONParserTest.java b/test/zutil/parser/json/JSONParserTest.java similarity index 96% rename from test/zutil/test/JSONParserTest.java rename to test/zutil/parser/json/JSONParserTest.java index 35314f4..eb35732 100755 --- a/test/zutil/test/JSONParserTest.java +++ b/test/zutil/parser/json/JSONParserTest.java @@ -1,183 +1,183 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.parser.DataNode; -import zutil.parser.DataNode.DataType; -import zutil.parser.json.JSONParser; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - - -public class JSONParserTest { - - @Test - public void nullString(){ - DataNode data = JSONParser.read(null); - assertNull(data); - } - - @Test - public void emptyString(){ - DataNode data = JSONParser.read(""); - assertNull(data); - } - - @Test - public void emptyMap(){ - DataNode data = JSONParser.read("{}"); - assertEquals(DataType.Map, data.getType()); - assertEquals( 0, data.size()); - } - - @Test - public void emptyList(){ - DataNode data = JSONParser.read("[]"); - assertEquals(DataType.List, data.getType()); - assertEquals( 0, data.size()); - } - - @Test - public void valueInt(){ - DataNode data = JSONParser.read("1234"); - assert(data.isValue()); - assertEquals( DataType.Number, data.getType()); - assertEquals( 1234, data.getInt()); - } - - @Test - public void valueDouble(){ - DataNode data = JSONParser.read("12.34"); - assert(data.isValue()); - assertEquals( DataType.Number, data.getType()); - assertEquals( 12.34, data.getDouble(), 0); - } - - @Test - public void valueBoolean(){ - DataNode data = JSONParser.read("false"); - assert(data.isValue()); - assertEquals( DataType.Boolean, data.getType()); - assertEquals( false, data.getBoolean()); - } - - @Test - public void valueBooleanUpperCase(){ - DataNode data = JSONParser.read("TRUE"); - assert(data.isValue()); - assertEquals( DataType.Boolean, data.getType()); - assertEquals( true, data.getBoolean()); - } - - @Test - public void valueStringNoQuotes(){ - DataNode data = JSONParser.read("teststring"); - assert(data.isValue()); - assertEquals( DataType.String, data.getType()); - assertEquals( "teststring", data.getString()); - } - - @Test - public void toManyCommasInList(){ - DataNode data = JSONParser.read("[1,2,3,]"); - assertEquals(DataType.List, data.getType()); - assertEquals( 1, data.get(0).getInt()); - assertEquals( 2, data.get(1).getInt()); - assertEquals( 3, data.get(2).getInt()); - } - - @Test - public void toManyCommasInMap(){ - DataNode data = JSONParser.read("{1:1,2:2,3:3,}"); - assertEquals(DataType.Map, data.getType()); - assertEquals( 1, data.get("1").getInt()); - assertEquals( 2, data.get("2").getInt()); - assertEquals( 3, data.get("3").getInt()); - } - - @Test - public void nullValueInList(){ - DataNode data = JSONParser.read("[1,null,3,]"); - assertEquals(DataType.List, data.getType()); - assertEquals(3, data.size()); - assertEquals( "1", data.get(0).getString()); - assertNull(data.get(1)); - assertEquals( "3", data.get(2).getString()); - } - - @Test - public void nullValueInMap(){ - DataNode data = JSONParser.read("{1:1,2:null,3:3,}"); - assertEquals(DataType.Map, data.getType()); - assertEquals(3, data.size()); - assertEquals( "1", data.getString("1")); - assertNull(data.get("2")); - assertEquals( "3", data.getString("3")); - } - - @Test - public void emptyStringInMap(){ - DataNode data = JSONParser.read("{1:{2:\"\"}}"); - assertEquals(DataType.Map, data.getType()); - assertEquals(1, data.size()); - assertEquals( "", data.get("1").getString("2")); - } - - - @Test - public void complexMap() { - String json = "{" + - "\"test1\": 1234," + - "\"TEST1\": 5678," + - "\"test3\": 1234.99," + - "\"test4\": \"91011\"," + - "\"test5\": [12,13,14,15]," + - "\"test6\": [\"a\",\"b\",\"c\",\"d\"]" + - "}"; - - DataNode data = JSONParser.read(json); - assert( data.isMap() ); - assert( 1234 == data.get("test1").getInt() ); - assert( 5678 == data.get("TEST1").getInt() ); - assert( 1234.99 == data.get("test3").getDouble() ); - assertEquals( "91011", data.get("test4").getString() ); - - assert( data.get("test5").isList() ); - assertEquals( 4, data.get("test5").size() ); - assertEquals( 12, data.get("test5").get(0).getInt() ); - assertEquals( 13, data.get("test5").get(1).getInt() ); - assertEquals( 14, data.get("test5").get(2).getInt() ); - assertEquals( 15, data.get("test5").get(3).getInt() ); - - assert( data.get("test6").isList() ); - assertEquals( 4, data.get("test6").size() ); - assertEquals( "a", data.get("test6").get(0).getString() ); - assertEquals( "b", data.get("test6").get(1).getString() ); - assertEquals( "c", data.get("test6").get(2).getString() ); - assertEquals( "d", data.get("test6").get(3).getString() ); - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.parser.json; + +import org.junit.Test; +import zutil.parser.DataNode; +import zutil.parser.DataNode.DataType; +import zutil.parser.json.JSONParser; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + + +public class JSONParserTest { + + @Test + public void nullString(){ + DataNode data = JSONParser.read(null); + assertNull(data); + } + + @Test + public void emptyString(){ + DataNode data = JSONParser.read(""); + assertNull(data); + } + + @Test + public void emptyMap(){ + DataNode data = JSONParser.read("{}"); + assertEquals(DataType.Map, data.getType()); + assertEquals( 0, data.size()); + } + + @Test + public void emptyList(){ + DataNode data = JSONParser.read("[]"); + assertEquals(DataType.List, data.getType()); + assertEquals( 0, data.size()); + } + + @Test + public void valueInt(){ + DataNode data = JSONParser.read("1234"); + assert(data.isValue()); + assertEquals( DataType.Number, data.getType()); + assertEquals( 1234, data.getInt()); + } + + @Test + public void valueDouble(){ + DataNode data = JSONParser.read("12.34"); + assert(data.isValue()); + assertEquals( DataType.Number, data.getType()); + assertEquals( 12.34, data.getDouble(), 0); + } + + @Test + public void valueBoolean(){ + DataNode data = JSONParser.read("false"); + assert(data.isValue()); + assertEquals( DataType.Boolean, data.getType()); + assertEquals( false, data.getBoolean()); + } + + @Test + public void valueBooleanUpperCase(){ + DataNode data = JSONParser.read("TRUE"); + assert(data.isValue()); + assertEquals( DataType.Boolean, data.getType()); + assertEquals( true, data.getBoolean()); + } + + @Test + public void valueStringNoQuotes(){ + DataNode data = JSONParser.read("teststring"); + assert(data.isValue()); + assertEquals( DataType.String, data.getType()); + assertEquals( "teststring", data.getString()); + } + + @Test + public void toManyCommasInList(){ + DataNode data = JSONParser.read("[1,2,3,]"); + assertEquals(DataType.List, data.getType()); + assertEquals( 1, data.get(0).getInt()); + assertEquals( 2, data.get(1).getInt()); + assertEquals( 3, data.get(2).getInt()); + } + + @Test + public void toManyCommasInMap(){ + DataNode data = JSONParser.read("{1:1,2:2,3:3,}"); + assertEquals(DataType.Map, data.getType()); + assertEquals( 1, data.get("1").getInt()); + assertEquals( 2, data.get("2").getInt()); + assertEquals( 3, data.get("3").getInt()); + } + + @Test + public void nullValueInList(){ + DataNode data = JSONParser.read("[1,null,3,]"); + assertEquals(DataType.List, data.getType()); + assertEquals(3, data.size()); + assertEquals( "1", data.get(0).getString()); + assertNull(data.get(1)); + assertEquals( "3", data.get(2).getString()); + } + + @Test + public void nullValueInMap(){ + DataNode data = JSONParser.read("{1:1,2:null,3:3,}"); + assertEquals(DataType.Map, data.getType()); + assertEquals(3, data.size()); + assertEquals( "1", data.getString("1")); + assertNull(data.get("2")); + assertEquals( "3", data.getString("3")); + } + + @Test + public void emptyStringInMap(){ + DataNode data = JSONParser.read("{1:{2:\"\"}}"); + assertEquals(DataType.Map, data.getType()); + assertEquals(1, data.size()); + assertEquals( "", data.get("1").getString("2")); + } + + + @Test + public void complexMap() { + String json = "{" + + "\"test1\": 1234," + + "\"TEST1\": 5678," + + "\"test3\": 1234.99," + + "\"test4\": \"91011\"," + + "\"test5\": [12,13,14,15]," + + "\"test6\": [\"a\",\"b\",\"c\",\"d\"]" + + "}"; + + DataNode data = JSONParser.read(json); + assert( data.isMap() ); + assert( 1234 == data.get("test1").getInt() ); + assert( 5678 == data.get("TEST1").getInt() ); + assert( 1234.99 == data.get("test3").getDouble() ); + assertEquals( "91011", data.get("test4").getString() ); + + assert( data.get("test5").isList() ); + assertEquals( 4, data.get("test5").size() ); + assertEquals( 12, data.get("test5").get(0).getInt() ); + assertEquals( 13, data.get("test5").get(1).getInt() ); + assertEquals( 14, data.get("test5").get(2).getInt() ); + assertEquals( 15, data.get("test5").get(3).getInt() ); + + assert( data.get("test6").isList() ); + assertEquals( 4, data.get("test6").size() ); + assertEquals( "a", data.get("test6").get(0).getString() ); + assertEquals( "b", data.get("test6").get(1).getString() ); + assertEquals( "c", data.get("test6").get(2).getString() ); + assertEquals( "d", data.get("test6").get(3).getString() ); + } +} diff --git a/test/zutil/test/JSONSerializerBenchmark.java b/test/zutil/parser/json/JSONSerializerBenchmark.java similarity index 95% rename from test/zutil/test/JSONSerializerBenchmark.java rename to test/zutil/parser/json/JSONSerializerBenchmark.java index 681f265..42810c7 100755 --- a/test/zutil/test/JSONSerializerBenchmark.java +++ b/test/zutil/parser/json/JSONSerializerBenchmark.java @@ -1,125 +1,126 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 com.carrotsearch.junitbenchmarks.BenchmarkRule; -import org.junit.Rule; -import org.junit.Test; -import zutil.test.JSONSerializerTest.TestClass; - -import java.io.*; - -import static org.junit.Assert.assertEquals; - -public class JSONSerializerBenchmark { - private static final int TEST_EXECUTIONS = 2000; - - @Rule - public BenchmarkRule benchmarkRun = new BenchmarkRule(); - - @Test - public void testJavaLegacySerialize() throws InterruptedException, IOException, ClassNotFoundException{ - for(int i=0; i T sendReceiveObject(T sourceObj) throws IOException{ - return readObjectFromJson( - writeObjectToJson(sourceObj)); - } - - @SuppressWarnings("unchecked") - public static T readObjectFromJson(String json) throws IOException{ - StringReader bin = new StringReader(json); - JSONObjectInputStream in = new JSONObjectInputStream(bin); - T targetObj = (T) in.readObject(); - in.close(); - - return targetObj; - } - - public static String writeObjectToJson(T sourceObj) throws IOException{ - return writeObjectToJson(sourceObj, true); - } - public static String writeObjectToJson(T sourceObj, boolean metadata) throws IOException{ - StringOutputStream bout = new StringOutputStream(); - JSONObjectOutputStream out = new JSONObjectOutputStream(bout); - out.enableMetaData(metadata); - - out.writeObject(sourceObj); - out.flush(); - out.close(); - - String data = bout.toString(); - System.out.println(data); - - return data; - } - - /******************** Test Classes ************************************/ - - public static class TestClass implements Serializable{ - private static final long serialVersionUID = 1L; - String str; - double decimal; - TestObj obj1; - TestObj obj2; - - public TestClass init(){ - this.str = "abcd"; - this.decimal = 1.1; - this.obj1 = new TestObj().init(); - this.obj2 = new TestObj().init(); - return this; - } - - public static void assertEquals(TestClass obj1, TestClass obj2){ - Assert.assertEquals(obj1.str, obj2.str); - Assert.assertEquals(obj1.decimal, obj2.decimal, 0.001); - Assert.assertEquals(obj1.obj1, obj2.obj1); - Assert.assertEquals(obj1.obj2, obj2.obj2); - } - } - - public static class TestClassObjClone{ - TestObj obj1; - TestObj obj2; - - public TestClassObjClone init(){ - this.obj1 = this.obj2 = new TestObj().init(); - return this; - } - - public boolean equals(Object obj){ - return obj instanceof TestClassObjClone && - this.obj1.equals(((TestClassObjClone)obj).obj1) && - this.obj1 == this.obj2 && - ((TestClassObjClone)obj).obj1 == ((TestClassObjClone)obj).obj2; - } - } - - public static class TestObj implements Serializable{ - private static final long serialVersionUID = 1L; - int value; - - public TestObj init(){ - this.value = 42; - return this; - } - - public boolean equals(Object obj){ - return obj instanceof TestObj && - this.value == ((TestObj)obj).value; - } - } - - public static class TestClassArray{ - private int[] array; - - public TestClassArray init(){ - array = new int[]{1,2,3,4}; - return this; - } - - public boolean equals(Object obj){ - return obj instanceof TestClassArray && - Arrays.equals(this.array ,((TestClassArray)obj).array); - } - } - - public static class TestClassStringArray{ - private String[] array; - - public TestClassStringArray init(){ - array = new String[]{"test","string","array"}; - return this; - } - - public boolean equals(Object obj){ - return obj instanceof TestClassStringArray && - Arrays.equals(this.array ,((TestClassStringArray)obj).array); - } - } - - public static class TestClassMap{ - private HashMap map; - - public TestClassMap init(){ - map = new HashMap<>(); - map.put("key1", "value1"); - map.put("key2", "value2"); - return this; - } - - public static void assertEquals(TestClassMap obj1, TestClassMap obj2){ - Assert.assertEquals(obj1.map, obj2.map); - } - } - - public static class TestClassList{ - private ArrayList list; - - public TestClassList init(){ - list = new ArrayList<>(); - list.add("value1"); - list.add("value2"); - return this; - } - - public static void assertEquals(TestClassList obj1, TestClassList obj2){ - Assert.assertEquals(obj1.list, obj2.list); - } - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.parser.json; + +import org.junit.Assert; +import org.junit.Test; +import zutil.io.StringOutputStream; + +import java.io.IOException; +import java.io.Serializable; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + + +public class JSONSerializerTest{ + + @Test + public void testOutputSerializerWithPrimitives() throws InterruptedException, IOException, ClassNotFoundException{ + TestClass sourceObj = new TestClass().init(); + + String data = writeObjectToJson(sourceObj); + data = data.replace("\"", "'"); + + assertThat(data, containsString("'str': 'abcd'")); + assertThat(data, containsString("'value': 42")); + assertThat(data, containsString("'decimal': 1.1")); + } + + @Test + public void testInputSerializerWithPrimitives() throws InterruptedException, IOException, ClassNotFoundException{ + TestClass sourceObj = new TestClass().init(); + + TestClass targetObj = sendReceiveObject(sourceObj); + + TestClass.assertEquals(sourceObj, targetObj); + } + + @Test + public void testOutputSerializerWithClones() throws InterruptedException, IOException, ClassNotFoundException{ + TestClassObjClone sourceObj = new TestClassObjClone().init(); + + String data = writeObjectToJson(sourceObj); + data = data.replace("\"", "'"); + + assertThat(data, containsString("'@class': 'zutil.test.JSONSerializerTest$TestClassObjClone'")); + assertThat(data, containsString("'obj1': {'@class': 'zutil.test.JSONSerializerTest$TestObj', '@object_id': 2, 'value': 42}")); + assertThat(data, containsString("'obj2': {'@object_id': 2}")); + } + + @Test + public void testInputSerializerWithClones() throws InterruptedException, IOException, ClassNotFoundException{ + TestClassObjClone sourceObj = new TestClassObjClone().init(); + + TestClassObjClone targetObj = sendReceiveObject(sourceObj); + + assertEquals( sourceObj, targetObj ); + } + + @Test + public void testOutputSerializerWithArrays() throws InterruptedException, IOException, ClassNotFoundException{ + TestClassArray sourceObj = new TestClassArray().init(); + + String data = writeObjectToJson(sourceObj); + data = data.replace("\"", "'"); + + assertEquals( + "{'@class': 'zutil.test.JSONSerializerTest$TestClassArray', 'array': [1, 2, 3, 4], '@object_id': 1}\n", + data); + } + + @Test + public void testInputSerializerWithArrays() throws InterruptedException, IOException, ClassNotFoundException{ + TestClassArray sourceObj = new TestClassArray().init(); + + TestClassArray targetObj = sendReceiveObject(sourceObj); + assertEquals( sourceObj, targetObj ); + } + + @Test + public void testInputSerializerWithStringArrays() throws InterruptedException, IOException, ClassNotFoundException{ + TestClassStringArray sourceObj = new TestClassStringArray().init(); + + TestClassStringArray targetObj = sendReceiveObject(sourceObj); + assertEquals( sourceObj, targetObj ); + } + + @Test + public void testSerializerWithNullFieldsHidden() throws InterruptedException, IOException, ClassNotFoundException{ + TestClass sourceObj = new TestClass(); + + String data = writeObjectToJson(sourceObj, false); + data = data.replace("\"", "'"); + assertEquals( + "{'decimal': 0.0}\n", + data); + + TestClass targetObj = sendReceiveObject(sourceObj); + TestClass.assertEquals(sourceObj, targetObj); + } + + @Test + public void testSerializerWithMapField() throws InterruptedException, IOException, ClassNotFoundException{ + TestClassMap sourceObj = new TestClassMap().init(); + + TestClassMap targetObj = sendReceiveObject(sourceObj); + TestClassMap.assertEquals(sourceObj, targetObj); + } + + @Test + public void testSerializerWithMapFieldWithNullEntry() throws InterruptedException, IOException, ClassNotFoundException{ + TestClassMap sourceObj = new TestClassMap().init(); + sourceObj.map.put("key1", null); + + TestClassMap targetObj = sendReceiveObject(sourceObj); + sourceObj.map.remove("key1"); // key1 should not be set in destination + TestClassMap.assertEquals(sourceObj, targetObj); + } + + @Test + public void testSerializerWithListField() throws InterruptedException, IOException, ClassNotFoundException{ + TestClassList sourceObj = new TestClassList().init(); + + String data = writeObjectToJson(sourceObj); + data = data.replace("\"", "'"); + assertThat(data, containsString("'list': ['value1', 'value2']")); + + TestClassList targetObj = sendReceiveObject(sourceObj); + TestClassList.assertEquals(sourceObj, targetObj); + } + + /******************* Utility Functions ************************************/ + + public static T sendReceiveObject(T sourceObj) throws IOException{ + return readObjectFromJson( + writeObjectToJson(sourceObj)); + } + + @SuppressWarnings("unchecked") + public static T readObjectFromJson(String json) throws IOException{ + StringReader bin = new StringReader(json); + JSONObjectInputStream in = new JSONObjectInputStream(bin); + T targetObj = (T) in.readObject(); + in.close(); + + return targetObj; + } + + public static String writeObjectToJson(T sourceObj) throws IOException{ + return writeObjectToJson(sourceObj, true); + } + public static String writeObjectToJson(T sourceObj, boolean metadata) throws IOException{ + StringOutputStream bout = new StringOutputStream(); + JSONObjectOutputStream out = new JSONObjectOutputStream(bout); + out.enableMetaData(metadata); + + out.writeObject(sourceObj); + out.flush(); + out.close(); + + String data = bout.toString(); + System.out.println(data); + + return data; + } + + /******************** Test Classes ************************************/ + + public static class TestClass implements Serializable{ + private static final long serialVersionUID = 1L; + String str; + double decimal; + TestObj obj1; + TestObj obj2; + + public TestClass init(){ + this.str = "abcd"; + this.decimal = 1.1; + this.obj1 = new TestObj().init(); + this.obj2 = new TestObj().init(); + return this; + } + + public static void assertEquals(TestClass obj1, TestClass obj2){ + Assert.assertEquals(obj1.str, obj2.str); + Assert.assertEquals(obj1.decimal, obj2.decimal, 0.001); + Assert.assertEquals(obj1.obj1, obj2.obj1); + Assert.assertEquals(obj1.obj2, obj2.obj2); + } + } + + public static class TestClassObjClone{ + TestObj obj1; + TestObj obj2; + + public TestClassObjClone init(){ + this.obj1 = this.obj2 = new TestObj().init(); + return this; + } + + public boolean equals(Object obj){ + return obj instanceof TestClassObjClone && + this.obj1.equals(((TestClassObjClone)obj).obj1) && + this.obj1 == this.obj2 && + ((TestClassObjClone)obj).obj1 == ((TestClassObjClone)obj).obj2; + } + } + + public static class TestObj implements Serializable{ + private static final long serialVersionUID = 1L; + int value; + + public TestObj init(){ + this.value = 42; + return this; + } + + public boolean equals(Object obj){ + return obj instanceof TestObj && + this.value == ((TestObj)obj).value; + } + } + + public static class TestClassArray{ + private int[] array; + + public TestClassArray init(){ + array = new int[]{1,2,3,4}; + return this; + } + + public boolean equals(Object obj){ + return obj instanceof TestClassArray && + Arrays.equals(this.array ,((TestClassArray)obj).array); + } + } + + public static class TestClassStringArray{ + private String[] array; + + public TestClassStringArray init(){ + array = new String[]{"test","string","array"}; + return this; + } + + public boolean equals(Object obj){ + return obj instanceof TestClassStringArray && + Arrays.equals(this.array ,((TestClassStringArray)obj).array); + } + } + + public static class TestClassMap{ + private HashMap map; + + public TestClassMap init(){ + map = new HashMap<>(); + map.put("key1", "value1"); + map.put("key2", "value2"); + return this; + } + + public static void assertEquals(TestClassMap obj1, TestClassMap obj2){ + Assert.assertEquals(obj1.map, obj2.map); + } + } + + public static class TestClassList{ + private ArrayList list; + + public TestClassList init(){ + list = new ArrayList<>(); + list.add("value1"); + list.add("value2"); + return this; + } + + public static void assertEquals(TestClassList obj1, TestClassList obj2){ + Assert.assertEquals(obj1.list, obj2.list); + } + } +} diff --git a/test/zutil/test/BloomFilterTest.java b/test/zutil/struct/BloomFilterTest.java similarity index 95% rename from test/zutil/test/BloomFilterTest.java rename to test/zutil/struct/BloomFilterTest.java index 1886544..2dfa9fb 100755 --- a/test/zutil/test/BloomFilterTest.java +++ b/test/zutil/struct/BloomFilterTest.java @@ -1,87 +1,87 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 junit.framework.TestCase; -import zutil.struct.BloomFilter; - -import java.text.DecimalFormat; -import java.util.HashSet; -import java.util.Random; - -/** - * This code may be used, modified, and redistributed provided that the - * author tag below remains intact. - * - * @author Ian Clarke - */ - -public class BloomFilterTest extends TestCase { - public void testBloomFilter() { - DecimalFormat df = new DecimalFormat("0.00000"); - Random r = new Random(124445l); - int bfSize = 400000; - System.out.println("Testing " + bfSize + " bit SimpleBloomFilter"); - for (int i = 5; i < 10; i++) { - int addCount = 10000 * (i + 1); - BloomFilter bf = new BloomFilter(bfSize, addCount); - HashSet added = new HashSet(); - for (int x = 0; x < addCount; x++) { - int num = r.nextInt(); - added.add(num); - } - bf.addAll(added); - assertTrue("Assert that there are no false negatives", bf - .containsAll(added)); - - int falsePositives = 0; - for (int x = 0; x < addCount; x++) { - int num = r.nextInt(); - - // Ensure that this random number hasn't been added already - if (added.contains(num)) { - continue; - } - - // If necessary, record a false positive - if (bf.contains(num)) { - falsePositives++; - } - } - double expectedFP = bf.falsePosetiveProbability(); - double actualFP = (double) falsePositives / (double) addCount; - System.out.println("Got " + falsePositives - + " false positives out of " + addCount + " added items, rate = " - + df.format(actualFP) + ", expected = " - + df.format(expectedFP)); - double ratio = actualFP/expectedFP; - assertTrue( - "Assert that the actual false positive rate doesn't deviate by more than 10% from what was predicted, ratio: "+ratio, - ratio < 1.1); - } - } - - -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.struct; + +import junit.framework.TestCase; + +import java.text.DecimalFormat; +import java.util.HashSet; +import java.util.Random; + + +/** + * This code may be used, modified, and redistributed provided that the + * author tag below remains intact. + * + * @author Ian Clarke + */ + +public class BloomFilterTest extends TestCase { + public void testBloomFilter() { + DecimalFormat df = new DecimalFormat("0.00000"); + Random r = new Random(124445l); + int bfSize = 400000; + System.out.println("Testing " + bfSize + " bit SimpleBloomFilter"); + for (int i = 5; i < 10; i++) { + int addCount = 10000 * (i + 1); + BloomFilter bf = new BloomFilter(bfSize, addCount); + HashSet added = new HashSet(); + for (int x = 0; x < addCount; x++) { + int num = r.nextInt(); + added.add(num); + } + bf.addAll(added); + assertTrue("Assert that there are no false negatives", bf + .containsAll(added)); + + int falsePositives = 0; + for (int x = 0; x < addCount; x++) { + int num = r.nextInt(); + + // Ensure that this random number hasn't been added already + if (added.contains(num)) { + continue; + } + + // If necessary, record a false positive + if (bf.contains(num)) { + falsePositives++; + } + } + double expectedFP = bf.falsePosetiveProbability(); + double actualFP = (double) falsePositives / (double) addCount; + System.out.println("Got " + falsePositives + + " false positives out of " + addCount + " added items, rate = " + + df.format(actualFP) + ", expected = " + + df.format(expectedFP)); + double ratio = actualFP/expectedFP; + assertTrue( + "Assert that the actual false positive rate doesn't deviate by more than 10% from what was predicted, ratio: "+ratio, + ratio < 1.1); + } + } + + +} diff --git a/test/zutil/test/CircularBufferTest.java b/test/zutil/struct/CircularBufferTest.java similarity index 95% rename from test/zutil/test/CircularBufferTest.java rename to test/zutil/struct/CircularBufferTest.java index 871d515..d32ff14 100755 --- a/test/zutil/test/CircularBufferTest.java +++ b/test/zutil/struct/CircularBufferTest.java @@ -1,119 +1,119 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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.struct.CircularBuffer; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * Created by Ziver on 2015-09-22. - */ -public class CircularBufferTest { - - @Test - public void addToEmpty() { - CircularBuffer buff = new CircularBuffer(0); - try { - buff.add(10); - fail("IndexOutOfBoundsException was not thrown"); - } catch (IndexOutOfBoundsException e) {} - } - - @Test - public void addOneElement() { - CircularBuffer buff = new CircularBuffer(1); - assertEquals(0, buff.size()); - buff.add(10); - assertEquals(1, buff.size()); - assertEquals((Integer) 10, buff.get(0)); - } - - @Test - public void addThreeElements() { - CircularBuffer buff = new CircularBuffer(10); - buff.add(10); - buff.add(11); - buff.add(12); - assertEquals(3, buff.size()); - assertEquals((Integer) 12, buff.get(0)); - assertEquals((Integer) 11, buff.get(1)); - assertEquals((Integer) 10, buff.get(2)); - } - - @Test - public void addOutOfRange() { - CircularBuffer buff = new CircularBuffer(2); - buff.add(10); - buff.add(11); - buff.add(12); - assertEquals(2, buff.size()); - assertEquals((Integer) 12, buff.get(0)); - assertEquals((Integer) 11, buff.get(1)); - try { - buff.get(2); - fail("IndexOutOfBoundsException was not thrown"); - } catch (IndexOutOfBoundsException e) {} - } - - @Test - public void iteratorEmpty() { - CircularBuffer buff = new CircularBuffer(10); - Iterator it = buff.iterator(); - - assert (!it.hasNext()); - try { - it.next(); - fail("NoSuchElementException was not thrown"); - } catch (NoSuchElementException e) {} - } - - @Test - public void iteratorThreeElements() { - CircularBuffer buff = new CircularBuffer(10); - buff.add(10); - buff.add(11); - buff.add(12); - - Iterator it = buff.iterator(); - assert (it.hasNext()); - assertEquals((Integer) 12, it.next()); - assert (it.hasNext()); - assertEquals((Integer) 11, it.next()); - assert (it.hasNext()); - assertEquals((Integer) 10, it.next()); - assert (!it.hasNext()); - - try { - it.next(); - fail("NoSuchElementException was not thrown"); - } catch (NoSuchElementException e) {} - } -} +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ziver Koc + * + * 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.struct; + +import org.junit.Test; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + + +/** + * Created by Ziver on 2015-09-22. + */ +public class CircularBufferTest { + + @Test + public void addToEmpty() { + CircularBuffer buff = new CircularBuffer(0); + try { + buff.add(10); + fail("IndexOutOfBoundsException was not thrown"); + } catch (IndexOutOfBoundsException e) {} + } + + @Test + public void addOneElement() { + CircularBuffer buff = new CircularBuffer(1); + assertEquals(0, buff.size()); + buff.add(10); + assertEquals(1, buff.size()); + assertEquals((Integer) 10, buff.get(0)); + } + + @Test + public void addThreeElements() { + CircularBuffer buff = new CircularBuffer(10); + buff.add(10); + buff.add(11); + buff.add(12); + assertEquals(3, buff.size()); + assertEquals((Integer) 12, buff.get(0)); + assertEquals((Integer) 11, buff.get(1)); + assertEquals((Integer) 10, buff.get(2)); + } + + @Test + public void addOutOfRange() { + CircularBuffer buff = new CircularBuffer(2); + buff.add(10); + buff.add(11); + buff.add(12); + assertEquals(2, buff.size()); + assertEquals((Integer) 12, buff.get(0)); + assertEquals((Integer) 11, buff.get(1)); + try { + buff.get(2); + fail("IndexOutOfBoundsException was not thrown"); + } catch (IndexOutOfBoundsException e) {} + } + + @Test + public void iteratorEmpty() { + CircularBuffer buff = new CircularBuffer(10); + Iterator it = buff.iterator(); + + assert (!it.hasNext()); + try { + it.next(); + fail("NoSuchElementException was not thrown"); + } catch (NoSuchElementException e) {} + } + + @Test + public void iteratorThreeElements() { + CircularBuffer buff = new CircularBuffer(10); + buff.add(10); + buff.add(11); + buff.add(12); + + Iterator it = buff.iterator(); + assert (it.hasNext()); + assertEquals((Integer) 12, it.next()); + assert (it.hasNext()); + assertEquals((Integer) 11, it.next()); + assert (it.hasNext()); + assertEquals((Integer) 10, it.next()); + assert (!it.hasNext()); + + try { + it.next(); + fail("NoSuchElementException was not thrown"); + } catch (NoSuchElementException e) {} + } +} diff --git a/test/zutil/test/TimedHashSetTest.java b/test/zutil/struct/TimedHashSetTest.java similarity index 97% rename from test/zutil/test/TimedHashSetTest.java rename to test/zutil/struct/TimedHashSetTest.java index ecdd143..d92daf9 100755 --- a/test/zutil/test/TimedHashSetTest.java +++ b/test/zutil/struct/TimedHashSetTest.java @@ -22,13 +22,13 @@ * THE SOFTWARE. */ -package zutil.test; +package zutil.struct; import org.junit.Test; -import zutil.struct.TimedHashSet; import static org.junit.Assert.assertFalse; + /** * Created by Ziver on 2015-11-20. */ diff --git a/test/zutil/test/FileFinderHasherTest.java b/test/zutil/test/FileFinderHasherTest.java deleted file mode 100755 index 0f24056..0000000 --- a/test/zutil/test/FileFinderHasherTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2015 Ziver Koc - * - * 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 zutil.Hasher; -import zutil.io.file.FileUtil; - -import java.io.File; -import java.net.URISyntaxException; -import java.util.List; - -public class FileFinderHasherTest { - public static void main(String[] args) throws URISyntaxException{ - String relativePath = "zutil/test"; - - File path = FileUtil.find(relativePath); - List files = FileUtil.search(path); - for(int i=0; i