diff --git a/src/zutil/ArrayUtil.java b/src/zutil/ArrayUtil.java index 146bdf0..681c233 100755 --- a/src/zutil/ArrayUtil.java +++ b/src/zutil/ArrayUtil.java @@ -34,7 +34,7 @@ public class ArrayUtil { /** * Converts a List with Integer objects to a primary type int array */ - public static int[] toIntArray(List list){ + public static int[] toIntArray(List list) { if (list == null) return null; int[] arr = new int[list.size()]; diff --git a/src/zutil/ByteUtil.java b/src/zutil/ByteUtil.java index 36d535c..2090006 100755 --- a/src/zutil/ByteUtil.java +++ b/src/zutil/ByteUtil.java @@ -53,7 +53,7 @@ public class ByteUtil { * @param length is the length of bits to return, valid values 1-8 * @return a new byte containing a sub byte defined by the index and length */ - public static byte getBits(byte data, int index, int length){ + public static byte getBits(byte data, int index, int length) { return (byte) (data & getBitMask(index, length)); } @@ -65,7 +65,7 @@ public class ByteUtil { * @param length is the length of bits to return, valid values 1-8 * @return a new byte containing a sub byte defined by the index and length */ - public static byte getShiftedBits(byte data, int index, int length){ + public static byte getShiftedBits(byte data, int index, int length) { int ret = 0xFF & getBits(data, index, length); ret = ret >>> index+1-length; return (byte) ret; @@ -78,7 +78,7 @@ public class ByteUtil { * @param length is the length of bits to return, valid values 1-8 * @return a new byte containing a sub byte defined by the index and length */ - public static byte getBits(byte data, int length){ + public static byte getBits(byte data, int length) { return getBits(data, length-1, length); } @@ -89,10 +89,10 @@ public class ByteUtil { * @param length is the length of bits to return * @return a new byte array of te given length containing the given data. */ - public static byte[] getBits(byte[] data, int length){ + public static byte[] getBits(byte[] data, int length) { byte[] dest = new byte[(int) Math.ceil(length/8.0)]; System.arraycopy(data, 0, dest, 0, Math.min(data.length, dest.length)); - if(length % 8 != 0) + if (length % 8 != 0) dest[dest.length-1] = getBits(dest[dest.length-1], length % 8); return dest; } @@ -104,7 +104,7 @@ public class ByteUtil { * @param length is the length of bits to return, valid values 1-8 * @return a new byte containing a sub byte defined by the index and length */ - public static byte getBitsMSB(byte data, int length){ + public static byte getBitsMSB(byte data, int length) { return getShiftedBits(data, 7, length); } @@ -115,7 +115,7 @@ public class ByteUtil { * @param data is the byte array that will be reversed. * @return a new byte array that will have the same data but in reverse byte order */ - public static byte[] getReverseByteOrder(byte[] data){ + public static byte[] getReverseByteOrder(byte[] data) { byte[] dest = new byte[data.length]; if (data.length > 0) for (int i=0; i index || index > 7) + if (0 > index || index > 7) throw new IllegalArgumentException("Invalid index argument, allowed values: 0-7"); - if(length < 0 || index-length < 0) - throw new IllegalArgumentException("Invalid length argument: "+length+", allowed values: 1 to "+(index+1)+" for index "+index); + if (length < 0 || index-length < 0) + throw new IllegalArgumentException("Invalid length argument: " + length + ", allowed values: 1 to " + (index+1) + " for index " + index); return (byte) BYTE_MASK[index][length]; } @@ -147,16 +147,16 @@ public class ByteUtil { * @return same data reference as the data input */ public static byte[] shiftLeft(byte[] data, int shiftBy) { - if(0 > shiftBy || shiftBy > 8) - throw new IllegalArgumentException("Invalid shiftBy("+shiftBy+") argument, allowed values: 0-8"); + if (0 > shiftBy || shiftBy > 8) + throw new IllegalArgumentException("Invalid shiftBy(" + shiftBy + ") argument, allowed values: 0-8"); if (shiftBy == 0) return data; byte rest; - for (int i=0; i>> shiftBy); - if(i != 0) + if (i != 0) data[i-1] |= rest; } @@ -171,16 +171,16 @@ public class ByteUtil { * @return same data reference as the data input */ public static byte[] shiftRight(byte[] data, int shiftBy) { - if(0 > shiftBy || shiftBy > 8) - throw new IllegalArgumentException("Invalid shiftBy("+shiftBy+") argument, allowed values: 0-8"); + if (0 > shiftBy || shiftBy > 8) + throw new IllegalArgumentException("Invalid shiftBy(" + shiftBy + ") argument, allowed values: 0-8"); if (shiftBy == 0) return data; byte rest = 0; - for (int i=0; i type){ + public static boolean isWrapper(Class type) { return wrappers.contains(type); } /** * @return if the given class is a primitive including String */ - public static boolean isPrimitive(Class type){ + public static boolean isPrimitive(Class type) { return primitives.contains(type); } @@ -86,7 +86,7 @@ public class ClassUtil { * @return true if the given class is a type representing a number without any decimals. * E.g. long, int, short, char, byte and corresponding wrapper. */ - public static boolean isNumber(Class type){ + public static boolean isNumber(Class type) { return Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type) || Integer.class.isAssignableFrom(type) || @@ -103,7 +103,7 @@ public class ClassUtil { * @return true if the given class is a type representing a number with decimals. * E.g. double, float and corresponding wrapper. */ - public static boolean isDecimal(Class type){ + public static boolean isDecimal(Class type) { return Double.class.isAssignableFrom(type) || double.class.isAssignableFrom(type) || Float.class.isAssignableFrom(type) || @@ -113,8 +113,8 @@ public class ClassUtil { /** * @return a bool value depending on if the given class is available in the classpath */ - public boolean isAvailable(String clazz){ - try{ + public boolean isAvailable(String clazz) { + try { Class.forName(clazz); return true; } catch (ClassNotFoundException e) { @@ -127,7 +127,7 @@ public class ClassUtil { * @param field is the field to fetch the generics classes from. * @return the generics class assigned to the specific field or a empty list if there are no generics. */ - public static Class[] getGenericClasses(Field field){ + public static Class[] getGenericClasses(Field field) { return getGenericClasses(field.getGenericType()); } @@ -148,8 +148,8 @@ public class ClassUtil { * @return the generics for a specific super class or a empty list if * there is no generics or the super class is not found */ - public static Class[] getGenericClasses(Class c, Class superClass){ - if(superClass != null) { + public static Class[] getGenericClasses(Class c, Class superClass) { + if (superClass != null) { // Search for the super class while (c.getSuperclass() != null && c.getSuperclass() != Object.class) { // Did we find the super class? @@ -160,13 +160,13 @@ public class ClassUtil { } return new Class[0]; } - private static Class[] getGenericClasses(Type genericType){ - if(genericType instanceof ParameterizedType){ + private static Class[] getGenericClasses(Type genericType) { + if (genericType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericType; Type[] argTypes = aType.getActualTypeArguments(); Class[] classArray = new Class[argTypes.length]; - for(int i=0; i) argTypes[i]; } return classArray; @@ -178,16 +178,16 @@ public class ClassUtil { /** * @return the first class in the stack that do not match the filter */ - public static String getCallingClass(Class... filter){ + public static String getCallingClass(Class... filter) { ArrayList filterStr = new ArrayList(filter.length + 1); filterStr.add(ClassUtil.class.getName()); for (Class clazz : filter) filterStr.add(clazz.getName()); StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); - for(int i=1; i, Iterable{ /** * A Constructor that takes a String containing 5 (or 6 for extended) individual fields in Cron format */ - public CronTimer(String cron){ + public CronTimer(String cron) { String[] arr = cron.split("\\s"); if (arr.length < 5 || arr.length > 6) throw new IllegalArgumentException( - "String must contain between 5-6 fields, but got("+arr.length+" fields): "+cron); + "String must contain between 5-6 fields, but got(" + arr.length + " fields): " + cron); init(arr[0], arr[1], arr[2], arr[3], arr[4], (arr.length>5 ? arr[5]: "*")); } /** * A Constructor that takes separate Strings for each field */ - public CronTimer(String minute, String hour, String dayOfMonth, String monthOfYear, String dayOfWeek){ + public CronTimer(String minute, String hour, String dayOfMonth, String monthOfYear, String dayOfWeek) { this(minute, hour, dayOfMonth, monthOfYear, dayOfWeek, "*"); } /** * A Constructor that takes separate Strings for each field with an extended year field */ - public CronTimer(String minute, String hour, String dayOfMonth, String monthOfYear, String dayOfWeek, String year){ + public CronTimer(String minute, String hour, String dayOfMonth, String monthOfYear, String dayOfWeek, String year) { init(minute, hour, dayOfMonth, monthOfYear, dayOfWeek, year); } - private void init(String minute, String hour, String dayOfMonth, String monthOfYear, String dayOfWeek, String year){ + private void init(String minute, String hour, String dayOfMonth, String monthOfYear, String dayOfWeek, String year) { minutes = ArrayUtil.toIntArray(getRange(minute, 0, 59)); hours = ArrayUtil.toIntArray(getRange(hour, 0, 23)); dayOfMonths = ArrayUtil.toIntArray(getRange(dayOfMonth, 1, 31)); @@ -105,14 +105,14 @@ public class CronTimer implements Iterator, Iterable{ 1970, Calendar.getInstance().get(Calendar.YEAR)+30)); } - protected static List getRange(String str, int from, int to){ + protected static List getRange(String str, int from, int to) { if (str == null || str.isEmpty()) return Collections.emptyList(); List list = new LinkedList<>(); String[] commaArr = str.split(","); - if (commaArr.length > 1){ + if (commaArr.length > 1) { for (String section : commaArr) list.addAll(getRange(section, from, to)); } @@ -128,20 +128,20 @@ public class CronTimer implements Iterator, Iterable{ else { String[] rangeArr; if (str.equals("*")) - rangeArr = new String[]{""+from, ""+to}; + rangeArr = new String[]{"" +from, "" +to}; else rangeArr = str.split("-", 2); if (rangeArr.length == 2) { int rangeFrom = Integer.parseInt(rangeArr[0]); int rangeTo = Integer.parseInt(rangeArr[1]); if (from > rangeFrom || rangeTo > to) - throw new IllegalArgumentException("Invalid range "+rangeFrom+"-"+rangeTo+" must be between: "+from+"-"+to); + throw new IllegalArgumentException("Invalid range " + rangeFrom + "-" + rangeTo + " must be between: " + from + "-" + to); for (int i = rangeFrom; i <= rangeTo; ++i) list.add(i); } else { int value = Integer.parseInt(str); if (from > value || value > to) - throw new IllegalArgumentException("Valid values are between "+from+"-"+to+" but got: "+value); + throw new IllegalArgumentException("Valid values are between " + from + "-" + to + " but got: " + value); list.add(value); } } @@ -153,7 +153,7 @@ public class CronTimer implements Iterator, Iterable{ /** * Set the TimeZone that should be used by the cron algorithm */ - public void setTimeZone(TimeZone timeZone){ + public void setTimeZone(TimeZone timeZone) { this.timeZone = timeZone; } @@ -279,7 +279,7 @@ public class CronTimer implements Iterator, Iterable{ return cal.getTimeInMillis(); } - protected Calendar getCalendar(long timestamp){ + protected Calendar getCalendar(long timestamp) { Calendar cal = Calendar.getInstance(); if (timeZone != null) cal.setTimeZone(timeZone); @@ -290,8 +290,8 @@ public class CronTimer implements Iterator, Iterable{ /** * Converts Calendar DAY_OF_WEEK enum to id starting from 1 (Monday) to 7 (Sunday) */ - private int getDayOfWeekID(int calDayOfWeek){ - switch (calDayOfWeek){ + private int getDayOfWeekID(int calDayOfWeek) { + switch (calDayOfWeek) { case Calendar.MONDAY: return 1; case Calendar.TUESDAY: return 2; case Calendar.WEDNESDAY: return 3; @@ -302,8 +302,8 @@ public class CronTimer implements Iterator, Iterable{ } return -1; } - private int getDayOfWeekEnum(int dayId){ - switch (dayId){ + private int getDayOfWeekEnum(int dayId) { + switch (dayId) { case 1: return Calendar.MONDAY; case 2: return Calendar.TUESDAY; case 3: return Calendar.WEDNESDAY; diff --git a/src/zutil/Encrypter.java b/src/zutil/Encrypter.java index 492d192..7dbf6a2 100644 --- a/src/zutil/Encrypter.java +++ b/src/zutil/Encrypter.java @@ -137,7 +137,7 @@ public class Encrypter { public Encrypter(String stringKey, Digest digest, Algorithm crypto, int iteration, int keyBitSize) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException { // Generate the secret key specs. - String instance = "PBKDF2With"+ digest; + String instance = "PBKDF2With" + digest; SecretKeyFactory factory = SecretKeyFactory.getInstance(instance); KeySpec keySpec = new PBEKeySpec(stringKey.toCharArray(), salt, iteration, keyBitSize); SecretKey tmp = factory.generateSecret(keySpec); @@ -157,7 +157,7 @@ public class Encrypter { * @param data is the data to encrypt * @return The encrypted data */ - public byte[] encrypt(byte[] data){ + public byte[] encrypt(byte[] data) { try { byte[] encryption = new byte[encipher.getOutputSize(data.length)]; @@ -186,7 +186,7 @@ public class Encrypter { * @param encrypted is the encrypted data * @return The decrypted data */ - public byte[] decrypt(byte[] encrypted){ + public byte[] decrypt(byte[] encrypted) { try { byte[] dataTmp = new byte[encrypted.length]; int ptLength = decipher.update(encrypted, 0, encrypted.length, dataTmp, 0); @@ -215,21 +215,21 @@ public class Encrypter { /** * @return The key for this encrypter */ - public Key getKey(){ + public Key getKey() { return key; } /** * @return the algorithm used by this encrypter */ - public String getAlgorithm(){ + public String getAlgorithm() { return key.getAlgorithm(); } /** * Randomizes the salt for the key */ - public static void randomizeSalt(){ + public static void randomizeSalt() { Random random = new Random(); random.nextBytes(salt); } diff --git a/src/zutil/Hasher.java b/src/zutil/Hasher.java index 699abd2..7f61daf 100755 --- a/src/zutil/Hasher.java +++ b/src/zutil/Hasher.java @@ -51,7 +51,7 @@ public class Hasher { byte[] buffer = new byte[8192]; int read; try { - while( (read = is.read(buffer)) > 0) { + while ((read = is.read(buffer)) > 0) { digest.update(buffer, 0, read); } byte[] md5sum = digest.digest(); @@ -59,7 +59,7 @@ public class Hasher { output = bigInt.toString(16); } catch(IOException e) { - throw new RuntimeException("Unable to process file for "+hashType+" hash", e); + throw new RuntimeException("Unable to process file for " + hashType + " hash", e); } is.close(); @@ -72,7 +72,7 @@ public class Hasher { * @param str is the String to hash * @return an String containing the hash */ - public static String MD5(String str){ + public static String MD5(String str) { try { return hash(str, "MD5"); } catch (Exception e) { @@ -87,7 +87,7 @@ public class Hasher { * @param object is the object to hash * @return an String containing the hash */ - public static String MD5(Serializable object){ + public static String MD5(Serializable object) { try { return hash(object, "MD5"); } catch (Exception e) { @@ -118,7 +118,7 @@ public class Hasher { * @param str is the String to hash * @return an String containing the hash */ - public static String SHA1(String str){ + public static String SHA1(String str) { try { return hash(str, "SHA-1"); } catch (Exception e) { @@ -133,7 +133,7 @@ public class Hasher { * @param object is the object to hash * @return an String containing the hash */ - public static String SHA1(Serializable object){ + public static String SHA1(Serializable object) { try { return hash(object, "SHA-1"); } catch (Exception e) { @@ -149,7 +149,7 @@ public class Hasher { * @param key is the key to use with the hash * @return an String containing the hash */ - public static String HMAC_SHA256(String str, String key){ + public static String HMAC_SHA256(String str, String key) { return HMAC("HmacSHA256", str.getBytes(), key.getBytes()); } @@ -161,7 +161,7 @@ public class Hasher { * @param key is the key to use with the hash * @return an String containing the hash */ - public static String HMAC(String algo, byte[] data, byte[] key){ + public static String HMAC(String algo, byte[] data, byte[] key) { try { // Get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key, algo); @@ -171,7 +171,7 @@ public class Hasher { mac.init(signingKey); // Compute the HMAC on input data bytes - byte[] raw = mac.doFinal( data ); + byte[] raw = mac.doFinal(data); return Converter.toHexString(raw); } catch (Exception e) { @@ -180,7 +180,7 @@ public class Hasher { return null; } - public static String PBKDF2(String data, String salt, int iterations){ + public static String PBKDF2(String data, String salt, int iterations) { try { PBEKeySpec spec = new PBEKeySpec( data.toCharArray(), @@ -254,7 +254,7 @@ public class Hasher { int h = seed ^ length; int i=0; - for(; i+4 getLocalInet4Address(){ + public static List getLocalInet4Address() { ArrayList ips = new ArrayList<>(); try { Enumeration netIntf = NetworkInterface.getNetworkInterfaces(); - while(netIntf.hasMoreElements()){ + while (netIntf.hasMoreElements()) { Enumeration addresses = netIntf.nextElement().getInetAddresses(); - while (addresses.hasMoreElements()){ + while (addresses.hasMoreElements()) { InetAddress ip = addresses.nextElement(); if (ip instanceof Inet4Address && ip.isSiteLocalAddress()) ips.add(ip); diff --git a/src/zutil/MimeTypeUtil.java b/src/zutil/MimeTypeUtil.java index ef5cac5..2836783 100644 --- a/src/zutil/MimeTypeUtil.java +++ b/src/zutil/MimeTypeUtil.java @@ -53,10 +53,10 @@ public class MimeTypeUtil { private static void readMimeFile(String path) throws IOException { DataNode json = JSONParser.read(FileUtil.getContent(path)); - for (Iterator it = json.keyIterator(); it.hasNext(); ) { + for (Iterator it = json.keyIterator(); it.hasNext();) { String primaryType = it.next(); - for (Iterator it2 = json.get(primaryType).keyIterator(); it2.hasNext(); ) { + for (Iterator it2 = json.get(primaryType).keyIterator(); it2.hasNext();) { String subType = it2.next(); DataNode mimeJson = json.get(primaryType).get(subType); @@ -69,7 +69,7 @@ public class MimeTypeUtil { } } - private static void addMimeType(MimeType mime){ + private static void addMimeType(MimeType mime) { mimes.add(mime); for (String extension : mime.getExtensions()) { diff --git a/src/zutil/OneInstanceFile.java b/src/zutil/OneInstanceFile.java index 112b08a..75578a8 100644 --- a/src/zutil/OneInstanceFile.java +++ b/src/zutil/OneInstanceFile.java @@ -33,7 +33,7 @@ import java.nio.channels.OverlappingFileLockException; /** * This class checks if the application is already running * by Locking a file - * + * * @author Ziver Koc */ public class OneInstanceFile implements OneInstance{ @@ -46,7 +46,7 @@ public class OneInstanceFile implements OneInstance{ * * @param filename The name of the file to be locked */ - public OneInstanceFile(String filename){ + public OneInstanceFile(String filename) { this.file = new File(System.getProperty("user.home"), filename); } @@ -57,7 +57,7 @@ public class OneInstanceFile implements OneInstance{ */ public boolean check() { boolean tmp = lockApp(); - if( tmp ) closeLock(); + if (tmp) closeLock(); return !tmp; } diff --git a/src/zutil/OneInstanceNetwork.java b/src/zutil/OneInstanceNetwork.java index 996ec5f..9842ae4 100644 --- a/src/zutil/OneInstanceNetwork.java +++ b/src/zutil/OneInstanceNetwork.java @@ -44,7 +44,7 @@ public class OneInstanceNetwork extends Thread implements OneInstance{ * * @param port The port to lock */ - public OneInstanceNetwork(int port){ + public OneInstanceNetwork(int port) { this.port = port; } @@ -53,7 +53,7 @@ public class OneInstanceNetwork extends Thread implements OneInstance{ * * @return Always true */ - public boolean lockApp(){ + public boolean lockApp() { this.start(); return true; } diff --git a/src/zutil/StringUtil.java b/src/zutil/StringUtil.java index 6f3e3b8..cbf3482 100755 --- a/src/zutil/StringUtil.java +++ b/src/zutil/StringUtil.java @@ -43,74 +43,74 @@ public class StringUtil { * @param bytes size (in bytes) * @return string */ - public static String formatByteSizeToString(long bytes){ + public static String formatByteSizeToString(long bytes) { int total = sizes.length-1; double value = bytes; - for(; value > 1024 ;total--) { + for (; value > 1024; total--) { value /= 1024; } - value = (double)( (int)(value*10) )/10; - return value+" "+sizes[total]; + value = (double)((int)(value * 10)) / 10; + return value + " " + sizes[total]; } /** * @return a human readable String with year/month/day/hour/min/sec/milisec delimitation. */ - public static String formatTimeToString(long milisec){ + public static String formatTimeToString(long milisec) { StringBuilder str = new StringBuilder(); long tmp; // Years - if( milisec >= 31557032762.3361d ){ + if (milisec >= 31557032762.3361d) { tmp = (long) (milisec / 31557032762.3361d); milisec -= tmp * 31557032762.3361d; - if( tmp > 1 ) + if (tmp > 1) str.append(tmp).append(" years "); else str.append(tmp).append(" year "); } // Months - if( milisec >= 2629743830L){ + if (milisec >= 2629743830L) { tmp = milisec / 2629743830L; milisec -= tmp * 2629743830L; - if( tmp > 1 ) + if (tmp > 1) str.append(tmp).append(" months "); else str.append(tmp).append(" month "); } // Days - if( milisec >= 86400000 ){ + if (milisec >= 86400000) { tmp = milisec / 86400000; milisec -= tmp * 86400000; - if( tmp > 1 ) + if (tmp > 1) str.append(tmp).append(" days "); else str.append(tmp).append(" day "); } // Hours - if( milisec >= 3600000 ){ + if (milisec >= 3600000) { tmp = milisec / 3600000; milisec -= tmp * 3600000; - if( tmp > 1 ) + if (tmp > 1) str.append(tmp).append(" hours "); else str.append(tmp).append(" hour "); } // Minutes - if( milisec >= 60000 ){ + if (milisec >= 60000) { tmp = milisec / 60000; milisec -= tmp * 60000; str.append(tmp).append(" min "); } // sec - if( milisec >= 1000 ){ + if (milisec >= 1000) { tmp = milisec / 1000; milisec -= tmp * 1000; str.append(tmp).append(" sec "); } - if( milisec > 0 ){ + if (milisec > 0) { str.append(milisec).append(" milisec "); } @@ -123,7 +123,7 @@ public class StringUtil { * * @return a new String with the given length or longer if the number has more characters. */ - public static String prefixInt(int number, int length){ + public static String prefixInt(int number, int length) { StringBuilder str = new StringBuilder().append(number).reverse(); while (str.length() < length) str.append('0'); @@ -137,7 +137,7 @@ public class StringUtil { * @return a String containing all entries in the list with the specified delimiter in between entries */ @SafeVarargs - public static String join(String delimiter, T... array){ + public static String join(String delimiter, T... array) { return join(delimiter, Arrays.asList(array)); } /** @@ -145,10 +145,10 @@ public class StringUtil { * @param list a list of object that toString() will be called on * @return a String containing all entries in the list with the specified delimiter in between entries */ - public static String join(String delimiter, Iterable list){ + public static String join(String delimiter, Iterable list) { StringBuilder str = new StringBuilder(); Iterator it = list.iterator(); - if(it.hasNext()) { + if (it.hasNext()) { str.append(it.next().toString()); while (it.hasNext()) { str.append(delimiter).append(it.next().toString()); @@ -164,30 +164,30 @@ public class StringUtil { * @param trim is the char to trim * @return a trimmed String */ - public static String trim(String str, char trim){ - if( str == null || str.isEmpty() ) + public static String trim(String str, char trim) { + if (str == null || str.isEmpty()) return str; int start=0, stop=str.length(); // The beginning - for(int i=0; istart ;i--){ + for (int i=str.length()-1; i>start; i--) { char c = str.charAt(i); - if(c <= ' ' || c == trim) + if (c <= ' ' || c == trim) stop = i; else break; } - if(start >= str.length()) + if (start >= str.length()) return ""; return str.substring(start, stop); @@ -198,12 +198,12 @@ public class StringUtil { * * @param str is the string to trim */ - public static String trimQuotes(String str){ - if( str == null ) + public static String trimQuotes(String str) { + if (str == null) return null; str = str.trim(); - if( str.length() >= 2 && str.charAt(0)=='\"' && str.charAt(str.length()-1)=='\"'){ + if (str.length() >= 2 && str.charAt(0)=='\"' && str.charAt(str.length()-1)=='\"') { str = str.substring(1, str.length()-1); } @@ -216,10 +216,10 @@ public class StringUtil { /** * @return A string containing a specific amount of spaces */ - public static String getSpaces(int i){ - if(SPACES.size() <= i){ // Do we need to generate more spaces? + public static String getSpaces(int i) { + if (SPACES.size() <= i) { // Do we need to generate more spaces? synchronized (SPACES) { // Make sure no one else updates the list at the same time - if(SPACES.size() <= i) { // Make sure the previous synchronized thread hasn't already generated strings + if (SPACES.size() <= i) { // Make sure the previous synchronized thread hasn't already generated strings if (SPACES.isEmpty()) SPACES.add(""); for (int j = SPACES.size(); j <= i; j++) { @@ -242,7 +242,7 @@ public class StringUtil { * @param delimiter a single character delimiter * @return a List with all data between the delimiter */ - public static List split(String str, char delimiter){ + public static List split(String str, char delimiter) { ArrayList splitList = new ArrayList<>(); int from = 0, to = 0; diff --git a/src/zutil/Timer.java b/src/zutil/Timer.java index 98a99e0..3c50a43 100755 --- a/src/zutil/Timer.java +++ b/src/zutil/Timer.java @@ -44,7 +44,7 @@ public class Timer { * * @param millisecond the time in milliseconds that the timeout should happen. */ - public Timer(long millisecond){ + public Timer(long millisecond) { this.period = millisecond; reset(); } @@ -54,7 +54,7 @@ public class Timer { * * @return a reference of itself */ - public Timer start(){ + public Timer start() { timestamp = System.currentTimeMillis(); return this; } @@ -62,21 +62,21 @@ public class Timer { /** * Will reset the timer so that {@link #hasTimedOut()} returns true */ - public void reset(){ + public void reset() { timestamp = -1; } /** * @return true if the timer has timed out or has been reset, false if timer is running */ - public boolean hasTimedOut(){ + public boolean hasTimedOut() { return timestamp + period < System.currentTimeMillis(); } - public String toString(){ + public String toString() { if (hasTimedOut()) return "Timed out"; else - return "Timeout in "+StringUtil.formatTimeToString((timestamp+period)-System.currentTimeMillis()); + return "Timeout in " +StringUtil.formatTimeToString((timestamp+period)-System.currentTimeMillis()); } } diff --git a/src/zutil/algo/EuclideansAlgo.java b/src/zutil/algo/EuclideansAlgo.java index 5d36c6e..1eef6d0 100644 --- a/src/zutil/algo/EuclideansAlgo.java +++ b/src/zutil/algo/EuclideansAlgo.java @@ -38,18 +38,18 @@ import java.util.LinkedList; */ public class EuclideansAlgo { - public static void main(String[] args){ + public static void main(String[] args) { MultiPrintStream.out.println("*** Correct Answer: "); MultiPrintStream.out.println("java.util.LinkedList{0, 2, 1, 1, 1, 4, 12, 102, 1, 1, 2, 3, 2, 2, 36}"); MultiPrintStream.out.println("GCD: 1"); MultiPrintStream.out.println("*** Integer:"); MultiPrintStream.out.dump(calcGenerators(60728973, 160523347)); - MultiPrintStream.out.println("GCD: "+calc(60728973, 160523347)); + MultiPrintStream.out.println("GCD: " +calc(60728973, 160523347)); MultiPrintStream.out.println("*** BigInteger: "); MultiPrintStream.out.dump(calcGenerators(new BigInteger("60728973"), new BigInteger("160523347"))); - MultiPrintStream.out.println("GCD: "+calc(new BigInteger("60728973"), new BigInteger("160523347"))); + MultiPrintStream.out.println("GCD: " +calc(new BigInteger("60728973"), new BigInteger("160523347"))); } /** @@ -60,9 +60,9 @@ public class EuclideansAlgo { * @param b is the second integer * @return a integer containing the GCD of the integers */ - public static int calc(int a, int b){ + public static int calc(int a, int b) { int t; - while( b != 0 ){ + while (b != 0) { t = b; b = a % b; a = t; @@ -79,12 +79,12 @@ public class EuclideansAlgo { * @param b is the second BigInteger * @return a BigInteger containing the GCD of the BigIntegers */ - public static BigInteger calc(BigInteger a, BigInteger b){ + public static BigInteger calc(BigInteger a, BigInteger b) { BigInteger t; - while( !b.equals(BigInteger.ZERO) ){ + while (!b.equals(BigInteger.ZERO)) { t = b; - b = a.mod( b ); + b = a.mod(b); a = t; } @@ -99,12 +99,12 @@ public class EuclideansAlgo { * @param b is the second integer * @return a list of integers that is generators for a and b */ - public static LinkedList calcGenerators(int a, int b){ + public static LinkedList calcGenerators(int a, int b) { LinkedList list = new LinkedList<>(); int t; - while( b != 0 ){ - list.add( a/b ); + while (b != 0) { + list.add(a / b); t = b; b = a % b; a = t; @@ -121,14 +121,14 @@ public class EuclideansAlgo { * @param b is the second BigInteger * @return a list of BigIntegers that is generators of a and b */ - public static LinkedList calcGenerators(BigInteger a, BigInteger b){ + public static LinkedList calcGenerators(BigInteger a, BigInteger b) { LinkedList list = new LinkedList<>(); BigInteger t; - while( !b.equals(BigInteger.ZERO) ){ - list.add( new BigInteger("0").add( a.divide( b ) ) ); + while (!b.equals(BigInteger.ZERO)) { + list.add(new BigInteger("0").add(a.divide(b))); t = b; - b = a.mod( b ); + b = a.mod(b); a = t; } diff --git a/src/zutil/algo/LevenshteinDistance.java b/src/zutil/algo/LevenshteinDistance.java index 02e4725..986a70e 100644 --- a/src/zutil/algo/LevenshteinDistance.java +++ b/src/zutil/algo/LevenshteinDistance.java @@ -55,8 +55,8 @@ public class LevenshteinDistance { public static int getDistance(String str1, String str2, int[][] matrix) { int len1 = str1.length()+1; int len2 = str2.length()+1; - if(matrix.length < len1 || matrix[0].length < len2) - throw new IndexOutOfBoundsException("matrix["+matrix.length+"]["+matrix[0].length+"] must be of size ["+len1+"]["+len2+"] or larger"); + if (matrix.length < len1 || matrix[0].length < len2) + throw new IndexOutOfBoundsException("matrix[" + matrix.length + "][" + matrix[0].length + "] must be of size [" + len1 + "][" + len2 + "] or larger"); // source prefixes can be transformed into empty string by // dropping all characters @@ -82,19 +82,19 @@ public class LevenshteinDistance { /* System.out.println(); for (int j=0; j < len2+1; j++) { - if(j>1) - System.out.print(str2.charAt(j-2)+" "); + if (j>1) + System.out.print(str2.charAt(j-2) + " "); else System.out.print("_ "); for (int i=0; i < len1+1; i++) { - if(j==0) { + if (j==0) { if (i > 1) System.out.print(str1.charAt(i - 2) + " "); else if (i != 0) System.out.print("_ "); } else if (i != 0) - System.out.print(matrix[i-1][j-1]+" "); + System.out.print(matrix[i-1][j-1] + " "); } System.out.println(); } @@ -102,7 +102,7 @@ public class LevenshteinDistance { return matrix[len1 - 1][len2 - 1]; } - private static int min(int a, int b, int c){ + private static int min(int a, int b, int c) { int i = (a < b) ? a : b; return (i < c) ? i : c; //return Math.min(i, Math.min(j, k)); diff --git a/src/zutil/algo/ShanksTonelliAlgo.java b/src/zutil/algo/ShanksTonelliAlgo.java index 117367e..6a2cd86 100644 --- a/src/zutil/algo/ShanksTonelliAlgo.java +++ b/src/zutil/algo/ShanksTonelliAlgo.java @@ -33,47 +33,47 @@ import java.math.BigInteger; * @see Wikipedia */ public class ShanksTonelliAlgo { - public static BigInteger calc(BigInteger n, BigInteger p){ + public static BigInteger calc(BigInteger n, BigInteger p) { BigInteger nOrg = n; BigInteger S = null, V, R, U, X; BigInteger ONE = BigInteger.ONE; - BigInteger TWO = BigInteger.valueOf( 2 ); - BigInteger Q = p.add( ONE ).divide( TWO ); + BigInteger TWO = BigInteger.valueOf(2); + BigInteger Q = p.add(ONE).divide(TWO); - switch( p.mod( BigInteger.valueOf(4) ).intValue() ){ + switch (p.mod(BigInteger.valueOf(4)).intValue()) { case 3: - S = n.pow( Q.divide( TWO ).intValue() ).mod( p ); + S = n.pow(Q.divide(TWO).intValue()).mod(p); break; case 1: S = ONE; - n = n.subtract( ONE ); - while (n.divide( p ).compareTo( ONE ) == 0) { - S = S.add( ONE ); + n = n.subtract(ONE); + while (n.divide(p).compareTo(ONE) == 0) { + S = S.add(ONE); //n = (n-2s+1) mod p - n = n.subtract( TWO.multiply( S ) ).add( ONE ).mod( p ); - if (n.compareTo( BigInteger.ZERO ) == 0){ + n = n.subtract(TWO.multiply(S)).add(ONE).mod(p); + if (n.compareTo(BigInteger.ZERO) == 0) { return S; } } - Q = Q.divide( TWO ); + Q = Q.divide(TWO); V = ONE; R = S; U = ONE; - while (Q.compareTo( BigInteger.ZERO ) > 0) { - X = R.pow(2).subtract( n.multiply( U.pow(2) ) ).mod( p ); - U = TWO.multiply( R ).multiply( U ).mod( p ); + while (Q.compareTo(BigInteger.ZERO) > 0) { + X = R.pow(2).subtract(n.multiply(U.pow(2))).mod(p); + U = TWO.multiply(R).multiply(U).mod(p); R = X; - if ( Q.testBit(0) ){ - X = S.multiply( R ).subtract( n.multiply(V).multiply(U) ).mod( p ); - V = V.multiply(R).add( S.multiply(U) ).mod( p ); + if (Q.testBit(0)) { + X = S.multiply(R).subtract(n.multiply(V).multiply(U)).mod(p); + V = V.multiply(R).add(S.multiply(U)).mod(p); S = X; } - Q = Q.divide( TWO ); + Q = Q.divide(TWO); } } - if( S != null && S.multiply( S ).mod( p ).compareTo( nOrg ) != 0 ){ + if (S != null && S.multiply(S).mod(p).compareTo(nOrg) != 0) { return null; } @@ -87,21 +87,21 @@ public class ShanksTonelliAlgo { p-1 = ( 2^S )/( 1-p ) * 2^S; // R = n^( (Q+1)/2 ) mod p - R = n.pow( Q.add(BigInteger.ONE).divide(BigInteger.valueOf(2)).intValue() ).mod( p ); + R = n.pow(Q.add(BigInteger.ONE).divide(BigInteger.valueOf(2)).intValue()).mod(p); // V = W^Q mod p - V = W.pow( Q.intValue() ).mod( p ); + V = W.pow(Q.intValue()).mod(p); - for(int i=S.intValue(); true ;){ - while( true ){ + for (int i=S.intValue(); true;) { + while (true) { i--; // 1 = ( ( R^2 * n^-1 )^2^i ) mod p - if( ( R.pow(2).multiply( n.pow(-1) ) ).pow( (int)Math.pow(2, i) ).mod( p ).compareTo( BigInteger.ONE ) == 0 ) + if ((R.pow(2).multiply(n.pow(-1))).pow((int)Math.pow(2, i)).mod(p).compareTo(BigInteger.ONE) == 0) break; } - if(i == 0) return R; + if (i == 0) return R; //R = ( RV^(2^(S-i-1)) ) mod p - else R = ( R.multiply( V.pow( (int)Math.pow( 2, S.intValue()-i-1) ) )).mod( p ); + else R = (R.multiply(V.pow((int)Math.pow(2, S.intValue()-i-1) ) )).mod(p ); } */ } diff --git a/src/zutil/algo/WienersAlgo.java b/src/zutil/algo/WienersAlgo.java index 2f3e5b5..5a43da5 100644 --- a/src/zutil/algo/WienersAlgo.java +++ b/src/zutil/algo/WienersAlgo.java @@ -48,7 +48,7 @@ public class WienersAlgo { * First index is p and second is q. * If no value was found then it returns null. */ - public static BigInteger[] calc(BigInteger n, BigInteger e){ + public static BigInteger[] calc(BigInteger n, BigInteger e) { BigInteger[] ret; LinkedList gen = EuclideansAlgo.calcGenerators(e, n); @@ -59,30 +59,30 @@ public class WienersAlgo { BigInteger d1 = BigInteger.ONE; BigInteger t, n1, g; - while(!gen.isEmpty()){ + while (!gen.isEmpty()) { g = gen.poll(); t = c1; - c1 = g.multiply( c1 ).add( c0 ); + c1 = g.multiply(c1).add(c0); c0 = t; t = d1; - d1 = g.multiply( d1 ).add( d0 ); + d1 = g.multiply(d1).add(d0); d0 = t; // (d1*e-1) % c1 == 0 - n1 = d1.multiply( e ).subtract( BigInteger.ONE ); - if( n1.mod( c1 ).equals( BigInteger.ZERO ) ){ - n1 = n1.divide( c1 ); + n1 = d1.multiply(e).subtract(BigInteger.ONE); + if (n1.mod(c1).equals(BigInteger.ZERO)) { + n1 = n1.divide(c1); // x^2 - ( n - n1 +1 )x + n = 0 ret = ZMath.pqFormula( - n.subtract( n1 ).add( BigInteger.ONE ).negate(), + n.subtract(n1).add(BigInteger.ONE).negate(), n); - if(ret[0].compareTo( BigInteger.ZERO ) >= 0 && - ret[1].compareTo( BigInteger.ZERO ) >= 0 && - ret[0].multiply( ret[1] ).equals( n )){ + if (ret[0].compareTo(BigInteger.ZERO) >= 0 && + ret[1].compareTo(BigInteger.ZERO) >= 0 && + ret[0].multiply(ret[1]).equals(n)) { return ret; } } diff --git a/src/zutil/algo/path/BreadthFirstSearch.java b/src/zutil/algo/path/BreadthFirstSearch.java index 228f542..15214b1 100644 --- a/src/zutil/algo/path/BreadthFirstSearch.java +++ b/src/zutil/algo/path/BreadthFirstSearch.java @@ -42,24 +42,24 @@ public class BreadthFirstSearch implements PathFinder{ * @param stop is the goal Node * @return A list with the path */ - public LinkedList find(PathNode start, PathNode stop){ + public LinkedList find(PathNode start, PathNode stop) { Queue queue = new LinkedList<>(); HashSet visited = new HashSet<>(); queue.add(start); - visited.add( start ); + visited.add(start); PathNode tmp; - while(!queue.isEmpty()){ + while (!queue.isEmpty()) { tmp = queue.poll(); - for(PathNode next : tmp.getNeighbors()){ - if(!visited.contains( next ) && tmp.getNeighborCost(next) > 0){ + for (PathNode next : tmp.getNeighbors()) { + if (!visited.contains(next) && tmp.getNeighborCost(next) > 0) { queue.add(next); - visited.add( next ); + visited.add(next); next.setParentNeighbor(tmp); - if(next.equals(stop)){ + if (next.equals(stop)) { return stop.traversTo(start); } } diff --git a/src/zutil/algo/path/DepthFirstSearch.java b/src/zutil/algo/path/DepthFirstSearch.java index fdc4eef..849782e 100644 --- a/src/zutil/algo/path/DepthFirstSearch.java +++ b/src/zutil/algo/path/DepthFirstSearch.java @@ -42,10 +42,10 @@ public class DepthFirstSearch { * @param stop Stop Node * @return A list with the path */ - public LinkedList find(PathNode start, PathNode stop){ + public LinkedList find(PathNode start, PathNode stop) { visited.clear(); PathNode node = dfs(start, stop); - return node.traversTo( start ); + return node.traversTo(start); } /** @@ -53,17 +53,17 @@ public class DepthFirstSearch { * @param node The node to search from * @return The stop PathNode if a path was found else null */ - private PathNode dfs(PathNode node, PathNode stop){ - visited.add( node ); - if(node.equals(stop)){ + private PathNode dfs(PathNode node, PathNode stop) { + visited.add(node); + if (node.equals(stop)) { return node; } - for(PathNode next : node.getNeighbors()){ - if(!visited.contains( next ) && node.getNeighborCost(next) > 0){ + for (PathNode next : node.getNeighbors()) { + if (!visited.contains(next) && node.getNeighborCost(next) > 0) { next.setParentNeighbor(node); PathNode tmp = dfs(next, stop); - if(tmp != null){ + if (tmp != null) { return tmp; } } diff --git a/src/zutil/algo/path/StandardPathNode.java b/src/zutil/algo/path/StandardPathNode.java index 17b4add..2c788d9 100644 --- a/src/zutil/algo/path/StandardPathNode.java +++ b/src/zutil/algo/path/StandardPathNode.java @@ -36,7 +36,7 @@ public class StandardPathNode implements PathNode{ private HashMap neighbors; private PathNode parent; - public StandardPathNode(){ + public StandardPathNode() { neighbors = new HashMap<>(); } @@ -59,11 +59,11 @@ public class StandardPathNode implements PathNode{ public LinkedList traversTo(PathNode goal) { LinkedList path = new LinkedList<>(); PathNode current = this; - while(current != null){ + while (current != null) { path.addFirst(current); current = current.getParentNeighbor(); - if(goal.equals( current )){ - path.addFirst( goal ); + if (goal.equals(current)) { + path.addFirst(goal); return path; } } diff --git a/src/zutil/algo/search/QuickSelect.java b/src/zutil/algo/search/QuickSelect.java index 7d76379..8b3bfe3 100644 --- a/src/zutil/algo/search/QuickSelect.java +++ b/src/zutil/algo/search/QuickSelect.java @@ -27,17 +27,17 @@ package zutil.algo.search; import zutil.algo.sort.sortable.SortableDataList; /** - * This algorithm is a modified QuickSort + * This algorithm is a modified QuickSort * to find the k smallest or biggest value * http://en.wikipedia.org/wiki/Selection_algorithm - * + * * @author Ziver * */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class QuickSelect { - public static Object find(SortableDataList list, int k){ + public static Object find(SortableDataList list, int k) { return find(list, k, 0, list.size()-1); } @@ -52,13 +52,13 @@ public class QuickSelect { else return select(list, k, pivotNewIndex+1, right) */ - public static Object find(SortableDataList list, int k, int left, int right){ + public static Object find(SortableDataList list, int k, int left, int right) { // select a pivot int pivot = right/2; int newPivot = partition(list, left, right, pivot); - if(k == newPivot) + if (k == newPivot) return list.get(k); - else if(k < newPivot) + else if (k < newPivot) return find(list, k, left, newPivot-1); else return find(list, k, newPivot+1, right); @@ -76,14 +76,14 @@ public class QuickSelect { swap list[right] and list[storeIndex] // Move pivot to its final place return storeIndex */ - private static int partition(SortableDataList list, int left, int right, int pivot){ + private static int partition(SortableDataList list, int left, int right, int pivot) { Object pivotValue = list.get(pivot); list.swap(pivot, right); int storeIndex = left; - for(int i=left; i files){ + private void mergeFiles(LinkedList files) { try { BufferedReader[] chunkReader = new BufferedReader[files.size()]; String[] rows = new String[files.size()]; @@ -97,23 +97,23 @@ public class ExternalSort { boolean someFileStillHasRows = false; - for (int i=0; i readChunk(BufferedReader in) throws IOException{ LinkedList list = new LinkedList<>(); String tmp; - for(int i=0; i list){ + private void removeFiles(LinkedList list) { for (File file : list) { file.delete(); } diff --git a/src/zutil/algo/sort/MergeSort.java b/src/zutil/algo/sort/MergeSort.java index 57363d5..1283888 100644 --- a/src/zutil/algo/sort/MergeSort.java +++ b/src/zutil/algo/sort/MergeSort.java @@ -34,8 +34,8 @@ public class MergeSort{ * * @param list is the list to sort */ - public static void sort(int[] list){ - if(list == null) + public static void sort(int[] list) { + if (list == null) return; sort(list, 0, list.length); @@ -49,10 +49,10 @@ public class MergeSort{ * @param start is the starting index of the sub list * @param stop is the end index of the sub list */ - protected static void sort(int[] list, int start, int stop){ - if(stop-start <= 1) return; + protected static void sort(int[] list, int start, int stop) { + if (stop-start <= 1) return; - int pivot = start+(stop-start)/2; + int pivot = start + (stop - start) / 2; sort(list, start, pivot); sort(list, pivot, stop); @@ -69,7 +69,7 @@ public class MergeSort{ * @param stop is the end of the second sublist * @param pivot is the end index for the first list and the beginning of the second. */ - protected static void merge(int[] list, int start, int stop, int pivot){ + protected static void merge(int[] list, int start, int stop, int pivot) { int length = pivot-start; int[] tmp = new int[stop-start]; @@ -77,12 +77,11 @@ public class MergeSort{ int index1 = 0; int index2 = length; - for(int i=start; i= length || tmp[index1] > tmp[index2]) ){ + for (int i=start; i= length || tmp[index1] > tmp[index2])) { list[i] = tmp[index2]; ++index2; - } - else { + } else { list[i] = tmp[index1]; ++index1; } @@ -96,8 +95,8 @@ public class MergeSort{ * * @param list is the list to sort */ - public static void sort(SortableDataList list){ - if(list == null) + public static void sort(SortableDataList list) { + if (list == null) return; sort(list, 0, list.size()); @@ -111,8 +110,8 @@ public class MergeSort{ * @param start is the starting index of the sub list * @param stop is the end index of the sub list */ - protected static void sort(SortableDataList list, int start, int stop){ - if(stop-start <= 1) return; + protected static void sort(SortableDataList list, int start, int stop) { + if (stop-start <= 1) return; int pivot = start+(stop-start)/2; sort(list, start, pivot); @@ -132,23 +131,22 @@ public class MergeSort{ * @param pivot is the end index for the first list and the beginning of the second. */ @SuppressWarnings({ "unchecked", "rawtypes" }) - protected static void merge(SortableDataList list, int start, int stop, int pivot){ + protected static void merge(SortableDataList list, int start, int stop, int pivot) { int length = pivot-start; Object[] tmp = new Object[stop-start]; - for(int i=0; i= length || ((Comparable)tmp[index1]).compareTo(tmp[index2]) > 0 )){ - list.set(i, (T)tmp[index2]); + for (int i=start; i= length || ((Comparable)tmp[index1]).compareTo(tmp[index2]) > 0)) { + list.set(i, (T) tmp[index2]); ++index2; - } - else { - list.set(i, (T)tmp[index1]); + } else { + list.set(i, (T) tmp[index1]); ++index1; } } diff --git a/src/zutil/algo/sort/QuickSort.java b/src/zutil/algo/sort/QuickSort.java index a18c657..5db4827 100644 --- a/src/zutil/algo/sort/QuickSort.java +++ b/src/zutil/algo/sort/QuickSort.java @@ -29,7 +29,7 @@ import zutil.algo.sort.sortable.SortableDataList; /** * This class implements QuickSort to sort a array - * + * * @author Ziver */ public class QuickSort{ @@ -42,10 +42,10 @@ public class QuickSort{ * * @param list is the list to sort. */ - public static void sort(SortableDataList list){ + public static void sort(SortableDataList list) { sort(list, 0, list.size()-1, MIDDLE_PIVOT, true); } - + /** * Sort the elements in ascending order using Quicksort. * @@ -53,7 +53,7 @@ public class QuickSort{ * @param type is the type of pivot * @param insert is if insertion sort will be used */ - public static void sort(SortableDataList list, int type, boolean insert){ + public static void sort(SortableDataList list, int type, boolean insert) { sort(list, 0, list.size()-1, type, insert); } @@ -66,43 +66,43 @@ public class QuickSort{ * @param start is the index to start from * @param stop is the index to stop * @param type is the type of pivot to use - */ + */ @SuppressWarnings({ "unchecked", "rawtypes" }) - public static void sort(SortableDataList list, int start, int stop, int type, boolean insertionSort){ - if(stop-start <= 15 && insertionSort){ - SimpleSort.insertionSort( list, start, stop); + public static void sort(SortableDataList list, int start, int stop, int type, boolean insertionSort) { + if (stop-start <= 15 && insertionSort) { + SimpleSort.insertionSort(list, start, stop); } int pivotIndex = pivot(list,start,stop,type); Object pivot = list.get(pivotIndex); int left=start, right=stop; do{ - while(list.compare(left, pivot) < 0){ + while (list.compare(left, pivot) < 0) { left++; } - while(list.compare(right, pivot) > 0){ + while (list.compare(right, pivot) > 0) { right--; } - if(left <= right){ + if (left <= right) { list.swap(left, right); left++; right--; } - }while(left <= right); + }while (left <= right); - if(start < right){ + if (start < right) { sort(list, start, right, type, insertionSort); } - if(left < stop){ + if (left < stop) { sort(list, left, stop, type, insertionSort); } } @SuppressWarnings({ "unchecked", "rawtypes" }) - private static int pivot(SortableDataList list, int start, int stop,int type){ - switch(type){ + private static int pivot(SortableDataList list, int start, int stop,int type) { + switch(type) { case RANDOM_PIVOT: return start+(int)(Math.random()*(stop-start)); case MEDIAN_PIVOT: @@ -111,9 +111,9 @@ public class QuickSort{ (Comparable)list.get(list.size()/2), (Comparable)list.get(list.size()-1)}; SimpleSort.insertionSort(new SortableComparableArray(i)); - if(i[i.length/2].compareTo(list.get(start)) == 0) + if (i[i.length/2].compareTo(list.get(start)) == 0) return start; - else if(i[i.length/2].compareTo(list.get(stop)) == 0) + else if (i[i.length/2].compareTo(list.get(stop)) == 0) return stop; else return start+(stop-start)/2; diff --git a/src/zutil/algo/sort/Randomizer.java b/src/zutil/algo/sort/Randomizer.java index e0ce948..4db776f 100644 --- a/src/zutil/algo/sort/Randomizer.java +++ b/src/zutil/algo/sort/Randomizer.java @@ -27,9 +27,9 @@ package zutil.algo.sort; import zutil.algo.sort.sortable.SortableDataList; /** - * This class randomizes the index of all the elements in + * This class randomizes the index of all the elements in * the Sortable object - * + * * @author Ziver */ public class Randomizer { @@ -38,11 +38,11 @@ public class Randomizer { * Randomizes the index of all the elements * @param list The list */ - @SuppressWarnings({ "rawtypes" }) - public static void sort(SortableDataList list){ + @SuppressWarnings({"rawtypes"}) + public static void sort(SortableDataList list) { int size = list.size(); - for(int i=0; i list){ + public static void bubbleSort(SortableDataList list) { bubbleSort(list, 0, list.size()); - } + } /** * Sort the elements in ascending order using bubble sort * witch is the slowest of the algorithms. * Complexity: O(n^2). - * + * * @param list is an array of integers. * @param start is the index to start from * @param stop is the index to stop */ - public static void bubbleSort(SortableDataList list, int start, int stop){ - for(int i=start; i 0){ + public static void bubbleSort(SortableDataList list, int start, int stop) { + for (int i=start; i 0) { list.swap(j, j+1); } } @@ -67,24 +67,24 @@ public class SimpleSort{ * Sort the elements in ascending order using selection sort * witch in practice is 40% faster than bubble sort. * Complexity: O(n^2). - * + * * @param list is the list to sort. */ - public static void selectionSort(SortableDataList list){ + public static void selectionSort(SortableDataList list) { selectionSort(list, 0, list.size()); - } + } /** * Sort the elements in ascending order using selection sort * witch in practice is 40% faster than bubble sort. * Complexity: O(n^2). - * + * * @param list is the list to sort. * @param start is the index to start from * @param stop is the index to stop */ - public static void selectionSort(SortableDataList list, int start, int stop){ + public static void selectionSort(SortableDataList list, int start, int stop) { for (int i = start; i < stop - 1; i++) { - // find index m of the minimum element in v[i..n-1] + // find index m of the minimum element in v[i..n-1] int m = i; for (int j = i + 1; j < stop; j++) { if (list.compare(j, m) < 0) @@ -102,24 +102,24 @@ public class SimpleSort{ * * @param list is a list to sort. */ - public static void insertionSort(SortableDataList list){ + public static void insertionSort(SortableDataList list) { insertionSort(list, 0, list.size()); - } + } /** * Sort the elements in ascending order using insertion sort * witch in practice is 5 times faster than bubble sort. * Complexity: O(n^2). - * + * * @param list is an array of integers. * @param start is the index to start from * @param stop is the index to stop */ - public static void insertionSort(SortableDataList list, int start, int stop){ - for(int i=start; i0 ;--j){ + public static void insertionSort(SortableDataList list, int start, int stop) { + for (int i=start; i0; --j) { list.swap(j-1, j); } } } - + } diff --git a/src/zutil/algo/sort/sortable/SortableArrayList.java b/src/zutil/algo/sort/sortable/SortableArrayList.java index c2f8cbc..427774e 100644 --- a/src/zutil/algo/sort/sortable/SortableArrayList.java +++ b/src/zutil/algo/sort/sortable/SortableArrayList.java @@ -30,7 +30,7 @@ import java.util.ArrayList; public class SortableArrayList implements SortableDataList{ private ArrayList list; - public SortableArrayList(ArrayList list){ + public SortableArrayList(ArrayList list) { this.list = list; } @@ -38,7 +38,7 @@ public class SortableArrayList implements SortableDataList{ return list.get(i); } - public void set(int i, T o){ + public void set(int i, T o) { list.set(i, o); } diff --git a/src/zutil/algo/sort/sortable/SortableComparableArray.java b/src/zutil/algo/sort/sortable/SortableComparableArray.java index 126aac8..a5ddfc6 100644 --- a/src/zutil/algo/sort/sortable/SortableComparableArray.java +++ b/src/zutil/algo/sort/sortable/SortableComparableArray.java @@ -28,7 +28,7 @@ package zutil.algo.sort.sortable; public class SortableComparableArray implements SortableDataList{ private Comparable[] list; - public SortableComparableArray(Comparable[] list){ + public SortableComparableArray(Comparable[] list) { this.list = list; } @@ -36,7 +36,7 @@ public class SortableComparableArray implements SortableDataList{ return list[i]; } - public void set(int i, Comparable o){ + public void set(int i, Comparable o) { list[i] = o; } @@ -51,20 +51,20 @@ public class SortableComparableArray implements SortableDataList{ } public int compare(int a, int b) { - if(list[a].compareTo(list[b]) < 0){ + if (list[a].compareTo(list[b]) < 0) { return -1; } - else if(list[a].compareTo(list[b]) > 0){ + else if (list[a].compareTo(list[b]) > 0) { return 1; } return 0; } public int compare(int a, Comparable b) { - if(list[a].compareTo(b) < 0){ + if (list[a].compareTo(b) < 0) { return -1; } - else if(list[a].compareTo(b) > 0){ + else if (list[a].compareTo(b) > 0) { return 1; } return 0; diff --git a/src/zutil/algo/sort/sortable/SortableIntArray.java b/src/zutil/algo/sort/sortable/SortableIntArray.java index 71a0fcf..0fa4936 100644 --- a/src/zutil/algo/sort/sortable/SortableIntArray.java +++ b/src/zutil/algo/sort/sortable/SortableIntArray.java @@ -27,7 +27,7 @@ package zutil.algo.sort.sortable; public class SortableIntArray implements SortableDataList{ private int[] list; - public SortableIntArray(int[] list){ + public SortableIntArray(int[] list) { this.list = list; } @@ -35,7 +35,7 @@ public class SortableIntArray implements SortableDataList{ return list[i]; } - public void set(int i, Integer o){ + public void set(int i, Integer o) { list[i] = o; } @@ -50,20 +50,20 @@ public class SortableIntArray implements SortableDataList{ } public int compare(int a, int b) { - if(list[a] < list[b]){ + if (list[a] < list[b]) { return -1; } - else if(list[a] > list[b]){ + else if (list[a] > list[b]) { return 1; } return 0; } public int compare(int a, Integer b) { - if(list[a] < b){ + if (list[a] < b) { return -1; } - else if(list[a] > b){ + else if (list[a] > b) { return 1; } return 0; diff --git a/src/zutil/algo/sort/sortable/SortableLinkedList.java b/src/zutil/algo/sort/sortable/SortableLinkedList.java index 5db7701..daf726b 100644 --- a/src/zutil/algo/sort/sortable/SortableLinkedList.java +++ b/src/zutil/algo/sort/sortable/SortableLinkedList.java @@ -30,7 +30,7 @@ import java.util.LinkedList; public class SortableLinkedList implements SortableDataList{ private LinkedList list; - public SortableLinkedList(LinkedList list){ + public SortableLinkedList(LinkedList list) { this.list = list; } @@ -38,7 +38,7 @@ public class SortableLinkedList implements SortableDataList{ return list.get(i); } - public void set(int i, T o){ + public void set(int i, T o) { list.set(i, o); } diff --git a/src/zutil/api/Gravatar.java b/src/zutil/api/Gravatar.java index 7859fcd..047440b 100644 --- a/src/zutil/api/Gravatar.java +++ b/src/zutil/api/Gravatar.java @@ -37,7 +37,7 @@ public class Gravatar { * @param email the email assosicated with the avatar * @return a http url as a String that points to a avatar image */ - public static String getImageUrl(String email){ + public static String getImageUrl(String email) { return getImageUrl(email, null, -1); } /** @@ -45,7 +45,7 @@ public class Gravatar { * @param size the requested image size. default is 80px * @return a http url as a String that points to a avatar image */ - public static String getImageUrl(String email, int size){ + public static String getImageUrl(String email, int size) { return getImageUrl(email, null, size); } /** @@ -53,7 +53,7 @@ public class Gravatar { * @param format the picture file format. e.g. "jpg", "png" * @return a http url as a String that points to a avatar image */ - public static String getImageUrl(String email, String format){ + public static String getImageUrl(String email, String format) { return getImageUrl(email, format, -1); } /** @@ -62,9 +62,9 @@ public class Gravatar { * @param size the requested image size. default is 80px * @return a http url as a String that points to a avatar image */ - public static String getImageUrl(String email, String format, int size){ - String formatStr = (format!=null ? "."+format : ""); - String sizeStr = (size > 0 ? "?size="+size : ""); + public static String getImageUrl(String email, String format, int size) { + String formatStr = (format!=null ? "." + format : ""); + String sizeStr = (size > 0 ? "?size=" + size : ""); return new StringBuilder(GRAVATAR_IMG_PREFIX) .append(getHash(email)) .append(formatStr) @@ -73,8 +73,8 @@ public class Gravatar { } - private static String getHash(String email){ - email = (""+email).trim(); + private static String getHash(String email) { + email = ("" + email).trim(); email = email.toLowerCase(); return Hasher.MD5(email); } diff --git a/src/zutil/chart/AbstractChart.java b/src/zutil/chart/AbstractChart.java index 35f0680..123e78f 100755 --- a/src/zutil/chart/AbstractChart.java +++ b/src/zutil/chart/AbstractChart.java @@ -43,15 +43,15 @@ public abstract class AbstractChart extends JPanel{ - protected void paintComponent(Graphics g){ + protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); - Rectangle bound = drawAxis( g2, new Rectangle(0, 0, getWidth(), getHeight())); - drawChart( g2, bound ); + Rectangle bound = drawAxis(g2, new Rectangle(0, 0, getWidth(), getHeight())); + drawChart(g2, bound); } @@ -79,7 +79,7 @@ public abstract class AbstractChart extends JPanel{ * * @param data is the data to draw */ - public void setChartData(ChartData data){ + public void setChartData(ChartData data) { this.data = data; } @@ -91,7 +91,7 @@ public abstract class AbstractChart extends JPanel{ * @param bound is the drawing bounds * @return a x pixel coordinate */ - static protected double getXCoordinate(double x, double scale, Rectangle bound){ + static protected double getXCoordinate(double x, double scale, Rectangle bound) { return bound.x + x * scale; } @@ -103,15 +103,15 @@ public abstract class AbstractChart extends JPanel{ * @param bound is the drawing bounds * @return a y pixel coordinate */ - static protected double getYCoordinate(double y, double scale, Rectangle bound){ - return bound.y + bound.height - ( y * scale ); + static protected double getYCoordinate(double y, double scale, Rectangle bound) { + return bound.y + bound.height - (y * scale); } - static protected double getXScale(ChartData data, Rectangle bound){ + static protected double getXScale(ChartData data, Rectangle bound) { return (double) bound.width / (Math.abs(data.getMaxX()) + Math.abs(data.getMinX())); } - static protected double getYScale(ChartData data, Rectangle bound){ + static protected double getYScale(ChartData data, Rectangle bound) { return (double) bound.height / (Math.abs(data.getMaxY()) + Math.abs(data.getMinY())); } } diff --git a/src/zutil/chart/ChartData.java b/src/zutil/chart/ChartData.java index def74a0..4cd7f20 100755 --- a/src/zutil/chart/ChartData.java +++ b/src/zutil/chart/ChartData.java @@ -41,55 +41,55 @@ public class ChartData { private ArrayList points; - public ChartData(){ + public ChartData() { xStrings = new HashMap<>(); yStrings = new HashMap<>(); points = new ArrayList<>(); } - public void setXValueString(int x, String name){ + public void setXValueString(int x, String name) { xStrings.put(x, name); } - public void setYValueString(int y, String name){ + public void setYValueString(int y, String name) { yStrings.put(y, name); } - public void addPoint(int x, int y){ - points.add( new Point( x, y)); + public void addPoint(int x, int y) { + points.add(new Point(x, y)); setMaxMin(x, y); } - private void setMaxMin(int x, int y){ - if( x > maxX) maxX = x; - if( x < minX) minX = x; + private void setMaxMin(int x, int y) { + if (x > maxX) maxX = x; + if (x < minX) minX = x; - if( y > maxY) maxY = y; - if( y < minY) minY = y; + if (y > maxY) maxY = y; + if (y < minY) minY = y; } - public int getMaxX(){ + public int getMaxX() { return maxX; } - public int getMinX(){ + public int getMinX() { return minX; } - public int getMaxY(){ + public int getMaxY() { return maxY; } - public int getMinY(){ + public int getMinY() { return minY; } - public String getXString(int x){ + public String getXString(int x) { return xStrings.get(x); } - public String getYString(int y){ + public String getYString(int y) { return yStrings.get(y); } - protected List getData(){ + protected List getData() { return points; } } diff --git a/src/zutil/chart/LineAxis.java b/src/zutil/chart/LineAxis.java index 9199a36..e67b6d6 100755 --- a/src/zutil/chart/LineAxis.java +++ b/src/zutil/chart/LineAxis.java @@ -33,8 +33,8 @@ import java.awt.geom.Line2D; public abstract class LineAxis extends AbstractChart{ @Override - protected Rectangle drawAxis(Graphics2D g2, Rectangle bound){ - if( data == null ) + protected Rectangle drawAxis(Graphics2D g2, Rectangle bound) { + if (data == null) return null; width = bound.width; @@ -42,24 +42,24 @@ public abstract class LineAxis extends AbstractChart{ chartBound = new Rectangle(); int stepLength = 7; - // ********************************** + // ------------------------------------------------ // Calculate Font sizes - // ********************************** + // ------------------------------------------------ FontMetrics metric = g2.getFontMetrics(); int fontHeight = metric.getHeight(); int fontXWidth = 0; int fontYWidth = 0; - for( Point p : data.getData() ){ + for (Point p : data.getData()) { int length; - String tmp = data.getXString( p.x ); - if( tmp != null ) length = metric.stringWidth( tmp ); - else length = metric.stringWidth( ""+p.x ); + String tmp = data.getXString(p.x); + if (tmp != null) length = metric.stringWidth(tmp); + else length = metric.stringWidth("" + p.x); fontXWidth = Math.max(length, fontXWidth); - tmp = data.getXString( p.y ); - if( tmp != null ) length = metric.stringWidth( tmp ); - else length = metric.stringWidth( ""+p.y ); + tmp = data.getXString(p.y); + if (tmp != null) length = metric.stringWidth(tmp); + else length = metric.stringWidth("" + p.y); fontYWidth = Math.max(length, fontYWidth); } @@ -67,7 +67,7 @@ public abstract class LineAxis extends AbstractChart{ Point origo = new Point( PADDING + fontYWidth + stepLength, - height - PADDING - fontHeight - stepLength ); + height - PADDING - fontHeight - stepLength); chartBound.x = (int) (origo.getX() + 1); chartBound.y = PADDING; chartBound.width = width - chartBound.x - PADDING; @@ -81,9 +81,9 @@ public abstract class LineAxis extends AbstractChart{ g2.setStroke(new BasicStroke(1.5f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND)); // Y Axis - g2.draw( new Line2D.Double( origo.getX(), PADDING, origo.getX(), origo.getY()+PADDING/2 )); + g2.draw(new Line2D.Double(origo.getX(), PADDING, origo.getX(), origo.getY()+PADDING/2)); // X Axis - g2.draw( new Line2D.Double( origo.getX()-PADDING/2, origo.getY(), width-PADDING, origo.getY() )); + g2.draw(new Line2D.Double(origo.getX()-PADDING/2, origo.getY(), width-PADDING, origo.getY())); // Y Axis steps and labels // X Axis steps and labels diff --git a/src/zutil/chart/LineChart.java b/src/zutil/chart/LineChart.java index cb7ca66..75cb4be 100755 --- a/src/zutil/chart/LineChart.java +++ b/src/zutil/chart/LineChart.java @@ -43,7 +43,7 @@ public class LineChart extends LineAxis{ // Draw lines Point prevP = null; - for(Point p : data.getData()){ + for (Point p : data.getData()) { if (prevP != null) drawLine(g2, bound, xScale, yScale, prevP.x, prevP.y, p.x, p.y); prevP = p; @@ -51,7 +51,7 @@ public class LineChart extends LineAxis{ } private void drawLine(Graphics2D g2, Rectangle bound, double xScale, double yScale, - double x1, double y1, double x2, double y2){ + double x1, double y1, double x2, double y2) { // Line g2.draw(new Line2D.Double( getXCoordinate(x1, xScale, bound), diff --git a/src/zutil/converter/Converter.java b/src/zutil/converter/Converter.java index 95aafa3..9e6a6f0 100755 --- a/src/zutil/converter/Converter.java +++ b/src/zutil/converter/Converter.java @@ -32,7 +32,7 @@ import java.util.Iterator; import java.util.Map; public class Converter { - private Converter(){} + private Converter() {} /** * Converts an object to an array of bytes. @@ -57,7 +57,7 @@ public class Converter { * @param num is the number to convert * @return a byte array of four bytes */ - public static byte[] toBytes(int num){ + public static byte[] toBytes(int num) { return new byte[]{ (byte)(num & 0xff), (byte)((num >> 8)& 0xff), @@ -70,7 +70,7 @@ public class Converter { * * @return a byte array with the same binary value as the char. */ - public static byte[] toBytes(char[] arr){ + public static byte[] toBytes(char[] arr) { byte[] ret = new byte[arr.length]; for (int i=0; i= hex.length()) + for (int i=0; i= hex.length()) b[(i+1)/2] = hexToByte(hex.charAt(i), '0'); else b[(i+1)/2] = hexToByte(hex.charAt(i), hex.charAt(i+1)); @@ -116,9 +116,9 @@ public class Converter { * @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; + public static byte hexToByte(char quad1, char quad2) { + byte b = hexToByte(quad2); + b |= hexToByte(quad1) << 4; return b; } @@ -129,8 +129,8 @@ public class Converter { * @return a byte that corresponds to the hex * @throws IllegalArgumentException if hex is not a valid hex character */ - public static byte hexToByte( char hex ) throws IllegalArgumentException{ - switch( Character.toLowerCase(hex) ){ + public static byte hexToByte(char hex) throws IllegalArgumentException{ + switch(Character.toLowerCase(hex)) { case '0': return 0x00; case '1': return 0x01; case '2': return 0x02; @@ -148,7 +148,7 @@ public class Converter { case 'e': return 0x0e; case 'f': return 0x0f; default: - throw new IllegalArgumentException("'"+hex+"' is an illegal hex character only 0-9 and a-f characters allowed"); + throw new IllegalArgumentException("'" + hex + "' is an illegal hex character only 0-9 and a-f characters allowed"); } } @@ -187,7 +187,7 @@ public class Converter { * @param raw the byte array to convert * @return a bit String */ - public static String toBitString(byte raw){ + public static String toBitString(byte raw) { StringBuilder str = new StringBuilder(8); for (int i=0; i<8; ++i) { str.append(raw & 0x01); @@ -204,11 +204,11 @@ public class Converter { * @param raw the byte array to convert * @return a hex String */ - public static String toHexString(byte[][] raw){ + public static String toHexString(byte[][] raw) { StringBuilder ret = new StringBuilder(); - for(byte[] a : raw){ - for(byte b : a){ + for (byte[] a : raw) { + for (byte b : a) { ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]); ret.append(HEX_CHARS[(int) b & 0x0F ]); } @@ -217,11 +217,11 @@ public class Converter { return ret.toString(); } - public static String toHexStringByColumn(byte[][] raw){ + public static String toHexStringByColumn(byte[][] raw) { StringBuilder ret = new StringBuilder(); - for(int col=0; col>> 0x04)& 0x0F ]); ret.append(HEX_CHARS[(int) raw[row][col] & 0x0F ]); } @@ -236,12 +236,12 @@ public class Converter { * @param raw the byte array to convert * @return a hex String */ - public static String toHexString(byte[] raw){ + public static String toHexString(byte[] raw) { StringBuilder ret = new StringBuilder(); - for(byte b : raw){ - ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]); - ret.append(HEX_CHARS[(int) b & 0x0F ]); + for (byte b : raw) { + ret.append(HEX_CHARS[(int) (b >>> 0x04) & 0x0F]); + ret.append(HEX_CHARS[(int) b & 0x0F]); } return ret.toString(); @@ -253,9 +253,9 @@ public class Converter { * @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 ]; + public static String toHexString(byte raw) { + String ret = "" +HEX_CHARS[(int) (raw >>> 0x04)& 0x0F ]; + ret += "" +HEX_CHARS[(int) raw & 0x0F ]; return ret; } @@ -266,10 +266,10 @@ public class Converter { * @param raw the byte to convert * @return a String with 1's and 0's */ - public static String toString(byte raw){ + public static String toString(byte raw) { StringBuilder ret = new StringBuilder(); - for(int i=128; i>0 ;i=( i<1 ? 0 : i/2 ) ){ - ret.append(( (raw & i) == 0 ? '0' : '1')); + for (int i=128; i>0; i=(i<1 ? 0 : i/2)) { + ret.append(((raw & i) == 0 ? '0' : '1')); } return ret.toString(); } @@ -280,11 +280,11 @@ public class Converter { * @param raw the byte array to convert * @return a String with 1's and 0's */ - public static String toString(byte[] raw){ + public static String toString(byte[] raw) { StringBuilder ret = new StringBuilder(); - for(byte b : raw){ - for(int i=128; i>0 ;i=( i<1 ? 0 : i/2 ) ){ - ret.append(( (b & i) == 0 ? '0' : '1')); + for (byte b : raw) { + for (int i=128; i>0; i=(i<1 ? 0 : i/2)) { + ret.append(((b & i) == 0 ? '0' : '1')); } } return ret.toString(); @@ -295,11 +295,11 @@ public class Converter { * * @return a comma separated String */ - public static String toString(Map map){ + public static String toString(Map map) { StringBuilder tmp = new StringBuilder(); tmp.append("{"); Iterator it = map.keySet().iterator(); - while(it.hasNext()){ + while (it.hasNext()) { Object key = it.next(); Object value = map.get(key); tmp.append(key); @@ -312,7 +312,7 @@ public class Converter { else tmp.append("null"); - if(it.hasNext()) + if (it.hasNext()) tmp.append(", "); } tmp.append('}'); @@ -325,7 +325,7 @@ public class Converter { * @param bits the BitSet to convert * @return a Integer */ - public static int toInt(BitSet bits){ + public static int toInt(BitSet bits) { int ret = 0; for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i+1)) { @@ -341,11 +341,11 @@ public class Converter { * @param bits the boolean array to convert * @return a Integer */ - public static int toInt(boolean[] bits){ + 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); + if (bits[i])ret += Math.pow(2, bits.length-i-1); } return ret; @@ -357,7 +357,7 @@ public class Converter { * @param b is the byte to convert * @return the integer value of the byte */ - public static int toInt(byte b){ + public static int toInt(byte b) { return (int)(b & 0xff); } @@ -367,9 +367,9 @@ public class Converter { * @param b is the byte array of size 1-4 * @return the int value of the byte array */ - public static int toInt(byte[] b){ + public static int toInt(byte[] b) { int i = 0; - switch (b.length){ + switch (b.length) { default: case 4: i |= 0xFF000000 & (b[3] << 24); case 3: i |= 0x00FF0000 & (b[2] << 16); @@ -386,11 +386,11 @@ public class Converter { * @param num the Integer to convert * @return a BitSet object */ - public static BitSet toBitSet(int num){ + public static BitSet toBitSet(int num) { BitSet ret = new BitSet(); String tmp = Integer.toBinaryString(num); - for(int i=0; i T fromString(String data, Class c){ - if(data == null || data.isEmpty()) + 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) Boolean.valueOf(data); - else if(c == boolean.class) return (T) Boolean.valueOf(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)) + 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) Boolean.valueOf(data); + else if (c == boolean.class) return (T) Boolean.valueOf(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){ + } catch (Exception e) { e.printStackTrace(); } return null; @@ -434,15 +434,15 @@ public class Converter { /** * Replaces reserved and unsafe characters in URLs with hex values */ - public static String urlEncode( String str ){ + 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' || + 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) ); + c=='*' || c=='\'' || c=='(' || c==')' || c==',') + out.append(c); + else { + out.append('%').append(toHexString((byte)c)); } } @@ -452,16 +452,16 @@ public class Converter { /** * Replaces hex values from a URL with the proper characters */ - public static String urlDecode( String str ){ + public static String urlDecode(String str) { StringBuilder out = new StringBuilder(); char[] array = str.toCharArray(); - for( int i=0; i= pow){ + if (tmpNum >= pow) { long numberAtIndex = tmpNum/pow; // The number at position 3 tmpNum -= numberAtIndex*pow; - buffer.append( convert((int)numberAtIndex) ).append(" "); - buffer.append( NUMERIC_STRINGS.get( pow ) ).append(" "); + buffer.append(convert((int)numberAtIndex)).append(" "); + buffer.append(NUMERIC_STRINGS.get(pow)).append(" "); } } - if (tmpNum >= 20){ // second number in the integer + if (tmpNum >= 20) { // second number in the integer long numberAtIndex = ((tmpNum % 100)/10)*10; // The number at position 2 tmpNum -= numberAtIndex; - buffer.append( NUMERIC_STRINGS.get(numberAtIndex) ).append(" "); + buffer.append(NUMERIC_STRINGS.get(numberAtIndex)).append(" "); } if (NUMERIC_STRINGS.containsKey(tmpNum)) buffer.append(NUMERIC_STRINGS.get(tmpNum)); diff --git a/src/zutil/converter/WGS84Converter.java b/src/zutil/converter/WGS84Converter.java index 29f5b7b..3feebbd 100755 --- a/src/zutil/converter/WGS84Converter.java +++ b/src/zutil/converter/WGS84Converter.java @@ -25,12 +25,12 @@ 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")); + 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")); } /** @@ -39,31 +39,31 @@ public class WGS84Converter { * @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){ + 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")) + 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.\\\"]*")){ + 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){ + if (tmp.length > 2) { sec = Float.parseFloat(tmp[2]); } } // 3444.0000S 13521.0000E - else if(coordinate.matches("[0-9]{4,5}.[0-9]*[NSEW]")){ + else if (coordinate.matches("[0-9]{4,5}.[0-9]*[NSEW]")) { 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]*")){ + else if (coordinate.matches("\\-?[0-9]{2,3}.[0-9]*")) { return Float.parseFloat(coordinate); } diff --git a/src/zutil/db/DBConnection.java b/src/zutil/db/DBConnection.java index c9ef58b..836f709 100755 --- a/src/zutil/db/DBConnection.java +++ b/src/zutil/db/DBConnection.java @@ -56,7 +56,7 @@ public class DBConnection implements Closeable{ */ public DBConnection(String jndi) throws NamingException, SQLException{ InitialContext ctx = new InitialContext(); - DataSource ds = (DataSource)ctx.lookup("java:comp/env/"+jndi); + DataSource ds = (DataSource)ctx.lookup("java:comp/env/" + jndi); this.conn = ds.getConnection(); } @@ -83,7 +83,7 @@ public class DBConnection implements Closeable{ */ public DBConnection(DBMS dbms, String url, String db, String user, String password) throws Exception{ String dbms_name = initDriver(dbms); - conn = DriverManager.getConnection ("jdbc:"+dbms_name+"://"+url+"/"+db, user, password); + conn = DriverManager.getConnection ("jdbc:" + dbms_name + "://" + url + "/" + db, user, password); } /** @@ -94,13 +94,13 @@ public class DBConnection implements Closeable{ */ public DBConnection(DBMS dbms, String db) throws Exception{ String dbms_name = initDriver(dbms); - conn = DriverManager.getConnection ("jdbc:"+dbms_name+":"+db); + conn = DriverManager.getConnection ("jdbc:" + dbms_name + ":" + db); } /** * @return the underlying connection */ - public Connection getConnection(){ + public Connection getConnection() { return conn; } @@ -111,7 +111,7 @@ public class DBConnection implements Closeable{ * @return the protocol name of the DBMS */ public static String initDriver(DBMS db) throws InstantiationException, IllegalAccessException, ClassNotFoundException{ - switch(db){ + switch(db) { case MySQL: Class.forName("com.mysql.jdbc.Driver").newInstance(); DriverManager.setLoginTimeout(10); @@ -127,10 +127,10 @@ public class DBConnection implements Closeable{ /** * @return the last inserted id or -1 if there was an error */ - public long getLastInsertID(){ - try{ + public long getLastInsertID() { + try { return exec("SELECT LAST_INSERT_ID()", new SimpleSQLResult<>()); - }catch(SQLException e){ + } catch (SQLException e) { logger.log(Level.WARNING, null, e); } return -1; @@ -138,17 +138,17 @@ public class DBConnection implements Closeable{ /** * @return the last inserted id or -1 if there was an error */ - public long getLastInsertID(Statement stmt){ + public long getLastInsertID(Statement stmt) { ResultSet result = null; - try{ + try { result = stmt.getGeneratedKeys(); - if(result != null){ + if (result != null) { return new SimpleSQLResult().handleQueryResult(stmt, result); } - }catch(SQLException e){ + } catch (SQLException e) { logger.log(Level.WARNING, null, e); } finally { - if(result != null) { + if (result != null) { try { result.close(); } catch (SQLException e) { @@ -179,7 +179,7 @@ public class DBConnection implements Closeable{ * @return update count or -1 if the query is not an update query */ public int exec(String query) throws SQLException { - PreparedStatement stmt = getPreparedStatement( query ); + PreparedStatement stmt = getPreparedStatement(query); return exec(stmt); } @@ -190,10 +190,10 @@ public class DBConnection implements Closeable{ * @return update count or -1 if the query is not an update query */ public static int exec(PreparedStatement stmt) throws SQLException { - Integer ret = exec(stmt, new SQLResultHandler(){ + Integer ret = exec(stmt, new SQLResultHandler() { public Integer handleQueryResult(Statement stmt, ResultSet result) { try { - if(stmt != null) + if (stmt != null) return stmt.getUpdateCount(); else return -1; @@ -204,7 +204,7 @@ public class DBConnection implements Closeable{ } }); - if(ret != null) + if (ret != null) return ret; return -1; } @@ -217,7 +217,7 @@ public class DBConnection implements Closeable{ * @return update count or -1 if the query is not an update query */ public T exec(String query, SQLResultHandler handler) throws SQLException { - PreparedStatement stmt = getPreparedStatement( query ); + PreparedStatement stmt = getPreparedStatement(query); return exec(stmt, handler); } @@ -229,24 +229,24 @@ public class DBConnection implements Closeable{ * @return the object from the handler */ public static T exec(PreparedStatement stmt, SQLResultHandler handler) { - try{ + try { // Execute boolean isResultSet = stmt.execute(); // Handle result - if( handler != null ){ + if (handler != null) { ResultSet result = null; - try{ - if(isResultSet){ + try { + if (isResultSet) { result = stmt.getResultSet(); return handler.handleQueryResult(stmt, result); } else return null; - }catch(SQLException e){ + } catch(SQLException e) { logger.log(Level.WARNING, null, e); - }finally{ - if(result != null){ + } finally { + if (result != null) { try { result.close(); } catch (SQLException e) { @@ -255,7 +255,7 @@ public class DBConnection implements Closeable{ } } } - }catch(SQLException e){ + } catch (SQLException e) { logger.log(Level.WARNING, null, e); // Cleanup } finally { @@ -277,10 +277,10 @@ public class DBConnection implements Closeable{ * @return a array of ints representing the number of updates for each batch statements */ public static int[] execBatch(PreparedStatement stmt) throws SQLException{ - try{ + try { // Execute return stmt.executeBatch(); - }catch(SQLException e){ + } catch (SQLException e) { logger.log(Level.WARNING, null, e); // Cleanup } finally { @@ -300,8 +300,8 @@ public class DBConnection implements Closeable{ * * @param pool is the pool */ - protected void setPool(DBConnectionPool pool){ - if( pool != null ) + protected void setPool(DBConnectionPool pool) { + if (pool != null) pool.removeConnection(this); this.pool = pool; } @@ -311,11 +311,11 @@ public class DBConnection implements Closeable{ * * @return true or false depending on the validity of the connection */ - public boolean valid(){ + public boolean valid() { try { conn.getMetaData(); return !conn.isClosed(); - }catch (Exception e) { + } catch (Exception e) { return false; } } @@ -323,12 +323,12 @@ public class DBConnection implements Closeable{ /** * Disconnects from the database or releases the connection back to the pool */ - public void close(){ - if(pool != null){ + public void close() { + if (pool != null) { pool.releaseConnection(this); conn = null; } - else{ + else { forceClose(); } } @@ -336,10 +336,10 @@ public class DBConnection implements Closeable{ /** * Disconnects from the database */ - public void forceClose(){ + public void forceClose() { if (conn != null) { try { - if( !conn.isClosed() ) + if (!conn.isClosed()) conn.close(); } catch (SQLException e) { logger.log(Level.WARNING, null, e); @@ -348,7 +348,7 @@ public class DBConnection implements Closeable{ } } - public boolean equals(Object o){ + public boolean equals(Object o) { return conn.equals(o); } } diff --git a/src/zutil/db/DBQueue.java b/src/zutil/db/DBQueue.java index d2bf492..f1ad14b 100755 --- a/src/zutil/db/DBQueue.java +++ b/src/zutil/db/DBQueue.java @@ -58,12 +58,12 @@ public class DBQueue implements Queue{ * @param db is the connection to the DB * @param table is the name of the table */ - public DBQueue(DBConnection db, String table){ + public DBQueue(DBConnection db, String table) { this.db = db; this.table = table; } - public boolean add(Object arg0){ + public boolean add(Object arg0) { try { PreparedStatement sql = db.getPreparedStatement("INSERT INTO ? (data) VALUES(?)"); sql.setObject(1, table); @@ -86,7 +86,7 @@ public class DBQueue implements Queue{ public synchronized E peek() { try { - return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler(){ + return db.exec("SELECT * FROM " + table + " LIMIT 1", new SQLResultHandler() { public E handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{ if (rs.next()) try { @@ -105,14 +105,14 @@ public class DBQueue implements Queue{ public synchronized E poll() { try { - return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler(){ + return db.exec("SELECT * FROM " + table + " LIMIT 1", new SQLResultHandler() { public E handleQueryResult(Statement stmt, ResultSet rs) { - try{ - if (rs.next()) { - db.exec("DELETE FROM "+table+" WHERE id="+rs.getInt("id")+" LIMIT 1"); - return (E) Converter.toObject(rs.getBytes("data")); - } - }catch(Exception e){ + try { + if (rs.next()) { + db.exec("DELETE FROM " + table + " WHERE id=" + rs.getInt("id") + " LIMIT 1"); + return (E) Converter.toObject(rs.getBytes("data")); + } + } catch (Exception e) { e.printStackTrace(MultiPrintStream.out); } return null; @@ -135,7 +135,7 @@ public class DBQueue implements Queue{ public void clear() { try { - db.exec("TRUNCATE TABLE `"+table+"`"); + db.exec("TRUNCATE TABLE `" + table + "`"); } catch (SQLException e) { e.printStackTrace(MultiPrintStream.out); } @@ -143,7 +143,7 @@ public class DBQueue implements Queue{ public boolean contains(Object arg0) { try { - return db.exec("SELECT data FROM "+table+" WHERE data='"+Converter.toBytes(arg0)+"' LIMIT 1", new SQLResultHandler(){ + return db.exec("SELECT data FROM " + table + " WHERE data='" + Converter.toBytes(arg0) + "' LIMIT 1", new SQLResultHandler() { public Boolean handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{ return rs.next(); } @@ -170,7 +170,7 @@ public class DBQueue implements Queue{ public synchronized boolean remove(Object arg0) { try { - db.exec("DELETE FROM "+table+" WHERE data='"+Converter.toBytes(arg0)+"' LIMIT 1"); + db.exec("DELETE FROM " + table + " WHERE data='" + Converter.toBytes(arg0) + "' LIMIT 1"); return true; } catch (Exception e) { e.printStackTrace(MultiPrintStream.out); @@ -190,7 +190,7 @@ public class DBQueue implements Queue{ public int size() { try { - return db.exec("SELECT count(*) FROM "+table, new SQLResultHandler(){ + return db.exec("SELECT count(*) FROM " +table, new SQLResultHandler() { public Integer handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{ if (rs.next()) return rs.getInt(1); diff --git a/src/zutil/db/DBUpgradeHandler.java b/src/zutil/db/DBUpgradeHandler.java index 22433d6..b7185e0 100755 --- a/src/zutil/db/DBUpgradeHandler.java +++ b/src/zutil/db/DBUpgradeHandler.java @@ -55,13 +55,13 @@ public class DBUpgradeHandler { private HashSet ignoredTablesSet; - public DBUpgradeHandler(DBConnection reference){ + public DBUpgradeHandler(DBConnection reference) { this.tableRenameMap = new HashMap<>(); this.ignoredTablesSet = new HashSet<>(); this.reference = reference; } - public void setTargetDB(DBConnection db){ + public void setTargetDB(DBConnection db) { this.target = db; } @@ -71,14 +71,14 @@ public class DBUpgradeHandler { * @param oldTableName current name of the table * @param newTableName new name that old table will be renamed to. */ - public void addTableRenameMapping(String oldTableName, String newTableName){ + public void addTableRenameMapping(String oldTableName, String newTableName) { this.tableRenameMap.put(oldTableName, newTableName); } /** * @param table a table name that will be ignored from the upgrade procedure */ - public void addIgnoredTable(String table){ + public void addIgnoredTable(String table) { ignoredTablesSet.add(table); } @@ -89,7 +89,7 @@ public class DBUpgradeHandler { * * @param enable true to enable forced upgrade */ - public void setForcedDBUpgrade(boolean enable){ + public void setForcedDBUpgrade(boolean enable) { this.forceUpgradeEnabled = enable; } @@ -106,7 +106,7 @@ public class DBUpgradeHandler { logger.fine("Committing upgrade transaction..."); target.getConnection().commit(); - } catch(SQLException e){ + } catch(SQLException e) { target.getConnection().rollback(); throw e; } finally { @@ -115,7 +115,7 @@ public class DBUpgradeHandler { } private void upgradeRenameTables() throws SQLException { - if(tableRenameMap.size() > 0) { + if (tableRenameMap.size() > 0) { List targetTables = getTableList(target); for (String oldTableName : tableRenameMap.keySet()) { @@ -133,8 +133,8 @@ public class DBUpgradeHandler { List refTables = getTableList(reference); List targetTables = getTableList(target); - for(String table : refTables){ - if(!targetTables.contains(table)){ + for (String table : refTables) { + if (!targetTables.contains(table)) { logger.fine(String.format("Creating new table: '%s'", table)); // Get reference create sql String sql = getTableSql(reference, table); @@ -148,8 +148,8 @@ public class DBUpgradeHandler { List refTables = getTableList(reference); List targetTables = getTableList(target); - for(String table : targetTables){ - if(!refTables.contains(table)){ + for (String table : targetTables) { + if (!refTables.contains(table)) { logger.fine(String.format("Dropping table: '%s'", table)); target.exec("DROP TABLE " + table); } @@ -160,8 +160,8 @@ public class DBUpgradeHandler { List refTables = getTableList(reference); List targetTables = getTableList(target); - for(String table : targetTables){ - if(refTables.contains(table)){ + for (String table : targetTables) { + if (refTables.contains(table)) { // Get reference structure List refStruct = getColumnList(reference, table); // Get target structure @@ -169,12 +169,12 @@ public class DBUpgradeHandler { // Check unnecessary columns boolean execForcedUpgrade = false; - for(DBColumn column : targetStruct) { - if(refStruct.contains(column)) { + for (DBColumn column : targetStruct) { + if (refStruct.contains(column)) { DBColumn refColumn = refStruct.get(refStruct.indexOf(column)); // Check if the columns have the same type - if(!column.type.equals(refColumn.type)){ - if(forceUpgradeEnabled) + if (!column.type.equals(refColumn.type)) { + if (forceUpgradeEnabled) execForcedUpgrade = true; else logger.warning(String.format( @@ -193,9 +193,9 @@ public class DBUpgradeHandler { } // Do a forced upgrade where we create a new table and migrate the old data - if(execForcedUpgrade){ + if (execForcedUpgrade) { // Backup table - String backupTable = table+"_temp"; + String backupTable = table + "_temp"; logger.fine(String.format("Forced Upgrade: Backing up table: '%s' to: '%s'", table, backupTable)); target.exec(String.format("ALTER TABLE %s RENAME TO %s", table, backupTable)); @@ -216,17 +216,17 @@ public class DBUpgradeHandler { target.exec("DROP TABLE " + backupTable); } // Do a soft upgrade, add missing columns - else{ + else { // Add new columns - for(DBColumn column : refStruct) { - if(!targetStruct.contains(column)) { + for (DBColumn column : refStruct) { + if (!targetStruct.contains(column)) { logger.fine(String.format("Adding column '%s.%s'", table, column.name)); target.exec( String.format("ALTER TABLE %s ADD COLUMN %s %s %s%s%s", table, column.name, column.type, - (column.defaultValue != null ? " DEFAULT '"+column.defaultValue+"'" : ""), + (column.defaultValue != null ? " DEFAULT '" +column.defaultValue + "'" : ""), (column.notNull ? " NOT NULL" : ""), (column.publicKey ? " PRIMARY KEY" : ""))); } @@ -241,9 +241,9 @@ public class DBUpgradeHandler { return db.exec("SELECT name FROM sqlite_master WHERE type='table';", new SQLResultHandler>() { public List handleQueryResult(Statement stmt, ResultSet result) throws SQLException { ArrayList list = new ArrayList<>(); - while( result.next() ) { + while (result.next()) { String table = result.getString(1); - if(!ignoredTablesSet.contains(table)) + if (!ignoredTablesSet.contains(table)) list.add(result.getString(1)); } return list; @@ -268,12 +268,12 @@ public class DBUpgradeHandler { String defaultValue; boolean publicKey; - public boolean equals(Object obj){ + public boolean equals(Object obj) { return obj instanceof DBColumn && name.equals(((DBColumn)obj).name); } - public String toString(){ + public String toString() { return name; } } @@ -283,7 +283,7 @@ public class DBUpgradeHandler { @Override public List handleQueryResult(Statement stmt, ResultSet result) throws SQLException { ArrayList list = new ArrayList<>(); - while (result.next()){ + while (result.next()) { DBColumn column = new DBColumn(); column.name = result.getString("name"); column.type = result.getString("type"); diff --git a/src/zutil/db/SQLQuery.java b/src/zutil/db/SQLQuery.java index d68f43b..a116440 100644 --- a/src/zutil/db/SQLQuery.java +++ b/src/zutil/db/SQLQuery.java @@ -36,15 +36,15 @@ public class SQLQuery { protected static abstract class SQLQueryItem{ SQLQueryItem root; - protected SQLQueryItem(){} + protected SQLQueryItem() {} - protected void setRoot(SQLQueryItem root){ + protected void setRoot(SQLQueryItem root) { this.root = root; } protected abstract void build(StringBuilder query); - public String toString(){ + public String toString() { StringBuilder query = new StringBuilder(); root.build(query); return query.toString(); @@ -74,27 +74,27 @@ public class SQLQuery { /** * @param params is the columns that you want out of the SELECT query, leave empty for all columns */ - protected SQLSelect(String ...params ){ + protected SQLSelect(String ...params) { setRoot(this); this.params = params; } protected void build(StringBuilder query) { query.append("SELECT "); - if( params == null || params.length <= 0 ) + if (params == null || params.length <= 0) query.append("*"); - else{ - for(int i=0; i */ public static class SQLUpdate extends SQLQueryItem{ - protected SQLUpdate(){ + protected SQLUpdate() { setRoot(this); } @@ -128,7 +128,7 @@ public class SQLQuery { * */ public static class SQLInsert extends SQLQueryItem{ - protected SQLInsert(){ + protected SQLInsert() { setRoot(this); } @@ -146,7 +146,7 @@ public class SQLQuery { * */ public static class SQLDelete extends SQLQueryItem{ - protected SQLDelete(){ + protected SQLDelete() { setRoot(this); } @@ -161,75 +161,80 @@ public class SQLQuery { LinkedList tables = new LinkedList<>(); SQLQueryItem next; - protected SQLFrom(SQLQueryItem root, String ...tables){ + protected SQLFrom(SQLQueryItem root, String ...tables) { setRoot(root); Collections.addAll(this.tables, tables); } - public SQLFrom NATURAL_JOIN(String table){ + public SQLFrom NATURAL_JOIN(String table) { return joinLastTable("NATURAL JOIN", table); } - public SQLFrom NATURAL_JOIN(String ...tables){ + public SQLFrom NATURAL_JOIN(String ...tables) { return joinTable("NATURAL JOIN", tables); } - public SQLFrom JOIN(String table){ + public SQLFrom JOIN(String table) { return joinLastTable("JOIN", table); } - public SQLFrom JOIN(String ...tables){ + public SQLFrom JOIN(String ...tables) { return joinTable("JOIN", tables); } - public SQLFrom UNION(String table){ + public SQLFrom UNION(String table) { return joinLastTable("UNION", table); } - public SQLFrom UNION(String ...tables){ + public SQLFrom UNION(String ...tables) { return joinTable("UNION", tables); } - private SQLFrom joinLastTable(String type, String table){ + private SQLFrom joinLastTable(String type, String table) { String last = tables.getLast(); tables.removeLast(); tables.add(last + " " + type + " " + table); return this; } - private SQLFrom joinTable(String type, String[] tables){ - if( tables.length < 2 ) + private SQLFrom joinTable(String type, String[] tables) { + if (tables.length < 2) return this; + StringBuilder str = new StringBuilder(); - for(int i=0; i conds = new LinkedList<>(); SQLQueryItem next; - protected SQLWhere(SQLQueryItem root){ + protected SQLWhere(SQLQueryItem root) { setRoot(root); } /** * Equals (arg1 = arg2) */ - public SQLWhere EQ(String arg1, String arg2){ + public SQLWhere EQ(String arg1, String arg2) { return cond("=", arg1, arg2); } /** * Not Equal (arg1 != arg2) */ - public SQLWhere NE(String arg1, String arg2){ + public SQLWhere NE(String arg1, String arg2) { return cond("!=", arg1, arg2); } /** * Less than (arg1 < arg2) */ - public SQLWhere LT(String arg1, String arg2){ + public SQLWhere LT(String arg1, String arg2) { return cond("<", arg1, arg2); } /** * Greater than (arg1 > arg2) */ - public SQLWhere GT(String arg1, String arg2){ + public SQLWhere GT(String arg1, String arg2) { return cond(">", arg1, arg2); } /** * Less than or equal (arg1 <= arg2) */ - public SQLWhere LE(String arg1, String arg2){ + public SQLWhere LE(String arg1, String arg2) { return cond("<=", arg1, arg2); } /** * Greater than or equal (arg1 >= arg2) */ - public SQLWhere GE(String arg1, String arg2){ + public SQLWhere GE(String arg1, String arg2) { return cond(">=", arg1, arg2); } - private SQLWhere cond(String cond, String arg1, String arg2){ + private SQLWhere cond(String cond, String arg1, String arg2) { conds.add(arg1 + cond + arg2); return this; } - public SQLGroupBy GROUP_BY( String ...cols ){ + public SQLGroupBy GROUP_BY(String ...cols) { return (SQLGroupBy) (next = new SQLGroupBy(root, cols)); } - public SQLOrderBy ORDER_BY( String ...cols ){ + public SQLOrderBy ORDER_BY(String ...cols) { return (SQLOrderBy) (next = new SQLOrderBy(root, cols)); } - public SQLLimit LIMIT( long count ){ + public SQLLimit LIMIT(long count) { return (SQLLimit) (next = new SQLLimit(root, count)); } protected void build(StringBuilder query) { query.append(" WHERE "); - if( conds.isEmpty() ) - throw new RuntimeException("The WHERE query item must hav atleast 1 condition!"); - for(int i=0; i{ - protected SQLGroupBy(SQLQueryItem root, String ...cols){ - super( root, cols ); + protected SQLGroupBy(SQLQueryItem root, String ...cols) { + super(root, cols); } - public SQLOrderBy ORDER_BY( String ...cols ){ + public SQLOrderBy ORDER_BY(String ...cols) { return (SQLOrderBy) (next = new SQLOrderBy(root, cols)); } - public SQLLimit LIMIT( long count ){ + public SQLLimit LIMIT(long count) { return (SQLLimit) (next = new SQLLimit(root, count)); } @@ -367,12 +374,12 @@ public class SQLQuery { } public static class SQLOrderBy extends SQLGroupOrderBy{ - protected SQLOrderBy(SQLQueryItem root, String ...cols){ - super( root, cols ); + protected SQLOrderBy(SQLQueryItem root, String ...cols) { + super(root, cols); } - public SQLLimit LIMIT( long count ){ + public SQLLimit LIMIT(long count) { return (SQLLimit) (next = new SQLLimit(root, count)); } @@ -385,36 +392,36 @@ public class SQLQuery { long start; Long count; - protected SQLLimit(SQLQueryItem root, long start){ - setRoot( root ); + protected SQLLimit(SQLQueryItem root, long start) { + setRoot(root); this.start = start; } - public SQLLimit TO( long count ){ + public SQLLimit TO(long count) { this.count = count; return this; } protected void build(StringBuilder query) { - query.append(" LIMIT ").append( start ); - if( count != null ) query.append(' ').append( count ); + query.append(" LIMIT ").append(start); + if (count != null) query.append(' ').append(count); } } //******************************************* - public static SQLSelect SELECT( String ...params ){ - return new SQLSelect( params ); + public static SQLSelect SELECT(String ...params) { + return new SQLSelect(params); } - public static SQLUpdate UPDATE(){ + public static SQLUpdate UPDATE() { return new SQLUpdate(); } - public static SQLInsert INSERT(){ + public static SQLInsert INSERT() { return new SQLInsert(); } - public static SQLDelete DELETE(){ + public static SQLDelete DELETE() { return new SQLDelete(); } diff --git a/src/zutil/db/bean/DBBean.java b/src/zutil/db/bean/DBBean.java index f82f766..ff2eba5 100755 --- a/src/zutil/db/bean/DBBean.java +++ b/src/zutil/db/bean/DBBean.java @@ -116,7 +116,7 @@ public abstract class DBBean { protected ReentrantLock readLock; - protected DBBean(){ + protected DBBean() { DBBeanConfig.getBeanConfig(this.getClass()); saveLock = new ReentrantLock(); readLock = new ReentrantLock(); @@ -221,7 +221,7 @@ public abstract class DBBean { DBBeanCache.add(this); // Save sub beans, after we get the parent beans id - if (recursive){ + if (recursive) { for (DBBeanSubBeanConfig subBeanField : config.getSubBeans()) { if (this.id == null) throw new SQLException("Unknown parent bean id"); @@ -242,7 +242,7 @@ public abstract class DBBean { // Save links in link table String sql; if (!subBeanField.isStandaloneLinkTable()) // Sub Bean and link table is the same table - sql = "UPDATE "+ subBeanField.getLinkTableName() +" SET "+ subBeanField.getParentIdColumnName() +"=? WHERE "+ subIdCol +"=?"; + sql = "UPDATE " + subBeanField.getLinkTableName() + " SET " + subBeanField.getParentIdColumnName() + "=? WHERE " + subIdCol + "=?"; else sql = "INSERT INTO " + subBeanField.getLinkTableName() + " (" + subBeanField.getParentIdColumnName() + ", " + subIdCol + ") SELECT ?,? " + "WHERE NOT EXISTS(SELECT 1 FROM " + subBeanField.getLinkTableName() + " WHERE " + subBeanField.getParentIdColumnName() + "=? AND " + subIdCol + "=?);"; @@ -292,8 +292,8 @@ public abstract class DBBean { */ public void delete(DBConnection db, boolean recursive) throws SQLException{ Class c = this.getClass(); - DBBeanConfig config = DBBeanConfig.getBeanConfig( c ); - if( this.getId() == null ) + DBBeanConfig config = DBBeanConfig.getBeanConfig(c); + if (this.getId() == null) throw new NullPointerException("ID field is null! (Has the bean been saved?)"); // Delete sub beans @@ -303,10 +303,10 @@ public abstract class DBBean { for (DBBean subObj : list) { // Delete links if (subBeanField.isStandaloneLinkTable()) { - String sql = "DELETE FROM "+subBeanField.getLinkTableName()+" WHERE "+subBeanField.getParentIdColumnName()+"=?"; - logger.finest("Delete link, query: "+sql); - PreparedStatement stmt = db.getPreparedStatement( sql ); - stmt.setLong(1, this.getId() ); + String sql = "DELETE FROM " + subBeanField.getLinkTableName() + " WHERE " + subBeanField.getParentIdColumnName() + "=?"; + logger.finest("Delete link, query: " + sql); + PreparedStatement stmt = db.getPreparedStatement(sql); + stmt.setLong(1, this.getId()); DBConnection.exec(stmt); } // Delete sub beans @@ -317,10 +317,10 @@ public abstract class DBBean { } // Delete this bean from DB - String sql = "DELETE FROM "+config.getTableName()+" WHERE "+config.getIdColumnName()+"=?"; - logger.finest("Delete Bean("+c.getName()+", id: "+this.getId()+") query: "+sql); - PreparedStatement stmt = db.getPreparedStatement( sql ); - stmt.setLong(1, this.getId() ); + String sql = "DELETE FROM " + config.getTableName() + " WHERE " + config.getIdColumnName() + "=?"; + logger.finest("Delete Bean(" + c.getName() + ", id: " + this.getId() + ") query: " + sql); + PreparedStatement stmt = db.getPreparedStatement(sql); + stmt.setLong(1, this.getId()); DBConnection.exec(stmt); // Clear cache and reset id @@ -339,13 +339,13 @@ public abstract class DBBean { */ public static List load(DBConnection db, Class c) throws SQLException { // Initiate a BeanConfig if there is non - DBBeanConfig config = DBBeanConfig.getBeanConfig( c ); + DBBeanConfig config = DBBeanConfig.getBeanConfig(c); // Generate query - String sql = "SELECT * FROM "+config.getTableName(); - logger.finest("Load all Beans("+c.getName()+") query: "+sql); - PreparedStatement stmt = db.getPreparedStatement( sql ); + String sql = "SELECT * FROM " +config.getTableName(); + logger.finest("Load all Beans(" + c.getName() + ") query: " + sql); + PreparedStatement stmt = db.getPreparedStatement(sql); // Run query - return DBConnection.exec(stmt, DBBeanSQLResultHandler.createList(c, db) ); + return DBConnection.exec(stmt, DBBeanSQLResultHandler.createList(c, db)); } /** @@ -360,14 +360,14 @@ public abstract class DBBean { */ public static T load(DBConnection db, Class c, long id) throws SQLException { // Initiate a BeanConfig if there is non - DBBeanConfig config = DBBeanConfig.getBeanConfig( c ); + DBBeanConfig config = DBBeanConfig.getBeanConfig(c); // Generate query - String sql = "SELECT * FROM "+config.getTableName()+" WHERE "+config.getIdColumnName()+"=? LIMIT 1"; - logger.finest("Load Bean("+c.getName()+", id: "+id+") query: "+sql); - PreparedStatement stmt = db.getPreparedStatement( sql ); - stmt.setObject(1, id ); + String sql = "SELECT * FROM " + config.getTableName() + " WHERE " + config.getIdColumnName() + "=? LIMIT 1"; + logger.finest("Load Bean(" + c.getName() + ", id: " + id + ") query: " + sql); + PreparedStatement stmt = db.getPreparedStatement(sql); + stmt.setObject(1, id); // Run query - T obj = DBConnection.exec(stmt, DBBeanSQLResultHandler.create(c, db) ); + T obj = DBConnection.exec(stmt, DBBeanSQLResultHandler.create(c, db)); return obj; } @@ -391,7 +391,7 @@ public abstract class DBBean { query.append(classToDBType(Long.class)); query.append(" PRIMARY KEY AUTO_INCREMENT, "); - for( DBBeanFieldConfig field : config.getFields() ){ + for (DBBeanFieldConfig field : config.getFields()) { query.append(" "); query.append(field.getName()); query.append(classToDBType(c)); @@ -400,33 +400,33 @@ public abstract class DBBean { query.delete(query.length()-2, query.length()); query.append(")"); - logger.finest("Create Bean("+c.getName()+") query: " + db.toString()); + logger.finest("Create Bean(" + c.getName() + ") query: " + db.toString()); PreparedStatement stmt = db.getPreparedStatement(db.toString()); // Execute the SQL DBConnection.exec(stmt); } - private static String classToDBType(Class c){ - if( c == String.class) return "CLOB"; // TEXT - else if(c == Short.class) return "SMALLINT"; - else if(c == short.class) return "SMALLINT"; - else if(c == Integer.class) return "INTEGER"; - else if(c == int.class) return "INTEGER"; - else if(c == BigInteger.class) return "BIGINT"; - else if(c == Long.class) return "DECIMAL"; - else if(c == long.class) return "DECIMAL"; - else if(c == Float.class) return "DOUBLE"; - else if(c == float.class) return "DOUBLE"; - else if(c == Double.class) return "DOUBLE"; - else if(c == double.class) return "DOUBLE"; - else if(c == BigDecimal.class) return "DECIMAL"; - else if(c == Boolean.class) return "BOOLEAN"; - else if(c == boolean.class) return "BOOLEAN"; - else if(c == Byte.class) return "BINARY(1)"; - else if(c == byte.class) return "BINARY(1)"; - else if(c == Timestamp.class) return "DATETIME"; - else if(DBBean.class.isAssignableFrom(c)) + private static String classToDBType(Class c) { + if ( c == String.class) return "CLOB"; // TEXT + else if (c == Short.class) return "SMALLINT"; + else if (c == short.class) return "SMALLINT"; + else if (c == Integer.class) return "INTEGER"; + else if (c == int.class) return "INTEGER"; + else if (c == BigInteger.class) return "BIGINT"; + else if (c == Long.class) return "DECIMAL"; + else if (c == long.class) return "DECIMAL"; + else if (c == Float.class) return "DOUBLE"; + else if (c == float.class) return "DOUBLE"; + else if (c == Double.class) return "DOUBLE"; + else if (c == double.class) return "DOUBLE"; + else if (c == BigDecimal.class) return "DECIMAL"; + else if (c == Boolean.class) return "BOOLEAN"; + else if (c == boolean.class) return "BOOLEAN"; + else if (c == Byte.class) return "BINARY(1)"; + else if (c == byte.class) return "BINARY(1)"; + else if (c == Timestamp.class) return "DATETIME"; + else if (DBBean.class.isAssignableFrom(c)) return classToDBType(Long.class); return null; } @@ -434,11 +434,11 @@ public abstract class DBBean { /** * @return the bean id or null if the bean has not bean saved yet */ - public final Long getId(){ + public final Long getId() { return id; } - final void setId(Long id){ + final void setId(Long id) { this.id = id; } @@ -449,5 +449,5 @@ public abstract class DBBean { /** * Will be called whenever the bean has been updated from the database. */ - protected void postUpdateAction(){} + protected void postUpdateAction() {} } diff --git a/src/zutil/db/bean/DBBeanConfig.java b/src/zutil/db/bean/DBBeanConfig.java index 1e84110..60fed4f 100755 --- a/src/zutil/db/bean/DBBeanConfig.java +++ b/src/zutil/db/bean/DBBeanConfig.java @@ -50,27 +50,27 @@ class DBBeanConfig{ private ArrayList subBeanFields = new ArrayList<>(); - private DBBeanConfig(){ } + private DBBeanConfig() { } /** * @return the configuration object for the specified class */ - public static DBBeanConfig getBeanConfig(Class c){ - if( !beanConfigs.containsKey( c.getName() ) ) - initBeanConfig( c ); - return beanConfigs.get( c.getName() ); + public static DBBeanConfig getBeanConfig(Class c) { + if (!beanConfigs.containsKey(c.getName())) + initBeanConfig(c); + return beanConfigs.get(c.getName()); } /** * Caches the fields */ - private static void initBeanConfig(Class c){ + private static void initBeanConfig(Class c) { DBBeanConfig config = new DBBeanConfig(); // Find the table name DBBean.DBTable tableAnn = c.getAnnotation(DBBean.DBTable.class); - if( tableAnn != null ){ + if (tableAnn != null) { config.tableName = tableAnn.value(); config.idColumnName = tableAnn.idColumn(); } else { @@ -79,14 +79,14 @@ class DBBeanConfig{ } // Add the fields in the bean and all the super classes fields - for(Class cc = c; cc != DBBean.class ;cc = cc.getSuperclass()){ + for (Class cc = c; cc != DBBean.class; cc = cc.getSuperclass()) { Field[] fields = cc.getDeclaredFields(); - for( Field field : fields ){ + for (Field field : fields) { int mod = field.getModifiers(); - if( !Modifier.isTransient( mod ) && - !Modifier.isFinal( mod ) && - !Modifier.isStatic( mod ) && - !config.fields.contains( field )){ + if (!Modifier.isTransient(mod) && + !Modifier.isFinal(mod) && + !Modifier.isStatic(mod) && + !config.fields.contains(field)) { if (List.class.isAssignableFrom(field.getType()) && field.getAnnotation(DBBean.DBLinkTable.class) != null) config.subBeanFields.add(new DBBeanSubBeanConfig(field)); @@ -94,7 +94,7 @@ class DBBeanConfig{ config.fields.add(new DBBeanFieldConfig(field)); } } - if( tableAnn == null || !tableAnn.superBean() ) + if (tableAnn == null || !tableAnn.superBean()) break; } @@ -102,19 +102,19 @@ class DBBeanConfig{ } - public String getTableName(){ + public String getTableName() { return tableName; } - public String getIdColumnName(){ + public String getIdColumnName() { return idColumnName; } - public List getFields(){ + public List getFields() { return fields; } - public List getSubBeans(){ + public List getSubBeans() { return subBeanFields; } @@ -123,31 +123,31 @@ class DBBeanConfig{ private Field field; private String fieldName; - private DBBeanFieldConfig(Field field){ + private DBBeanFieldConfig(Field field) { this.field = field; - if( !Modifier.isPublic( field.getModifiers())) + if (!Modifier.isPublic(field.getModifiers())) field.setAccessible(true); DBBean.DBColumn colAnnotation = field.getAnnotation(DBBean.DBColumn.class); - if(colAnnotation != null) + if (colAnnotation != null) fieldName = colAnnotation.value(); else fieldName = field.getName(); } - public String getName(){ + public String getName() { return fieldName; } - public Class getType(){ + public Class getType() { return field.getType(); } public Object getValue(Object obj) { try { return field.get(obj); - } catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } return null; @@ -175,7 +175,7 @@ class DBBeanConfig{ else field.set(obj, fieldValue); } - } catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } } @@ -188,7 +188,7 @@ class DBBeanConfig{ private DBBeanConfig subBeanConfig; private String parentIdCol; - private DBBeanSubBeanConfig(Field field){ + private DBBeanSubBeanConfig(Field field) { super(field); DBBean.DBLinkTable linkAnnotation = field.getAnnotation(DBBean.DBLinkTable.class); @@ -203,7 +203,7 @@ class DBBeanConfig{ return linkTableName; } - public boolean isStandaloneLinkTable(){ + public boolean isStandaloneLinkTable() { return !linkTableName.equals(subBeanConfig.tableName); } diff --git a/src/zutil/db/bean/DBBeanObjectDSO.java b/src/zutil/db/bean/DBBeanObjectDSO.java index 85fc5f5..1192e67 100755 --- a/src/zutil/db/bean/DBBeanObjectDSO.java +++ b/src/zutil/db/bean/DBBeanObjectDSO.java @@ -91,7 +91,7 @@ public abstract class DBBeanObjectDSO extends DBBean{ - public T getObject(){ + public T getObject() { return cachedObj; } @@ -100,8 +100,8 @@ public abstract class DBBeanObjectDSO extends DBBean{ * * @param obj is the object to set or null to reset the DSO */ - public void setObject(T obj){ - if(obj != null) { + public void setObject(T obj) { + if (obj != null) { type = obj.getClass().getName(); config = null; cachedObj = obj; @@ -112,15 +112,15 @@ public abstract class DBBeanObjectDSO extends DBBean{ } } - public String getObjectClass(){ + public String getObjectClass() { return type; } - public void setObjectClass(Class clazz){ + public void setObjectClass(Class clazz) { setObjectClass(clazz.getName()); } - public void setObjectClass(String clazz){ + public void setObjectClass(String clazz) { if (this.type == null || !this.type.equals(type)) { // TODO: check if clazz is subclass of T setObject(null); @@ -129,15 +129,15 @@ public abstract class DBBeanObjectDSO extends DBBean{ } } - public Configurator getObjectConfigurator(){ + public Configurator getObjectConfigurator() { return new Configurator<>(cachedObj); } - public String toString(){ + public String toString() { Object obj = getObject(); if (obj != null) return obj.toString(); - return "null (DSO: "+ super.toString() +")"; + return "null (DSO: " + super.toString() + ")"; } } diff --git a/src/zutil/db/handler/ListSQLResult.java b/src/zutil/db/handler/ListSQLResult.java index fa2533c..20c2b0c 100755 --- a/src/zutil/db/handler/ListSQLResult.java +++ b/src/zutil/db/handler/ListSQLResult.java @@ -34,9 +34,9 @@ import java.util.List; /** * Adds the result of the query to a List. - * + * * The handler will add the first column of every row to a list. - * + * * @author Ziver */ public class ListSQLResult implements SQLResultHandler> { @@ -46,21 +46,21 @@ public class ListSQLResult implements SQLResultHandler> { /** * Creates a new List. */ - public ListSQLResult(){ + public ListSQLResult() { this.list = new ArrayList<>(); } /** * Uses a existing list that items will be appended on. */ - public ListSQLResult(List l){ + public ListSQLResult(List l) { this.list = l; } public List handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ - while( result.next() ) + while (result.next()) list.add((T)result.getObject(1)); return list; } diff --git a/src/zutil/db/handler/PropertiesSQLResult.java b/src/zutil/db/handler/PropertiesSQLResult.java index 8878fca..e4972e0 100755 --- a/src/zutil/db/handler/PropertiesSQLResult.java +++ b/src/zutil/db/handler/PropertiesSQLResult.java @@ -33,10 +33,10 @@ import java.util.Properties; /** * Adds the result of the query to a Properties object, - * - * The handler sets the first column of the result as + * + * The handler sets the first column of the result as * the key and the second column as the value - * + * * @author Ziver */ public class PropertiesSQLResult implements SQLResultHandler { @@ -46,14 +46,14 @@ public class PropertiesSQLResult implements SQLResultHandler { /** * Creates a new Properties object to be filled */ - public PropertiesSQLResult(){ + public PropertiesSQLResult() { this.prop = new Properties(); } /** * Adds data to a existing Properties object */ - public PropertiesSQLResult(Properties p){ + public PropertiesSQLResult(Properties p) { this.prop = p; } @@ -62,7 +62,7 @@ public class PropertiesSQLResult implements SQLResultHandler { * Is called to handle an result from an query. */ public Properties handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ - while( result.next() ) + while (result.next()) prop.setProperty(result.getString(1), result.getString(2)); return prop; } diff --git a/src/zutil/db/handler/SimpleSQLResult.java b/src/zutil/db/handler/SimpleSQLResult.java index 40c0567..a74ea31 100755 --- a/src/zutil/db/handler/SimpleSQLResult.java +++ b/src/zutil/db/handler/SimpleSQLResult.java @@ -32,7 +32,7 @@ import java.sql.Statement; /** * Returns the first column of the first row from the query - * + * * @author Ziver */ public class SimpleSQLResult implements SQLResultHandler { @@ -44,7 +44,7 @@ public class SimpleSQLResult implements SQLResultHandler { */ @SuppressWarnings("unchecked") public T handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ - if( result.next() ) + if (result.next()) return (T) result.getObject(1); return null; } diff --git a/src/zutil/image/ImageFilterProcessor.java b/src/zutil/image/ImageFilterProcessor.java index 53c8e3a..8151e16 100644 --- a/src/zutil/image/ImageFilterProcessor.java +++ b/src/zutil/image/ImageFilterProcessor.java @@ -40,7 +40,7 @@ public abstract class ImageFilterProcessor { private BufferedImage img; private ProgressListener progress; - public ImageFilterProcessor(BufferedImage img){ + public ImageFilterProcessor(BufferedImage img) { this.img = img; } @@ -48,22 +48,23 @@ public abstract class ImageFilterProcessor { * Sets the listener * @param listener is the listener, null to disable the progress */ - public void setProgressListener(ProgressListener listener){ + public void setProgressListener(ProgressListener listener) { this.progress = listener; } /** * Returns the listener */ - public ProgressListener getProgressListener(){ + public ProgressListener getProgressListener() { return this.progress; } /** * Sets the progress in percent */ - protected void setProgress(double percent){ - if(progress != null) progress.progressUpdate(this, null, percent); + protected void setProgress(double percent) { + if (progress != null) + progress.progressUpdate(this, null, percent); } /** @@ -88,7 +89,7 @@ public abstract class ImageFilterProcessor { int cols = img.getWidth(); int rows = img.getHeight(); - if(cols < 0 || rows < 0){ + if (cols < 0 || rows < 0) { throw new InterruptedException("Image not Loaded!!!"); } @@ -119,16 +120,16 @@ public abstract class ImageFilterProcessor { int[] pixels = img.getRGB(0, 0, cols, rows, null, 0, cols); // Read the pixel data and put it in the data array - for(int y=0; y> 24) & 0xFF); //Red data @@ -151,7 +152,7 @@ public abstract class ImageFilterProcessor { * @param rows is the rows of the image * @return A Image */ - public static BufferedImage convertToImage(int[][][] pixels, int cols, int rows){ + public static BufferedImage convertToImage(int[][][] pixels, int cols, int rows) { int[] data = new int[cols * rows * 4]; //Move the data into the 1D array. Note the @@ -159,8 +160,8 @@ public abstract class ImageFilterProcessor { // bitwise left-shift operators to put the // four 8-bit bytes into each int. int index = 0; - for(int y=0; y height){ + if (keep_aspect) { + if (scale_width * source.getHeight() > height) { scale_width = scale_height; - }else{ + } else { scale_height = scale_width; } } @@ -78,17 +78,17 @@ public class ImageUtil { * @param aspect is the aspect ratio to convert the image to * @return a new image with the specified aspect ratio */ - public static BufferedImage cropToAspectRatio(BufferedImage image, float aspect){ + public static BufferedImage cropToAspectRatio(BufferedImage image, float aspect) { int x = 0, y = 0; int width = image.getWidth(); int height = image.getHeight(); // Check if the width is larger than the heigth - if( width > height ){ + if (width > height) { width = (int) (height * aspect); x = image.getWidth()/2 - width/2; } - else{ + else { height = (int) (width * aspect); y = image.getHeight()/2 - height/2; } @@ -106,7 +106,7 @@ public class ImageUtil { * @param height is the wanted height * @return a new image with the specified width and height */ - public static BufferedImage cropScale(BufferedImage source, int width, int height){ + public static BufferedImage cropScale(BufferedImage source, int width, int height) { float aspect = width/height; BufferedImage tmp = cropToAspectRatio(source, aspect); tmp = scale(tmp, width, height, false); diff --git a/src/zutil/image/RAWImageUtil.java b/src/zutil/image/RAWImageUtil.java index db92a26..a1cf066 100644 --- a/src/zutil/image/RAWImageUtil.java +++ b/src/zutil/image/RAWImageUtil.java @@ -53,11 +53,11 @@ public class RAWImageUtil { */ public static int getPeakValue(int[][][] data, int startX, int startY, int stopX, int stopY) { int peak = 0; - for(int y=startY; y peak) peak = data[y][x][1]; - if(data[y][x][2] > peak) peak = data[y][x][2]; - if(data[y][x][3] > peak) peak = data[y][x][3]; + for (int y=startY; y peak) peak = data[y][x][1]; + if (data[y][x][2] > peak) peak = data[y][x][2]; + if (data[y][x][3] > peak) peak = data[y][x][3]; } } return peak; @@ -74,8 +74,8 @@ public class RAWImageUtil { * @param scale The scale to normalize the image by */ public static void normalize(int[][][] data, int startX, int startY, int stopX, int stopY, double scale) { - for(int y=startY; y 255) + else if (color > 255) return 255; else return color; diff --git a/src/zutil/image/filter/BlurFilter.java b/src/zutil/image/filter/BlurFilter.java index 9dc35c7..6fe6a05 100755 --- a/src/zutil/image/filter/BlurFilter.java +++ b/src/zutil/image/filter/BlurFilter.java @@ -37,7 +37,7 @@ public class BlurFilter extends ImageFilterProcessor{ * Creates a blur effect on the image * @param img The image to blur */ - public BlurFilter(BufferedImage img){ + public BlurFilter(BufferedImage img) { this(img, 10); } @@ -46,7 +46,7 @@ public class BlurFilter extends ImageFilterProcessor{ * @param img The image to blur * @param blur The amount to blur */ - public BlurFilter(BufferedImage img, int blur){ + public BlurFilter(BufferedImage img, int blur) { super(img); blurValue = blur; } @@ -59,17 +59,17 @@ public class BlurFilter extends ImageFilterProcessor{ 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 (redScale > 1) redScale = 1; + else if (redScale < 0) redScale = 0; - if(greenScale > 1) greenScale = 1; - else if(greenScale < 0) greenScale = 0; + if (greenScale > 1) greenScale = 1; + else if (greenScale < 0) greenScale = 0; - if(blueScale > 1) blueScale = 1; - else if(blueScale < 0) blueScale = 0; + if (blueScale > 1) blueScale = 1; + else if (blueScale < 0) blueScale = 0; // Applying the color intensity to the image - for(int y=startY; y */ - public DitheringFilter(BufferedImage img, int[][] palette){ + public DitheringFilter(BufferedImage img, int[][] palette) { super(img); this.palette = palette; } @@ -67,9 +67,9 @@ public class DitheringFilter extends ImageFilterProcessor{ 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 ); + 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 ); + output[y+1][x+1][i] = RAWImageUtil.clip(output[y+1][x+1][i] + (error*1)/16); } } } diff --git a/src/zutil/image/filter/GaussianBlurFilter.java b/src/zutil/image/filter/GaussianBlurFilter.java index 9908f76..80e4e1c 100755 --- a/src/zutil/image/filter/GaussianBlurFilter.java +++ b/src/zutil/image/filter/GaussianBlurFilter.java @@ -28,7 +28,7 @@ import java.awt.image.BufferedImage; /** * Blurs an image whit the Gaussian blur algorithm - * + * * @author Ziver */ public class GaussianBlurFilter extends ConvolutionFilter{ @@ -45,24 +45,24 @@ public class GaussianBlurFilter extends ConvolutionFilter{ this.sigma = sigma; } - protected double[][] generateKernel(){ + 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){ + 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){ + for (int fy=0; fy= 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] ) ]++; + 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); + 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); + private int getMedianIndex(int i) { + if (i < 0) return Math.abs(i); else return i+256; } - private int findMedian(int[] median, int medianCount){ + private int findMedian(int[] median, int medianCount) { int sum = 0; int ret = 0; - for(int i=0; i= medianCount && ret == 0){ + if (sum >= medianCount && ret == 0) { ret = i-256; } } @@ -147,7 +147,7 @@ public class MedianFilter extends ImageFilterProcessor{ private int rows; private int channel; - public SortableARGB(int[][][] data, int cols, int rows, int channel){ + public SortableARGB(int[][][] data, int cols, int rows, int channel) { this.data = data; this.cols = cols; this.rows = rows; @@ -166,7 +166,7 @@ public class MedianFilter extends ImageFilterProcessor{ return data[ getY(i) ][ getX(i) ][ channel ]; } - public void set(int i, Integer o){ + public void set(int i, Integer o) { data[ getY(i) ][ getX(i) ][ channel ] = o; } @@ -181,11 +181,11 @@ public class MedianFilter extends ImageFilterProcessor{ } - private int getX(int a){ + private int getX(int a) { return a % cols; } - private int getY(int a){ + private int getY(int a) { return a / cols; } diff --git a/src/zutil/image/filter/ResizeImage.java b/src/zutil/image/filter/ResizeImage.java index 2ba546c..3249610 100755 --- a/src/zutil/image/filter/ResizeImage.java +++ b/src/zutil/image/filter/ResizeImage.java @@ -40,7 +40,7 @@ public class ResizeImage extends ImageFilterProcessor{ * @param img The image to resize * @param w The new width */ - public ResizeImage(BufferedImage img, int w){ + public ResizeImage(BufferedImage img, int w) { this(img, w, -1); } @@ -51,7 +51,7 @@ public class ResizeImage extends ImageFilterProcessor{ * @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){ + public ResizeImage(BufferedImage img, int w, int h) { super(img); width = w; height = h; @@ -59,10 +59,10 @@ public class ResizeImage extends ImageFilterProcessor{ @Override public int[][][] process(final int[][][] data, int startX, int startY, int stopX, int stopY) { - if(width < 1){ + if (width < 1) { height = (int)(((double)width/(stopX-startX))*(stopY-startY)); } - else if(height < 1){ + else if (height < 1) { width = (int)(((double)height/(stopY-startY))*(stopX-startY)); } @@ -70,9 +70,9 @@ public class ResizeImage extends ImageFilterProcessor{ double xScale = ((double)(stopX-startX)/width); double yScale = ((double)(stopY-startY)/height); - for(int y=0; y radius){ + if (distance > radius) { scale = 0; } - else{ + else { scale = 1-(distance/radius); } diff --git a/src/zutil/io/BufferedBoundaryInputStream.java b/src/zutil/io/BufferedBoundaryInputStream.java index d2d2ad9..17a0cf1 100755 --- a/src/zutil/io/BufferedBoundaryInputStream.java +++ b/src/zutil/io/BufferedBoundaryInputStream.java @@ -62,7 +62,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ * * @param in is the InputStream that the buffer will use */ - public BufferedBoundaryInputStream(InputStream in){ + public BufferedBoundaryInputStream(InputStream in) { this(in, DEFAULT_BUF_SIZE); } @@ -72,7 +72,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ * @param in is the InputStream that the buffer will use * @param buf_size speifies the buffer size */ - public BufferedBoundaryInputStream(InputStream in, int buf_size){ + public BufferedBoundaryInputStream(InputStream in, int buf_size) { super(in); buffer = new byte[buf_size]; } @@ -85,7 +85,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ if (fillBuffer() < 0) return -1; - if(isOnBoundary()) + if (isOnBoundary()) return -1; // boundary return buffer[buf_pos++]; } @@ -132,7 +132,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ /** * @return if the current position in the buffer is a boundary */ - public boolean isOnBoundary(){ + public boolean isOnBoundary() { return buf_bound_pos == buf_pos; } @@ -163,7 +163,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ buf_pos = buf_end; } - if (buf_bound_pos >= 0){ // is boundary in buffer? + if (buf_bound_pos >= 0) { // is boundary in buffer? buf_pos += boundary.length; findNextBoundary(); } @@ -181,7 +181,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ */ public long skip(long n) throws IOException { int leftover = available(); - if(n > leftover){ + if (n > leftover) { buf_pos = buf_end; return leftover; } @@ -192,7 +192,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ /** * Sets the boundary for the stream */ - public void setBoundary(String b){ + public void setBoundary(String b) { this.boundary = b.getBytes(); findNextBoundary(); // redo the search with the new boundary } @@ -200,7 +200,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ /** * Sets the boundary for the stream */ - public void setBoundary(byte[] b){ + public void setBoundary(byte[] b) { boundary = new byte[b.length]; System.arraycopy(b, 0, boundary, 0, b.length); findNextBoundary(); // redo the search with the new boundary @@ -223,7 +223,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ /** * @return true for BufferedBoundaryInputStream */ - public boolean markSupported(){ + public boolean markSupported() { return true; } @@ -267,7 +267,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ */ private int fillBuffer() throws IOException { // Do we need to fill the buffer - if(buf_pos < buf_end-boundary.length) + if (buf_pos < buf_end-boundary.length) return 0; int leftover = buf_end - buf_pos; @@ -288,7 +288,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ if (leftover > 0 && buf_pos != 0) System.arraycopy(buffer, buf_pos, buffer, 0, leftover); // Set new positions - if (buf_mark >= 0){ + if (buf_mark >= 0) { buf_pos = tmp_pos - buf_mark; buf_mark = 0; } else @@ -311,7 +311,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ /** * Searches for the nearest boundary from the current buffer position */ - private void findNextBoundary(){ + private void findNextBoundary() { // No need to check for boundary if buffer is smaller than the boundary length for (int i = buf_pos; i <= buf_end-boundary.length; i++) { for (int b = 0; b < boundary.length; b++) { diff --git a/src/zutil/io/BufferedRandomAccessFile.java b/src/zutil/io/BufferedRandomAccessFile.java index 6b4a4a9..13a2f98 100644 --- a/src/zutil/io/BufferedRandomAccessFile.java +++ b/src/zutil/io/BufferedRandomAccessFile.java @@ -101,8 +101,8 @@ public class BufferedRandomAccessFile extends RandomAccessFile{ * @return the buffer */ private int fillBuffer() throws IOException { - int n = super.read(buffer, 0, BUF_SIZE ); - if(n >= 0) { + int n = super.read(buffer, 0, BUF_SIZE); + if (n >= 0) { file_pos +=n; buf_end = n; buf_pos = 0; @@ -123,11 +123,11 @@ public class BufferedRandomAccessFile extends RandomAccessFile{ * @return the next byte in the buffer */ public final int read() throws IOException{ - if(buf_pos >= buf_end) { - if(fillBuffer() < 0) + if (buf_pos >= buf_end) { + if (fillBuffer() < 0) return -1; } - if(buf_end == 0) { + if (buf_end == 0) { return -1; } else { buf_pos++; @@ -154,28 +154,28 @@ public class BufferedRandomAccessFile extends RandomAccessFile{ * @return the amount of bytes read or -1 if eof */ public int read(byte b[], int off, int len) throws IOException { - if(buf_pos >= buf_end) { - if(fillBuffer() < 0) + if (buf_pos >= buf_end) { + if (fillBuffer() < 0) return -1; // EOF } // Copy from buffer int leftover = buf_end - buf_pos; - if(len <= leftover) { + if (len <= leftover) { System.arraycopy(buffer, buf_pos, b, off, len); buf_pos += len; return len; } System.arraycopy(buffer, buf_pos, b, off, leftover); - int n = super.read(b, off+leftover, len-leftover ); + int n = super.read(b, off+leftover, len-leftover); fillBuffer(); - if( n >= 0 ) + if (n >= 0) return leftover + n; return leftover; - /*for(int i = 0; i < len; i++) { + /*for (int i = 0; i < len; i++) { int c = this.read(); - if(c != -1) + if (c != -1) b[off+i] = (byte)c; else { return i; @@ -189,7 +189,7 @@ public class BufferedRandomAccessFile extends RandomAccessFile{ */ public long getFilePointer() { long l = file_pos; - return (l - buf_end + buf_pos) ; + return (l - buf_end + buf_pos); } /** @@ -199,7 +199,7 @@ public class BufferedRandomAccessFile extends RandomAccessFile{ */ public void seek(long pos) throws IOException { int n = (int)(file_pos - pos); - if(n >= 0 && n <= buf_end) { + if (n >= 0 && n <= buf_end) { buf_pos = buf_end - n; } else { super.seek(pos); @@ -214,19 +214,19 @@ public class BufferedRandomAccessFile extends RandomAccessFile{ */ public final String readNextLine() throws IOException { String str; - if(buf_end-buf_pos <= 0) { - if(fillBuffer() < 0) { + if (buf_end-buf_pos <= 0) { + if (fillBuffer() < 0) { throw new IOException("Error filling buffer!"); } } int lineEnd = -1; - for(int i = buf_pos; i < buf_end; i++) { - if(buffer[i] == '\n') { + for (int i = buf_pos; i < buf_end; i++) { + if (buffer[i] == '\n') { lineEnd = i; break; } } - if(lineEnd < 0) { + if (lineEnd < 0) { StringBuilder input = new StringBuilder(256); int c; while (((c = read()) != -1) && (c != '\n')) { @@ -238,7 +238,7 @@ public class BufferedRandomAccessFile extends RandomAccessFile{ return input.toString(); } - if(lineEnd > 0 && buffer[lineEnd-1] == '\r'){ + if (lineEnd > 0 && buffer[lineEnd-1] == '\r') { str = new String(buffer, buf_pos, lineEnd - buf_pos -1); } else { diff --git a/src/zutil/io/DynamicByteArrayStream.java b/src/zutil/io/DynamicByteArrayStream.java index 4ac131e..dd6952b 100644 --- a/src/zutil/io/DynamicByteArrayStream.java +++ b/src/zutil/io/DynamicByteArrayStream.java @@ -44,7 +44,7 @@ public class DynamicByteArrayStream extends InputStream{ /** * Create a new instance of DynamicByteArrayStream */ - public DynamicByteArrayStream(){ + public DynamicByteArrayStream() { bytes = new ArrayList<>(); globalPos = 0; globalSize = 0; @@ -57,7 +57,7 @@ public class DynamicByteArrayStream extends InputStream{ * * @param b is the byte array to add. */ - public synchronized void append(byte[] b){ + public synchronized void append(byte[] b) { bytes.add(b); globalSize += b.length; } @@ -70,7 +70,7 @@ public class DynamicByteArrayStream extends InputStream{ * @param offset is the offset in the byte array * @param length is the amount of data to add */ - public synchronized void append(byte[] b, int offset, int length){ + public synchronized void append(byte[] b, int offset, int length) { byte[] new_b = new byte[length]; System.arraycopy(b, offset, new_b, 0, length); bytes.add(new_b); @@ -79,12 +79,12 @@ public class DynamicByteArrayStream extends InputStream{ @Override public synchronized int read() { - if(globalPos >= globalSize) return -1; + if (globalPos >= globalSize) return -1; int ret = bytes.get(globalArrayIndex)[localArrayOffset] & 0xff; globalPos++; localArrayOffset++; - if(localArrayOffset >= bytes.get(globalArrayIndex).length){ + if (localArrayOffset >= bytes.get(globalArrayIndex).length) { globalArrayIndex++; localArrayOffset = 0; } @@ -92,15 +92,15 @@ public class DynamicByteArrayStream extends InputStream{ } public synchronized int read(byte b[], int off, int len) { - if(len <= 0) return 0; - if(globalPos >= globalSize) return -1; + if (len <= 0) return 0; + if (globalPos >= globalSize) return -1; int bytes_read=0; - if(globalPos+len >= globalSize) len = globalSize - globalPos; - while(bytes_read= globalSize) len = globalSize - globalPos; + while (bytes_read src.length){ + if (localArrayOffset +len-bytes_read > src.length) { int length = src.length- localArrayOffset; System.arraycopy(src, localArrayOffset, b, off+bytes_read, length); @@ -109,7 +109,7 @@ public class DynamicByteArrayStream extends InputStream{ bytes_read += length; } // Read length is SHORTER than local array - else{ + else { int length = len-bytes_read; System.arraycopy(src, localArrayOffset, b, off+bytes_read, length); @@ -128,7 +128,7 @@ public class DynamicByteArrayStream extends InputStream{ /** * Clears this stream from the byte arrays */ - public synchronized void clear(){ + public synchronized void clear() { globalSize = 0; reset(); bytes.clear(); @@ -147,7 +147,7 @@ public class DynamicByteArrayStream extends InputStream{ /** * @return all of the buffers content as a byte array. */ - public byte[] getBytes(){ + public byte[] getBytes() { byte[] data = new byte[globalSize]; this.read(data, 0, globalSize); return data; @@ -159,7 +159,7 @@ public class DynamicByteArrayStream extends InputStream{ * * @return all the contents of the buffers as a String. */ - public String toString(){ - return new String( this.getBytes() ); + public String toString() { + return new String(this.getBytes()); } } diff --git a/src/zutil/io/IOUtil.java b/src/zutil/io/IOUtil.java index 803a800..ac02614 100755 --- a/src/zutil/io/IOUtil.java +++ b/src/zutil/io/IOUtil.java @@ -55,7 +55,7 @@ public class IOUtil { DynamicByteArrayStream dyn_buff = new DynamicByteArrayStream(); byte[] buff = new byte[8192]; int len; - while((len = stream.read(buff)) >= 0){ + while ((len = stream.read(buff)) >= 0) { dyn_buff.append(buff, 0, len); } @@ -108,7 +108,7 @@ public class IOUtil { int readLength = 0; int c; - while((length < 0 || readLength < length) && (c = stream.read()) >= 0){ + while ((length < 0 || readLength < length) && (c = stream.read()) >= 0) { str.append((char) c); readLength++; } @@ -162,7 +162,7 @@ public class IOUtil { int readLength = 0; int c; - while((length < 0 || readLength < length) && (c = reader.read()) >= 0){ + while ((length < 0 || readLength < length) && (c = reader.read()) >= 0) { str.append((char) c); readLength++; } @@ -222,7 +222,7 @@ public class IOUtil { public static void copyStream(InputStream in, OutputStream out) throws IOException { byte[] buff = new byte[8192]; // This is the default BufferedInputStream buffer size int len; - while((len = in.read(buff)) > 0){ + while ((len = in.read(buff)) > 0) { out.write(buff, 0, len); } } @@ -237,7 +237,7 @@ public class IOUtil { public static void copyStream(Reader in, Writer out) throws IOException { char[] buff = new char[8192]; // This is the default BufferedReader buffer size int len; - while((len = in.read(buff)) > 0){ + while ((len = in.read(buff)) > 0) { out.write(buff, 0, len); } } diff --git a/src/zutil/io/InputStreamCloser.java b/src/zutil/io/InputStreamCloser.java index 264f147..b220e47 100755 --- a/src/zutil/io/InputStreamCloser.java +++ b/src/zutil/io/InputStreamCloser.java @@ -32,14 +32,14 @@ import java.io.InputStream; * A simple Class that mirrors a InputStream but * also has an additional Closeable objects that * will be closed when the this object is closed. - * + * * @author Ziver */ public class InputStreamCloser extends InputStream{ private Closeable[] c; private InputStream in; - public InputStreamCloser(InputStream in, Closeable... c){ + public InputStreamCloser(InputStream in, Closeable... c) { this.c = c; this.in = in; } diff --git a/src/zutil/io/MultiPrintStream.java b/src/zutil/io/MultiPrintStream.java index f272937..87da405 100755 --- a/src/zutil/io/MultiPrintStream.java +++ b/src/zutil/io/MultiPrintStream.java @@ -43,7 +43,7 @@ public class MultiPrintStream extends PrintStream { //a instance of this class public static MultiPrintStream out = new MultiPrintStream(); - public MultiPrintStream(){ + public MultiPrintStream() { super(new PrintStream(System.out)); streams = new ArrayList<>(); streams.add(new PrintStream(System.out)); @@ -53,7 +53,7 @@ public class MultiPrintStream extends PrintStream { * This constructor makes a simple PrintStream that prints to the console and to a file * @param file is the file name to output to */ - public MultiPrintStream(String file){ + public MultiPrintStream(String file) { super(new PrintStream(System.out)); try { streams = new ArrayList<>(); @@ -69,7 +69,7 @@ public class MultiPrintStream extends PrintStream { * This constructor takes a array of PrintStreams to be used * @param streams is a array of the streams that will be used */ - public MultiPrintStream(PrintStream[] streams){ + public MultiPrintStream(PrintStream[] streams) { super(streams[0]); this.streams = new ArrayList<>(); Collections.addAll(this.streams, streams); @@ -79,7 +79,7 @@ public class MultiPrintStream extends PrintStream { * This constructor takes a array of PrintStreams to be used * @param instanceStream is a array of the streams that will be used */ - public static void makeInstance(MultiPrintStream instanceStream){ + public static void makeInstance(MultiPrintStream instanceStream) { out = instanceStream; } @@ -87,7 +87,7 @@ public class MultiPrintStream extends PrintStream { * Adds a PrintStream to the list of streams * @param p is the PrintStream to add */ - public void addPrintStream(PrintStream p){ + public void addPrintStream(PrintStream p) { streams.add(p); } @@ -95,7 +95,7 @@ public class MultiPrintStream extends PrintStream { * Remove a PrintStream from the list * @param p is the PrintStream to remove */ - public void removePrintStream(PrintStream p){ + public void removePrintStream(PrintStream p) { streams.remove(p); } @@ -103,7 +103,7 @@ public class MultiPrintStream extends PrintStream { * Remove a PrintStream from the list * @param p is the index of the PrintStream to remove */ - public void removePrintStream(int p){ + public void removePrintStream(int p) { streams.remove(p); } @@ -111,58 +111,58 @@ public class MultiPrintStream extends PrintStream { * writes to all the PrintStreams */ public void write(int b) { - for(int i=0; i oClass = o.getClass(); - buffer.append( oClass.getName() ); + buffer.append(oClass.getName()); String nextHead = head + "\t"; // Prints out Arrays - if ( oClass.isArray() ) { - buffer.append( "[" ); - for ( int i=0; i it = ((Collection)o).iterator(); - buffer.append( "[" ); - while(it.hasNext()){ + buffer.append("["); + while (it.hasNext()) { Object value = it.next(); buffer.append("\n"); buffer.append(nextHead); - buffer.append( (dumbCapable(value, depth-1) ? - dumpToString(value, nextHead, depth-1) : value) ); - if(it.hasNext()) - buffer.append( "," ); + buffer.append((dumbCapable(value, depth-1) ? + dumpToString(value, nextHead, depth-1) : value)); + if (it.hasNext()) + buffer.append(","); } - buffer.append( "\n" ); + buffer.append("\n"); buffer.append(head); - buffer.append( "]" ); + buffer.append("]"); } // Prints out a Map - else if(o instanceof Map){ + else if (o instanceof Map) { Iterator it = ((Map)o).keySet().iterator(); - buffer.append( "{" ); - while(it.hasNext()){ + buffer.append("{"); + while (it.hasNext()) { Object key = it.next(); Object value = ((Map)o).get(key); buffer.append("\n"); buffer.append(nextHead); - buffer.append( key ); - buffer.append( "=>" ); - buffer.append( (dumbCapable(value, depth-1) ? - dumpToString(value, nextHead, depth-1) : value) ); - if(it.hasNext()) - buffer.append( "," ); + buffer.append(key); + buffer.append("=>"); + buffer.append((dumbCapable(value, depth-1) ? + dumpToString(value, nextHead, depth-1) : value)); + if (it.hasNext()) + buffer.append(","); } - buffer.append( "\n" ); + buffer.append("\n"); buffer.append(head); - buffer.append( "}" ); + buffer.append("}"); } // Prints out data from InputStream - else if(o instanceof InputStream){ - buffer.append( " =>{\n" ); + else if (o instanceof InputStream) { + buffer.append(" =>{\n"); try { InputStream in = (InputStream)o; int tmp; - while((tmp = in.read()) != -1){ + while ((tmp = in.read()) != -1) { buffer.append(nextHead); - buffer.append( (char)tmp ); + buffer.append((char)tmp); } in.close(); } catch (IOException e) { e.printStackTrace(); } - buffer.append( "\n" ); + buffer.append("\n"); buffer.append(head); - buffer.append( "}" ); + buffer.append("}"); } // Prints out data from InputStream - else if(o instanceof Reader){ - buffer.append( " =>{\n" ); + else if (o instanceof Reader) { + buffer.append(" =>{\n"); try { Reader in = (Reader)o; int tmp; - while((tmp = in.read()) != -1){ + while ((tmp = in.read()) != -1) { buffer.append(nextHead); - buffer.append( (char)tmp ); + buffer.append((char)tmp); } in.close(); } catch (IOException e) { e.printStackTrace(); } - buffer.append( "\n" ); + buffer.append("\n"); buffer.append(head); - buffer.append( "}" ); + buffer.append("}"); } // Prints out Object properties - else{ - buffer.append( "{" ); - while ( oClass != null ) { + else { + buffer.append("{"); + while (oClass != null) { Field[] fields = oClass.getDeclaredFields(); - for ( int i=0; i{ private boolean searchCompressedFiles = false; - public FileSearcher(File root){ + public FileSearcher(File root) { this.root = root; } @@ -66,7 +66,7 @@ public class FileSearcher implements Iterable{ /** * @param file Sets the exact file name to search for (includes extension) */ - public void setFileName(String file){ + public void setFileName(String file) { fileName = file; } @@ -75,14 +75,14 @@ public class FileSearcher implements Iterable{ * * @param ext is a String containing the file extension */ - public void setExtension(String ext){ + public void setExtension(String ext) { extension = ext; } /** * Defines if the search should go into sub-folders */ - public void setRecursive(boolean recursive){ + public void setRecursive(boolean recursive) { this.recursive = recursive; } @@ -90,26 +90,26 @@ public class FileSearcher implements Iterable{ * Sets how deep into folders the search should go * (Recursion needs to be enabled for this attribute to be used) */ - //public void setDepth(int depth){ + //public void setDepth(int depth) { // this.depth = depth; //} /** * Sets if the searcher should match to files. */ - public void searchFiles(boolean searchFiles){ + public void searchFiles(boolean searchFiles) { this.searchFiles = searchFiles; } /** * Sets if the searcher should match to folders. */ - public void searchFolders(boolean searchFolders){ + public void searchFolders(boolean searchFolders) { this.searchFolders = searchFolders; } /** * Sets if the searcher should go into compressed files. */ - public void searchCompressedFiles(boolean searchCompressedFiles){ + public void searchCompressedFiles(boolean searchCompressedFiles) { this.searchCompressedFiles = searchCompressedFiles; } @@ -125,7 +125,7 @@ public class FileSearcher implements Iterable{ private int index; private FileSearchItem nextItem; - public FileSearchIterator(){ + public FileSearchIterator() { fileList = new ArrayList<>(); index = 0; @@ -149,30 +149,30 @@ public class FileSearcher implements Iterable{ FileSearchItem ret = nextItem; // Find the next file - for(; index { ZipFile zipFile = new ZipFile(file.getPath()); Enumeration e = zipFile.entries(); - while(e.hasMoreElements()){ + while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); fileList.add(new FileSearchZipItem(file.getPath(), entry)); } @@ -198,24 +198,24 @@ public class FileSearcher implements Iterable{ logger.log(Level.WARNING, "Unable to traverse file: " + file.getPath(), e); } } - + // ---------------------------------------------- // Regular Files // ---------------------------------------------- - - else if(searchFiles && file.isFile()){ - if(extension == null && fileName == null) // Should we match all files + + else if (searchFiles && file.isFile()) { + if (extension == null && fileName == null) // Should we match all files break; - else if(extension != null && + else if (extension != null && FileUtil.getFileExtension(file.getName()).equalsIgnoreCase(extension)) break; - else if(fileName != null && + else if (fileName != null && file.getName().equalsIgnoreCase(fileName)) break; } } - if(index { return ret; } - private void addFiles(FileSearchItem root, String[] list){ - if(root instanceof FileSearchFileItem) { + private void addFiles(FileSearchItem root, String[] list) { + if (root instanceof FileSearchFileItem) { for (String file : list) { fileList.add(new FileSearchFileItem( new File(((FileSearchFileItem)root).file, file))); @@ -258,7 +258,7 @@ public class FileSearcher implements Iterable{ protected static class FileSearchFileItem implements FileSearchItem{ private File file; - protected FileSearchFileItem(File file){ + protected FileSearchFileItem(File file) { this.file = file; } @@ -281,14 +281,14 @@ public class FileSearcher implements Iterable{ private ZipEntry entry; private String fileName; - protected FileSearchZipItem(String file, ZipEntry entry){ + protected FileSearchZipItem(String file, ZipEntry entry) { this.zipFile = file; this.entry = entry; this.fileName = new File(entry.getName()).getName(); } public String getName() { return fileName; } - public String getPath() { return "zip://"+zipFile+":"+entry.getName(); } + public String getPath() { return "zip://" + zipFile + ":" + entry.getName(); } public boolean isCompressed() { return true; } public boolean isFile() { return !entry.isDirectory(); } diff --git a/src/zutil/io/file/FileUtil.java b/src/zutil/io/file/FileUtil.java index 938a5a8..b69848d 100755 --- a/src/zutil/io/file/FileUtil.java +++ b/src/zutil/io/file/FileUtil.java @@ -52,8 +52,8 @@ public class FileUtil { * @param path is the path * @return A String with a relative path */ - public static String relativePath(File file, String path){ - if(file == null || path == null) + public static String relativePath(File file, String path) { + if (file == null || path == null) return null; String absolute = file.getAbsolutePath(); @@ -75,14 +75,14 @@ public class FileUtil { * @param path is the path to the file (no / if not absolute path) * @return A File object for the file */ - public static File find(String path){ + public static File find(String path) { try { File file = new File(path); - if(file.exists()) + if (file.exists()) return file; URL url = findURL(path); - if(url != null && "file".equals(url.getProtocol())) + if (url != null && "file".equals(url.getProtocol())) return new File(url.toURI()); } catch (Exception e) { logger.log(Level.FINE, "Unable to find file: " + path, e); @@ -96,7 +96,7 @@ public class FileUtil { */ public static void copy(File source, File destination) throws IOException{ try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); - BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destination));){ + BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destination));) { IOUtil.copyStream(in, out); } @@ -112,10 +112,10 @@ public class FileUtil { * subsequent call will return a incremented the number * if the previous file was created. */ - public static File getNextFile(File file){ - for(int i = 1; i<10000; ++i){ + public static File getNextFile(File file) { + for (int i = 1; i<10000; ++i) { File next = new File(file.getParentFile(), file.getName() + "." + StringUtil.prefixInt(i, 4)); - if(!next.exists()) + if (!next.exists()) return next; } return null; @@ -127,7 +127,7 @@ public class FileUtil { * @param path is the path to the file (no / if not absolute path) * @return A URL object for the file */ - public static URL findURL(String path){ + public static URL findURL(String path) { return Thread.currentThread().getContextClassLoader().getResource(path); } @@ -137,10 +137,10 @@ public class FileUtil { * @param path is the path to the file (no / if not absolute path) * @return A InputStream object for the file */ - public static InputStream getInputStream(String path){ + public static InputStream getInputStream(String path) { try { File file = new File(path); - if(file.exists()) + if (file.exists()) return new BufferedInputStream(new FileInputStream(file)); return Thread.currentThread().getContextClassLoader() @@ -217,7 +217,7 @@ public class FileUtil { * @param dir is the directory to search in * @return a List of files */ - public static List search(File dir){ + public static List search(File dir) { return search(dir, new LinkedList<>(), true); } @@ -229,7 +229,7 @@ public class FileUtil { * @param recursive if the search should go into subdirectories * @return A List of files */ - public static List search(File dir, List fileList, boolean recursive){ + public static List search(File dir, List fileList, boolean recursive) { return search(dir, new LinkedList<>(), false, (recursive ? Integer.MAX_VALUE : 0)); } @@ -242,25 +242,25 @@ public class FileUtil { * @param recurse if the search should go into subdirectories * @return A List with the files and/or folders */ - public static List search(File dir, List fileList, boolean folders, int recurse){ - if(recurse<0) + public static List search(File dir, List fileList, boolean folders, int recurse) { + if (recurse<0) return fileList; --recurse; - if(folders){ - fileList.add( dir ); + if (folders) { + fileList.add(dir); } File file; String[] temp = dir.list(); - if(temp != null){ - for(int i=0; i 0 ) - ret.append( prefix ); - ret.append( array[i] ); + if (record.getMessage() != null) { + String[] array = splitter.split(record.getMessage()); + for (int i=0; i 0) + ret.append(prefix); + ret.append(array[i]); } - ret.append( '\n' ); + ret.append('\n'); } - if( record.getThrown() != null ){ + if (record.getThrown() != null) { StringOutputStream out = new StringOutputStream(); record.getThrown().printStackTrace(new PrintStream(out)); - String[] array = splitter.split( out.toString() ); - for( int i=0; i 0 ) - ret.append( prefix ); - ret.append( array[i] ); + String[] array = splitter.split(out.toString()); + for (int i=0; i 0) + ret.append(prefix); + ret.append(array[i]); } - ret.append( '\n' ); + ret.append('\n'); } return ret.toString(); } @@ -117,7 +117,7 @@ public class CompactLogFormatter extends Formatter{ * * @param enable set to True to activate time stamp */ - public void enableTimeStamp(boolean enable){ + public void enableTimeStamp(boolean enable) { timeStamp = enable; } @@ -126,7 +126,7 @@ public class CompactLogFormatter extends Formatter{ * * @param ts is the String to send to SimpleDateFormat */ - public void setTimeStamp(String ts){ + public void setTimeStamp(String ts) { dateFormatter = new SimpleDateFormat(ts); } @@ -135,7 +135,7 @@ public class CompactLogFormatter extends Formatter{ * * @param enable set to True to activate class/source name */ - public void enableClassName(boolean enable){ + public void enableClassName(boolean enable) { className = enable; } @@ -144,14 +144,14 @@ public class CompactLogFormatter extends Formatter{ * * @param enable set to True to activate class/source name */ - public void enableMethodName(boolean enable){ + public void enableMethodName(boolean enable) { methodName = enable; } /** * @return the Class name */ - private String paddClassName(String source){ + private String paddClassName(String source) { String cStr = padd_cache.get(source); if (cStr == null || cStr.length() != max_class_name) { cStr = source.substring(source.lastIndexOf('.') + 1); // Remove packages diff --git a/src/zutil/log/CounterManager.java b/src/zutil/log/CounterManager.java index e792c41..9585841 100644 --- a/src/zutil/log/CounterManager.java +++ b/src/zutil/log/CounterManager.java @@ -57,7 +57,7 @@ public class CounterManager { } private static synchronized Counter getCounter(String clazz, String name) { Counter counter; - if ( ! counters.containsKey(clazz) || ! counters.get(clazz).containsKey(name)) { + if (! counters.containsKey(clazz) || ! counters.get(clazz).containsKey(name)) { // Get the platform MBeanServer MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); // Unique identification of MBeans @@ -68,7 +68,7 @@ public class CounterManager { ObjectName objectName = new ObjectName(clazz + ":name=" + counter.getName()); mbs.registerMBean(counter, objectName); // Register the singleton - if ( ! counters.containsKey(clazz)) + if (! counters.containsKey(clazz)) counters.put(clazz, new HashMap<>()); counters.get(clazz).put(name, counter); } catch (Exception e) { @@ -103,28 +103,28 @@ public class CounterManager { private AtomicInteger counter = new AtomicInteger(); - protected Counter(String name){ + protected Counter(String name) { this.name = name; } - public void add(int i){ + public void add(int i) { int prev = counter.getAndAdd(i); updateMetaData(prev + i); } - public void set(int i){ + public void set(int i) { counter.getAndSet(i); updateMetaData(i); } - public void increment(){ + public void increment() { int i = counter.incrementAndGet(); updateMetaData(i); } - public void decrement(){ + public void decrement() { int i = counter.decrementAndGet(); updateMetaData(i); } - private void updateMetaData(int i){ + private void updateMetaData(int i) { if (max < i) max = i; if (min > i) @@ -142,7 +142,7 @@ public class CounterManager { * @return current value of the counter */ @Override - public int getValue(){ + public int getValue() { return counter.intValue(); } /** diff --git a/src/zutil/log/InputStreamLogger.java b/src/zutil/log/InputStreamLogger.java index 1452986..363c290 100755 --- a/src/zutil/log/InputStreamLogger.java +++ b/src/zutil/log/InputStreamLogger.java @@ -41,19 +41,19 @@ public class InputStreamLogger extends InputStream implements StreamLogger.LogCa private InputStream in; private StreamLogger log; - public InputStreamLogger(InputStream in){ + public InputStreamLogger(InputStream in) { this(null, in); } - public InputStreamLogger(String prefix, InputStream in){ + public InputStreamLogger(String prefix, InputStream in) { this.in = in; this.log = new StreamLogger(prefix, this); } - public boolean isLoggable(){ + public boolean isLoggable() { return logger.isLoggable(Level.FINEST); } - public void log(String msg){ + public void log(String msg) { logger.finest(msg); } diff --git a/src/zutil/log/LogUtil.java b/src/zutil/log/LogUtil.java index 07c75db..a5246bd 100755 --- a/src/zutil/log/LogUtil.java +++ b/src/zutil/log/LogUtil.java @@ -33,19 +33,19 @@ import java.util.logging.*; /** * Utility functions for the standard Java Logger - * + * * @author Ziver */ public class LogUtil { - private static final Logger logger = Logger.getLogger( LogUtil.class.getName() ); + private static final Logger logger = Logger.getLogger(LogUtil.class.getName()); - private LogUtil(){} + private LogUtil() {} /** * @return a new Logger for the calling class */ - public static Logger getLogger(){ + public static Logger getLogger() { return Logger.getLogger(ClassUtil.getCallingClass(LogUtil.class)); } @@ -54,7 +54,7 @@ public class LogUtil { * * @param f is the formatter class */ - public static void setGlobalFormatter(Formatter f){ + public static void setGlobalFormatter(Formatter f) { Logger root = Logger.getLogger(""); for (Handler handler : root.getHandlers()) { handler.setFormatter(f); @@ -66,7 +66,7 @@ public class LogUtil { * * @param f is the formatter class */ - public static void setFormatter(String name, Formatter f){ + public static void setFormatter(String name, Formatter f) { Logger root = Logger.getLogger(name); for (Handler handler : root.getHandlers()) { handler.setFormatter(f); @@ -76,14 +76,14 @@ public class LogUtil { /** * Sets the global log level */ - public static void setGlobalLevel(Level level){ + public static void setGlobalLevel(Level level) { setLevel("", level); } /** * Adds a Handler to the root namespace */ - public static void addGlobalHandler(Handler handler){ + public static void addGlobalHandler(Handler handler) { Logger root = Logger.getLogger(""); root.addHandler(handler); } @@ -91,33 +91,33 @@ public class LogUtil { /** * Sets the log level for a specified class */ - public static void setLevel(Class c, Level level){ + public static void setLevel(Class c, Level level) { setLevel(c.getName(), level); } /** * Sets the log level for a specified logger */ - public static void setLevel(String name, Level level){ - logger.fine("Changing log level of \""+name+"\" to \""+level.getLocalizedName()+"\""); + public static void setLevel(String name, Level level) { + logger.fine("Changing log level of \"" + name + "\" to \"" + level.getLocalizedName() + "\""); Logger newLogger = Logger.getLogger(name); newLogger.setLevel(level); // Check if the logger has a handler - if( newLogger.getHandlers().length > 0 ){ + if (newLogger.getHandlers().length > 0) { // Set the level on the handlers if its level is higher for (Handler handler : newLogger.getHandlers()) { - if(handler.getLevel().intValue() > level.intValue()) + if (handler.getLevel().intValue() > level.intValue()) handler.setLevel(level); } } } - public static boolean isLoggable(Class clazz, Level level){ + public static boolean isLoggable(Class clazz, Level level) { return Logger.getLogger(clazz.getName()).isLoggable(level); } - public static void readConfiguration(String file){ - try{ + public static void readConfiguration(String file) { + try { File confFile = FileUtil.find(file); if (confFile != null) { FileInputStream in = new FileInputStream(confFile); @@ -125,9 +125,9 @@ public class LogUtil { in.close(); } else - logger.warning("Unable to find logging configuration file: "+file); - } catch (Exception e){ - logger.log(Level.SEVERE, "Unable to load logging configuration: "+file, e); + logger.warning("Unable to find logging configuration file: " +file); + } catch (Exception e) { + logger.log(Level.SEVERE, "Unable to load logging configuration: " +file, e); } } } diff --git a/src/zutil/log/OutputStreamLogger.java b/src/zutil/log/OutputStreamLogger.java index 02c05f7..29b7e46 100755 --- a/src/zutil/log/OutputStreamLogger.java +++ b/src/zutil/log/OutputStreamLogger.java @@ -42,19 +42,19 @@ public class OutputStreamLogger extends OutputStream implements StreamLogger.Log private StreamLogger log; - public OutputStreamLogger(OutputStream out){ + public OutputStreamLogger(OutputStream out) { this(null, out); } - public OutputStreamLogger(String prefix, OutputStream out){ + public OutputStreamLogger(String prefix, OutputStream out) { this.out = out; this.log = new StreamLogger(prefix, this); } - public boolean isLoggable(){ + public boolean isLoggable() { return logger.isLoggable(Level.FINEST); } - public void log(String msg){ + public void log(String msg) { logger.finest(msg); } diff --git a/src/zutil/log/StreamLogger.java b/src/zutil/log/StreamLogger.java index 8e5f780..e976ab1 100755 --- a/src/zutil/log/StreamLogger.java +++ b/src/zutil/log/StreamLogger.java @@ -37,8 +37,8 @@ public class StreamLogger { private StringBuilder buffer; - protected StreamLogger(String prefix, LogCallback logger){ - if(logger == null) + protected StreamLogger(String prefix, LogCallback logger) { + if (logger == null) throw new NullPointerException("LogCallback can not be NULL"); this.prefix = prefix; this.logger = logger; @@ -46,29 +46,29 @@ public class StreamLogger { } - protected void log(int n){ - if(n < 0 || n == DELIMETER) + protected void log(int n) { + if (n < 0 || n == DELIMETER) flushLog(); else buffer.append((char)n); - if(buffer.length() > MAX_BUFFER_SIZE) + if (buffer.length() > MAX_BUFFER_SIZE) flushLog(); } - protected void log(byte[] b, int off, int len){ + protected void log(byte[] b, int off, int len) { if (logger.isLoggable()) { - for(int i=0; i MAX_BUFFER_SIZE) + if (buffer.length() > MAX_BUFFER_SIZE) flushLog(); } } - protected void flushLog(){ - if(buffer.length() > 0) { + protected void flushLog() { + if (buffer.length() > 0) { if (prefix != null) logger.log(prefix + ": " + buffer.toString()); else @@ -76,7 +76,7 @@ public class StreamLogger { clearLog(); } } - protected void clearLog(){ + protected void clearLog() { buffer.delete(0, buffer.length()); } diff --git a/src/zutil/math/Matrix.java b/src/zutil/math/Matrix.java index bb1fb1e..b56997f 100755 --- a/src/zutil/math/Matrix.java +++ b/src/zutil/math/Matrix.java @@ -39,11 +39,11 @@ public class Matrix { * * @return a new matrix with the result */ - public static double[][] add(double[][] matrix, double num){ + public static double[][] add(double[][] matrix, double num) { double[][] result = new double[matrix.length][matrix[0].length]; for (int y=0; y < matrix.length; ++y) { - for (int x=0; x < matrix[y].length; ++x){ + for (int x=0; x < matrix[y].length; ++x) { result[y][x] = matrix[y][x] + num; } } @@ -56,11 +56,11 @@ public class Matrix { * * @return a new matrix with the result */ - public static double[][] subtract(double[][] matrix, double num){ + public static double[][] subtract(double[][] matrix, double num) { double[][] result = new double[matrix.length][matrix[0].length]; for (int y=0; y < matrix.length; ++y) { - for (int x=0; x < matrix[y].length; ++x){ + for (int x=0; x < matrix[y].length; ++x) { result[y][x] = matrix[y][x] - num; } } @@ -73,11 +73,11 @@ public class Matrix { * * @return a new matrix with the result */ - public static double[][] multiply(double[][] matrix, double num){ + public static double[][] multiply(double[][] matrix, double num) { double[][] result = new double[matrix.length][matrix[0].length]; for (int y=0; y < matrix.length; ++y) { - for (int x=0; x < matrix[y].length; ++x){ + for (int x=0; x < matrix[y].length; ++x) { result[y][x] = matrix[y][x] * num; } } @@ -90,7 +90,7 @@ public class Matrix { * * @return a new matrix with the result */ - public static double[][] divide(double[][] matrix, double num){ + public static double[][] divide(double[][] matrix, double num) { return multiply(matrix, 1/num); } @@ -176,7 +176,7 @@ public class Matrix { * * @return a new matrix with the result */ - public static double[][] multiply(double[][] matrix, double[] vector){ + public static double[][] multiply(double[][] matrix, double[] vector) { vectorPreCheck(matrix, vector); double[][] result = new double[matrix.length][matrix[0].length]; @@ -194,7 +194,7 @@ public class Matrix { * * @return a new matrix with the result */ - public static double[][] divide(double[][] matrix, double[] vector){ + public static double[][] divide(double[][] matrix, double[] vector) { vectorPreCheck(matrix, vector); double[][] result = new double[matrix.length][matrix[0].length]; @@ -255,7 +255,7 @@ public class Matrix { * * @return a new vector with subtracted elements */ - public static double[] add(double[] vector1, double[] vector2){ + public static double[] add(double[] vector1, double[] vector2) { vectorPreCheck(vector1, vector2); double[] result = new double[vector1.length]; @@ -271,7 +271,7 @@ public class Matrix { * * @return a new matrix with subtracted elements */ - public static double[][] add(double[][] matrix, double[] vector){ + public static double[][] add(double[][] matrix, double[] vector) { vectorPreCheck(matrix, vector); double[][] result = new double[matrix.length][matrix[0].length]; @@ -289,7 +289,7 @@ public class Matrix { * * @return a new vector with subtracted elements */ - public static double[] subtract(double[] vector1, double[] vector2){ + public static double[] subtract(double[] vector1, double[] vector2) { vectorPreCheck(vector1, vector2); double[] result = new double[vector1.length]; @@ -305,7 +305,7 @@ public class Matrix { * * @return a new matrix with subtracted elements */ - public static double[][] subtract(double[][] matrix, double[] vector){ + public static double[][] subtract(double[][] matrix, double[] vector) { vectorPreCheck(matrix, vector); double[][] result = new double[matrix.length][matrix[0].length]; @@ -324,7 +324,7 @@ public class Matrix { * * @return a new vector with the result */ - public static double[] multiply(double[][] matrix, double[] vector){ + public static double[] multiply(double[][] matrix, double[] vector) { vectorPreCheck(matrix, vector); double[] result = new double[matrix.length]; @@ -342,12 +342,12 @@ public class Matrix { * * @return a new vector with the result */ - public static double[] divide(double[][] matrix, double[] vector){ + public static double[] divide(double[][] matrix, double[] vector) { vectorPreCheck(matrix, vector); double[] result = new double[matrix.length]; for (int y=0; y < matrix.length; ++y) { - for (int x=0; x < matrix[y].length; ++x){ + for (int x=0; x < matrix[y].length; ++x) { result[y] += matrix[y][x] / vector[x]; } } @@ -389,13 +389,13 @@ public class Matrix { * * @return a new matrix with the result */ - public static double[][] multiply(double[][] matrix1, double[][] matrix2){ + public static double[][] multiply(double[][] matrix1, double[][] matrix2) { matrixPreCheck(matrix1, matrix2); double[][] result = new double[matrix1.length][matrix2[0].length]; for (int y=0; y < result.length; ++y) { for (int x=0; x= 0){ + else { + while (index >= 0) { char c = increment(ret.charAt(index)); - if(c != 0){ - if(index == 0 && ret.length() < maxChar) ret.append('a'); - if(index == 0) ret = new StringBuffer(""+c); + if (c != 0) { + if (index == 0 && ret.length() < maxChar) ret.append('a'); + if (index == 0) ret = new StringBuffer("" +c); else ret.setCharAt(index,c); break; } - else{ + else { //ret.setCharAt(index,'a'); ret.deleteCharAt(index); index--; @@ -66,14 +66,14 @@ public class Tick { * @param c is the char to increment * @return the incremented char in lowercase 0 if it reached the end */ - public static char increment(char c){ - switch(Character.toLowerCase(c)){ + public static char increment(char c) { + switch(Character.toLowerCase(c)) { case 'z': return (char)134; case (char)134: return (char)132; case (char)132: return (char)148; } c = (char)(Character.toLowerCase(c) + 1); - if(isAlphabetic(c)){ + if (isAlphabetic(c)) { return c; } return 0; @@ -86,8 +86,8 @@ public class Tick { * @param c is the char to check * @return true if the char is a valid letter */ - public static boolean isAlphabetic(char c){ - switch(Character.toLowerCase(c)){ + public static boolean isAlphabetic(char c) { + switch(Character.toLowerCase(c)) { case 'a': case 'b': case 'c': diff --git a/src/zutil/math/ZMath.java b/src/zutil/math/ZMath.java index 380a985..df7db51 100755 --- a/src/zutil/math/ZMath.java +++ b/src/zutil/math/ZMath.java @@ -28,7 +28,7 @@ import java.math.BigInteger; /** * Very Simple math functions - * + * * @author Ziver */ public class ZMath { @@ -36,7 +36,7 @@ public class ZMath { /** * Calculates the percentage of the values */ - public static double percent(int min, int max, int value){ + public static double percent(int min, int max, int value) { return ((double)(value-min)/(max-min))*100; } @@ -45,10 +45,10 @@ public class ZMath { * * @return the two values of x as an array */ - public static double[] pqFormula(double p, double q){ + public static double[] pqFormula(double p, double q) { double[] ret = new double[2]; double t = (p/2); - ret[0] = Math.sqrt( t*t - q ); + ret[0] = Math.sqrt(t*t - q); ret[1] = -ret[0]; t *= -1; ret[0] += t; @@ -62,14 +62,14 @@ public class ZMath { * * @return the two values of x as an array */ - public static BigInteger[] pqFormula(BigInteger p, BigInteger q){ + public static BigInteger[] pqFormula(BigInteger p, BigInteger q) { BigInteger[] ret = new BigInteger[2]; - BigInteger t = p.divide( BigInteger.valueOf(2) ); - ret[0] = sqrt( t.multiply( t ).subtract( q ) ); + BigInteger t = p.divide(BigInteger.valueOf(2)); + ret[0] = sqrt(t.multiply(t).subtract(q)); ret[1] = ret[0].negate(); t = t.negate(); - ret[0] = ret[0].add( t ); - ret[1] = ret[1].add( t ); + ret[0] = ret[0].add(t); + ret[1] = ret[1].add(t); return ret; } @@ -77,23 +77,23 @@ public class ZMath { * Calculates the square root of a big number * */ - public static BigInteger sqrt(BigInteger value){ + public static BigInteger sqrt(BigInteger value) { BigInteger op = value; BigInteger res = BigInteger.ZERO; BigInteger one = BigInteger.ONE; - while( one.compareTo( op ) < 0 ){ - one = one.shiftLeft( 2 ); + while (one.compareTo(op) < 0) { + one = one.shiftLeft(2); } one = one.shiftRight(2); - while( !one.equals( BigInteger.ZERO ) ){ - if( op.compareTo( res.add( one ) ) >= 0 ){ - op = op.subtract( res.add( one ) ); - res = res.add( one.shiftLeft( 1 ) ); + while (!one.equals(BigInteger.ZERO)) { + if (op.compareTo(res.add(one)) >= 0) { + op = op.subtract(res.add(one)); + res = res.add(one.shiftLeft(1)); } - res = res.shiftRight( 1 ); - one = one.shiftRight( 2 ); + res = res.shiftRight(1); + one = one.shiftRight(2); } return res; diff --git a/src/zutil/ml/LinearRegression.java b/src/zutil/ml/LinearRegression.java index 890f3e8..12b7107 100755 --- a/src/zutil/ml/LinearRegression.java +++ b/src/zutil/ml/LinearRegression.java @@ -43,7 +43,7 @@ public class LinearRegression { * h(x) = theta0 * x0 + theta1 * x1 + ... + thetan * xn => transpose(theta) * x * */ - protected static double[] calculateHypothesis(double[][] x, double[] theta){ + protected static double[] calculateHypothesis(double[][] x, double[] theta) { return Matrix.multiply(x, theta); } @@ -56,7 +56,7 @@ public class LinearRegression { * m = learning data size (rows) * @return a number indicating the error rate */ - protected static double calculateCost(double[][] x, double[] y, double[] theta){ + protected static double calculateCost(double[][] x, double[] y, double[] theta) { double[] hypothesis = calculateHypothesis(x, theta); double[] normalized = Matrix.subtract(hypothesis, y); @@ -64,14 +64,14 @@ public class LinearRegression { Matrix.Elemental.pow(normalized,2)); } - private static double calculateDiff(double[] vector1, double[] vector2){ + private static double calculateDiff(double[] vector1, double[] vector2) { return Math.abs(Matrix.sum(vector1) - Matrix.sum(vector2)); } /** * Will try to find the best theta value. */ - public static double[] gradientDescent(double[][] x, double[] y, double[] theta, double alpha){ + public static double[] gradientDescent(double[][] x, double[] y, double[] theta, double alpha) { double[] newTheta = theta.clone(); double[] prevTheta = new double[newTheta.length]; double thetaDiff = 0; @@ -96,7 +96,7 @@ public class LinearRegression { *
* @return the theta that was found to minimize the cost function */ - public static double[] gradientDescentIteration(double[][] x, double[] y, double[] theta, double alpha){ + public static double[] gradientDescentIteration(double[][] x, double[] y, double[] theta, double alpha) { double[] newTheta = new double[theta.length]; double m = y.length; double[] hypothesis = calculateHypothesis(x, theta); diff --git a/src/zutil/ml/neural/Perceptron.java b/src/zutil/ml/neural/Perceptron.java index ba4aa08..c316db5 100755 --- a/src/zutil/ml/neural/Perceptron.java +++ b/src/zutil/ml/neural/Perceptron.java @@ -55,7 +55,7 @@ public class Perceptron { private OutputConnection[] outputs; - public Perceptron(int inputCount, int outputCount){ + public Perceptron(int inputCount, int outputCount) { inputs = new InputConnection[inputCount]; outputs = new OutputConnection[outputCount]; } diff --git a/src/zutil/net/FTPClient.java b/src/zutil/net/FTPClient.java index 2b98bb3..2c56e8c 100755 --- a/src/zutil/net/FTPClient.java +++ b/src/zutil/net/FTPClient.java @@ -66,17 +66,17 @@ public class FTPClient extends Thread{ PATH_CREATED ( 257 ); private int code; - FTPReturnCode(int code){ + FTPReturnCode(int code) { this.code = code; } - public boolean isError(){ + public boolean isError() { return code >= 400; } - public static FTPReturnCode fromCode(int code){ - for(FTPReturnCode type : FTPReturnCode.values()){ - if(code == type.code) return type; + public static FTPReturnCode fromCode(int code) { + for (FTPReturnCode type : FTPReturnCode.values()) { + if (code == type.code) return type; } return UNKNOWN; } @@ -105,10 +105,10 @@ public class FTPClient extends Thread{ connectionType = conn_type; readCommand(); - sendCommand("USER "+user); - sendNoReplyCommand("PASS "+pass); + sendCommand("USER " +user); + sendNoReplyCommand("PASS " +pass); String tmp = readCommand(); - if(parseReturnCode(tmp) == FTPReturnCode.LOGIN_NO){ + if (parseReturnCode(tmp) == FTPReturnCode.LOGIN_NO) { close(); throw new AccountException(tmp); } @@ -126,7 +126,7 @@ public class FTPClient extends Thread{ */ private FTPReturnCode sendCommand(String cmd) throws IOException{ sendNoReplyCommand(cmd); - return parseReturnCode( readCommand( ) ); + return parseReturnCode(readCommand()); } /** @@ -145,9 +145,9 @@ public class FTPClient extends Thread{ */ private String readCommand() throws IOException{ String tmp = in.readLine(); - while(!Character.isWhitespace(tmp.charAt(3))){ + while (!Character.isWhitespace(tmp.charAt(3))) { tmp = in.readLine(); - if(parseReturnCode(tmp).isError()) throw new IOException(tmp); + if (parseReturnCode(tmp).isError()) throw new IOException(tmp); } return tmp; } @@ -158,7 +158,7 @@ public class FTPClient extends Thread{ * @param msg message String from the server * @return a status code response */ - private FTPReturnCode parseReturnCode(String msg){ + private FTPReturnCode parseReturnCode(String msg) { return FTPReturnCode.fromCode(Integer.parseInt(msg.substring(0, 3))); } @@ -173,7 +173,7 @@ public class FTPClient extends Thread{ */ public String[] getFileList(String path) throws IOException{ BufferedInputStream data_in = getDataInputStream(); - sendCommand("NLST "+path); + sendCommand("NLST " +path); String data = new String(IOUtil.readContent(data_in)); @@ -192,7 +192,7 @@ public class FTPClient extends Thread{ Pattern regex = Pattern.compile("\\s+"); BufferedInputStream data_in = getDataInputStream(); - sendCommand("LIST "+path); + sendCommand("LIST " +path); String data = new String(IOUtil.readContent(data_in)); @@ -209,7 +209,7 @@ public class FTPClient extends Thread{ */ public void sendFile(String path, String data) throws IOException{ BufferedOutputStream data_out = getDataOutputStream(); - sendCommand("STOR "+path); + sendCommand("STOR " +path); byte[] byte_data = data.getBytes(); data_out.write(byte_data, 0, byte_data.length); @@ -224,7 +224,7 @@ public class FTPClient extends Thread{ * @param path The path to the directory */ public boolean createDir(String path) throws IOException{ - if(sendCommand("MKD "+path) == FTPReturnCode.PATH_CREATED) + if (sendCommand("MKD " +path) == FTPReturnCode.PATH_CREATED) return true; return false; } @@ -237,7 +237,7 @@ public class FTPClient extends Thread{ */ private BufferedInputStream getFileInputStream(String path) throws IOException{ BufferedInputStream input = getDataInputStream(); - sendCommand("RETR "+path); + sendCommand("RETR " +path); return input; } @@ -261,7 +261,7 @@ public class FTPClient extends Thread{ * @return true if the command was successful, false otherwise */ public boolean removeFile(String path) throws IOException{ - if(sendCommand("DELE "+path) == FTPReturnCode.FILE_ACTION_OK) + if (sendCommand("DELE " +path) == FTPReturnCode.FILE_ACTION_OK) return true; return false; } @@ -272,7 +272,7 @@ public class FTPClient extends Thread{ * @return True if the command was successful or false otherwise */ public boolean removeDir(String path) throws IOException{ - if(sendCommand("RMD "+path) == FTPReturnCode.FILE_ACTION_OK) + if (sendCommand("RMD " + path) == FTPReturnCode.FILE_ACTION_OK) return true; return false; } @@ -286,12 +286,12 @@ public class FTPClient extends Thread{ * @return a PrintStream for the channel */ public BufferedOutputStream getDataOutputStream() throws IOException{ - if(connectionType == FTPConnectionType.PASSIVE){ // Passive Mode + if (connectionType == FTPConnectionType.PASSIVE) { // Passive Mode int port = setPassiveMode(); Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port); return new BufferedOutputStream(data_socket.getOutputStream()); } - else{ // Active Mode + else { // Active Mode return null; } } @@ -302,12 +302,12 @@ public class FTPClient extends Thread{ * @return a BufferedReader for the data channel */ public BufferedInputStream getDataInputStream() throws IOException{ - if(connectionType == FTPConnectionType.PASSIVE){ // Passive Mode + if (connectionType == FTPConnectionType.PASSIVE) { // Passive Mode int port = setPassiveMode(); Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port); return new BufferedInputStream(data_socket.getInputStream()); } - else{ // Active Mode + else { // Active Mode return null; } } @@ -321,13 +321,13 @@ public class FTPClient extends Thread{ private int setPassiveMode() throws IOException{ sendNoReplyCommand("PASV"); String ret_msg = readCommand(); - if(parseReturnCode(ret_msg) != FTPReturnCode.ENTERING_PASSIVE){ - throw new IOException("Passive mode rejected by server: "+ret_msg); + if (parseReturnCode(ret_msg) != FTPReturnCode.ENTERING_PASSIVE) { + throw new IOException("Passive mode rejected by server: " +ret_msg); } ret_msg = ret_msg.substring(ret_msg.indexOf('(')+1, ret_msg.indexOf(')')); String[] tmpArray = ret_msg.split("[,]"); - if(tmpArray.length <= 1) + if (tmpArray.length <= 1) return Integer.parseInt(tmpArray[0]); else return Integer.parseInt(tmpArray[4])*256 + Integer.parseInt(tmpArray[5]); @@ -339,13 +339,13 @@ public class FTPClient extends Thread{ /** * Keep the connection alive */ - public void run(){ + public void run() { try { - while(true){ - if(last_sent > System.currentTimeMillis() + FTP_NOOP_INT*1000){ + while (true) { + if (last_sent > System.currentTimeMillis() + FTP_NOOP_INT * 1000) { sendCommand("NOOP"); } - try{ Thread.sleep(5000); }catch(Exception e){} + try { Thread.sleep(5000); } catch (Exception e) {} } } catch (IOException e1) { e1.printStackTrace(); diff --git a/src/zutil/net/InetScanner.java b/src/zutil/net/InetScanner.java index c889b67..d8905c6 100755 --- a/src/zutil/net/InetScanner.java +++ b/src/zutil/net/InetScanner.java @@ -43,7 +43,7 @@ public class InetScanner { private boolean canceled; - public void setListener(InetScanListener listener){ + public void setListener(InetScanListener listener) { this.listener = listener; } @@ -53,7 +53,7 @@ public class InetScanner { * * @param ip the network ip address */ - public synchronized void scan(InetAddress ip){ + public synchronized void scan(InetAddress ip) { canceled = false; String netAddr = ip.getHostAddress().substring(0, ip.getHostAddress().lastIndexOf('.')+1); @@ -76,7 +76,7 @@ public class InetScanner { /** * Cancels the ongoing ip scan */ - public void cancel(){ + public void cancel() { canceled = true; } @@ -84,7 +84,7 @@ public class InetScanner { /** * Will check if the given IP is reachable (Pingable) */ - public static boolean isReachable(String host){ + public static boolean isReachable(String host) { String[] output = OSAbstractionLayer.exec(platformPingCmd(host)); for (String line : output) { @@ -108,18 +108,18 @@ public class InetScanner { } - private static String platformPingCmd(String ip){ - switch (OSAbstractionLayer.getInstance().getOSType()){ + private static String platformPingCmd(String ip) { + switch (OSAbstractionLayer.getInstance().getOSType()) { case Windows: - return "ping -n 1 -w "+ TIMEOUT_SEC*1000 +" " + ip; + return "ping -n 1 -w " + (TIMEOUT_SEC*1000) + " " + ip; case Linux: case MacOS: - return "ping -c 1 -W "+ TIMEOUT_SEC +" " + ip; + return "ping -c 1 -W " + TIMEOUT_SEC + " " + ip; default: return null; } } - private static boolean platformPingCheck(String line){ + private static boolean platformPingCheck(String line) { return line.contains("TTL=") || line.contains("ttl="); } diff --git a/src/zutil/net/POP3Client.java b/src/zutil/net/POP3Client.java index 586e576..0d0a0cb 100644 --- a/src/zutil/net/POP3Client.java +++ b/src/zutil/net/POP3Client.java @@ -275,7 +275,7 @@ public class POP3Client { */ private boolean parseReturnCode(String msg) { int endPos = (msg.indexOf(' ') < 0 ? msg.length() : msg.indexOf(' ')); - return msg.substring(0, endPos).equals("+OK"); + return msg.substring(0, endPos).equals(" +OK"); } //********************************************************************************* diff --git a/src/zutil/net/ServerFind.java b/src/zutil/net/ServerFind.java index e382ff4..c77e473 100644 --- a/src/zutil/net/ServerFind.java +++ b/src/zutil/net/ServerFind.java @@ -63,12 +63,12 @@ public class ServerFind extends Thread { start(); } - public void run (){ + public void run() { byte[] buf = new byte[256]; DatagramPacket packet; DatagramSocket lan_socket; - while (!shutdown){ + while (!shutdown) { try { packet = new DatagramPacket(buf, buf.length); mSocket.receive(packet); @@ -89,7 +89,7 @@ public class ServerFind extends Thread { /** * Closes the broadcast socket */ - public void close(){ + public void close() { shutdown = true; mSocket.close(); } diff --git a/src/zutil/net/ServerFindClient.java b/src/zutil/net/ServerFindClient.java index a7a37d1..ec355ff 100644 --- a/src/zutil/net/ServerFindClient.java +++ b/src/zutil/net/ServerFindClient.java @@ -46,7 +46,7 @@ public class ServerFindClient{ * * @param port The port to contact the server on */ - public ServerFindClient(int port){ + public ServerFindClient(int port) { this.port = port; } diff --git a/src/zutil/net/ThroughputCalculator.java b/src/zutil/net/ThroughputCalculator.java index 4a2a104..2983336 100644 --- a/src/zutil/net/ThroughputCalculator.java +++ b/src/zutil/net/ThroughputCalculator.java @@ -38,14 +38,14 @@ public class ThroughputCalculator { private long total_data_amount; private float frequency = UPDATES_PER_SEC; - public void setTotalHandledData(long bytes){ + public void setTotalHandledData(long bytes) { setHandledData(bytes - total_data_amount); total_data_amount = bytes; } - public void setHandledData(long bytes){ + public void setHandledData(long bytes) { long currentTimeStamp = System.nanoTime(); data_amount += bytes; - if(currentTimeStamp - (NANOSEC_PER_SECOND/frequency) > previousTimeStamp) { + if (currentTimeStamp - (NANOSEC_PER_SECOND/frequency) > previousTimeStamp) { throughput = data_amount / ((currentTimeStamp - previousTimeStamp) / NANOSEC_PER_SECOND); previousTimeStamp = currentTimeStamp; data_amount = 0; @@ -53,21 +53,21 @@ public class ThroughputCalculator { } } - public double getByteThroughput(){ + public double getByteThroughput() { setHandledData(0); // Update throughput updated = false; return throughput; } - public double getBitThroughput(){ + public double getBitThroughput() { return getByteThroughput()*8; } - public boolean isUpdated(){ + public boolean isUpdated() { return updated; } public void setFrequency(float frequency) { - if(frequency < 0) + if (frequency < 0) this.frequency = UPDATES_PER_SEC; else this.frequency = frequency; diff --git a/src/zutil/net/dns/MulticastDnsClient.java b/src/zutil/net/dns/MulticastDnsClient.java index 9a27aba..c86513d 100755 --- a/src/zutil/net/dns/MulticastDnsClient.java +++ b/src/zutil/net/dns/MulticastDnsClient.java @@ -64,12 +64,12 @@ public class MulticastDnsClient extends ThreadedUDPNetwork implements ThreadedUD public MulticastDnsClient() throws IOException { super(MDNS_MULTICAST_ADDR, MDNS_MULTICAST_PORT); - setThread( this ); + setThread(this); this.activeProbes = new HashSet<>(); } - public void setListener(DnsResolutionListener listener){ + public void setListener(DnsResolutionListener listener) { this.listener = listener; } @@ -91,11 +91,11 @@ public class MulticastDnsClient extends ThreadedUDPNetwork implements ThreadedUD DatagramPacket udpPacket = new DatagramPacket( buffer.toByteArray(), buffer.size(), - InetAddress.getByName( MDNS_MULTICAST_ADDR ), - MDNS_MULTICAST_PORT ); + InetAddress.getByName(MDNS_MULTICAST_ADDR), + MDNS_MULTICAST_PORT); - logger.fine("Sending MDSN probe id: "+id+", for domain: " + domain); - //System.out.println("Sending:\n"+ByteUtil.toFormattedString(udpPacket.getData(), udpPacket.getOffset(), udpPacket.getLength())); + logger.fine("Sending MDSN probe id: " + id + ", for domain: " + domain); + //System.out.println("Sending:\n" +ByteUtil.toFormattedString(udpPacket.getData(), udpPacket.getOffset(), udpPacket.getLength())); //MultiPrintStream.out.dump(dnsPacket,3); send(udpPacket); @@ -109,19 +109,19 @@ public class MulticastDnsClient extends ThreadedUDPNetwork implements ThreadedUD BinaryStructInputStream in = new BinaryStructInputStream(buffer); DnsPacket dnsPacket = DnsPacket.read(in); - //System.out.println("Received:\n"+ByteUtil.toFormattedString(packet.getData(), packet.getOffset(), packet.getLength())); + //System.out.println("Received:\n" +ByteUtil.toFormattedString(packet.getData(), packet.getOffset(), packet.getLength())); MultiPrintStream.out.dump(dnsPacket,3); if (dnsPacket.getHeader().flagQueryResponse) { - if (activeProbes.contains(dnsPacket.getHeader().id)){ - logger.fine("Received MDNS response from: "+packet.getAddress()+", msg id: " + dnsPacket.getHeader().id); + if (activeProbes.contains(dnsPacket.getHeader().id)) { + logger.fine("Received MDNS response from: " + packet.getAddress() + ", msg id: " + dnsPacket.getHeader().id); if (listener != null) listener.receivedResponse(dnsPacket); } else { - logger.fine("Received MDNS packet: "+packet.getAddress()+", msg id: " + dnsPacket.getHeader().id); + logger.fine("Received MDNS packet: " + packet.getAddress() + ", msg id: " + dnsPacket.getHeader().id); } } - } catch (IOException e){ + } catch (IOException e) { logger.log(Level.WARNING, null, e); } } diff --git a/src/zutil/net/dns/MulticastDnsServer.java b/src/zutil/net/dns/MulticastDnsServer.java index 9d62d4c..3709143 100755 --- a/src/zutil/net/dns/MulticastDnsServer.java +++ b/src/zutil/net/dns/MulticastDnsServer.java @@ -66,7 +66,7 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD public MulticastDnsServer() throws IOException { super(MDNS_MULTICAST_ADDR, MDNS_MULTICAST_PORT); - setThread( this ); + setThread(this); } @@ -76,7 +76,7 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD * @param name is the domain name to add the entry under * @param ip the IPv4 address to respond with */ - public void addEntry(String name, InetAddress ip){ + public void addEntry(String name, InetAddress ip) { addEntry(name, DnsConstants.TYPE.A, DnsConstants.CLASS.IN, ip.getAddress()); } /** @@ -87,7 +87,7 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD * @param clazz {@link zutil.net.dns.packet.DnsConstants.CLASS} * @param data is the payload to include in client response */ - public void addEntry(String name, int type, int clazz, byte[] data){ + public void addEntry(String name, int type, int clazz, byte[] data) { DnsPacketResource resource = new DnsPacketResource(); resource.name = name; resource.type = type; @@ -100,7 +100,7 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD } private void addEntry(DnsPacketResource resource) { - if ( ! entries.containsKey(resource.name)) + if (! entries.containsKey(resource.name)) entries.put(resource.name, new ArrayList<>()); entries.get(resource.name).add(resource); } @@ -116,9 +116,9 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD DnsPacket dnsPacket = DnsPacket.read(in); // Just handle queries and no responses - if ( ! dnsPacket.getHeader().flagQueryResponse) { + if (! dnsPacket.getHeader().flagQueryResponse) { DnsPacket response = handleReceivedPacket(packet.getAddress(), dnsPacket); - if (response != null){ + if (response != null) { ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); BinaryStructOutputStream out = new BinaryStructOutputStream(outBuffer); response.write(out); @@ -126,29 +126,29 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD DatagramPacket outPacket = new DatagramPacket( outBuffer.toByteArray(), outBuffer.size(), - InetAddress.getByName( MDNS_MULTICAST_ADDR ), - MDNS_MULTICAST_PORT ); + InetAddress.getByName(MDNS_MULTICAST_ADDR), + MDNS_MULTICAST_PORT); send(outPacket); } } - } catch (IOException e){ + } catch (IOException e) { logger.log(Level.WARNING, null, e); } } - protected DnsPacket handleReceivedPacket(InetAddress address, DnsPacket request){ + protected DnsPacket handleReceivedPacket(InetAddress address, DnsPacket request) { DnsPacket response = new DnsPacket(); response.getHeader().setDefaultResponseData(); - for (DnsPacketQuestion question : request.getQuestions()){ + for (DnsPacketQuestion question : request.getQuestions()) { if (question.name == null) continue; - switch (question.type){ + switch (question.type) { // ------------------------------------------ // Normal Domain Name Resolution // ------------------------------------------ case DnsConstants.TYPE.A: - if (entries.containsKey(question.name)){ + if (entries.containsKey(question.name)) { logger.finer("Received request for domain: '" + question.name + "' from source: " + address); response.addAnswerRecord(entries.get(question.name)); } else { @@ -163,7 +163,7 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD case DnsConstants.TYPE.PTR: if (question.name.startsWith("_service.")) { String postFix = question.name.substring(9); - for (String domain : entries.keySet()){ + for (String domain : entries.keySet()) { if (domain.endsWith(postFix)) { logger.finer("Received request for service: '" + question.name + "' from source: " + address); response.addAnswerRecord(entries.get(domain)); @@ -171,7 +171,7 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD logger.finest("Received request for unknown service: '" + question.name + "' from source: " + address); } } - } else if (entries.containsKey(question.name)){ + } else if (entries.containsKey(question.name)) { logger.finer("Received request for service: '" + question.name + "' from source: " + address); response.addAnswerRecord(entries.get(question.name)); } else { diff --git a/src/zutil/net/dns/packet/DnsPacket.java b/src/zutil/net/dns/packet/DnsPacket.java index e00a8f9..6ae74e2 100755 --- a/src/zutil/net/dns/packet/DnsPacket.java +++ b/src/zutil/net/dns/packet/DnsPacket.java @@ -46,7 +46,7 @@ public class DnsPacket { private ArrayList additionalRecords; - public DnsPacket(){ + public DnsPacket() { header = new DnsPacketHeader(); questions = new ArrayList<>(); answerRecords = new ArrayList<>(); @@ -55,40 +55,40 @@ public class DnsPacket { } - public DnsPacketHeader getHeader(){ + public DnsPacketHeader getHeader() { return header; } - public List getQuestions(){ + public List getQuestions() { return Collections.unmodifiableList(questions); } - public List getAnswerRecords(){ + public List getAnswerRecords() { return Collections.unmodifiableList(answerRecords); } - public List getNameServers(){ + public List getNameServers() { return Collections.unmodifiableList(nameServers); } - public List getAdditionalRecords(){ + public List getAdditionalRecords() { return Collections.unmodifiableList(additionalRecords); } - public void addQuestion(DnsPacketQuestion question){ + public void addQuestion(DnsPacketQuestion question) { questions.add(question); header.countQuestion = questions.size(); } - public void addAnswerRecord(DnsPacketResource resource){ + public void addAnswerRecord(DnsPacketResource resource) { answerRecords.add(resource); header.countAnswerRecord = answerRecords.size(); } - public void addAnswerRecord(List resources){ + public void addAnswerRecord(List resources) { answerRecords.addAll(resources); header.countAnswerRecord = answerRecords.size(); } - public void addNameServer(DnsPacketResource resource){ + public void addNameServer(DnsPacketResource resource) { nameServers.add(resource); header.countNameServer = nameServers.size(); } - public void addAdditionalRecord(DnsPacketResource resource){ + public void addAdditionalRecord(DnsPacketResource resource) { additionalRecords.add(resource); header.countAdditionalRecord = additionalRecords.size(); } @@ -109,7 +109,7 @@ public class DnsPacket { return packet; } private static void readResource(BinaryStructInputStream structIn, int count, ArrayList list) throws IOException { - for (int i=0; i(); sessions = new ConcurrentHashMap<>(); @@ -93,7 +93,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{ ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); exec.scheduleWithFixedDelay(new SessionGarbageCollector(), 10000, SESSION_TTL / 2, TimeUnit.MILLISECONDS); - logger.info("HTTP"+(keyStore==null ? "" : "S")+" Server ready and listening to port: " + port); + logger.info("HTTP" + (keyStore==null ? "" : "S") + " Server ready and listening to port: " + port); } /** @@ -101,20 +101,20 @@ public class HttpServer extends ThreadedTCPNetworkServer{ * removes old sessions from the session HashMap */ private class SessionGarbageCollector implements Runnable { - public void run(){ + public void run() { Object[] keys = sessions.keySet().toArray(); int count = 0; - for(Object key : keys){ + for (Object key : keys) { Map session = sessions.get(key); // Check if session is still valid - if(((Timer) session.get(SESSION_KEY_TTL)).hasTimedOut()){ + if (((Timer) session.get(SESSION_KEY_TTL)).hasTimedOut()) { sessions.remove(key); ++count; } } if (count > 0) - logger.fine("Removed "+count+" old sessions"); + logger.fine("Removed " + count + " old sessions"); } } @@ -124,9 +124,9 @@ public class HttpServer extends ThreadedTCPNetworkServer{ * @param name The URL or name of the page * @param page The page itself */ - public void setPage(String name, HttpPage page){ - if(name.charAt(0) != '/') - name = "/"+name; + public void setPage(String name, HttpPage page) { + if (name.charAt(0) != '/') + name = "/" +name; pages.put(name, page); } @@ -136,13 +136,13 @@ public class HttpServer extends ThreadedTCPNetworkServer{ * * @param page The HttpPage that will be shown */ - public void setDefaultPage(HttpPage page){ + public void setDefaultPage(HttpPage page) { defaultPage = page; } - protected ThreadedTCPNetworkServerThread getThreadInstance( Socket s ){ + protected ThreadedTCPNetworkServerThread getThreadInstance(Socket s) { try { - return new HttpServerThread( s ); + return new HttpServerThread(s); } catch (IOException e) { logger.log(Level.SEVERE, "Could not start new Thread", e); } @@ -163,7 +163,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{ this.socket = socket; } - public void run(){ + public void run() { long time = System.currentTimeMillis(); HttpHeaderParser headerParser; HttpHeader header = null; @@ -261,11 +261,11 @@ public class HttpServer extends ThreadedTCPNetworkServer{ } } finally { - try{ + try { out.close(); in.close(); socket.close(); - } catch( Exception e ) { + } catch(Exception e) { logger.log(Level.WARNING, "Could not close connection", e); } } @@ -275,9 +275,9 @@ public class HttpServer extends ThreadedTCPNetworkServer{ protected static void logRequest(HttpHeader header, Map session, - long time){ + long time) { // Debug - if(logger.isLoggable(Level.FINEST) ){ + if (logger.isLoggable(Level.FINEST)) { StringBuilder buff = new StringBuilder(); buff.append("Received request: ").append(header==null ? null : header.getRequestURL()); buff.append(", ("); @@ -288,10 +288,10 @@ public class HttpServer extends ThreadedTCPNetworkServer{ buff.append(", time: ").append(StringUtil.formatTimeToString(System.currentTimeMillis() - time)); logger.finer(buff.toString()); - } else if(logger.isLoggable(Level.FINER)){ + } else if (logger.isLoggable(Level.FINER)) { logger.finer( "Received request: " + (header==null ? null : header.getRequestURL()) - + ", time: "+ StringUtil.formatTimeToString(System.currentTimeMillis() - time)); + + ", time: " + StringUtil.formatTimeToString(System.currentTimeMillis() - time)); } } } diff --git a/src/zutil/net/http/multipart/MultipartFileField.java b/src/zutil/net/http/multipart/MultipartFileField.java index 1572ba2..5374f1a 100755 --- a/src/zutil/net/http/multipart/MultipartFileField.java +++ b/src/zutil/net/http/multipart/MultipartFileField.java @@ -59,18 +59,18 @@ public class MultipartFileField implements MultipartField{ /** * @return the amount of data received for this field */ - public long getLength(){ + public long getLength() { return 0; //TODO: } /** * @return the field name */ - public String getName(){ + public String getName() { return fieldname; } - public String getFilename(){ + public String getFilename() { return filename; } diff --git a/src/zutil/net/http/multipart/MultipartParser.java b/src/zutil/net/http/multipart/MultipartParser.java index 4d39e2e..629089c 100755 --- a/src/zutil/net/http/multipart/MultipartParser.java +++ b/src/zutil/net/http/multipart/MultipartParser.java @@ -61,24 +61,24 @@ public class MultipartParser implements Iterable{ private MultiPartIterator iterator; - public MultipartParser(InputStream in, String delimiter, long length){ + public MultipartParser(InputStream in, String delimiter, long length) { this.in = in; this.delimiter = delimiter; this.contentLength = length; } - public MultipartParser(HttpHeader header){ + public MultipartParser(HttpHeader header) { this(header.getInputStream(), parseDelimiter(header.getHeader("Content-type")), Long.parseLong(header.getHeader("Content-Length"))); } - private static String parseDelimiter(String contentTypeHeader){ + private static String parseDelimiter(String contentTypeHeader) { String delimiter = contentTypeHeader.split(" *; *")[1]; delimiter = delimiter.split(" *= *")[1]; return delimiter; } - public long getContentLength(){ + public long getContentLength() { return contentLength; } @@ -97,10 +97,10 @@ public class MultipartParser implements Iterable{ private boolean firstIteration; - protected MultiPartIterator(){ + protected MultiPartIterator() { this.boundaryIn = new BufferedBoundaryInputStream(in); - this.boundaryIn.setBoundary("--"+delimiter); + this.boundaryIn.setBoundary("--" +delimiter); firstIteration = true; } @@ -136,8 +136,8 @@ public class MultipartParser implements Iterable{ public MultipartField next() { try { boundaryIn.next(); - if (firstIteration){ - this.boundaryIn.setBoundary("\n--"+delimiter); // Add new-line to boundary after the first iteration + if (firstIteration) { + this.boundaryIn.setBoundary("\n--" +delimiter); // Add new-line to boundary after the first iteration firstIteration = false; } String tmp = IOUtil.readLine(boundaryIn); // read the new line after the delimiter @@ -151,13 +151,13 @@ public class MultipartParser implements Iterable{ // Parse String disposition = headers.get(HEADER_CONTENT_DISPOSITION); - if (disposition != null){ + if (disposition != null) { HttpHeaderParser.parseCookieValues(headers, disposition); - if (headers.containsKey("form-data")){ - if (headers.containsKey("filename")){ + if (headers.containsKey("form-data")) { + if (headers.containsKey("filename")) { return new MultipartFileField(headers, boundaryIn); } - else{ + else { MultipartStringField field = new MultipartStringField(headers, boundaryIn); return field; } diff --git a/src/zutil/net/http/page/HttpDigestAuthPage.java b/src/zutil/net/http/page/HttpDigestAuthPage.java index 93ca567..6816174 100755 --- a/src/zutil/net/http/page/HttpDigestAuthPage.java +++ b/src/zutil/net/http/page/HttpDigestAuthPage.java @@ -67,12 +67,12 @@ public class HttpDigestAuthPage implements HttpPage{ - public HttpDigestAuthPage(HttpPage page){ + public HttpDigestAuthPage(HttpPage page) { targetPage = page; } - public void setRealm(String realm){ + public void setRealm(String realm) { this.realm = realm; } @@ -97,11 +97,11 @@ public class HttpDigestAuthPage implements HttpPage{ out.setHeader(HTTP_AUTH_HEADER, generateAuthHeader((String) session.get(AUTH_NONCE))); out.println("401 Unauthorized"); } - else if ( ! headers.getHeader(HTTP_CLIENT_HEADER).startsWith(AUTH_TYPE)){ + else if (! headers.getHeader(HTTP_CLIENT_HEADER).startsWith(AUTH_TYPE)) { out.setResponseStatusCode(501); out.println("501 Not Implemented"); } - else{ + else { HashMap authMap = HttpHeaderParser.parseHeaderValues( headers.getHeader(HTTP_CLIENT_HEADER).substring(AUTH_TYPE.length()+1), // Skip auth type AUTH_DELIMITER); @@ -111,10 +111,10 @@ public class HttpDigestAuthPage implements HttpPage{ (String)session.get(AUTH_NONCE), authMap.get(AUTH_RESPONSE))) { // Safe area, user authenticated - logger.fine("User '"+authMap.get(AUTH_USERNAME)+"' has been authenticated for realm '"+realm+"'"); + logger.fine("User '" +authMap.get(AUTH_USERNAME) + "' has been authenticated for realm '" + realm + "'"); targetPage.respond(out, headers, session, cookie, request); } - else{ + else { out.setResponseStatusCode(403); out.println("403 Forbidden"); } @@ -122,7 +122,7 @@ public class HttpDigestAuthPage implements HttpPage{ } - private boolean authenticate(String username, String uri, String nonce, String clientResponse){ + private boolean authenticate(String username, String uri, String nonce, String clientResponse) { if (!userMap.containsKey(username)) // do user exist? return false; @@ -130,13 +130,13 @@ public class HttpDigestAuthPage implements HttpPage{ generateH1(username, userMap.get(username), realm), generateH2(uri), nonce); - if (generatedResponse.equals(clientResponse)){ + if (generatedResponse.equals(clientResponse)) { return true; } return false; } - private String generateAuthHeader(String nonce){ + private String generateAuthHeader(String nonce) { StringBuilder str = new StringBuilder(); str.append(AUTH_TYPE).append(' '); str.append(AUTH_REALM).append("=\"").append(realm).append("\", "); @@ -145,7 +145,7 @@ public class HttpDigestAuthPage implements HttpPage{ return str.toString(); } - private String generateNonce(){ + private String generateNonce() { byte[] buff = new byte[128/8]; secRandom.nextBytes(buff); return Hasher.SHA1(buff); @@ -155,7 +155,7 @@ public class HttpDigestAuthPage implements HttpPage{ String ha1; // If the algorithm directive's value is "MD5" or unspecified, then HA1 is // HA1=MD5(username:realm:password) - ha1 = Hasher.MD5(username +":"+ realm +":"+ password); + ha1 = Hasher.MD5(username + ":" + realm + ":" + password); // If the algorithm directive's value is "MD5-sess", then HA1 is // HA1=MD5(MD5(username:realm:password):nonce:cnonce) return ha1; @@ -165,19 +165,19 @@ public class HttpDigestAuthPage implements HttpPage{ String ha2; // If the qop directive's value is "auth" or is unspecified, then HA2 is // HA2=MD5(method:digestURI) - ha2 = Hasher.MD5("MD5:"+ uri); + ha2 = Hasher.MD5("MD5:" + uri); // If the qop directive's value is "auth-int", then HA2 is // HA2=MD5(method:digestURI:MD5(entityBody)) return ha2; } - private static String generateResponseHash(String ha1, String ha2, String nonce){ + private static String generateResponseHash(String ha1, String ha2, String nonce) { String response; // If the qop directive's value is "auth" or "auth-int", then compute the response as follows: // response=MD5(HA1:nonce:nonceCount:cnonce:qop:HA2) // If the qop directive is unspecified, then compute the response as follows: // response=MD5(HA1:nonce:HA2) - response = Hasher.MD5(ha1 +":"+ nonce +":"+ ha2); + response = Hasher.MD5(ha1 + ":" + nonce + ":" + ha2); return response; } diff --git a/src/zutil/net/http/page/HttpFilePage.java b/src/zutil/net/http/page/HttpFilePage.java index 9ee30a6..daa4a0b 100755 --- a/src/zutil/net/http/page/HttpFilePage.java +++ b/src/zutil/net/http/page/HttpFilePage.java @@ -64,7 +64,7 @@ public class HttpFilePage implements HttpPage{ /** * @param file a reference to a root directory or a file. */ - public HttpFilePage(File file){ + public HttpFilePage(File file) { if (file == null) throw new IllegalArgumentException("Root path cannot be null.");; @@ -108,7 +108,7 @@ public class HttpFilePage implements HttpPage{ String url = headers.getRequestURL(); out.println("
  • " + containingFile + "
  • "); + + "'>" + containingFile + ""); } out.println(" "); out.println("
    "); @@ -137,7 +137,7 @@ public class HttpFilePage implements HttpPage{ if (!out.isHeaderSent()) out.setResponseStatusCode(500); log.log(Level.WARNING, null, e); - out.println("500 Internal Server Error: "+e.getMessage() ); + out.println("500 Internal Server Error: " +e.getMessage()); } } @@ -189,14 +189,14 @@ public class HttpFilePage implements HttpPage{ /** * Enable or disable showing of folder contents */ - public void showFolders(boolean enabled){ + public void showFolders(boolean enabled) { this.showFolders = enabled; } /** * If directory links should be redirected to index files */ - public void redirectToIndexFile(boolean enabled){ + public void redirectToIndexFile(boolean enabled) { this.redirectToIndex = enabled; } } diff --git a/src/zutil/net/http/page/HttpRedirectPage.java b/src/zutil/net/http/page/HttpRedirectPage.java index 3e7a256..932f61c 100755 --- a/src/zutil/net/http/page/HttpRedirectPage.java +++ b/src/zutil/net/http/page/HttpRedirectPage.java @@ -40,11 +40,11 @@ public class HttpRedirectPage implements HttpPage{ private String redirectUrl; - public HttpRedirectPage(String redirectUrl){ + public HttpRedirectPage(String redirectUrl) { this.redirectUrl = redirectUrl; } - public void setPermanentRedirect(boolean permanent){ + public void setPermanentRedirect(boolean permanent) { this.permanent = permanent; } @@ -63,14 +63,14 @@ public class HttpRedirectPage implements HttpPage{ "\n" + " \n" + " \n" + - " \n" + + " \n" + " \n" + " Page Redirection\n" + " \n" + " \n" + - " If you are not redirected automatically, follow the link to "+ redirectUrl +"\n" + + " If you are not redirected automatically, follow the link to " + redirectUrl + "\n" + " \n" + "" ); diff --git a/src/zutil/net/mqtt/MqttBroker.java b/src/zutil/net/mqtt/MqttBroker.java index 2482ddc..b964279 100755 --- a/src/zutil/net/mqtt/MqttBroker.java +++ b/src/zutil/net/mqtt/MqttBroker.java @@ -131,7 +131,7 @@ public class MqttBroker extends ThreadedTCPNetworkServer { if (listener == null) return; - for (String topic : subscriptionListeners.keySet()){ + for (String topic : subscriptionListeners.keySet()) { unsubscribe(topic, listener); } } @@ -148,7 +148,7 @@ public class MqttBroker extends ThreadedTCPNetworkServer { List topicSubscriptions = subscriptionListeners.get(topic); - if (topicSubscriptions.remove(listener)){ + if (topicSubscriptions.remove(listener)) { logger.finer("Subscriber unsubscribed from topic (" + topic + "), subscriber count: " + topicSubscriptions.size()); if (topicSubscriptions.isEmpty()) { diff --git a/src/zutil/net/mqtt/packet/MqttPacket.java b/src/zutil/net/mqtt/packet/MqttPacket.java index a6a9dce..8ed9315 100755 --- a/src/zutil/net/mqtt/packet/MqttPacket.java +++ b/src/zutil/net/mqtt/packet/MqttPacket.java @@ -47,7 +47,7 @@ public class MqttPacket { in.reset(); // Resolve the correct header class - switch (packet.type){ + switch (packet.type) { case PACKET_TYPE_CONN: packet = new MqttPacketConnect(); break; case PACKET_TYPE_CONNACK: packet = new MqttPacketConnectAck(); break; case PACKET_TYPE_PUBLISH: packet = new MqttPacketPublish(); break; @@ -63,7 +63,7 @@ public class MqttPacket { case PACKET_TYPE_PINGRESP: packet = new MqttPacketPingResp(); break; case PACKET_TYPE_DISCONNECT: packet = new MqttPacketDisconnect(); break; default: - throw new IOException("Unknown header type: "+ packet.type); + throw new IOException("Unknown header type: " + packet.type); } in.read(packet); // TODO: payload diff --git a/src/zutil/net/mqtt/packet/MqttVariableIntSerializer.java b/src/zutil/net/mqtt/packet/MqttVariableIntSerializer.java index 73245cb..0c17863 100755 --- a/src/zutil/net/mqtt/packet/MqttVariableIntSerializer.java +++ b/src/zutil/net/mqtt/packet/MqttVariableIntSerializer.java @@ -62,6 +62,6 @@ public class MqttVariableIntSerializer implements BinaryFieldSerializer if (x > 0) encodedByte = encodedByte & 128; out.write(encodedByte); - } while ( x > 0 ); + } while (x > 0); } } diff --git a/src/zutil/net/nio/NioClient.java b/src/zutil/net/nio/NioClient.java index 40eef30..a9ad5ba 100755 --- a/src/zutil/net/nio/NioClient.java +++ b/src/zutil/net/nio/NioClient.java @@ -71,7 +71,7 @@ public class NioClient extends NioNetwork{ send(remoteAddress, data); } - public SocketAddress getRemoteAddress(){ + public SocketAddress getRemoteAddress() { return remoteAddress; } } diff --git a/src/zutil/net/nio/NioNetwork.java b/src/zutil/net/nio/NioNetwork.java index 6ae7f2a..7992beb 100755 --- a/src/zutil/net/nio/NioNetwork.java +++ b/src/zutil/net/nio/NioNetwork.java @@ -93,7 +93,7 @@ public abstract class NioNetwork implements Runnable { * * @param worker the worker that should handle incoming messages */ - public void setDefaultWorker(Worker worker){ + public void setDefaultWorker(Worker worker) { this.worker = worker; } @@ -102,7 +102,7 @@ public abstract class NioNetwork implements Runnable { * Connect to a remote Server. */ protected void connect(SocketAddress address) throws IOException { - logger.fine("Connecting to: "+address); + logger.fine("Connecting to: " +address); // Create a non-blocking socket channel SocketChannel socketChannel = SocketChannel.open(); socketChannel.socket().setReuseAddress(true); @@ -128,7 +128,7 @@ public abstract class NioNetwork implements Runnable { * @param address the target address where the message should be sent * @param data the data to send */ - public void send(SocketAddress address, byte[] data){ + public void send(SocketAddress address, byte[] data) { logger.finest("Sending Queue..."); SocketChannel socket = getSocketChannel(address); @@ -231,13 +231,13 @@ public abstract class NioNetwork implements Runnable { // adds the client to the clients list registerSocketChannel(socketChannel); - logger.fine("New Connection("+socketChannel.getRemoteAddress()+")!!! Count: "+clients.size()); + logger.fine("New Connection(" + socketChannel.getRemoteAddress() + ")!!! Count: " + clients.size()); } /** * Finnish an ongoing remote connection establishment procedure */ - private void establishConnection(SelectionKey key){ + private void establishConnection(SelectionKey key) { SocketChannel socketChannel = (SocketChannel) key.channel(); try { @@ -248,7 +248,7 @@ public abstract class NioNetwork implements Runnable { key.interestOps(SelectionKey.OP_WRITE); registerSocketChannel(socketChannel); - logger.fine("Connection established("+socketChannel.getRemoteAddress()+")"); + logger.fine("Connection established(" + socketChannel.getRemoteAddress() + ")"); } catch (IOException e) { // Cancel the channel's registration with our selector e.printStackTrace(); @@ -265,7 +265,7 @@ public abstract class NioNetwork implements Runnable { synchronized (pendingWriteData) { List queue = pendingWriteData.get(socketChannel); - if(queue == null){ + if (queue == null) { queue = new ArrayList<>(); pendingWriteData.put(socketChannel, queue); } @@ -310,7 +310,7 @@ public abstract class NioNetwork implements Runnable { socketChannel.close(); clients.remove(remoteAdr); pendingWriteData.remove(socketChannel); - logger.fine("Connection forcibly closed("+remoteAdr+")! Remaining connections: "+clients.size()); + logger.fine("Connection forcibly closed(" + remoteAdr + ")! Remaining connections: " + clients.size()); throw new IOException("Remote forcibly closed the connection"); } @@ -321,7 +321,7 @@ public abstract class NioNetwork implements Runnable { key.cancel(); clients.remove(remoteAdr); pendingWriteData.remove(socketChannel); - logger.fine("Connection Closed("+remoteAdr+")! Remaining connections: "+clients.size()); + logger.fine("Connection Closed(" + remoteAdr + ")! Remaining connections: " + clients.size()); throw new IOException("Remote closed the connection"); } @@ -329,7 +329,7 @@ public abstract class NioNetwork implements Runnable { //byte[] rspByteData = new byte[numRead]; //System.arraycopy(readBuffer.array(), 0, rspByteData, 0, numRead); - try{ + try { Object rspData = Converter.toObject(readBuffer.array()); // Hand the data off to our worker thread @@ -339,14 +339,14 @@ public abstract class NioNetwork implements Runnable { } else { logger.fine("No worker set, message unhandled!"); } - }catch(Exception e){ + } catch (Exception e) { e.printStackTrace(); } } - private ClientData registerSocketChannel(SocketChannel socket){ + private ClientData registerSocketChannel(SocketChannel socket) { InetSocketAddress remoteAdr = (InetSocketAddress) socket.socket().getRemoteSocketAddress(); if (!clients.containsKey(remoteAdr)) { ClientData clientData = new ClientData(socket); @@ -354,7 +354,7 @@ public abstract class NioNetwork implements Runnable { } return clients.get(remoteAdr); } - private SocketChannel getSocketChannel(SocketAddress address){ + private SocketChannel getSocketChannel(SocketAddress address) { return clients.get(address).getSocketChannel(); } @@ -377,7 +377,7 @@ public abstract class NioNetwork implements Runnable { * Close all connections */ public void close() throws IOException{ - if(serverChannel != null){ + if (serverChannel != null) { serverChannel.close(); serverChannel.keyFor(selector).cancel(); } diff --git a/src/zutil/net/nio/NioServer.java b/src/zutil/net/nio/NioServer.java index 00009be..8625657 100755 --- a/src/zutil/net/nio/NioServer.java +++ b/src/zutil/net/nio/NioServer.java @@ -78,9 +78,9 @@ public class NioServer extends NioNetwork{ * * @param data the data to broadcast */ - public void broadcast(byte[] data){ - synchronized(clients){ - for(InetSocketAddress target : clients.keySet()){ + public void broadcast(byte[] data) { + synchronized(clients) { + for (InetSocketAddress target : clients.keySet()) { send(target, data); } } diff --git a/src/zutil/net/nio/response/ResponseHandler.java b/src/zutil/net/nio/response/ResponseHandler.java index 2cdcfae..a96407c 100755 --- a/src/zutil/net/nio/response/ResponseHandler.java +++ b/src/zutil/net/nio/response/ResponseHandler.java @@ -38,7 +38,7 @@ public abstract class ResponseHandler { * Blocks the calling thread until there is a response */ public void waitForResponse() { - while(!gotResponse()) { + while (!gotResponse()) { try { synchronized (this) { this.wait(); @@ -50,7 +50,7 @@ public abstract class ResponseHandler { /** * @return true if a response has been received */ - public boolean gotResponse(){ + public boolean gotResponse() { return (rsp != null); } diff --git a/src/zutil/net/nio/response/StringResponseMessage.java b/src/zutil/net/nio/response/StringResponseMessage.java index f83a292..05c6e80 100755 --- a/src/zutil/net/nio/response/StringResponseMessage.java +++ b/src/zutil/net/nio/response/StringResponseMessage.java @@ -34,7 +34,7 @@ public class StringResponseMessage extends EchoMessage implements RequestRespons private String msg; - public StringResponseMessage(String msg){ + public StringResponseMessage(String msg) { this.msg = msg; responseId = (long)(Math.random()*Long.MAX_VALUE); } @@ -44,11 +44,11 @@ public class StringResponseMessage extends EchoMessage implements RequestRespons return responseId; } - public void setString(String msg){ + public void setString(String msg) { this.msg = msg; } - public String toString(){ + public String toString() { return msg; } } \ No newline at end of file diff --git a/src/zutil/net/nio/server/ClientData.java b/src/zutil/net/nio/server/ClientData.java index 8b618ce..a6999b3 100755 --- a/src/zutil/net/nio/server/ClientData.java +++ b/src/zutil/net/nio/server/ClientData.java @@ -32,24 +32,24 @@ public class ClientData { private long lastMessageReceived; - public ClientData(SocketChannel socketChannel){ + public ClientData(SocketChannel socketChannel) { this.socketChannel = socketChannel; } - public SocketChannel getSocketChannel(){ + public SocketChannel getSocketChannel() { return socketChannel; } - public InetSocketAddress getAddress(){ + public InetSocketAddress getAddress() { return (InetSocketAddress) socketChannel.socket().getRemoteSocketAddress(); } - public void setLastMessageReceived(long time){ + public void setLastMessageReceived(long time) { lastMessageReceived = time; } - public long getLastMessageReceived(){ + public long getLastMessageReceived() { return lastMessageReceived; } } diff --git a/src/zutil/net/nio/worker/StandardWorker.java b/src/zutil/net/nio/worker/StandardWorker.java index 6892bc1..e8b6f42 100755 --- a/src/zutil/net/nio/worker/StandardWorker.java +++ b/src/zutil/net/nio/worker/StandardWorker.java @@ -52,7 +52,7 @@ public class StandardWorker extends ThreadedEventWorker { /** * Creates a new StandardWorker */ - public StandardWorker(NioNetwork nio){ + public StandardWorker(NioNetwork nio) { this.nio = nio; } @@ -61,27 +61,27 @@ public class StandardWorker extends ThreadedEventWorker { @Override public void messageEvent(WorkerEventData event) { try { - logger.finer("Message: "+event.data.getClass().getName()); + logger.finer("Message: " +event.data.getClass().getName()); - if(event.data instanceof EchoMessage && !((EchoMessage)event.data).echo()){ + if (event.data instanceof EchoMessage && !((EchoMessage)event.data).echo()) { // Echo back the received message ((EchoMessage)event.data).received(); - logger.finer("Echoing Message: "+event.data); + logger.finer("Echoing Message: " +event.data); nio.send(event.remoteAddress, event.data); } - else if(event.data instanceof RequestResponseMessage && - rspEvents.get(((RequestResponseMessage)event.data).getResponseId()) != null){ + else if (event.data instanceof RequestResponseMessage && + rspEvents.get(((RequestResponseMessage)event.data).getResponseId()) != null) { long responseId = ((RequestResponseMessage)event.data).getResponseId(); // Look up the handler for this channel ResponseHandler handler = rspEvents.get(responseId); // And pass the response to it handler.handleResponse(event.data); rspEvents.remove(responseId); - logger.finer("Response Request Message: "+event.data); + logger.finer("Response Request Message: " +event.data); } - else{ + else { // Check mapped workers - if(services.containsKey(event.data.getClass())){ + if (services.containsKey(event.data.getClass())) { services.get(event.data.getClass()).messageEvent(event); } } @@ -96,7 +96,7 @@ public class StandardWorker extends ThreadedEventWorker { * @param messageClass the received message class * @param worker the worker that should handle the specified message type */ - public void registerWorker(Class messageClass, ThreadedEventWorker worker){ + public void registerWorker(Class messageClass, ThreadedEventWorker worker) { services.put(messageClass, worker); } @@ -105,7 +105,7 @@ public class StandardWorker extends ThreadedEventWorker { * * @param messageClass the received message class */ - public void unregisterWorker(Class messageClass){ + public void unregisterWorker(Class messageClass) { services.remove(messageClass); } diff --git a/src/zutil/net/nio/worker/ThreadedEventWorker.java b/src/zutil/net/nio/worker/ThreadedEventWorker.java index 71b7407..b7b4139 100755 --- a/src/zutil/net/nio/worker/ThreadedEventWorker.java +++ b/src/zutil/net/nio/worker/ThreadedEventWorker.java @@ -27,14 +27,14 @@ package zutil.net.nio.worker; public abstract class ThreadedEventWorker extends Worker implements Runnable{ private Thread thread; - public ThreadedEventWorker(){ + public ThreadedEventWorker() { thread = new Thread(this); thread.start(); } public void run() { - while(true) { - try{ + while (true) { + try { // Wait for data to become available messageEvent(pollEvent()); } catch (Exception e) { diff --git a/src/zutil/net/nio/worker/Worker.java b/src/zutil/net/nio/worker/Worker.java index 3d0568e..3d129cd 100755 --- a/src/zutil/net/nio/worker/Worker.java +++ b/src/zutil/net/nio/worker/Worker.java @@ -45,7 +45,7 @@ public abstract class Worker { /** * @return true if there is a event in the queue */ - protected boolean hasEvent(){ + protected boolean hasEvent() { return !queue.isEmpty(); } @@ -54,7 +54,7 @@ public abstract class Worker { * * @return the next event */ - protected WorkerEventData pollEvent(){ + protected WorkerEventData pollEvent() { synchronized(queue) { while (queue.isEmpty()) { try { diff --git a/src/zutil/net/nio/worker/chat/ChatMessage.java b/src/zutil/net/nio/worker/chat/ChatMessage.java index ed75412..11f3b13 100755 --- a/src/zutil/net/nio/worker/chat/ChatMessage.java +++ b/src/zutil/net/nio/worker/chat/ChatMessage.java @@ -38,7 +38,7 @@ public class ChatMessage implements Message { /** * Registers the user to the main chat */ - public ChatMessage(){ + public ChatMessage() { this("", "", ChatMessageType.REGISTER); } @@ -47,7 +47,7 @@ public class ChatMessage implements Message { * * @param room The room to register to */ - public ChatMessage(String room){ + public ChatMessage(String room) { this("", room, ChatMessageType.REGISTER); } @@ -57,11 +57,11 @@ public class ChatMessage implements Message { * @param msg The message * @param room The room */ - public ChatMessage(String msg, String room){ + public ChatMessage(String msg, String room) { this(msg, room, ChatMessageType.MESSAGE); } - public ChatMessage(String msg, String room, ChatMessageType type){ + public ChatMessage(String msg, String room, ChatMessageType type) { this.msg = msg; this.room = room; this.type = type; diff --git a/src/zutil/net/nio/worker/chat/ChatService.java b/src/zutil/net/nio/worker/chat/ChatService.java index 2cd5f30..f6ca033 100755 --- a/src/zutil/net/nio/worker/chat/ChatService.java +++ b/src/zutil/net/nio/worker/chat/ChatService.java @@ -52,28 +52,28 @@ public class ChatService extends ThreadedEventWorker{ public void messageEvent(WorkerEventData event) { try { // New message - if(event.data instanceof ChatMessage){ + if (event.data instanceof ChatMessage) { ChatMessage chatmessage = (ChatMessage)event.data; //is this a new message - if(chatmessage.type == ChatMessage.ChatMessageType.MESSAGE){ + if (chatmessage.type == ChatMessage.ChatMessageType.MESSAGE) { // Is this the server - if(rooms.containsKey(chatmessage.room)){ + if (rooms.containsKey(chatmessage.room)) { LinkedList tmpList = rooms.get(chatmessage.room); // Broadcast the message - for(SocketAddress remote : tmpList){ + for (SocketAddress remote : tmpList) { event.network.send(remote, chatmessage); // TODO: should not be done for clients } } - logger.finer("New Chat Message: "+chatmessage.msg); + logger.finer("New Chat Message: " +chatmessage.msg); listener.messageAction(chatmessage.msg, chatmessage.room); } // register to a room - else if(chatmessage.type == ChatMessage.ChatMessageType.REGISTER){ + else if (chatmessage.type == ChatMessage.ChatMessageType.REGISTER) { registerUser(chatmessage.room, event.remoteAddress); } // unregister to a room - else if(chatmessage.type == ChatMessage.ChatMessageType.UNREGISTER){ + else if (chatmessage.type == ChatMessage.ChatMessageType.UNREGISTER) { unRegisterUser(chatmessage.room, event.remoteAddress); } } @@ -88,7 +88,7 @@ public class ChatService extends ThreadedEventWorker{ * * @param remoteAddress the address of the remote user */ - public void registerUser(SocketAddress remoteAddress){ + public void registerUser(SocketAddress remoteAddress) { registerUser("", remoteAddress); } @@ -98,9 +98,9 @@ public class ChatService extends ThreadedEventWorker{ * @param room the room name * @param remoteAddress the address of the remote user */ - public void registerUser(String room, SocketAddress remoteAddress){ + public void registerUser(String room, SocketAddress remoteAddress) { addRoom(room); - logger.fine("New Chat User: "+remoteAddress); + logger.fine("New Chat User: " +remoteAddress); rooms.get(room).add(remoteAddress); } @@ -110,9 +110,9 @@ public class ChatService extends ThreadedEventWorker{ * @param room the room name * @param remoteAddress the address of the remote user */ - public void unRegisterUser(String room, SocketAddress remoteAddress){ - if(rooms.containsKey(room)){ - logger.fine("Remove Chat User: "+remoteAddress); + public void unRegisterUser(String room, SocketAddress remoteAddress) { + if (rooms.containsKey(room)) { + logger.fine("Remove Chat User: " +remoteAddress); rooms.get(room).remove(remoteAddress); removeRoom(room); } @@ -123,9 +123,9 @@ public class ChatService extends ThreadedEventWorker{ * * @param room The name of the room */ - private void addRoom(String room){ - if(!rooms.containsKey(room)){ - logger.fine("New Chat Room: "+room); + private void addRoom(String room) { + if (!rooms.containsKey(room)) { + logger.fine("New Chat Room: " +room); rooms.put(room, new LinkedList<>()); } } @@ -135,9 +135,9 @@ public class ChatService extends ThreadedEventWorker{ * * @param room The room */ - private void removeRoom(String room){ - if(rooms.get(room).isEmpty()){ - logger.fine("Remove Chat Room: "+room); + private void removeRoom(String room) { + if (rooms.get(room).isEmpty()) { + logger.fine("Remove Chat Room: " + room); rooms.remove(room); } } diff --git a/src/zutil/net/nio/worker/grid/GridClient.java b/src/zutil/net/nio/worker/grid/GridClient.java index 9e47fc6..6759ace 100755 --- a/src/zutil/net/nio/worker/grid/GridClient.java +++ b/src/zutil/net/nio/worker/grid/GridClient.java @@ -53,7 +53,7 @@ public class GridClient extends ThreadedEventWorker { * @param thread the Thread interface to run for the jobs * @param network the NioClient to use to communicate to the server */ - public GridClient(GridThread thread, NioClient network){ + public GridClient(GridThread thread, NioClient network) { jobQueue = new LinkedList<>(); GridClient.thread = thread; GridClient.network = network; @@ -68,7 +68,7 @@ public class GridClient extends ThreadedEventWorker { network.setDefaultWorker(this); network.send(new GridMessage(GridMessage.REGISTER)); - for(int i=0; i implements Message { * * @param type is the type of message */ - public GridMessage(int type){ + public GridMessage(int type) { this(type, 0, null); } @@ -69,7 +69,7 @@ public class GridMessage implements Message { * @param type is the type of message * @param jobId is the id of the job */ - public GridMessage(int type, int jobId){ + public GridMessage(int type, int jobId) { this(type, jobId, null); } @@ -80,7 +80,7 @@ public class GridMessage implements Message { * @param jobId is the id of the job * @param data is the data to send with this message */ - public GridMessage(int type, int jobId, T data){ + public GridMessage(int type, int jobId, T data) { this.type = type; this.jobId = jobId; this.data = data; @@ -89,21 +89,21 @@ public class GridMessage implements Message { /** * @return the type of message */ - public int messageType(){ + public int messageType() { return type; } /** * @return the job id for this message */ - public int getJobQueueID(){ + public int getJobQueueID() { return jobId; } /** * @return the data in this message, may not always carry any data. */ - public T getData(){ + public T getData() { return data; } } diff --git a/src/zutil/net/nio/worker/grid/GridServerWorker.java b/src/zutil/net/nio/worker/grid/GridServerWorker.java index c2b07a6..2b4a845 100755 --- a/src/zutil/net/nio/worker/grid/GridServerWorker.java +++ b/src/zutil/net/nio/worker/grid/GridServerWorker.java @@ -34,7 +34,7 @@ import java.util.Queue; /** * Implements a simple network computing server - * + * * @author Ziver */ @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -48,7 +48,7 @@ public class GridServerWorker extends ThreadedEventWorker{ private int nextJobID; - public GridServerWorker(GridResultHandler resHandler, GridJobGenerator jobGenerator){ + public GridServerWorker(GridResultHandler resHandler, GridJobGenerator jobGenerator) { this.resHandler = resHandler; this.jobGenerator = jobGenerator; nextJobID = 0; @@ -64,21 +64,21 @@ public class GridServerWorker extends ThreadedEventWorker{ public void messageEvent(WorkerEventData e) { try { // ignores other messages than GridMessage - if(e.data instanceof GridMessage){ + if (e.data instanceof GridMessage) { GridMessage msg = (GridMessage)e.data; GridJob job; - switch(msg.messageType()){ + switch(msg.messageType()) { case GridMessage.REGISTER: e.network.send(e.remoteAddress, new GridMessage(GridMessage.INIT_DATA, 0, jobGenerator.initValues())); break; // Sending new data to compute to the client case GridMessage.NEW_DATA: - if(!resendJobQueue.isEmpty()){ // checks first if there is a job for recalculation + if (!resendJobQueue.isEmpty()) { // checks first if there is a job for recalculation job = resendJobQueue.poll(); job.renewTimeStamp(); } - else{ // generates new job + else { // generates new job job = new GridJob(nextJobID, jobGenerator.generateJob()); jobs.put(job.jobID, job); @@ -111,7 +111,7 @@ public class GridServerWorker extends ThreadedEventWorker{ * * @param timeout is the timeout in minutes */ - public void setJobTimeout(int timeout){ + public void setJobTimeout(int timeout) { jobTimeout = 1000*60*timeout; } @@ -120,15 +120,15 @@ public class GridServerWorker extends ThreadedEventWorker{ * Runs some behind the scenes stuff * like job garbage collection. */ - public void run(){ - while(true){ + public void run() { + while (true) { long time = System.currentTimeMillis(); - for(int jobID : jobs.keySet()){ - if(time-jobs.get(jobID).timestamp > jobTimeout){ + for (int jobID : jobs.keySet()) { + if (time-jobs.get(jobID).timestamp > jobTimeout) { resendJobQueue.add(jobs.get(jobID)); } } - try{Thread.sleep(1000*60*1);}catch(Exception e){}; + try {Thread.sleep(1000*60*1);} catch (Exception e) {}; } } } diff --git a/src/zutil/net/nio/worker/grid/GridThread.java b/src/zutil/net/nio/worker/grid/GridThread.java index 3e14aa3..09040a5 100755 --- a/src/zutil/net/nio/worker/grid/GridThread.java +++ b/src/zutil/net/nio/worker/grid/GridThread.java @@ -25,9 +25,9 @@ package zutil.net.nio.worker.grid; /** - * This interface is the thread that will do + * This interface is the thread that will do * all the computation in the grid - * + * * @author Ziver */ public abstract class GridThread implements Runnable{ @@ -38,15 +38,15 @@ public abstract class GridThread implements Runnable{ */ public abstract void setInitData(Object data); - public void run(){ - while(true){ + public void run() { + while (true) { GridJob tmp = null; try { tmp = GridClient.getNextJob(); compute(tmp); } catch (Exception e) { e.printStackTrace(); - if(tmp != null){ + if (tmp != null) { GridClient.jobError(tmp.jobID); } } diff --git a/src/zutil/net/nio/worker/sync/GraphicsSyncMessage.java b/src/zutil/net/nio/worker/sync/GraphicsSyncMessage.java index eb5b327..d5aaee3 100755 --- a/src/zutil/net/nio/worker/sync/GraphicsSyncMessage.java +++ b/src/zutil/net/nio/worker/sync/GraphicsSyncMessage.java @@ -37,13 +37,13 @@ public class GraphicsSyncMessage extends SyncMessage{ public float rotZ; public float rotW; - public GraphicsSyncMessage(String id){ + public GraphicsSyncMessage(String id) { this.type = MessageType.SYNC; this.id = id; } - public boolean equals(Object obj){ - if(obj instanceof GraphicsSyncMessage){ + public boolean equals(Object obj) { + if (obj instanceof GraphicsSyncMessage) { GraphicsSyncMessage tmp = (GraphicsSyncMessage)obj; return (tmp.locX == locX && tmp.locY == locY && tmp.locZ == locZ && tmp.rotX == rotX && diff --git a/src/zutil/net/nio/worker/sync/ObjectSync.java b/src/zutil/net/nio/worker/sync/ObjectSync.java index 7dba5b1..ff78e1d 100755 --- a/src/zutil/net/nio/worker/sync/ObjectSync.java +++ b/src/zutil/net/nio/worker/sync/ObjectSync.java @@ -27,7 +27,7 @@ package zutil.net.nio.worker.sync; public abstract class ObjectSync { public String id; - public ObjectSync(String id){ + public ObjectSync(String id) { this.id = id; } diff --git a/src/zutil/net/nio/worker/sync/SyncService.java b/src/zutil/net/nio/worker/sync/SyncService.java index 2c6111a..9ac53de 100755 --- a/src/zutil/net/nio/worker/sync/SyncService.java +++ b/src/zutil/net/nio/worker/sync/SyncService.java @@ -42,23 +42,23 @@ public class SyncService extends ThreadedEventWorker{ /** * Adds a object to be synced */ - public void addSyncObject(ObjectSync os){ + public void addSyncObject(ObjectSync os) { sync.put(os.id, os); - logger.fine("New Sync object: "+os); + logger.fine("New Sync object: " + os); } @Override - public void messageEvent(WorkerEventData event){ - if(event.data instanceof SyncMessage){ + public void messageEvent(WorkerEventData event) { + if (event.data instanceof SyncMessage) { SyncMessage syncMessage = (SyncMessage)event.data; - if(syncMessage.type == SyncMessage.MessageType.SYNC){ + if (syncMessage.type == SyncMessage.MessageType.SYNC) { ObjectSync obj = sync.get(syncMessage.id); - if(obj != null){ + if (obj != null) { logger.finer("Syncing Message..."); obj.syncObject(syncMessage); } } - else if(syncMessage.type == SyncMessage.MessageType.REMOVE){ + else if (syncMessage.type == SyncMessage.MessageType.REMOVE) { sync.remove(syncMessage.id).remove(); } } @@ -67,8 +67,8 @@ public class SyncService extends ThreadedEventWorker{ /** * Syncs all the objects whit the server */ - public void sync(){ - for(String id : sync.keySet()){ + public void sync() { + for (String id : sync.keySet()) { sync.get(id).sendSync(); } } diff --git a/src/zutil/net/smtp/Email.java b/src/zutil/net/smtp/Email.java index 11a1730..c240be1 100755 --- a/src/zutil/net/smtp/Email.java +++ b/src/zutil/net/smtp/Email.java @@ -36,7 +36,7 @@ import static zutil.net.smtp.SmtpClient.NEWLINE; /** * Simplifies sending of a email - * + * * @author Ziver */ public class Email { @@ -60,68 +60,68 @@ public class Email { - public Email(){ } + public Email() { } - public void setFrom(String address){ + public void setFrom(String address) { this.fromAddress = sanitizeParam(address); } - public void setFrom(String address, String niceName){ + public void setFrom(String address, String niceName) { fromAddress = sanitizeParam(address); fromName = sanitizeParam(niceName); } - public String getFromAddress(){ + public String getFromAddress() { return fromAddress; } public String getFromName() { return fromName; } - public void setReplyTo(String address){ + public void setReplyTo(String address) { this.replyToAddress = sanitizeParam(address); } public String getReplyToAddress() { return replyToAddress; } - public void setTo(String address){ + public void setTo(String address) { this.toAddress = sanitizeParam(address); } - public void setTo(String address, String niceName){ + public void setTo(String address, String niceName) { this.toAddress = sanitizeParam(address); this.toName = sanitizeParam(niceName); } - public String getToAddress(){ + public String getToAddress() { return toAddress; } public String getToName() { return toName; } - public void setDate(Date date){ + public void setDate(Date date) { this.date = date; } - public void setContentType(ContentType t){ + public void setContentType(ContentType t) { type = t; } - public void setSubject(String subject){ + public void setSubject(String subject) { this.subject = sanitizeParam(subject); } - public String getSubject(){ + public String getSubject() { return subject; } - public void setMessage(String msg){ + public void setMessage(String msg) { message = msg.replaceAll("(\\r\\n|\\n)", NEWLINE); - message = message.replaceAll(NEWLINE+"\\.", NEWLINE +".."); + message = message.replaceAll(NEWLINE + "\\.", NEWLINE + ".."); } - public String getMessage(){ + public String getMessage() { return message; } - private String sanitizeParam(String param){ + private String sanitizeParam(String param) { return PATTERN_NEWLINE.matcher(param).replaceAll(""); } @@ -132,47 +132,47 @@ public class Email { * @throws IllegalArgumentException if from address and to address has not been set */ public void write(Writer out) throws IOException{ - if(fromAddress == null) + if (fromAddress == null) throw new IllegalArgumentException("From value cannot be null!"); - if(toAddress == null) + if (toAddress == null) throw new IllegalArgumentException("To value cannot be null!"); //************ Headers // From if (fromName !=null) - out.write("From: "+ fromName +" <"+ fromAddress +">"+ NEWLINE); + out.write("From: " + fromName + " <" + fromAddress + ">" + NEWLINE); else - out.write("From: "+ fromAddress + NEWLINE); + out.write("From: " + fromAddress + NEWLINE); // Reply-To - if ( replyToAddress != null ) - out.write("Reply-To: <"+ replyToAddress +">"+ NEWLINE); + if (replyToAddress != null) + out.write("Reply-To: <" + replyToAddress + ">" + NEWLINE); // To if (toName !=null) - out.write("To: "+ toName +" <"+ toAddress +">"+ NEWLINE); + out.write("To: " + toName + " <" + toAddress + ">" + NEWLINE); else - out.write("To: "+ toAddress + NEWLINE); + out.write("To: " + toAddress + NEWLINE); // Date if (date != null) - out.write("Date: "+dateFormatter.format(date) + NEWLINE); + out.write("Date: " +dateFormatter.format(date) + NEWLINE); else - out.write("Date: "+dateFormatter.format(new Date(System.currentTimeMillis())) + NEWLINE); + out.write("Date: " +dateFormatter.format(new Date(System.currentTimeMillis())) + NEWLINE); // Content type - switch( type ){ + switch(type) { case HTML: - out.write("Content-Type: text/html;"+ NEWLINE); break; + out.write("Content-Type: text/html;" + NEWLINE); break; default: - out.write("Content-Type: text/plain;"+ NEWLINE); break; + out.write("Content-Type: text/plain;" + NEWLINE); break; } // Subject - out.write("Subject: "+(subject!=null ? subject : "") + NEWLINE); + out.write("Subject: " +(subject!=null ? subject : "") + NEWLINE); out.write(NEWLINE); //*********** Mesasge - out.write( message ); + out.write(message); } } \ No newline at end of file diff --git a/src/zutil/net/smtp/SmtpClient.java b/src/zutil/net/smtp/SmtpClient.java index 9d5d901..08f0c05 100755 --- a/src/zutil/net/smtp/SmtpClient.java +++ b/src/zutil/net/smtp/SmtpClient.java @@ -105,11 +105,11 @@ public class SmtpClient { * @param email a email object containing message specific data */ public synchronized void send(Email email) { - if(email.getFromAddress() == null) + if (email.getFromAddress() == null) throw new IllegalArgumentException("From value cannot be null!"); - if(email.getToAddress() == null) + if (email.getToAddress() == null) throw new IllegalArgumentException("To value cannot be null!"); - try{ + try { // Pre metadata sendCommand(CMD_FROM + ":" + email.getFromAddress()); sendCommand(CMD_TO + ":" + email.getToAddress()); @@ -119,8 +119,8 @@ public class SmtpClient { out.write(NEWLINE); sendCommand(CMD_DATA_END); reset(); - }catch(IOException e){ - logger.log(Level.SEVERE, null,e ); + } catch (IOException e) { + logger.log(Level.SEVERE, null, e); } } @@ -133,7 +133,7 @@ public class SmtpClient { * @return the server response code */ public synchronized int sendCommand(String cmd) throws IOException{ - logger.finest(">> "+cmd); + logger.finest(">> " +cmd); out.write(cmd + NEWLINE); out.flush(); String reply = readCommand(); @@ -147,14 +147,14 @@ public class SmtpClient { */ public synchronized String readCommand() throws IOException{ String tmp = in.readLine(); - logger.finest(">> "+tmp); - if(parseReturnCode(tmp) >= 400 ) + logger.finest(">> " +tmp); + if (parseReturnCode(tmp) >= 400) throw new IOException(tmp); return tmp; } - private static int parseReturnCode(String msg){ + private static int parseReturnCode(String msg) { return Integer.parseInt(msg.substring(0, 3)); } diff --git a/src/zutil/net/ssdp/SSDPClient.java b/src/zutil/net/ssdp/SSDPClient.java index 11aa570..c787de0 100755 --- a/src/zutil/net/ssdp/SSDPClient.java +++ b/src/zutil/net/ssdp/SSDPClient.java @@ -65,7 +65,7 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork * listening socket at the SSDP port. */ public SSDPClient() throws IOException{ - super( SSDP_MULTICAST_ADDR, SSDP_PORT ); + super(SSDP_MULTICAST_ADDR, SSDP_PORT); super.setThread(this); services_st = new HashMap<>(); @@ -85,36 +85,36 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork * MX: 3 * */ - public void requestService(String searchTarget){ + public void requestService(String searchTarget) { requestService(searchTarget, null); } - public void requestService(String searchTarget, HashMap headers){ + public void requestService(String searchTarget, HashMap headers) { try { // Generate an SSDP discover message ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - HttpPrintStream http = new HttpPrintStream( buffer, HttpPrintStream.HttpMessageType.REQUEST ); + HttpPrintStream http = new HttpPrintStream(buffer, HttpPrintStream.HttpMessageType.REQUEST); http.setRequestType("M-SEARCH"); http.setRequestURL("*"); - http.setHeader("Host", SSDP_MULTICAST_ADDR +":"+ SSDP_PORT ); - http.setHeader("ST", searchTarget ); - http.setHeader("Man", "\"ssdp:discover\"" ); - http.setHeader("MX", "3" ); - http.setHeader("USER-AGENT", USER_AGENT ); - if(headers != null) { + http.setHeader("Host", SSDP_MULTICAST_ADDR + ":" + SSDP_PORT); + http.setHeader("ST", searchTarget); + http.setHeader("Man", "\"ssdp:discover\""); + http.setHeader("MX", "3"); + http.setHeader("USER-AGENT", USER_AGENT); + if (headers != null) { for (String key : headers.keySet()) { http.setHeader(key, headers.get(key)); } } - logger.log(Level.FINEST, "Sending Multicast: "+ http); + logger.log(Level.FINEST, "Sending Multicast: " + http); http.flush(); byte[] data = buffer.toByteArray(); - //System.out.println(new String(data)+"****************"); + //System.out.println(new String(data) + "****************"); DatagramPacket packet = new DatagramPacket( data, data.length, - InetAddress.getByName( SSDP_MULTICAST_ADDR ), - SSDP_PORT ); - super.send( packet ); + InetAddress.getByName(SSDP_MULTICAST_ADDR), + SSDP_PORT); + super.send(packet); http.close(); } catch (Exception e) { e.printStackTrace(); @@ -124,7 +124,7 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork /** * Set a listener that will be notified when new services are detected */ - public void setListener(SSDPServiceListener listener){ + public void setListener(SSDPServiceListener listener) { this.listener = listener; } @@ -135,8 +135,8 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork * @param searchTarget is the search target * @return a list of received services */ - public LinkedList getServices(String searchTarget){ - if(services_st.get(searchTarget) == null) + public LinkedList getServices(String searchTarget) { + if (services_st.get(searchTarget) == null) return new LinkedList<>(); return services_st.get(searchTarget); } @@ -147,8 +147,8 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork * @param searchTarget is the search target * @return the amount of services cached */ - public int getServicesCount(String searchTarget){ - if(services_st.containsKey(searchTarget)){ + public int getServicesCount(String searchTarget) { + if (services_st.containsKey(searchTarget)) { return services_st.get(searchTarget).size(); } return 0; @@ -160,22 +160,22 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork * @param usn is the unique identifier for a service * @return an service, null if there is no such service */ - public StandardSSDPInfo getService(String usn){ - return services_usn.get( usn ); + public StandardSSDPInfo getService(String usn) { + return services_usn.get(usn); } /** * Clears all the received information of the services */ - public void clearServices(){ + public void clearServices() { services_usn.clear(); services_st.clear(); } /** * Clears all services matching the search target */ - public void clearServices(String st){ - if(services_st.get(st) != null) { + public void clearServices(String st) { + if (services_st.get(st) != null) { for (StandardSSDPInfo service : services_st.get(st)) { services_usn.remove(service.getUSN()); } @@ -208,7 +208,7 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork } // Remove service - if ("NOTIFY".equals(header.getRequestType()) && "ssdp:byebye".equalsIgnoreCase(header.getHeader("NTS"))){ + if ("NOTIFY".equals(header.getRequestType()) && "ssdp:byebye".equalsIgnoreCase(header.getHeader("NTS"))) { logger.log(Level.FINER, "Received NOTIFY:byebye (from: " + packet.getAddress() + "): " + header); if (service != null) { services_usn.remove(usn); @@ -224,7 +224,7 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork boolean newService = false; // Add new service - if (service == null){ + if (service == null) { newService = true; service = new StandardSSDPInfo(); services_usn.put(usn, service); @@ -249,17 +249,17 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork else { logger.log(Level.FINEST, "Ignored (from: " + packet.getAddress() + "): " + header); } - } catch (IOException e){ + } catch (IOException e) { logger.log(Level.SEVERE, null, e); } } - private long getCacheTime(String cache_control){ + private long getCacheTime(String cache_control) { long ret = 0; HashMap tmpMap = new HashMap<>(); HttpHeaderParser.parseHeaderValues(tmpMap, cache_control, ","); - if(tmpMap.containsKey("max-age")) - ret = Long.parseLong( tmpMap.get("max-age") ); + if (tmpMap.containsKey("max-age")) + ret = Long.parseLong(tmpMap.get("max-age")); return ret; } diff --git a/src/zutil/net/ssdp/SSDPServer.java b/src/zutil/net/ssdp/SSDPServer.java index db5f9c8..5372670 100755 --- a/src/zutil/net/ssdp/SSDPServer.java +++ b/src/zutil/net/ssdp/SSDPServer.java @@ -82,13 +82,13 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork public SSDPServer() throws IOException{ - super( SSDP_MULTICAST_ADDR, SSDP_PORT ); - super.setThread( this ); + super(SSDP_MULTICAST_ADDR, SSDP_PORT); + super.setThread(this); services = new HashMap<>(); - setCacheTime( DEFAULT_CACHE_TIME ); - enableNotify( true ); + setCacheTime(DEFAULT_CACHE_TIME); + enableNotify(true); } /** @@ -96,8 +96,8 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork * * @param service add a new service to be announced */ - public void addService(SSDPServiceInfo service){ - services.put( service.getSearchTarget(), service ); + public void addService(SSDPServiceInfo service) { + services.put(service.getSearchTarget(), service); } /** * Remove a service from being announced. This function will @@ -105,9 +105,9 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork * * @param searchTarget is the ST value in SSDP */ - public void removeService(String searchTarget){ - sendByeBye( searchTarget ); - services.remove( searchTarget ); + public void removeService(String searchTarget) { + sendByeBye(searchTarget); + services.remove(searchTarget); } /** @@ -117,9 +117,9 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork * * @param time is the time in seconds */ - public void setCacheTime(int time){ + public void setCacheTime(int time) { cache_time = time; - if( isNotifyEnabled() ){ + if (isNotifyEnabled()) { enableNotify(false); enableNotify(true); } @@ -129,12 +129,12 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork * Enable or disable notification messages to clients * every cache_time/2 seconds */ - public void enableNotify(boolean enable){ - if( enable && notifyTimer==null ){ + public void enableNotify(boolean enable) { + if (enable && notifyTimer == null) { notifyTimer = new NotifyTimer(); Timer timer = new Timer(); timer.schedule(new NotifyTimer(), 0, cache_time*1000/2); - }else if( !enable && notifyTimer!=null ){ + } else if (!enable && notifyTimer != null) { notifyTimer.cancel(); notifyTimer = null; } @@ -142,7 +142,7 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork /** * @return if notification messages is enabled */ - public boolean isNotifyEnabled(){ + public boolean isNotifyEnabled() { return notifyTimer != null; } @@ -167,36 +167,36 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork */ public void receivedPacket(DatagramPacket packet, ThreadedUDPNetwork network) { try { - String msg = new String( packet.getData(), packet.getOffset(), packet.getLength() ); - HttpHeaderParser headerParser = new HttpHeaderParser( msg ); + String msg = new String(packet.getData(), packet.getOffset(), packet.getLength()); + HttpHeaderParser headerParser = new HttpHeaderParser(msg); HttpHeader header = headerParser.read(); // ******* Respond // Check that the message is an ssdp discovery message - if( header.getRequestType() != null && header.getRequestType().equalsIgnoreCase("M-SEARCH") ){ + if (header.getRequestType() != null && header.getRequestType().equalsIgnoreCase("M-SEARCH")) { String man = header.getHeader("Man"); - if(man != null) + if (man != null) man = StringUtil.trim(man, '\"'); String st = header.getHeader("ST"); // Check that its the correct URL and that its an ssdp:discover message - if( header.getRequestURL().equals("*") && "ssdp:discover".equalsIgnoreCase(man) ){ + if (header.getRequestURL().equals("*") && "ssdp:discover".equalsIgnoreCase(man)) { // Check if the requested service exists - if( services.containsKey( st ) ){ - logger.log(Level.FINEST, "Received Multicast(from: "+packet.getAddress()+"): "+ header); + if (services.containsKey(st)) { + logger.log(Level.FINEST, "Received Multicast(from: " + packet.getAddress() + "): " + header); // Generate the SSDP response ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - HttpPrintStream http = new HttpPrintStream( buffer ); + HttpPrintStream http = new HttpPrintStream(buffer); http.setResponseStatusCode(200); - http.setHeader("Location", services.get(st).getLocation() ); - http.setHeader("USN", services.get(st).getUSN() ); - http.setHeader("Server", SERVER_INFO ); - http.setHeader("ST", st ); - http.setHeader("EXT", "" ); - http.setHeader("Cache-Control", "max-age = "+ cache_time ); - if(services.get(st) instanceof SSDPCustomInfo) + http.setHeader("Location", services.get(st).getLocation()); + http.setHeader("USN", services.get(st).getUSN()); + http.setHeader("Server", SERVER_INFO); + http.setHeader("ST", st); + http.setHeader("EXT", ""); + http.setHeader("Cache-Control", "max-age = " + cache_time); + if (services.get(st) instanceof SSDPCustomInfo) ((SSDPCustomInfo)services.get(st)).writeHeaders(http); - logger.log(Level.FINEST, "Sending Response: "+ http); + logger.log(Level.FINEST, "Sending Response: " + http); http.flush(); byte[] data = buffer.toByteArray(); @@ -204,7 +204,7 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork data, data.length, packet.getAddress(), packet.getPort()); - network.send( packet ); + network.send(packet); http.close(); } } @@ -223,16 +223,16 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork * @author Ziver */ private class NotifyTimer extends TimerTask { - public void run(){ + public void run() { sendNotify(); } } /** * Sends keep-alive messages to update the cache of the clients */ - public void sendNotify(){ - for(String st : services.keySet()){ - sendNotify( st ); + public void sendNotify() { + for (String st : services.keySet()) { + sendNotify(st); } } /** @@ -249,22 +249,22 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork * Location: http://localhost:80 * Cache-Control: max-age = 7393 */ - public void sendNotify(String searchTarget){ + public void sendNotify(String searchTarget) { try { SSDPServiceInfo service = services.get(searchTarget); // Generate the SSDP response ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - HttpPrintStream http = new HttpPrintStream( buffer, HttpPrintStream.HttpMessageType.REQUEST ); + HttpPrintStream http = new HttpPrintStream(buffer, HttpPrintStream.HttpMessageType.REQUEST); http.setRequestType("NOTIFY"); http.setRequestURL("*"); - http.setHeader("Server", SERVER_INFO ); - http.setHeader("Host", SSDP_MULTICAST_ADDR+":"+SSDP_PORT ); - http.setHeader("NT", searchTarget ); - http.setHeader("NTS", "ssdp:alive" ); - http.setHeader("Location", service.getLocation() ); - http.setHeader("Cache-Control", "max-age = "+cache_time ); - http.setHeader("USN", service.getUSN() ); - if(service instanceof SSDPCustomInfo) + http.setHeader("Server", SERVER_INFO); + http.setHeader("Host", SSDP_MULTICAST_ADDR + ":" + SSDP_PORT); + http.setHeader("NT", searchTarget); + http.setHeader("NTS", "ssdp:alive"); + http.setHeader("Location", service.getLocation()); + http.setHeader("Cache-Control", "max-age = " + cache_time); + http.setHeader("USN", service.getUSN()); + if (service instanceof SSDPCustomInfo) ((SSDPCustomInfo) service).writeHeaders(http); logger.log(Level.FINEST, "Sending Notification: " + http); http.flush(); @@ -272,9 +272,9 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork byte[] data = buffer.toByteArray(); DatagramPacket packet = new DatagramPacket( data, data.length, - InetAddress.getByName( SSDP_MULTICAST_ADDR ), - SSDP_PORT ); - super.send( packet ); + InetAddress.getByName(SSDP_MULTICAST_ADDR), + SSDP_PORT); + super.send(packet); http.close(); } catch (Exception e) { @@ -287,9 +287,9 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork * Shutdown message is sent to the clients that all * the service is shutting down. */ - public void sendByeBye(){ - for(String st : services.keySet()){ - sendByeBye( st ); + public void sendByeBye() { + for (String st : services.keySet()) { + sendByeBye(st); } } /** @@ -304,27 +304,27 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork * NTS: ssdp:byebye * USN: someunique:idscheme3 */ - public void sendByeBye(String searchTarget){ + public void sendByeBye(String searchTarget) { try { // Generate the SSDP response ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - HttpPrintStream http = new HttpPrintStream( buffer, HttpPrintStream.HttpMessageType.REQUEST ); + HttpPrintStream http = new HttpPrintStream(buffer, HttpPrintStream.HttpMessageType.REQUEST); http.setRequestType("NOTIFY"); http.setRequestURL("*"); - http.setHeader("Server", SERVER_INFO ); - http.setHeader("Host", SSDP_MULTICAST_ADDR+":"+SSDP_PORT ); - http.setHeader("NT", searchTarget ); - http.setHeader("NTS", "ssdp:byebye" ); - http.setHeader("USN", services.get(searchTarget).getUSN() ); + http.setHeader("Server", SERVER_INFO); + http.setHeader("Host", SSDP_MULTICAST_ADDR + ":" + SSDP_PORT); + http.setHeader("NT", searchTarget); + http.setHeader("NTS", "ssdp:byebye"); + http.setHeader("USN", services.get(searchTarget).getUSN()); logger.log(Level.FINEST, "Sending ByeBye: " + http); http.flush(); byte[] data = buffer.toByteArray(); DatagramPacket packet = new DatagramPacket( data, data.length, - InetAddress.getByName( SSDP_MULTICAST_ADDR ), - SSDP_PORT ); - super.send( packet ); + InetAddress.getByName(SSDP_MULTICAST_ADDR), + SSDP_PORT); + super.send(packet); http.close(); } catch (Exception e) { diff --git a/src/zutil/net/ssdp/StandardSSDPInfo.java b/src/zutil/net/ssdp/StandardSSDPInfo.java index 4ddbce8..8c6a32b 100755 --- a/src/zutil/net/ssdp/StandardSSDPInfo.java +++ b/src/zutil/net/ssdp/StandardSSDPInfo.java @@ -80,38 +80,38 @@ public class StandardSSDPInfo implements SSDPServiceInfo, SSDPCustomInfo{ /** * @return The URL to the Service, e.g. "http://192.168.0.1:80/index.html" */ - public String getLocation(){ + public String getLocation() { return location; } /** * @return the Search Target, e.g. "upnp:rootdevice" */ - public String getSearchTarget(){ + public String getSearchTarget() { return st; } /** * @return the expiration time for the values in this object */ - public long getExpirationTime(){ + public long getExpirationTime() { return expiration_time; } /** * @return the USN value, e.g. "uuid:abcdefgh-7dec-11d0-a765-00a0c91e6bf6 " */ - public String getUSN(){ - if( usn==null ) + public String getUSN() { + if (usn == null) usn = genUSN(); - return usn+"::"+st; + return usn + "::" + st; } /** * @return only the USN UUID String */ - public String getUUID(){ - if( usn==null ) + public String getUUID() { + if (usn == null) usn = genUSN(); return usn; } @@ -121,19 +121,19 @@ public class StandardSSDPInfo implements SSDPServiceInfo, SSDPCustomInfo{ * * @return an unique string that corresponds to the service */ - private String genUSN(){ - return "uuid:" + UUID.nameUUIDFromBytes( (st+location+Math.random()).getBytes() ); + private String genUSN() { + return "uuid:" + UUID.nameUUIDFromBytes((st+location+Math.random()).getBytes()); } - public String toString(){ - return "USN: "+usn+"\nLocation: "+location+"\nST: "+st+"\nExpiration-Time: "+new Date(expiration_time); + public String toString() { + return "USN: " + usn + "\nLocation: " + location + "\nST: " + st + "\nExpiration-Time: " + new Date(expiration_time); } public void setHeader(String key, String value) { headers.put(key, value); } - public String getHeader(String header){ + public String getHeader(String header) { return headers.get(header); } @Override @@ -151,7 +151,7 @@ public class StandardSSDPInfo implements SSDPServiceInfo, SSDPCustomInfo{ } } - public InetAddress getInetAddress(){ + public InetAddress getInetAddress() { return inetAddress; } diff --git a/src/zutil/net/threaded/ThreadedTCPNetworkServer.java b/src/zutil/net/threaded/ThreadedTCPNetworkServer.java index 4ae041f..596020e 100755 --- a/src/zutil/net/threaded/ThreadedTCPNetworkServer.java +++ b/src/zutil/net/threaded/ThreadedTCPNetworkServer.java @@ -59,7 +59,7 @@ public abstract class ThreadedTCPNetworkServer extends Thread{ * * @param port The port that the server should listen to */ - public ThreadedTCPNetworkServer(int port){ + public ThreadedTCPNetworkServer(int port) { this(port, null, null); } /** @@ -69,7 +69,7 @@ public abstract class ThreadedTCPNetworkServer extends Thread{ * @param keyStore If this is not null then the server will use SSL connection with this keyStore file path * @param keyStorePass If this is not null then the server will use a SSL connection with the given certificate */ - public ThreadedTCPNetworkServer(int port, File keyStore, String keyStorePass){ + public ThreadedTCPNetworkServer(int port, File keyStore, String keyStorePass) { this.port = port; executor = Executors.newCachedThreadPool(); this.keyStorePass = keyStorePass; @@ -77,25 +77,25 @@ public abstract class ThreadedTCPNetworkServer extends Thread{ } - public void run(){ + public void run() { ServerSocket serverSocket = null; - try{ - if(keyStorePass != null && keyStore != null){ + try { + if (keyStorePass != null && keyStore != null) { registerCertificate(keyStore, keyStorePass); - serverSocket = initSSL( port ); + serverSocket = initSSL(port); } - else{ - serverSocket = new ServerSocket( port ); + else { + serverSocket = new ServerSocket(port); } - logger.info("Listening for TCP Connections on port: "+port); + logger.info("Listening for TCP Connections on port: " +port); - while(true){ + while (true) { Socket connectionSocket = serverSocket.accept(); - ThreadedTCPNetworkServerThread thread = getThreadInstance( connectionSocket ); - if( thread!=null ) { + ThreadedTCPNetworkServerThread thread = getThreadInstance(connectionSocket); + + if (thread != null) { executor.execute(thread); - } - else{ + } else { logger.severe("Unable to instantiate ThreadedTCPNetworkServerThread, closing connection!"); connectionSocket.close(); } @@ -103,10 +103,10 @@ public abstract class ThreadedTCPNetworkServer extends Thread{ } catch(Exception e) { logger.log(Level.SEVERE, null, e); } finally { - if( serverSocket!=null ){ - try{ + if (serverSocket != null) { + try { serverSocket.close(); - }catch(IOException e){ logger.log(Level.SEVERE, null, e); } + } catch(IOException e) { logger.log(Level.SEVERE, null, e); } } } } @@ -119,7 +119,7 @@ public abstract class ThreadedTCPNetworkServer extends Thread{ * @param s is an new connection to an host * @return a new instance of an thread or null */ - protected abstract ThreadedTCPNetworkServerThread getThreadInstance( Socket s ) throws IOException; + protected abstract ThreadedTCPNetworkServerThread getThreadInstance(Socket s) throws IOException; /** * Initiates a SSLServerSocket @@ -148,7 +148,7 @@ public abstract class ThreadedTCPNetworkServer extends Thread{ * Stops the server and interrupts its internal thread. * This is a permanent action that will not be able to recover from */ - public void close(){ + public void close() { this.interrupt(); } } diff --git a/src/zutil/net/threaded/ThreadedUDPNetwork.java b/src/zutil/net/threaded/ThreadedUDPNetwork.java index 891c68c..2af47ad 100755 --- a/src/zutil/net/threaded/ThreadedUDPNetwork.java +++ b/src/zutil/net/threaded/ThreadedUDPNetwork.java @@ -69,7 +69,7 @@ public class ThreadedUDPNetwork extends Thread{ this.type = UDPType.UNICAST; this.port = port; - socket = new DatagramSocket( port ); + socket = new DatagramSocket(port); } /** @@ -79,27 +79,27 @@ public class ThreadedUDPNetwork extends Thread{ * @param multicastAddr is the multicast address that the server will listen on * @throws IOException if there is any issue opening the connection */ - public ThreadedUDPNetwork(String multicastAddr, int port ) throws IOException{ + public ThreadedUDPNetwork(String multicastAddr, int port) throws IOException{ this.type = UDPType.MULTICAST; this.port = port; // init udp socket - MulticastSocket msocket = new MulticastSocket( port ); - InetAddress group = InetAddress.getByName( multicastAddr ); - msocket.joinGroup( group ); + MulticastSocket msocket = new MulticastSocket(port); + InetAddress group = InetAddress.getByName(multicastAddr); + msocket.joinGroup(group); socket = msocket; } - public void run(){ - try{ - while(true){ + public void run() { + try { + while (true) { byte[] buf = new byte[BUFFER_SIZE]; DatagramPacket packet = new DatagramPacket(buf, buf.length); - socket.receive( packet ); - if( thread!=null ) - thread.receivedPacket( packet, this ); + socket.receive(packet); + if (thread != null) + thread.receivedPacket(packet, this); } } catch (Exception e) { e.printStackTrace(); @@ -129,7 +129,7 @@ public class ThreadedUDPNetwork extends Thread{ * Stops the server and interrupts its internal thread. * This is a permanent action that will not be able to recover from */ - public void close(){ + public void close() { this.interrupt(); socket.close(); } diff --git a/src/zutil/net/torrent/TorrentFile.java b/src/zutil/net/torrent/TorrentFile.java index 05d69e8..b3d2347 100755 --- a/src/zutil/net/torrent/TorrentFile.java +++ b/src/zutil/net/torrent/TorrentFile.java @@ -26,14 +26,14 @@ package zutil.net.torrent; /** * This class represents a File for download - * + * * @author Ziver */ public class TorrentFile{ private String filename; private long size; - public TorrentFile(String filename, long size){ + public TorrentFile(String filename, long size) { this.filename = filename; this.size = size; } diff --git a/src/zutil/net/torrent/TorrentMetainfo.java b/src/zutil/net/torrent/TorrentMetainfo.java index b2224fe..5faae20 100755 --- a/src/zutil/net/torrent/TorrentMetainfo.java +++ b/src/zutil/net/torrent/TorrentMetainfo.java @@ -81,27 +81,27 @@ public class TorrentMetainfo { created_by = metainfo.getString("created by"); comment = metainfo.getString("comment"); encoding = metainfo.getString("encoding"); - if( metainfo.get("creation date") != null ) + if (metainfo.get("creation date") != null) creation_date = metainfo.getLong("creation date"); - if( metainfo.get("announce-list") != null ){ + if (metainfo.get("announce-list") != null) { DataNode tmp = metainfo.get("announce-list"); announce_list = new ArrayList<>(); - for( DataNode tracker : tmp ) - announce_list.add( tracker.getString() ); + for (DataNode tracker : tmp) + announce_list.add(tracker.getString()); } // info data DataNode info = metainfo.get("info"); name = info.getString("name"); piece_length = info.getLong("piece length"); - if( info.get("private") != null ) + if (info.get("private") != null) is_private = (info.getInt("private") != 0); // Split the hashes String hashes = info.getString("pieces"); piece_hashes = new ArrayList<>(); - for(int i=0; i(); // Single-file torrent - if( info.get("files") == null ){ + if (info.get("files") == null) { Long fileSize = size = info.getLong("length"); - file_list.add( new TorrentFile(name, fileSize) ); + file_list.add(new TorrentFile(name, fileSize)); } // Multi-file torrent - else{ + else { DataNode files = info.get("files"); - for( DataNode file : files ){ + for (DataNode file : files) { StringBuilder filename = new StringBuilder(); DataNode tmp = file.get("path"); // File in subdir - if( tmp.isList() ){ + if (tmp.isList()) { Iterator it = tmp.iterator(); - while( it.hasNext() ){ + while (it.hasNext()) { filename.append(it.next().getString()); - if(it.hasNext()) + if (it.hasNext()) filename.append(File.separator); } } @@ -133,7 +133,7 @@ public class TorrentMetainfo { filename.append(tmp.getString()); Long fileSize = file.getLong("length"); size += fileSize; - file_list.add( new TorrentFile(filename.toString(), fileSize) ); + file_list.add(new TorrentFile(filename.toString(), fileSize)); } } } diff --git a/src/zutil/net/torrent/TorrentTracker.java b/src/zutil/net/torrent/TorrentTracker.java index 42a1e3a..3ce02c7 100755 --- a/src/zutil/net/torrent/TorrentTracker.java +++ b/src/zutil/net/torrent/TorrentTracker.java @@ -45,7 +45,7 @@ public class TorrentTracker { // TODO: incomplete public void update() throws IOException { HttpClient request = new HttpClient(HttpClient.HttpRequestType.GET); - request.setURL( trackerURL ); + request.setURL(trackerURL); HttpHeader response = request.send(); } } diff --git a/src/zutil/net/update/FileInfo.java b/src/zutil/net/update/FileInfo.java index 52b5108..6e8b32b 100644 --- a/src/zutil/net/update/FileInfo.java +++ b/src/zutil/net/update/FileInfo.java @@ -34,7 +34,7 @@ import java.io.Serializable; /** * This class is used to store the files * and there hashes - * + * * @author Ziver */ public class FileInfo implements Serializable{ @@ -62,20 +62,20 @@ public class FileInfo implements Serializable{ public long getSize() { return size; } - public File getFile(){ + public File getFile() { return file; } - public boolean equals(Object comp){ - if(comp instanceof FileInfo){ + public boolean equals(Object comp) { + if (comp instanceof FileInfo) { FileInfo tmp = (FileInfo)comp; return path.equals(tmp.path) && hash.equals(tmp.hash); } return false; } - public String toString(){ + public String toString() { return path; } } diff --git a/src/zutil/net/update/UpdateClient.java b/src/zutil/net/update/UpdateClient.java index 61eaebc..df1a29a 100644 --- a/src/zutil/net/update/UpdateClient.java +++ b/src/zutil/net/update/UpdateClient.java @@ -65,7 +65,7 @@ public class UpdateClient{ this.path = path; } - public void setProgressListener(ProgressListener p){ + public void setProgressListener(ProgressListener p) { progress = p; } @@ -73,12 +73,12 @@ public class UpdateClient{ * Updates the files */ public void update() throws IOException{ - try{ - ObjectOutputStream out = new ObjectOutputStream( socket.getOutputStream()); - ObjectInputStream in = new ObjectInputStream ( socket.getInputStream() ); + try { + ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); + ObjectInputStream in = new ObjectInputStream (socket.getInputStream()); // send client file list - out.writeObject( fileList ); + out.writeObject(fileList); out.flush(); // get update list FileListMessage updateList = (FileListMessage) in.readObject(); @@ -87,12 +87,12 @@ public class UpdateClient{ // receive file updates File tmpPath = FileUtil.find(path); totalReceived = 0; - for(FileInfo info : updateList.getFileList() ){ + for (FileInfo info : updateList.getFileList()) { // reading new file data - File file = new File( tmpPath, info.getPath() ); - logger.fine("Updating file: "+file); - if( !file.getParentFile().exists() && !file.getParentFile().mkdirs() ){ - throw new IOException("Unable to create folder: "+file.getParentFile()); + File file = new File(tmpPath, info.getPath()); + logger.fine("Updating file: " +file); + if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { + throw new IOException("Unable to create folder: " +file.getParentFile()); } File tmpFile = File.createTempFile(file.getName(), ".tmp", tmpPath); tmpFile.deleteOnExit(); @@ -105,30 +105,30 @@ public class UpdateClient{ long time = System.currentTimeMillis(); long timeTotalReceived = 0; - while( bytesReceived < info.getSize() ) { + while (bytesReceived < info.getSize()) { byteRead = in.read(buffer); fileOut.write(buffer, 0, byteRead); bytesReceived += byteRead; - if(time+1000 < System.currentTimeMillis()){ + if (time+1000 < System.currentTimeMillis()) { time = System.currentTimeMillis(); speed = (int)(totalReceived - timeTotalReceived); timeTotalReceived = totalReceived; } totalReceived += byteRead; - if(progress != null) progress.progressUpdate(this, info, ((double)totalReceived/updateList.getTotalSize())*100); + if (progress != null) progress.progressUpdate(this, info, ((double)totalReceived/updateList.getTotalSize())*100); } fileOut.close(); speed = 0; // delete old file and replace whit new file.delete(); - if( !tmpFile.renameTo(file) ){ - throw new IOException("Can not move downloaded file: "+tmpFile.getAbsolutePath()+" to: "+file); + if (!tmpFile.renameTo(file)) { + throw new IOException("Can not move downloaded file: " + tmpFile.getAbsolutePath() + " to: " + file); } } - }catch(ClassNotFoundException e){ + } catch (ClassNotFoundException e) { logger.log(Level.SEVERE, null, e); } @@ -140,7 +140,7 @@ public class UpdateClient{ * * @return The speed in bytes/s */ - public long getSpeed(){ + public long getSpeed() { return speed; } @@ -149,7 +149,7 @@ public class UpdateClient{ * * @return a long that represents bytes */ - public long getTotalReceived(){ + public long getTotalReceived() { return totalReceived; } @@ -158,7 +158,7 @@ public class UpdateClient{ * * @return a long that represents bytes */ - public long getTotalSize(){ + public long getTotalSize() { return expectedSize; } diff --git a/src/zutil/net/update/UpdateServer.java b/src/zutil/net/update/UpdateServer.java index b77a428..404b21c 100755 --- a/src/zutil/net/update/UpdateServer.java +++ b/src/zutil/net/update/UpdateServer.java @@ -76,34 +76,34 @@ public class UpdateServer extends ThreadedTCPNetworkServer{ * * @param c is the socket to the client */ - public UpdateServerThread(Socket c){ + public UpdateServerThread(Socket c) { socket = c; try { - out = new ObjectOutputStream( socket.getOutputStream()); - in = new ObjectInputStream ( socket.getInputStream() ); + out = new ObjectOutputStream(socket.getOutputStream()); + in = new ObjectInputStream (socket.getInputStream()); } catch (IOException e) { logger.log(Level.SEVERE, null, e); } } - public void run(){ + public void run() { try { - logger.info("Client["+socket.getInetAddress()+"] connectiong..."); + logger.info("Client[" + socket.getInetAddress() + "] connectiong..."); // receive the clients file list FileListMessage clientFileList = (FileListMessage)in.readObject(); MultiPrintStream.out.dump(clientFileList); - FileListMessage diff = fileList.getDiff( clientFileList ); + FileListMessage diff = fileList.getDiff(clientFileList); MultiPrintStream.out.dump(diff); - out.writeObject( diff ); + out.writeObject(diff); - logger.info("Updating client["+socket.getInetAddress()+"]..."); - for(FileInfo info : diff.getFileList()){ + logger.info("Updating client[" + socket.getInetAddress() + "]..."); + for (FileInfo info : diff.getFileList()) { // send file data - FileInputStream input = new FileInputStream( info.getFile() ); - byte[] nextBytes = new byte[ socket.getSendBufferSize() ]; + FileInputStream input = new FileInputStream(info.getFile()); + byte[] nextBytes = new byte[socket.getSendBufferSize()]; int bytesRead; - while((bytesRead = input.read(nextBytes)) > 0){ + while ((bytesRead = input.read(nextBytes)) > 0) { out.write(nextBytes,0,bytesRead); } out.flush(); @@ -112,11 +112,11 @@ public class UpdateServer extends ThreadedTCPNetworkServer{ out.flush(); socket.close(); - logger.info("Client["+socket.getInetAddress()+"] update done."); + logger.info("Client[" + socket.getInetAddress() + "] update done."); } catch (Exception e) { - logger.log(Level.SEVERE, "Update error Client["+socket.getInetAddress()+"].", e); + logger.log(Level.SEVERE, "Update error Client[" + socket.getInetAddress() + "].", e); } finally { - logger.info("Client["+socket.getInetAddress()+"] disconnected."); + logger.info("Client[" + socket.getInetAddress() + "] disconnected."); } } } diff --git a/src/zutil/net/update/Zupdater.java b/src/zutil/net/update/Zupdater.java index ed551c9..acab49a 100644 --- a/src/zutil/net/update/Zupdater.java +++ b/src/zutil/net/update/Zupdater.java @@ -62,12 +62,12 @@ public class Zupdater extends JFrame implements ProgressListener1"); out.println(" 0"); out.println(" "); - out.println(" "+url+"");//"+ssdp.getLocation()+" + out.println(" " + url + "");//" + ssdp.getLocation() + " out.println(" "); out.println(" urn:schemas-upnp-org:device:MediaServer:1"); out.println(" ZupNP AV Media Server"); @@ -72,7 +72,7 @@ public class UPnPMediaServer extends UPnPRootDevice{ out.println(" ZupNP Server"); out.println(" UPnP AV Media Server"); out.println(" 0.1"); - out.println(" "+getUUID()+""); + out.println(" " + getUUID() + ""); out.println(" "); out.println(" "); out.println(" urn:schemas-upnp-org:service:ConnectionManager:1"); @@ -96,20 +96,20 @@ public class UPnPMediaServer extends UPnPRootDevice{ public long getExpirationTime() { - return 60*30; // 30min + return 60 * 30; // 30min } public String getLocation() { - return url+"RootDesc"; + return url + "RootDesc"; } public String getSearchTarget() { return "upnp:rootdevice"; } public String getUSN() { - return getUUID()+"::upnp:rootdevice"; + return getUUID() + "::upnp:rootdevice"; } public String getUUID() { - if(uuid==null){ - uuid = "uuid:"+UUID.nameUUIDFromBytes( this.getClass().toString().getBytes() ); //(url+Math.random()).getBytes() + if (uuid == null) { + uuid = "uuid:" + UUID.nameUUIDFromBytes(this.getClass().toString().getBytes()); //(url+Math.random()).getBytes() } return uuid; } diff --git a/src/zutil/net/upnp/service/UPnPContentDirectory.java b/src/zutil/net/upnp/service/UPnPContentDirectory.java index 09f17cf..ef93840 100755 --- a/src/zutil/net/upnp/service/UPnPContentDirectory.java +++ b/src/zutil/net/upnp/service/UPnPContentDirectory.java @@ -49,9 +49,9 @@ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface private static List file_list; - public UPnPContentDirectory(){} + public UPnPContentDirectory() {} - public UPnPContentDirectory(File dir){ + public UPnPContentDirectory(File dir) { file_list = FileUtil.search(dir, new LinkedList<>(), true, Integer.MAX_VALUE); } @@ -61,7 +61,7 @@ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface * */ @WSReturnName("SortCaps") - public String GetSearchCapabilities(){ + public String GetSearchCapabilities() { // "dc:title,res@size" return ""; } @@ -72,7 +72,7 @@ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface * */ @WSReturnName("SortCaps") - public String GetSortCapabilities(){ + public String GetSortCapabilities() { return "dc:title"; } @@ -84,7 +84,7 @@ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface * */ @WSReturnName("Id") - public int GetSystemUpdateID(){ + public int GetSystemUpdateID() { return 0; } @@ -106,23 +106,23 @@ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface @WSParamName("SortCriteria") String SortCriteria) { BrowseRetObj ret = new BrowseRetObj(); - if( BrowseFlag.equals("BrowseMetadata") ){ + if (BrowseFlag.equals("BrowseMetadata")) { } - else if( BrowseFlag.equals("BrowseDirectChildren") ){ + else if (BrowseFlag.equals("BrowseDirectChildren")) { StringBuilder xml = new StringBuilder(); - xml.append( "" ); - List tmp = FileUtil.search( file_list.get(Integer.parseInt(ObjectID)), new LinkedList<>(), false ); - for(File file : tmp){ + "xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\">"); + List tmp = FileUtil.search(file_list.get(Integer.parseInt(ObjectID)), new LinkedList<>(), false); + for (File file : tmp) { xml.append(" "); xml.append(" ").append(file.getName()).append(" "); - if( file.isDirectory() ) + if (file.isDirectory()) xml.append(" object.container.storageFolder "); else xml.append(" object.container "); @@ -132,10 +132,10 @@ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface ret.NumberReturned++; ret.TotalMatches++; } - xml.append( "" ); + xml.append(""); ret.Result = xml.toString(); - //Document document = DocumentHelper.parseText( xml.toString() ); + //Document document = DocumentHelper.parseText(xml.toString()); //ret.Result = document.getRootElement(); } return ret; diff --git a/src/zutil/net/ws/WSClientFactory.java b/src/zutil/net/ws/WSClientFactory.java index 122c407..dc13d8b 100755 --- a/src/zutil/net/ws/WSClientFactory.java +++ b/src/zutil/net/ws/WSClientFactory.java @@ -48,7 +48,7 @@ public class WSClientFactory { * @param handler is the handler that will execute the calls to the web service * @return a client Object */ - public static T createClient(Class intf, InvocationHandler handler){ + public static T createClient(Class intf, InvocationHandler handler) { try { T obj = (T) Proxy.newProxyInstance( WSClientFactory.class.getClassLoader(), @@ -56,7 +56,7 @@ public class WSClientFactory { handler); return obj; - } catch (Exception e){ + } catch (Exception e) { logger.log(Level.SEVERE, null, e); } diff --git a/src/zutil/net/ws/WSInterface.java b/src/zutil/net/ws/WSInterface.java index eead304..d27c30c 100755 --- a/src/zutil/net/ws/WSInterface.java +++ b/src/zutil/net/ws/WSInterface.java @@ -38,7 +38,7 @@ import java.lang.annotation.Target; * Example: *
      *	private static class Test implements WSInterface{
    - *		public Test(){}
    + *		public Test() {}
      *
      *		@WSDocumentation("This is a description of the method")
      *		@WSParamDocumentation("arg1 = variable description?")
    @@ -56,7 +56,7 @@ import java.lang.annotation.Target;
      *		}
      *
      *		@WSIgnore()
    - *		public void privatZ(....){
    + *		public void privatZ(....) {
      *			...
      *		}
      *	}
    diff --git a/src/zutil/net/ws/WSParameterDef.java b/src/zutil/net/ws/WSParameterDef.java
    index 162fdde..62f638d 100644
    --- a/src/zutil/net/ws/WSParameterDef.java
    +++ b/src/zutil/net/ws/WSParameterDef.java
    @@ -44,7 +44,7 @@ public class WSParameterDef {
         private boolean optional = false;
     
     
    -    protected WSParameterDef(WSMethodDef mDef, Class paramClass, Annotation[] annotations){
    +    protected WSParameterDef(WSMethodDef mDef, Class paramClass, Annotation[] annotations) {
             this.mDef = mDef;
             this.paramClass = paramClass;
     
    @@ -92,7 +92,7 @@ public class WSParameterDef {
             this.optional = optional;
         }
     
    -    public WSMethodDef getMethod(){
    +    public WSMethodDef getMethod() {
             return mDef;
         }
     }
    diff --git a/src/zutil/net/ws/WSReturnObject.java b/src/zutil/net/ws/WSReturnObject.java
    index ed28c3d..07b8646 100644
    --- a/src/zutil/net/ws/WSReturnObject.java
    +++ b/src/zutil/net/ws/WSReturnObject.java
    @@ -40,7 +40,7 @@ import java.lang.reflect.Field;
      *	    @WSDocumentation("The users last name")
      *		public String lastname;
      *
    - *		public TestObject(String n, String l){
    + *		public TestObject(String n, String l) {
      *			name = n;
      *			lastname = l;
      *		}
    diff --git a/src/zutil/net/ws/WebServiceDef.java b/src/zutil/net/ws/WebServiceDef.java
    index 28e72d4..95e0b74 100755
    --- a/src/zutil/net/ws/WebServiceDef.java
    +++ b/src/zutil/net/ws/WebServiceDef.java
    @@ -48,7 +48,7 @@ public class WebServiceDef {
         private HashMap methods = new HashMap<>();
     
     
    -    public WebServiceDef(Class intf){
    +    public WebServiceDef(Class intf) {
             this.intf = intf;
             name = intf.getSimpleName();
     
    @@ -64,9 +64,9 @@ public class WebServiceDef {
             if (documentationAnnotation != null)
                 this.documentation = documentationAnnotation.value();
     
    -        for(Method m : intf.getDeclaredMethods()){
    +        for (Method m : intf.getDeclaredMethods()) {
                 // Check for public methods
    -            if ((m.getModifiers() & Modifier.PUBLIC) > 0 && !m.isAnnotationPresent(WSInterface.WSIgnore.class)){
    +            if ((m.getModifiers() & Modifier.PUBLIC) > 0 && !m.isAnnotationPresent(WSInterface.WSIgnore.class)) {
                     WSMethodDef method = new WSMethodDef(this, m);
                     methods.put(method.getName(), method);
                 }
    @@ -77,21 +77,21 @@ public class WebServiceDef {
         /**
          * @return the class that defines this web service
          */
    -    public Class getWSClass(){
    +    public Class getWSClass() {
             return intf;
         }
     
         /**
          * @return the name of the Service (usually the class name of the WSInterface)
          */
    -    public String getName(){
    +    public String getName() {
             return name;
         }
     
         /**
          * @return a human readable description of the service, or a empty String if no documentation has been provided.
          */
    -    public String getDocumentation(){
    +    public String getDocumentation() {
             return documentation;
         }
     
    @@ -99,36 +99,36 @@ public class WebServiceDef {
          * @param name  is the name of the method
          * @return if there is a method by the given name
          */
    -    public boolean hasMethod( String name ){
    -        return methods.containsKey( name );
    +    public boolean hasMethod(String name) {
    +        return methods.containsKey(name);
         }
     
         /**
          * @param name  is the name of the method
          * @return the method or null if there is no such method
          */
    -    public WSMethodDef getMethod( String name ){
    -        return methods.get( name );
    +    public WSMethodDef getMethod(String name) {
    +        return methods.get(name);
         }
     
         /**
          * @return a Set of all the method names
          */
    -    public Set getMethodNames(){
    +    public Set getMethodNames() {
             return methods.keySet();
         }
     
         /**
          * @return all the methods
          */
    -    public Collection getMethods(){
    +    public Collection getMethods() {
             return methods.values();
         }
     
         /**
    -     * @return the namespace of this web service ( usually the URL of the service )
    +     * @return the namespace of this web service (usually the URL of the service )
          */
    -    public String getPath(){
    +    public String getPath() {
             return path;
         }
     
    diff --git a/src/zutil/net/ws/openapi/OpenAPIWriter.java b/src/zutil/net/ws/openapi/OpenAPIWriter.java
    index a7d33f6..1ace638 100644
    --- a/src/zutil/net/ws/openapi/OpenAPIWriter.java
    +++ b/src/zutil/net/ws/openapi/OpenAPIWriter.java
    @@ -39,7 +39,7 @@ public class OpenAPIWriter {
         }
     
     
    -    public void addServer(String url, String description){
    +    public void addServer(String url, String description) {
             servers.add(new ServerData(url, description));
             cache = null;
         }
    diff --git a/src/zutil/net/ws/rest/RESTClientFactory.java b/src/zutil/net/ws/rest/RESTClientFactory.java
    index fbcb5e9..296acdf 100644
    --- a/src/zutil/net/ws/rest/RESTClientFactory.java
    +++ b/src/zutil/net/ws/rest/RESTClientFactory.java
    @@ -50,7 +50,7 @@ public class RESTClientFactory {
          * @param 	intf 	is the class of the web service definition
          * @return a client Object
          */
    -    public static  T createClient(URL url, Class intf){
    +    public static  T createClient(URL url, Class intf) {
             T obj = WSClientFactory.createClient(intf,
                     new RESTClientInvocationHandler(url, new WebServiceDef(intf)));
             return obj;
    diff --git a/src/zutil/net/ws/rest/RESTHttpPage.java b/src/zutil/net/ws/rest/RESTHttpPage.java
    index 4bfff9c..9146596 100755
    --- a/src/zutil/net/ws/rest/RESTHttpPage.java
    +++ b/src/zutil/net/ws/rest/RESTHttpPage.java
    @@ -50,7 +50,7 @@ public class RESTHttpPage implements HttpPage {
         private WSInterface ws;
     
     
    -    public RESTHttpPage(WSInterface wsObject ){
    +    public RESTHttpPage(WSInterface wsObject) {
             this.ws = wsObject;
             this.wsDef = new WebServiceDef(ws.getClass());
         }
    @@ -88,17 +88,17 @@ public class RESTHttpPage implements HttpPage {
                 out.close();
                 return strBuffer.toString();
             }
    -        return "{error: \"Unknown target: "+targetMethod+"\"}";
    +        return "{error: \"Unknown target: " + targetMethod + "\"}";
         }
     
    -    private Object[] prepareInputParams(WSMethodDef methodDef, Map input){
    +    private Object[] prepareInputParams(WSMethodDef methodDef, Map input) {
             List inputParamDefs = methodDef.getInputs();
             Object[] inputParams = new Object[inputParamDefs.size()];
     
             // Get the parameter values
    -        for (int i=0; i T createClient(URL url, Class intf){
    -        T obj = WSClientFactory.createClient( intf,
    +    public static  T createClient(URL url, Class intf) {
    +        T obj = WSClientFactory.createClient(intf,
                     new SOAPClientInvocationHandler(url, new WebServiceDef(intf)));
             return obj;
         }
    diff --git a/src/zutil/net/ws/soap/SOAPHttpPage.java b/src/zutil/net/ws/soap/SOAPHttpPage.java
    index d8a5e58..aa54c1d 100755
    --- a/src/zutil/net/ws/soap/SOAPHttpPage.java
    +++ b/src/zutil/net/ws/soap/SOAPHttpPage.java
    @@ -91,7 +91,7 @@ public class SOAPHttpPage implements HttpPage{
         /** Session enabled **/
         private boolean session_enabled;
     
    -    public SOAPHttpPage( WebServiceDef wsDef ) {
    +    public SOAPHttpPage(WebServiceDef wsDef) {
             this.wsDef = wsDef;
             this.session_enabled = false;
         }
    @@ -162,8 +162,8 @@ public class SOAPHttpPage implements HttpPage{
                 Document document = genSOAPResponse((data!=null ? data.toString() : ""), obj);
     
                 OutputFormat format = OutputFormat.createPrettyPrint();
    -            XMLWriter writer = new XMLWriter( out, format );
    -            writer.write( document );
    +            XMLWriter writer = new XMLWriter(out, format);
    +            writer.write(document);
     
     
                 // DEBUG
    @@ -171,8 +171,8 @@ public class SOAPHttpPage implements HttpPage{
                     System.out.println("********** Request");
                     System.out.println(request);
                     System.out.println("********** Response");
    -                writer = new XMLWriter( System.out, format );
    -                writer.write( document );
    +                writer = new XMLWriter(System.out, format);
    +                writer.write(document);
                 }
             } catch (Exception e) {
                 logger.log(Level.WARNING, "Unhandled request", e);
    @@ -207,33 +207,33 @@ public class SOAPHttpPage implements HttpPage{
                 envelope.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                 envelope.addNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
     
    -            Element body = envelope.addElement( "soap:Body" );
    +            Element body = envelope.addElement("soap:Body");
                 try {
                     Element request = getXMLRoot(xml);
                     if (request == null) return document;
                     // Header
    -                if ( request.element("Header") != null) {
    -                    Element header = envelope.addElement( "soap:Header" );
    -                    prepareInvoke( obj, request.element("Header"), header );
    +                if (request.element("Header") != null) {
    +                    Element header = envelope.addElement("soap:Header");
    +                    prepareInvoke(obj, request.element("Header"), header);
                     }
     
                     // Body
    -                if ( request.element("Body") != null) {
    -                    prepareInvoke( obj, request.element("Body"), body );
    +                if (request.element("Body") != null) {
    +                    prepareInvoke(obj, request.element("Body"), body);
                     }
                 } catch(Throwable e) {
                     body.clearContent();
                     Element fault = body.addElement("soap:Fault");
                     // The fault source
                     if (e instanceof SOAPException || e instanceof SAXException || e instanceof DocumentException)
    -                    fault.addElement("faultcode").setText( "soap:Client" );
    +                    fault.addElement("faultcode").setText("soap:Client");
                     else
    -                    fault.addElement("faultcode").setText( "soap:Server" );
    +                    fault.addElement("faultcode").setText("soap:Server");
                     // The fault message
    -                if ( e.getMessage() == null || e.getMessage().isEmpty())
    -                    fault.addElement("faultstring").setText( ""+e.getClass().getSimpleName() );
    +                if (e.getMessage() == null || e.getMessage().isEmpty())
    +                    fault.addElement("faultstring").setText("" +e.getClass().getSimpleName());
                     else
    -                    fault.addElement("faultstring").setText( ""+e.getMessage() );
    +                    fault.addElement("faultstring").setText("" +e.getMessage());
                     logger.log(Level.WARNING, "Caught exception from SOAP Class", e);
                 }
             } catch (Exception e) {
    @@ -267,17 +267,17 @@ public class SOAPHttpPage implements HttpPage{
         @SuppressWarnings("unchecked")
         private void prepareInvoke(WSInterface obj, Element requestRoot, Element responseRoot) throws Throwable{
             Iterator it = requestRoot.elementIterator();
    -        while(it.hasNext()) {
    +        while (it.hasNext()) {
                 Element e = it.next();
    -            if (wsDef.hasMethod( e.getQName().getName())) {
    +            if (wsDef.hasMethod(e.getQName().getName())) {
                     WSMethodDef methodDef = wsDef.getMethod(e.getQName().getName());
                     List inputParamDefs = methodDef.getInputs();
                     Object[] inputParams = new Object[inputParamDefs.size()];
     
                     // Get the parameter values
    -                for(int i=0; i 0) {
                         Element response = responseRoot.addElement("");
    -                    response.addNamespace("m", methodDef.getAbsolutePath() );
    +                    response.addNamespace("m", methodDef.getAbsolutePath());
                         response.setName("m:" + methodDef.getName() + "Response");
     
                         if (outputParams instanceof WSReturnObject) {
                             Field[] f = outputParams.getClass().getFields();
    -                        for(int i=0; i binding -> operation -> output
                 Element output = operation.addElement("wsdl:output");
                 // definitions -> binding -> operation -> input -> body
    diff --git a/src/zutil/osal/MultiCommandExecutor.java b/src/zutil/osal/MultiCommandExecutor.java
    index 3ff8b8d..b965f22 100644
    --- a/src/zutil/osal/MultiCommandExecutor.java
    +++ b/src/zutil/osal/MultiCommandExecutor.java
    @@ -46,7 +46,7 @@ public class MultiCommandExecutor implements AutoCloseable{
         private boolean eol = true;
     
     
    -    public MultiCommandExecutor(){
    +    public MultiCommandExecutor() {
             try {
                 // Generate delimiter
                 byte[] tmp = new byte[16];
    @@ -55,7 +55,7 @@ public class MultiCommandExecutor implements AutoCloseable{
     
                 //init shell
                 String shellCmd;
    -            switch (OSAbstractionLayer.getInstance().getOSType()){
    +            switch (OSAbstractionLayer.getInstance().getOSType()) {
                     case Windows:
                         shellCmd = SHELL_WINDOWS; break;
                     case Linux:
    @@ -70,9 +70,9 @@ public class MultiCommandExecutor implements AutoCloseable{
                 stdin = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
                 stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
     
    -        } catch (RuntimeException e){
    +        } catch (RuntimeException e) {
                 throw e;
    -        } catch (Exception e){
    +        } catch (Exception e) {
                 throw new RuntimeException("Unable to initiate shell",e);
             }
         }
    @@ -83,7 +83,7 @@ public class MultiCommandExecutor implements AutoCloseable{
             eol = false;
     
             stdin.write(cmd);
    -        switch (OSAbstractionLayer.getInstance().getOSType()){
    +        switch (OSAbstractionLayer.getInstance().getOSType()) {
                 case Windows:
                     stdin.write(" & echo & echo " + delimiter); break;
                 case Linux:
    @@ -111,7 +111,7 @@ public class MultiCommandExecutor implements AutoCloseable{
     
     
         @Override
    -    public void close(){
    +    public void close() {
             try {
                 // finally close the shell by execution exit command
                 stdin.write("exit");
    @@ -121,7 +121,7 @@ public class MultiCommandExecutor implements AutoCloseable{
                 process = null;
                 stdin = null;
                 stdout = null;
    -        } catch (Exception e){
    +        } catch (Exception e) {
                 e.printStackTrace();
             }
         }
    diff --git a/src/zutil/osal/OSAbstractionLayer.java b/src/zutil/osal/OSAbstractionLayer.java
    index 490bc57..fa5319c 100755
    --- a/src/zutil/osal/OSAbstractionLayer.java
    +++ b/src/zutil/osal/OSAbstractionLayer.java
    @@ -44,17 +44,17 @@ public abstract class OSAbstractionLayer {
         // Variables
         private static OSAbstractionLayer instance;
     
    -    public static OSAbstractionLayer getInstance(){
    -        if(instance == null)
    +    public static OSAbstractionLayer getInstance() {
    +        if (instance == null)
                 instance = getAbstractionLayer();
             return instance;
         }
     
    -    private static OSAbstractionLayer getAbstractionLayer(){
    +    private static OSAbstractionLayer getAbstractionLayer() {
             String os = System.getProperty("os.name");
    -        if     (os.contains("Linux"))   return new OsalLinuxImpl();
    -        else if(os.contains("Windows")) return new OsalWindowsImpl();
    -        else if(os.contains("Mac"))     return new OsalMacOSImpl();
    +        if      (os.contains("Linux"))   return new OsalLinuxImpl();
    +        else if (os.contains("Windows")) return new OsalWindowsImpl();
    +        else if (os.contains("Mac"))     return new OsalMacOSImpl();
             else                            return new OsalDummyImpl();
         }
     
    @@ -66,7 +66,7 @@ public abstract class OSAbstractionLayer {
          */
         protected static String getFirstLineFromExec(String cmd) {
             String[] tmp = exec(cmd);
    -        if(tmp.length > 1)
    +        if (tmp.length > 1)
                 return tmp[0];
             return null;
         }
    diff --git a/src/zutil/osal/linux/HalLinuxImpl.java b/src/zutil/osal/linux/HalLinuxImpl.java
    index 0401578..8e7a7ee 100755
    --- a/src/zutil/osal/linux/HalLinuxImpl.java
    +++ b/src/zutil/osal/linux/HalLinuxImpl.java
    @@ -31,5 +31,5 @@ import zutil.osal.HardwareAbstractionLayer;
      */
     public class HalLinuxImpl implements HardwareAbstractionLayer {
     
    -    protected HalLinuxImpl(){}
    +    protected HalLinuxImpl() {}
     }
    diff --git a/src/zutil/osal/linux/OsalLinuxImpl.java b/src/zutil/osal/linux/OsalLinuxImpl.java
    index de8b381..61d2d8a 100755
    --- a/src/zutil/osal/linux/OsalLinuxImpl.java
    +++ b/src/zutil/osal/linux/OsalLinuxImpl.java
    @@ -48,9 +48,9 @@ public class OsalLinuxImpl extends OSAbstractionLayer {
     
         @Override
         public String getKernelVersion() {
    -        try{
    +        try {
                 return getFirstLineFromExec("uname -r");
    -        } catch(Exception e){
    +        } catch(Exception e) {
                 e.printStackTrace();
             }
             return null;
    @@ -58,9 +58,9 @@ public class OsalLinuxImpl extends OSAbstractionLayer {
     
         @Override
         public String getUsername() {
    -        try{
    +        try {
                 return getFirstLineFromExec("whoami");
    -        } catch(Exception e){
    +        } catch(Exception e) {
                 e.printStackTrace();
             }
             return null;
    @@ -68,7 +68,7 @@ public class OsalLinuxImpl extends OSAbstractionLayer {
     
         @Override
         public File getUserConfigPath() {
    -        return new File("/home/"+getUsername());
    +        return new File("/home/" +getUsername());
         }
     
         @Override
    @@ -78,7 +78,7 @@ public class OsalLinuxImpl extends OSAbstractionLayer {
     
         @Override
         public HardwareAbstractionLayer getHAL() {
    -        if(hal == null)
    +        if (hal == null)
                 hal = new HalLinuxImpl();
             return hal;
         }
    diff --git a/src/zutil/osal/linux/app/AptGet.java b/src/zutil/osal/linux/app/AptGet.java
    index 5b52c30..3116151 100755
    --- a/src/zutil/osal/linux/app/AptGet.java
    +++ b/src/zutil/osal/linux/app/AptGet.java
    @@ -47,7 +47,7 @@ public class AptGet {
             packageTimer.reset();
         }
     
    -    public static void upgrade(){
    +    public static void upgrade() {
             update();
             OSAbstractionLayer.exec("apt-get -y " +
                     // Dont display configuration conflicts
    @@ -56,9 +56,9 @@ public class AptGet {
             packageTimer.reset();
         }
     
    -    public static void update(){
    +    public static void update() {
             // Only run every 5 min
    -        if(updateTimer.hasTimedOut()){
    +        if (updateTimer.hasTimedOut()) {
                 OSAbstractionLayer.exec("apt-get update");
                 updateTimer.start();
             }
    @@ -70,15 +70,15 @@ public class AptGet {
         }
     
     
    -    public static Package getPackage(String pkg){
    +    public static Package getPackage(String pkg) {
             updatePackages();
             return packages.get(pkg);
         }
    -    public static synchronized void updatePackages(){
    +    public static synchronized void updatePackages() {
             // Only run every 5 min
    -        if(packageTimer.hasTimedOut()){
    +        if (packageTimer.hasTimedOut()) {
                 String[] output = OSAbstractionLayer.exec("dpkg --list");
    -            for(int i=5; i();
             this.host = host;
             this.port = port;
    @@ -74,27 +74,27 @@ public class NutUPSClient {
         }
     
     
    -    public UPSDevice getUPS(String id){
    +    public UPSDevice getUPS(String id) {
             update();
             return __getUPS(id);
         }
    -    private UPSDevice __getUPS(String id){
    -        for (UPSDevice ups : upsDevices){
    +    private UPSDevice __getUPS(String id) {
    +        for (UPSDevice ups : upsDevices) {
                 if (ups.equals(id))
                     return ups;
             }
             return null;
         }
     
    -    public UPSDevice[] getUPSList(){
    +    public UPSDevice[] getUPSList() {
             update();
             return upsDevices.toArray(new UPSDevice[0]);
         }
     
     
    -    protected synchronized void update(){
    -        if(pollTimer.hasTimedOut()){
    -            logger.fine("Starting UPS data refresh ("+host+":"+port+")");
    +    protected synchronized void update() {
    +        if (pollTimer.hasTimedOut()) {
    +            logger.fine("Starting UPS data refresh (" + host + ":" + port + ")");
                 try(Socket s = new Socket(host, port)) {
                     Writer out = new OutputStreamWriter(s.getOutputStream());
                     BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    @@ -102,19 +102,19 @@ public class NutUPSClient {
                     // Refresh device list
                     HashMap tmp = new HashMap<>();
                     sendListCommand(out, in, "UPS", tmp);
    -                for (String upsId : tmp.keySet()){
    -                    if(__getUPS(upsId) == null) {
    -                        logger.fine("Registering new UPS device: "+upsId);
    +                for (String upsId : tmp.keySet()) {
    +                    if (__getUPS(upsId) == null) {
    +                        logger.fine("Registering new UPS device: " +upsId);
                             upsDevices.add(new UPSDevice(upsId));
                         }
                     }
     
                     // Refresh device data
    -                for (UPSDevice ups : upsDevices){
    +                for (UPSDevice ups : upsDevices) {
                         ups.update(out, in);
                     }
     
    -            } catch (Exception e){
    +            } catch (Exception e) {
                     logger.log(Level.WARNING, null, e);
                 }
                 // reset timer
    @@ -131,11 +131,11 @@ public class NutUPSClient {
             out.flush();
     
             String line = in.readLine();
    -        if ( ! line.startsWith("BEGIN LIST"))
    -            throw new IOException("Unexpected response from upsd: Request: '"+request+"' Response: '"+line+"'");
    +        if (! line.startsWith("BEGIN LIST"))
    +            throw new IOException("Unexpected response from upsd: Request: '" + request + "' Response: '" + line + "'");
     
    -        Pattern listKeyValuePatter = Pattern.compile("\\w* (?:\\w* )?([\\w.]+) \"(.*)\"");
    -        while ((line=in.readLine()) != null){
    +        Pattern listKeyValuePatter = Pattern.compile("\\w* (?:\\w*)?([\\w.]+) \"(.*)\"");
    +        while ((line=in.readLine()) != null) {
                 if (line.startsWith("END"))
                     break;
                 Matcher m = listKeyValuePatter.matcher(line);
    @@ -153,19 +153,19 @@ public class NutUPSClient {
             private HashMap parameters = new HashMap<>();
     
     
    -        protected UPSDevice(String id){
    +        protected UPSDevice(String id) {
                 this.id = id;
             }
     
             protected synchronized void update(Writer out, BufferedReader in) throws IOException {
    -            if(pollTimer == null || pollTimer.hasTimedOut()){
    +            if (pollTimer == null || pollTimer.hasTimedOut()) {
                     parameters.clear();
    -                logger.fine("Updating UPS parameters for: "+id);
    -                sendListCommand(out, in, "VAR "+id, parameters);
    +                logger.fine("Updating UPS parameters for: " +id);
    +                sendListCommand(out, in, "VAR " +id, parameters);
                 }
             }
     
    -        public boolean equals(Object o){
    +        public boolean equals(Object o) {
                 if (o instanceof String)
                     return id.equals(o);
                 else if (o instanceof UPSDevice)
    @@ -174,25 +174,25 @@ public class NutUPSClient {
             }
     
     
    -        public String getId(){
    +        public String getId() {
                 return id;
             }
    -        public String getModelName(){
    +        public String getModelName() {
                 return parameters.get(PARAMETER_MANUFACTURER) + " " + parameters.get(PARAMETER_MODEL);
             }
             public String getDescription() {
                 return parameters.get(PARAMETER_DESCRIPTION);
             }
    -        public int getPowerLoad(){
    +        public int getPowerLoad() {
                 return Integer.parseInt(parameters.get(PARAMETER_POWER_LOAD));
             }
    -        public int getPowerUsage(){
    +        public int getPowerUsage() {
                 return Integer.parseInt(parameters.get(PARAMETER_POWER_USAGE));
             }
    -        public int getBatteryCharge(){
    +        public int getBatteryCharge() {
                 return Integer.parseInt(parameters.get(PARAMETER_BATTERY_CHARGE));
             }
    -        public double getBatteryVoltage(){
    +        public double getBatteryVoltage() {
                 return Double.parseDouble(parameters.get(PARAMETER_BATTERY_VOLTAGE));
             }
     
    diff --git a/src/zutil/osal/linux/app/ProcDiskstats.java b/src/zutil/osal/linux/app/ProcDiskstats.java
    index d26c827..2066bbc 100755
    --- a/src/zutil/osal/linux/app/ProcDiskstats.java
    +++ b/src/zutil/osal/linux/app/ProcDiskstats.java
    @@ -50,8 +50,8 @@ public class ProcDiskstats {
         private static Timer updateTimer = new Timer(TTL);
     
     
    -    private synchronized static void update(){
    -        if(!updateTimer.hasTimedOut())
    +    private synchronized static void update() {
    +        if (!updateTimer.hasTimedOut())
                 return;
     
             try {
    @@ -65,11 +65,11 @@ public class ProcDiskstats {
         protected static void parse(BufferedReader in) throws IOException {
             updateTimer.start();
             String line;
    -        while((line=in.readLine()) != null){
    +        while ((line=in.readLine()) != null) {
                 String[] str = line.trim().split("\\s+", 4);
    -            if(str.length >= 4) {
    +            if (str.length >= 4) {
                     String devName = str[2];
    -                if(!hdds.containsKey(devName)){
    +                if (!hdds.containsKey(devName)) {
                         HddStats hdd = new HddStats(devName);
                         hdds.put(hdd.getDevName(), hdd);
                     }
    @@ -80,7 +80,7 @@ public class ProcDiskstats {
     
     
     
    -    public static HddStats getStats(String devName){
    +    public static HddStats getStats(String devName) {
             update();
             return hdds.get(devName);
         }
    @@ -120,9 +120,9 @@ public class ProcDiskstats {
                 readThroughput = new ThroughputCalculator();
                 writeThroughput = new ThroughputCalculator();
             }
    -        protected void update(String line){
    +        protected void update(String line) {
                 String[] stats = line.split("\\s+");
    -            if(stats.length >= 11){
    +            if (stats.length >= 11) {
                     readIO =       Long.parseLong(stats[0]);
                     readMerges =   Long.parseLong(stats[1]);
                     readSectors =  Long.parseLong(stats[2]);
    @@ -233,25 +233,25 @@ public class ProcDiskstats {
             /**
              * @return the average byte/second read throughput from the disk
              */
    -        public double getReadThroughput(){
    +        public double getReadThroughput() {
                 return readThroughput.getByteThroughput();
             }
             /**
              * @return the average byte/second write throughput to the disk
              */
    -        public double getWriteThroughput(){
    +        public double getWriteThroughput() {
                 return writeThroughput.getByteThroughput();
             }
         }
     
     
    -    public static void main(String[] args){
    -        while(true){
    +    public static void main(String[] args) {
    +        while (true) {
                 HddStats hdd = ProcDiskstats.getStats("sda");
                 System.out.println("sda= " +
    -                    "read: "  + StringUtil.formatByteSizeToString((long)hdd.getReadThroughput()) + "/s "+
    +                    "read: "  + StringUtil.formatByteSizeToString((long)hdd.getReadThroughput()) + "/s " +
                         "write: " + StringUtil.formatByteSizeToString((long)hdd.getWriteThroughput()) + "/s");
    -            try{Thread.sleep(1000);}catch (Exception e){}
    +            try {Thread.sleep(1000);} catch (Exception e) {}
             }
         }
     }
    diff --git a/src/zutil/osal/linux/app/ProcStat.java b/src/zutil/osal/linux/app/ProcStat.java
    index 1c82491..3d7395d 100755
    --- a/src/zutil/osal/linux/app/ProcStat.java
    +++ b/src/zutil/osal/linux/app/ProcStat.java
    @@ -52,8 +52,8 @@ public class ProcStat {
         private static Timer updateTimer = new Timer(TTL);
     
     
    -    private synchronized static void update(){
    -        if(!updateTimer.hasTimedOut())
    +    private synchronized static void update() {
    +        if (!updateTimer.hasTimedOut())
                 return;
     
             try {
    @@ -67,21 +67,21 @@ public class ProcStat {
         protected static void parse(BufferedReader in) throws IOException {
             updateTimer.start();
             String line;
    -        while((line=in.readLine()) != null){
    +        while ((line=in.readLine()) != null) {
                 String[] str = line.split("\\s+");
    -            if(str[0].equals("cpu")) {
    +            if (str[0].equals("cpu")) {
                     cpuTotal.update(str);
                 }
    -            else if(str[0].startsWith("cpu")){
    +            else if (str[0].startsWith("cpu")) {
                     int cpuId = Integer.parseInt(str[0].substring(3));
    -                if(cpus.size() <= cpuId)
    +                if (cpus.size() <= cpuId)
                         cpus.add(new CpuStats());
                     cpus.get(cpuId).update(str);
                 }
    -            else if(str[0].startsWith("btime")){
    +            else if (str[0].startsWith("btime")) {
                     uptime = Long.parseLong(str[1]);
                 }
    -            else if(str[0].startsWith("processes")){
    +            else if (str[0].startsWith("processes")) {
                     processes = Long.parseLong(str[1]);
                 }
             }
    @@ -89,25 +89,25 @@ public class ProcStat {
     
     
     
    -    public static CpuStats getTotalCpuStats(){
    +    public static CpuStats getTotalCpuStats() {
             update();
             return cpuTotal;
         }
    -    public static Iterator getCpuStats(){
    +    public static Iterator getCpuStats() {
             update();
             return cpus.iterator();
         }
         /**
          * @return the time at which the system booted, in seconds since the Unix epoch.
          */
    -    public static long getUptime(){
    +    public static long getUptime() {
             update();
             return uptime;
         }
         /**
          * @return the number of processes and threads created, which includes (but is not limited to) those created by calls to the fork() and clone() system calls.
          */
    -    public static long getProcesses(){
    +    public static long getProcesses() {
             update();
             return processes;
         }
    @@ -135,10 +135,10 @@ public class ProcStat {
             private float load_iowait;
             private float load_virtual;
     
    -        protected CpuStats(){}
    -        protected void update(String[] stats){
    +        protected CpuStats() {}
    +        protected void update(String[] stats) {
                 long newUser, newNice, newSystem, newIdle, newIowait, newIrq, newSoftirq, newSteal=0, newGuest=0, newGuestNice=0;
    -            if(stats.length >= 1+8){
    +            if (stats.length >= 1+8) {
                     newUser =    Long.parseLong(stats[1]);
                     newNice =    Long.parseLong(stats[2]);
                     newSystem =  Long.parseLong(stats[3]);
    @@ -146,7 +146,7 @@ public class ProcStat {
                     newIowait =  Long.parseLong(stats[5]);
                     newIrq =     Long.parseLong(stats[6]);
                     newSoftirq = Long.parseLong(stats[7]);
    -                if(stats.length >= 1+8+3){
    +                if (stats.length >= 1+8+3) {
                         newSteal =     Long.parseLong(stats[8]);
                         newGuest =     Long.parseLong(stats[9]);
                         newGuestNice = Long.parseLong(stats[10]);
    @@ -200,15 +200,15 @@ public class ProcStat {
     
         }
     
    -    public static void main(String[] args){
    -        while(true){
    +    public static void main(String[] args) {
    +        while (true) {
                 Iterator it = ProcStat.getCpuStats();
    -            for(int i=0; it.hasNext(); ++i){
    +            for (int i=0; it.hasNext(); ++i) {
                     CpuStats cpu = it.next();
    -                System.out.print("CPU"+i+": " + cpu.getTotalLoad()+ " ");
    +                System.out.print("CPU" + i + ": " + cpu.getTotalLoad() + " ");
                 }
                 System.out.println("Total Load: " + ProcStat.getTotalCpuStats().getTotalLoad());
    -            try{Thread.sleep(1000);}catch (Exception e){}
    +            try {Thread.sleep(1000);} catch (Exception e) {}
             }
         }
     }
    diff --git a/src/zutil/osal/linux/app/Ps.java b/src/zutil/osal/linux/app/Ps.java
    index 74e1477..5804e34 100755
    --- a/src/zutil/osal/linux/app/Ps.java
    +++ b/src/zutil/osal/linux/app/Ps.java
    @@ -31,8 +31,8 @@ import zutil.osal.OSAbstractionLayer;
      */
     public class Ps {
     
    -    public static boolean isRunning(int pid){
    -        String[] output = OSAbstractionLayer.exec("ps -p "+pid);
    +    public static boolean isRunning(int pid) {
    +        String[] output = OSAbstractionLayer.exec("ps -p " +pid);
             return output.length > 1;
         }
     }
    diff --git a/src/zutil/osal/macos/OsalMacOSImpl.java b/src/zutil/osal/macos/OsalMacOSImpl.java
    index afcd988..dde4a6f 100755
    --- a/src/zutil/osal/macos/OsalMacOSImpl.java
    +++ b/src/zutil/osal/macos/OsalMacOSImpl.java
    @@ -57,7 +57,7 @@ public class OsalMacOSImpl extends OSAbstractionLayer {
     
         @Override
         public File getUserConfigPath() {
    -        return new File("/home/"+getUsername());
    +        return new File("/home/" +getUsername());
         }
     
         @Override
    diff --git a/src/zutil/osal/windows/app/TypePerf.java b/src/zutil/osal/windows/app/TypePerf.java
    index febfc90..65c7c27 100755
    --- a/src/zutil/osal/windows/app/TypePerf.java
    +++ b/src/zutil/osal/windows/app/TypePerf.java
    @@ -67,7 +67,7 @@ public class TypePerf {
         private static DataNode[] execute(String path) throws IOException {
             DataNode[] ret = new DataNode[2];
     
    -        String[] output = OSAbstractionLayer.exec("typeperf \""+ path +"\"  -SC 0 -y");
    +        String[] output = OSAbstractionLayer.exec("typeperf \"" + path + "\"  -SC 0 -y");
             CSVParser parser = new CSVParser(new StringReader(output[1] + "\n" + output[2]));
     
             ret[0] = parser.getHeaders();
    diff --git a/src/zutil/parser/BBCodeParser.java b/src/zutil/parser/BBCodeParser.java
    index c758b9a..f87d926 100755
    --- a/src/zutil/parser/BBCodeParser.java
    +++ b/src/zutil/parser/BBCodeParser.java
    @@ -41,7 +41,7 @@ public class BBCodeParser {
         /**
          * Initiates a instance of the parser with the most used BBCodes.
          */
    -    public BBCodeParser(){
    +    public BBCodeParser() {
             bbcodes = new HashMap<>();
             addBBCode("b", "%2");
             addBBCode("i", "%2");
    @@ -63,7 +63,7 @@ public class BBCodeParser {
          * @param 	html 		is the corresponding HTML e.g. {@code %2}
          * 						where the %x corresponds to BBCode like this: [url=%1]%2[/url]
          */
    -    public void addBBCode(String bbcode, String html){
    +    public void addBBCode(String bbcode, String html) {
             bbcodes.put(bbcode, html);
         }
     
    @@ -72,7 +72,7 @@ public class BBCodeParser {
          *
          * @param 	bbcode 		is the bbcode to remove
          */
    -    public void removeBBCode(String bbcode){
    +    public void removeBBCode(String bbcode) {
             bbcodes.remove(bbcode);
         }
     
    @@ -82,7 +82,7 @@ public class BBCodeParser {
          * @param 	text 		is a String with BBCode
          * @return a String where all BBCode has been replaced by HTML
          */
    -    public String read(String text){
    +    public String read(String text) {
             StringBuilder out = new StringBuilder();
             StringBuilder t = new StringBuilder(text);
     
    @@ -91,40 +91,40 @@ public class BBCodeParser {
             return out.toString();
         }
     
    -    private void read(MutableInt index, StringBuilder text, StringBuilder out, String rootBBC){
    +    private void read(MutableInt index, StringBuilder text, StringBuilder out, String rootBBC) {
             StringBuilder bbcode = null;
             boolean closeTag = false;
    -        while(index.i < text.length()){
    +        while (index.i < text.length()) {
                 char c = text.charAt(index.i);
    -            if(c == '['){
    +            if (c == '[') {
                     bbcode = new StringBuilder();
                 }
    -            else if(bbcode!=null && c == '/'){
    +            else if (bbcode != null && c == '/') {
                     closeTag = true;
                 }
    -            else if(bbcode!=null){
    +            else if (bbcode != null) {
                     String param = "";
    -                switch(c){
    +                switch(c) {
                         case '=':
                             param = parseParam(index, text);
                         case ']':
                             String bbcode_cache = bbcode.toString();
    -                        if(closeTag){
    -                            if(!rootBBC.equals(bbcode_cache)){
    +                        if (closeTag) {
    +                            if (!rootBBC.equals(bbcode_cache)) {
                                     out.append("[/").append(bbcode).append("]");
                                 }
                                 return;
                             }
                             String value = parseValue(index, text, bbcode_cache);
    -                        if(bbcodes.containsKey( bbcode_cache )){
    -                            String html = bbcodes.get( bbcode_cache );
    +                        if (bbcodes.containsKey(bbcode_cache)) {
    +                            String html = bbcodes.get(bbcode_cache);
                                 html = html.replaceAll("%1", param);
                                 html = html.replaceAll("%2", value);
                                 out.append(html);
                             }
    -                        else{
    +                        else {
                                 out.append('[').append(bbcode);
    -                            if(!param.isEmpty())
    +                            if (!param.isEmpty())
                                     out.append('=').append(param);
                                 out.append(']').append(value);
                                 out.append("[/").append(bbcode).append("]");
    @@ -141,9 +141,9 @@ public class BBCodeParser {
     
                 index.i++;
             }
    -        if(bbcode!=null)
    -            if(closeTag)out.append("[/").append(bbcode);
    -            else 		out.append('[').append(bbcode);
    +        if (bbcode != null)
    +            if (closeTag) out.append("[/").append(bbcode);
    +            else 		 out.append('[').append(bbcode);
         }
     
         /**
    @@ -152,13 +152,13 @@ public class BBCodeParser {
          * @param	text	is the text to parse from
          * @return only the parameter string
          */
    -    private String parseParam(MutableInt index, StringBuilder text){
    +    private String parseParam(MutableInt index, StringBuilder text) {
             StringBuilder param = new StringBuilder();
    -        while(index.i < text.length()){
    +        while (index.i < text.length()) {
                 char c = text.charAt(index.i);
    -            if(c == ']')
    +            if (c == ']')
                     break;
    -            else if(c != '=')
    +            else if (c != '=')
                     param.append(c);
                 index.i++;
             }
    @@ -170,15 +170,15 @@ public class BBCodeParser {
          *
          * @param	text	is the text to parse the value from
          */
    -    private String parseValue(MutableInt index, StringBuilder text, String bbcode){
    +    private String parseValue(MutableInt index, StringBuilder text, String bbcode) {
             StringBuilder value = new StringBuilder();
    -        while(index.i < text.length()){
    +        while (index.i < text.length()) {
                 char c = text.charAt(index.i);
    -            if(c == '['){
    +            if (c == '[') {
                     read(index, text, value, bbcode);
                     break;
                 }
    -            else if(c != ']')
    +            else if (c != ']')
                     value.append(c);
                 index.i++;
             }
    diff --git a/src/zutil/parser/BEncodedParser.java b/src/zutil/parser/BEncodedParser.java
    index c294064..f676992 100755
    --- a/src/zutil/parser/BEncodedParser.java
    +++ b/src/zutil/parser/BEncodedParser.java
    @@ -70,7 +70,7 @@ public class BEncodedParser {
                         throw new ParseException("Corrupt bEncoding", index.i);
                     tmp = data.substring(index.i, end);
                     index.i += tmp.length() + 1;
    -                return new DataNode( new Long(tmp));
    +                return new DataNode(new Long(tmp));
                 /*
                  * Lists are prefixed with a l and terminated by an e. The list
                  * should contain a series of bEncoded elements. For example, the
    @@ -80,14 +80,14 @@ public class BEncodedParser {
                  */
                 case 'l':
                     index.i++;
    -                DataNode list = new DataNode( DataType.List );
    +                DataNode list = new DataNode(DataType.List);
                     c = data.charAt(index.i);
    -                while(c != 'e'){
    -                    list.add( decode_BEncoded(index, data) );
    +                while (c != 'e') {
    +                    list.add(decode_BEncoded(index, data));
                         c = data.charAt(index.i);
                     }
                     index.i++;
    -                if(list.size() == 1) return list.get(0);
    +                if (list.size() == 1) return list.get(0);
                     else return list;
                     /*
                      * Dictionaries are prefixed with a d and terminated by an e. They
    @@ -97,9 +97,9 @@ public class BEncodedParser {
                      */
                 case 'd':
                     index.i++;
    -                DataNode map = new DataNode( DataType.Map );
    +                DataNode map = new DataNode(DataType.Map);
                     c = data.charAt(index.i);
    -                while(c != 'e'){
    +                while (c != 'e') {
                         DataNode tmp2 = decode_BEncoded(index, data);
                         map.set(tmp2.getString(), decode_BEncoded(index, data));
                         if (index.i >= data.length())
    @@ -122,7 +122,7 @@ public class BEncodedParser {
                     index.i += tmp.length() + 1;
                     String ret = data.substring(index.i, index.i+length);
                     index.i += length;
    -                return new DataNode( ret );
    +                return new DataNode(ret);
             }
         }
     }
    diff --git a/src/zutil/parser/Base64Decoder.java b/src/zutil/parser/Base64Decoder.java
    index 5df1c63..acc7cb1 100755
    --- a/src/zutil/parser/Base64Decoder.java
    +++ b/src/zutil/parser/Base64Decoder.java
    @@ -45,44 +45,44 @@ public class Base64Decoder {
         private byte rest_data;
         private int rest = 0;
     
    -    public Base64Decoder(){
    +    public Base64Decoder() {
             output = new DynamicByteArrayStream();
         }
     
     
    -    public static String decode( String data ){
    +    public static String decode(String data) {
             Base64Decoder base64 = new Base64Decoder();
    -        base64.read( data );
    +        base64.read(data);
             return base64.toString();
         }
     
    -    public static String decodeToHex( String data ){
    +    public static String decodeToHex(String data) {
             Base64Decoder base64 = new Base64Decoder();
    -        base64.read( data );
    -        return Converter.toHexString( base64.getByte() );
    +        base64.read(data);
    +        return Converter.toHexString(base64.getByte());
         }
     
    -    public static byte[] decodeToByte( String data ){
    +    public static byte[] decodeToByte(String data) {
             Base64Decoder base64 = new Base64Decoder();
    -        base64.read( data );
    +        base64.read(data);
             return base64.getByte();
         }
     
    -    public void read( String data ){
    -        byte[] buffer = new byte[ (data.length()*6/8) + 1 ];
    +    public void read(String data) {
    +        byte[] buffer = new byte[(data.length()*6/8) + 1];
             int buffi = 0;
    -        if( rest != 0 )
    +        if (rest != 0)
                 buffer[0] = rest_data;
     
    -        for( int i=0; i> 2)    & 0b0011_1111);
                         break;
    @@ -63,15 +63,15 @@ public class Base64Encoder {
                 buffer[buffIndex++] = getChar(b);
             }
             // Any rest left?
    -        if(rest == 2)
    +        if (rest == 2)
                 buffer[buffIndex++] = getChar((byte) ((data[data.length-1] << 4) & 0b0011_0000));
    -        else if(rest == 4)
    +        else if (rest == 4)
                 buffer[buffIndex++] = getChar((byte) ((data[data.length-1] << 2) & 0b0011_1100));
    -        else if(rest == 6)
    +        else if (rest == 6)
                 buffer[buffIndex++] = getChar((byte) (data[data.length-1]        & 0b0011_1111));
     
             // Add padding
    -        for(; buffIndex= 0 && c != '\n'){
    -            if(c == delimiter && !quoteStarted){
    +        while ((c=in.read()) >= 0 && c != '\n') {
    +            if (c == delimiter && !quoteStarted) {
                     data.add(value.toString());
                     value.delete(0, value.length()); // Reset StringBuilder
                 }
    -            else if(c == '\"' &&  // Ignored quotes
    -                    (value.length() == 0 || quoteStarted)){
    +            else if (c == '\"' &&  // Ignored quotes
    +                    (value.length() == 0 || quoteStarted)) {
                     quoteStarted = !quoteStarted;
                 }
                 else
                     value.append((char)c);
             }
    -        if(value.length() > 0)
    +        if (value.length() > 0)
                 data.add(value.toString());
    -        if(data.size() == 0)
    +        if (data.size() == 0)
                 return null;
             return data;
         }
    diff --git a/src/zutil/parser/MathParser.java b/src/zutil/parser/MathParser.java
    index b3e554a..4dbdafb 100644
    --- a/src/zutil/parser/MathParser.java
    +++ b/src/zutil/parser/MathParser.java
    @@ -145,7 +145,7 @@ public class MathParser {
             }
     
             public String toString() {
    -            return "( " + math.toString() + " )";
    +            return "( " + math.toString() + ")";
             }
         }
     
    diff --git a/src/zutil/parser/Templator.java b/src/zutil/parser/Templator.java
    index 4b919d1..16bbed5 100755
    --- a/src/zutil/parser/Templator.java
    +++ b/src/zutil/parser/Templator.java
    @@ -101,7 +101,7 @@ public class Templator {
          * be regenerated if the file changes.
          */
         public Templator(File tmpl) throws IOException {
    -        if(tmpl == null)
    +        if (tmpl == null)
                 throw new IOException("File can not be null!");
     
             this.data = new HashMap<>();
    @@ -110,33 +110,33 @@ public class Templator {
             this.lastModified = file.lastModified();
         }
     
    -    public Templator(String tmpl){
    +    public Templator(String tmpl) {
             this.data = new HashMap<>();
             parseTemplate(tmpl);
         }
     
     
    -    public void set(String key, Object data){
    +    public void set(String key, Object data) {
             this.data.put(key, data);
         }
    -    public Object get(String key){
    +    public Object get(String key) {
             return this.data.get(key);
         }
    -    public void remove(String key){
    +    public void remove(String key) {
             this.data.remove(key);
         }
     
         /**
          * Will clear all data attributes
          */
    -    public void clear(){
    +    public void clear() {
             data.clear();
         }
     
    -    public String compile(){
    -        if(file != null && lastModified != file.lastModified()){
    +    public String compile() {
    +        if (file != null && lastModified != file.lastModified()) {
                 try {
    -                log.info("Template file("+file.getName()+") changed. Regenerating template...");
    +                log.info("Template file(" + file.getName() + ") changed. Regenerating template...");
                     parseTemplate(FileUtil.getContent(file));
                     this.lastModified = file.lastModified();
                 } catch(IOException e) {
    @@ -145,7 +145,7 @@ public class Templator {
             }
     
             StringBuilder str = new StringBuilder();
    -        if(tmplRoot != null)
    +        if (tmplRoot != null)
                 tmplRoot.compile(str);
             return str.toString();
         }
    @@ -153,17 +153,17 @@ public class Templator {
         /**
          * Will parse or re-parse the source template.
          */
    -    private void parseTemplate(String tmpl){
    +    private void parseTemplate(String tmpl) {
             tmplRoot = parseTemplate(new TemplateNode(), tmpl, new MutableInt(), null);
         }
    -    private TemplateNode parseTemplate(TemplateNode root, String tmpl, MutableInt m, String parentTag){
    +    private TemplateNode parseTemplate(TemplateNode root, String tmpl, MutableInt m, String parentTag) {
             StringBuilder data = new StringBuilder();
             boolean tagOpen = false;
     
    -        for(; m.i 0) // Still some text left, add to node
    +        if (data.length() > 0) // Still some text left, add to node
                 root.add(new TemplateStaticString(data.toString()));
     
             // If we get to this point means that this node is incorrectly close
             // or this is the end of the file, so we convert it to a normal node
    -        if(parentTag != null) {
    +        if (parentTag != null) {
                 root = new TemplateNode(root);
    -            String tagName = "{{"+parentTag+"}}";
    +            String tagName = "{{" + parentTag + "}}";
                 log.severe("Missing closure of tag: " + tagName);
                 root.addFirst(new TemplateStaticString(tagName));
             }
    @@ -234,22 +234,22 @@ public class Templator {
         protected class TemplateNode implements TemplateEntity {
             private List entities;
     
    -        public TemplateNode(){
    +        public TemplateNode() {
                 this.entities = new ArrayList<>();
             }
    -        public TemplateNode(TemplateNode node){
    +        public TemplateNode(TemplateNode node) {
                 this.entities = node.entities;
             }
     
    -        public void addFirst(TemplateEntity s){
    +        public void addFirst(TemplateEntity s) {
                 entities.add(0, s);
             }
    -        public void add(TemplateEntity s){
    +        public void add(TemplateEntity s) {
                 entities.add(s);
             }
     
             public void compile(StringBuilder str) {
    -            for(TemplateEntity sec : entities)
    +            for (TemplateEntity sec : entities)
                     sec.compile(str);
             }
         }
    @@ -257,38 +257,38 @@ public class Templator {
         protected class TemplateCondition extends TemplateNode {
             private TemplateDataAttribute attrib;
     
    -        public TemplateCondition(String key){
    +        public TemplateCondition(String key) {
                 this.attrib = new TemplateDataAttribute(key);
             }
     
             public void compile(StringBuilder str) {
                 Object obj = attrib.getObject();
    -            if(obj != null) {
    -                if(obj instanceof Boolean){
    +            if (obj != null) {
    +                if (obj instanceof Boolean) {
                         if ((Boolean) obj)
                             super.compile(str);
                     }
    -                else if(obj instanceof Short){
    +                else if (obj instanceof Short) {
                         if ((Short) obj != 0)
                             super.compile(str);
                     }
    -                else if(obj instanceof Integer){
    +                else if (obj instanceof Integer) {
                         if ((Integer) obj != 0)
                             super.compile(str);
                     }
    -                else if(obj instanceof Long){
    +                else if (obj instanceof Long) {
                         if ((Long) obj != 0L)
                             super.compile(str);
                     }
    -                else if(obj instanceof Float){
    +                else if (obj instanceof Float) {
                         if ((Float) obj != 0f)
                             super.compile(str);
                     }
    -                else if(obj instanceof Double){
    +                else if (obj instanceof Double) {
                         if ((Double) obj != 0d)
                             super.compile(str);
                     }
    -                else if(obj instanceof Iterable || obj.getClass().isArray()) {
    +                else if (obj instanceof Iterable || obj.getClass().isArray()) {
                         Object prevObj = get(".");
                         set(".", obj);
     
    @@ -306,7 +306,7 @@ public class Templator {
                         }
     
                         // Reset map to parent object
    -                    if(prevObj != null)
    +                    if (prevObj != null)
                             set(".", prevObj);
                         else
                             remove(".");
    @@ -321,28 +321,28 @@ public class Templator {
         protected class TemplateNegativeCondition extends TemplateNode {
             private TemplateDataAttribute attrib;
     
    -        public TemplateNegativeCondition(String key){
    +        public TemplateNegativeCondition(String key) {
                 this.attrib = new TemplateDataAttribute(key);
             }
     
             public void compile(StringBuilder str) {
                 Object obj = attrib.getObject();
    -            if(obj == null)
    +            if (obj == null)
                     super.compile(str);
                 else {
    -                if(obj instanceof Boolean) {
    -                    if ( ! (Boolean) obj)
    +                if (obj instanceof Boolean) {
    +                    if (! (Boolean) obj)
                             super.compile(str);
                     }
    -                else if(obj instanceof Integer){
    +                else if (obj instanceof Integer) {
                         if ((Integer) obj == 0)
                             super.compile(str);
                     }
    -                else if(obj instanceof Collection) {
    +                else if (obj instanceof Collection) {
                         if (((Collection) obj).isEmpty())
                             super.compile(str);
                     }
    -                else if(obj.getClass().isArray()) {
    +                else if (obj.getClass().isArray()) {
                         if (((Object[]) obj).length <= 0)
                             super.compile(str);
                     }
    @@ -353,7 +353,7 @@ public class Templator {
         protected class TemplateStaticString implements TemplateEntity {
             private String text;
     
    -        public TemplateStaticString(String text){
    +        public TemplateStaticString(String text) {
                 this.text = text;
             }
     
    @@ -366,34 +366,34 @@ public class Templator {
             private String tag;
             private String[] keys;
     
    -        public TemplateDataAttribute(String tag){
    +        public TemplateDataAttribute(String tag) {
                 this.tag = tag;
                 this.keys = tag.trim().split("\\.");
    -            if(this.keys.length == 0)
    +            if (this.keys.length == 0)
                     this.keys = new String[]{"."};
    -            if(this.keys[0].isEmpty()) // if tag starts with "."
    +            if (this.keys[0].isEmpty()) // if tag starts with "."
                     this.keys[0] = ".";
             }
     
     
    -        public Object getObject(){
    +        public Object getObject() {
                 if (data.containsKey(tag))
                     return data.get(tag);
                 else if (data.containsKey(keys[0]) && data.get(keys[0]) != null) {
                     Object obj = data.get(keys[0]);
    -                for(int i=1; i 2) {
    +                if (attrib.endsWith("()")) { // Is this a function call?
    +                    if (attrib.length() > 2) {
                             String funcName = attrib.substring(0, attrib.length()-2);
                             // Using a loop as the direct lookup throws a exception if no field was found
                             // So this is probably a bit faster
    @@ -405,9 +405,9 @@ public class Templator {
                             }
                         }
                     }
    -                else if(obj.getClass().isArray() && "length".equals(attrib))
    +                else if (obj.getClass().isArray() && "length".equals(attrib))
                         return Array.getLength(obj);
    -                else if(obj instanceof Collection && "length".equals(attrib))
    +                else if (obj instanceof Collection && "length".equals(attrib))
                         return ((Collection) obj).size();
                     else {
                         // Using a loop as the direct lookup throws a exception if no field was found
    @@ -419,7 +419,7 @@ public class Templator {
                             }
                         }
                     }
    -            }catch (IllegalAccessException | InvocationTargetException e){
    +            } catch (IllegalAccessException | InvocationTargetException e) {
                     log.log(Level.WARNING, null, e);
                 }
                 return null;
    @@ -428,8 +428,8 @@ public class Templator {
     
             public void compile(StringBuilder str) {
                 Object obj = getObject();
    -            if(obj != null)
    -                if(obj instanceof Templator)
    +            if (obj != null)
    +                if (obj instanceof Templator)
                         str.append(((Templator) obj).compile());
                     else
                         str.append(obj.toString());
    diff --git a/src/zutil/parser/URLDecoder.java b/src/zutil/parser/URLDecoder.java
    index 2f9f786..08ac7ec 100755
    --- a/src/zutil/parser/URLDecoder.java
    +++ b/src/zutil/parser/URLDecoder.java
    @@ -34,9 +34,9 @@ import java.io.UnsupportedEncodingException;
      * Created by Ziver on 2015-12-11.
      */
     public class URLDecoder {
    -    
    -    public static String decode(String url){
    -        if(url == null)
    +
    +    public static String decode(String url) {
    +        if (url == null)
                 return null;
     
             try {
    @@ -44,16 +44,16 @@ public class URLDecoder {
                 byte[] buffer = null;
                 for (int i=0; i getStructFieldList(Class clazz){
    +    protected static List getStructFieldList(Class clazz) {
             if (!cache.containsKey(clazz)) {
                 try {
                     ArrayList list = new ArrayList<>();
    -                for(Class cc = clazz; cc != Object.class ;cc = cc.getSuperclass()) { // iterate through all super classes
    +                for (Class cc = clazz; cc != Object.class; cc = cc.getSuperclass()) { // iterate through all super classes
                         for (Field field : cc.getDeclaredFields()) {
                             if (field.isAnnotationPresent(BinaryField.class) ||
                                     field.isAnnotationPresent(CustomBinaryField.class) ||
    @@ -86,7 +86,7 @@ public class BinaryFieldData {
             this.lengthField = null;
             this.lengthMultiplier = 1;
             this.serializer = null;
    -        if (field.isAnnotationPresent(CustomBinaryField.class)){
    +        if (field.isAnnotationPresent(CustomBinaryField.class)) {
                 CustomBinaryField fieldData = field.getAnnotation(CustomBinaryField.class);
                 this.index = fieldData.index();
                 this.serializer = fieldData.serializer().newInstance();
    @@ -97,7 +97,7 @@ public class BinaryFieldData {
                 this.lengthMultiplier = fieldData.multiplier();
                 this.lengthField = new BinaryFieldData(
                         field.getDeclaringClass().getDeclaredField(fieldData.lengthField()));
    -            if ( !ClassUtil.isNumber(lengthField.getType()))
    +            if (!ClassUtil.isNumber(lengthField.getType()))
                     throw new IllegalArgumentException("Length variable for VariableLengthBinaryStruct needs to be of a number type.");
             }
             else {
    @@ -108,14 +108,14 @@ public class BinaryFieldData {
         }
     
     
    -    public String getName(){
    +    public String getName() {
             return field.getName();
         }
    -    public Class getType(){
    +    public Class getType() {
             return field.getType();
         }
     
    -    public void setByteValue(Object obj, byte[] data){
    +    public void setByteValue(Object obj, byte[] data) {
             try {
                 field.setAccessible(true);
                 if (field.getType() == Boolean.class || field.getType() == boolean.class)
    @@ -127,21 +127,21 @@ public class BinaryFieldData {
                 else if (field.getType() == String.class)
                     field.set(obj, new String(ByteUtil.getReverseByteOrder(data), StandardCharsets.ISO_8859_1));
                 else
    -                throw new UnsupportedOperationException("Unsupported BinaryStruct field class: "+ field.getType());
    -        } catch (IllegalAccessException e){
    +                throw new UnsupportedOperationException("Unsupported BinaryStruct field class: " + field.getType());
    +        } catch (IllegalAccessException e) {
                 e.printStackTrace();
             }
         }
    -    public void setValue(Object obj, Object value){
    +    public void setValue(Object obj, Object value) {
             try {
                 field.setAccessible(true);
                 field.set(obj, value);
    -        } catch (IllegalAccessException e){
    +        } catch (IllegalAccessException e) {
                 e.printStackTrace();
             }
         }
     
    -    public byte[] getByteValue(Object obj){
    +    public byte[] getByteValue(Object obj) {
             try {
                 field.setAccessible(true);
                 if (field.getType() == Boolean.class || field.getType() == boolean.class)
    @@ -162,13 +162,13 @@ public class BinaryFieldData {
                                     ((String)(field.get(obj))).getBytes(StandardCharsets.ISO_8859_1),
                                     getBitLength(obj)));
                 else
    -                throw new UnsupportedOperationException("Unsupported BinaryStruct field type: "+ getType());
    -        } catch (IllegalAccessException e){
    +                throw new UnsupportedOperationException("Unsupported BinaryStruct field type: " + getType());
    +        } catch (IllegalAccessException e) {
                 e.printStackTrace();
             }
             return null;
         }
    -    public Object getValue(Object obj){
    +    public Object getValue(Object obj) {
             try {
                 field.setAccessible(true);
                 return field.get(obj);
    @@ -179,24 +179,24 @@ public class BinaryFieldData {
         }
     
     
    -    public int getBitLength(Object obj){
    -        if(lengthField != null)
    +    public int getBitLength(Object obj) {
    +        if (lengthField != null)
                 return (int) lengthField.getValue(obj) * lengthMultiplier;
             return length;
         }
     
    -    public BinaryFieldSerializer getSerializer(){
    +    public BinaryFieldSerializer getSerializer() {
             return serializer;
         }
     
     
         @Override
    -    public String toString(){
    +    public String toString() {
             return field.getDeclaringClass().getSimpleName() + "::" + field.getName() +
                     " (" +
                     (lengthField != null ?
    -                    "LengthField: " + lengthField +", LengthMultiplier: "+lengthMultiplier :
    -                    length+" bits") +
    +                    "LengthField: " + lengthField + ", LengthMultiplier: " + lengthMultiplier :
    +                    length + " bits") +
                     (serializer != null ?
                         ", Serializer: " + serializer.getClass().getName() : "") +
                     ")";
    diff --git a/src/zutil/parser/binary/BinaryStructInputStream.java b/src/zutil/parser/binary/BinaryStructInputStream.java
    index 6afd1fe..79b8d7b 100755
    --- a/src/zutil/parser/binary/BinaryStructInputStream.java
    +++ b/src/zutil/parser/binary/BinaryStructInputStream.java
    @@ -43,7 +43,7 @@ public class BinaryStructInputStream {
         private byte data;
         private int dataBitIndex = -1;
     
    -    public BinaryStructInputStream(InputStream in){
    +    public BinaryStructInputStream(InputStream in) {
             this.in = in;
         }
     
    @@ -63,7 +63,7 @@ public class BinaryStructInputStream {
                 ByteArrayInputStream buffer = new ByteArrayInputStream(data, offset, length);
                 BinaryStructInputStream in = new BinaryStructInputStream(buffer);
                 read = in.read(struct);
    -        } catch (Exception e){
    +        } catch (Exception e) {
                 e.printStackTrace();
             }
             return read;
    @@ -76,8 +76,8 @@ public class BinaryStructInputStream {
             List structDataList = BinaryFieldData.getStructFieldList(struct.getClass());
     
             int totalReadLength = 0;
    -        for (BinaryFieldData field : structDataList){
    -            if (field.getSerializer() != null){
    +        for (BinaryFieldData field : structDataList) {
    +            if (field.getSerializer() != null) {
                     Object value = field.getSerializer().read(in, field);
                     field.setValue(struct, value);
                 }
    @@ -87,7 +87,7 @@ public class BinaryStructInputStream {
                     int shiftBy = shiftLeftBy(dataBitIndex, field.getBitLength(struct));
     
                     // Parse value
    -                for (int valueDataIndex=valueData.length-1; valueDataIndex >= 0 ; --valueDataIndex) {
    +                for (int valueDataIndex=valueData.length-1; valueDataIndex >= 0; --valueDataIndex) {
                         if (dataBitIndex < 0) { // Read new data?
                             data = (byte) in.read();
                             dataBitIndex = 7;
    @@ -110,13 +110,13 @@ public class BinaryStructInputStream {
         /**
          * @see InputStream#markSupported()
          */
    -    public boolean markSupported(){
    +    public boolean markSupported() {
             return in.markSupported();
         }
         /**
          * @see InputStream#mark(int)
          */
    -    public void mark(int limit){
    +    public void mark(int limit) {
             in.mark(limit);
         }
         /**
    @@ -128,7 +128,7 @@ public class BinaryStructInputStream {
     
     
     
    -    protected static int shiftLeftBy(int bitIndex, int bitLength){
    +    protected static int shiftLeftBy(int bitIndex, int bitLength) {
             return (8 - ((7-bitIndex) + bitLength) % 8) % 8;
         }
     }
    diff --git a/src/zutil/parser/binary/BinaryStructOutputStream.java b/src/zutil/parser/binary/BinaryStructOutputStream.java
    index caa3d7a..3d66ba5 100755
    --- a/src/zutil/parser/binary/BinaryStructOutputStream.java
    +++ b/src/zutil/parser/binary/BinaryStructOutputStream.java
    @@ -45,7 +45,7 @@ public class BinaryStructOutputStream {
         private int restBitLength; // length from Most Significant Bit
     
     
    -    public BinaryStructOutputStream(OutputStream out){
    +    public BinaryStructOutputStream(OutputStream out) {
             this.out = out;
     
             rest = 0;
    @@ -85,12 +85,12 @@ public class BinaryStructOutputStream {
         public void write(BinaryStruct struct) throws IOException {
             List structDataList = BinaryFieldData.getStructFieldList(struct.getClass());
     
    -        for (BinaryFieldData field : structDataList){
    -            if (field.getSerializer() != null){
    +        for (BinaryFieldData field : structDataList) {
    +            if (field.getSerializer() != null) {
                     localFlush();
                     field.getSerializer().write(out, field.getValue(struct), field);
                 }
    -            else{
    +            else {
                     int fieldBitLength = field.getBitLength(struct);
                     byte[] data = field.getByteValue(struct);
                     data = ByteUtil.shiftRight(data, ((8 - fieldBitLength % 8) % 8));
    @@ -122,7 +122,7 @@ public class BinaryStructOutputStream {
             out.flush();
         }
         private void localFlush() throws IOException {
    -        if(restBitLength > 0){
    +        if (restBitLength > 0) {
                 out.write(0xFF & rest);
                 rest = 0;
                 restBitLength = 0;
    diff --git a/src/zutil/parser/json/JSONObjectInputStream.java b/src/zutil/parser/json/JSONObjectInputStream.java
    index 5396855..9125ca6 100755
    --- a/src/zutil/parser/json/JSONObjectInputStream.java
    +++ b/src/zutil/parser/json/JSONObjectInputStream.java
    @@ -71,7 +71,7 @@ public class JSONObjectInputStream extends InputStream implements ObjectInput, C
          *
          * @param   c       the Class that will be instantiated for the root JSON.
          */
    -    public void registerRootClass(Class c){
    +    public void registerRootClass(Class c) {
             registeredClasses.put(null, c);
         }
     
    @@ -83,7 +83,7 @@ public class JSONObjectInputStream extends InputStream implements ObjectInput, C
          * @param   key     a String key that will be looked for in the InputStream
          * @param   c       the Class that will be instantiated for the specific key.
          */
    -    public void registerClass(String key, Class c){
    +    public void registerClass(String key, Class c) {
             registeredClasses.put(key, c);
         }
     
    @@ -107,9 +107,9 @@ public class JSONObjectInputStream extends InputStream implements ObjectInput, C
          * @return  the object read from the stream
          */
         public synchronized  T readObject(Class c) {
    -        try{
    +        try {
                 DataNode root = parser.read();
    -            if(root != null){
    +            if (root != null) {
                     return (T)readObject(c, null, root);
                 }
             } catch (Exception e) {
    @@ -123,39 +123,39 @@ public class JSONObjectInputStream extends InputStream implements ObjectInput, C
     
         @SuppressWarnings({ "rawtypes", "unchecked" })
         protected Object readType(Class type, Class[] genType, String key, DataNode json) throws IllegalAccessException, ClassNotFoundException, InstantiationException, NoSuchFieldException {
    -        if(json == null || type == null)
    +        if (json == null || type == null)
                 return null;
             // Field type is a primitive?
    -        if(type.isPrimitive() || String.class.isAssignableFrom(type)){
    +        if (type.isPrimitive() || String.class.isAssignableFrom(type)) {
                 return readPrimitive(type, json);
             }
    -        else if(type.isArray()){
    -            if(type.getComponentType() == byte.class)
    +        else if (type.isArray()) {
    +            if (type.getComponentType() == byte.class)
                     return Base64Decoder.decodeToByte(json.getString());
    -            else{
    +            else {
                     Object array = Array.newInstance(type.getComponentType(), json.size());
    -                for(int i=0; i=1? genType[0] : null), null, key, json.get(i)));
                 }
                 return list;
             }
    -        else if(Map.class.isAssignableFrom(type)){
    -            if(genType == null || genType.length < 2)
    +        else if (Map.class.isAssignableFrom(type)) {
    +            if (genType == null || genType.length < 2)
                     genType = ClassUtil.getGenericClasses(type, Map.class);
                 Map map = (Map)type.newInstance();
    -            for(Iterator it=json.keyIterator(); it.hasNext();){
    +            for (Iterator it=json.keyIterator(); it.hasNext();) {
                     String subKey = it.next();
    -                if(json.get(subKey) != null) {
    +                if (json.get(subKey) != null) {
                         map.put(
                                 subKey,
                                 readType((genType.length >= 2 ? genType[1] : null), null, subKey, json.get(subKey)));
    @@ -164,7 +164,7 @@ public class JSONObjectInputStream extends InputStream implements ObjectInput, C
                 return map;
             }
             // Field is a new Object
    -        else{
    +        else {
                 return readObject(type, key, json);
             }
         }
    @@ -172,39 +172,39 @@ public class JSONObjectInputStream extends InputStream implements ObjectInput, C
     
         protected Object readObject(Class type, String key, DataNode json) throws IllegalAccessException, InstantiationException, ClassNotFoundException, IllegalArgumentException, NoSuchFieldException {
             // Only parse if json is a map
    -        if(json == null || !json.isMap())
    +        if (json == null || !json.isMap())
                 return null;
             // See if the Object id is in the cache before continuing
    -        if(json.getString("@object_id") != null && objectCache.containsKey(json.getInt(MD_OBJECT_ID)))
    +        if (json.getString("@object_id") != null && objectCache.containsKey(json.getInt(MD_OBJECT_ID)))
                 return objectCache.get(json.getInt(MD_OBJECT_ID));
     
             // Resolve the class
             Object obj;
             // Try using explicit class
    -        if(type != null){
    +        if (type != null) {
                 obj = type.newInstance();
             }
             // Try using metadata
    -        else if(json.getString(MD_CLASS) != null) {
    +        else if (json.getString(MD_CLASS) != null) {
                 Class objClass = Class.forName(json.getString(MD_CLASS));
                 obj = objClass.newInstance();
             }
             // Search for registered classes
    -        else if(registeredClasses.containsKey(key)){
    +        else if (registeredClasses.containsKey(key)) {
                 Class objClass = registeredClasses.get(key);
                 obj = objClass.newInstance();
             }
             // Unknown class
             else {
    -            logger.warning("Unknown type for key: '"+key+"'");
    +            logger.warning("Unknown type for key: '" + key + "'");
                 return null;
             }
     
             // Read all fields from the new object instance
    -        for(Field field : obj.getClass().getDeclaredFields()){
    -            if((field.getModifiers() & Modifier.STATIC) == 0 &&
    +        for (Field field : obj.getClass().getDeclaredFields()) {
    +            if ((field.getModifiers() & Modifier.STATIC) == 0 &&
                         (field.getModifiers() & Modifier.TRANSIENT) == 0 &&
    -                    json.get(field.getName()) != null){
    +                    json.get(field.getName()) != null) {
                     // Parse field
                     field.setAccessible(true);
                     field.set(obj,
    @@ -216,24 +216,24 @@ public class JSONObjectInputStream extends InputStream implements ObjectInput, C
                 }
             }
             // Add object to the cache
    -        if(json.getString(MD_OBJECT_ID) != null)
    +        if (json.getString(MD_OBJECT_ID) != null)
                 objectCache.put(json.getInt(MD_OBJECT_ID), obj);
             return obj;
         }
     
     
    -    protected static Object readPrimitive(Class type, DataNode json){
    -        if     (type == int.class ||
    +    protected static Object readPrimitive(Class type, DataNode json) {
    +        if      (type == int.class ||
                     type == Integer.class) return json.getInt();
    -        else if(type == long.class ||
    +        else if (type == long.class ||
                     type == Long.class)    return json.getLong();
     
    -        else if(type == double.class ||
    +        else if (type == double.class ||
                     type == Double.class)  return json.getDouble();
     
    -        else if(type == boolean.class ||
    +        else if (type == boolean.class ||
                     type == Boolean.class) return json.getBoolean();
    -        else if(type == String.class)  return json.getString();
    +        else if (type == String.class)  return json.getString();
             return null;
         }
     
    diff --git a/src/zutil/parser/json/JSONObjectOutputStream.java b/src/zutil/parser/json/JSONObjectOutputStream.java
    index 611e62f..6e99d73 100755
    --- a/src/zutil/parser/json/JSONObjectOutputStream.java
    +++ b/src/zutil/parser/json/JSONObjectOutputStream.java
    @@ -67,7 +67,7 @@ public class JSONObjectOutputStream extends OutputStream implements ObjectOutput
         /**
          * @return a String containing the JSON representation of the Object
          */
    -    public static String toString(Object obj){
    +    public static String toString(Object obj) {
             try {
                 StringOutputStream out = new StringOutputStream();
                 JSONObjectOutputStream writer = new JSONObjectOutputStream(out);
    @@ -81,7 +81,7 @@ public class JSONObjectOutputStream extends OutputStream implements ObjectOutput
         }
     
         public synchronized void writeObject(Object obj) throws IOException{
    -        try{
    +        try {
                 out.write(getDataNode(obj));
             } catch (IllegalAccessException e) {
                 throw new IOException("Unable to serialize object", e);
    @@ -91,20 +91,20 @@ public class JSONObjectOutputStream extends OutputStream implements ObjectOutput
         }
     
         protected DataNode getDataNode(Object obj) throws IOException, IllegalArgumentException, IllegalAccessException {
    -        if(obj == null)
    +        if (obj == null)
                 return null;
             Class objClass = obj.getClass();
             DataNode root;
     
             // Check if the object is a primitive
    -        if(ClassUtil.isPrimitive(obj.getClass()) ||
    -                ClassUtil.isWrapper(obj.getClass())){
    +        if (ClassUtil.isPrimitive(obj.getClass()) ||
    +                ClassUtil.isWrapper(obj.getClass())) {
                 root = getPrimitiveDataNode(obj.getClass(), obj);
             }
             // Add an array
    -        else if(objClass.isArray()){
    +        else if (objClass.isArray()) {
                 // Special case for byte arrays
    -            if(objClass.getComponentType() == byte.class) {
    +            if (objClass.getComponentType() == byte.class) {
                     root = new DataNode(DataType.String);
                     root.set(Base64Encoder.encode((byte[])obj));
                 }
    @@ -117,18 +117,18 @@ public class JSONObjectOutputStream extends OutputStream implements ObjectOutput
                 }
             }
             // List
    -        else if(List.class.isAssignableFrom(objClass)){
    +        else if (List.class.isAssignableFrom(objClass)) {
                 root = new DataNode(DataNode.DataType.List);
                 List list = (List)obj;
    -            for(Object item : list){
    +            for (Object item : list) {
                     root.add(getDataNode(item));
                 }
             }
             // Map
    -        else if(Map.class.isAssignableFrom(objClass)){
    +        else if (Map.class.isAssignableFrom(objClass)) {
                 root = new DataNode(DataNode.DataType.Map);
                 Map map = (Map)obj;
    -            for(Object key : map.keySet()){
    +            for (Object key : map.keySet()) {
                     root.set(
                             getDataNode(key).getString(),
                             getDataNode(map.get(key)));
    @@ -138,27 +138,27 @@ public class JSONObjectOutputStream extends OutputStream implements ObjectOutput
             else {
                 root = new DataNode(DataNode.DataType.Map);
                 // Generate meta data
    -            if(generateMetaData){
    +            if (generateMetaData) {
                     // Cache
    -                if(objectCache.containsKey(obj)){ // Hit
    +                if (objectCache.containsKey(obj)) { // Hit
                         root.set(MD_OBJECT_ID, objectCache.get(obj));
                         return root;
                     }
    -                else{ // Miss
    +                else { // Miss
                         objectCache.put(obj, objectCache.size()+1);
                         root.set(MD_OBJECT_ID, objectCache.size());
                     }
                     root.set(MD_CLASS, obj.getClass().getName());
                 }
                 // Add all the fields to the DataNode
    -            for(Field field : obj.getClass().getDeclaredFields()){
    -                if( ! Modifier.isStatic(field.getModifiers()) &&
    -                        ! Modifier.isTransient(field.getModifiers())){
    +            for (Field field : obj.getClass().getDeclaredFields()) {
    +                if (! Modifier.isStatic(field.getModifiers()) &&
    +                        ! Modifier.isTransient(field.getModifiers())) {
                         field.setAccessible(true);
                         Object fieldObj = field.get(obj);
     
                         // has object a value?
    -                    if(ignoreNullFields && fieldObj == null)
    +                    if (ignoreNullFields && fieldObj == null)
                             continue;
                         else
                             root.set(field.getName(), getDataNode(fieldObj));
    @@ -178,18 +178,18 @@ public class JSONObjectOutputStream extends OutputStream implements ObjectOutput
                     type == Double.class)
                 node = new DataNode(DataType.Number);
     
    -        else if(type == boolean.class ||
    +        else if (type == boolean.class ||
                     type == Boolean.class)
                 node = new DataNode(DataType.Boolean);
     
    -        else if(type == String.class ||
    +        else if (type == String.class ||
                     type == char.class ||
                     type == Character.class)
                 node = new DataNode(DataType.String);
             else
    -            throw new IllegalArgumentException("Unsupported primitive data type: "+type.getName());
    +            throw new IllegalArgumentException("Unsupported primitive data type: " +type.getName());
     
    -        if(value != null)
    +        if (value != null)
                 node.set(value.toString());
             return node;
         }
    @@ -202,7 +202,7 @@ public class JSONObjectOutputStream extends OutputStream implements ObjectOutput
          *
          * All the meta-data tags will start with a '@'
          */
    -    public void enableMetaData(boolean generate){
    +    public void enableMetaData(boolean generate) {
             generateMetaData = generate;
         }
     
    diff --git a/src/zutil/parser/json/JSONParser.java b/src/zutil/parser/json/JSONParser.java
    index a80b7f6..7ad63e1 100755
    --- a/src/zutil/parser/json/JSONParser.java
    +++ b/src/zutil/parser/json/JSONParser.java
    @@ -50,10 +50,10 @@ public class JSONParser extends Parser {
         private Reader in;
     
     
    -    public JSONParser(Reader in){
    +    public JSONParser(Reader in) {
            this.in = in;
         }
    -    public JSONParser(InputStream in){
    +    public JSONParser(InputStream in) {
             this.in = new InputStreamReader(in);
         }
     
    @@ -74,12 +74,12 @@ public class JSONParser extends Parser {
          * @param 	json	is the JSON String to parse
          * @return a DataNode object representing the JSON in the input String
          */
    -    public static DataNode read(String json){
    -        try{
    +    public static DataNode read(String json) {
    +        try {
                 return parse(new StringReader(json), new MutableInt());
    -        }catch (IOException e){
    +        } catch (IOException e) {
                 e.printStackTrace();
    -        }catch (NullPointerException e){}
    +        } catch (NullPointerException e) {}
             return null;
         }
     
    @@ -93,10 +93,10 @@ public class JSONParser extends Parser {
             end.i = CONTINUE;
     
             int c;
    -        while((c=in.read()) >= 0 &&
    +        while ((c=in.read()) >= 0 &&
                     (Character.isWhitespace(c) || c == ',' || c == ':'));
     
    -        switch( c ){
    +        switch(c) {
                 // End of stream
                 case -1:
                 // This is the end of an Map or List
    @@ -108,23 +108,23 @@ public class JSONParser extends Parser {
                 // Parse Map
                 case '{':
                     root = new DataNode(DataType.Map);
    -                while(end.i == CONTINUE) {
    +                while (end.i == CONTINUE) {
                         key = parse(in, end);
    -                    if(end.i == END_WITH_NULL) // Break if there is no more data
    +                    if (end.i == END_WITH_NULL) // Break if there is no more data
                             break;
                         node = parse(in, end);
    -                    if(end.i != END_WITH_NULL) // Only add the entry if it is a value
    -                        root.set( key.toString(), node );
    +                    if (end.i != END_WITH_NULL) // Only add the entry if it is a value
    +                        root.set(key.toString(), node);
                     }
                     end.i = CONTINUE;
                     break;
                 // Parse List
                 case '[':
                     root = new DataNode(DataType.List);
    -                while(end.i == CONTINUE){
    +                while (end.i == CONTINUE) {
                         node = parse(in, end);
    -                    if(end.i != END_WITH_NULL)
    -                        root.add( node );
    +                    if (end.i != END_WITH_NULL)
    +                        root.add(node);
                     }
                     end.i = CONTINUE;
                     break;
    @@ -133,15 +133,15 @@ public class JSONParser extends Parser {
                 case '\"':
                     root = new DataNode(DataType.String);
                     StringBuilder str = new StringBuilder();
    -                while((c=in.read()) >= 0 && c != '\"')
    +                while ((c=in.read()) >= 0 && c != '\"')
                         str.append((char)c);
                     root.set(str.toString());
                     break;
                 // Parse unknown type
                 default:
                     StringBuilder tmp = new StringBuilder().append((char)c);
    -                while((c=in.read()) >= 0 && c != ',' && c != ':'){
    -                    if(c == ']' || c == '}'){
    +                while ((c=in.read()) >= 0 && c != ',' && c != ':') {
    +                    if (c == ']' || c == '}') {
                             end.i = END_WITH_VALUE;
                             break;
                         }
    @@ -149,17 +149,17 @@ public class JSONParser extends Parser {
                     }
                     // Check what type of type the data is
                     String data = tmp.toString().trim();
    -                if( NULL_PATTERN.matcher(data).matches() )
    +                if (NULL_PATTERN.matcher(data).matches())
                         root = null;
    -                else if( BOOLEAN_PATTERN.matcher(data).matches() )
    +                else if (BOOLEAN_PATTERN.matcher(data).matches())
                         root = new DataNode(DataType.Boolean);
    -                else if( NUMBER_PATTERN.matcher(data).matches() )
    +                else if (NUMBER_PATTERN.matcher(data).matches())
                         root = new DataNode(DataType.Number);
                     else {
                         root = new DataNode(DataType.String);
                         data = unEscapeString(data);
                     }
    -                if(root != null)
    +                if (root != null)
                         root.set(data);
                     break;
             }
    @@ -167,7 +167,7 @@ public class JSONParser extends Parser {
             return root;
         }
     
    -    private static String unEscapeString(String str){
    +    private static String unEscapeString(String str) {
             // Replace two backslash with one
             return str.replaceAll("\\\\\\\\", "\\\\");
         }
    diff --git a/src/zutil/parser/json/JSONWriter.java b/src/zutil/parser/json/JSONWriter.java
    index b03d023..8321235 100755
    --- a/src/zutil/parser/json/JSONWriter.java
    +++ b/src/zutil/parser/json/JSONWriter.java
    @@ -46,8 +46,8 @@ public class JSONWriter{
          *
          * @param out the OutputStream that the Nodes will be sent to
          */
    -    public JSONWriter(OutputStream out){
    -        this( new PrintWriter(out) );
    +    public JSONWriter(OutputStream out) {
    +        this(new PrintWriter(out));
         }
     
         /**
    @@ -55,8 +55,8 @@ public class JSONWriter{
          *
          * @param out the OutputStream that the Nodes will be sent to
          */
    -    public JSONWriter(Writer out){
    -        this( new PrintWriter(out) );
    +    public JSONWriter(Writer out) {
    +        this(new PrintWriter(out));
         }
     
         /**
    @@ -64,7 +64,7 @@ public class JSONWriter{
          *
          * @param out the OutputStream that the Nodes will be sent to
          */
    -    public JSONWriter(PrintWriter out){
    +    public JSONWriter(PrintWriter out) {
             this.out = out;
         }
     
    @@ -73,20 +73,20 @@ public class JSONWriter{
          *
          * @param root is the root node
          */
    -    public void write(DataNode root){
    -        if(root == null){
    +    public void write(DataNode root) {
    +        if (root == null) {
                 out.print("null");
                 return;
             }
     
             boolean first = true;
    -        switch(root.getType()){
    +        switch(root.getType()) {
                 // Write Map
                 case Map:
                     out.append('{');
                     Iterator it = root.keyIterator();
    -                while(it.hasNext()){
    -                    if(!first)
    +                while (it.hasNext()) {
    +                    if (!first)
                             out.append(", ");
                         String key = it.next();
                         out.append('\"');
    @@ -100,8 +100,8 @@ public class JSONWriter{
                 // Write List
                 case List:
                     out.append('[');
    -                for(DataNode node : root){
    -                    if(!first)
    +                for (DataNode node : root) {
    +                    if (!first)
                             out.append(", ");
                         write(node);
                         first = false;
    @@ -109,7 +109,7 @@ public class JSONWriter{
                     out.append(']');
                     break;
                 default:
    -                if(root.getString() != null && root.getType() == DataType.String){
    +                if (root.getString() != null && root.getType() == DataType.String) {
                         out.append('\"');
                         out.append(escapeString(root.toString()));
                         out.append('\"');
    @@ -119,7 +119,7 @@ public class JSONWriter{
             }
         }
     
    -    private static String escapeString(String str){
    +    private static String escapeString(String str) {
             // Replace one backslash with two
             return str.replaceAll("\\\\", "\\\\\\\\");
         }
    @@ -127,14 +127,14 @@ public class JSONWriter{
         /**
          * Closes the internal stream
          */
    -    public void close(){
    +    public void close() {
             out.close();
         }
     
         /**
          * @return a String containing the JSON representation of the input DataNode graph
          */
    -    public static String toString(DataNode root){
    +    public static String toString(DataNode root) {
             StringOutputStream out = new StringOutputStream();
             JSONWriter writer = new JSONWriter(out);
             writer.write(root);
    @@ -142,7 +142,7 @@ public class JSONWriter{
             return out.toString();
         }
     
    -    public void flush(){
    +    public void flush() {
             out.flush();
         }
     }
    diff --git a/src/zutil/plugin/PluginData.java b/src/zutil/plugin/PluginData.java
    index 20ab139..7f0a297 100755
    --- a/src/zutil/plugin/PluginData.java
    +++ b/src/zutil/plugin/PluginData.java
    @@ -58,15 +58,15 @@ public class PluginData {
             log.fine("Plugin: " + this);
     
             DataNode node = data.get("interfaces");
    -        if(node.isMap())
    +        if (node.isMap())
                 addInterfaces(node);
    -        else if(node.isList()) {
    +        else if (node.isList()) {
                 for (DataNode childNode : node) {
                     addInterfaces(childNode);
                 }
             }
         }
    -    private void addInterfaces(DataNode node){
    +    private void addInterfaces(DataNode node) {
             Iterator intf_it = node.keyIterator();
             while (intf_it.hasNext()) {
                 String pluginIntf = intf_it.next();
    @@ -79,7 +79,7 @@ public class PluginData {
                             (intfClass==null ? "(Not Available) " : "") + pluginIntf + " --> " +
                             (pluginClass==null ? "(Not Available) " : "") + className);
                 else
    -                log.finer("Plugin interface: "+ pluginIntf +" --> "+ className);
    +                log.finer("Plugin interface: " + pluginIntf + " --> " + className);
     
                 if (intfClass == null || pluginClass == null)
                     continue;
    @@ -92,7 +92,7 @@ public class PluginData {
         private static Class getClassByName(String name) {
             try {
                 return Class.forName(name);
    -        }catch (Exception e){
    +        } catch (Exception e) {
                 //log.log(Level.WARNING, null, e); // No need to log, we are handling it
             }
             return null;
    @@ -102,32 +102,32 @@ public class PluginData {
         /**
          * @return a version number for the plugin (specified in the plugin.json file
          */
    -    public double getVersion(){
    +    public double getVersion() {
             return pluginVersion;
         }
         /**
          * @return the name of the plugin
          */
    -    public String getName(){
    +    public String getName() {
             return pluginName;
         }
         /**
          * @return the name of the plugin
          */
    -    public String getDescription(){
    +    public String getDescription() {
             return pluginDescription;
         }
         /**
          * @return if this plugin is enabled
          */
    -    public boolean isEnabled(){
    +    public boolean isEnabled() {
             return enabled;
         }
     
         /**
          * Enables or disables this plugin
          */
    -    public void setEnabled(boolean enabled){
    +    public void setEnabled(boolean enabled) {
             this.enabled = enabled;
         }
     
    @@ -135,16 +135,16 @@ public class PluginData {
         /**
          * @return a Iterator for all singleton Object instance that implement the specified interface
          */
    -    public  Iterator getObjectIterator(Class intf){
    -        if(!classMap.containsKey(intf))
    +    public  Iterator getObjectIterator(Class intf) {
    +        if (!classMap.containsKey(intf))
                 return Collections.emptyIterator();
             return new PluginSingletonIterator<>(classMap.get(intf).iterator());
         }
         /**
          * @return a Iterator for all classes implementing the interface by the plugin
          */
    -    public Iterator> getClassIterator(Class intf){
    -        if(!classMap.containsKey(intf))
    +    public Iterator> getClassIterator(Class intf) {
    +        if (!classMap.containsKey(intf))
                 return Collections.emptyIterator();
             return classMap.get(intf).iterator();
         }
    @@ -163,12 +163,12 @@ public class PluginData {
         /**
          * @return true if the specified interface is defined by the plugin
          */
    -    public boolean contains(Class intf){
    +    public boolean contains(Class intf) {
             return classMap.containsKey(intf);
         }
     
    -    public String toString(){
    -        return getName()+"(version: "+getVersion()+")";
    +    public String toString() {
    +        return getName() + "(version: " + getVersion() + ")";
         }
     
     
    @@ -186,11 +186,11 @@ public class PluginData {
     
             @Override
             public boolean hasNext() {
    -            if(currentObj != null)
    +            if (currentObj != null)
                     return true;
    -            while (classIt.hasNext()){
    +            while (classIt.hasNext()) {
                     currentObj = (T)getObject(classIt.next());
    -                if(currentObj != null)
    +                if (currentObj != null)
                         return true;
                 }
                 return false;
    @@ -198,7 +198,7 @@ public class PluginData {
     
             @Override
             public T next() {
    -            if(!hasNext())
    +            if (!hasNext())
                     throw new NoSuchElementException();
                 T tmp = currentObj;
                 currentObj = null;
    diff --git a/src/zutil/plugin/PluginManager.java b/src/zutil/plugin/PluginManager.java
    index 6ab7583..8e967bb 100755
    --- a/src/zutil/plugin/PluginManager.java
    +++ b/src/zutil/plugin/PluginManager.java
    @@ -62,13 +62,13 @@ public class PluginManager implements Iterable{
         /**
          * Constructor that will look for plugins in the working directory.
          */
    -    public PluginManager(){
    +    public PluginManager() {
             this("./");
         }
         /**
          * Constructor that will look for plugins in the specified directory.
          */
    -    public PluginManager(String path){
    +    public PluginManager(String path) {
             plugins = new HashMap<>();
     
             FileSearcher search = new FileSearcher(new File(path));
    @@ -78,20 +78,20 @@ public class PluginManager implements Iterable{
             search.setFileName("plugin.json");
     
             log.fine("Searching for plugins...");
    -        for(FileSearcher.FileSearchItem file : search){
    +        for (FileSearcher.FileSearchItem file : search) {
                 try {
                     DataNode node = JSONParser.read(IOUtil.readContentAsString(file.getInputStream(), true));
                     log.fine("Found plugin: " + file.getPath());
                     PluginData plugin = new PluginData(node);
     
    -                if (!plugins.containsKey(plugin.getName())){
    +                if (!plugins.containsKey(plugin.getName())) {
                         plugins.put(plugin.getName(), plugin);
                     }
                     else {
                         double version = plugins.get(plugin.getName()).getVersion();
    -                    if(version < plugin.getVersion())
    +                    if (version < plugin.getVersion())
                             plugins.put(plugin.getName(), plugin);
    -                    else if(version == plugin.getVersion())
    +                    else if (version == plugin.getVersion())
                             log.fine("Ignoring duplicate plugin: " + plugin);
                         else
                             log.fine("Ignoring outdated plugin: " + plugin);
    @@ -157,7 +157,7 @@ public class PluginManager implements Iterable{
     
         private  List toList(Iterator it) {
             ArrayList list = new ArrayList<>();
    -        while(it.hasNext())
    +        while (it.hasNext())
                 list.add(it.next());
             return list;
         }
    @@ -198,7 +198,7 @@ public class PluginManager implements Iterable{
             @Override
             public PluginData next() {
                 nextIndex = getNextIndex();
    -            if(nextIndex < 0)
    +            if (nextIndex < 0)
                     throw new NoSuchElementException();
     
                 return pluginList.get(nextIndex++);
    @@ -211,21 +211,21 @@ public class PluginManager implements Iterable{
             private Iterator pluginIt;
             private Iterator> classIt;
     
    -        PluginClassIterator(Iterator it, Class intf){
    +        PluginClassIterator(Iterator it, Class intf) {
                 this.intf = intf;
                 this.pluginIt = it;
             }
     
             @Override
             public boolean hasNext() {
    -            if(pluginIt == null)
    +            if (pluginIt == null)
                     return false;
    -            if(classIt != null && classIt.hasNext())
    +            if (classIt != null && classIt.hasNext())
                     return true;
     
    -            while(pluginIt.hasNext()) {
    +            while (pluginIt.hasNext()) {
                     classIt = pluginIt.next().getClassIterator(intf);
    -                if(classIt.hasNext())
    +                if (classIt.hasNext())
                         return true;
                 }
                 classIt = null;
    @@ -234,7 +234,7 @@ public class PluginManager implements Iterable{
     
             @Override
             public Class next() {
    -            if(!hasNext())
    +            if (!hasNext())
                     throw new NoSuchElementException();
                 return (Class) classIt.next();
             }
    @@ -246,21 +246,21 @@ public class PluginManager implements Iterable{
             private Iterator pluginIt;
             private Iterator objectIt;
     
    -        PluginSingletonIterator(Iterator it, Class intf){
    +        PluginSingletonIterator(Iterator it, Class intf) {
                 this.intf = intf;
                 this.pluginIt = it;
             }
     
             @Override
             public boolean hasNext() {
    -            if(pluginIt == null)
    +            if (pluginIt == null)
                     return false;
    -            if(objectIt != null && objectIt.hasNext())
    +            if (objectIt != null && objectIt.hasNext())
                     return true;
     
    -            while(pluginIt.hasNext()) {
    +            while (pluginIt.hasNext()) {
                     objectIt = pluginIt.next().getObjectIterator(intf);
    -                if(objectIt.hasNext())
    +                if (objectIt.hasNext())
                         return true;
                 }
                 objectIt = null;
    @@ -269,7 +269,7 @@ public class PluginManager implements Iterable{
     
             @Override
             public T next() {
    -            if(!hasNext())
    +            if (!hasNext())
                     throw new NoSuchElementException();
                 return objectIt.next();
             }
    diff --git a/src/zutil/struct/BloomFilter.java b/src/zutil/struct/BloomFilter.java
    index 6b54765..5a92808 100644
    --- a/src/zutil/struct/BloomFilter.java
    +++ b/src/zutil/struct/BloomFilter.java
    @@ -53,7 +53,7 @@ public class BloomFilter implements Set, Serializable
          * @param	expected_data_count The estimated amount of data to
          * 			be inserted(a bigger number is better than a smaller)
          */
    -    public BloomFilter(int size, int expected_data_count){
    +    public BloomFilter(int size, int expected_data_count) {
             bits = new BitSet(size);
             k = (int)((size/expected_data_count) * Math.log(2));
             content_size = 0;
    @@ -68,7 +68,7 @@ public class BloomFilter implements Set, Serializable
             try {
                 content_size++;
                 int hash = 0;
    -            for(int i=0; i implements Set, Serializable
          * @return If the optimal size has been reached
          */
         public boolean addAll(Collection c) {
    -        for(T t : c){
    +        for (T t : c) {
                 add(t);
             }
             return isFull();
    @@ -106,12 +106,14 @@ public class BloomFilter implements Set, Serializable
          */
         public boolean contains(Object o) {
             try {
    -            if(!(o instanceof Serializable))return false;
    +            if (!(o instanceof Serializable))
    +                return false;
    +
                 int hash = 0;
    -            for(int i=0; i implements Set, Serializable
          * @param	c	The collection
          */
         public boolean containsAll(Collection c) {
    -        for(Object o : c){
    -            if(!contains(o)) return false;
    +        for (Object o : c) {
    +            if (!contains(o)) return false;
             }
             return true;
         }
    @@ -157,7 +159,7 @@ public class BloomFilter implements Set, Serializable
         /**
          * @return The false positive probability of the current state of the filter
          */
    -    public double falsePositiveProbability(){
    +    public double falsePositiveProbability() {
             return Math.pow(0.6185, bits.size()/content_size);
         }
     
    @@ -167,7 +169,7 @@ public class BloomFilter implements Set, Serializable
          *
          * @param	k	The hash count
          */
    -    public void setHashCount(int k){
    +    public void setHashCount(int k) {
             this.k = k;
         }
     
    diff --git a/src/zutil/struct/CircularBuffer.java b/src/zutil/struct/CircularBuffer.java
    index 8b11f1e..98f06f5 100755
    --- a/src/zutil/struct/CircularBuffer.java
    +++ b/src/zutil/struct/CircularBuffer.java
    @@ -44,28 +44,28 @@ public class CircularBuffer implements Iterable{
         /**
          * Initiates the buffer with a maximum size of maxSize.
          */
    -    public CircularBuffer(int maxSize){
    +    public CircularBuffer(int maxSize) {
             buffer = new Object[maxSize];
             buffSize = 0;
             buffPos  = 0;
         }
     
    -    public void add(T obj){
    -        if(buffPos+1 >= buffer.length)
    +    public void add(T obj) {
    +        if (buffPos+1 >= buffer.length)
                 buffPos = 0;
             else
                 ++buffPos;
    -        if(buffSize < buffer.length)
    +        if (buffSize < buffer.length)
                 ++buffSize;
             buffer[buffPos] = obj;
             ++addCount;
         }
     
         public T get(int index) {
    -        if(index >= buffSize)
    -            throw new IndexOutOfBoundsException("Index "+ index +" is larger than actual buffer size "+ buffSize);
    +        if (index >= buffSize)
    +            throw new IndexOutOfBoundsException("Index " + index + " is larger than actual buffer size " + buffSize);
             int buffIndex = buffPos - index;
    -        if(buffIndex < 0)
    +        if (buffIndex < 0)
                 buffIndex = buffer.length - Math.abs(buffIndex);
             return (T)buffer[buffIndex];
         }
    @@ -97,7 +97,7 @@ public class CircularBuffer implements Iterable{
     
             @Override
             public T next() {
    -            if(iteratorPos >= buffSize)
    +            if (iteratorPos >= buffSize)
                     throw new NoSuchElementException();
                 return get(iteratorPos++);
             }
    diff --git a/src/zutil/struct/HistoryList.java b/src/zutil/struct/HistoryList.java
    index 9b92769..3403bc4 100644
    --- a/src/zutil/struct/HistoryList.java
    +++ b/src/zutil/struct/HistoryList.java
    @@ -36,8 +36,8 @@ public class HistoryList implements Iterable{
         /**
          * Creates an HistoryList object
          */
    -    public HistoryList(){
    -        this( Integer.MAX_VALUE );
    +    public HistoryList() {
    +        this(Integer.MAX_VALUE);
         }
     
         /**
    @@ -45,7 +45,7 @@ public class HistoryList implements Iterable{
          *
          * @param histLength the maximum size of the list
          */
    -    public HistoryList(int histLength){
    +    public HistoryList(int histLength) {
             history_length = histLength;
             history = new LinkedList<>();
         }
    @@ -56,8 +56,8 @@ public class HistoryList implements Iterable{
          * @param i is the index
          * @return item in that index
          */
    -    public T get(int i){
    -        return history.get( i );
    +    public T get(int i) {
    +        return history.get(i);
         }
     
         /**
    @@ -66,12 +66,12 @@ public class HistoryList implements Iterable{
          *
          * @param item is the item to add
          */
    -    public void add(T item){
    -        while (historyIndex < history.size()-1){
    +    public void add(T item) {
    +        while (historyIndex < history.size()-1) {
                 history.removeLast();
             }
             history.addLast(item);
    -        if (history_length < history.size()){
    +        if (history_length < history.size()) {
                 history.removeFirst();
             }
     
    @@ -81,7 +81,7 @@ public class HistoryList implements Iterable{
         /**
          * @return the previous item in the list
          */
    -    public T getPrevious(){
    +    public T getPrevious() {
             if (historyIndex > 0)
                 historyIndex -= 1;
             else
    @@ -92,24 +92,24 @@ public class HistoryList implements Iterable{
         /**
          * @return the next item in the list
          */
    -    public T getNext(){
    -        if (next()){
    +    public T getNext() {
    +        if (next()) {
                 historyIndex += 1;
             }
    -        else{
    +        else {
                 historyIndex = history.size()-1;
             }
             return history.get(historyIndex);
         }
     
    -    public T getCurrent(){
    +    public T getCurrent() {
             return history.get(historyIndex);
         }
     
         /**
          * @return if there are items newer than the current
          */
    -    public boolean next(){
    +    public boolean next() {
             if (historyIndex < history.size()-1)
                 return true;
             return false;
    @@ -118,7 +118,7 @@ public class HistoryList implements Iterable{
         /**
          * @return an iterator of the list
          */
    -    public Iterator iterator(){
    +    public Iterator iterator() {
             return history.iterator();
         }
     }
    diff --git a/src/zutil/struct/MultiMap.java b/src/zutil/struct/MultiMap.java
    index 81d7825..3c79759 100644
    --- a/src/zutil/struct/MultiMap.java
    +++ b/src/zutil/struct/MultiMap.java
    @@ -77,7 +77,7 @@ public class MultiMap implements Map {
         @Override
         public boolean containsValue(Object value) {
             for (K key : internalMap.keySet()) {
    -            for (V keyValue : internalMap.get(key)){
    +            for (V keyValue : internalMap.get(key)) {
                     if (Objects.equals(value, keyValue))
                         return true;
                 }
    @@ -111,7 +111,7 @@ public class MultiMap implements Map {
         public void putAll(Map m) {
             if (m instanceof MultiMap) {
                 for (K key : m.keySet()) {
    -                for (V value : ((MultiMap) m).getAll(key)){
    +                for (V value : ((MultiMap) m).getAll(key)) {
                         put(key, value);
                     }
                 }
    @@ -173,7 +173,7 @@ public class MultiMap implements Map {
         public Collection values() {
             LinkedList list = new LinkedList<>();
     
    -        for(List valueList : internalMap.values()) {
    +        for (List valueList : internalMap.values()) {
                 list.addAll(valueList);
             }
     
    diff --git a/src/zutil/struct/MutableInt.java b/src/zutil/struct/MutableInt.java
    index 5b27001..63497b2 100644
    --- a/src/zutil/struct/MutableInt.java
    +++ b/src/zutil/struct/MutableInt.java
    @@ -27,15 +27,15 @@ package zutil.struct;
     /**
      * A simple class that only contains a public int. Can be used in
      * recursive functions as a persistent integer.
    - *  
    + *
      * @author Ziver
      */
     public class MutableInt {
         public int i = 0;
     
    -    public MutableInt(){}
    +    public MutableInt() {}
     
    -    public MutableInt(int i){
    +    public MutableInt(int i) {
             this.i = i;
         }
     }
    diff --git a/src/zutil/struct/ObjectCache.java b/src/zutil/struct/ObjectCache.java
    index 44da0e9..7c779ec 100755
    --- a/src/zutil/struct/ObjectCache.java
    +++ b/src/zutil/struct/ObjectCache.java
    @@ -33,7 +33,7 @@ import java.util.Map;
     
     /**
      * This is a Object cache where objects can be stored with {@link java.lang.ref.WeakReference} and a time limit.
    - * 
    + *
      * Created by Ziver on 2016-07-29.
      */
     public class ObjectCache {
    @@ -47,7 +47,7 @@ public class ObjectCache {
         private long ttl;
     
     
    -    public ObjectCache(long ttl){
    +    public ObjectCache(long ttl) {
             this.ttl = ttl;
         }
     
    @@ -55,7 +55,7 @@ public class ObjectCache {
         /**
          * Stores a key and value pair in the cache.
          */
    -    public void put(K key, V value){
    +    public void put(K key, V value) {
             CacheEntry entry = new CacheEntry<>();
             entry.timer = new Timer(ttl).start();
             entry.value = new WeakReference<>(value);
    @@ -67,8 +67,8 @@ public class ObjectCache {
          * Checks if the specific key is available in
          * the cache and that it is valid.
          */
    -    public boolean containsKey(Object key){
    -        if(cache.containsKey(key)){
    +    public boolean containsKey(Object key) {
    +        if (cache.containsKey(key)) {
                 CacheEntry entry = cache.get(key);
                 if (entry.timer.hasTimedOut() || entry.value.get() == null) // entry to old or not valid
                     cache.remove(key);
    @@ -79,7 +79,7 @@ public class ObjectCache {
         }
     
     
    -    public V get(Object key){
    +    public V get(Object key) {
             if (containsKey(key))
                 return cache.get(key).value.get();
             return null;
    @@ -101,9 +101,9 @@ public class ObjectCache {
          *
          * @return the number of objects removed from the Set
          */
    -    public int garbageCollect(){
    +    public int garbageCollect() {
             int count = 0;
    -        for(Iterator>> it = cache.entrySet().iterator(); it.hasNext(); ) {
    +        for (Iterator>> it = cache.entrySet().iterator(); it.hasNext();) {
                 Map.Entry> mapEntry = it.next();
                 if (mapEntry.getValue().timer.hasTimedOut() || mapEntry.getValue().value.get() == null) { // entry to old or not valid
                     it.remove();
    diff --git a/src/zutil/struct/TimedHashSet.java b/src/zutil/struct/TimedHashSet.java
    index c657bc6..6d61da6 100755
    --- a/src/zutil/struct/TimedHashSet.java
    +++ b/src/zutil/struct/TimedHashSet.java
    @@ -41,7 +41,7 @@ public class TimedHashSet {
         /**
          * @param   ttl     milliseconds the entries will live
          */
    -    public TimedHashSet(long ttl){
    +    public TimedHashSet(long ttl) {
             this.ttl = ttl;
             this.map = new HashMap<>();
         }
    @@ -50,13 +50,13 @@ public class TimedHashSet {
         /**
          * @return true if the object already existed in the set which will reset the TTL.
          */
    -    public boolean add(T o){
    +    public boolean add(T o) {
             return map.put(o, new Timer(ttl).start()) != null;
         }
     
    -    public boolean contains(Object o){
    -        if(map.containsKey(o)){
    -            if(map.get(o).hasTimedOut()) // entry to old
    +    public boolean contains(Object o) {
    +        if (map.containsKey(o)) {
    +            if (map.get(o).hasTimedOut()) // entry to old
                     map.remove(o);
                 else
                     return true;
    @@ -78,9 +78,9 @@ public class TimedHashSet {
          *
          * @return the number of objects removed from the Set
          */
    -    public int garbageCollect(){
    +    public int garbageCollect() {
             int count = 0;
    -        for(Iterator> it = map.entrySet().iterator(); it.hasNext(); ) {
    +        for (Iterator> it = map.entrySet().iterator(); it.hasNext();) {
                 Map.Entry entry = it.next();
                 if (entry.getValue().hasTimedOut()) { // entry to old
                     it.remove();
    diff --git a/src/zutil/ui/Configurator.java b/src/zutil/ui/Configurator.java
    index a1bbaca..392df23 100755
    --- a/src/zutil/ui/Configurator.java
    +++ b/src/zutil/ui/Configurator.java
    @@ -87,29 +87,29 @@ public class Configurator {
         private PostConfigurationActionListener postListener;
     
     
    -    public Configurator(T obj){
    +    public Configurator(T obj) {
             this.obj = obj;
             this.params = getConfiguration(obj.getClass(), obj);
         }
     
     
    -    public T getObject(){
    +    public T getObject() {
             return obj;
         }
     
    -    public ConfigurationParam[] getConfiguration(){
    +    public ConfigurationParam[] getConfiguration() {
             return params;
         }
     
    -    public static ConfigurationParam[] getConfiguration(Class c){
    -        if(!classConf.containsKey(c))
    +    public static ConfigurationParam[] getConfiguration(Class c) {
    +        if (!classConf.containsKey(c))
                 classConf.put(c, getConfiguration(c, null));
             return classConf.get(c);
         }
    -    protected static ConfigurationParam[] getConfiguration(Class c, Object obj){
    +    protected static ConfigurationParam[] getConfiguration(Class c, Object obj) {
             ArrayList conf = new ArrayList<>();
     
    -        for(Class cc = c; cc != Object.class ;cc = cc.getSuperclass()) { // iterate through all super classes
    +        for (Class cc = c; cc != Object.class; cc = cc.getSuperclass()) { // iterate through all super classes
                 for (Field f : cc.getDeclaredFields()) {
                     if (f.isAnnotationPresent(Configurable.class)) {
                         try {
    @@ -131,9 +131,9 @@ public class Configurator {
          *
          * @return a reference to itself so that method calls can be chained.
          */
    -    public Configurator setValues(Map parameters){
    -        for(ConfigurationParam param : this.params){
    -            if(parameters.containsKey(param.getName()))
    +    public Configurator setValues(Map parameters) {
    +        for (ConfigurationParam param : this.params) {
    +            if (parameters.containsKey(param.getName()))
                     param.setValue(parameters.get(param.getName()));
             }
             return this;
    @@ -145,19 +145,20 @@ public class Configurator {
          *
          * @return a reference to itself so that method calls can be chained.
          */
    -    public Configurator setValues(DataNode node){
    -        if(!node.isMap())
    +    public Configurator setValues(DataNode node) {
    +        if (!node.isMap())
                 return this;
    -        for(ConfigurationParam param : this.params){
    -            if(node.get(param.getName()) != null)
    +
    +        for (ConfigurationParam param : this.params) {
    +            if (node.get(param.getName()) != null)
                     param.setValue(node.getString(param.getName()));
             }
             return this;
         }
     
    -    public DataNode getValuesAsNode(){
    +    public DataNode getValuesAsNode() {
             DataNode node = new DataNode(DataNode.DataType.Map);
    -        for(ConfigurationParam param : this.params){
    +        for (ConfigurationParam param : this.params) {
                 node.set(param.getName(), param.getString());
             }
             return node;
    @@ -167,14 +168,14 @@ public class Configurator {
         /**
          * Set a listener that will be called just before the configuration has been applied
          */
    -    public void setPreConfigurationListener(PreConfigurationActionListener listener){
    +    public void setPreConfigurationListener(PreConfigurationActionListener listener) {
             preListener = listener;
         }
     
         /**
          * Set a listener that will be called after the configuration has been applied
          */
    -    public void setPostConfigurationListener(PostConfigurationActionListener listener){
    +    public void setPostConfigurationListener(PostConfigurationActionListener listener) {
             postListener = listener;
         }
     
    @@ -187,21 +188,21 @@ public class Configurator {
          * The postConfigurationAction() method will be called after the target object is
          * configured if it implements the PostConfigurationActionListener interface.
          */
    -    public void applyConfiguration(){
    -        if(preListener != null)
    +    public void applyConfiguration() {
    +        if (preListener != null)
                 preListener.preConfigurationAction(this, obj);
    -        if(obj instanceof PreConfigurationActionListener)
    +        if (obj instanceof PreConfigurationActionListener)
                 ((PreConfigurationActionListener) obj).preConfigurationAction(this, obj);
     
             StringBuilder strParams = new StringBuilder();
    -        for(ConfigurationParam param : params){
    +        for (ConfigurationParam param : params) {
                 try {
                     param.apply(obj);
     
                     // Logging
    -                if(logger.isLoggable(Level.FINE)) {
    +                if (logger.isLoggable(Level.FINE)) {
                         strParams.append(param.getName()).append(": ");
    -                    if(param.isTypeString())
    +                    if (param.isTypeString())
                             strParams.append("'").append(param.getString()).append("'");
                         else
                             strParams.append(param.getString());
    @@ -211,12 +212,12 @@ public class Configurator {
                     logger.log(Level.WARNING, null, e);
                 }
             }
    -        if(logger.isLoggable(Level.FINE))
    -            logger.fine("Configured object: " + obj.getClass().getName() + " ("+ strParams +")");
    +        if (logger.isLoggable(Level.FINE))
    +            logger.fine("Configured object: " + obj.getClass().getName() + " (" + strParams + ")");
     
    -        if(obj instanceof PostConfigurationActionListener)
    +        if (obj instanceof PostConfigurationActionListener)
                 ((PostConfigurationActionListener) obj).postConfigurationAction(this, obj);
    -        if(postListener != null)
    +        if (postListener != null)
                 postListener.postConfigurationAction(this, obj);
         }
     
    @@ -242,42 +243,42 @@ public class Configurator {
                 field = f;
                 field.setAccessible(true);
                 name = field.getName();
    -            if(obj != null)
    +            if (obj != null)
                     value = field.get(obj);
    -            if(field.isAnnotationPresent(Configurable.class)) {
    +            if (field.isAnnotationPresent(Configurable.class)) {
                     niceName = field.getAnnotation(Configurable.class).value();
                     order = field.getAnnotation(Configurable.class).order();
                 }
    -            else{
    +            else {
                     niceName = name;
                     order = Integer.MAX_VALUE;
                 }
     
    -            if     (f.getType() == String.class)    type = ConfigType.STRING;
    -            else if(f.getType() == int.class)       type = ConfigType.INT;
    -            else if(f.getType() == double.class)    type = ConfigType.INT;
    -            else if(f.getType() == boolean.class)   type = ConfigType.BOOLEAN;
    -            else if(f.getType().isEnum())           type = ConfigType.ENUM;
    +            if      (f.getType() == String.class)    type = ConfigType.STRING;
    +            else if (f.getType() == int.class)       type = ConfigType.INT;
    +            else if (f.getType() == double.class)    type = ConfigType.INT;
    +            else if (f.getType() == boolean.class)   type = ConfigType.BOOLEAN;
    +            else if (f.getType().isEnum())           type = ConfigType.ENUM;
                 else
    -                throw new IllegalArgumentException(f.getType()+" is not a supported configurable type");
    +                throw new IllegalArgumentException(f.getType() + " is not a supported configurable type");
     
             }
     
    -        public String getName(){       return name;}
    -        public String getNiceName(){   return niceName;}
    -        public ConfigType getType(){   return type;}
    -        public boolean isTypeString(){ return type == ConfigType.STRING;}
    -        public boolean isTypeInt(){    return type == ConfigType.INT;}
    -        public boolean isTypeBoolean(){return type == ConfigType.BOOLEAN;}
    -        public boolean isTypeEnum(){   return type == ConfigType.ENUM;}
    +        public String getName() {       return name;}
    +        public String getNiceName() {   return niceName;}
    +        public ConfigType getType() {   return type;}
    +        public boolean isTypeString() { return type == ConfigType.STRING;}
    +        public boolean isTypeInt() {    return type == ConfigType.INT;}
    +        public boolean isTypeBoolean() {return type == ConfigType.BOOLEAN;}
    +        public boolean isTypeEnum() {   return type == ConfigType.ENUM;}
     
    -        public String getString(){
    -            if(value == null)
    +        public String getString() {
    +            if (value == null)
                     return null;
                 return value.toString();
             }
    -        public boolean getBoolean(){
    -            if(value == null || type != ConfigType.BOOLEAN)
    +        public boolean getBoolean() {
    +            if (value == null || type != ConfigType.BOOLEAN)
                     return false;
                 return (boolean)value;
             }
    @@ -285,7 +286,7 @@ public class Configurator {
             /**
              * @return a String array with all enum possibilities or empty array if the type is not an enum
              */
    -        public String[] getPossibleValues(){
    +        public String[] getPossibleValues() {
                 if (type == ConfigType.ENUM) {
                     Object[] constants = field.getType().getEnumConstants();
                     String[] values = new String[constants.length];
    @@ -301,8 +302,8 @@ public class Configurator {
              * to apply the change to the source object the method
              * {@link #applyConfiguration()} needs to be called
              */
    -        public void setValue(String v){
    -            switch(type){
    +        public void setValue(String v) {
    +            switch(type) {
                     case STRING:
                         value = v; break;
                     case INT:
    @@ -319,7 +320,7 @@ public class Configurator {
             }
     
             protected void apply(Object obj) throws IllegalAccessException {
    -            if(obj != null)
    +            if (obj != null)
                     field.set(obj, value);
             }
     
    diff --git a/src/zutil/ui/Console.java b/src/zutil/ui/Console.java
    index 810fd2e..64077b9 100644
    --- a/src/zutil/ui/Console.java
    +++ b/src/zutil/ui/Console.java
    @@ -53,15 +53,15 @@ public class Console{
         private TrayIcon trayIcon;
         private int bufferSize;
     
    -    public Console(String title){
    +    public Console(String title) {
             this(title, 680, 340, 50000, false);
         }
     
    -    public Console(String title, boolean tray){
    +    public Console(String title, boolean tray) {
             this(title, 680, 340, 50000, tray);
         }
     
    -    public Console(String title, int width, int height, int buffer, boolean tray){
    +    public Console(String title, int width, int height, int buffer, boolean tray) {
             ConsoleInputStream in = new ConsoleInputStream();
             DEFAULT_ICON = FileUtil.find(DEFAULT_ICON).getAbsolutePath();
             initUI(title, in);
    @@ -80,7 +80,7 @@ public class Console{
         /**
          * initiates the ui
          */
    -    private void initUI(String title, KeyListener listener){
    +    private void initUI(String title, KeyListener listener) {
             frame = new JFrame(title);
     
             console = new JTextPane();
    @@ -99,14 +99,14 @@ public class Console{
             frame.add(scroll, BorderLayout.CENTER);
         }
     
    -    public void setIcon(){
    +    public void setIcon() {
     
         }
     
    -    public void appendConsole(String s, Style style){
    +    public void appendConsole(String s, Style style) {
             try {
                 doc.insertString(doc.getLength(), s, style);
    -            if(doc.getLength() > bufferSize){
    +            if (doc.getLength() > bufferSize) {
                     doc.remove(0, doc.getLength() - bufferSize);
                 }
             } catch (BadLocationException e) {
    @@ -118,7 +118,7 @@ public class Console{
          * Enables the tray icon and sets the icon
          * @param img The image to use as the icon
          */
    -    public void setTrayIcon(Image img){
    +    public void setTrayIcon(Image img) {
             enableTray(true);
             trayIcon.setImage(img);
         }
    @@ -128,7 +128,7 @@ public class Console{
          *
          * @param img The image to use as a icon
          */
    -    public void setFrameIcon(Image img){
    +    public void setFrameIcon(Image img) {
             frame.setIconImage(img);
         }
     
    @@ -137,12 +137,12 @@ public class Console{
          *
          * @param 	enable	if tray icon is enabled
          */
    -    public void enableTray(boolean enable){
    -        if(enable && SystemTray.isSupported()){
    +    public void enableTray(boolean enable) {
    +        if (enable && SystemTray.isSupported()) {
                 frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
                 SystemTray tray = SystemTray.getSystemTray();
     
    -            if(trayIcon == null){
    +            if (trayIcon == null) {
                     // Menu
                     PopupMenu menu = new PopupMenu();
                     MenuItem item = new MenuItem("Open");
    @@ -166,9 +166,9 @@ public class Console{
                             Toolkit.getDefaultToolkit().getImage(DEFAULT_ICON),
                             "Console", menu);
                     trayIcon.setImageAutoSize(true);
    -                trayIcon.addMouseListener(new MouseListener(){
    +                trayIcon.addMouseListener(new MouseListener() {
                         public void mouseClicked(MouseEvent e) {
    -                        if(e.getClickCount() == 2)
    +                        if (e.getClickCount() == 2)
                                 frame.setVisible(true);
                         }
                         public void mouseEntered(MouseEvent e) {}
    @@ -184,7 +184,7 @@ public class Console{
                     System.err.println("TrayIcon could not be added.");
                 }
             }
    -        else{
    +        else {
                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 SystemTray.getSystemTray().remove(trayIcon);
             }
    @@ -216,39 +216,39 @@ public class Console{
                 trayMessageType = type;
             }
     
    -        public void print(String s){
    +        public void print(String s) {
                 appendConsole(s, style);
                 console.setCaretPosition(console.getDocument().getLength());
    -            if(trayMessageType != null && trayIcon != null){
    +            if (trayMessageType != null && trayIcon != null) {
                     trayIcon.displayMessage(
    -                        s.substring(0, (s.length() > 25 ? 25 : s.length()))+"...",
    +                        s.substring(0, (s.length() > 25 ? 25 : s.length())) + "...",
                             s, trayMessageType);
     
                 }
             }
     
    -        public void println(String s){
    -            print(s+"\n");
    +        public void println(String s) {
    +            print(s + "\n");
             }
     
    -        public void println(){			println("");}
    -        public void println(boolean x){	println(""+x);}
    -        public void println(char x){	println(""+x);}
    -        public void println(char[] x){	println(new String(x));}
    -        public void println(double x){	println(""+x);}
    -        public void println(float x){	println(""+x);}
    -        public void println(int x){		println(""+x);}
    -        public void println(long x){	println(""+x);}
    -        public void println(Object x){	println(""+x);}
    +        public void println() {			 println("");}
    +        public void println(boolean x) { println("" +x);}
    +        public void println(char x) {	 println("" +x);}
    +        public void println(char[] x) {	 println(new String(x));}
    +        public void println(double x) {	 println("" +x);}
    +        public void println(float x) {	 println("" +x);}
    +        public void println(int x) {     println("" +x);}
    +        public void println(long x) {	 println("" +x);}
    +        public void println(Object x) {	 println("" +x);}
     
    -        public void print(boolean x){	print(""+x);}
    -        public void print(char x){		print(""+x);}
    -        public void print(char[] x){	print(new String(x));}
    -        public void print(double x){	print(""+x);}
    -        public void print(float x){		print(""+x);}
    -        public void print(int x){		print(""+x);}
    -        public void print(long x){		print(""+x);}
    -        public void print(Object x){	print(""+x);}
    +        public void print(boolean x) {   print("" +x);}
    +        public void print(char x) {	     print("" +x);}
    +        public void print(char[] x) {    print(new String(x));}
    +        public void print(double x) {    print("" +x);}
    +        public void print(float x) {     print("" +x);}
    +        public void print(int x) {       print("" +x);}
    +        public void print(long x) {      print("" +x);}
    +        public void print(Object x) {     print("" +x);}
         }
     
         private class ConsoleInputStream extends InputStream implements KeyListener{
    @@ -257,20 +257,20 @@ public class Console{
     
             @Override
             public int read() {
    -            if(input < 0) {
    +            if (input < 0) {
                     input = 0;
                     return -1;
                 }
     
                 read = true;
                 input = 0;
    -            while(input == 0){
    +            while (input == 0) {
                     try {Thread.sleep(10);} catch (InterruptedException e) {}
                 }
                 read = false;
     
                 System.out.print((char)input);
    -            if(input == KeyEvent.VK_ENTER){
    +            if (input == KeyEvent.VK_ENTER) {
                     input = -1;
                     return '\n';
                 }
    @@ -284,11 +284,11 @@ public class Console{
     
             @Override
             public int read(byte[] b, int off, int len) throws IOException {
    -            System.out.println(off+"-"+len);
    +            System.out.println(off + "-" + len);
                 int i;
    -            for(i=-1; i() {
                 @Override
                 public int compare(Navigation o1, Navigation o2) {
    @@ -99,8 +99,8 @@ public class Navigation implements Iterable{
          * Returns null if no navigation object found.
          */
         private Navigation getSubNav(String id, String name) {
    -        for(Navigation nav : subNav) {
    -            if(nav.equals(id) || nav.equals(name))
    +        for (Navigation nav : subNav) {
    +            if (nav.equals(id) || nav.equals(name))
                     return nav;
             }
             return null;
    @@ -113,23 +113,23 @@ public class Navigation implements Iterable{
     
     
     
    -    public String getName(){
    +    public String getName() {
             return name;
         }
    -    public Object getResource(){
    +    public Object getResource() {
             return resource;
         }
     
     
     
    -    private void setParentNav(Navigation nav){
    +    private void setParentNav(Navigation nav) {
             this.parentNav = nav;
         }
         /**
          * Assign a resource object specific to this navigation object.
          * This can be used if target page needs some additional information.
          */
    -    public Navigation setResource(Object obj){
    +    public Navigation setResource(Object obj) {
             resource = obj;
             return this;
         }
    @@ -138,9 +138,9 @@ public class Navigation implements Iterable{
          * used for deciding the order the parent will sort all sub navigation.
          * Lower values will be at the top of sub-nav list.
          */
    -    public Navigation setWeight(int weightOrder){
    +    public Navigation setWeight(int weightOrder) {
             this.weight = weightOrder;
    -        if(parentNav != null)
    +        if (parentNav != null)
                 parentNav.sortSubNavs();
             return this;
         }
    @@ -148,8 +148,8 @@ public class Navigation implements Iterable{
     
     
         @Override
    -    public boolean equals(Object o){
    -        if(o instanceof String)
    +    public boolean equals(Object o) {
    +        if (o instanceof String)
                 return this.name.equals(o);
             return this == o || o != null && Objects.equals(this.id, ((Navigation) o).id);
         }
    @@ -157,7 +157,7 @@ public class Navigation implements Iterable{
     
     
     
    -    public static Navigation createRootNav(){
    +    public static Navigation createRootNav() {
             return new Navigation(null, null);
         }
         public static Navigation getRootNav(Map request) {
    @@ -172,13 +172,13 @@ public class Navigation implements Iterable{
         /**
          * Will create a clone of the navigation tree with some request instance specific information
          */
    -    public NavInstance createParameterizedNavInstance(Map request){
    +    public NavInstance createParameterizedNavInstance(Map request) {
             Navigation nav = getParameterizedNavigation(request);
             if (nav != null)
                 return createParameterizedNavInstance(getBreadcrumb(nav));
             return createParameterizedNavInstance(Collections.EMPTY_LIST);
         }
    -    private NavInstance createParameterizedNavInstance(List activeList){
    +    private NavInstance createParameterizedNavInstance(List activeList) {
             NavInstance instance = new ParameterizedNavInstance(this);
             instance.setActive(activeList.contains(this));
             for (Navigation nav : subNav)
    @@ -189,20 +189,20 @@ public class Navigation implements Iterable{
          * @return the specific Navigation object requested by client
          */
         public static Navigation getParameterizedNavigation(Map request) {
    -        if(request.containsKey(NAVIGATION_URL_KEY))
    +        if (request.containsKey(NAVIGATION_URL_KEY))
                 return navMap.get(request.get(NAVIGATION_URL_KEY));
             return null;
         }
     
     
     
    -    public NavInstance createPagedNavInstance(HttpHeader header){
    +    public NavInstance createPagedNavInstance(HttpHeader header) {
             Navigation nav = getPagedNavigation(header);
             if (nav != null)
                 return createPagedNavInstance(getBreadcrumb(nav));
             return createPagedNavInstance(Collections.EMPTY_LIST);
         }
    -    private NavInstance createPagedNavInstance(List activeList){
    +    private NavInstance createPagedNavInstance(List activeList) {
             NavInstance instance = new PagedNavInstance(this);
             instance.setActive(activeList.contains(this));
             for (Navigation nav : subNav)
    @@ -226,8 +226,8 @@ public class Navigation implements Iterable{
          */
         public static List getBreadcrumb(Navigation nav) {
             LinkedList list = new LinkedList();
    -        if (nav != null){
    -            while(nav != null){
    +        if (nav != null) {
    +            while (nav != null) {
                     list.addFirst(nav);
                     nav = nav.parentNav;
                 }
    @@ -243,31 +243,31 @@ public class Navigation implements Iterable{
             protected boolean active;
             protected ArrayList subNavInstance;
     
    -        protected NavInstance(Navigation nav){
    +        protected NavInstance(Navigation nav) {
                 this.nav = nav;
                 this.subNavInstance = new ArrayList<>();
             }
     
    -        protected void setActive(boolean active){
    +        protected void setActive(boolean active) {
                 this.active = active;
             }
    -        protected void addSubNav(NavInstance subNav){
    +        protected void addSubNav(NavInstance subNav) {
                 subNavInstance.add(subNav);
             }
     
    -        public boolean isActive(){
    +        public boolean isActive() {
                 return active;
             }
             public List getSubNavs() { return subNavInstance; }
     
             // Mirror getters from Navigation
    -        public String getName(){                 return nav.getName(); }
    -        public Object getResource(){             return nav.getResource(); }
    +        public String getName() {                 return nav.getName(); }
    +        public Object getResource() {             return nav.getResource(); }
     
             public abstract String getURL();
     
     
    -        public boolean equals(Object o){
    +        public boolean equals(Object o) {
                 if (o instanceof Navigation)
                     return nav.equals(o);
                 else if (o instanceof NavInstance)
    @@ -279,15 +279,15 @@ public class Navigation implements Iterable{
         public static class ParameterizedNavInstance extends NavInstance{
             protected ParameterizedNavInstance(Navigation nav) { super(nav); }
     
    -        public String getURL(){
    -            return "?"+NAVIGATION_URL_KEY+"="+nav.id;
    +        public String getURL() {
    +            return "?" + NAVIGATION_URL_KEY + "=" + nav.id;
             }
         }
     
         public static class PagedNavInstance extends NavInstance{
             protected PagedNavInstance(Navigation nav) { super(nav); }
     
    -        public String getURL(){
    +        public String getURL() {
                 return "/" + nav.id;
             }
         }
    diff --git a/src/zutil/ui/UserMessageManager.java b/src/zutil/ui/UserMessageManager.java
    index 64deeb8..487d7b5 100644
    --- a/src/zutil/ui/UserMessageManager.java
    +++ b/src/zutil/ui/UserMessageManager.java
    @@ -43,7 +43,7 @@ public class UserMessageManager implements Iterable getMessages() {
             List messagesClone = new ArrayList<>(messages.size());
    -        for (Iterator it = messages.iterator(); it.hasNext(); ) {
    +        for (Iterator it = messages.iterator(); it.hasNext();) {
                 UserMessage alert = it.next();
                 if (alert.ttl <= 0) { // if alert is to old, remove it
                     logger.fine("Message dismissed with end of life, alert id: " + alert.id);
    diff --git a/src/zutil/ui/configurator.dynamic.tmpl b/src/zutil/ui/configurator.dynamic.tmpl
    index d30499c..ade94f8 100755
    --- a/src/zutil/ui/configurator.dynamic.tmpl
    +++ b/src/zutil/ui/configurator.dynamic.tmpl
    @@ -29,7 +29,7 @@
                 selector.change(); // Update dynamic inputs
                 // set dynamic form data
                 $.each(button.attr(), function(fieldName, value) {
    -                if(fieldName.startsWith("data-")) {
    +                if (fieldName.startsWith("data-")) {
                         fieldName = fieldName.substring(5);
                         // case insensitive search
                         input = modal.find("input").filter(function() {
    diff --git a/src/zutil/ui/wizard/Wizard.java b/src/zutil/ui/wizard/Wizard.java
    index db9ce5e..9d5fda1 100644
    --- a/src/zutil/ui/wizard/Wizard.java
    +++ b/src/zutil/ui/wizard/Wizard.java
    @@ -66,14 +66,14 @@ public class Wizard implements ActionListener{
         private ValidationFail oldFail;
     
     
    -    private Wizard(WizardListener listener){
    +    private Wizard(WizardListener listener) {
             this(listener, null);
         }
     
         /**
          * Creates a new Wizard
          */
    -    public Wizard(WizardListener listener, WizardPage start){
    +    public Wizard(WizardListener listener, WizardPage start) {
             this(listener, start, BACKGROUND_1);
         }
     
    @@ -83,30 +83,30 @@ public class Wizard implements ActionListener{
          * @param start is the first page in the wizard
          * @param bg is the background image to use
          */
    -    public Wizard(WizardListener listener, final WizardPage start, final String bg){
    +    public Wizard(WizardListener listener, final WizardPage start, final String bg) {
             try {
                 this.listener = listener;
                 pages = new HistoryList<>();
                 values = new HashMap<>();
    -            handler = new WizardActionHandler( values );
    +            handler = new WizardActionHandler(values);
     
                 // GUI
                 frame = new JFrame();
                 initComponents();
    -            sidebar.scale( false );
    +            sidebar.scale(false);
     
                 // add action listener to the buttons
    -            back.addActionListener( this );
    -            next.addActionListener( this );
    -            cancel.addActionListener( this );
    -            finish.addActionListener( this );
    +            back.addActionListener(this);
    +            next.addActionListener(this);
    +            cancel.addActionListener(this);
    +            finish.addActionListener(this);
     
                 // Set the image in the sidebar
    -            sidebar.setImage(ImageIO.read( FileUtil.getInputStream( bg ) ));
    +            sidebar.setImage(ImageIO.read(FileUtil.getInputStream(bg)));
     
                 // add the first page
    -            pages.add( start );
    -            displayWizardPage( start );
    +            pages.add(start);
    +            displayWizardPage(start);
     
             } catch (Exception e) {
                 e.printStackTrace(MultiPrintStream.out);
    @@ -116,7 +116,7 @@ public class Wizard implements ActionListener{
         /**
          * Sets the title of the Wizard
          */
    -    public void setTitle(String s){
    +    public void setTitle(String s) {
             frame.setTitle(s);
         }
     
    @@ -126,21 +126,21 @@ public class Wizard implements ActionListener{
          * @param w is the width
          * @param h is the height
          */
    -    public void setSize(int w, int h){
    +    public void setSize(int w, int h) {
             frame.setSize(w, h);
         }
     
         /**
          * Displays the wizard
          */
    -    public void start(){
    +    public void start() {
             frame.setVisible(true);
         }
     
         /**
          * @return the JFrame used for the wizard
          */
    -    public JFrame getFrame(){
    +    public JFrame getFrame() {
             return frame;
         }
     
    @@ -149,58 +149,60 @@ public class Wizard implements ActionListener{
          *
          * @param page is the page to be displayed
          */
    -    protected void displayWizardPage(WizardPage page){
    +    protected void displayWizardPage(WizardPage page) {
             pageContainer.getViewport().setView(page);
    -        pageTitle.setText( page.getPageDescription() );
    +        pageTitle.setText(page.getPageDescription());
         }
     
         public void actionPerformed(ActionEvent e) {
             // Back Button
    -        if(e.getSource() == back){
    +        if (e.getSource() == back) {
                 WizardPage page = pages.getPrevious();
    -            displayWizardPage( page );
    -            if(pages.get(0) == page){
    -                back.setEnabled( false );
    +            displayWizardPage(page);
    +            if (pages.get(0) == page) {
    +                back.setEnabled(false);
                 }
             }
             // Next Button and Finish Button
    -        else if(e.getSource() == next || e.getSource() == finish){
    +        else if (e.getSource() == next || e.getSource() == finish) {
                 WizardPage page = pages.getCurrent();
    -            page.registerValues( handler );
    -            if(DEBUG) MultiPrintStream.out.println(values);
    +            page.registerValues(handler);
    +            if (DEBUG) MultiPrintStream.out.println(values);
     
    -            ValidationFail fail = page.validate( values );
    -            if(fail != null){
    +            ValidationFail fail = page.validate(values);
    +            if (fail != null) {
                     // reset old fail
    -                if(oldFail != null) oldFail.getSource().setBorder( BorderFactory.createEmptyBorder() );
    -                if(fail.getSource() != null)
    -                    fail.getSource().setBorder( BorderFactory.createLineBorder(Color.RED) );
    -                //pageStatus.setText( fail.getMessage() );
    +                if (oldFail != null) oldFail.getSource().setBorder(BorderFactory.createEmptyBorder());
    +                if (fail.getSource() != null)
    +                    fail.getSource().setBorder(BorderFactory.createLineBorder(Color.RED));
    +                //pageStatus.setText(fail.getMessage());
                 }
    -            else if(e.getSource() == finish){
    +            else if (e.getSource() == finish) {
                     frame.dispose();
    -                listener.onFinished( values );
    +                listener.onFinished(values);
                 }
    -            else if(e.getSource() == next){
    -                WizardPage nextPage = page.getNextPage( values );
    -                if(nextPage == null){
    +            else if (e.getSource() == next) {
    +                WizardPage nextPage = page.getNextPage(values);
    +                if (nextPage == null) {
                         frame.dispose();
    -                    listener.onCancel(page, values );
    +                    listener.onCancel(page, values);
                         return;
                     }
    -                pages.add( nextPage );
    -                displayWizardPage( nextPage );
    -                back.setEnabled( true );
    -                if( nextPage.isFinalPage() ){
    -                    next.setEnabled( false );
    -                    finish.setEnabled( true );
    +
    +                pages.add(nextPage);
    +                displayWizardPage(nextPage);
    +                back.setEnabled(true);
    +
    +                if (nextPage.isFinalPage()) {
    +                    next.setEnabled(false);
    +                    finish.setEnabled(true);
                     }
                 }
             }
             // Cancel Button
    -        else if(e.getSource() == cancel){
    +        else if (e.getSource() == cancel) {
                 frame.dispose();
    -            listener.onCancel(pages.getCurrent(), values );
    +            listener.onCancel(pages.getCurrent(), values);
             }
         }
     
    diff --git a/src/zutil/ui/wizard/WizardActionHandler.java b/src/zutil/ui/wizard/WizardActionHandler.java
    index e23922a..31e55be 100644
    --- a/src/zutil/ui/wizard/WizardActionHandler.java
    +++ b/src/zutil/ui/wizard/WizardActionHandler.java
    @@ -38,7 +38,7 @@ import java.util.HashMap;
     public class WizardActionHandler implements ActionListener, FocusListener, ListSelectionListener{
         private HashMap values;
     
    -    public WizardActionHandler(HashMap values){
    +    public WizardActionHandler(HashMap values) {
             this.values = values;
         }
     
    @@ -51,40 +51,40 @@ public class WizardActionHandler implements ActionListener, FocusListener, ListS
         public void focusLost(FocusEvent e) {
             event(e);
         }
    -    public void event(AWTEvent e){
    -        if(e.getSource() instanceof Component)
    -            registerValue( (Component)e.getSource() );
    +    public void event(AWTEvent e) {
    +        if (e.getSource() instanceof Component)
    +            registerValue((Component) e.getSource());
         }
         public void valueChanged(ListSelectionEvent e) {
    -        if(e.getSource() instanceof Component)
    -            registerValue( (Component)e.getSource() );
    +        if (e.getSource() instanceof Component)
    +            registerValue((Component) e.getSource());
         }
     
    -    public void registerListener(Component c){
    +    public void registerListener(Component c) {
             /*
              * JToggleButton
              * JCheckBox
              * JRadioButton
              */
    -        if(c instanceof JToggleButton){
    +        if (c instanceof JToggleButton) {
                 JToggleButton o = (JToggleButton) c;
    -            o.addActionListener( this );
    +            o.addActionListener(this);
             }
             /*
              * JEditorPane
              * JTextArea
              * JTextField
              */
    -        else if(c instanceof JTextComponent){
    +        else if (c instanceof JTextComponent) {
                 JTextComponent o = (JTextComponent) c;
    -            o.addFocusListener( this );
    +            o.addFocusListener(this);
             }
             /*
              * JList
              */
    -        else if(c instanceof JList){
    +        else if (c instanceof JList) {
                 JList o = (JList) c;
    -            o.addListSelectionListener( this );
    +            o.addListSelectionListener(this);
             }
         }
     
    @@ -98,25 +98,25 @@ public class WizardActionHandler implements ActionListener, FocusListener, ListS
              * JCheckBox
              * JRadioButton
              */
    -        if(c instanceof JToggleButton){
    +        if (c instanceof JToggleButton) {
                 JToggleButton o = (JToggleButton) c;
    -            values.put( o.getName() , o.isSelected() );
    +            values.put(o.getName(), o.isSelected());
             }
             /*
              * JEditorPane
              * JTextArea
              * JTextField
              */
    -        else if(c instanceof JTextComponent){
    +        else if (c instanceof JTextComponent) {
                 JTextComponent o = (JTextComponent) c;
    -            values.put( o.getName() , o.getText() );
    +            values.put(o.getName(), o.getText());
             }
             /*
              * JList
              */
    -        else if(c instanceof JList){
    +        else if (c instanceof JList) {
                 JList o = (JList) c;
    -            values.put( o.getName() , o.getSelectedValue() );
    +            values.put(o.getName(), o.getSelectedValue());
             }
         }
     }
    diff --git a/src/zutil/ui/wizard/WizardPage.java b/src/zutil/ui/wizard/WizardPage.java
    index f8f1166..e766818 100644
    --- a/src/zutil/ui/wizard/WizardPage.java
    +++ b/src/zutil/ui/wizard/WizardPage.java
    @@ -42,7 +42,7 @@ public abstract class WizardPage extends JPanel{
         /** if this is the last page in the wizard */
         private boolean lastPage = false;
     
    -    public WizardPage(){
    +    public WizardPage() {
             components = new LinkedList<>();
         }
     
    @@ -53,22 +53,22 @@ public abstract class WizardPage extends JPanel{
          *
          * @param c is the component
          */
    -    public void registerComponent(Component c){
    -        components.add( c );
    +    public void registerComponent(Component c) {
    +        components.add(c);
         }
     
         /**
          * Sets if this is the last page in the wizard,
          * Should be called as early as possible.
          */
    -    public void setFinalPage(boolean b){
    +    public void setFinalPage(boolean b) {
             lastPage = b;
         }
     
         /**
          * @return is this is the last page in the wizard
          */
    -    public boolean isFinalPage(){
    +    public boolean isFinalPage() {
             return lastPage;
         }
     
    @@ -92,7 +92,7 @@ public abstract class WizardPage extends JPanel{
          * @param values is the values until now
          * @return a ValidateFail object or null if the validation passed
          */
    -    public ValidationFail validate(HashMap values){
    +    public ValidationFail validate(HashMap values) {
             return null;
         }
     
    @@ -102,9 +102,9 @@ public abstract class WizardPage extends JPanel{
          *
          * @param listener is the object that handles the save process
          */
    -    public void registerValues(WizardActionHandler listener){
    -        for(Component c : components){
    -            listener.registerValue( c );
    +    public void registerValues(WizardActionHandler listener) {
    +        for (Component c : components) {
    +            listener.registerValue(c);
             }
         }
     }
    @@ -125,7 +125,7 @@ class ValidationFail{
          *
          * @param msg is a message to the user about the fault
          */
    -    public ValidationFail(String msg){
    +    public ValidationFail(String msg) {
             this(null, msg);
         }
     
    @@ -135,16 +135,16 @@ class ValidationFail{
          * @param c is the component that failed the validation
          * @param msg is a message to the user about the fault
          */
    -    public ValidationFail(JComponent c, String msg){
    +    public ValidationFail(JComponent c, String msg) {
             this.source = c;
             this.msg = msg;
         }
     
    -    public JComponent getSource(){
    +    public JComponent getSource() {
             return source;
         }
     
    -    public String getMessage(){
    +    public String getMessage() {
             return msg;
         }
     }
    diff --git a/src/zutil/ui/wizard/listener/BlockingWizardListener.java b/src/zutil/ui/wizard/listener/BlockingWizardListener.java
    index eebdcdc..1ed02dd 100644
    --- a/src/zutil/ui/wizard/listener/BlockingWizardListener.java
    +++ b/src/zutil/ui/wizard/listener/BlockingWizardListener.java
    @@ -45,11 +45,11 @@ public class BlockingWizardListener implements WizardListener{
          * 			as a boolean if the wizard was canceled and "canceledPage"
          * 			witch is the page where the cancel button was pressed
          */
    -    public HashMap getValues(){
    -        while(values == null){
    -            try{
    +    public HashMap getValues() {
    +        while (values == null) {
    +            try {
                     Thread.sleep(100);
    -            }catch(Exception e){}
    +            } catch(Exception e) {}
             }
             return values;
         }
    diff --git a/src/zutil/ui/wizard/page/SummaryPage.java b/src/zutil/ui/wizard/page/SummaryPage.java
    index 2358c09..81a262d 100755
    --- a/src/zutil/ui/wizard/page/SummaryPage.java
    +++ b/src/zutil/ui/wizard/page/SummaryPage.java
    @@ -39,22 +39,22 @@ import java.util.HashMap;
     public class SummaryPage extends WizardPage{
         private static final long serialVersionUID = 1L;
     
    -    public SummaryPage(HashMap values){
    -        this.setFinalPage( true );
    +    public SummaryPage(HashMap values) {
    +        this.setFinalPage(true);
     
             JTextArea summary = new JTextArea();
             summary.setEditable(false);
             summary.setEnabled(false);
    -        this.add( summary );
    +        this.add(summary);
     
             StringBuilder tmp = new StringBuilder();
    -        for(String key : values.keySet()){
    +        for (String key : values.keySet()) {
                 tmp.append(key);
                 tmp.append(": ");
    -            tmp.append(values.get( key ));
    +            tmp.append(values.get(key));
                 tmp.append("\n");
             }
    -        summary.setText( tmp.toString() );
    +        summary.setText(tmp.toString());
         }
     
         @Override
    diff --git a/src/zutil/wrapper/SerializableBufferedImage.java b/src/zutil/wrapper/SerializableBufferedImage.java
    index f35cfe7..0244a5c 100644
    --- a/src/zutil/wrapper/SerializableBufferedImage.java
    +++ b/src/zutil/wrapper/SerializableBufferedImage.java
    @@ -36,15 +36,15 @@ public class SerializableBufferedImage implements Serializable{
     
         private BufferedImage image;
     
    -    public SerializableBufferedImage(BufferedImage image){
    +    public SerializableBufferedImage(BufferedImage image) {
             this.image = image;
         }
     
    -    public BufferedImage getImage(){
    +    public BufferedImage getImage() {
             return image;
         }
     
    -    public void setImage(BufferedImage image){
    +    public void setImage(BufferedImage image) {
             this.image=image;
         }
     
    diff --git a/test/zutil/ByteUtilTest.java b/test/zutil/ByteUtilTest.java
    index 0cc3021..622be55 100755
    --- a/test/zutil/ByteUtilTest.java
    +++ b/test/zutil/ByteUtilTest.java
    @@ -37,7 +37,7 @@ public class ByteUtilTest {
     
     
         @Test
    -    public void getShiftedBits(){
    +    public void getShiftedBits() {
             assertEquals(1, ByteUtil.getShiftedBits((byte)0b1000_0000, 7, 1));
             assertEquals(1, ByteUtil.getShiftedBits((byte)0b0001_0000, 4, 1));
             assertEquals(1, ByteUtil.getShiftedBits((byte)0b0000_0001, 0, 1));
    @@ -49,14 +49,14 @@ public class ByteUtilTest {
     
     
         @Test
    -    public void getBits(){
    +    public void getBits() {
             assertEquals(0x01, ByteUtil.getBits((byte)0x11, 1));
             assertEquals(0x03, ByteUtil.getBits((byte)0x13, 4));
             assertEquals((byte)0x55, ByteUtil.getBits((byte)0x55, 8));
         }
     
         @Test
    -    public void getBitsMSB(){
    +    public void getBitsMSB() {
             assertEquals(0x01, ByteUtil.getBitsMSB((byte)0x80, 1));
             assertEquals(0x05, ByteUtil.getBitsMSB((byte)0x52, 4));
             assertEquals((byte)0x55, ByteUtil.getBitsMSB((byte)0x55, 8));
    @@ -65,7 +65,7 @@ public class ByteUtilTest {
         }
     
         @Test
    -    public void getBitsArray(){
    +    public void getBitsArray() {
             assertArrayEquals(new byte[]{}, ByteUtil.getBits(new byte[]{0x00}, 0));
             assertArrayEquals(new byte[]{0x00}, ByteUtil.getBits(new byte[]{}, 1));
             assertArrayEquals(new byte[]{0x00,0x00,0x00,0x00}, ByteUtil.getBits(new byte[]{0x00}, 32));
    @@ -76,7 +76,7 @@ public class ByteUtilTest {
         }
     
         @Test
    -    public void getReverseByteOrder(){
    +    public void getReverseByteOrder() {
             assertArrayEquals(new byte[]{}, ByteUtil.getReverseByteOrder(new byte[]{}));
             assertArrayEquals(new byte[]{0x11}, ByteUtil.getReverseByteOrder(new byte[]{0x11}));
             assertArrayEquals(new byte[]{0x22,0x11}, ByteUtil.getReverseByteOrder(new byte[]{0x11,0x22}));
    @@ -85,7 +85,7 @@ public class ByteUtilTest {
     
     
         @Test
    -    public void toFormattedString(){
    +    public void toFormattedString() {
             byte[] data = new byte[1];
             assertEquals("000  00                       '.       '",
                     ByteUtil.toFormattedString(data));
    @@ -110,7 +110,7 @@ public class ByteUtilTest {
     
     
         @Test
    -    public void shiftLeft(){
    +    public void shiftLeft() {
             assertArrayEquals(         new byte[]{},
                     ByteUtil.shiftLeft(new byte[]{}, 4));
             assertArrayEquals(         new byte[]{0b0000_0001},
    @@ -128,7 +128,7 @@ public class ByteUtilTest {
         }
     
         @Test
    -    public void shiftRight(){
    +    public void shiftRight() {
             assertArrayEquals(         new byte[]{},
                     ByteUtil.shiftRight(new byte[]{}, 4));
             assertArrayEquals(         new byte[]{0b0000_0001},
    diff --git a/test/zutil/CronTimerTest.java b/test/zutil/CronTimerTest.java
    index 131078a..8f81fd4 100755
    --- a/test/zutil/CronTimerTest.java
    +++ b/test/zutil/CronTimerTest.java
    @@ -65,19 +65,19 @@ public class CronTimerTest {
             try{
                 CronTimer.getRange("50", 1,12);
                 fail("Did not receive Exception");
    -        } catch (IllegalArgumentException e){e.printStackTrace();} // We expect exception
    +        } catch (IllegalArgumentException e) {e.printStackTrace();} // We expect exception
             try{
                 CronTimer.getRange("0", 1,12);
                 fail("Did not receive Exception");
    -        } catch (IllegalArgumentException e){e.printStackTrace();} // We expect exception
    +        } catch (IllegalArgumentException e) {e.printStackTrace();} // We expect exception
             try{
                 CronTimer.getRange("1-50", 1,12);
                 fail("Did not receive Exception");
    -        } catch (IllegalArgumentException e){e.printStackTrace();} // We expect exception
    +        } catch (IllegalArgumentException e) {e.printStackTrace();} // We expect exception
             try{
                 CronTimer.getRange("0-5", 3,12);
                 fail("Did not receive Exception");
    -        } catch (IllegalArgumentException e){e.printStackTrace();} // We expect exception
    +        } catch (IllegalArgumentException e) {e.printStackTrace();} // We expect exception
         }
     
         @Test
    @@ -89,14 +89,14 @@ public class CronTimerTest {
         }
     
         @Test
    -    public void minuteWildcard(){
    +    public void minuteWildcard() {
             CronTimer cron = getCronTimer("0 * * * * *");
             assertEquals(1041382800000L, (long)cron.next(1041379200000L));
             assertEquals(1041382800000L, (long)cron.next(1041379260000L));
         }
     
         @Test
    -    public void hourWildcard(){
    +    public void hourWildcard() {
             CronTimer cron = getCronTimer("* 0 * * * *");
             assertEquals(1041379260000L, (long)cron.next(1041379200000L));
             assertEquals(1041379320000L, (long)cron.next(1041379260000L)); // minute change
    @@ -105,7 +105,7 @@ public class CronTimerTest {
         }
     
         @Test
    -    public void dayWildcard(){
    +    public void dayWildcard() {
             CronTimer cron = getCronTimer("* * 1 * * *");
             assertEquals(1041379260000L, (long)cron.next(1041379200000L));
             assertEquals(1041379320000L, (long)cron.next(1041379260000L)); // minute change
    @@ -113,7 +113,7 @@ public class CronTimerTest {
         }
     
         @Test
    -    public void monthWildcard(){
    +    public void monthWildcard() {
             CronTimer cron = getCronTimer("* * * 1 * *");
             assertEquals(1041379260000L, (long)cron.next(1041379200000L));
             assertEquals(1041382860000L, (long)cron.next(1041382800000L)); // hour change
    @@ -122,14 +122,14 @@ public class CronTimerTest {
         }
     
         @Test
    -    public void weekDayWildcard(){
    +    public void weekDayWildcard() {
             CronTimer cron = getCronTimer("* * * * 3 *");
             assertEquals(1041379260000L, (long)cron.next(1041379200000L));
             assertEquals(1041984000000L, (long)cron.next(1041465600000L)); // day change
         }
     
         @Test
    -    public void yearWildcard(){
    +    public void yearWildcard() {
             CronTimer cron = getCronTimer("* * * * * 2003");
             assertEquals(1041379260000L, (long)cron.next(1041379200000L));
             assertEquals(1041379320000L, (long)cron.next(1041379260000L)); // min change
    diff --git a/test/zutil/EncrypterTest.java b/test/zutil/EncrypterTest.java
    index 0e33d2f..c8916b2 100755
    --- a/test/zutil/EncrypterTest.java
    +++ b/test/zutil/EncrypterTest.java
    @@ -65,7 +65,7 @@ public class EncrypterTest {
     
     
     
    -    public static String encryptDecrypt(Encrypter encrypter, Encrypter decrypter, String 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/HasherTest.java b/test/zutil/HasherTest.java
    index 2bf807e..119a932 100755
    --- a/test/zutil/HasherTest.java
    +++ b/test/zutil/HasherTest.java
    @@ -32,7 +32,7 @@ import static org.junit.Assert.assertEquals;
     public class HasherTest {
     
         @Test
    -    public void MD5Test(){
    +    public void MD5Test() {
             assertEquals(Hasher.MD5("AAAABBBB"),   "9da4fc50e09e5eeb8ae8149ef4f23792");
             assertEquals(Hasher.MD5("qwerty12345"),"85064efb60a9601805dcea56ec5402f7");
             assertEquals(Hasher.MD5("123456789"),  "25f9e794323b453885f5181f1b624d0b");
    @@ -40,7 +40,7 @@ public class HasherTest {
         }
     
         @Test
    -    public void SHA1Test(){
    +    public void SHA1Test() {
             assertEquals(Hasher.SHA1("AAAABBBB"),   "7cd188ef3a9ea7fa0ee9c62c168709695460f5c0");
             assertEquals(Hasher.SHA1("qwerty12345"),"4e17a448e043206801b95de317e07c839770c8b8");
             assertEquals(Hasher.SHA1("123456789"),  "f7c3bc1d808e04732adf679965ccc34ca7ae3441");
    @@ -48,7 +48,7 @@ public class HasherTest {
         }
     
         @Test
    -    public void PBKDF2(){
    +    public void PBKDF2() {
             assertEquals(Hasher.PBKDF2("AAAABBBB", "s", 1000),
                     "8da1853fe2a2efc82aa444e7274b74cf25190e580898bbaac83c502099506dd7");
             assertEquals(Hasher.PBKDF2("AAAABBBB", "salt", 1000),
    diff --git a/test/zutil/StringUtilTest.java b/test/zutil/StringUtilTest.java
    index d6b0760..c8ab51b 100755
    --- a/test/zutil/StringUtilTest.java
    +++ b/test/zutil/StringUtilTest.java
    @@ -72,7 +72,7 @@ public class StringUtilTest {
         }
     
         @Test
    -    public void joinTest(){
    +    public void joinTest() {
             assertEquals("", StringUtil.join(",", Collections.emptyList()));
             assertEquals("1,2,3,4,5", StringUtil.join(",", 1,2,3,4,5));
             assertEquals("1,2,3,4,5", StringUtil.join(",", Arrays.asList(1,2,3,4,5)));
    diff --git a/test/zutil/algo/search/QuickSelectTest.java b/test/zutil/algo/search/QuickSelectTest.java
    index c31ee8d..699a56d 100755
    --- a/test/zutil/algo/search/QuickSelectTest.java
    +++ b/test/zutil/algo/search/QuickSelectTest.java
    @@ -33,7 +33,7 @@ import java.util.Arrays;
      * TODO: Convert to JUnit
      */
     public class QuickSelectTest {
    -    public static void main(String[] args){
    +    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};
     
    @@ -46,7 +46,7 @@ public class QuickSelectTest {
             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]){
    +        for(int i=1; i array[i]) {
                     error = i;
                 }
             }
     
    -        if(error >= 0){
    -            System.out.println("\nArray not sorted!! ("+array[error-1]+" > "+array[error]+")");
    +        if (error >= 0) {
    +            System.out.println("\nArray not sorted!! (" + array[error-1] + " > " + array[error] + ")");
             }
    -        System.out.println("\nTime: "+time+" ms");
    +        System.out.println("\nTime: " + time + " ms");
         }
    -} 
    +}
    diff --git a/test/zutil/benchmark/AnonymousFunctionBenchmark.java b/test/zutil/benchmark/AnonymousFunctionBenchmark.java
    index 135f41a..c4c5959 100755
    --- a/test/zutil/benchmark/AnonymousFunctionBenchmark.java
    +++ b/test/zutil/benchmark/AnonymousFunctionBenchmark.java
    @@ -40,7 +40,7 @@ public class AnonymousFunctionBenchmark {
     
         @Test
         public void functionLoop() {
    -        for(int k=0; k splitList = StringUtil.split(str, delimiter.charAt(0));
                 assertSplit(splitList.toArray(new String[0]));
             }
    diff --git a/test/zutil/io/BufferedBoundaryInputStreamTest.java b/test/zutil/io/BufferedBoundaryInputStreamTest.java
    index f05a8e6..df11062 100755
    --- a/test/zutil/io/BufferedBoundaryInputStreamTest.java
    +++ b/test/zutil/io/BufferedBoundaryInputStreamTest.java
    @@ -197,8 +197,8 @@ public class BufferedBoundaryInputStreamTest {
     
             int out;
             StringBuilder output = new StringBuilder();
    -        while((out = in.read()) != -1){
    -            output.append((char)out);
    +        while ((out = in.read()) != -1){
    +            output.append((char) out);
             }
             assertEquals(data, output.toString());
         }
    diff --git a/test/zutil/io/file/FileChangedTest.java b/test/zutil/io/file/FileChangedTest.java
    index 70746fc..9a99e02 100755
    --- a/test/zutil/io/file/FileChangedTest.java
    +++ b/test/zutil/io/file/FileChangedTest.java
    @@ -33,7 +33,7 @@ public class FileChangedTest implements FileWatcher.FileChangeListener {
             FileWatcher watcher = new FileWatcher(FileUtil.find("test.txt"));
             watcher.setListener(new FileChangedTest());
     
    -        while(true){
    +        while (true) {
                 try {
                     Thread.sleep(10);
                 } catch (InterruptedException e) {
    diff --git a/test/zutil/math/MatrixTest.java b/test/zutil/math/MatrixTest.java
    index 652328b..05ea27e 100755
    --- a/test/zutil/math/MatrixTest.java
    +++ b/test/zutil/math/MatrixTest.java
    @@ -35,25 +35,25 @@ import static org.junit.Assert.assertEquals;
     public class MatrixTest {
     
         @Test
    -    public void scalarAdd(){
    +    public void scalarAdd() {
             assertArrayEquals(new double[][]{{4,5},{-2,11}},
                     Matrix.add(new double[][]{{2,3},{-4,9}}, 2));
         }
     
         @Test
    -    public void scalarSubtraction(){
    +    public void scalarSubtraction() {
             assertArrayEquals(new double[][]{{0,1},{-6,7}},
                     Matrix.subtract(new double[][]{{2,3},{-4,9}}, 2));
         }
     
         @Test
    -    public void scalarMultiply(){
    +    public void scalarMultiply() {
             assertArrayEquals(new double[][]{{4,6},{-8,18}},
                     Matrix.multiply(new double[][]{{2,3},{-4,9}}, 2));
         }
     
         @Test
    -    public void scalarDivision(){
    +    public void scalarDivision() {
             assertArrayEquals(new double[][]{{1,2},{-2,5}},
                     Matrix.divide(new double[][]{{2,4},{-4,10}}, 2));
         }
    @@ -61,25 +61,25 @@ public class MatrixTest {
     
     
         @Test
    -    public void elementalAdd(){
    +    public void elementalAdd() {
             assertArrayEquals(new double[][]{{3,5},{-1,13}},
                     Matrix.Elemental.add(new double[][]{{2,3},{-4,9}}, new double[][]{{1,2},{3,4}}));
         }
     
         @Test
    -    public void elementalSubtract(){
    +    public void elementalSubtract() {
             assertArrayEquals(new double[][]{{1,1},{-7,5}},
                     Matrix.Elemental.subtract(new double[][]{{2,3},{-4,9}}, new double[][]{{1,2},{3,4}}));
         }
     
         @Test
    -    public void elementalMultiply(){
    +    public void elementalMultiply() {
             assertArrayEquals(new double[][]{{2,6},{-12,36}},
                     Matrix.Elemental.multiply(new double[][]{{2,3},{-4,9}}, new double[][]{{1,2},{3,4}}));
         }
     
         @Test
    -    public void elementalVectorPow(){
    +    public void elementalVectorPow() {
             assertArrayEquals(
                     new double[]{4,9,16,81},
                     Matrix.Elemental.pow(new double[]{2,3,-4,9}, 2),
    @@ -87,7 +87,7 @@ public class MatrixTest {
         }
     
         @Test
    -    public void elementalMatrixPow(){
    +    public void elementalMatrixPow() {
             assertArrayEquals(new double[][]{{4,9},{16,81}},
                     Matrix.Elemental.pow(new double[][]{{2,3},{-4,9}}, 2));
         }
    @@ -95,7 +95,7 @@ public class MatrixTest {
     
     
         @Test
    -    public void vectorAddition(){
    +    public void vectorAddition() {
             assertArrayEquals(
                     new double[]{3,5,-1,13},
                     Matrix.add(new double[]{2,3,-4,9}, new double[]{1,2,3,4}),
    @@ -104,7 +104,7 @@ public class MatrixTest {
         }
     
         @Test
    -    public void vectorMatrixAddition(){
    +    public void vectorMatrixAddition() {
             assertArrayEquals(
                     new double[][]{{2,3,4,5},{2,3,4,5},{2,3,4,5},{2,3,4,5}},
                     Matrix.add(new double[][]{{1,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,4}}, new double[]{1,1,1,1})
    @@ -112,7 +112,7 @@ public class MatrixTest {
         }
     
         @Test
    -    public void vectorSubtraction(){
    +    public void vectorSubtraction() {
             assertArrayEquals(
                     new double[]{1,1,-7,5},
                     Matrix.subtract(new double[]{2,3,-4,9}, new double[]{1,2,3,4}),
    @@ -121,7 +121,7 @@ public class MatrixTest {
         }
     
         @Test
    -    public void vectorMatrixSubtraction(){
    +    public void vectorMatrixSubtraction() {
             assertArrayEquals(
                     new double[][]{{0,1,2,3},{0,1,2,3},{0,1,2,3},{0,1,2,3}},
                     Matrix.subtract(new double[][]{{1,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,4}}, new double[]{1,1,1,1})
    @@ -129,7 +129,7 @@ public class MatrixTest {
         }
     
         @Test
    -    public void vectorMultiply(){
    +    public void vectorMultiply() {
             assertArrayEquals(
                     new double[]{0.1, 0.4, 0.9, 1.6},
                     Matrix.Elemental.multiply(
    @@ -139,7 +139,7 @@ public class MatrixTest {
         }
     
         @Test
    -    public void vectorMatrixMultiply(){
    +    public void vectorMatrixMultiply() {
             assertArrayEquals(
                     new double[]{1.4, 1.9, 2.4, 2.9},
                     Matrix.multiply(
    @@ -149,7 +149,7 @@ public class MatrixTest {
         }
     
         @Test
    -    public void vectorMatrixDivision(){
    +    public void vectorMatrixDivision() {
             assertArrayEquals(
                     new double[]{4,1},
                     Matrix.divide(new double[][]{{2,4},{-4,10}}, new double[]{1,2}),
    @@ -158,7 +158,7 @@ public class MatrixTest {
         }
     
         @Test
    -    public void vectorMatrixElementalMultiply(){
    +    public void vectorMatrixElementalMultiply() {
             assertArrayEquals(
                     new double[][]{{1, 4, 9}, {1, 6, 12}, {1, 8, 15}, {1, 10, 18}},
                     Matrix.Elemental.multiply(
    @@ -167,7 +167,7 @@ public class MatrixTest {
         }
     
         @Test
    -    public void vectorMatrixElementalDivision(){
    +    public void vectorMatrixElementalDivision() {
             assertArrayEquals(
                     new double[][]{{2,2},{-4,5}},
                     Matrix.Elemental.divide(
    @@ -176,7 +176,7 @@ public class MatrixTest {
         }
     
         @Test
    -    public void vectorSum(){
    +    public void vectorSum() {
             assertEquals(
                     20.0,
                     Matrix.sum(new double[]{1,2,0,3,5,9}),
    @@ -187,7 +187,7 @@ public class MatrixTest {
     
     
         @Test
    -    public void matrixMultiply(){
    +    public void matrixMultiply() {
             assertArrayEquals(
                     new double[][]{{486,410.4,691.6},{314,341.6,416.4},{343.5,353.4,463.6},{173,285.2,190.8}},
                     Matrix.multiply(
    @@ -197,7 +197,7 @@ public class MatrixTest {
         }
     
         @Test
    -    public void matrixTranspose(){
    +    public void matrixTranspose() {
             assertArrayEquals(
                     new double[][]{{1,3},{2,5},{0,9}},
                     Matrix.transpose(
    @@ -206,7 +206,7 @@ public class MatrixTest {
         }
     
         @Test
    -    public void matrixSum(){
    +    public void matrixSum() {
             assertEquals(
                     20.0,
                     Matrix.sum(new double[][]{{1,2,0},{3,5,9}}),
    @@ -217,7 +217,7 @@ public class MatrixTest {
     
     
         @Test
    -    public void identity(){
    +    public void identity() {
             assertArrayEquals(
                     new double[][]{{1}},
                     Matrix.identity(1));
    @@ -228,7 +228,7 @@ public class MatrixTest {
         }
     
         @Test
    -    public void getColumn(){
    +    public void getColumn() {
             assertArrayEquals(
                     new double[]{2,3,4,1},
                     Matrix.getColumn(new double[][]{{1,2,3,4},{2,3,4,1},{3,4,1,2},{4,1,2,3}}, 1),
    diff --git a/test/zutil/net/ServerFindClientTest.java b/test/zutil/net/ServerFindClientTest.java
    index b7b473f..0213102 100755
    --- a/test/zutil/net/ServerFindClientTest.java
    +++ b/test/zutil/net/ServerFindClientTest.java
    @@ -28,7 +28,7 @@ import java.io.IOException;
     
     
     public class ServerFindClientTest {
    -    public static void main(String[] args){
    +    public static void main(String[] args) {
             try {
                 ServerFindClient client = new ServerFindClient(2000);
                 System.out.println(client.find().getHostAddress());
    diff --git a/test/zutil/net/ServerFindServerTest.java b/test/zutil/net/ServerFindServerTest.java
    index b06886c..e077621 100755
    --- a/test/zutil/net/ServerFindServerTest.java
    +++ b/test/zutil/net/ServerFindServerTest.java
    @@ -28,7 +28,7 @@ import java.io.IOException;
     
     
     public class ServerFindServerTest {
    -    public static void main(String[] args){
    +    public static void main(String[] args) {
             try {
                 new ServerFind(2000);
             } catch (IOException e) {
    diff --git a/test/zutil/net/http/page/HttpGuessTheNumber.java b/test/zutil/net/http/page/HttpGuessTheNumber.java
    index ed767bb..a3e05b4 100755
    --- a/test/zutil/net/http/page/HttpGuessTheNumber.java
    +++ b/test/zutil/net/http/page/HttpGuessTheNumber.java
    @@ -69,7 +69,7 @@ public class HttpGuessTheNumber implements HttpPage {
             String low = cookie.get(COOKIE_KEY_LOW);
             String high = cookie.get(COOKIE_KEY_HIGH);
     
    -        if(session.containsKey(SESSION_KEY_NUMBER)){
    +        if (session.containsKey(SESSION_KEY_NUMBER)){
                 if (request.containsKey(REQUEST_KEY_GUESS)) {
                     int guess = Integer.parseInt(request.get(REQUEST_KEY_GUESS));
                     int number = (Integer) session.get(SESSION_KEY_NUMBER);
    @@ -94,7 +94,7 @@ public class HttpGuessTheNumber implements HttpPage {
                     }
                 }
             }
    -        else{
    +        else {
                 session.put(SESSION_KEY_NUMBER, (int)(Math.random()*99+1));
                 low = "0";
                 high = "100";
    diff --git a/test/zutil/net/http/page/oauth/OAuth2TokenPageTest.java b/test/zutil/net/http/page/oauth/OAuth2TokenPageTest.java
    index 3b95475..947be2e 100644
    --- a/test/zutil/net/http/page/oauth/OAuth2TokenPageTest.java
    +++ b/test/zutil/net/http/page/oauth/OAuth2TokenPageTest.java
    @@ -47,7 +47,7 @@ public class OAuth2TokenPageTest {
         private OAuth2TokenPage tokenPage;
     
         @Before
    -    public void init(){
    +    public void init() {
             registry = new OAuth2Registry();
             tokenPage = new OAuth2TokenPage(registry);
     
    diff --git a/test/zutil/net/nio/NetworkClientTest.java b/test/zutil/net/nio/NetworkClientTest.java
    index c6ad41c..881cb0f 100755
    --- a/test/zutil/net/nio/NetworkClientTest.java
    +++ b/test/zutil/net/nio/NetworkClientTest.java
    @@ -49,7 +49,7 @@ public class NetworkClientTest {
                 client.setDefaultWorker(worker);
     
                 Thread.sleep(1000);
    -            while(time > System.currentTimeMillis()){
    +            while (time > System.currentTimeMillis()){
                     PrintResponseHandler handler = new PrintResponseHandler();
                     worker.send(client.getRemoteAddress(),
                             new StringResponseMessage("StringResponseMessage: "+count),
    diff --git a/test/zutil/net/nio/NetworkServerTest.java b/test/zutil/net/nio/NetworkServerTest.java
    index 595712f..a566bc5 100755
    --- a/test/zutil/net/nio/NetworkServerTest.java
    +++ b/test/zutil/net/nio/NetworkServerTest.java
    @@ -42,7 +42,7 @@ public class NetworkServerTest {
                 NioServer server = new NioServer(6056);
                 server.setDefaultWorker(new StandardWorker(server));
     
    -            while(true){
    +            while (true){
                     Thread.sleep(1000);
                 }
             } catch (IOException e) {
    diff --git a/test/zutil/net/ws/rest/RESTHttpPageTest.java b/test/zutil/net/ws/rest/RESTHttpPageTest.java
    index 1558bc5..83c6002 100755
    --- a/test/zutil/net/ws/rest/RESTHttpPageTest.java
    +++ b/test/zutil/net/ws/rest/RESTHttpPageTest.java
    @@ -37,7 +37,7 @@ import static org.junit.Assert.assertEquals;
     public class RESTHttpPageTest {
     
         public static class TestClass implements WSInterface{
    -        public String hello(){
    +        public String hello() {
                 return "hello world";
             }
         }
    @@ -53,7 +53,7 @@ public class RESTHttpPageTest {
     
     
         public static class TestEchoClass implements WSInterface{
    -        public String echo(@WSParamName("input") String input){
    +        public String echo(@WSParamName("input") String input) {
                 return "echo: "+input;
             }
         }
    diff --git a/test/zutil/parser/CSVParserTest.java b/test/zutil/parser/CSVParserTest.java
    index 903b723..800d02b 100755
    --- a/test/zutil/parser/CSVParserTest.java
    +++ b/test/zutil/parser/CSVParserTest.java
    @@ -40,13 +40,13 @@ public class CSVParserTest {
     
     
         @Test
    -    public void emptyTest(){
    +    public void emptyTest() {
             DataNode node = CSVParser.read("");
             assertNull(node);
         }
     
         @Test
    -    public void simpleTest(){
    +    public void simpleTest() {
             DataNode node = CSVParser.read("hello,world,you");
             assertEquals(3, node.size());
             assertEquals("hello", node.get(0).getString());
    @@ -83,7 +83,7 @@ public class CSVParserTest {
         }
     
         @Test
    -    public void quotedTest(){
    +    public void quotedTest() {
             DataNode node = CSVParser.read("\"hello\",\"world\",\"you\"");
             assertEquals(3, node.size());
             assertEquals("hello", node.get(0).getString());
    @@ -92,7 +92,7 @@ public class CSVParserTest {
         }
     
         @Test
    -    public void quotedIncorrectlyTest(){
    +    public void quotedIncorrectlyTest() {
             DataNode node = CSVParser.read("hello\",wo\"rl\"d,\"you\"");
             assertEquals(3, node.size());
             assertEquals("hello\"", node.get(0).getString());
    diff --git a/test/zutil/parser/URLDecoderTest.java b/test/zutil/parser/URLDecoderTest.java
    index 74001b9..5bd1bf7 100755
    --- a/test/zutil/parser/URLDecoderTest.java
    +++ b/test/zutil/parser/URLDecoderTest.java
    @@ -35,7 +35,7 @@ import static org.junit.Assert.assertNull;
     public class URLDecoderTest {
     
         @Test
    -    public void simpleTest(){
    +    public void simpleTest() {
             assertNull(URLDecoder.decode(null));
             assertEquals("", URLDecoder.decode(""));
             assertEquals("space space", URLDecoder.decode("space space"));
    @@ -44,7 +44,7 @@ public class URLDecoderTest {
         }
     
         @Test
    -    public void percentTest(){
    +    public void percentTest() {
             assertEquals("test+", URLDecoder.decode("test%2B"));
             assertEquals("test%2", URLDecoder.decode("test%2"));
             assertEquals("test+test", URLDecoder.decode("test%2Btest"));
    diff --git a/test/zutil/parser/json/JSONSerializerBenchmark.java b/test/zutil/parser/json/JSONSerializerBenchmark.java
    index 9ba95ed..6f8793e 100755
    --- a/test/zutil/parser/json/JSONSerializerBenchmark.java
    +++ b/test/zutil/parser/json/JSONSerializerBenchmark.java
    @@ -40,7 +40,7 @@ public class JSONSerializerBenchmark {
     
         @Test
         public void testJavaLegacySerialize() throws IOException, ClassNotFoundException{
    -        for(int i=0; i