Formatting cleanup

This commit is contained in:
Ziver Koc 2021-03-23 21:49:52 +01:00
parent 65b47d0755
commit ec1758ce20
222 changed files with 2739 additions and 2726 deletions

View file

@ -34,7 +34,7 @@ public class ArrayUtil {
/** /**
* Converts a List with Integer objects to a primary type int array * Converts a List with Integer objects to a primary type int array
*/ */
public static int[] toIntArray(List<Integer> list){ public static int[] toIntArray(List<Integer> list) {
if (list == null) if (list == null)
return null; return null;
int[] arr = new int[list.size()]; int[] arr = new int[list.size()];

View file

@ -53,7 +53,7 @@ public class ByteUtil {
* @param length is the length of bits to return, valid values 1-8 * @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 * @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)); 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 * @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 * @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); int ret = 0xFF & getBits(data, index, length);
ret = ret >>> index+1-length; ret = ret >>> index+1-length;
return (byte) ret; return (byte) ret;
@ -78,7 +78,7 @@ public class ByteUtil {
* @param length is the length of bits to return, valid values 1-8 * @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 * @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); return getBits(data, length-1, length);
} }
@ -89,10 +89,10 @@ public class ByteUtil {
* @param length is the length of bits to return * @param length is the length of bits to return
* @return a new byte array of te given length containing the given data. * @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)]; byte[] dest = new byte[(int) Math.ceil(length/8.0)];
System.arraycopy(data, 0, dest, 0, Math.min(data.length, dest.length)); 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); dest[dest.length-1] = getBits(dest[dest.length-1], length % 8);
return dest; return dest;
} }
@ -104,7 +104,7 @@ public class ByteUtil {
* @param length is the length of bits to return, valid values 1-8 * @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 * @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); return getShiftedBits(data, 7, length);
} }
@ -115,7 +115,7 @@ public class ByteUtil {
* @param data is the byte array that will be reversed. * @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 * @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]; byte[] dest = new byte[data.length];
if (data.length > 0) if (data.length > 0)
for (int i=0; i<data.length; ++i) for (int i=0; i<data.length; ++i)
@ -131,10 +131,10 @@ public class ByteUtil {
*/ */
public static byte getBitMask(int index, int length) { public static byte getBitMask(int index, int length) {
--length; --length;
if(0 > index || index > 7) if (0 > index || index > 7)
throw new IllegalArgumentException("Invalid index argument, allowed values: 0-7"); throw new IllegalArgumentException("Invalid index argument, allowed values: 0-7");
if(length < 0 || index-length < 0) if (length < 0 || index-length < 0)
throw new IllegalArgumentException("Invalid length argument: "+length+", allowed values: 1 to "+(index+1)+" for index "+index); throw new IllegalArgumentException("Invalid length argument: " + length + ", allowed values: 1 to " + (index+1) + " for index " + index);
return (byte) BYTE_MASK[index][length]; return (byte) BYTE_MASK[index][length];
} }
@ -147,16 +147,16 @@ public class ByteUtil {
* @return same data reference as the data input * @return same data reference as the data input
*/ */
public static byte[] shiftLeft(byte[] data, int shiftBy) { public static byte[] shiftLeft(byte[] data, int shiftBy) {
if(0 > shiftBy || shiftBy > 8) if (0 > shiftBy || shiftBy > 8)
throw new IllegalArgumentException("Invalid shiftBy("+shiftBy+") argument, allowed values: 0-8"); throw new IllegalArgumentException("Invalid shiftBy(" + shiftBy + ") argument, allowed values: 0-8");
if (shiftBy == 0) if (shiftBy == 0)
return data; return data;
byte rest; byte rest;
for (int i=0; i<data.length; ++i){ for (int i=0; i<data.length; ++i) {
rest = (byte)(getBits(data[i], shiftBy-1, shiftBy) << 8 - shiftBy); rest = (byte)(getBits(data[i], shiftBy-1, shiftBy) << 8 - shiftBy);
data[i] = (byte)((data[i]&0xFF) >>> shiftBy); data[i] = (byte)((data[i]&0xFF) >>> shiftBy);
if(i != 0) if (i != 0)
data[i-1] |= rest; data[i-1] |= rest;
} }
@ -171,16 +171,16 @@ public class ByteUtil {
* @return same data reference as the data input * @return same data reference as the data input
*/ */
public static byte[] shiftRight(byte[] data, int shiftBy) { public static byte[] shiftRight(byte[] data, int shiftBy) {
if(0 > shiftBy || shiftBy > 8) if (0 > shiftBy || shiftBy > 8)
throw new IllegalArgumentException("Invalid shiftBy("+shiftBy+") argument, allowed values: 0-8"); throw new IllegalArgumentException("Invalid shiftBy(" + shiftBy + ") argument, allowed values: 0-8");
if (shiftBy == 0) if (shiftBy == 0)
return data; return data;
byte rest = 0; byte rest = 0;
for (int i=0; i<data.length; ++i){ for (int i=0; i<data.length; ++i) {
byte preRest = getBitsMSB(data[i], shiftBy); byte preRest = getBitsMSB(data[i], shiftBy);
data[i] = (byte)(data[i] << shiftBy); data[i] = (byte)(data[i] << shiftBy);
if(i != 0) if (i != 0)
data[i] |= rest; data[i] |= rest;
rest = preRest; rest = preRest;
} }
@ -195,7 +195,7 @@ public class ByteUtil {
* @param data The source binary data to format * @param data The source binary data to format
* @return A multiline String with human readable HEX and ASCII * @return A multiline String with human readable HEX and ASCII
*/ */
public static String toFormattedString(byte[] data){ public static String toFormattedString(byte[] data) {
return toFormattedString(data, 0, data.length); return toFormattedString(data, 0, data.length);
} }
@ -205,26 +205,26 @@ public class ByteUtil {
* @param data The source binary data to format * @param data The source binary data to format
* @return A multiline String with human readable HEX and ASCII * @return A multiline String with human readable HEX and ASCII
*/ */
public static String toFormattedString(byte[] data, int offset, int length){ public static String toFormattedString(byte[] data, int offset, int length) {
StringBuilder output = new StringBuilder(); StringBuilder output = new StringBuilder();
//000 XX XX XX XX XX XX XX XX '........' //000 XX XX XX XX XX XX XX XX '........'
int maxOffset = (""+length).length(); int maxOffset = ("" +length).length();
for(; offset<length; offset+=8){ for (; offset<length; offset+=8) {
if(offset != 0) if (offset != 0)
output.append('\n'); output.append('\n');
// Offset // Offset
String offsetStr = ""+offset; String offsetStr = "" +offset;
for(int i=offsetStr.length(); i<3 || i<maxOffset; ++i){ for (int i=offsetStr.length(); i<3 || i<maxOffset; ++i) {
output.append('0'); output.append('0');
} }
output.append(offsetStr); output.append(offsetStr);
output.append(" "); output.append(" ");
// HEX // HEX
for(int i=0; i<8; ++i){ for (int i=0; i<8; ++i) {
if(offset+i < length) if (offset+i < length)
output.append(Converter.toHexString(data[offset+i])); output.append(Converter.toHexString(data[offset+i]));
else else
output.append(" "); output.append(" ");
@ -234,9 +234,9 @@ public class ByteUtil {
// ACII // ACII
output.append('\''); output.append('\'');
for(int i=0; i<8; ++i){ for (int i=0; i<8; ++i) {
if(offset+i < length) if (offset+i < length)
if( 32 <= data[offset+i] && data[offset+i] <= 126 ) if (32 <= data[offset+i] && data[offset+i] <= 126)
output.append((char)data[offset+i]); output.append((char)data[offset+i]);
else else
output.append('.'); output.append('.');

View file

@ -71,14 +71,14 @@ public class ClassUtil {
/** /**
* @return if the given class is a wrapper for a primitive * @return if the given class is a wrapper for a primitive
*/ */
public static boolean isWrapper(Class<?> type){ public static boolean isWrapper(Class<?> type) {
return wrappers.contains(type); return wrappers.contains(type);
} }
/** /**
* @return if the given class is a primitive including String * @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); 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. * @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. * 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) || return Long.class.isAssignableFrom(type) ||
long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type) ||
Integer.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. * @return true if the given class is a type representing a number with decimals.
* E.g. double, float and corresponding wrapper. * E.g. double, float and corresponding wrapper.
*/ */
public static boolean isDecimal(Class<?> type){ public static boolean isDecimal(Class<?> type) {
return Double.class.isAssignableFrom(type) || return Double.class.isAssignableFrom(type) ||
double.class.isAssignableFrom(type) || double.class.isAssignableFrom(type) ||
Float.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 * @return a bool value depending on if the given class is available in the classpath
*/ */
public boolean isAvailable(String clazz){ public boolean isAvailable(String clazz) {
try{ try {
Class.forName(clazz); Class.forName(clazz);
return true; return true;
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
@ -127,7 +127,7 @@ public class ClassUtil {
* @param field is the field to fetch the generics classes from. * @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. * @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()); return getGenericClasses(field.getGenericType());
} }
@ -148,8 +148,8 @@ public class ClassUtil {
* @return the generics for a specific super class or a empty list if * @return the generics for a specific super class or a empty list if
* there is no generics or the super class is not found * there is no generics or the super class is not found
*/ */
public static Class<?>[] getGenericClasses(Class<?> c, Class<?> superClass){ public static Class<?>[] getGenericClasses(Class<?> c, Class<?> superClass) {
if(superClass != null) { if (superClass != null) {
// Search for the super class // Search for the super class
while (c.getSuperclass() != null && c.getSuperclass() != Object.class) { while (c.getSuperclass() != null && c.getSuperclass() != Object.class) {
// Did we find the super class? // Did we find the super class?
@ -160,13 +160,13 @@ public class ClassUtil {
} }
return new Class[0]; return new Class[0];
} }
private static Class<?>[] getGenericClasses(Type genericType){ private static Class<?>[] getGenericClasses(Type genericType) {
if(genericType instanceof ParameterizedType){ if (genericType instanceof ParameterizedType) {
ParameterizedType aType = (ParameterizedType) genericType; ParameterizedType aType = (ParameterizedType) genericType;
Type[] argTypes = aType.getActualTypeArguments(); Type[] argTypes = aType.getActualTypeArguments();
Class<?>[] classArray = new Class<?>[argTypes.length]; Class<?>[] classArray = new Class<?>[argTypes.length];
for(int i=0; i<classArray.length; ++i) { for (int i=0; i<classArray.length; ++i) {
if(argTypes[i] instanceof Class) if (argTypes[i] instanceof Class)
classArray[i] = (Class<?>) argTypes[i]; classArray[i] = (Class<?>) argTypes[i];
} }
return classArray; return classArray;
@ -178,16 +178,16 @@ public class ClassUtil {
/** /**
* @return the first class in the stack that do not match the filter * @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); ArrayList filterStr = new ArrayList(filter.length + 1);
filterStr.add(ClassUtil.class.getName()); filterStr.add(ClassUtil.class.getName());
for (Class clazz : filter) for (Class clazz : filter)
filterStr.add(clazz.getName()); filterStr.add(clazz.getName());
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for(int i=1; i<stackTraceElements.length ;++i){ for (int i=1; i<stackTraceElements.length; ++i) {
String className = stackTraceElements[i].getClassName(); String className = stackTraceElements[i].getClassName();
if( !filterStr.contains(className) ){ if (!filterStr.contains(className)) {
return className; return className;
} }
} }

View file

@ -75,27 +75,27 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
/** /**
* A Constructor that takes a String containing 5 (or 6 for extended) individual fields in Cron format * 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"); String[] arr = cron.split("\\s");
if (arr.length < 5 || arr.length > 6) if (arr.length < 5 || arr.length > 6)
throw new IllegalArgumentException( 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]: "*")); 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 * 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, "*"); this(minute, hour, dayOfMonth, monthOfYear, dayOfWeek, "*");
} }
/** /**
* A Constructor that takes separate Strings for each field with an extended year field * 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); 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)); minutes = ArrayUtil.toIntArray(getRange(minute, 0, 59));
hours = ArrayUtil.toIntArray(getRange(hour, 0, 23)); hours = ArrayUtil.toIntArray(getRange(hour, 0, 23));
dayOfMonths = ArrayUtil.toIntArray(getRange(dayOfMonth, 1, 31)); dayOfMonths = ArrayUtil.toIntArray(getRange(dayOfMonth, 1, 31));
@ -105,14 +105,14 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
1970, 1970,
Calendar.getInstance().get(Calendar.YEAR)+30)); Calendar.getInstance().get(Calendar.YEAR)+30));
} }
protected static List<Integer> getRange(String str, int from, int to){ protected static List<Integer> getRange(String str, int from, int to) {
if (str == null || str.isEmpty()) if (str == null || str.isEmpty())
return Collections.emptyList(); return Collections.emptyList();
List<Integer> list = new LinkedList<>(); List<Integer> list = new LinkedList<>();
String[] commaArr = str.split(","); String[] commaArr = str.split(",");
if (commaArr.length > 1){ if (commaArr.length > 1) {
for (String section : commaArr) for (String section : commaArr)
list.addAll(getRange(section, from, to)); list.addAll(getRange(section, from, to));
} }
@ -128,20 +128,20 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
else { else {
String[] rangeArr; String[] rangeArr;
if (str.equals("*")) if (str.equals("*"))
rangeArr = new String[]{""+from, ""+to}; rangeArr = new String[]{"" +from, "" +to};
else else
rangeArr = str.split("-", 2); rangeArr = str.split("-", 2);
if (rangeArr.length == 2) { if (rangeArr.length == 2) {
int rangeFrom = Integer.parseInt(rangeArr[0]); int rangeFrom = Integer.parseInt(rangeArr[0]);
int rangeTo = Integer.parseInt(rangeArr[1]); int rangeTo = Integer.parseInt(rangeArr[1]);
if (from > rangeFrom || rangeTo > to) 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) for (int i = rangeFrom; i <= rangeTo; ++i)
list.add(i); list.add(i);
} else { } else {
int value = Integer.parseInt(str); int value = Integer.parseInt(str);
if (from > value || value > to) 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); list.add(value);
} }
} }
@ -153,7 +153,7 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
/** /**
* Set the TimeZone that should be used by the cron algorithm * Set the TimeZone that should be used by the cron algorithm
*/ */
public void setTimeZone(TimeZone timeZone){ public void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone; this.timeZone = timeZone;
} }
@ -279,7 +279,7 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
return cal.getTimeInMillis(); return cal.getTimeInMillis();
} }
protected Calendar getCalendar(long timestamp){ protected Calendar getCalendar(long timestamp) {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
if (timeZone != null) if (timeZone != null)
cal.setTimeZone(timeZone); cal.setTimeZone(timeZone);
@ -290,8 +290,8 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
/** /**
* Converts Calendar DAY_OF_WEEK enum to id starting from 1 (Monday) to 7 (Sunday) * Converts Calendar DAY_OF_WEEK enum to id starting from 1 (Monday) to 7 (Sunday)
*/ */
private int getDayOfWeekID(int calDayOfWeek){ private int getDayOfWeekID(int calDayOfWeek) {
switch (calDayOfWeek){ switch (calDayOfWeek) {
case Calendar.MONDAY: return 1; case Calendar.MONDAY: return 1;
case Calendar.TUESDAY: return 2; case Calendar.TUESDAY: return 2;
case Calendar.WEDNESDAY: return 3; case Calendar.WEDNESDAY: return 3;
@ -302,8 +302,8 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
} }
return -1; return -1;
} }
private int getDayOfWeekEnum(int dayId){ private int getDayOfWeekEnum(int dayId) {
switch (dayId){ switch (dayId) {
case 1: return Calendar.MONDAY; case 1: return Calendar.MONDAY;
case 2: return Calendar.TUESDAY; case 2: return Calendar.TUESDAY;
case 3: return Calendar.WEDNESDAY; case 3: return Calendar.WEDNESDAY;

View file

@ -137,7 +137,7 @@ public class Encrypter {
public Encrypter(String stringKey, Digest digest, Algorithm crypto, int iteration, int keyBitSize) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException { public Encrypter(String stringKey, Digest digest, Algorithm crypto, int iteration, int keyBitSize) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException {
// Generate the secret key specs. // Generate the secret key specs.
String instance = "PBKDF2With"+ digest; String instance = "PBKDF2With" + digest;
SecretKeyFactory factory = SecretKeyFactory.getInstance(instance); SecretKeyFactory factory = SecretKeyFactory.getInstance(instance);
KeySpec keySpec = new PBEKeySpec(stringKey.toCharArray(), salt, iteration, keyBitSize); KeySpec keySpec = new PBEKeySpec(stringKey.toCharArray(), salt, iteration, keyBitSize);
SecretKey tmp = factory.generateSecret(keySpec); SecretKey tmp = factory.generateSecret(keySpec);
@ -157,7 +157,7 @@ public class Encrypter {
* @param data is the data to encrypt * @param data is the data to encrypt
* @return The encrypted data * @return The encrypted data
*/ */
public byte[] encrypt(byte[] data){ public byte[] encrypt(byte[] data) {
try { try {
byte[] encryption = new byte[encipher.getOutputSize(data.length)]; byte[] encryption = new byte[encipher.getOutputSize(data.length)];
@ -186,7 +186,7 @@ public class Encrypter {
* @param encrypted is the encrypted data * @param encrypted is the encrypted data
* @return The decrypted data * @return The decrypted data
*/ */
public byte[] decrypt(byte[] encrypted){ public byte[] decrypt(byte[] encrypted) {
try { try {
byte[] dataTmp = new byte[encrypted.length]; byte[] dataTmp = new byte[encrypted.length];
int ptLength = decipher.update(encrypted, 0, encrypted.length, dataTmp, 0); int ptLength = decipher.update(encrypted, 0, encrypted.length, dataTmp, 0);
@ -215,21 +215,21 @@ public class Encrypter {
/** /**
* @return The key for this encrypter * @return The key for this encrypter
*/ */
public Key getKey(){ public Key getKey() {
return key; return key;
} }
/** /**
* @return the algorithm used by this encrypter * @return the algorithm used by this encrypter
*/ */
public String getAlgorithm(){ public String getAlgorithm() {
return key.getAlgorithm(); return key.getAlgorithm();
} }
/** /**
* Randomizes the salt for the key * Randomizes the salt for the key
*/ */
public static void randomizeSalt(){ public static void randomizeSalt() {
Random random = new Random(); Random random = new Random();
random.nextBytes(salt); random.nextBytes(salt);
} }

View file

@ -51,7 +51,7 @@ public class Hasher {
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
int read; int read;
try { try {
while( (read = is.read(buffer)) > 0) { while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read); digest.update(buffer, 0, read);
} }
byte[] md5sum = digest.digest(); byte[] md5sum = digest.digest();
@ -59,7 +59,7 @@ public class Hasher {
output = bigInt.toString(16); output = bigInt.toString(16);
} }
catch(IOException e) { 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(); is.close();
@ -72,7 +72,7 @@ public class Hasher {
* @param str is the String to hash * @param str is the String to hash
* @return an String containing the hash * @return an String containing the hash
*/ */
public static String MD5(String str){ public static String MD5(String str) {
try { try {
return hash(str, "MD5"); return hash(str, "MD5");
} catch (Exception e) { } catch (Exception e) {
@ -87,7 +87,7 @@ public class Hasher {
* @param object is the object to hash * @param object is the object to hash
* @return an String containing the hash * @return an String containing the hash
*/ */
public static String MD5(Serializable object){ public static String MD5(Serializable object) {
try { try {
return hash(object, "MD5"); return hash(object, "MD5");
} catch (Exception e) { } catch (Exception e) {
@ -118,7 +118,7 @@ public class Hasher {
* @param str is the String to hash * @param str is the String to hash
* @return an String containing the hash * @return an String containing the hash
*/ */
public static String SHA1(String str){ public static String SHA1(String str) {
try { try {
return hash(str, "SHA-1"); return hash(str, "SHA-1");
} catch (Exception e) { } catch (Exception e) {
@ -133,7 +133,7 @@ public class Hasher {
* @param object is the object to hash * @param object is the object to hash
* @return an String containing the hash * @return an String containing the hash
*/ */
public static String SHA1(Serializable object){ public static String SHA1(Serializable object) {
try { try {
return hash(object, "SHA-1"); return hash(object, "SHA-1");
} catch (Exception e) { } catch (Exception e) {
@ -149,7 +149,7 @@ public class Hasher {
* @param key is the key to use with the hash * @param key is the key to use with the hash
* @return an String containing 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()); return HMAC("HmacSHA256", str.getBytes(), key.getBytes());
} }
@ -161,7 +161,7 @@ public class Hasher {
* @param key is the key to use with the hash * @param key is the key to use with the hash
* @return an String containing 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 { try {
// Get an hmac_sha1 key from the raw key bytes // Get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key, algo); SecretKeySpec signingKey = new SecretKeySpec(key, algo);
@ -171,7 +171,7 @@ public class Hasher {
mac.init(signingKey); mac.init(signingKey);
// Compute the HMAC on input data bytes // Compute the HMAC on input data bytes
byte[] raw = mac.doFinal( data ); byte[] raw = mac.doFinal(data);
return Converter.toHexString(raw); return Converter.toHexString(raw);
} catch (Exception e) { } catch (Exception e) {
@ -180,7 +180,7 @@ public class Hasher {
return null; return null;
} }
public static String PBKDF2(String data, String salt, int iterations){ public static String PBKDF2(String data, String salt, int iterations) {
try { try {
PBEKeySpec spec = new PBEKeySpec( PBEKeySpec spec = new PBEKeySpec(
data.toCharArray(), data.toCharArray(),
@ -254,7 +254,7 @@ public class Hasher {
int h = seed ^ length; int h = seed ^ length;
int i=0; int i=0;
for(; i+4<length ;i+=4){ for (; i+4<length; i+=4) {
// get the first 4 bytes // get the first 4 bytes
int k = data[i+3] & 0xff; int k = data[i+3] & 0xff;
k <<= 8; k <<= 8;
@ -275,7 +275,7 @@ public class Hasher {
// Handle the last few bytes of the input // Handle the last few bytes of the input
i = length % 4; i = length % 4;
switch(i){ switch(i) {
case 3: h ^= data[length-3] << 16; case 3: h ^= data[length-3] << 16;
case 2: h ^= data[length-2] << 8; case 2: h ^= data[length-2] << 8;
case 1: h ^= data[length-1]; case 1: h ^= data[length-1];

View file

@ -44,13 +44,13 @@ public class InetUtil {
/** /**
* @return a list of IPv4 addresses for the all local network cards * @return a list of IPv4 addresses for the all local network cards
*/ */
public static List<InetAddress> getLocalInet4Address(){ public static List<InetAddress> getLocalInet4Address() {
ArrayList<InetAddress> ips = new ArrayList<>(); ArrayList<InetAddress> ips = new ArrayList<>();
try { try {
Enumeration<NetworkInterface> netIntf = NetworkInterface.getNetworkInterfaces(); Enumeration<NetworkInterface> netIntf = NetworkInterface.getNetworkInterfaces();
while(netIntf.hasMoreElements()){ while (netIntf.hasMoreElements()) {
Enumeration<InetAddress> addresses = netIntf.nextElement().getInetAddresses(); Enumeration<InetAddress> addresses = netIntf.nextElement().getInetAddresses();
while (addresses.hasMoreElements()){ while (addresses.hasMoreElements()) {
InetAddress ip = addresses.nextElement(); InetAddress ip = addresses.nextElement();
if (ip instanceof Inet4Address && ip.isSiteLocalAddress()) if (ip instanceof Inet4Address && ip.isSiteLocalAddress())
ips.add(ip); ips.add(ip);

View file

@ -53,10 +53,10 @@ public class MimeTypeUtil {
private static void readMimeFile(String path) throws IOException { private static void readMimeFile(String path) throws IOException {
DataNode json = JSONParser.read(FileUtil.getContent(path)); DataNode json = JSONParser.read(FileUtil.getContent(path));
for (Iterator<String> it = json.keyIterator(); it.hasNext(); ) { for (Iterator<String> it = json.keyIterator(); it.hasNext();) {
String primaryType = it.next(); String primaryType = it.next();
for (Iterator<String> it2 = json.get(primaryType).keyIterator(); it2.hasNext(); ) { for (Iterator<String> it2 = json.get(primaryType).keyIterator(); it2.hasNext();) {
String subType = it2.next(); String subType = it2.next();
DataNode mimeJson = json.get(primaryType).get(subType); 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); mimes.add(mime);
for (String extension : mime.getExtensions()) { for (String extension : mime.getExtensions()) {

View file

@ -46,7 +46,7 @@ public class OneInstanceFile implements OneInstance{
* *
* @param filename The name of the file to be locked * @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); this.file = new File(System.getProperty("user.home"), filename);
} }
@ -57,7 +57,7 @@ public class OneInstanceFile implements OneInstance{
*/ */
public boolean check() { public boolean check() {
boolean tmp = lockApp(); boolean tmp = lockApp();
if( tmp ) closeLock(); if (tmp) closeLock();
return !tmp; return !tmp;
} }

View file

@ -44,7 +44,7 @@ public class OneInstanceNetwork extends Thread implements OneInstance{
* *
* @param port The port to lock * @param port The port to lock
*/ */
public OneInstanceNetwork(int port){ public OneInstanceNetwork(int port) {
this.port = port; this.port = port;
} }
@ -53,7 +53,7 @@ public class OneInstanceNetwork extends Thread implements OneInstance{
* *
* @return Always true * @return Always true
*/ */
public boolean lockApp(){ public boolean lockApp() {
this.start(); this.start();
return true; return true;
} }

View file

@ -43,74 +43,74 @@ public class StringUtil {
* @param bytes size (in bytes) * @param bytes size (in bytes)
* @return string * @return string
*/ */
public static String formatByteSizeToString(long bytes){ public static String formatByteSizeToString(long bytes) {
int total = sizes.length-1; int total = sizes.length-1;
double value = bytes; double value = bytes;
for(; value > 1024 ;total--) { for (; value > 1024; total--) {
value /= 1024; value /= 1024;
} }
value = (double)( (int)(value*10) )/10; value = (double)((int)(value * 10)) / 10;
return value+" "+sizes[total]; return value + " " + sizes[total];
} }
/** /**
* @return a human readable String with year/month/day/hour/min/sec/milisec delimitation. * @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(); StringBuilder str = new StringBuilder();
long tmp; long tmp;
// Years // Years
if( milisec >= 31557032762.3361d ){ if (milisec >= 31557032762.3361d) {
tmp = (long) (milisec / 31557032762.3361d); tmp = (long) (milisec / 31557032762.3361d);
milisec -= tmp * 31557032762.3361d; milisec -= tmp * 31557032762.3361d;
if( tmp > 1 ) if (tmp > 1)
str.append(tmp).append(" years "); str.append(tmp).append(" years ");
else else
str.append(tmp).append(" year "); str.append(tmp).append(" year ");
} }
// Months // Months
if( milisec >= 2629743830L){ if (milisec >= 2629743830L) {
tmp = milisec / 2629743830L; tmp = milisec / 2629743830L;
milisec -= tmp * 2629743830L; milisec -= tmp * 2629743830L;
if( tmp > 1 ) if (tmp > 1)
str.append(tmp).append(" months "); str.append(tmp).append(" months ");
else else
str.append(tmp).append(" month "); str.append(tmp).append(" month ");
} }
// Days // Days
if( milisec >= 86400000 ){ if (milisec >= 86400000) {
tmp = milisec / 86400000; tmp = milisec / 86400000;
milisec -= tmp * 86400000; milisec -= tmp * 86400000;
if( tmp > 1 ) if (tmp > 1)
str.append(tmp).append(" days "); str.append(tmp).append(" days ");
else else
str.append(tmp).append(" day "); str.append(tmp).append(" day ");
} }
// Hours // Hours
if( milisec >= 3600000 ){ if (milisec >= 3600000) {
tmp = milisec / 3600000; tmp = milisec / 3600000;
milisec -= tmp * 3600000; milisec -= tmp * 3600000;
if( tmp > 1 ) if (tmp > 1)
str.append(tmp).append(" hours "); str.append(tmp).append(" hours ");
else else
str.append(tmp).append(" hour "); str.append(tmp).append(" hour ");
} }
// Minutes // Minutes
if( milisec >= 60000 ){ if (milisec >= 60000) {
tmp = milisec / 60000; tmp = milisec / 60000;
milisec -= tmp * 60000; milisec -= tmp * 60000;
str.append(tmp).append(" min "); str.append(tmp).append(" min ");
} }
// sec // sec
if( milisec >= 1000 ){ if (milisec >= 1000) {
tmp = milisec / 1000; tmp = milisec / 1000;
milisec -= tmp * 1000; milisec -= tmp * 1000;
str.append(tmp).append(" sec "); str.append(tmp).append(" sec ");
} }
if( milisec > 0 ){ if (milisec > 0) {
str.append(milisec).append(" milisec "); 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. * @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(); StringBuilder str = new StringBuilder().append(number).reverse();
while (str.length() < length) while (str.length() < length)
str.append('0'); 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 * @return a String containing all entries in the list with the specified delimiter in between entries
*/ */
@SafeVarargs @SafeVarargs
public static <T> String join(String delimiter, T... array){ public static <T> String join(String delimiter, T... array) {
return join(delimiter, Arrays.asList(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 * @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 * @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(); StringBuilder str = new StringBuilder();
Iterator<?> it = list.iterator(); Iterator<?> it = list.iterator();
if(it.hasNext()) { if (it.hasNext()) {
str.append(it.next().toString()); str.append(it.next().toString());
while (it.hasNext()) { while (it.hasNext()) {
str.append(delimiter).append(it.next().toString()); str.append(delimiter).append(it.next().toString());
@ -164,30 +164,30 @@ public class StringUtil {
* @param trim is the char to trim * @param trim is the char to trim
* @return a trimmed String * @return a trimmed String
*/ */
public static String trim(String str, char trim){ public static String trim(String str, char trim) {
if( str == null || str.isEmpty() ) if (str == null || str.isEmpty())
return str; return str;
int start=0, stop=str.length(); int start=0, stop=str.length();
// The beginning // The beginning
for(int i=0; i<str.length() ;i++){ for (int i=0; i<str.length(); i++) {
char c = str.charAt(i); char c = str.charAt(i);
if(c <= ' ' || c == trim) if (c <= ' ' || c == trim)
start = i+1; start = i + 1;
else else
break; break;
} }
// The end // The end
for(int i=str.length()-1; i>start ;i--){ for (int i=str.length()-1; i>start; i--) {
char c = str.charAt(i); char c = str.charAt(i);
if(c <= ' ' || c == trim) if (c <= ' ' || c == trim)
stop = i; stop = i;
else else
break; break;
} }
if(start >= str.length()) if (start >= str.length())
return ""; return "";
return str.substring(start, stop); return str.substring(start, stop);
@ -198,12 +198,12 @@ public class StringUtil {
* *
* @param str is the string to trim * @param str is the string to trim
*/ */
public static String trimQuotes(String str){ public static String trimQuotes(String str) {
if( str == null ) if (str == null)
return null; return null;
str = str.trim(); 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); str = str.substring(1, str.length()-1);
} }
@ -216,10 +216,10 @@ public class StringUtil {
/** /**
* @return A string containing a specific amount of spaces * @return A string containing a specific amount of spaces
*/ */
public static String getSpaces(int i){ public static String getSpaces(int i) {
if(SPACES.size() <= i){ // Do we need to generate more spaces? 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 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()) if (SPACES.isEmpty())
SPACES.add(""); SPACES.add("");
for (int j = SPACES.size(); j <= i; j++) { for (int j = SPACES.size(); j <= i; j++) {
@ -242,7 +242,7 @@ public class StringUtil {
* @param delimiter a single character delimiter * @param delimiter a single character delimiter
* @return a List with all data between the delimiter * @return a List with all data between the delimiter
*/ */
public static List<String> split(String str, char delimiter){ public static List<String> split(String str, char delimiter) {
ArrayList<String> splitList = new ArrayList<>(); ArrayList<String> splitList = new ArrayList<>();
int from = 0, to = 0; int from = 0, to = 0;

View file

@ -44,7 +44,7 @@ public class Timer {
* *
* @param millisecond the time in milliseconds that the timeout should happen. * @param millisecond the time in milliseconds that the timeout should happen.
*/ */
public Timer(long millisecond){ public Timer(long millisecond) {
this.period = millisecond; this.period = millisecond;
reset(); reset();
} }
@ -54,7 +54,7 @@ public class Timer {
* *
* @return a reference of itself * @return a reference of itself
*/ */
public Timer start(){ public Timer start() {
timestamp = System.currentTimeMillis(); timestamp = System.currentTimeMillis();
return this; return this;
} }
@ -62,21 +62,21 @@ public class Timer {
/** /**
* Will reset the timer so that {@link #hasTimedOut()} returns true * Will reset the timer so that {@link #hasTimedOut()} returns true
*/ */
public void reset(){ public void reset() {
timestamp = -1; timestamp = -1;
} }
/** /**
* @return true if the timer has timed out or has been reset, false if timer is running * @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(); return timestamp + period < System.currentTimeMillis();
} }
public String toString(){ public String toString() {
if (hasTimedOut()) if (hasTimedOut())
return "Timed out"; return "Timed out";
else else
return "Timeout in "+StringUtil.formatTimeToString((timestamp+period)-System.currentTimeMillis()); return "Timeout in " +StringUtil.formatTimeToString((timestamp+period)-System.currentTimeMillis());
} }
} }

View file

@ -38,18 +38,18 @@ import java.util.LinkedList;
*/ */
public class EuclideansAlgo { public class EuclideansAlgo {
public static void main(String[] args){ public static void main(String[] args) {
MultiPrintStream.out.println("*** Correct Answer: "); 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("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("GCD: 1");
MultiPrintStream.out.println("*** Integer:"); MultiPrintStream.out.println("*** Integer:");
MultiPrintStream.out.dump(calcGenerators(60728973, 160523347)); 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.println("*** BigInteger: ");
MultiPrintStream.out.dump(calcGenerators(new BigInteger("60728973"), new BigInteger("160523347"))); 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 * @param b is the second integer
* @return a integer containing the GCD of the integers * @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; int t;
while( b != 0 ){ while (b != 0) {
t = b; t = b;
b = a % b; b = a % b;
a = t; a = t;
@ -79,12 +79,12 @@ public class EuclideansAlgo {
* @param b is the second BigInteger * @param b is the second BigInteger
* @return a BigInteger containing the GCD of the BigIntegers * @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; BigInteger t;
while( !b.equals(BigInteger.ZERO) ){ while (!b.equals(BigInteger.ZERO)) {
t = b; t = b;
b = a.mod( b ); b = a.mod(b);
a = t; a = t;
} }
@ -99,12 +99,12 @@ public class EuclideansAlgo {
* @param b is the second integer * @param b is the second integer
* @return a list of integers that is generators for a and b * @return a list of integers that is generators for a and b
*/ */
public static LinkedList<Integer> calcGenerators(int a, int b){ public static LinkedList<Integer> calcGenerators(int a, int b) {
LinkedList<Integer> list = new LinkedList<>(); LinkedList<Integer> list = new LinkedList<>();
int t; int t;
while( b != 0 ){ while (b != 0) {
list.add( a/b ); list.add(a / b);
t = b; t = b;
b = a % b; b = a % b;
a = t; a = t;
@ -121,14 +121,14 @@ public class EuclideansAlgo {
* @param b is the second BigInteger * @param b is the second BigInteger
* @return a list of BigIntegers that is generators of a and b * @return a list of BigIntegers that is generators of a and b
*/ */
public static LinkedList<BigInteger> calcGenerators(BigInteger a, BigInteger b){ public static LinkedList<BigInteger> calcGenerators(BigInteger a, BigInteger b) {
LinkedList<BigInteger> list = new LinkedList<>(); LinkedList<BigInteger> list = new LinkedList<>();
BigInteger t; BigInteger t;
while( !b.equals(BigInteger.ZERO) ){ while (!b.equals(BigInteger.ZERO)) {
list.add( new BigInteger("0").add( a.divide( b ) ) ); list.add(new BigInteger("0").add(a.divide(b)));
t = b; t = b;
b = a.mod( b ); b = a.mod(b);
a = t; a = t;
} }

View file

@ -55,8 +55,8 @@ public class LevenshteinDistance {
public static int getDistance(String str1, String str2, int[][] matrix) { public static int getDistance(String str1, String str2, int[][] matrix) {
int len1 = str1.length()+1; int len1 = str1.length()+1;
int len2 = str2.length()+1; int len2 = str2.length()+1;
if(matrix.length < len1 || matrix[0].length < len2) 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"); 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 // source prefixes can be transformed into empty string by
// dropping all characters // dropping all characters
@ -82,19 +82,19 @@ public class LevenshteinDistance {
/* /*
System.out.println(); System.out.println();
for (int j=0; j < len2+1; j++) { for (int j=0; j < len2+1; j++) {
if(j>1) if (j>1)
System.out.print(str2.charAt(j-2)+" "); System.out.print(str2.charAt(j-2) + " ");
else else
System.out.print("_ "); System.out.print("_ ");
for (int i=0; i < len1+1; i++) { for (int i=0; i < len1+1; i++) {
if(j==0) { if (j==0) {
if (i > 1) if (i > 1)
System.out.print(str1.charAt(i - 2) + " "); System.out.print(str1.charAt(i - 2) + " ");
else if (i != 0) else if (i != 0)
System.out.print("_ "); System.out.print("_ ");
} }
else if (i != 0) else if (i != 0)
System.out.print(matrix[i-1][j-1]+" "); System.out.print(matrix[i-1][j-1] + " ");
} }
System.out.println(); System.out.println();
} }
@ -102,7 +102,7 @@ public class LevenshteinDistance {
return matrix[len1 - 1][len2 - 1]; 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; int i = (a < b) ? a : b;
return (i < c) ? i : c; return (i < c) ? i : c;
//return Math.min(i, Math.min(j, k)); //return Math.min(i, Math.min(j, k));

View file

@ -33,47 +33,47 @@ import java.math.BigInteger;
* @see <a href="http://en.wikipedia.org/wiki/Shanks-Tonelli_algorithm">Wikipedia</a> * @see <a href="http://en.wikipedia.org/wiki/Shanks-Tonelli_algorithm">Wikipedia</a>
*/ */
public class ShanksTonelliAlgo { public class ShanksTonelliAlgo {
public static BigInteger calc(BigInteger n, BigInteger p){ public static BigInteger calc(BigInteger n, BigInteger p) {
BigInteger nOrg = n; BigInteger nOrg = n;
BigInteger S = null, V, R, U, X; BigInteger S = null, V, R, U, X;
BigInteger ONE = BigInteger.ONE; BigInteger ONE = BigInteger.ONE;
BigInteger TWO = BigInteger.valueOf( 2 ); BigInteger TWO = BigInteger.valueOf(2);
BigInteger Q = p.add( ONE ).divide( TWO ); BigInteger Q = p.add(ONE).divide(TWO);
switch( p.mod( BigInteger.valueOf(4) ).intValue() ){ switch (p.mod(BigInteger.valueOf(4)).intValue()) {
case 3: case 3:
S = n.pow( Q.divide( TWO ).intValue() ).mod( p ); S = n.pow(Q.divide(TWO).intValue()).mod(p);
break; break;
case 1: case 1:
S = ONE; S = ONE;
n = n.subtract( ONE ); n = n.subtract(ONE);
while (n.divide( p ).compareTo( ONE ) == 0) { while (n.divide(p).compareTo(ONE) == 0) {
S = S.add( ONE ); S = S.add(ONE);
//n = (n-2s+1) mod p //n = (n-2s+1) mod p
n = n.subtract( TWO.multiply( S ) ).add( ONE ).mod( p ); n = n.subtract(TWO.multiply(S)).add(ONE).mod(p);
if (n.compareTo( BigInteger.ZERO ) == 0){ if (n.compareTo(BigInteger.ZERO) == 0) {
return S; return S;
} }
} }
Q = Q.divide( TWO ); Q = Q.divide(TWO);
V = ONE; V = ONE;
R = S; R = S;
U = ONE; U = ONE;
while (Q.compareTo( BigInteger.ZERO ) > 0) { while (Q.compareTo(BigInteger.ZERO) > 0) {
X = R.pow(2).subtract( n.multiply( U.pow(2) ) ).mod( p ); X = R.pow(2).subtract(n.multiply(U.pow(2))).mod(p);
U = TWO.multiply( R ).multiply( U ).mod( p ); U = TWO.multiply(R).multiply(U).mod(p);
R = X; R = X;
if ( Q.testBit(0) ){ if (Q.testBit(0)) {
X = S.multiply( R ).subtract( n.multiply(V).multiply(U) ).mod( p ); X = S.multiply(R).subtract(n.multiply(V).multiply(U)).mod(p);
V = V.multiply(R).add( S.multiply(U) ).mod( p ); V = V.multiply(R).add(S.multiply(U)).mod(p);
S = X; 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; return null;
} }
@ -87,21 +87,21 @@ public class ShanksTonelliAlgo {
p-1 = ( 2^S )/( 1-p ) * 2^S; p-1 = ( 2^S )/( 1-p ) * 2^S;
// R = n^( (Q+1)/2 ) mod p // 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^Q mod p
V = W.pow( Q.intValue() ).mod( p ); V = W.pow(Q.intValue()).mod(p);
for(int i=S.intValue(); true ;){ for (int i=S.intValue(); true;) {
while( true ){ while (true) {
i--; i--;
// 1 = ( ( R^2 * n^-1 )^2^i ) mod p // 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; break;
} }
if(i == 0) return R; if (i == 0) return R;
//R = ( RV^(2^(S-i-1)) ) mod p //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 );
} }
*/ */
} }

View file

@ -48,7 +48,7 @@ public class WienersAlgo {
* First index is p and second is q. * First index is p and second is q.
* If no value was found then it returns null. * 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; BigInteger[] ret;
LinkedList<BigInteger> gen = EuclideansAlgo.calcGenerators(e, n); LinkedList<BigInteger> gen = EuclideansAlgo.calcGenerators(e, n);
@ -59,30 +59,30 @@ public class WienersAlgo {
BigInteger d1 = BigInteger.ONE; BigInteger d1 = BigInteger.ONE;
BigInteger t, n1, g; BigInteger t, n1, g;
while(!gen.isEmpty()){ while (!gen.isEmpty()) {
g = gen.poll(); g = gen.poll();
t = c1; t = c1;
c1 = g.multiply( c1 ).add( c0 ); c1 = g.multiply(c1).add(c0);
c0 = t; c0 = t;
t = d1; t = d1;
d1 = g.multiply( d1 ).add( d0 ); d1 = g.multiply(d1).add(d0);
d0 = t; d0 = t;
// (d1*e-1) % c1 == 0 // (d1*e-1) % c1 == 0
n1 = d1.multiply( e ).subtract( BigInteger.ONE ); n1 = d1.multiply(e).subtract(BigInteger.ONE);
if( n1.mod( c1 ).equals( BigInteger.ZERO ) ){ if (n1.mod(c1).equals(BigInteger.ZERO)) {
n1 = n1.divide( c1 ); n1 = n1.divide(c1);
// x^2 - ( n - n1 +1 )x + n = 0 // x^2 - ( n - n1 +1 )x + n = 0
ret = ZMath.pqFormula( ret = ZMath.pqFormula(
n.subtract( n1 ).add( BigInteger.ONE ).negate(), n.subtract(n1).add(BigInteger.ONE).negate(),
n); n);
if(ret[0].compareTo( BigInteger.ZERO ) >= 0 && if (ret[0].compareTo(BigInteger.ZERO) >= 0 &&
ret[1].compareTo( BigInteger.ZERO ) >= 0 && ret[1].compareTo(BigInteger.ZERO) >= 0 &&
ret[0].multiply( ret[1] ).equals( n )){ ret[0].multiply(ret[1]).equals(n)) {
return ret; return ret;
} }
} }

View file

@ -42,24 +42,24 @@ public class BreadthFirstSearch implements PathFinder{
* @param stop is the goal Node * @param stop is the goal Node
* @return A list with the path * @return A list with the path
*/ */
public LinkedList<PathNode> find(PathNode start, PathNode stop){ public LinkedList<PathNode> find(PathNode start, PathNode stop) {
Queue<PathNode> queue = new LinkedList<>(); Queue<PathNode> queue = new LinkedList<>();
HashSet<PathNode> visited = new HashSet<>(); HashSet<PathNode> visited = new HashSet<>();
queue.add(start); queue.add(start);
visited.add( start ); visited.add(start);
PathNode tmp; PathNode tmp;
while(!queue.isEmpty()){ while (!queue.isEmpty()) {
tmp = queue.poll(); tmp = queue.poll();
for(PathNode next : tmp.getNeighbors()){ for (PathNode next : tmp.getNeighbors()) {
if(!visited.contains( next ) && tmp.getNeighborCost(next) > 0){ if (!visited.contains(next) && tmp.getNeighborCost(next) > 0) {
queue.add(next); queue.add(next);
visited.add( next ); visited.add(next);
next.setParentNeighbor(tmp); next.setParentNeighbor(tmp);
if(next.equals(stop)){ if (next.equals(stop)) {
return stop.traversTo(start); return stop.traversTo(start);
} }
} }

View file

@ -42,10 +42,10 @@ public class DepthFirstSearch {
* @param stop Stop Node * @param stop Stop Node
* @return A list with the path * @return A list with the path
*/ */
public LinkedList<PathNode> find(PathNode start, PathNode stop){ public LinkedList<PathNode> find(PathNode start, PathNode stop) {
visited.clear(); visited.clear();
PathNode node = dfs(start, stop); 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 * @param node The node to search from
* @return The stop PathNode if a path was found else null * @return The stop PathNode if a path was found else null
*/ */
private PathNode dfs(PathNode node, PathNode stop){ private PathNode dfs(PathNode node, PathNode stop) {
visited.add( node ); visited.add(node);
if(node.equals(stop)){ if (node.equals(stop)) {
return node; return node;
} }
for(PathNode next : node.getNeighbors()){ for (PathNode next : node.getNeighbors()) {
if(!visited.contains( next ) && node.getNeighborCost(next) > 0){ if (!visited.contains(next) && node.getNeighborCost(next) > 0) {
next.setParentNeighbor(node); next.setParentNeighbor(node);
PathNode tmp = dfs(next, stop); PathNode tmp = dfs(next, stop);
if(tmp != null){ if (tmp != null) {
return tmp; return tmp;
} }
} }

View file

@ -36,7 +36,7 @@ public class StandardPathNode implements PathNode{
private HashMap<PathNode,Integer> neighbors; private HashMap<PathNode,Integer> neighbors;
private PathNode parent; private PathNode parent;
public StandardPathNode(){ public StandardPathNode() {
neighbors = new HashMap<>(); neighbors = new HashMap<>();
} }
@ -59,11 +59,11 @@ public class StandardPathNode implements PathNode{
public LinkedList<PathNode> traversTo(PathNode goal) { public LinkedList<PathNode> traversTo(PathNode goal) {
LinkedList<PathNode> path = new LinkedList<>(); LinkedList<PathNode> path = new LinkedList<>();
PathNode current = this; PathNode current = this;
while(current != null){ while (current != null) {
path.addFirst(current); path.addFirst(current);
current = current.getParentNeighbor(); current = current.getParentNeighbor();
if(goal.equals( current )){ if (goal.equals(current)) {
path.addFirst( goal ); path.addFirst(goal);
return path; return path;
} }
} }

View file

@ -37,7 +37,7 @@ import zutil.algo.sort.sortable.SortableDataList;
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
public class QuickSelect { 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); return find(list, k, 0, list.size()-1);
} }
@ -52,13 +52,13 @@ public class QuickSelect {
else else
return select(list, k, pivotNewIndex+1, right) 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 // select a pivot
int pivot = right/2; int pivot = right/2;
int newPivot = partition(list, left, right, pivot); int newPivot = partition(list, left, right, pivot);
if(k == newPivot) if (k == newPivot)
return list.get(k); return list.get(k);
else if(k < newPivot) else if (k < newPivot)
return find(list, k, left, newPivot-1); return find(list, k, left, newPivot-1);
else else
return find(list, k, newPivot+1, right); 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 swap list[right] and list[storeIndex] // Move pivot to its final place
return storeIndex 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); Object pivotValue = list.get(pivot);
list.swap(pivot, right); list.swap(pivot, right);
int storeIndex = left; int storeIndex = left;
for(int i=left; i<right ;i++){ for (int i=left; i<right; i++) {
if(list.compare(i, pivotValue) < 0){ if (list.compare(i, pivotValue) < 0) {
list.swap(storeIndex, i); list.swap(storeIndex, i);
storeIndex = storeIndex+1; storeIndex = storeIndex + 1;
} }
} }
list.swap(right, storeIndex); list.swap(right, storeIndex);

View file

@ -89,7 +89,7 @@ public class ExternalSort {
* *
* @param files a list of files to be merged * @param files a list of files to be merged
*/ */
private void mergeFiles(LinkedList<File> files){ private void mergeFiles(LinkedList<File> files) {
try { try {
BufferedReader[] chunkReader = new BufferedReader[files.size()]; BufferedReader[] chunkReader = new BufferedReader[files.size()];
String[] rows = new String[files.size()]; String[] rows = new String[files.size()];
@ -97,23 +97,23 @@ public class ExternalSort {
boolean someFileStillHasRows = false; boolean someFileStillHasRows = false;
for (int i=0; i<files.size(); i++){ for (int i=0; i<files.size(); i++) {
chunkReader[i] = new BufferedReader(new FileReader(files.get(i))); chunkReader[i] = new BufferedReader(new FileReader(files.get(i)));
// get the first row // get the first row
String line = chunkReader[i].readLine(); String line = chunkReader[i].readLine();
if (line != null){ if (line != null) {
rows[i] = line; rows[i] = line;
someFileStillHasRows = true; someFileStillHasRows = true;
} }
else{ else {
rows[i] = null; rows[i] = null;
} }
} }
String row; String row;
while (someFileStillHasRows){ while (someFileStillHasRows) {
String min; String min;
int minIndex; int minIndex;
@ -128,16 +128,16 @@ public class ExternalSort {
} }
// check which one is minimum // check which one is minimum
for(int i=1; i<rows.length ;i++){ for (int i=1; i<rows.length; i++) {
row = rows[i]; row = rows[i];
if (min!=null) { if (min != null) {
if(row!=null && row.compareTo(min) < 0){ if (row != null && row.compareTo(min) < 0) {
minIndex = i; minIndex = i;
min = row; min = row;
} }
} }
else{ else {
if(row!=null){ if (row != null) {
min = row; min = row;
minIndex = i; minIndex = i;
} }
@ -147,27 +147,27 @@ public class ExternalSort {
if (minIndex < 0) { if (minIndex < 0) {
someFileStillHasRows = false; someFileStillHasRows = false;
} }
else{ else {
// write to the sorted file // write to the sorted file
out.append(rows[minIndex]); out.append(rows[minIndex]);
out.newLine(); out.newLine();
// get another row from the file that had the min // get another row from the file that had the min
String line = chunkReader[minIndex].readLine(); String line = chunkReader[minIndex].readLine();
if (line != null){ if (line != null) {
rows[minIndex] = line; rows[minIndex] = line;
} }
else{ else {
rows[minIndex] = null; rows[minIndex] = null;
} }
} }
// check if one still has rows // check if one still has rows
someFileStillHasRows = false; someFileStillHasRows = false;
for(int i=0; i<rows.length ; i++){ for (int i=0; i<rows.length; i++) {
if(rows[i] != null){ if (rows[i] != null) {
if (minIndex < 0){ if (minIndex < 0) {
throw(new IOException("Error sorting!!!")); throw new IOException("Error sorting!!!");
} }
someFileStillHasRows = true; someFileStillHasRows = true;
break; break;
@ -175,13 +175,13 @@ public class ExternalSort {
} }
// check the actual files one more time // check the actual files one more time
if (!someFileStillHasRows){ if (!someFileStillHasRows) {
//write the last one not covered above //write the last one not covered above
for(int i=0; i<rows.length ; i++){ for (int i=0; i<rows.length; i++) {
if (rows[i] == null){ if (rows[i] == null) {
String line = chunkReader[i].readLine(); String line = chunkReader[i].readLine();
if (line != null){ if (line != null) {
someFileStillHasRows=true; someFileStillHasRows = true;
rows[i] = line; rows[i] = line;
} }
} }
@ -190,11 +190,11 @@ public class ExternalSort {
} }
// close all the files // close all the files
out.close(); out.close();
for(int i=0; i<chunkReader.length ; i++){ for (int i=0; i<chunkReader.length; i++) {
chunkReader[i].close(); chunkReader[i].close();
} }
} }
catch (Exception ex){ catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
System.exit(-1); System.exit(-1);
} }
@ -215,10 +215,10 @@ public class ExternalSort {
//QuickSort.sort(new SortableLinkedList(chunk)); //QuickSort.sort(new SortableLinkedList(chunk));
Collections.sort(chunk); Collections.sort(chunk);
File file = new File("extsort"+chunkFiles.size()+".txt"); File file = new File("extsort" + chunkFiles.size() + ".txt");
chunkFiles.add(file); chunkFiles.add(file);
writeChunk(chunk,file); writeChunk(chunk,file);
}while(!chunk.isEmpty()); }while (!chunk.isEmpty());
return chunkFiles; return chunkFiles;
} }
@ -232,9 +232,9 @@ public class ExternalSort {
private LinkedList<String> readChunk(BufferedReader in) throws IOException{ private LinkedList<String> readChunk(BufferedReader in) throws IOException{
LinkedList<String> list = new LinkedList<>(); LinkedList<String> list = new LinkedList<>();
String tmp; String tmp;
for(int i=0; i<CHUNK_SIZE ;i++){ for (int i=0; i<CHUNK_SIZE; i++) {
tmp = in.readLine(); tmp = in.readLine();
if(tmp == null) break; if (tmp == null) break;
list.add(tmp); list.add(tmp);
} }
return list; return list;
@ -256,7 +256,7 @@ public class ExternalSort {
out.close(); out.close();
} }
private void removeFiles(LinkedList<File> list){ private void removeFiles(LinkedList<File> list) {
for (File file : list) { for (File file : list) {
file.delete(); file.delete();
} }

View file

@ -34,8 +34,8 @@ public class MergeSort{
* *
* @param list is the list to sort * @param list is the list to sort
*/ */
public static void sort(int[] list){ public static void sort(int[] list) {
if(list == null) if (list == null)
return; return;
sort(list, 0, list.length); sort(list, 0, list.length);
@ -49,10 +49,10 @@ public class MergeSort{
* @param start is the starting index of the sub list * @param start is the starting index of the sub list
* @param stop is the end 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){ protected static void sort(int[] list, int start, int stop) {
if(stop-start <= 1) return; if (stop-start <= 1) return;
int pivot = start+(stop-start)/2; int pivot = start + (stop - start) / 2;
sort(list, start, pivot); sort(list, start, pivot);
sort(list, pivot, stop); sort(list, pivot, stop);
@ -69,7 +69,7 @@ public class MergeSort{
* @param stop is the end of the second sublist * @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. * @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 length = pivot-start;
int[] tmp = new int[stop-start]; int[] tmp = new int[stop-start];
@ -77,12 +77,11 @@ public class MergeSort{
int index1 = 0; int index1 = 0;
int index2 = length; int index2 = length;
for(int i=start; i<stop ;++i){ for (int i=start; i<stop; ++i) {
if( index2 < stop-start && (index1 >= length || tmp[index1] > tmp[index2]) ){ if (index2 < stop-start && (index1 >= length || tmp[index1] > tmp[index2])) {
list[i] = tmp[index2]; list[i] = tmp[index2];
++index2; ++index2;
} } else {
else {
list[i] = tmp[index1]; list[i] = tmp[index1];
++index1; ++index1;
} }
@ -96,8 +95,8 @@ public class MergeSort{
* *
* @param list is the list to sort * @param list is the list to sort
*/ */
public static void sort(SortableDataList<?> list){ public static void sort(SortableDataList<?> list) {
if(list == null) if (list == null)
return; return;
sort(list, 0, list.size()); sort(list, 0, list.size());
@ -111,8 +110,8 @@ public class MergeSort{
* @param start is the starting index of the sub list * @param start is the starting index of the sub list
* @param stop is the end 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){ protected static void sort(SortableDataList<?> list, int start, int stop) {
if(stop-start <= 1) return; if (stop-start <= 1) return;
int pivot = start+(stop-start)/2; int pivot = start+(stop-start)/2;
sort(list, start, pivot); 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. * @param pivot is the end index for the first list and the beginning of the second.
*/ */
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
protected static <T> void merge(SortableDataList<T> list, int start, int stop, int pivot){ protected static <T> void merge(SortableDataList<T> list, int start, int stop, int pivot) {
int length = pivot-start; int length = pivot-start;
Object[] tmp = new Object[stop-start]; Object[] tmp = new Object[stop-start];
for(int i=0; i<tmp.length ;++i){ for (int i=0; i<tmp.length; ++i) {
tmp[i] = list.get( start+i ); tmp[i] = list.get(start + i);
} }
int index1 = 0; int index1 = 0;
int index2 = length; int index2 = length;
for(int i=start; i<stop ;++i){ for (int i=start; i<stop; ++i) {
if( index2 < stop-start && (index1 >= length || ((Comparable)tmp[index1]).compareTo(tmp[index2]) > 0 )){ if (index2 < stop-start && (index1 >= length || ((Comparable)tmp[index1]).compareTo(tmp[index2]) > 0)) {
list.set(i, (T)tmp[index2]); list.set(i, (T) tmp[index2]);
++index2; ++index2;
} } else {
else { list.set(i, (T) tmp[index1]);
list.set(i, (T)tmp[index1]);
++index1; ++index1;
} }
} }

View file

@ -42,7 +42,7 @@ public class QuickSort{
* *
* @param list is the list to sort. * @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(list, 0, list.size()-1, MIDDLE_PIVOT, true);
} }
@ -53,7 +53,7 @@ public class QuickSort{
* @param type is the type of pivot * @param type is the type of pivot
* @param insert is if insertion sort will be used * @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); sort(list, 0, list.size()-1, type, insert);
} }
@ -68,41 +68,41 @@ public class QuickSort{
* @param type is the type of pivot to use * @param type is the type of pivot to use
*/ */
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
public static void sort(SortableDataList list, int start, int stop, int type, boolean insertionSort){ public static void sort(SortableDataList list, int start, int stop, int type, boolean insertionSort) {
if(stop-start <= 15 && insertionSort){ if (stop-start <= 15 && insertionSort) {
SimpleSort.insertionSort( list, start, stop); SimpleSort.insertionSort(list, start, stop);
} }
int pivotIndex = pivot(list,start,stop,type); int pivotIndex = pivot(list,start,stop,type);
Object pivot = list.get(pivotIndex); Object pivot = list.get(pivotIndex);
int left=start, right=stop; int left=start, right=stop;
do{ do{
while(list.compare(left, pivot) < 0){ while (list.compare(left, pivot) < 0) {
left++; left++;
} }
while(list.compare(right, pivot) > 0){ while (list.compare(right, pivot) > 0) {
right--; right--;
} }
if(left <= right){ if (left <= right) {
list.swap(left, right); list.swap(left, right);
left++; left++;
right--; right--;
} }
}while(left <= right); }while (left <= right);
if(start < right){ if (start < right) {
sort(list, start, right, type, insertionSort); sort(list, start, right, type, insertionSort);
} }
if(left < stop){ if (left < stop) {
sort(list, left, stop, type, insertionSort); sort(list, left, stop, type, insertionSort);
} }
} }
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
private static int pivot(SortableDataList<?> list, int start, int stop,int type){ private static int pivot(SortableDataList<?> list, int start, int stop,int type) {
switch(type){ switch(type) {
case RANDOM_PIVOT: case RANDOM_PIVOT:
return start+(int)(Math.random()*(stop-start)); return start+(int)(Math.random()*(stop-start));
case MEDIAN_PIVOT: case MEDIAN_PIVOT:
@ -111,9 +111,9 @@ public class QuickSort{
(Comparable)list.get(list.size()/2), (Comparable)list.get(list.size()/2),
(Comparable)list.get(list.size()-1)}; (Comparable)list.get(list.size()-1)};
SimpleSort.insertionSort(new SortableComparableArray(i)); 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; 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; return stop;
else else
return start+(stop-start)/2; return start+(stop-start)/2;

View file

@ -38,11 +38,11 @@ public class Randomizer {
* Randomizes the index of all the elements * Randomizes the index of all the elements
* @param list The list * @param list The list
*/ */
@SuppressWarnings({ "rawtypes" }) @SuppressWarnings({"rawtypes"})
public static void sort(SortableDataList list){ public static void sort(SortableDataList list) {
int size = list.size(); int size = list.size();
for(int i=0; i<size ;i++){ for (int i=0; i<size; i++) {
list.swap(i, (int)(Math.random()*size)); list.swap(i, (int) (Math.random() * size));
} }
} }
} }

View file

@ -41,7 +41,7 @@ public class SimpleSort{
* *
* @param list is the list to sort. * @param list is the list to sort.
*/ */
public static void bubbleSort(SortableDataList<?> list){ public static void bubbleSort(SortableDataList<?> list) {
bubbleSort(list, 0, list.size()); bubbleSort(list, 0, list.size());
} }
/** /**
@ -53,10 +53,10 @@ public class SimpleSort{
* @param start is the index to start from * @param start is the index to start from
* @param stop is the index to stop * @param stop is the index to stop
*/ */
public static void bubbleSort(SortableDataList<?> list, int start, int stop){ public static void bubbleSort(SortableDataList<?> list, int start, int stop) {
for(int i=start; i<stop ;++i){ for (int i=start; i<stop; ++i) {
for(int j=stop-2; i<=j ;--j){ for (int j=stop-2; i<=j; --j) {
if(list.compare(j, j+1) > 0){ if (list.compare(j, j+1) > 0) {
list.swap(j, j+1); list.swap(j, j+1);
} }
} }
@ -70,7 +70,7 @@ public class SimpleSort{
* *
* @param list is the list to sort. * @param list is the list to sort.
*/ */
public static void selectionSort(SortableDataList<?> list){ public static void selectionSort(SortableDataList<?> list) {
selectionSort(list, 0, list.size()); selectionSort(list, 0, list.size());
} }
/** /**
@ -82,7 +82,7 @@ public class SimpleSort{
* @param start is the index to start from * @param start is the index to start from
* @param stop is the index to stop * @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++) { 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; int m = i;
@ -102,7 +102,7 @@ public class SimpleSort{
* *
* @param list is a list to sort. * @param list is a list to sort.
*/ */
public static void insertionSort(SortableDataList<?> list){ public static void insertionSort(SortableDataList<?> list) {
insertionSort(list, 0, list.size()); insertionSort(list, 0, list.size());
} }
/** /**
@ -114,9 +114,9 @@ public class SimpleSort{
* @param start is the index to start from * @param start is the index to start from
* @param stop is the index to stop * @param stop is the index to stop
*/ */
public static void insertionSort(SortableDataList<?> list, int start, int stop){ public static void insertionSort(SortableDataList<?> list, int start, int stop) {
for(int i=start; i<stop ;++i){ for (int i=start; i<stop; ++i) {
for(int j=i; start<j && list.compare(j-1, j)>0 ;--j){ for (int j=i; start<j && list.compare(j-1, j)>0; --j) {
list.swap(j-1, j); list.swap(j-1, j);
} }
} }

View file

@ -30,7 +30,7 @@ import java.util.ArrayList;
public class SortableArrayList<T> implements SortableDataList<T>{ public class SortableArrayList<T> implements SortableDataList<T>{
private ArrayList<T> list; private ArrayList<T> list;
public SortableArrayList(ArrayList<T> list){ public SortableArrayList(ArrayList<T> list) {
this.list = list; this.list = list;
} }
@ -38,7 +38,7 @@ public class SortableArrayList<T> implements SortableDataList<T>{
return list.get(i); return list.get(i);
} }
public void set(int i, T o){ public void set(int i, T o) {
list.set(i, o); list.set(i, o);
} }

View file

@ -28,7 +28,7 @@ package zutil.algo.sort.sortable;
public class SortableComparableArray implements SortableDataList<Comparable>{ public class SortableComparableArray implements SortableDataList<Comparable>{
private Comparable[] list; private Comparable[] list;
public SortableComparableArray(Comparable[] list){ public SortableComparableArray(Comparable[] list) {
this.list = list; this.list = list;
} }
@ -36,7 +36,7 @@ public class SortableComparableArray implements SortableDataList<Comparable>{
return list[i]; return list[i];
} }
public void set(int i, Comparable o){ public void set(int i, Comparable o) {
list[i] = o; list[i] = o;
} }
@ -51,20 +51,20 @@ public class SortableComparableArray implements SortableDataList<Comparable>{
} }
public int compare(int a, int b) { public int compare(int a, int b) {
if(list[a].compareTo(list[b]) < 0){ if (list[a].compareTo(list[b]) < 0) {
return -1; return -1;
} }
else if(list[a].compareTo(list[b]) > 0){ else if (list[a].compareTo(list[b]) > 0) {
return 1; return 1;
} }
return 0; return 0;
} }
public int compare(int a, Comparable b) { public int compare(int a, Comparable b) {
if(list[a].compareTo(b) < 0){ if (list[a].compareTo(b) < 0) {
return -1; return -1;
} }
else if(list[a].compareTo(b) > 0){ else if (list[a].compareTo(b) > 0) {
return 1; return 1;
} }
return 0; return 0;

View file

@ -27,7 +27,7 @@ package zutil.algo.sort.sortable;
public class SortableIntArray implements SortableDataList<Integer>{ public class SortableIntArray implements SortableDataList<Integer>{
private int[] list; private int[] list;
public SortableIntArray(int[] list){ public SortableIntArray(int[] list) {
this.list = list; this.list = list;
} }
@ -35,7 +35,7 @@ public class SortableIntArray implements SortableDataList<Integer>{
return list[i]; return list[i];
} }
public void set(int i, Integer o){ public void set(int i, Integer o) {
list[i] = o; list[i] = o;
} }
@ -50,20 +50,20 @@ public class SortableIntArray implements SortableDataList<Integer>{
} }
public int compare(int a, int b) { public int compare(int a, int b) {
if(list[a] < list[b]){ if (list[a] < list[b]) {
return -1; return -1;
} }
else if(list[a] > list[b]){ else if (list[a] > list[b]) {
return 1; return 1;
} }
return 0; return 0;
} }
public int compare(int a, Integer b) { public int compare(int a, Integer b) {
if(list[a] < b){ if (list[a] < b) {
return -1; return -1;
} }
else if(list[a] > b){ else if (list[a] > b) {
return 1; return 1;
} }
return 0; return 0;

View file

@ -30,7 +30,7 @@ import java.util.LinkedList;
public class SortableLinkedList<T> implements SortableDataList<T>{ public class SortableLinkedList<T> implements SortableDataList<T>{
private LinkedList<T> list; private LinkedList<T> list;
public SortableLinkedList(LinkedList<T> list){ public SortableLinkedList(LinkedList<T> list) {
this.list = list; this.list = list;
} }
@ -38,7 +38,7 @@ public class SortableLinkedList<T> implements SortableDataList<T>{
return list.get(i); return list.get(i);
} }
public void set(int i, T o){ public void set(int i, T o) {
list.set(i, o); list.set(i, o);
} }

View file

@ -37,7 +37,7 @@ public class Gravatar {
* @param email the email assosicated with the avatar * @param email the email assosicated with the avatar
* @return a http url as a String that points to a avatar image * @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); return getImageUrl(email, null, -1);
} }
/** /**
@ -45,7 +45,7 @@ public class Gravatar {
* @param size the requested image size. default is 80px * @param size the requested image size. default is 80px
* @return a http url as a String that points to a avatar image * @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); return getImageUrl(email, null, size);
} }
/** /**
@ -53,7 +53,7 @@ public class Gravatar {
* @param format the picture file format. e.g. "jpg", "png" * @param format the picture file format. e.g. "jpg", "png"
* @return a http url as a String that points to a avatar image * @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); return getImageUrl(email, format, -1);
} }
/** /**
@ -62,9 +62,9 @@ public class Gravatar {
* @param size the requested image size. default is 80px * @param size the requested image size. default is 80px
* @return a http url as a String that points to a avatar image * @return a http url as a String that points to a avatar image
*/ */
public static String getImageUrl(String email, String format, int size){ public static String getImageUrl(String email, String format, int size) {
String formatStr = (format!=null ? "."+format : ""); String formatStr = (format!=null ? "." + format : "");
String sizeStr = (size > 0 ? "?size="+size : ""); String sizeStr = (size > 0 ? "?size=" + size : "");
return new StringBuilder(GRAVATAR_IMG_PREFIX) return new StringBuilder(GRAVATAR_IMG_PREFIX)
.append(getHash(email)) .append(getHash(email))
.append(formatStr) .append(formatStr)
@ -73,8 +73,8 @@ public class Gravatar {
} }
private static String getHash(String email){ private static String getHash(String email) {
email = (""+email).trim(); email = ("" + email).trim();
email = email.toLowerCase(); email = email.toLowerCase();
return Hasher.MD5(email); return Hasher.MD5(email);
} }

View file

@ -43,15 +43,15 @@ public abstract class AbstractChart extends JPanel{
protected void paintComponent(Graphics g){ protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g; Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON); RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR); RenderingHints.VALUE_INTERPOLATION_BILINEAR);
Rectangle bound = drawAxis( g2, new Rectangle(0, 0, getWidth(), getHeight())); Rectangle bound = drawAxis(g2, new Rectangle(0, 0, getWidth(), getHeight()));
drawChart( g2, bound ); drawChart(g2, bound);
} }
@ -79,7 +79,7 @@ public abstract class AbstractChart extends JPanel{
* *
* @param data is the data to draw * @param data is the data to draw
*/ */
public void setChartData(ChartData data){ public void setChartData(ChartData data) {
this.data = data; this.data = data;
} }
@ -91,7 +91,7 @@ public abstract class AbstractChart extends JPanel{
* @param bound is the drawing bounds * @param bound is the drawing bounds
* @return a x pixel coordinate * @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; return bound.x + x * scale;
} }
@ -103,15 +103,15 @@ public abstract class AbstractChart extends JPanel{
* @param bound is the drawing bounds * @param bound is the drawing bounds
* @return a y pixel coordinate * @return a y pixel coordinate
*/ */
static protected double getYCoordinate(double y, double scale, Rectangle bound){ static protected double getYCoordinate(double y, double scale, Rectangle bound) {
return bound.y + bound.height - ( y * scale ); 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())); 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())); return (double) bound.height / (Math.abs(data.getMaxY()) + Math.abs(data.getMinY()));
} }
} }

View file

@ -41,55 +41,55 @@ public class ChartData {
private ArrayList<Point> points; private ArrayList<Point> points;
public ChartData(){ public ChartData() {
xStrings = new HashMap<>(); xStrings = new HashMap<>();
yStrings = new HashMap<>(); yStrings = new HashMap<>();
points = new ArrayList<>(); points = new ArrayList<>();
} }
public void setXValueString(int x, String name){ public void setXValueString(int x, String name) {
xStrings.put(x, name); xStrings.put(x, name);
} }
public void setYValueString(int y, String name){ public void setYValueString(int y, String name) {
yStrings.put(y, name); yStrings.put(y, name);
} }
public void addPoint(int x, int y){ public void addPoint(int x, int y) {
points.add( new Point( x, y)); points.add(new Point(x, y));
setMaxMin(x, y); setMaxMin(x, y);
} }
private void setMaxMin(int x, int y){ private void setMaxMin(int x, int y) {
if( x > maxX) maxX = x; if (x > maxX) maxX = x;
if( x < minX) minX = x; if (x < minX) minX = x;
if( y > maxY) maxY = y; if (y > maxY) maxY = y;
if( y < minY) minY = y; if (y < minY) minY = y;
} }
public int getMaxX(){ public int getMaxX() {
return maxX; return maxX;
} }
public int getMinX(){ public int getMinX() {
return minX; return minX;
} }
public int getMaxY(){ public int getMaxY() {
return maxY; return maxY;
} }
public int getMinY(){ public int getMinY() {
return minY; return minY;
} }
public String getXString(int x){ public String getXString(int x) {
return xStrings.get(x); return xStrings.get(x);
} }
public String getYString(int y){ public String getYString(int y) {
return yStrings.get(y); return yStrings.get(y);
} }
protected List<Point> getData(){ protected List<Point> getData() {
return points; return points;
} }
} }

View file

@ -33,8 +33,8 @@ import java.awt.geom.Line2D;
public abstract class LineAxis extends AbstractChart{ public abstract class LineAxis extends AbstractChart{
@Override @Override
protected Rectangle drawAxis(Graphics2D g2, Rectangle bound){ protected Rectangle drawAxis(Graphics2D g2, Rectangle bound) {
if( data == null ) if (data == null)
return null; return null;
width = bound.width; width = bound.width;
@ -42,24 +42,24 @@ public abstract class LineAxis extends AbstractChart{
chartBound = new Rectangle(); chartBound = new Rectangle();
int stepLength = 7; int stepLength = 7;
// ********************************** // ------------------------------------------------
// Calculate Font sizes // Calculate Font sizes
// ********************************** // ------------------------------------------------
FontMetrics metric = g2.getFontMetrics(); FontMetrics metric = g2.getFontMetrics();
int fontHeight = metric.getHeight(); int fontHeight = metric.getHeight();
int fontXWidth = 0; int fontXWidth = 0;
int fontYWidth = 0; int fontYWidth = 0;
for( Point p : data.getData() ){ for (Point p : data.getData()) {
int length; int length;
String tmp = data.getXString( p.x ); String tmp = data.getXString(p.x);
if( tmp != null ) length = metric.stringWidth( tmp ); if (tmp != null) length = metric.stringWidth(tmp);
else length = metric.stringWidth( ""+p.x ); else length = metric.stringWidth("" + p.x);
fontXWidth = Math.max(length, fontXWidth); fontXWidth = Math.max(length, fontXWidth);
tmp = data.getXString( p.y ); tmp = data.getXString(p.y);
if( tmp != null ) length = metric.stringWidth( tmp ); if (tmp != null) length = metric.stringWidth(tmp);
else length = metric.stringWidth( ""+p.y ); else length = metric.stringWidth("" + p.y);
fontYWidth = Math.max(length, fontYWidth); fontYWidth = Math.max(length, fontYWidth);
} }
@ -67,7 +67,7 @@ public abstract class LineAxis extends AbstractChart{
Point origo = new Point( Point origo = new Point(
PADDING + fontYWidth + stepLength, PADDING + fontYWidth + stepLength,
height - PADDING - fontHeight - stepLength ); height - PADDING - fontHeight - stepLength);
chartBound.x = (int) (origo.getX() + 1); chartBound.x = (int) (origo.getX() + 1);
chartBound.y = PADDING; chartBound.y = PADDING;
chartBound.width = width - chartBound.x - 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)); g2.setStroke(new BasicStroke(1.5f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND));
// Y Axis // 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 // 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 // Y Axis steps and labels
// X Axis steps and labels // X Axis steps and labels

View file

@ -43,7 +43,7 @@ public class LineChart extends LineAxis{
// Draw lines // Draw lines
Point prevP = null; Point prevP = null;
for(Point p : data.getData()){ for (Point p : data.getData()) {
if (prevP != null) if (prevP != null)
drawLine(g2, bound, xScale, yScale, prevP.x, prevP.y, p.x, p.y); drawLine(g2, bound, xScale, yScale, prevP.x, prevP.y, p.x, p.y);
prevP = p; prevP = p;
@ -51,7 +51,7 @@ public class LineChart extends LineAxis{
} }
private void drawLine(Graphics2D g2, Rectangle bound, double xScale, double yScale, 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 // Line
g2.draw(new Line2D.Double( g2.draw(new Line2D.Double(
getXCoordinate(x1, xScale, bound), getXCoordinate(x1, xScale, bound),

View file

@ -32,7 +32,7 @@ import java.util.Iterator;
import java.util.Map; import java.util.Map;
public class Converter { public class Converter {
private Converter(){} private Converter() {}
/** /**
* Converts an object to an array of bytes. * Converts an object to an array of bytes.
@ -57,7 +57,7 @@ public class Converter {
* @param num is the number to convert * @param num is the number to convert
* @return a byte array of four bytes * @return a byte array of four bytes
*/ */
public static byte[] toBytes(int num){ public static byte[] toBytes(int num) {
return new byte[]{ return new byte[]{
(byte)(num & 0xff), (byte)(num & 0xff),
(byte)((num >> 8)& 0xff), (byte)((num >> 8)& 0xff),
@ -70,7 +70,7 @@ public class Converter {
* *
* @return a byte array with the same binary value as the char. * @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]; byte[] ret = new byte[arr.length];
for (int i=0; i<arr.length; ++i) for (int i=0; i<arr.length; ++i)
ret[i] = (byte) (arr[i] & 0xFF); ret[i] = (byte) (arr[i] & 0xFF);
@ -84,7 +84,7 @@ public class Converter {
* @param num is the number to convert * @param num is the number to convert
* @return a byte value of the integer * @return a byte value of the integer
*/ */
public static byte toByte(int num){ public static byte toByte(int num) {
return (byte)(num & 0xff); return (byte)(num & 0xff);
} }
@ -94,14 +94,14 @@ public class Converter {
* @param hex a String containing data coded in hex * @param hex a String containing data coded in hex
* @return a byte array * @return a byte array
*/ */
public static byte[] hexToByte(String hex){ public static byte[] hexToByte(String hex) {
if(hex == null) if (hex == null)
return null; return null;
if(hex.startsWith("0x")) if (hex.startsWith("0x"))
hex = hex.substring(2); hex = hex.substring(2);
byte[] b = new byte[(int)Math.ceil(hex.length()/2.0)]; byte[] b = new byte[(int)Math.ceil(hex.length()/2.0)];
for(int i=0; i<hex.length(); i+=2){ for (int i=0; i<hex.length(); i+=2) {
if(i+1 >= hex.length()) if (i+1 >= hex.length())
b[(i+1)/2] = hexToByte(hex.charAt(i), '0'); b[(i+1)/2] = hexToByte(hex.charAt(i), '0');
else else
b[(i+1)/2] = hexToByte(hex.charAt(i), hex.charAt(i+1)); 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 * @param quad2 is the second hex value
* @return a byte that corresponds to the hex * @return a byte that corresponds to the hex
*/ */
public static byte hexToByte( char quad1, char quad2){ public static byte hexToByte(char quad1, char quad2) {
byte b = hexToByte( quad2 ); byte b = hexToByte(quad2);
b |= hexToByte( quad1 ) << 4; b |= hexToByte(quad1) << 4;
return b; return b;
} }
@ -129,8 +129,8 @@ public class Converter {
* @return a byte that corresponds to the hex * @return a byte that corresponds to the hex
* @throws IllegalArgumentException if hex is not a valid hex character * @throws IllegalArgumentException if hex is not a valid hex character
*/ */
public static byte hexToByte( char hex ) throws IllegalArgumentException{ public static byte hexToByte(char hex) throws IllegalArgumentException{
switch( Character.toLowerCase(hex) ){ switch(Character.toLowerCase(hex)) {
case '0': return 0x00; case '0': return 0x00;
case '1': return 0x01; case '1': return 0x01;
case '2': return 0x02; case '2': return 0x02;
@ -148,7 +148,7 @@ public class Converter {
case 'e': return 0x0e; case 'e': return 0x0e;
case 'f': return 0x0f; case 'f': return 0x0f;
default: 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 * @param raw the byte array to convert
* @return a bit String * @return a bit String
*/ */
public static String toBitString(byte raw){ public static String toBitString(byte raw) {
StringBuilder str = new StringBuilder(8); StringBuilder str = new StringBuilder(8);
for (int i=0; i<8; ++i) { for (int i=0; i<8; ++i) {
str.append(raw & 0x01); str.append(raw & 0x01);
@ -204,11 +204,11 @@ public class Converter {
* @param raw the byte array to convert * @param raw the byte array to convert
* @return a hex String * @return a hex String
*/ */
public static String toHexString(byte[][] raw){ public static String toHexString(byte[][] raw) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
for(byte[] a : raw){ for (byte[] a : raw) {
for(byte b : a){ for (byte b : a) {
ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]); ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]);
ret.append(HEX_CHARS[(int) b & 0x0F ]); ret.append(HEX_CHARS[(int) b & 0x0F ]);
} }
@ -217,11 +217,11 @@ public class Converter {
return ret.toString(); return ret.toString();
} }
public static String toHexStringByColumn(byte[][] raw){ public static String toHexStringByColumn(byte[][] raw) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
for(int col=0; col<raw[0].length ;col++){ for (int col=0; col<raw[0].length; col++) {
for(int row=0; row<raw.length ;row++){ for (int row=0; row<raw.length; row++) {
ret.append(HEX_CHARS[(int) (raw[row][col] >>> 0x04)& 0x0F ]); ret.append(HEX_CHARS[(int) (raw[row][col] >>> 0x04)& 0x0F ]);
ret.append(HEX_CHARS[(int) raw[row][col] & 0x0F ]); ret.append(HEX_CHARS[(int) raw[row][col] & 0x0F ]);
} }
@ -236,12 +236,12 @@ public class Converter {
* @param raw the byte array to convert * @param raw the byte array to convert
* @return a hex String * @return a hex String
*/ */
public static String toHexString(byte[] raw){ public static String toHexString(byte[] raw) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
for(byte b : raw){ for (byte b : raw) {
ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]); ret.append(HEX_CHARS[(int) (b >>> 0x04) & 0x0F]);
ret.append(HEX_CHARS[(int) b & 0x0F ]); ret.append(HEX_CHARS[(int) b & 0x0F]);
} }
return ret.toString(); return ret.toString();
@ -253,9 +253,9 @@ public class Converter {
* @param raw the byte to convert * @param raw the byte to convert
* @return a hex String * @return a hex String
*/ */
public static String toHexString(byte raw){ public static String toHexString(byte raw) {
String ret = ""+HEX_CHARS[(int) (raw >>> 0x04)& 0x0F ]; String ret = "" +HEX_CHARS[(int) (raw >>> 0x04)& 0x0F ];
ret += ""+HEX_CHARS[(int) raw & 0x0F ]; ret += "" +HEX_CHARS[(int) raw & 0x0F ];
return ret; return ret;
} }
@ -266,10 +266,10 @@ public class Converter {
* @param raw the byte to convert * @param raw the byte to convert
* @return a String with 1's and 0's * @return a String with 1's and 0's
*/ */
public static String toString(byte raw){ public static String toString(byte raw) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
for(int i=128; i>0 ;i=( i<1 ? 0 : i/2 ) ){ for (int i=128; i>0; i=(i<1 ? 0 : i/2)) {
ret.append(( (raw & i) == 0 ? '0' : '1')); ret.append(((raw & i) == 0 ? '0' : '1'));
} }
return ret.toString(); return ret.toString();
} }
@ -280,11 +280,11 @@ public class Converter {
* @param raw the byte array to convert * @param raw the byte array to convert
* @return a String with 1's and 0's * @return a String with 1's and 0's
*/ */
public static String toString(byte[] raw){ public static String toString(byte[] raw) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
for(byte b : raw){ for (byte b : raw) {
for(int i=128; i>0 ;i=( i<1 ? 0 : i/2 ) ){ for (int i=128; i>0; i=(i<1 ? 0 : i/2)) {
ret.append(( (b & i) == 0 ? '0' : '1')); ret.append(((b & i) == 0 ? '0' : '1'));
} }
} }
return ret.toString(); return ret.toString();
@ -295,11 +295,11 @@ public class Converter {
* *
* @return a comma separated String * @return a comma separated String
*/ */
public static String toString(Map map){ public static String toString(Map map) {
StringBuilder tmp = new StringBuilder(); StringBuilder tmp = new StringBuilder();
tmp.append("{"); tmp.append("{");
Iterator<Object> it = map.keySet().iterator(); Iterator<Object> it = map.keySet().iterator();
while(it.hasNext()){ while (it.hasNext()) {
Object key = it.next(); Object key = it.next();
Object value = map.get(key); Object value = map.get(key);
tmp.append(key); tmp.append(key);
@ -312,7 +312,7 @@ public class Converter {
else else
tmp.append("null"); tmp.append("null");
if(it.hasNext()) if (it.hasNext())
tmp.append(", "); tmp.append(", ");
} }
tmp.append('}'); tmp.append('}');
@ -325,7 +325,7 @@ public class Converter {
* @param bits the BitSet to convert * @param bits the BitSet to convert
* @return a Integer * @return a Integer
*/ */
public static int toInt(BitSet bits){ public static int toInt(BitSet bits) {
int ret = 0; int ret = 0;
for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i+1)) { 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 * @param bits the boolean array to convert
* @return a Integer * @return a Integer
*/ */
public static int toInt(boolean[] bits){ public static int toInt(boolean[] bits) {
int ret = 0; int ret = 0;
for (int i = bits.length-1; i >= 0; i--) { 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; return ret;
@ -357,7 +357,7 @@ public class Converter {
* @param b is the byte to convert * @param b is the byte to convert
* @return the integer value of the byte * @return the integer value of the byte
*/ */
public static int toInt(byte b){ public static int toInt(byte b) {
return (int)(b & 0xff); return (int)(b & 0xff);
} }
@ -367,9 +367,9 @@ public class Converter {
* @param b is the byte array of size 1-4 * @param b is the byte array of size 1-4
* @return the int value of the byte array * @return the int value of the byte array
*/ */
public static int toInt(byte[] b){ public static int toInt(byte[] b) {
int i = 0; int i = 0;
switch (b.length){ switch (b.length) {
default: default:
case 4: i |= 0xFF000000 & (b[3] << 24); case 4: i |= 0xFF000000 & (b[3] << 24);
case 3: i |= 0x00FF0000 & (b[2] << 16); case 3: i |= 0x00FF0000 & (b[2] << 16);
@ -386,11 +386,11 @@ public class Converter {
* @param num the Integer to convert * @param num the Integer to convert
* @return a BitSet object * @return a BitSet object
*/ */
public static BitSet toBitSet(int num){ public static BitSet toBitSet(int num) {
BitSet ret = new BitSet(); BitSet ret = new BitSet();
String tmp = Integer.toBinaryString(num); String tmp = Integer.toBinaryString(num);
for(int i=0; i<tmp.length() ;i++){ for (int i=0; i<tmp.length(); i++) {
ret.set(i , tmp.charAt(tmp.length()-i-1) != '0'); ret.set(i , tmp.charAt(tmp.length()-i-1) != '0');
} }
return ret; return ret;
@ -406,26 +406,26 @@ public class Converter {
* @return a instance of the class with the value in the string or null if there was an problem * @return a instance of the class with the value in the string or null if there was an problem
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T fromString(String data, Class<T> c){ public static <T> T fromString(String data, Class<T> c) {
if(data == null || data.isEmpty()) if (data == null || data.isEmpty())
return null; return null;
try{ try {
if( c == String.class) return (T) data; if ( c == String.class) return (T) data;
else if(c == Integer.class) return (T) new Integer(data); else if (c == Integer.class) return (T) new Integer(data);
else if(c == int.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 == 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 == 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 == 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 == 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(c == byte.class) return (T) new Byte(data); else if (c == byte.class) return (T) new Byte(data);
else if(byte[].class.isAssignableFrom(c)) else if (byte[].class.isAssignableFrom(c))
return (T) Base64Decoder.decode(data); return (T) Base64Decoder.decode(data);
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
@ -434,15 +434,15 @@ public class Converter {
/** /**
* Replaces reserved and unsafe characters in URLs with hex values * 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(); StringBuilder out = new StringBuilder();
for( char c : str.toCharArray() ){ for (char c : str.toCharArray()) {
if( c>='0' && c<='9' || c>='A' && c<='Z' || c>='a' && c<='z' || if (c>='0' && c<='9' || c>='A' && c<='Z' || c>='a' && c<='z' ||
c=='$' || c=='-' || c=='_' || c=='.' || c=='+' || c=='!' || c=='$' || c=='-' || c=='_' || c=='.' || c=='+' || c=='!' ||
c=='*' || c=='\'' || c=='(' || c==')' || c==',' ) c=='*' || c=='\'' || c=='(' || c==')' || c==',')
out.append( c ); out.append(c);
else{ else {
out.append( '%' ).append( toHexString((byte)c) ); out.append('%').append(toHexString((byte)c));
} }
} }
@ -452,16 +452,16 @@ public class Converter {
/** /**
* Replaces hex values from a URL with the proper characters * 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(); StringBuilder out = new StringBuilder();
char[] array = str.toCharArray(); char[] array = str.toCharArray();
for( int i=0; i<array.length ;i++ ){ for (int i=0; i<array.length; i++) {
char c = array[i]; char c = array[i];
if( c == '%' && i+2<array.length ){ if (c == '%' && i+2<array.length) {
out.append( (char)hexToByte( array[++i], array[++i]) ); out.append((char) hexToByte(array[++i], array[++i]));
} }
else else
out.append( c ); out.append(c);
} }
return out.toString(); return out.toString();

View file

@ -88,24 +88,24 @@ public class NumberToWordsConverter {
long tmpNum = num; long tmpNum = num;
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
if (tmpNum < 0){ // Negative number if (tmpNum < 0) { // Negative number
tmpNum *= -1; tmpNum *= -1;
buffer.append("minus "); buffer.append("minus ");
} }
for(int i : NUMERIC_INDEXES){ for (int i : NUMERIC_INDEXES) {
long pow = (int)Math.pow(10, i); long pow = (int)Math.pow(10, i);
if (tmpNum >= pow){ if (tmpNum >= pow) {
long numberAtIndex = tmpNum/pow; // The number at position 3 long numberAtIndex = tmpNum/pow; // The number at position 3
tmpNum -= numberAtIndex*pow; tmpNum -= numberAtIndex*pow;
buffer.append( convert((int)numberAtIndex) ).append(" "); buffer.append(convert((int)numberAtIndex)).append(" ");
buffer.append( NUMERIC_STRINGS.get( pow ) ).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 long numberAtIndex = ((tmpNum % 100)/10)*10; // The number at position 2
tmpNum -= numberAtIndex; tmpNum -= numberAtIndex;
buffer.append( NUMERIC_STRINGS.get(numberAtIndex) ).append(" "); buffer.append(NUMERIC_STRINGS.get(numberAtIndex)).append(" ");
} }
if (NUMERIC_STRINGS.containsKey(tmpNum)) if (NUMERIC_STRINGS.containsKey(tmpNum))
buffer.append(NUMERIC_STRINGS.get(tmpNum)); buffer.append(NUMERIC_STRINGS.get(tmpNum));

View file

@ -25,12 +25,12 @@
package zutil.converter; package zutil.converter;
public class WGS84Converter { public class WGS84Converter {
public static void main(String[] args){ public static void main(String[] args) {
System.out.println(toWGS84Decimal("N 59<35> 47' 43\"")+" "+toWGS84Decimal(" E 17<31> 42' 55\"")); System.out.println(toWGS84Decimal("N 59<35> 47' 43\"") + " " +toWGS84Decimal(" E 17<31> 42' 55\""));
System.out.println(toWGS84Decimal("55<EFBFBD> 0' 0\"")+" "+toWGS84Decimal("68<EFBFBD> 59' 59,999\"")); System.out.println(toWGS84Decimal("55<EFBFBD> 0' 0\"") + " " +toWGS84Decimal("68<EFBFBD> 59' 59,999\""));
System.out.println(toWGS84Decimal("55<EFBFBD> 0.001'")+" "+toWGS84Decimal("68<EFBFBD> 59.999'")); System.out.println(toWGS84Decimal("55<EFBFBD> 0.001'") + " " +toWGS84Decimal("68<EFBFBD> 59.999'"));
System.out.println(toWGS84Decimal("3444.0000S")+" "+toWGS84Decimal("13521.0000E")); System.out.println(toWGS84Decimal("3444.0000S") + " " +toWGS84Decimal("13521.0000E"));
System.out.println(toWGS84Decimal("-44.0001")+" "+toWGS84Decimal("521.0001")); System.out.println(toWGS84Decimal("-44.0001") + " " +toWGS84Decimal("521.0001"));
} }
/** /**
@ -39,31 +39,31 @@ public class WGS84Converter {
* @param coordinate is the coordinate to convert * @param coordinate is the coordinate to convert
* @return the new coordinate in decimal degrees, returns 0 if conversions fails * @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; float deg=0, min=0, sec=0, neg=1;
coordinate = coordinate.trim().replaceAll(",", ".").toUpperCase(); coordinate = coordinate.trim().replaceAll(",", ".").toUpperCase();
if(coordinate.contains("S") || coordinate.contains("W")) if (coordinate.contains("S") || coordinate.contains("W"))
neg = -1; neg = -1;
// 55<EFBFBD> 0' 68<EFBFBD> 59,999 or 55<EFBFBD> 0' 0" 68<36> 59' 59,999" // 55<EFBFBD> 0' 68<EFBFBD> 59,999 or 55<EFBFBD> 0' 0" 68<36> 59' 59,999"
if(coordinate.matches("[NSWE ]? ?[0-9]{1,3}<7D> [0-9]{1,2}.?[0-9]*'[ 0-9.\\\"]*")){ if (coordinate.matches("[NSWE ]? ?[0-9]{1,3}<7D> [0-9]{1,2}.?[0-9]*'[ 0-9.\\\"]*")) {
coordinate = coordinate.replaceAll("[NSEW<45>'\\\"]", "").trim(); coordinate = coordinate.replaceAll("[NSEW<45>'\\\"]", "").trim();
String[] tmp = coordinate.split(" "); String[] tmp = coordinate.split(" ");
deg = Float.parseFloat(tmp[0]); deg = Float.parseFloat(tmp[0]);
min = Float.parseFloat(tmp[1]); min = Float.parseFloat(tmp[1]);
if(tmp.length > 2){ if (tmp.length > 2) {
sec = Float.parseFloat(tmp[2]); sec = Float.parseFloat(tmp[2]);
} }
} }
// 3444.0000S 13521.0000E // 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]", ""); coordinate = coordinate.replaceAll("[NS EW]", "");
float tmpf = Float.parseFloat(coordinate); float tmpf = Float.parseFloat(coordinate);
deg = (int)(tmpf/100); deg = (int)(tmpf/100);
min = tmpf-(deg*100); min = tmpf-(deg*100);
} }
// 55.0 68.99999 // 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); return Float.parseFloat(coordinate);
} }

View file

@ -56,7 +56,7 @@ public class DBConnection implements Closeable{
*/ */
public DBConnection(String jndi) throws NamingException, SQLException{ public DBConnection(String jndi) throws NamingException, SQLException{
InitialContext ctx = new InitialContext(); 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(); 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{ public DBConnection(DBMS dbms, String url, String db, String user, String password) throws Exception{
String dbms_name = initDriver(dbms); 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{ public DBConnection(DBMS dbms, String db) throws Exception{
String dbms_name = initDriver(dbms); String dbms_name = initDriver(dbms);
conn = DriverManager.getConnection ("jdbc:"+dbms_name+":"+db); conn = DriverManager.getConnection ("jdbc:" + dbms_name + ":" + db);
} }
/** /**
* @return the underlying connection * @return the underlying connection
*/ */
public Connection getConnection(){ public Connection getConnection() {
return conn; return conn;
} }
@ -111,7 +111,7 @@ public class DBConnection implements Closeable{
* @return the protocol name of the DBMS * @return the protocol name of the DBMS
*/ */
public static String initDriver(DBMS db) throws InstantiationException, IllegalAccessException, ClassNotFoundException{ public static String initDriver(DBMS db) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
switch(db){ switch(db) {
case MySQL: case MySQL:
Class.forName("com.mysql.jdbc.Driver").newInstance(); Class.forName("com.mysql.jdbc.Driver").newInstance();
DriverManager.setLoginTimeout(10); DriverManager.setLoginTimeout(10);
@ -127,10 +127,10 @@ public class DBConnection implements Closeable{
/** /**
* @return the last inserted id or -1 if there was an error * @return the last inserted id or -1 if there was an error
*/ */
public long getLastInsertID(){ public long getLastInsertID() {
try{ try {
return exec("SELECT LAST_INSERT_ID()", new SimpleSQLResult<>()); return exec("SELECT LAST_INSERT_ID()", new SimpleSQLResult<>());
}catch(SQLException e){ } catch (SQLException e) {
logger.log(Level.WARNING, null, e); logger.log(Level.WARNING, null, e);
} }
return -1; return -1;
@ -138,17 +138,17 @@ public class DBConnection implements Closeable{
/** /**
* @return the last inserted id or -1 if there was an error * @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; ResultSet result = null;
try{ try {
result = stmt.getGeneratedKeys(); result = stmt.getGeneratedKeys();
if(result != null){ if (result != null) {
return new SimpleSQLResult<Integer>().handleQueryResult(stmt, result); return new SimpleSQLResult<Integer>().handleQueryResult(stmt, result);
} }
}catch(SQLException e){ } catch (SQLException e) {
logger.log(Level.WARNING, null, e); logger.log(Level.WARNING, null, e);
} finally { } finally {
if(result != null) { if (result != null) {
try { try {
result.close(); result.close();
} catch (SQLException e) { } 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 * @return update count or -1 if the query is not an update query
*/ */
public int exec(String query) throws SQLException { public int exec(String query) throws SQLException {
PreparedStatement stmt = getPreparedStatement( query ); PreparedStatement stmt = getPreparedStatement(query);
return exec(stmt); 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 * @return update count or -1 if the query is not an update query
*/ */
public static int exec(PreparedStatement stmt) throws SQLException { public static int exec(PreparedStatement stmt) throws SQLException {
Integer ret = exec(stmt, new SQLResultHandler<Integer>(){ Integer ret = exec(stmt, new SQLResultHandler<Integer>() {
public Integer handleQueryResult(Statement stmt, ResultSet result) { public Integer handleQueryResult(Statement stmt, ResultSet result) {
try { try {
if(stmt != null) if (stmt != null)
return stmt.getUpdateCount(); return stmt.getUpdateCount();
else else
return -1; return -1;
@ -204,7 +204,7 @@ public class DBConnection implements Closeable{
} }
}); });
if(ret != null) if (ret != null)
return ret; return ret;
return -1; return -1;
} }
@ -217,7 +217,7 @@ public class DBConnection implements Closeable{
* @return update count or -1 if the query is not an update query * @return update count or -1 if the query is not an update query
*/ */
public <T> T exec(String query, SQLResultHandler<T> handler) throws SQLException { public <T> T exec(String query, SQLResultHandler<T> handler) throws SQLException {
PreparedStatement stmt = getPreparedStatement( query ); PreparedStatement stmt = getPreparedStatement(query);
return exec(stmt, handler); return exec(stmt, handler);
} }
@ -229,24 +229,24 @@ public class DBConnection implements Closeable{
* @return the object from the handler * @return the object from the handler
*/ */
public static <T> T exec(PreparedStatement stmt, SQLResultHandler<T> handler) { public static <T> T exec(PreparedStatement stmt, SQLResultHandler<T> handler) {
try{ try {
// Execute // Execute
boolean isResultSet = stmt.execute(); boolean isResultSet = stmt.execute();
// Handle result // Handle result
if( handler != null ){ if (handler != null) {
ResultSet result = null; ResultSet result = null;
try{ try {
if(isResultSet){ if (isResultSet) {
result = stmt.getResultSet(); result = stmt.getResultSet();
return handler.handleQueryResult(stmt, result); return handler.handleQueryResult(stmt, result);
} }
else else
return null; return null;
}catch(SQLException e){ } catch(SQLException e) {
logger.log(Level.WARNING, null, e); logger.log(Level.WARNING, null, e);
}finally{ } finally {
if(result != null){ if (result != null) {
try { try {
result.close(); result.close();
} catch (SQLException e) { } catch (SQLException e) {
@ -255,7 +255,7 @@ public class DBConnection implements Closeable{
} }
} }
} }
}catch(SQLException e){ } catch (SQLException e) {
logger.log(Level.WARNING, null, e); logger.log(Level.WARNING, null, e);
// Cleanup // Cleanup
} finally { } finally {
@ -277,10 +277,10 @@ public class DBConnection implements Closeable{
* @return a array of ints representing the number of updates for each batch statements * @return a array of ints representing the number of updates for each batch statements
*/ */
public static int[] execBatch(PreparedStatement stmt) throws SQLException{ public static int[] execBatch(PreparedStatement stmt) throws SQLException{
try{ try {
// Execute // Execute
return stmt.executeBatch(); return stmt.executeBatch();
}catch(SQLException e){ } catch (SQLException e) {
logger.log(Level.WARNING, null, e); logger.log(Level.WARNING, null, e);
// Cleanup // Cleanup
} finally { } finally {
@ -300,8 +300,8 @@ public class DBConnection implements Closeable{
* *
* @param pool is the pool * @param pool is the pool
*/ */
protected void setPool(DBConnectionPool pool){ protected void setPool(DBConnectionPool pool) {
if( pool != null ) if (pool != null)
pool.removeConnection(this); pool.removeConnection(this);
this.pool = pool; this.pool = pool;
} }
@ -311,11 +311,11 @@ public class DBConnection implements Closeable{
* *
* @return true or false depending on the validity of the connection * @return true or false depending on the validity of the connection
*/ */
public boolean valid(){ public boolean valid() {
try { try {
conn.getMetaData(); conn.getMetaData();
return !conn.isClosed(); return !conn.isClosed();
}catch (Exception e) { } catch (Exception e) {
return false; return false;
} }
} }
@ -323,12 +323,12 @@ public class DBConnection implements Closeable{
/** /**
* Disconnects from the database or releases the connection back to the pool * Disconnects from the database or releases the connection back to the pool
*/ */
public void close(){ public void close() {
if(pool != null){ if (pool != null) {
pool.releaseConnection(this); pool.releaseConnection(this);
conn = null; conn = null;
} }
else{ else {
forceClose(); forceClose();
} }
} }
@ -336,10 +336,10 @@ public class DBConnection implements Closeable{
/** /**
* Disconnects from the database * Disconnects from the database
*/ */
public void forceClose(){ public void forceClose() {
if (conn != null) { if (conn != null) {
try { try {
if( !conn.isClosed() ) if (!conn.isClosed())
conn.close(); conn.close();
} catch (SQLException e) { } catch (SQLException e) {
logger.log(Level.WARNING, null, 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); return conn.equals(o);
} }
} }

View file

@ -58,12 +58,12 @@ public class DBQueue<E> implements Queue<E>{
* @param db is the connection to the DB * @param db is the connection to the DB
* @param table is the name of the table * @param table is the name of the table
*/ */
public DBQueue(DBConnection db, String table){ public DBQueue(DBConnection db, String table) {
this.db = db; this.db = db;
this.table = table; this.table = table;
} }
public boolean add(Object arg0){ public boolean add(Object arg0) {
try { try {
PreparedStatement sql = db.getPreparedStatement("INSERT INTO ? (data) VALUES(?)"); PreparedStatement sql = db.getPreparedStatement("INSERT INTO ? (data) VALUES(?)");
sql.setObject(1, table); sql.setObject(1, table);
@ -86,7 +86,7 @@ public class DBQueue<E> implements Queue<E>{
public synchronized E peek() { public synchronized E peek() {
try { try {
return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler<E>(){ return db.exec("SELECT * FROM " + table + " LIMIT 1", new SQLResultHandler<E>() {
public E handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{ public E handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{
if (rs.next()) if (rs.next())
try { try {
@ -105,14 +105,14 @@ public class DBQueue<E> implements Queue<E>{
public synchronized E poll() { public synchronized E poll() {
try { try {
return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler<E>(){ return db.exec("SELECT * FROM " + table + " LIMIT 1", new SQLResultHandler<E>() {
public E handleQueryResult(Statement stmt, ResultSet rs) { public E handleQueryResult(Statement stmt, ResultSet rs) {
try{ try {
if (rs.next()) { if (rs.next()) {
db.exec("DELETE FROM "+table+" WHERE id="+rs.getInt("id")+" LIMIT 1"); db.exec("DELETE FROM " + table + " WHERE id=" + rs.getInt("id") + " LIMIT 1");
return (E) Converter.toObject(rs.getBytes("data")); return (E) Converter.toObject(rs.getBytes("data"));
} }
}catch(Exception e){ } catch (Exception e) {
e.printStackTrace(MultiPrintStream.out); e.printStackTrace(MultiPrintStream.out);
} }
return null; return null;
@ -135,7 +135,7 @@ public class DBQueue<E> implements Queue<E>{
public void clear() { public void clear() {
try { try {
db.exec("TRUNCATE TABLE `"+table+"`"); db.exec("TRUNCATE TABLE `" + table + "`");
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(MultiPrintStream.out); e.printStackTrace(MultiPrintStream.out);
} }
@ -143,7 +143,7 @@ public class DBQueue<E> implements Queue<E>{
public boolean contains(Object arg0) { public boolean contains(Object arg0) {
try { try {
return db.exec("SELECT data FROM "+table+" WHERE data='"+Converter.toBytes(arg0)+"' LIMIT 1", new SQLResultHandler<Boolean>(){ return db.exec("SELECT data FROM " + table + " WHERE data='" + Converter.toBytes(arg0) + "' LIMIT 1", new SQLResultHandler<Boolean>() {
public Boolean handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{ public Boolean handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{
return rs.next(); return rs.next();
} }
@ -170,7 +170,7 @@ public class DBQueue<E> implements Queue<E>{
public synchronized boolean remove(Object arg0) { public synchronized boolean remove(Object arg0) {
try { 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; return true;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(MultiPrintStream.out); e.printStackTrace(MultiPrintStream.out);
@ -190,7 +190,7 @@ public class DBQueue<E> implements Queue<E>{
public int size() { public int size() {
try { try {
return db.exec("SELECT count(*) FROM "+table, new SQLResultHandler<Integer>(){ return db.exec("SELECT count(*) FROM " +table, new SQLResultHandler<Integer>() {
public Integer handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{ public Integer handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{
if (rs.next()) if (rs.next())
return rs.getInt(1); return rs.getInt(1);

View file

@ -55,13 +55,13 @@ public class DBUpgradeHandler {
private HashSet<String> ignoredTablesSet; private HashSet<String> ignoredTablesSet;
public DBUpgradeHandler(DBConnection reference){ public DBUpgradeHandler(DBConnection reference) {
this.tableRenameMap = new HashMap<>(); this.tableRenameMap = new HashMap<>();
this.ignoredTablesSet = new HashSet<>(); this.ignoredTablesSet = new HashSet<>();
this.reference = reference; this.reference = reference;
} }
public void setTargetDB(DBConnection db){ public void setTargetDB(DBConnection db) {
this.target = db; this.target = db;
} }
@ -71,14 +71,14 @@ public class DBUpgradeHandler {
* @param oldTableName current name of the table * @param oldTableName current name of the table
* @param newTableName new name that old table will be renamed to. * @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); this.tableRenameMap.put(oldTableName, newTableName);
} }
/** /**
* @param table a table name that will be ignored from the upgrade procedure * @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); ignoredTablesSet.add(table);
} }
@ -89,7 +89,7 @@ public class DBUpgradeHandler {
* *
* @param enable true to enable forced upgrade * @param enable true to enable forced upgrade
*/ */
public void setForcedDBUpgrade(boolean enable){ public void setForcedDBUpgrade(boolean enable) {
this.forceUpgradeEnabled = enable; this.forceUpgradeEnabled = enable;
} }
@ -106,7 +106,7 @@ public class DBUpgradeHandler {
logger.fine("Committing upgrade transaction..."); logger.fine("Committing upgrade transaction...");
target.getConnection().commit(); target.getConnection().commit();
} catch(SQLException e){ } catch(SQLException e) {
target.getConnection().rollback(); target.getConnection().rollback();
throw e; throw e;
} finally { } finally {
@ -115,7 +115,7 @@ public class DBUpgradeHandler {
} }
private void upgradeRenameTables() throws SQLException { private void upgradeRenameTables() throws SQLException {
if(tableRenameMap.size() > 0) { if (tableRenameMap.size() > 0) {
List<String> targetTables = getTableList(target); List<String> targetTables = getTableList(target);
for (String oldTableName : tableRenameMap.keySet()) { for (String oldTableName : tableRenameMap.keySet()) {
@ -133,8 +133,8 @@ public class DBUpgradeHandler {
List<String> refTables = getTableList(reference); List<String> refTables = getTableList(reference);
List<String> targetTables = getTableList(target); List<String> targetTables = getTableList(target);
for(String table : refTables){ for (String table : refTables) {
if(!targetTables.contains(table)){ if (!targetTables.contains(table)) {
logger.fine(String.format("Creating new table: '%s'", table)); logger.fine(String.format("Creating new table: '%s'", table));
// Get reference create sql // Get reference create sql
String sql = getTableSql(reference, table); String sql = getTableSql(reference, table);
@ -148,8 +148,8 @@ public class DBUpgradeHandler {
List<String> refTables = getTableList(reference); List<String> refTables = getTableList(reference);
List<String> targetTables = getTableList(target); List<String> targetTables = getTableList(target);
for(String table : targetTables){ for (String table : targetTables) {
if(!refTables.contains(table)){ if (!refTables.contains(table)) {
logger.fine(String.format("Dropping table: '%s'", table)); logger.fine(String.format("Dropping table: '%s'", table));
target.exec("DROP TABLE " + table); target.exec("DROP TABLE " + table);
} }
@ -160,8 +160,8 @@ public class DBUpgradeHandler {
List<String> refTables = getTableList(reference); List<String> refTables = getTableList(reference);
List<String> targetTables = getTableList(target); List<String> targetTables = getTableList(target);
for(String table : targetTables){ for (String table : targetTables) {
if(refTables.contains(table)){ if (refTables.contains(table)) {
// Get reference structure // Get reference structure
List<DBColumn> refStruct = getColumnList(reference, table); List<DBColumn> refStruct = getColumnList(reference, table);
// Get target structure // Get target structure
@ -169,12 +169,12 @@ public class DBUpgradeHandler {
// Check unnecessary columns // Check unnecessary columns
boolean execForcedUpgrade = false; boolean execForcedUpgrade = false;
for(DBColumn column : targetStruct) { for (DBColumn column : targetStruct) {
if(refStruct.contains(column)) { if (refStruct.contains(column)) {
DBColumn refColumn = refStruct.get(refStruct.indexOf(column)); DBColumn refColumn = refStruct.get(refStruct.indexOf(column));
// Check if the columns have the same type // Check if the columns have the same type
if(!column.type.equals(refColumn.type)){ if (!column.type.equals(refColumn.type)) {
if(forceUpgradeEnabled) if (forceUpgradeEnabled)
execForcedUpgrade = true; execForcedUpgrade = true;
else else
logger.warning(String.format( 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 // Do a forced upgrade where we create a new table and migrate the old data
if(execForcedUpgrade){ if (execForcedUpgrade) {
// Backup table // Backup table
String backupTable = table+"_temp"; String backupTable = table + "_temp";
logger.fine(String.format("Forced Upgrade: Backing up table: '%s' to: '%s'", table, backupTable)); 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)); target.exec(String.format("ALTER TABLE %s RENAME TO %s", table, backupTable));
@ -216,17 +216,17 @@ public class DBUpgradeHandler {
target.exec("DROP TABLE " + backupTable); target.exec("DROP TABLE " + backupTable);
} }
// Do a soft upgrade, add missing columns // Do a soft upgrade, add missing columns
else{ else {
// Add new columns // Add new columns
for(DBColumn column : refStruct) { for (DBColumn column : refStruct) {
if(!targetStruct.contains(column)) { if (!targetStruct.contains(column)) {
logger.fine(String.format("Adding column '%s.%s'", table, column.name)); logger.fine(String.format("Adding column '%s.%s'", table, column.name));
target.exec( target.exec(
String.format("ALTER TABLE %s ADD COLUMN %s %s %s%s%s", String.format("ALTER TABLE %s ADD COLUMN %s %s %s%s%s",
table, table,
column.name, column.name,
column.type, column.type,
(column.defaultValue != null ? " DEFAULT '"+column.defaultValue+"'" : ""), (column.defaultValue != null ? " DEFAULT '" +column.defaultValue + "'" : ""),
(column.notNull ? " NOT NULL" : ""), (column.notNull ? " NOT NULL" : ""),
(column.publicKey ? " PRIMARY KEY" : ""))); (column.publicKey ? " PRIMARY KEY" : "")));
} }
@ -241,9 +241,9 @@ public class DBUpgradeHandler {
return db.exec("SELECT name FROM sqlite_master WHERE type='table';", new SQLResultHandler<List<String>>() { return db.exec("SELECT name FROM sqlite_master WHERE type='table';", new SQLResultHandler<List<String>>() {
public List<String> handleQueryResult(Statement stmt, ResultSet result) throws SQLException { public List<String> handleQueryResult(Statement stmt, ResultSet result) throws SQLException {
ArrayList<String> list = new ArrayList<>(); ArrayList<String> list = new ArrayList<>();
while( result.next() ) { while (result.next()) {
String table = result.getString(1); String table = result.getString(1);
if(!ignoredTablesSet.contains(table)) if (!ignoredTablesSet.contains(table))
list.add(result.getString(1)); list.add(result.getString(1));
} }
return list; return list;
@ -268,12 +268,12 @@ public class DBUpgradeHandler {
String defaultValue; String defaultValue;
boolean publicKey; boolean publicKey;
public boolean equals(Object obj){ public boolean equals(Object obj) {
return obj instanceof DBColumn && return obj instanceof DBColumn &&
name.equals(((DBColumn)obj).name); name.equals(((DBColumn)obj).name);
} }
public String toString(){ public String toString() {
return name; return name;
} }
} }
@ -283,7 +283,7 @@ public class DBUpgradeHandler {
@Override @Override
public List<DBColumn> handleQueryResult(Statement stmt, ResultSet result) throws SQLException { public List<DBColumn> handleQueryResult(Statement stmt, ResultSet result) throws SQLException {
ArrayList<DBColumn> list = new ArrayList<>(); ArrayList<DBColumn> list = new ArrayList<>();
while (result.next()){ while (result.next()) {
DBColumn column = new DBColumn(); DBColumn column = new DBColumn();
column.name = result.getString("name"); column.name = result.getString("name");
column.type = result.getString("type"); column.type = result.getString("type");

View file

@ -36,15 +36,15 @@ public class SQLQuery {
protected static abstract class SQLQueryItem{ protected static abstract class SQLQueryItem{
SQLQueryItem root; SQLQueryItem root;
protected SQLQueryItem(){} protected SQLQueryItem() {}
protected void setRoot(SQLQueryItem root){ protected void setRoot(SQLQueryItem root) {
this.root = root; this.root = root;
} }
protected abstract void build(StringBuilder query); protected abstract void build(StringBuilder query);
public String toString(){ public String toString() {
StringBuilder query = new StringBuilder(); StringBuilder query = new StringBuilder();
root.build(query); root.build(query);
return query.toString(); 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 * @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); setRoot(this);
this.params = params; this.params = params;
} }
protected void build(StringBuilder query) { protected void build(StringBuilder query) {
query.append("SELECT "); query.append("SELECT ");
if( params == null || params.length <= 0 ) if (params == null || params.length <= 0)
query.append("*"); query.append("*");
else{ else {
for(int i=0; i<params.length ;i++){ for (int i=0; i<params.length; i++) {
query.append(params[i]); query.append(params[i]);
if( i != params.length-1 ) if (i != params.length-1)
query.append(","); query.append(",");
} }
} }
if( from != null ) if (from != null)
from.build( query ); from.build(query);
} }
public SQLFrom FROM(String ...tables){ public SQLFrom FROM(String ...tables) {
return from = new SQLFrom(this, tables); return from = new SQLFrom(this, tables);
} }
} }
@ -109,7 +109,7 @@ public class SQLQuery {
* </XMP> * </XMP>
*/ */
public static class SQLUpdate extends SQLQueryItem{ public static class SQLUpdate extends SQLQueryItem{
protected SQLUpdate(){ protected SQLUpdate() {
setRoot(this); setRoot(this);
} }
@ -128,7 +128,7 @@ public class SQLQuery {
* </XMP> * </XMP>
*/ */
public static class SQLInsert extends SQLQueryItem{ public static class SQLInsert extends SQLQueryItem{
protected SQLInsert(){ protected SQLInsert() {
setRoot(this); setRoot(this);
} }
@ -146,7 +146,7 @@ public class SQLQuery {
* </XMP> * </XMP>
*/ */
public static class SQLDelete extends SQLQueryItem{ public static class SQLDelete extends SQLQueryItem{
protected SQLDelete(){ protected SQLDelete() {
setRoot(this); setRoot(this);
} }
@ -161,75 +161,80 @@ public class SQLQuery {
LinkedList<String> tables = new LinkedList<>(); LinkedList<String> tables = new LinkedList<>();
SQLQueryItem next; SQLQueryItem next;
protected SQLFrom(SQLQueryItem root, String ...tables){ protected SQLFrom(SQLQueryItem root, String ...tables) {
setRoot(root); setRoot(root);
Collections.addAll(this.tables, tables); Collections.addAll(this.tables, tables);
} }
public SQLFrom NATURAL_JOIN(String table){ public SQLFrom NATURAL_JOIN(String table) {
return joinLastTable("NATURAL JOIN", table); return joinLastTable("NATURAL JOIN", table);
} }
public SQLFrom NATURAL_JOIN(String ...tables){ public SQLFrom NATURAL_JOIN(String ...tables) {
return joinTable("NATURAL JOIN", tables); return joinTable("NATURAL JOIN", tables);
} }
public SQLFrom JOIN(String table){ public SQLFrom JOIN(String table) {
return joinLastTable("JOIN", table); return joinLastTable("JOIN", table);
} }
public SQLFrom JOIN(String ...tables){ public SQLFrom JOIN(String ...tables) {
return joinTable("JOIN", tables); return joinTable("JOIN", tables);
} }
public SQLFrom UNION(String table){ public SQLFrom UNION(String table) {
return joinLastTable("UNION", table); return joinLastTable("UNION", table);
} }
public SQLFrom UNION(String ...tables){ public SQLFrom UNION(String ...tables) {
return joinTable("UNION", tables); return joinTable("UNION", tables);
} }
private SQLFrom joinLastTable(String type, String table){ private SQLFrom joinLastTable(String type, String table) {
String last = tables.getLast(); String last = tables.getLast();
tables.removeLast(); tables.removeLast();
tables.add(last + " " + type + " " + table); tables.add(last + " " + type + " " + table);
return this; return this;
} }
private SQLFrom joinTable(String type, String[] tables){ private SQLFrom joinTable(String type, String[] tables) {
if( tables.length < 2 ) if (tables.length < 2)
return this; return this;
StringBuilder str = new StringBuilder(); StringBuilder str = new StringBuilder();
for(int i=0; i<tables.length ;i++){ for (int i=0; i<tables.length; i++) {
str.append(tables[i]); str.append(tables[i]);
if( i != tables.length-1 ) if (i != tables.length-1)
str.append(' ').append(type).append(' '); str.append(' ').append(type).append(' ');
} }
this.tables.add(str.toString()); this.tables.add(str.toString());
return this; return this;
} }
public SQLWhere WHERE(){ public SQLWhere WHERE() {
return (SQLWhere) (next = new SQLWhere(root)); return (SQLWhere) (next = new SQLWhere(root));
} }
public SQLGroupBy GROUP_BY( String ...cols ){ public SQLGroupBy GROUP_BY(String ...cols) {
return (SQLGroupBy) (next = new SQLGroupBy(root, 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)); return (SQLOrderBy) (next = new SQLOrderBy(root, cols));
} }
public SQLLimit LIMIT( long count ){ public SQLLimit LIMIT(long count) {
return (SQLLimit) (next = new SQLLimit(root, count)); return (SQLLimit) (next = new SQLLimit(root, count));
} }
protected void build(StringBuilder query) { protected void build(StringBuilder query) {
query.append(" FROM "); query.append(" FROM ");
if( tables.isEmpty() ) if (tables.isEmpty())
throw new RuntimeException("The FROM query item must have at least 1 table!"); throw new RuntimeException("The FROM query item must have at least 1 table!");
for(int i=0; i<tables.size() ;i++){
for (int i=0; i<tables.size(); i++) {
query.append(tables.get(i)); query.append(tables.get(i));
if( i != tables.size()-1 ) if (i != tables.size() - 1)
query.append(", "); query.append(", ");
} }
if( next != null ) next.build( query );
if (next != null)
next.build(query);
} }
} }
@ -240,73 +245,74 @@ public class SQLQuery {
LinkedList<String> conds = new LinkedList<>(); LinkedList<String> conds = new LinkedList<>();
SQLQueryItem next; SQLQueryItem next;
protected SQLWhere(SQLQueryItem root){ protected SQLWhere(SQLQueryItem root) {
setRoot(root); setRoot(root);
} }
/** /**
* Equals (arg1 = arg2) * Equals (arg1 = arg2)
*/ */
public SQLWhere EQ(String arg1, String arg2){ public SQLWhere EQ(String arg1, String arg2) {
return cond("=", arg1, arg2); return cond("=", arg1, arg2);
} }
/** /**
* Not Equal (arg1 != arg2) * Not Equal (arg1 != arg2)
*/ */
public SQLWhere NE(String arg1, String arg2){ public SQLWhere NE(String arg1, String arg2) {
return cond("!=", arg1, arg2); return cond("!=", arg1, arg2);
} }
/** /**
* Less than (arg1 &lt; arg2) * Less than (arg1 &lt; arg2)
*/ */
public SQLWhere LT(String arg1, String arg2){ public SQLWhere LT(String arg1, String arg2) {
return cond("<", arg1, arg2); return cond("<", arg1, arg2);
} }
/** /**
* Greater than (arg1 &gt; arg2) * Greater than (arg1 &gt; arg2)
*/ */
public SQLWhere GT(String arg1, String arg2){ public SQLWhere GT(String arg1, String arg2) {
return cond(">", arg1, arg2); return cond(">", arg1, arg2);
} }
/** /**
* Less than or equal (arg1 &lt;= arg2) * Less than or equal (arg1 &lt;= arg2)
*/ */
public SQLWhere LE(String arg1, String arg2){ public SQLWhere LE(String arg1, String arg2) {
return cond("<=", arg1, arg2); return cond("<=", arg1, arg2);
} }
/** /**
* Greater than or equal (arg1 &gt;= arg2) * Greater than or equal (arg1 &gt;= arg2)
*/ */
public SQLWhere GE(String arg1, String arg2){ public SQLWhere GE(String arg1, String arg2) {
return cond(">=", arg1, 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); conds.add(arg1 + cond + arg2);
return this; return this;
} }
public SQLGroupBy GROUP_BY( String ...cols ){ public SQLGroupBy GROUP_BY(String ...cols) {
return (SQLGroupBy) (next = new SQLGroupBy(root, 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)); return (SQLOrderBy) (next = new SQLOrderBy(root, cols));
} }
public SQLLimit LIMIT( long count ){ public SQLLimit LIMIT(long count) {
return (SQLLimit) (next = new SQLLimit(root, count)); return (SQLLimit) (next = new SQLLimit(root, count));
} }
protected void build(StringBuilder query) { protected void build(StringBuilder query) {
query.append(" WHERE "); query.append(" WHERE ");
if( conds.isEmpty() ) if (conds.isEmpty())
throw new RuntimeException("The WHERE query item must hav atleast 1 condition!"); throw new RuntimeException("The WHERE query item must have minimum 1 condition!");
for(int i=0; i<conds.size() ;i++){
for (int i=0; i<conds.size(); i++) {
query.append(conds.get(i)); query.append(conds.get(i));
if( i != conds.size()-1 ) if (i != conds.size() - 1)
query.append(" AND "); query.append(" AND ");
} }
if( next != null ) next.build( query ); if (next != null) next.build(query);
} }
} }
@ -317,47 +323,48 @@ public class SQLQuery {
protected String end; protected String end;
SQLQueryItem next; SQLQueryItem next;
protected SQLGroupOrderBy(SQLQueryItem root, String ...cols){ protected SQLGroupOrderBy(SQLQueryItem root, String ...cols) {
setRoot(root); setRoot(root);
this.cols = cols; this.cols = cols;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T ASC(){ public T ASC() {
end = "ASC"; end = "ASC";
return (T)this; return (T)this;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T DESC(){ public T DESC() {
end = "DESC"; end = "DESC";
return (T)this; return (T)this;
} }
protected void build(String op, StringBuilder query) { protected void build(String op, StringBuilder query) {
query.append(' ').append(op).append(' '); query.append(' ').append(op).append(' ');
if( cols == null || cols.length <= 0 ) if (cols == null || cols.length <= 0)
throw new RuntimeException("The "+op+" query item must hav atleast 1 column!"); throw new RuntimeException("The " + op + " query item must have minimum 1 column!");
for(int i=0; i<cols.length ;i++){
query.append( cols[i] ); for (int i=0; i<cols.length; i++) {
if( i != cols.length-1 ) query.append(cols[i]);
if (i != cols.length - 1)
query.append(","); query.append(",");
} }
if( end != null ) query.append(' ').append( end ); if (end != null) query.append(' ').append(end);
if( next != null ) next.build( query ); if (next != null) next.build(query);
} }
} }
public static class SQLGroupBy extends SQLGroupOrderBy<SQLGroupBy>{ public static class SQLGroupBy extends SQLGroupOrderBy<SQLGroupBy>{
protected SQLGroupBy(SQLQueryItem root, String ...cols){ protected SQLGroupBy(SQLQueryItem root, String ...cols) {
super( root, cols ); super(root, cols);
} }
public SQLOrderBy ORDER_BY( String ...cols ){ public SQLOrderBy ORDER_BY(String ...cols) {
return (SQLOrderBy) (next = new SQLOrderBy(root, 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)); return (SQLLimit) (next = new SQLLimit(root, count));
} }
@ -367,12 +374,12 @@ public class SQLQuery {
} }
public static class SQLOrderBy extends SQLGroupOrderBy<SQLOrderBy>{ public static class SQLOrderBy extends SQLGroupOrderBy<SQLOrderBy>{
protected SQLOrderBy(SQLQueryItem root, String ...cols){ protected SQLOrderBy(SQLQueryItem root, String ...cols) {
super( root, cols ); super(root, cols);
} }
public SQLLimit LIMIT( long count ){ public SQLLimit LIMIT(long count) {
return (SQLLimit) (next = new SQLLimit(root, count)); return (SQLLimit) (next = new SQLLimit(root, count));
} }
@ -385,36 +392,36 @@ public class SQLQuery {
long start; long start;
Long count; Long count;
protected SQLLimit(SQLQueryItem root, long start){ protected SQLLimit(SQLQueryItem root, long start) {
setRoot( root ); setRoot(root);
this.start = start; this.start = start;
} }
public SQLLimit TO( long count ){ public SQLLimit TO(long count) {
this.count = count; this.count = count;
return this; return this;
} }
protected void build(StringBuilder query) { protected void build(StringBuilder query) {
query.append(" LIMIT ").append( start ); query.append(" LIMIT ").append(start);
if( count != null ) query.append(' ').append( count ); if (count != null) query.append(' ').append(count);
} }
} }
//******************************************* //*******************************************
public static SQLSelect SELECT( String ...params ){ public static SQLSelect SELECT(String ...params) {
return new SQLSelect( params ); return new SQLSelect(params);
} }
public static SQLUpdate UPDATE(){ public static SQLUpdate UPDATE() {
return new SQLUpdate(); return new SQLUpdate();
} }
public static SQLInsert INSERT(){ public static SQLInsert INSERT() {
return new SQLInsert(); return new SQLInsert();
} }
public static SQLDelete DELETE(){ public static SQLDelete DELETE() {
return new SQLDelete(); return new SQLDelete();
} }

View file

@ -116,7 +116,7 @@ public abstract class DBBean {
protected ReentrantLock readLock; protected ReentrantLock readLock;
protected DBBean(){ protected DBBean() {
DBBeanConfig.getBeanConfig(this.getClass()); DBBeanConfig.getBeanConfig(this.getClass());
saveLock = new ReentrantLock(); saveLock = new ReentrantLock();
readLock = new ReentrantLock(); readLock = new ReentrantLock();
@ -221,7 +221,7 @@ public abstract class DBBean {
DBBeanCache.add(this); DBBeanCache.add(this);
// Save sub beans, after we get the parent beans id // Save sub beans, after we get the parent beans id
if (recursive){ if (recursive) {
for (DBBeanSubBeanConfig subBeanField : config.getSubBeans()) { for (DBBeanSubBeanConfig subBeanField : config.getSubBeans()) {
if (this.id == null) if (this.id == null)
throw new SQLException("Unknown parent bean id"); throw new SQLException("Unknown parent bean id");
@ -242,7 +242,7 @@ public abstract class DBBean {
// Save links in link table // Save links in link table
String sql; String sql;
if (!subBeanField.isStandaloneLinkTable()) // Sub Bean and link table is the same table 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 else
sql = "INSERT INTO " + subBeanField.getLinkTableName() + " (" + subBeanField.getParentIdColumnName() + ", " + subIdCol + ") SELECT ?,? " + sql = "INSERT INTO " + subBeanField.getLinkTableName() + " (" + subBeanField.getParentIdColumnName() + ", " + subIdCol + ") SELECT ?,? " +
"WHERE NOT EXISTS(SELECT 1 FROM " + subBeanField.getLinkTableName() + " WHERE " + subBeanField.getParentIdColumnName() + "=? AND " + subIdCol + "=?);"; "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{ public void delete(DBConnection db, boolean recursive) throws SQLException{
Class<? extends DBBean> c = this.getClass(); Class<? extends DBBean> c = this.getClass();
DBBeanConfig config = DBBeanConfig.getBeanConfig( c ); DBBeanConfig config = DBBeanConfig.getBeanConfig(c);
if( this.getId() == null ) if (this.getId() == null)
throw new NullPointerException("ID field is null! (Has the bean been saved?)"); throw new NullPointerException("ID field is null! (Has the bean been saved?)");
// Delete sub beans // Delete sub beans
@ -303,10 +303,10 @@ public abstract class DBBean {
for (DBBean subObj : list) { for (DBBean subObj : list) {
// Delete links // Delete links
if (subBeanField.isStandaloneLinkTable()) { if (subBeanField.isStandaloneLinkTable()) {
String sql = "DELETE FROM "+subBeanField.getLinkTableName()+" WHERE "+subBeanField.getParentIdColumnName()+"=?"; String sql = "DELETE FROM " + subBeanField.getLinkTableName() + " WHERE " + subBeanField.getParentIdColumnName() + "=?";
logger.finest("Delete link, query: "+sql); logger.finest("Delete link, query: " + sql);
PreparedStatement stmt = db.getPreparedStatement( sql ); PreparedStatement stmt = db.getPreparedStatement(sql);
stmt.setLong(1, this.getId() ); stmt.setLong(1, this.getId());
DBConnection.exec(stmt); DBConnection.exec(stmt);
} }
// Delete sub beans // Delete sub beans
@ -317,10 +317,10 @@ public abstract class DBBean {
} }
// Delete this bean from DB // Delete this bean from DB
String sql = "DELETE FROM "+config.getTableName()+" WHERE "+config.getIdColumnName()+"=?"; String sql = "DELETE FROM " + config.getTableName() + " WHERE " + config.getIdColumnName() + "=?";
logger.finest("Delete Bean("+c.getName()+", id: "+this.getId()+") query: "+sql); logger.finest("Delete Bean(" + c.getName() + ", id: " + this.getId() + ") query: " + sql);
PreparedStatement stmt = db.getPreparedStatement( sql ); PreparedStatement stmt = db.getPreparedStatement(sql);
stmt.setLong(1, this.getId() ); stmt.setLong(1, this.getId());
DBConnection.exec(stmt); DBConnection.exec(stmt);
// Clear cache and reset id // Clear cache and reset id
@ -339,13 +339,13 @@ public abstract class DBBean {
*/ */
public static <T extends DBBean> List<T> load(DBConnection db, Class<T> c) throws SQLException { public static <T extends DBBean> List<T> load(DBConnection db, Class<T> c) throws SQLException {
// Initiate a BeanConfig if there is non // Initiate a BeanConfig if there is non
DBBeanConfig config = DBBeanConfig.getBeanConfig( c ); DBBeanConfig config = DBBeanConfig.getBeanConfig(c);
// Generate query // Generate query
String sql = "SELECT * FROM "+config.getTableName(); String sql = "SELECT * FROM " +config.getTableName();
logger.finest("Load all Beans("+c.getName()+") query: "+sql); logger.finest("Load all Beans(" + c.getName() + ") query: " + sql);
PreparedStatement stmt = db.getPreparedStatement( sql ); PreparedStatement stmt = db.getPreparedStatement(sql);
// Run query // 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 extends DBBean> T load(DBConnection db, Class<T> c, long id) throws SQLException { public static <T extends DBBean> T load(DBConnection db, Class<T> c, long id) throws SQLException {
// Initiate a BeanConfig if there is non // Initiate a BeanConfig if there is non
DBBeanConfig config = DBBeanConfig.getBeanConfig( c ); DBBeanConfig config = DBBeanConfig.getBeanConfig(c);
// Generate query // Generate query
String sql = "SELECT * FROM "+config.getTableName()+" WHERE "+config.getIdColumnName()+"=? LIMIT 1"; String sql = "SELECT * FROM " + config.getTableName() + " WHERE " + config.getIdColumnName() + "=? LIMIT 1";
logger.finest("Load Bean("+c.getName()+", id: "+id+") query: "+sql); logger.finest("Load Bean(" + c.getName() + ", id: " + id + ") query: " + sql);
PreparedStatement stmt = db.getPreparedStatement( sql ); PreparedStatement stmt = db.getPreparedStatement(sql);
stmt.setObject(1, id ); stmt.setObject(1, id);
// Run query // Run query
T obj = DBConnection.exec(stmt, DBBeanSQLResultHandler.create(c, db) ); T obj = DBConnection.exec(stmt, DBBeanSQLResultHandler.create(c, db));
return obj; return obj;
} }
@ -391,7 +391,7 @@ public abstract class DBBean {
query.append(classToDBType(Long.class)); query.append(classToDBType(Long.class));
query.append(" PRIMARY KEY AUTO_INCREMENT, "); query.append(" PRIMARY KEY AUTO_INCREMENT, ");
for( DBBeanFieldConfig field : config.getFields() ){ for (DBBeanFieldConfig field : config.getFields()) {
query.append(" "); query.append(" ");
query.append(field.getName()); query.append(field.getName());
query.append(classToDBType(c)); query.append(classToDBType(c));
@ -400,33 +400,33 @@ public abstract class DBBean {
query.delete(query.length()-2, query.length()); query.delete(query.length()-2, query.length());
query.append(")"); 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()); PreparedStatement stmt = db.getPreparedStatement(db.toString());
// Execute the SQL // Execute the SQL
DBConnection.exec(stmt); DBConnection.exec(stmt);
} }
private static String classToDBType(Class<?> c){ private static String classToDBType(Class<?> c) {
if( c == String.class) return "CLOB"; // TEXT if ( c == String.class) return "CLOB"; // TEXT
else if(c == Short.class) return "SMALLINT"; else if (c == Short.class) return "SMALLINT";
else if(c == short.class) return "SMALLINT"; else if (c == short.class) return "SMALLINT";
else if(c == Integer.class) return "INTEGER"; else if (c == Integer.class) return "INTEGER";
else if(c == int.class) return "INTEGER"; else if (c == int.class) return "INTEGER";
else if(c == BigInteger.class) return "BIGINT"; else if (c == BigInteger.class) return "BIGINT";
else if(c == Long.class) return "DECIMAL"; else if (c == Long.class) return "DECIMAL";
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 == 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 == double.class) return "DOUBLE"; else if (c == double.class) return "DOUBLE";
else if(c == BigDecimal.class) return "DECIMAL"; else if (c == BigDecimal.class) return "DECIMAL";
else if(c == Boolean.class) return "BOOLEAN"; else if (c == Boolean.class) return "BOOLEAN";
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 == byte.class) return "BINARY(1)"; else if (c == byte.class) return "BINARY(1)";
else if(c == Timestamp.class) return "DATETIME"; else if (c == Timestamp.class) return "DATETIME";
else if(DBBean.class.isAssignableFrom(c)) else if (DBBean.class.isAssignableFrom(c))
return classToDBType(Long.class); return classToDBType(Long.class);
return null; return null;
} }
@ -434,11 +434,11 @@ public abstract class DBBean {
/** /**
* @return the bean id or null if the bean has not bean saved yet * @return the bean id or null if the bean has not bean saved yet
*/ */
public final Long getId(){ public final Long getId() {
return id; return id;
} }
final void setId(Long id){ final void setId(Long id) {
this.id = id; this.id = id;
} }
@ -449,5 +449,5 @@ public abstract class DBBean {
/** /**
* Will be called whenever the bean has been updated from the database. * Will be called whenever the bean has been updated from the database.
*/ */
protected void postUpdateAction(){} protected void postUpdateAction() {}
} }

View file

@ -50,27 +50,27 @@ class DBBeanConfig{
private ArrayList<DBBeanSubBeanConfig> subBeanFields = new ArrayList<>(); private ArrayList<DBBeanSubBeanConfig> subBeanFields = new ArrayList<>();
private DBBeanConfig(){ } private DBBeanConfig() { }
/** /**
* @return the configuration object for the specified class * @return the configuration object for the specified class
*/ */
public static DBBeanConfig getBeanConfig(Class<? extends DBBean> c){ public static DBBeanConfig getBeanConfig(Class<? extends DBBean> c) {
if( !beanConfigs.containsKey( c.getName() ) ) if (!beanConfigs.containsKey(c.getName()))
initBeanConfig( c ); initBeanConfig(c);
return beanConfigs.get( c.getName() ); return beanConfigs.get(c.getName());
} }
/** /**
* Caches the fields * Caches the fields
*/ */
private static void initBeanConfig(Class<? extends DBBean> c){ private static void initBeanConfig(Class<? extends DBBean> c) {
DBBeanConfig config = new DBBeanConfig(); DBBeanConfig config = new DBBeanConfig();
// Find the table name // Find the table name
DBBean.DBTable tableAnn = c.getAnnotation(DBBean.DBTable.class); DBBean.DBTable tableAnn = c.getAnnotation(DBBean.DBTable.class);
if( tableAnn != null ){ if (tableAnn != null) {
config.tableName = tableAnn.value(); config.tableName = tableAnn.value();
config.idColumnName = tableAnn.idColumn(); config.idColumnName = tableAnn.idColumn();
} else { } else {
@ -79,14 +79,14 @@ class DBBeanConfig{
} }
// Add the fields in the bean and all the super classes fields // 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(); Field[] fields = cc.getDeclaredFields();
for( Field field : fields ){ for (Field field : fields) {
int mod = field.getModifiers(); int mod = field.getModifiers();
if( !Modifier.isTransient( mod ) && if (!Modifier.isTransient(mod) &&
!Modifier.isFinal( mod ) && !Modifier.isFinal(mod) &&
!Modifier.isStatic( mod ) && !Modifier.isStatic(mod) &&
!config.fields.contains( field )){ !config.fields.contains(field)) {
if (List.class.isAssignableFrom(field.getType()) && if (List.class.isAssignableFrom(field.getType()) &&
field.getAnnotation(DBBean.DBLinkTable.class) != null) field.getAnnotation(DBBean.DBLinkTable.class) != null)
config.subBeanFields.add(new DBBeanSubBeanConfig(field)); config.subBeanFields.add(new DBBeanSubBeanConfig(field));
@ -94,7 +94,7 @@ class DBBeanConfig{
config.fields.add(new DBBeanFieldConfig(field)); config.fields.add(new DBBeanFieldConfig(field));
} }
} }
if( tableAnn == null || !tableAnn.superBean() ) if (tableAnn == null || !tableAnn.superBean())
break; break;
} }
@ -102,19 +102,19 @@ class DBBeanConfig{
} }
public String getTableName(){ public String getTableName() {
return tableName; return tableName;
} }
public String getIdColumnName(){ public String getIdColumnName() {
return idColumnName; return idColumnName;
} }
public List<DBBeanFieldConfig> getFields(){ public List<DBBeanFieldConfig> getFields() {
return fields; return fields;
} }
public List<DBBeanSubBeanConfig> getSubBeans(){ public List<DBBeanSubBeanConfig> getSubBeans() {
return subBeanFields; return subBeanFields;
} }
@ -123,31 +123,31 @@ class DBBeanConfig{
private Field field; private Field field;
private String fieldName; private String fieldName;
private DBBeanFieldConfig(Field field){ private DBBeanFieldConfig(Field field) {
this.field = field; this.field = field;
if( !Modifier.isPublic( field.getModifiers())) if (!Modifier.isPublic(field.getModifiers()))
field.setAccessible(true); field.setAccessible(true);
DBBean.DBColumn colAnnotation = field.getAnnotation(DBBean.DBColumn.class); DBBean.DBColumn colAnnotation = field.getAnnotation(DBBean.DBColumn.class);
if(colAnnotation != null) if (colAnnotation != null)
fieldName = colAnnotation.value(); fieldName = colAnnotation.value();
else else
fieldName = field.getName(); fieldName = field.getName();
} }
public String getName(){ public String getName() {
return fieldName; return fieldName;
} }
public Class<?> getType(){ public Class<?> getType() {
return field.getType(); return field.getType();
} }
public Object getValue(Object obj) { public Object getValue(Object obj) {
try { try {
return field.get(obj); return field.get(obj);
} catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
@ -175,7 +175,7 @@ class DBBeanConfig{
else else
field.set(obj, fieldValue); field.set(obj, fieldValue);
} }
} catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -188,7 +188,7 @@ class DBBeanConfig{
private DBBeanConfig subBeanConfig; private DBBeanConfig subBeanConfig;
private String parentIdCol; private String parentIdCol;
private DBBeanSubBeanConfig(Field field){ private DBBeanSubBeanConfig(Field field) {
super(field); super(field);
DBBean.DBLinkTable linkAnnotation = field.getAnnotation(DBBean.DBLinkTable.class); DBBean.DBLinkTable linkAnnotation = field.getAnnotation(DBBean.DBLinkTable.class);
@ -203,7 +203,7 @@ class DBBeanConfig{
return linkTableName; return linkTableName;
} }
public boolean isStandaloneLinkTable(){ public boolean isStandaloneLinkTable() {
return !linkTableName.equals(subBeanConfig.tableName); return !linkTableName.equals(subBeanConfig.tableName);
} }

View file

@ -91,7 +91,7 @@ public abstract class DBBeanObjectDSO<T> extends DBBean{
public T getObject(){ public T getObject() {
return cachedObj; return cachedObj;
} }
@ -100,8 +100,8 @@ public abstract class DBBeanObjectDSO<T> extends DBBean{
* *
* @param obj is the object to set or null to reset the DSO * @param obj is the object to set or null to reset the DSO
*/ */
public void setObject(T obj){ public void setObject(T obj) {
if(obj != null) { if (obj != null) {
type = obj.getClass().getName(); type = obj.getClass().getName();
config = null; config = null;
cachedObj = obj; cachedObj = obj;
@ -112,15 +112,15 @@ public abstract class DBBeanObjectDSO<T> extends DBBean{
} }
} }
public String getObjectClass(){ public String getObjectClass() {
return type; return type;
} }
public void setObjectClass(Class<? extends T> clazz){ public void setObjectClass(Class<? extends T> clazz) {
setObjectClass(clazz.getName()); setObjectClass(clazz.getName());
} }
public void setObjectClass(String clazz){ public void setObjectClass(String clazz) {
if (this.type == null || !this.type.equals(type)) { if (this.type == null || !this.type.equals(type)) {
// TODO: check if clazz is subclass of T // TODO: check if clazz is subclass of T
setObject(null); setObject(null);
@ -129,15 +129,15 @@ public abstract class DBBeanObjectDSO<T> extends DBBean{
} }
} }
public Configurator<T> getObjectConfigurator(){ public Configurator<T> getObjectConfigurator() {
return new Configurator<>(cachedObj); return new Configurator<>(cachedObj);
} }
public String toString(){ public String toString() {
Object obj = getObject(); Object obj = getObject();
if (obj != null) if (obj != null)
return obj.toString(); return obj.toString();
return "null (DSO: "+ super.toString() +")"; return "null (DSO: " + super.toString() + ")";
} }
} }

View file

@ -46,21 +46,21 @@ public class ListSQLResult<T> implements SQLResultHandler<List<T>> {
/** /**
* Creates a new List. * Creates a new List.
*/ */
public ListSQLResult(){ public ListSQLResult() {
this.list = new ArrayList<>(); this.list = new ArrayList<>();
} }
/** /**
* Uses a existing list that items will be appended on. * Uses a existing list that items will be appended on.
*/ */
public ListSQLResult(List l){ public ListSQLResult(List l) {
this.list = l; this.list = l;
} }
public List<T> handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ public List<T> handleQueryResult(Statement stmt, ResultSet result) throws SQLException{
while( result.next() ) while (result.next())
list.add((T)result.getObject(1)); list.add((T)result.getObject(1));
return list; return list;
} }

View file

@ -46,14 +46,14 @@ public class PropertiesSQLResult implements SQLResultHandler<Properties> {
/** /**
* Creates a new Properties object to be filled * Creates a new Properties object to be filled
*/ */
public PropertiesSQLResult(){ public PropertiesSQLResult() {
this.prop = new Properties(); this.prop = new Properties();
} }
/** /**
* Adds data to a existing Properties object * Adds data to a existing Properties object
*/ */
public PropertiesSQLResult(Properties p){ public PropertiesSQLResult(Properties p) {
this.prop = p; this.prop = p;
} }
@ -62,7 +62,7 @@ public class PropertiesSQLResult implements SQLResultHandler<Properties> {
* Is called to handle an result from an query. * Is called to handle an result from an query.
*/ */
public Properties handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ public Properties handleQueryResult(Statement stmt, ResultSet result) throws SQLException{
while( result.next() ) while (result.next())
prop.setProperty(result.getString(1), result.getString(2)); prop.setProperty(result.getString(1), result.getString(2));
return prop; return prop;
} }

View file

@ -44,7 +44,7 @@ public class SimpleSQLResult<T> implements SQLResultHandler<T> {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ public T handleQueryResult(Statement stmt, ResultSet result) throws SQLException{
if( result.next() ) if (result.next())
return (T) result.getObject(1); return (T) result.getObject(1);
return null; return null;
} }

View file

@ -40,7 +40,7 @@ public abstract class ImageFilterProcessor {
private BufferedImage img; private BufferedImage img;
private ProgressListener<ImageFilterProcessor,?> progress; private ProgressListener<ImageFilterProcessor,?> progress;
public ImageFilterProcessor(BufferedImage img){ public ImageFilterProcessor(BufferedImage img) {
this.img = img; this.img = img;
} }
@ -48,22 +48,23 @@ public abstract class ImageFilterProcessor {
* Sets the listener * Sets the listener
* @param listener is the listener, null to disable the progress * @param listener is the listener, null to disable the progress
*/ */
public void setProgressListener(ProgressListener<ImageFilterProcessor,?> listener){ public void setProgressListener(ProgressListener<ImageFilterProcessor,?> listener) {
this.progress = listener; this.progress = listener;
} }
/** /**
* Returns the listener * Returns the listener
*/ */
public ProgressListener<?,?> getProgressListener(){ public ProgressListener<?,?> getProgressListener() {
return this.progress; return this.progress;
} }
/** /**
* Sets the progress in percent * Sets the progress in percent
*/ */
protected void setProgress(double percent){ protected void setProgress(double percent) {
if(progress != null) progress.progressUpdate(this, null, percent); if (progress != null)
progress.progressUpdate(this, null, percent);
} }
/** /**
@ -88,7 +89,7 @@ public abstract class ImageFilterProcessor {
int cols = img.getWidth(); int cols = img.getWidth();
int rows = img.getHeight(); int rows = img.getHeight();
if(cols < 0 || rows < 0){ if (cols < 0 || rows < 0) {
throw new InterruptedException("Image not Loaded!!!"); 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); int[] pixels = img.getRGB(0, 0, cols, rows, null, 0, cols);
// Read the pixel data and put it in the data array // Read the pixel data and put it in the data array
for(int y=0; y<rows ;y++){ for (int y=0; y<rows; y++) {
// reading a row // reading a row
int[] aRow = new int[cols]; int[] aRow = new int[cols];
for(int x=0; x<cols ;x++){ for (int x=0; x<cols; x++) {
int element = y * cols + x; int element = y * cols + x;
aRow[x] = pixels[element]; aRow[x] = pixels[element];
} }
// Reading in the color data // Reading in the color data
for(int x=0; x<cols ;x++){ for (int x=0; x<cols; x++) {
//Alpha data //Alpha data
data[y][x][0] = ((aRow[x] >> 24) & 0xFF); data[y][x][0] = ((aRow[x] >> 24) & 0xFF);
//Red data //Red data
@ -151,7 +152,7 @@ public abstract class ImageFilterProcessor {
* @param rows is the rows of the image * @param rows is the rows of the image
* @return A 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]; int[] data = new int[cols * rows * 4];
//Move the data into the 1D array. Note the //Move the data into the 1D array. Note the
@ -159,8 +160,8 @@ public abstract class ImageFilterProcessor {
// bitwise left-shift operators to put the // bitwise left-shift operators to put the
// four 8-bit bytes into each int. // four 8-bit bytes into each int.
int index = 0; int index = 0;
for(int y=0; y<rows ;y++){ for (int y=0; y<rows; y++) {
for(int x=0; x< cols ;x++){ for (int x=0; x< cols; x++) {
data[index] = ((pixels[y][x][0] << 24) & 0xFF000000) data[index] = ((pixels[y][x][0] << 24) & 0xFF000000)
| ((pixels[y][x][1] << 16) & 0x00FF0000) | ((pixels[y][x][1] << 16) & 0x00FF0000)
| ((pixels[y][x][2] << 8) & 0x0000FF00) | ((pixels[y][x][2] << 8) & 0x0000FF00)
@ -181,7 +182,7 @@ public abstract class ImageFilterProcessor {
* *
* @param data is the raw image to apply the effect to. This will NOT be altered * @param data is the raw image to apply the effect to. This will NOT be altered
*/ */
public int[][][] process(int[][][] data){ public int[][][] process(int[][][] data) {
return process(data, 0, 0, data[0].length, data.length); return process(data, 0, 0, data[0].length, data.length);
} }

View file

@ -44,15 +44,15 @@ public class ImageUtil {
* @param keep_aspect is if the aspect ratio of the image should be kept * @param keep_aspect is if the aspect ratio of the image should be kept
* @return the resized image * @return the resized image
*/ */
public static BufferedImage scale(BufferedImage source, int width, int height, boolean keep_aspect){ public static BufferedImage scale(BufferedImage source, int width, int height, boolean keep_aspect) {
double scale_width = (double)width / source.getWidth(); double scale_width = (double)width / source.getWidth();
double scale_height = (double)height / source.getHeight(); double scale_height = (double)height / source.getHeight();
// aspect calculation // aspect calculation
if(keep_aspect){ if (keep_aspect) {
if(scale_width * source.getHeight() > height){ if (scale_width * source.getHeight() > height) {
scale_width = scale_height; scale_width = scale_height;
}else{ } else {
scale_height = scale_width; scale_height = scale_width;
} }
} }
@ -78,17 +78,17 @@ public class ImageUtil {
* @param aspect is the aspect ratio to convert the image to * @param aspect is the aspect ratio to convert the image to
* @return a new image with the specified aspect ratio * @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 x = 0, y = 0;
int width = image.getWidth(); int width = image.getWidth();
int height = image.getHeight(); int height = image.getHeight();
// Check if the width is larger than the heigth // Check if the width is larger than the heigth
if( width > height ){ if (width > height) {
width = (int) (height * aspect); width = (int) (height * aspect);
x = image.getWidth()/2 - width/2; x = image.getWidth()/2 - width/2;
} }
else{ else {
height = (int) (width * aspect); height = (int) (width * aspect);
y = image.getHeight()/2 - height/2; y = image.getHeight()/2 - height/2;
} }
@ -106,7 +106,7 @@ public class ImageUtil {
* @param height is the wanted height * @param height is the wanted height
* @return a new image with the specified width and 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; float aspect = width/height;
BufferedImage tmp = cropToAspectRatio(source, aspect); BufferedImage tmp = cropToAspectRatio(source, aspect);
tmp = scale(tmp, width, height, false); tmp = scale(tmp, width, height, false);

View file

@ -53,11 +53,11 @@ public class RAWImageUtil {
*/ */
public static int getPeakValue(int[][][] data, int startX, int startY, int stopX, int stopY) { public static int getPeakValue(int[][][] data, int startX, int startY, int stopX, int stopY) {
int peak = 0; int peak = 0;
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
if(data[y][x][1] > peak) peak = data[y][x][1]; if (data[y][x][1] > peak) peak = data[y][x][1];
if(data[y][x][2] > peak) peak = data[y][x][2]; if (data[y][x][2] > peak) peak = data[y][x][2];
if(data[y][x][3] > peak) peak = data[y][x][3]; if (data[y][x][3] > peak) peak = data[y][x][3];
} }
} }
return peak; return peak;
@ -74,8 +74,8 @@ public class RAWImageUtil {
* @param scale The scale to normalize the image by * @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) { public static void normalize(int[][][] data, int startX, int startY, int stopX, int stopY, double scale) {
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
data[y][x][1] = (int)(data[y][x][1] * scale); data[y][x][1] = (int)(data[y][x][1] * scale);
data[y][x][2] = (int)(data[y][x][2] * scale); data[y][x][2] = (int)(data[y][x][2] * scale);
data[y][x][3] = (int)(data[y][x][3] * scale); data[y][x][3] = (int)(data[y][x][3] * scale);
@ -95,8 +95,8 @@ public class RAWImageUtil {
* @param scale the scale to normalize the image by * @param scale the scale to normalize the image by
*/ */
public static void normalize(int[][][] output, int[][][] data, int startX, int startY, int stopX, int stopY, double scale) { public static void normalize(int[][][] output, int[][][] data, int startX, int startY, int stopX, int stopY, double scale) {
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
output[y][x][1] = (int)(data[y][x][1] * scale); output[y][x][1] = (int)(data[y][x][1] * scale);
output[y][x][2] = (int)(data[y][x][2] * scale); output[y][x][2] = (int)(data[y][x][2] * scale);
output[y][x][3] = (int)(data[y][x][3] * scale); output[y][x][3] = (int)(data[y][x][3] * scale);
@ -115,11 +115,11 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop * @param stopY is the y pixel of the image to stop
* @return the RMS value for the image * @return the RMS value for the image
*/ */
public static int getRMS(int[][][] data, int startX, int startY, int stopX, int stopY){ public static int getRMS(int[][][] data, int startX, int startY, int stopX, int stopY) {
int pixelCount = 0; int pixelCount = 0;
long accum = 0; long accum = 0;
for(int y=startY; y <stopY ;y++){ for (int y=startY; y <stopY; y++) {
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
accum += data[y][x][1] * data[y][x][1]; accum += data[y][x][1] * data[y][x][1];
accum += data[y][x][2] * data[y][x][2]; accum += data[y][x][2] * data[y][x][2];
accum += data[y][x][3] * data[y][x][3]; accum += data[y][x][3] * data[y][x][3];
@ -140,9 +140,9 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop * @param stopY is the y pixel of the image to stop
* @param scale is the number to scale the image color by * @param scale is the number to scale the image color by
*/ */
public static void scale(int[][][] data, int startX, int startY, int stopX, int stopY, double scale){ public static void scale(int[][][] data, int startX, int startY, int stopX, int stopY, double scale) {
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
data[y][x][1] *= scale; data[y][x][1] *= scale;
data[y][x][2] *= scale; data[y][x][2] *= scale;
data[y][x][3] *= scale; data[y][x][3] *= scale;
@ -156,7 +156,7 @@ public class RAWImageUtil {
* @param data is the image data * @param data is the image data
* @return the mean value of the image * @return the mean value of the image
*/ */
public static int getMeanValue(int[][][] data){ public static int getMeanValue(int[][][] data) {
return getMeanValue(data, 0, 0, data[0].length, data.length); return getMeanValue(data, 0, 0, data[0].length, data.length);
} }
@ -170,7 +170,7 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop * @param stopY is the y pixel of the image to stop
* @return the mean value of the image * @return the mean value of the image
*/ */
public static int getMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY){ public static int getMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY) {
int[] tmp = getMeanArray(data, startX, startY, stopX, stopY); int[] tmp = getMeanArray(data, startX, startY, stopX, stopY);
return (tmp[0] + tmp[1] + tmp[2])/3; return (tmp[0] + tmp[1] + tmp[2])/3;
} }
@ -185,17 +185,17 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop * @param stopY is the y pixel of the image to stop
* @return the mean value of the image * @return the mean value of the image
*/ */
public static int[] getMeanArray(int[][][] data, int startX, int startY, int stopX, int stopY){ public static int[] getMeanArray(int[][][] data, int startX, int startY, int stopX, int stopY) {
int mean[] = new int[3]; int mean[] = new int[3];
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
mean[0] += data[y][x][1]; mean[0] += data[y][x][1];
mean[1] += data[y][x][2]; mean[1] += data[y][x][2];
mean[2] += data[y][x][3]; mean[2] += data[y][x][3];
} }
} }
// calculate the mean value // calculate the mean value
int pixelCount = (stopY-startY)*(stopX-startX); int pixelCount = (stopY - startY) * (stopX - startX);
mean[0] /= pixelCount; mean[0] /= pixelCount;
mean[1] /= pixelCount; mean[1] /= pixelCount;
mean[2] /= pixelCount; mean[2] /= pixelCount;
@ -213,7 +213,7 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop * @param stopY is the y pixel of the image to stop
* @param mean is the mean value * @param mean is the mean value
*/ */
public static void remMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY, int mean){ public static void remMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY, int mean) {
addMeanValue(data, startX, startY, stopX, stopY, -mean); addMeanValue(data, startX, startY, stopX, stopY, -mean);
} }
@ -227,7 +227,7 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop * @param stopY is the y pixel of the image to stop
* @param mean is the mean value * @param mean is the mean value
*/ */
public static void addMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY, int mean){ public static void addMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY, int mean) {
addMeanArray(data, startX, startY, stopX, stopY, new int[]{mean, mean, mean}); addMeanArray(data, startX, startY, stopX, stopY, new int[]{mean, mean, mean});
} }
@ -241,7 +241,7 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop * @param stopY is the y pixel of the image to stop
* @param mean is an array of length 3 containing a mean value for each color RGB * @param mean is an array of length 3 containing a mean value for each color RGB
*/ */
public static void remMeanArray(int[][][] data, int startX, int startY, int stopX, int stopY, int[] mean){ public static void remMeanArray(int[][][] data, int startX, int startY, int stopX, int stopY, int[] mean) {
addMeanArray(data, startX, startY, stopX, stopY, new int[]{-mean[0], -mean[1], -mean[2]}); addMeanArray(data, startX, startY, stopX, stopY, new int[]{-mean[0], -mean[1], -mean[2]});
} }
@ -255,9 +255,9 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop * @param stopY is the y pixel of the image to stop
* @param mean is an array of length 3 containing a mean value for each color RGB * @param mean is an array of length 3 containing a mean value for each color RGB
*/ */
public static void addMeanArray(int[][][] data, int startX, int startY, int stopX, int stopY, int[] mean){ public static void addMeanArray(int[][][] data, int startX, int startY, int stopX, int stopY, int[] mean) {
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
data[y][x][1] += mean[0]; data[y][x][1] += mean[0];
data[y][x][2] += mean[1]; data[y][x][2] += mean[1];
data[y][x][3] += mean[2]; data[y][x][3] += mean[2];
@ -275,7 +275,7 @@ public class RAWImageUtil {
* @param height The amount of pixels to copy * @param height The amount of pixels to copy
* @return A copy of the data array * @return A copy of the data array
*/ */
public static int[][][] crop(int[][][] data, int xStart, int yStart, int width, int height){ public static int[][][] crop(int[][][] data, int xStart, int yStart, int width, int height) {
return crop(data, xStart, yStart, null, 0, 0, width, height); return crop(data, xStart, yStart, null, 0, 0, width, height);
} }
@ -292,10 +292,12 @@ public class RAWImageUtil {
* @param height The amount of pixels to copy * @param height The amount of pixels to copy
* @return A copy of the data array * @return A copy of the data array
*/ */
public static int[][][] crop(int[][][] data, int xData, int yData, int[][][] crop, int xCrop, int yCrop, int width, int height){ public static int[][][] crop(int[][][] data, int xData, int yData, int[][][] crop, int xCrop, int yCrop, int width, int height) {
if(crop==null) crop = new int[width][height][4]; if (crop == null)
for(int y=0; y<width ;y++){ crop = new int[width][height][4];
for(int x=0; x<height ;x++){
for (int y=0; y<width; y++) {
for (int x=0; x<height; x++) {
crop[y+yData][x+xData][0] = data[y+yCrop][x+xCrop][0]; crop[y+yData][x+xData][0] = data[y+yCrop][x+xCrop][0];
crop[y+yData][x+xData][1] = data[y+yCrop][x+xCrop][1]; crop[y+yData][x+xData][1] = data[y+yCrop][x+xCrop][1];
crop[y+yData][x+xData][2] = data[y+yCrop][x+xCrop][2]; crop[y+yData][x+xData][2] = data[y+yCrop][x+xCrop][2];
@ -311,7 +313,7 @@ public class RAWImageUtil {
* @param data The data to duplicate * @param data The data to duplicate
* @return an copy of the array * @return an copy of the array
*/ */
public static int[][][] copyArray(int[][][] data){ public static int[][][] copyArray(int[][][] data) {
return copyArray(data, 0, 0, data[0].length, data.length); return copyArray(data, 0, 0, data[0].length, data.length);
} }
@ -325,7 +327,7 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop * @param stopY is the y pixel of the image to stop
* @return The array copy * @return The array copy
*/ */
public static int[][][] copyArray(int[][][] data, int startX, int startY, int stopX, int stopY){ public static int[][][] copyArray(int[][][] data, int startX, int startY, int stopX, int stopY) {
int[][][] copy = new int[data.length][data[0].length][4]; int[][][] copy = new int[data.length][data[0].length][4];
return copyArray(data, copy, startX, startY, stopX, stopY); return copyArray(data, copy, startX, startY, stopX, stopY);
} }
@ -341,9 +343,9 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop * @param stopY is the y pixel of the image to stop
* @return the dest array * @return the dest array
*/ */
public static int[][][] copyArray(int[][][] data, int[][][] dest, int startX, int startY, int stopX, int stopY){ public static int[][][] copyArray(int[][][] data, int[][][] dest, int startX, int startY, int stopX, int stopY) {
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
dest[y][x][0] = data[y][x][0]; dest[y][x][0] = data[y][x][0];
dest[y][x][1] = data[y][x][1]; dest[y][x][1] = data[y][x][1];
dest[y][x][2] = data[y][x][2]; dest[y][x][2] = data[y][x][2];
@ -363,9 +365,9 @@ public class RAWImageUtil {
* @param stopX is the x pixel of the image to stop * @param stopX is the x pixel of the image to stop
* @param stopY is the y pixel of the image to stop * @param stopY is the y pixel of the image to stop
*/ */
public static void clip(int[][][] data, int startX, int startY, int stopX, int stopY){ public static void clip(int[][][] data, int startX, int startY, int stopX, int stopY) {
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
data[y][x][1] = clip(data[y][x][1]); data[y][x][1] = clip(data[y][x][1]);
data[y][x][2] = clip(data[y][x][2]); data[y][x][2] = clip(data[y][x][2]);
data[y][x][3] = clip(data[y][x][3]); data[y][x][3] = clip(data[y][x][3]);
@ -377,10 +379,10 @@ public class RAWImageUtil {
* This method clips the values of a color so that it * This method clips the values of a color so that it
* is in the range 0-255 * is in the range 0-255
*/ */
public static int clip(int color){ public static int clip(int color) {
if(color < 0) if (color < 0)
return 0; return 0;
else if(color > 255) else if (color > 255)
return 255; return 255;
else else
return color; return color;

View file

@ -37,7 +37,7 @@ public class BlurFilter extends ImageFilterProcessor{
* Creates a blur effect on the image * Creates a blur effect on the image
* @param img The image to blur * @param img The image to blur
*/ */
public BlurFilter(BufferedImage img){ public BlurFilter(BufferedImage img) {
this(img, 10); this(img, 10);
} }
@ -46,7 +46,7 @@ public class BlurFilter extends ImageFilterProcessor{
* @param img The image to blur * @param img The image to blur
* @param blur The amount to blur * @param blur The amount to blur
*/ */
public BlurFilter(BufferedImage img, int blur){ public BlurFilter(BufferedImage img, int blur) {
super(img); super(img);
blurValue = blur; blurValue = blur;
} }
@ -59,17 +59,17 @@ public class BlurFilter extends ImageFilterProcessor{
int[][][] output = RAWImageUtil.copyArray(data); int[][][] output = RAWImageUtil.copyArray(data);
//Perform the convolution one or more times in succession //Perform the convolution one or more times in succession
int redSum, greenSum, blueSum, outputPeak; int redSum, greenSum, blueSum, outputPeak;
for(int i=0; i<blurValue ;i++){ for (int i=0; i<blurValue; i++) {
//Iterate on each pixel as a registration point. //Iterate on each pixel as a registration point.
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
setProgress(ZMath.percent(0, (blurValue-1)*(stopY-startY-2), i*(stopY-startY-2)+y)); setProgress(ZMath.percent(0, (blurValue-1)*(stopY-startY-2), i*(stopY-startY-2)+y));
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
if(x == 0 || x == output[0].length-1 || y == 0 || y == output.length-1){ if (x == 0 || x == output[0].length-1 || y == 0 || y == output.length-1) {
redSum = output[y][x][1] * 9; redSum = output[y][x][1] * 9;
greenSum = output[y][x][2] * 9; greenSum = output[y][x][2] * 9;
blueSum = output[y][x][3] * 9; blueSum = output[y][x][3] * 9;
} }
else{ else {
redSum = redSum =
output[y - 1][x - 1][1] + output[y - 1][x - 1][1] +
output[y - 1][x - 0][1] + output[y - 1][x - 0][1] +
@ -110,7 +110,7 @@ public class BlurFilter extends ImageFilterProcessor{
// getting the new peak value and normalizing the image // getting the new peak value and normalizing the image
outputPeak = RAWImageUtil.getPeakValue(tmpData); outputPeak = RAWImageUtil.getPeakValue(tmpData);
RAWImageUtil.normalize(output, tmpData, startX, startY, stopX, stopY, ((double)inputPeak)/outputPeak ); RAWImageUtil.normalize(output, tmpData, startX, startY, stopX, stopY, ((double)inputPeak)/outputPeak);
} }
return output; return output;
} }

View file

@ -35,7 +35,7 @@ public class ColorIntensityFilter extends ImageFilterProcessor{
private double greenScale; private double greenScale;
private double blueScale; private double blueScale;
public ColorIntensityFilter(BufferedImage img){ public ColorIntensityFilter(BufferedImage img) {
this(img, 0.2, 0.2, 0.2, false); this(img, 0.2, 0.2, 0.2, false);
} }
@ -44,7 +44,7 @@ public class ColorIntensityFilter extends ImageFilterProcessor{
* @param img The image data * @param img The image data
* @param inv If the image color should be inverted * @param inv If the image color should be inverted
*/ */
public ColorIntensityFilter(BufferedImage img, boolean inv){ public ColorIntensityFilter(BufferedImage img, boolean inv) {
this(img, 0.5, 0.5, 0.5, inv); this(img, 0.5, 0.5, 0.5, inv);
} }
@ -55,7 +55,7 @@ public class ColorIntensityFilter extends ImageFilterProcessor{
* @param green The scale of green (0-1) * @param green The scale of green (0-1)
* @param blue The scale of blue (0-1) * @param blue The scale of blue (0-1)
*/ */
public ColorIntensityFilter(BufferedImage img, double red, double green, double blue){ public ColorIntensityFilter(BufferedImage img, double red, double green, double blue) {
this(img, red, green, blue, false); this(img, red, green, blue, false);
} }
@ -67,7 +67,7 @@ public class ColorIntensityFilter extends ImageFilterProcessor{
* @param blue The scale of blue (0-1) * @param blue The scale of blue (0-1)
* @param inv If the image color should be inverted * @param inv If the image color should be inverted
*/ */
public ColorIntensityFilter(BufferedImage img, double red, double green, double blue, boolean inv){ public ColorIntensityFilter(BufferedImage img, double red, double green, double blue, boolean inv) {
super(img); super(img);
invert = false; invert = false;
redScale = red; redScale = red;
@ -79,31 +79,31 @@ public class ColorIntensityFilter extends ImageFilterProcessor{
public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) {
int[][][] output = new int[data.length][data[0].length][4]; int[][][] output = new int[data.length][data[0].length][4];
// making sure the scales are right // making sure the scales are right
if(redScale > 1) redScale = 1; if (redScale > 1) redScale = 1;
else if(redScale < 0) redScale = 0; else if (redScale < 0) redScale = 0;
if(greenScale > 1) greenScale = 1; if (greenScale > 1) greenScale = 1;
else if(greenScale < 0) greenScale = 0; else if (greenScale < 0) greenScale = 0;
if(blueScale > 1) blueScale = 1; if (blueScale > 1) blueScale = 1;
else if(blueScale < 0) blueScale = 0; else if (blueScale < 0) blueScale = 0;
// Applying the color intensity to the image // Applying the color intensity to the image
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
setProgress(ZMath.percent(0, stopY-startY-1, y)); setProgress(ZMath.percent(0, stopY-startY-1, y));
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
if(!invert){ if (!invert) {
// inversion // inversion
output[y][x][0] = data[y][x][0]; output[y][x][0] = data[y][x][0];
output[y][x][1] = (int)( 255 - data[y][x][1] * redScale ); output[y][x][1] = (int)( 255 - data[y][x][1] * redScale);
output[y][x][2] = (int)( 255 - data[y][x][2] * greenScale ); output[y][x][2] = (int)( 255 - data[y][x][2] * greenScale);
output[y][x][3] = (int)( 255 - data[y][x][3] * blueScale ); output[y][x][3] = (int)( 255 - data[y][x][3] * blueScale);
} }
else{ else {
output[y][x][0] = data[y][x][0]; output[y][x][0] = data[y][x][0];
output[y][x][1] = (int)( data[y][x][1] * redScale ); output[y][x][1] = (int)(data[y][x][1] * redScale);
output[y][x][2] = (int)( data[y][x][2] * greenScale ); output[y][x][2] = (int)(data[y][x][2] * greenScale);
output[y][x][3] = (int)( data[y][x][3] * blueScale ); output[y][x][3] = (int)(data[y][x][3] * blueScale);
} }
} }
} }

View file

@ -37,7 +37,7 @@ public class ContrastBrightnessFilter extends ImageFilterProcessor{
* Creates a ContrastBrightnessEffect object with the given values * Creates a ContrastBrightnessEffect object with the given values
* @param img The image to apply the effect to * @param img The image to apply the effect to
*/ */
public ContrastBrightnessFilter(BufferedImage img){ public ContrastBrightnessFilter(BufferedImage img) {
this(img, 3, 1.2); this(img, 3, 1.2);
} }
@ -47,7 +47,7 @@ public class ContrastBrightnessFilter extends ImageFilterProcessor{
* @param con The contrast to apply * @param con The contrast to apply
* @param brig The brightness to apply * @param brig The brightness to apply
*/ */
public ContrastBrightnessFilter(BufferedImage img, double con, double brig){ public ContrastBrightnessFilter(BufferedImage img, double con, double brig) {
super(img); super(img);
contrast = con; contrast = con;
brightness = brig; brightness = brig;

View file

@ -59,21 +59,21 @@ public class ConvolutionFilter extends ImageFilterProcessor{
@Override @Override
public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) {
if(kernel == null) this.kernel = generateKernel(); if (kernel == null) this.kernel = generateKernel();
int[][][] tmpData = new int[data.length][data[0].length][4]; int[][][] tmpData = new int[data.length][data[0].length][4];
int xk_length = kernel[0].length; int xk_length = kernel[0].length;
int yk_length = kernel.length; int yk_length = kernel.length;
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
setProgress(ZMath.percent(0, (stopY-startY), y+1)); setProgress(ZMath.percent(0, (stopY-startY), y+1));
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
tmpData[y][x][0] = data[y][x][0]; // alpha tmpData[y][x][0] = data[y][x][0]; // alpha
for(int yk=0; yk<yk_length ;yk++){ for (int yk=0; yk<yk_length; yk++) {
for(int xk=0; xk<xk_length ;xk++){ for (int xk=0; xk<xk_length; xk++) {
if(0 <= y-yk_length/2+yk && y-yk_length/2+yk < data.length && if (0 <= y-yk_length/2+yk && y-yk_length/2+yk < data.length &&
0 <= x-xk_length/2+xk && x-xk_length/2+xk < data[0].length){ // check that its not out of index 0 <= x-xk_length/2+xk && x-xk_length/2+xk < data[0].length) { // check that its not out of index
tmpData[y][x][1] += data[y-yk_length/2+yk][x-xk_length/2+xk][1] * kernel[yk][xk]; tmpData[y][x][1] += data[y-yk_length/2+yk][x-xk_length/2+xk][1] * kernel[yk][xk];
tmpData[y][x][2] += data[y-yk_length/2+yk][x-xk_length/2+xk][2] * kernel[yk][xk]; tmpData[y][x][2] += data[y-yk_length/2+yk][x-xk_length/2+xk][2] * kernel[yk][xk];
tmpData[y][x][3] += data[y-yk_length/2+yk][x-xk_length/2+xk][3] * kernel[yk][xk]; tmpData[y][x][3] += data[y-yk_length/2+yk][x-xk_length/2+xk][3] * kernel[yk][xk];
@ -91,7 +91,7 @@ public class ConvolutionFilter extends ImageFilterProcessor{
/** /**
* Returns the kernel or null if it has not been generated yet. * Returns the kernel or null if it has not been generated yet.
*/ */
public double[][] getKernel(){ public double[][] getKernel() {
return kernel; return kernel;
} }
@ -100,7 +100,7 @@ public class ConvolutionFilter extends ImageFilterProcessor{
* *
* @return an special generated kernel * @return an special generated kernel
*/ */
protected double[][] generateKernel(){ protected double[][] generateKernel() {
return null; return null;
} }

View file

@ -42,7 +42,7 @@ public class DitheringFilter extends ImageFilterProcessor{
/** /**
* Sets up a default DitheringEffect * Sets up a default DitheringEffect
*/ */
public DitheringFilter(BufferedImage img){ public DitheringFilter(BufferedImage img) {
super(img); super(img);
} }
@ -56,7 +56,7 @@ public class DitheringFilter extends ImageFilterProcessor{
* Green data * Green data
* 4 -&gt; Blue data </pre> * 4 -&gt; Blue data </pre>
*/ */
public DitheringFilter(BufferedImage img, int[][] palette){ public DitheringFilter(BufferedImage img, int[][] palette) {
super(img); super(img);
this.palette = palette; this.palette = palette;
} }
@ -67,9 +67,9 @@ public class DitheringFilter extends ImageFilterProcessor{
int[] currentPixel; int[] currentPixel;
int[][][] output = RAWImageUtil.copyArray(data); int[][][] output = RAWImageUtil.copyArray(data);
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
setProgress(ZMath.percent(0, stopY-startY-1, y)); setProgress(ZMath.percent(0, stopY-startY-1, y));
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
currentPixel = output[y][x]; currentPixel = output[y][x];
index = findNearestColor(currentPixel, palette); index = findNearestColor(currentPixel, palette);
output[y][x] = palette[index]; output[y][x] = palette[index];
@ -77,14 +77,14 @@ public class DitheringFilter extends ImageFilterProcessor{
for (int i = 1; i < 4; i++) { for (int i = 1; i < 4; i++) {
error = currentPixel[i] - palette[index][i]; error = currentPixel[i] - palette[index][i];
if (x + 1 < output[0].length) { if (x + 1 < output[0].length) {
output[y+0][x+1][i] = RAWImageUtil.clip( output[y+0][x+1][i] + (error*7)/16 ); output[y+0][x+1][i] = RAWImageUtil.clip(output[y+0][x+1][i] + (error*7)/16);
} }
if (y + 1 < data.length) { if (y + 1 < data.length) {
if (x - 1 > 0) if (x - 1 > 0)
output[y+1][x-1][i] = RAWImageUtil.clip( output[y+1][x-1][i] + (error*3)/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 ); output[y+1][x+0][i] = RAWImageUtil.clip(output[y+1][x+0][i] + (error*5)/16);
if (x + 1 < data[0].length) 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);
} }
} }
} }

View file

@ -45,24 +45,24 @@ public class GaussianBlurFilter extends ConvolutionFilter{
this.sigma = sigma; this.sigma = sigma;
} }
protected double[][] generateKernel(){ protected double[][] generateKernel() {
return gaussianFunction(size, size, sigma); return gaussianFunction(size, size, sigma);
} }
/** /**
* Generates the kernel from the specified values * 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; double[][] kernel;
int center_x = size_x/2; int center_x = size_x/2;
int center_y = size_y/2; int center_y = size_y/2;
kernel = new double[size_y][size_x]; kernel = new double[size_y][size_x];
for(int y=0; y<size_y ;y++){ for (int y=0; y<size_y; y++) {
for(int x=0; x<size_x ;x++){ for (int x=0; x<size_x; x++) {
double tmp_x = (double)( (x-center_x)*(x-center_x) )/(2*sigma*sigma); double tmp_x = (double)((x - center_x) * (x - center_x)) / (2 * sigma * sigma);
double tmp_y = (double)( (y-center_y)*(y-center_y) )/(2*sigma*sigma); double tmp_y = (double)((y - center_y) * (y - center_y)) / (2 * sigma * sigma);
kernel[y][x] = 1.0/(2*Math.PI*sigma*sigma) * Math.exp( -(tmp_x + tmp_y) ); kernel[y][x] = 1.0 / (2 * Math.PI * sigma * sigma) * Math.exp(-(tmp_x + tmp_y));
} }
} }

View file

@ -54,12 +54,12 @@ public class MeanBlurFilter extends ConvolutionFilter{
this.windowSize = pixels; this.windowSize = pixels;
} }
protected double[][] generateKernel(){ protected double[][] generateKernel() {
double[][] kernel = new double[windowSize][windowSize]; double[][] kernel = new double[windowSize][windowSize];
double mean = 1.0/(windowSize*windowSize); double mean = 1.0/(windowSize*windowSize);
for(int y=0; y<windowSize ;y++){ for (int y=0; y<windowSize; y++) {
for(int x=0; x<windowSize ;x++){ for (int x=0; x<windowSize; x++) {
kernel[y][x] = mean; kernel[y][x] = mean;
} }
} }

View file

@ -93,46 +93,46 @@ public class MedianFilter extends ImageFilterProcessor{
int[][] tmpArray = new int[4][256*2]; int[][] tmpArray = new int[4][256*2];
int pixelCount; int pixelCount;
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
setProgress(ZMath.percent(0, stopY-startY-1, y)); setProgress(ZMath.percent(0, stopY-startY-1, y));
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
pixelCount = 0; pixelCount = 0;
for(int fy=0; fy<windowSize ;fy++){ for (int fy=0; fy<windowSize; fy++) {
for(int fx=0; fx<windowSize ;fx++){ for (int fx=0; fx<windowSize; fx++) {
if(y+fy-edgeY >= 0 && y+fy-edgeY < data.length && x+fx-edgeX >= 0 && x+fx-edgeX < data[0].length){ if (y+fy-edgeY >= 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] //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[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[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[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[3]) tmpArray[3][ getMedianIndex(tmpData[y + fy - edgeY][x + fx - edgeX][3])]++;
pixelCount++; pixelCount++;
} }
} }
} }
if(channels[0]) tmpData[y][x][0] = findMedian(tmpArray[0], 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[1]) tmpData[y][x][1] = findMedian(tmpArray[1], pixelCount/2);
if(channels[2]) tmpData[y][x][2] = findMedian(tmpArray[2], 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[3]) tmpData[y][x][3] = findMedian(tmpArray[3], pixelCount/2);
} }
} }
return tmpData; return tmpData;
} }
private int getMedianIndex(int i){ private int getMedianIndex(int i) {
if(i < 0) return Math.abs(i); if (i < 0) return Math.abs(i);
else return i+256; else return i+256;
} }
private int findMedian(int[] median, int medianCount){ private int findMedian(int[] median, int medianCount) {
int sum = 0; int sum = 0;
int ret = 0; int ret = 0;
for(int i=0; i<median.length ;i++){ for (int i=0; i<median.length; i++) {
sum += median[i]; sum += median[i];
median[i] = 0; median[i] = 0;
if(sum >= medianCount && ret == 0){ if (sum >= medianCount && ret == 0) {
ret = i-256; ret = i-256;
} }
} }
@ -147,7 +147,7 @@ public class MedianFilter extends ImageFilterProcessor{
private int rows; private int rows;
private int channel; 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.data = data;
this.cols = cols; this.cols = cols;
this.rows = rows; this.rows = rows;
@ -166,7 +166,7 @@ public class MedianFilter extends ImageFilterProcessor{
return data[ getY(i) ][ getX(i) ][ channel ]; 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; 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; return a % cols;
} }
private int getY(int a){ private int getY(int a) {
return a / cols; return a / cols;
} }

View file

@ -40,7 +40,7 @@ public class ResizeImage extends ImageFilterProcessor{
* @param img The image to resize * @param img The image to resize
* @param w The new width * @param w The new width
*/ */
public ResizeImage(BufferedImage img, int w){ public ResizeImage(BufferedImage img, int w) {
this(img, w, -1); 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 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 * @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); super(img);
width = w; width = w;
height = h; height = h;
@ -59,10 +59,10 @@ public class ResizeImage extends ImageFilterProcessor{
@Override @Override
public int[][][] process(final int[][][] data, int startX, int startY, int stopX, int stopY) { 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)); height = (int)(((double)width/(stopX-startX))*(stopY-startY));
} }
else if(height < 1){ else if (height < 1) {
width = (int)(((double)height/(stopY-startY))*(stopX-startY)); width = (int)(((double)height/(stopY-startY))*(stopX-startY));
} }
@ -70,9 +70,9 @@ public class ResizeImage extends ImageFilterProcessor{
double xScale = ((double)(stopX-startX)/width); double xScale = ((double)(stopX-startX)/width);
double yScale = ((double)(stopY-startY)/height); double yScale = ((double)(stopY-startY)/height);
for(int y=0; y<width ;y++){ for (int y=0; y<width; y++) {
setProgress(ZMath.percent(0, width-1, y)); setProgress(ZMath.percent(0, width-1, y));
for(int x=0; x<height ;x++){ for (int x=0; x<height; x++) {
newData[y][x][0] = data[(int)(y*yScale)][(int)(x*xScale)][0]; newData[y][x][0] = data[(int)(y*yScale)][(int)(x*xScale)][0];
newData[y][x][1] = data[(int)(y*yScale)][(int)(x*xScale)][1]; newData[y][x][1] = data[(int)(y*yScale)][(int)(x*xScale)][1];
newData[y][x][2] = data[(int)(y*yScale)][(int)(x*xScale)][2]; newData[y][x][2] = data[(int)(y*yScale)][(int)(x*xScale)][2];

View file

@ -63,23 +63,23 @@ public class SobelEdgeDetectionFilter extends ImageFilterProcessor{
setProgress(66); setProgress(66);
int[][][] output = new int[data.length][data[0].length][4]; int[][][] output = new int[data.length][data[0].length][4];
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
setProgress(66+ZMath.percent(0, (stopY-startY), y+1)/100*34); setProgress(66+ZMath.percent(0, (stopY-startY), y+1)/100*34);
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
output[y][x][0] = data[y][x][0]; output[y][x][0] = data[y][x][0];
output[y][x][1] = (int)Math.sqrt( xG[y][x][1]*xG[y][x][1] + yG[y][x][1]*yG[y][x][1] ); output[y][x][1] = (int)Math.sqrt(xG[y][x][1]*xG[y][x][1] + yG[y][x][1]*yG[y][x][1]);
output[y][x][2] = (int)Math.sqrt( xG[y][x][2]*xG[y][x][2] + yG[y][x][2]*yG[y][x][2] ); output[y][x][2] = (int)Math.sqrt(xG[y][x][2]*xG[y][x][2] + yG[y][x][2]*yG[y][x][2]);
output[y][x][3] = (int)Math.sqrt( xG[y][x][3]*xG[y][x][3] + yG[y][x][3]*yG[y][x][3] ); output[y][x][3] = (int)Math.sqrt(xG[y][x][3]*xG[y][x][3] + yG[y][x][3]*yG[y][x][3]);
/* /*
output[y][x][1] = Math.abs( xG[y][x][1] ) + Math.abs(yG[y][x][1] ); output[y][x][1] = Math.abs(xG[y][x][1]) + Math.abs(yG[y][x][1]);
output[y][x][2] = Math.abs( xG[y][x][2] ) + Math.abs(yG[y][x][2] ); output[y][x][2] = Math.abs(xG[y][x][2]) + Math.abs(yG[y][x][2]);
output[y][x][3] = Math.abs( xG[y][x][3] ) + Math.abs(yG[y][x][3] ); output[y][x][3] = Math.abs(xG[y][x][3]) + Math.abs(yG[y][x][3]);
*/ */
} }
} }
// gradient's direction: // gradient's direction:
// 0 = arctan( yG/xG ) // 0 = arctan(yG/xG)
return output; return output;
} }

View file

@ -39,7 +39,7 @@ public class SpotLightFilter extends ImageFilterProcessor{
* Sets up a default spotlight effect in * Sets up a default spotlight effect in
* the middle of the image * the middle of the image
*/ */
public SpotLightFilter(BufferedImage img){ public SpotLightFilter(BufferedImage img) {
this(img, 100, -1, -1); this(img, 100, -1, -1);
} }
@ -47,7 +47,7 @@ public class SpotLightFilter extends ImageFilterProcessor{
* Sets up a custom spotlight * Sets up a custom spotlight
* @param r The radius of the spotlight in pixels * @param r The radius of the spotlight in pixels
*/ */
public SpotLightFilter(BufferedImage img, int r){ public SpotLightFilter(BufferedImage img, int r) {
this(img, r, -1, -1); this(img, r, -1, -1);
} }
@ -57,7 +57,7 @@ public class SpotLightFilter extends ImageFilterProcessor{
* @param x The x position of the spotlight, if -1 then it will be centered * @param x The x position of the spotlight, if -1 then it will be centered
* @param y The y position of the spotlight, if -1 then it will be centered * @param y The y position of the spotlight, if -1 then it will be centered
*/ */
public SpotLightFilter(BufferedImage img, int r, int x, int y){ public SpotLightFilter(BufferedImage img, int r, int x, int y) {
super(img); super(img);
radius = r; radius = r;
xPos = x; xPos = x;
@ -66,24 +66,24 @@ public class SpotLightFilter extends ImageFilterProcessor{
@Override @Override
public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) {
if(xPos < 0) xPos = data[0].length/2; if (xPos < 0) xPos = data[0].length/2;
if(yPos < 0) yPos = data.length/2; if (yPos < 0) yPos = data.length/2;
int[][][] output = new int[data.length][data[0].length][4]; int[][][] output = new int[data.length][data[0].length][4];
double scale, dx, dy, distance; double scale, dx, dy, distance;
for(int y=startY; y<stopY ;y++){ for (int y=startY; y<stopY; y++) {
setProgress(ZMath.percent(0, (stopY-startY)-1, y)); setProgress(ZMath.percent(0, (stopY-startY)-1, y));
for(int x=startX; x<stopX ;x++){ for (int x=startX; x<stopX; x++) {
dx = x-xPos; dx = x-xPos;
dy = y-yPos; dy = y-yPos;
distance = Math.sqrt(dx*dx+dy*dy); distance = Math.sqrt(dx*dx+dy*dy);
if(distance > radius){ if (distance > radius) {
scale = 0; scale = 0;
} }
else{ else {
scale = 1-(distance/radius); scale = 1-(distance/radius);
} }

View file

@ -62,7 +62,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
* *
* @param in is the InputStream that the buffer will use * @param in is the InputStream that the buffer will use
*/ */
public BufferedBoundaryInputStream(InputStream in){ public BufferedBoundaryInputStream(InputStream in) {
this(in, DEFAULT_BUF_SIZE); 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 in is the InputStream that the buffer will use
* @param buf_size speifies the buffer size * @param buf_size speifies the buffer size
*/ */
public BufferedBoundaryInputStream(InputStream in, int buf_size){ public BufferedBoundaryInputStream(InputStream in, int buf_size) {
super(in); super(in);
buffer = new byte[buf_size]; buffer = new byte[buf_size];
} }
@ -85,7 +85,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
if (fillBuffer() < 0) if (fillBuffer() < 0)
return -1; return -1;
if(isOnBoundary()) if (isOnBoundary())
return -1; // boundary return -1; // boundary
return buffer[buf_pos++]; return buffer[buf_pos++];
} }
@ -132,7 +132,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
/** /**
* @return if the current position in the buffer is a boundary * @return if the current position in the buffer is a boundary
*/ */
public boolean isOnBoundary(){ public boolean isOnBoundary() {
return buf_bound_pos == buf_pos; return buf_bound_pos == buf_pos;
} }
@ -163,7 +163,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
buf_pos = buf_end; 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; buf_pos += boundary.length;
findNextBoundary(); findNextBoundary();
} }
@ -181,7 +181,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
*/ */
public long skip(long n) throws IOException { public long skip(long n) throws IOException {
int leftover = available(); int leftover = available();
if(n > leftover){ if (n > leftover) {
buf_pos = buf_end; buf_pos = buf_end;
return leftover; return leftover;
} }
@ -192,7 +192,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
/** /**
* Sets the boundary for the stream * Sets the boundary for the stream
*/ */
public void setBoundary(String b){ public void setBoundary(String b) {
this.boundary = b.getBytes(); this.boundary = b.getBytes();
findNextBoundary(); // redo the search with the new boundary findNextBoundary(); // redo the search with the new boundary
} }
@ -200,7 +200,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
/** /**
* Sets the boundary for the stream * Sets the boundary for the stream
*/ */
public void setBoundary(byte[] b){ public void setBoundary(byte[] b) {
boundary = new byte[b.length]; boundary = new byte[b.length];
System.arraycopy(b, 0, boundary, 0, b.length); System.arraycopy(b, 0, boundary, 0, b.length);
findNextBoundary(); // redo the search with the new boundary findNextBoundary(); // redo the search with the new boundary
@ -223,7 +223,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
/** /**
* @return true for BufferedBoundaryInputStream * @return true for BufferedBoundaryInputStream
*/ */
public boolean markSupported(){ public boolean markSupported() {
return true; return true;
} }
@ -267,7 +267,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
*/ */
private int fillBuffer() throws IOException { private int fillBuffer() throws IOException {
// Do we need to fill the buffer // Do we need to fill the buffer
if(buf_pos < buf_end-boundary.length) if (buf_pos < buf_end-boundary.length)
return 0; return 0;
int leftover = buf_end - buf_pos; int leftover = buf_end - buf_pos;
@ -288,7 +288,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
if (leftover > 0 && buf_pos != 0) if (leftover > 0 && buf_pos != 0)
System.arraycopy(buffer, buf_pos, buffer, 0, leftover); System.arraycopy(buffer, buf_pos, buffer, 0, leftover);
// Set new positions // Set new positions
if (buf_mark >= 0){ if (buf_mark >= 0) {
buf_pos = tmp_pos - buf_mark; buf_pos = tmp_pos - buf_mark;
buf_mark = 0; buf_mark = 0;
} else } else
@ -311,7 +311,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
/** /**
* Searches for the nearest boundary from the current buffer position * 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 // 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 i = buf_pos; i <= buf_end-boundary.length; i++) {
for (int b = 0; b < boundary.length; b++) { for (int b = 0; b < boundary.length; b++) {

View file

@ -101,8 +101,8 @@ public class BufferedRandomAccessFile extends RandomAccessFile{
* @return the buffer * @return the buffer
*/ */
private int fillBuffer() throws IOException { private int fillBuffer() throws IOException {
int n = super.read(buffer, 0, BUF_SIZE ); int n = super.read(buffer, 0, BUF_SIZE);
if(n >= 0) { if (n >= 0) {
file_pos +=n; file_pos +=n;
buf_end = n; buf_end = n;
buf_pos = 0; buf_pos = 0;
@ -123,11 +123,11 @@ public class BufferedRandomAccessFile extends RandomAccessFile{
* @return the next byte in the buffer * @return the next byte in the buffer
*/ */
public final int read() throws IOException{ public final int read() throws IOException{
if(buf_pos >= buf_end) { if (buf_pos >= buf_end) {
if(fillBuffer() < 0) if (fillBuffer() < 0)
return -1; return -1;
} }
if(buf_end == 0) { if (buf_end == 0) {
return -1; return -1;
} else { } else {
buf_pos++; buf_pos++;
@ -154,28 +154,28 @@ public class BufferedRandomAccessFile extends RandomAccessFile{
* @return the amount of bytes read or -1 if eof * @return the amount of bytes read or -1 if eof
*/ */
public int read(byte b[], int off, int len) throws IOException { public int read(byte b[], int off, int len) throws IOException {
if(buf_pos >= buf_end) { if (buf_pos >= buf_end) {
if(fillBuffer() < 0) if (fillBuffer() < 0)
return -1; // EOF return -1; // EOF
} }
// Copy from buffer // Copy from buffer
int leftover = buf_end - buf_pos; int leftover = buf_end - buf_pos;
if(len <= leftover) { if (len <= leftover) {
System.arraycopy(buffer, buf_pos, b, off, len); System.arraycopy(buffer, buf_pos, b, off, len);
buf_pos += len; buf_pos += len;
return len; return len;
} }
System.arraycopy(buffer, buf_pos, b, off, leftover); 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(); fillBuffer();
if( n >= 0 ) if (n >= 0)
return leftover + n; return leftover + n;
return leftover; return leftover;
/*for(int i = 0; i < len; i++) { /*for (int i = 0; i < len; i++) {
int c = this.read(); int c = this.read();
if(c != -1) if (c != -1)
b[off+i] = (byte)c; b[off+i] = (byte)c;
else { else {
return i; return i;
@ -189,7 +189,7 @@ public class BufferedRandomAccessFile extends RandomAccessFile{
*/ */
public long getFilePointer() { public long getFilePointer() {
long l = file_pos; 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 { public void seek(long pos) throws IOException {
int n = (int)(file_pos - pos); int n = (int)(file_pos - pos);
if(n >= 0 && n <= buf_end) { if (n >= 0 && n <= buf_end) {
buf_pos = buf_end - n; buf_pos = buf_end - n;
} else { } else {
super.seek(pos); super.seek(pos);
@ -214,19 +214,19 @@ public class BufferedRandomAccessFile extends RandomAccessFile{
*/ */
public final String readNextLine() throws IOException { public final String readNextLine() throws IOException {
String str; String str;
if(buf_end-buf_pos <= 0) { if (buf_end-buf_pos <= 0) {
if(fillBuffer() < 0) { if (fillBuffer() < 0) {
throw new IOException("Error filling buffer!"); throw new IOException("Error filling buffer!");
} }
} }
int lineEnd = -1; int lineEnd = -1;
for(int i = buf_pos; i < buf_end; i++) { for (int i = buf_pos; i < buf_end; i++) {
if(buffer[i] == '\n') { if (buffer[i] == '\n') {
lineEnd = i; lineEnd = i;
break; break;
} }
} }
if(lineEnd < 0) { if (lineEnd < 0) {
StringBuilder input = new StringBuilder(256); StringBuilder input = new StringBuilder(256);
int c; int c;
while (((c = read()) != -1) && (c != '\n')) { while (((c = read()) != -1) && (c != '\n')) {
@ -238,7 +238,7 @@ public class BufferedRandomAccessFile extends RandomAccessFile{
return input.toString(); 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); str = new String(buffer, buf_pos, lineEnd - buf_pos -1);
} }
else { else {

View file

@ -44,7 +44,7 @@ public class DynamicByteArrayStream extends InputStream{
/** /**
* Create a new instance of DynamicByteArrayStream * Create a new instance of DynamicByteArrayStream
*/ */
public DynamicByteArrayStream(){ public DynamicByteArrayStream() {
bytes = new ArrayList<>(); bytes = new ArrayList<>();
globalPos = 0; globalPos = 0;
globalSize = 0; globalSize = 0;
@ -57,7 +57,7 @@ public class DynamicByteArrayStream extends InputStream{
* *
* @param b is the byte array to add. * @param b is the byte array to add.
*/ */
public synchronized void append(byte[] b){ public synchronized void append(byte[] b) {
bytes.add(b); bytes.add(b);
globalSize += b.length; globalSize += b.length;
} }
@ -70,7 +70,7 @@ public class DynamicByteArrayStream extends InputStream{
* @param offset is the offset in the byte array * @param offset is the offset in the byte array
* @param length is the amount of data to add * @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]; byte[] new_b = new byte[length];
System.arraycopy(b, offset, new_b, 0, length); System.arraycopy(b, offset, new_b, 0, length);
bytes.add(new_b); bytes.add(new_b);
@ -79,12 +79,12 @@ public class DynamicByteArrayStream extends InputStream{
@Override @Override
public synchronized int read() { public synchronized int read() {
if(globalPos >= globalSize) return -1; if (globalPos >= globalSize) return -1;
int ret = bytes.get(globalArrayIndex)[localArrayOffset] & 0xff; int ret = bytes.get(globalArrayIndex)[localArrayOffset] & 0xff;
globalPos++; globalPos++;
localArrayOffset++; localArrayOffset++;
if(localArrayOffset >= bytes.get(globalArrayIndex).length){ if (localArrayOffset >= bytes.get(globalArrayIndex).length) {
globalArrayIndex++; globalArrayIndex++;
localArrayOffset = 0; localArrayOffset = 0;
} }
@ -92,15 +92,15 @@ public class DynamicByteArrayStream extends InputStream{
} }
public synchronized int read(byte b[], int off, int len) { public synchronized int read(byte b[], int off, int len) {
if(len <= 0) return 0; if (len <= 0) return 0;
if(globalPos >= globalSize) return -1; if (globalPos >= globalSize) return -1;
int bytes_read=0; int bytes_read=0;
if(globalPos+len >= globalSize) len = globalSize - globalPos; if (globalPos+len >= globalSize) len = globalSize - globalPos;
while(bytes_read<len){ while (bytes_read<len) {
byte[] src = bytes.get(globalArrayIndex); byte[] src = bytes.get(globalArrayIndex);
// Read length is LONGER than local array // Read length is LONGER than local array
if(localArrayOffset +len-bytes_read > src.length){ if (localArrayOffset +len-bytes_read > src.length) {
int length = src.length- localArrayOffset; int length = src.length- localArrayOffset;
System.arraycopy(src, localArrayOffset, b, off+bytes_read, length); System.arraycopy(src, localArrayOffset, b, off+bytes_read, length);
@ -109,7 +109,7 @@ public class DynamicByteArrayStream extends InputStream{
bytes_read += length; bytes_read += length;
} }
// Read length is SHORTER than local array // Read length is SHORTER than local array
else{ else {
int length = len-bytes_read; int length = len-bytes_read;
System.arraycopy(src, localArrayOffset, b, off+bytes_read, length); 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 * Clears this stream from the byte arrays
*/ */
public synchronized void clear(){ public synchronized void clear() {
globalSize = 0; globalSize = 0;
reset(); reset();
bytes.clear(); bytes.clear();
@ -147,7 +147,7 @@ public class DynamicByteArrayStream extends InputStream{
/** /**
* @return all of the buffers content as a byte array. * @return all of the buffers content as a byte array.
*/ */
public byte[] getBytes(){ public byte[] getBytes() {
byte[] data = new byte[globalSize]; byte[] data = new byte[globalSize];
this.read(data, 0, globalSize); this.read(data, 0, globalSize);
return data; return data;
@ -159,7 +159,7 @@ public class DynamicByteArrayStream extends InputStream{
* *
* @return all the contents of the buffers as a String. * @return all the contents of the buffers as a String.
*/ */
public String toString(){ public String toString() {
return new String( this.getBytes() ); return new String(this.getBytes());
} }
} }

View file

@ -55,7 +55,7 @@ public class IOUtil {
DynamicByteArrayStream dyn_buff = new DynamicByteArrayStream(); DynamicByteArrayStream dyn_buff = new DynamicByteArrayStream();
byte[] buff = new byte[8192]; byte[] buff = new byte[8192];
int len; int len;
while((len = stream.read(buff)) >= 0){ while ((len = stream.read(buff)) >= 0) {
dyn_buff.append(buff, 0, len); dyn_buff.append(buff, 0, len);
} }
@ -108,7 +108,7 @@ public class IOUtil {
int readLength = 0; int readLength = 0;
int c; int c;
while((length < 0 || readLength < length) && (c = stream.read()) >= 0){ while ((length < 0 || readLength < length) && (c = stream.read()) >= 0) {
str.append((char) c); str.append((char) c);
readLength++; readLength++;
} }
@ -162,7 +162,7 @@ public class IOUtil {
int readLength = 0; int readLength = 0;
int c; int c;
while((length < 0 || readLength < length) && (c = reader.read()) >= 0){ while ((length < 0 || readLength < length) && (c = reader.read()) >= 0) {
str.append((char) c); str.append((char) c);
readLength++; readLength++;
} }
@ -222,7 +222,7 @@ public class IOUtil {
public static void copyStream(InputStream in, OutputStream out) throws IOException { public static void copyStream(InputStream in, OutputStream out) throws IOException {
byte[] buff = new byte[8192]; // This is the default BufferedInputStream buffer size byte[] buff = new byte[8192]; // This is the default BufferedInputStream buffer size
int len; int len;
while((len = in.read(buff)) > 0){ while ((len = in.read(buff)) > 0) {
out.write(buff, 0, len); out.write(buff, 0, len);
} }
} }
@ -237,7 +237,7 @@ public class IOUtil {
public static void copyStream(Reader in, Writer out) throws IOException { public static void copyStream(Reader in, Writer out) throws IOException {
char[] buff = new char[8192]; // This is the default BufferedReader buffer size char[] buff = new char[8192]; // This is the default BufferedReader buffer size
int len; int len;
while((len = in.read(buff)) > 0){ while ((len = in.read(buff)) > 0) {
out.write(buff, 0, len); out.write(buff, 0, len);
} }
} }

View file

@ -39,7 +39,7 @@ public class InputStreamCloser extends InputStream{
private Closeable[] c; private Closeable[] c;
private InputStream in; private InputStream in;
public InputStreamCloser(InputStream in, Closeable... c){ public InputStreamCloser(InputStream in, Closeable... c) {
this.c = c; this.c = c;
this.in = in; this.in = in;
} }

View file

@ -43,7 +43,7 @@ public class MultiPrintStream extends PrintStream {
//a instance of this class //a instance of this class
public static MultiPrintStream out = new MultiPrintStream(); public static MultiPrintStream out = new MultiPrintStream();
public MultiPrintStream(){ public MultiPrintStream() {
super(new PrintStream(System.out)); super(new PrintStream(System.out));
streams = new ArrayList<>(); streams = new ArrayList<>();
streams.add(new PrintStream(System.out)); 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 * This constructor makes a simple PrintStream that prints to the console and to a file
* @param file is the file name to output to * @param file is the file name to output to
*/ */
public MultiPrintStream(String file){ public MultiPrintStream(String file) {
super(new PrintStream(System.out)); super(new PrintStream(System.out));
try { try {
streams = new ArrayList<>(); streams = new ArrayList<>();
@ -69,7 +69,7 @@ public class MultiPrintStream extends PrintStream {
* This constructor takes a array of PrintStreams to be used * This constructor takes a array of PrintStreams to be used
* @param streams is a array of the streams that will be used * @param streams is a array of the streams that will be used
*/ */
public MultiPrintStream(PrintStream[] streams){ public MultiPrintStream(PrintStream[] streams) {
super(streams[0]); super(streams[0]);
this.streams = new ArrayList<>(); this.streams = new ArrayList<>();
Collections.addAll(this.streams, streams); Collections.addAll(this.streams, streams);
@ -79,7 +79,7 @@ public class MultiPrintStream extends PrintStream {
* This constructor takes a array of PrintStreams to be used * This constructor takes a array of PrintStreams to be used
* @param instanceStream is a array of the streams that will be used * @param instanceStream is a array of the streams that will be used
*/ */
public static void makeInstance(MultiPrintStream instanceStream){ public static void makeInstance(MultiPrintStream instanceStream) {
out = instanceStream; out = instanceStream;
} }
@ -87,7 +87,7 @@ public class MultiPrintStream extends PrintStream {
* Adds a PrintStream to the list of streams * Adds a PrintStream to the list of streams
* @param p is the PrintStream to add * @param p is the PrintStream to add
*/ */
public void addPrintStream(PrintStream p){ public void addPrintStream(PrintStream p) {
streams.add(p); streams.add(p);
} }
@ -95,7 +95,7 @@ public class MultiPrintStream extends PrintStream {
* Remove a PrintStream from the list * Remove a PrintStream from the list
* @param p is the PrintStream to remove * @param p is the PrintStream to remove
*/ */
public void removePrintStream(PrintStream p){ public void removePrintStream(PrintStream p) {
streams.remove(p); streams.remove(p);
} }
@ -103,7 +103,7 @@ public class MultiPrintStream extends PrintStream {
* Remove a PrintStream from the list * Remove a PrintStream from the list
* @param p is the index of the PrintStream to remove * @param p is the index of the PrintStream to remove
*/ */
public void removePrintStream(int p){ public void removePrintStream(int p) {
streams.remove(p); streams.remove(p);
} }
@ -111,58 +111,58 @@ public class MultiPrintStream extends PrintStream {
* writes to all the PrintStreams * writes to all the PrintStreams
*/ */
public void write(int b) { public void write(int b) {
for(int i=0; i<streams.size() ;i++) for (int i=0; i<streams.size(); i++)
streams.get(i).write(b); streams.get(i).write(b);
} }
/** /**
* writes to all the PrintStreams * writes to all the PrintStreams
*/ */
public void write(byte buf[], int off, int len){ public void write(byte buf[], int off, int len) {
for(int i=0; i<streams.size() ;i++) for (int i=0; i<streams.size(); i++)
streams.get(i).write(buf, off, len); streams.get(i).write(buf, off, len);
} }
/** /**
* Prints with a new line to all the PrintStreams * Prints with a new line to all the PrintStreams
*/ */
public void println(String s){ public void println(String s) {
for(int i=0; i<streams.size() ;i++) for (int i=0; i<streams.size(); i++)
streams.get(i).println(s); streams.get(i).println(s);
} }
/** /**
* Prints to all the PrintStreams * Prints to all the PrintStreams
*/ */
public void print(String s){ public void print(String s) {
for(int i=0; i<streams.size() ;i++) for (int i=0; i<streams.size(); i++)
streams.get(i).print(s); streams.get(i).print(s);
} }
public void println(){ println("");} public void println() { println("");}
public void println(boolean x){ println(String.valueOf(x));} public void println(boolean x) {println(String.valueOf(x));}
public void println(char x){ println(String.valueOf(x));} public void println(char x) { println(String.valueOf(x));}
public void println(char[] x){ println(new String(x));} public void println(char[] x) { println(new String(x));}
public void println(double x){ println(String.valueOf(x));} public void println(double x) { println(String.valueOf(x));}
public void println(float x){ println(String.valueOf(x));} public void println(float x) { println(String.valueOf(x));}
public void println(int x){ println(String.valueOf(x));} public void println(int x) { println(String.valueOf(x));}
public void println(long x){ println(String.valueOf(x));} public void println(long x) { println(String.valueOf(x));}
public void println(Object x){ println(String.valueOf(x));} public void println(Object x) { println(String.valueOf(x));}
public void print(boolean x){ print(String.valueOf(x));} public void print(boolean x) { print(String.valueOf(x));}
public void print(char x){ print(String.valueOf(x));} public void print(char x) { print(String.valueOf(x));}
public void print(char[] x){ print(new String(x));} public void print(char[] x) { print(new String(x));}
public void print(double x){ print(String.valueOf(x));} public void print(double x) { print(String.valueOf(x));}
public void print(float x){ print(String.valueOf(x));} public void print(float x) { print(String.valueOf(x));}
public void print(int x){ print(String.valueOf(x));} public void print(int x) { print(String.valueOf(x));}
public void print(long x){ print(String.valueOf(x));} public void print(long x) { print(String.valueOf(x));}
public void print(Object x){ print(String.valueOf(x));} public void print(Object x) { print(String.valueOf(x));}
public boolean checkError(){ public boolean checkError() {
for(int i=0; i<streams.size() ;i++) for (int i=0; i<streams.size(); i++)
if(streams.get(i).checkError()) if (streams.get(i).checkError())
return true; return true;
return false; return false;
} }
@ -171,8 +171,8 @@ public class MultiPrintStream extends PrintStream {
/** /**
* closes all the PrintStreams * closes all the PrintStreams
*/ */
public void close(){ public void close() {
for(int i=0; i<streams.size() ;i++) for (int i=0; i<streams.size(); i++)
streams.get(i).close(); streams.get(i).close();
} }
@ -181,8 +181,8 @@ public class MultiPrintStream extends PrintStream {
* *
* @param o is the Object to dump * @param o is the Object to dump
*/ */
public void dump(Object o){ public void dump(Object o) {
println(dumpToString( o, 1)); println(dumpToString(o, 1));
} }
/** /**
@ -191,8 +191,8 @@ public class MultiPrintStream extends PrintStream {
* @param o is the Object to dump * @param o is the Object to dump
* @param depth sets the object dump depth, the object recursion depth * @param depth sets the object dump depth, the object recursion depth
*/ */
public void dump(Object o, int depth){ public void dump(Object o, int depth) {
println(dumpToString( o, depth)); println(dumpToString(o, depth));
} }
/** /**
@ -231,131 +231,131 @@ public class MultiPrintStream extends PrintStream {
*/ */
private static String dumpToString(Object o , String head, int depth) { private static String dumpToString(Object o , String head, int depth) {
if(o == null) if (o == null)
return "NULL"; return "NULL";
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
Class<?> oClass = o.getClass(); Class<?> oClass = o.getClass();
buffer.append( oClass.getName() ); buffer.append(oClass.getName());
String nextHead = head + "\t"; String nextHead = head + "\t";
// Prints out Arrays // Prints out Arrays
if ( oClass.isArray() ) { if (oClass.isArray()) {
buffer.append( "[" ); buffer.append("[");
for ( int i=0; i<Array.getLength(o) ;i++ ) { for (int i=0; i<Array.getLength(o); i++) {
Object value = Array.get(o,i); Object value = Array.get(o,i);
buffer.append("\n"); buffer.append("\n");
buffer.append(nextHead); buffer.append(nextHead);
buffer.append( (dumbCapable(value, depth-1) ? buffer.append((dumbCapable(value, depth-1) ?
dumpToString(value, nextHead, depth-1) : value) ); dumpToString(value, nextHead, depth-1) : value));
if ( i+1<Array.getLength(o) ) if (i+1 < Array.getLength(o))
buffer.append( "," ); buffer.append(",");
} }
buffer.append( "\n" ); buffer.append("\n");
buffer.append(head); buffer.append(head);
buffer.append( "]" ); buffer.append("]");
} }
// Prints out a list // Prints out a list
else if(o instanceof Collection){ else if (o instanceof Collection) {
Iterator<?> it = ((Collection<?>)o).iterator(); Iterator<?> it = ((Collection<?>)o).iterator();
buffer.append( "[" ); buffer.append("[");
while(it.hasNext()){ while (it.hasNext()) {
Object value = it.next(); Object value = it.next();
buffer.append("\n"); buffer.append("\n");
buffer.append(nextHead); buffer.append(nextHead);
buffer.append( (dumbCapable(value, depth-1) ? buffer.append((dumbCapable(value, depth-1) ?
dumpToString(value, nextHead, depth-1) : value) ); dumpToString(value, nextHead, depth-1) : value));
if(it.hasNext()) if (it.hasNext())
buffer.append( "," ); buffer.append(",");
} }
buffer.append( "\n" ); buffer.append("\n");
buffer.append(head); buffer.append(head);
buffer.append( "]" ); buffer.append("]");
} }
// Prints out a Map // Prints out a Map
else if(o instanceof Map){ else if (o instanceof Map) {
Iterator<?> it = ((Map<?,?>)o).keySet().iterator(); Iterator<?> it = ((Map<?,?>)o).keySet().iterator();
buffer.append( "{" ); buffer.append("{");
while(it.hasNext()){ while (it.hasNext()) {
Object key = it.next(); Object key = it.next();
Object value = ((Map<?,?>)o).get(key); Object value = ((Map<?,?>)o).get(key);
buffer.append("\n"); buffer.append("\n");
buffer.append(nextHead); buffer.append(nextHead);
buffer.append( key ); buffer.append(key);
buffer.append( "=>" ); buffer.append("=>");
buffer.append( (dumbCapable(value, depth-1) ? buffer.append((dumbCapable(value, depth-1) ?
dumpToString(value, nextHead, depth-1) : value) ); dumpToString(value, nextHead, depth-1) : value));
if(it.hasNext()) if (it.hasNext())
buffer.append( "," ); buffer.append(",");
} }
buffer.append( "\n" ); buffer.append("\n");
buffer.append(head); buffer.append(head);
buffer.append( "}" ); buffer.append("}");
} }
// Prints out data from InputStream // Prints out data from InputStream
else if(o instanceof InputStream){ else if (o instanceof InputStream) {
buffer.append( " =>{\n" ); buffer.append(" =>{\n");
try { try {
InputStream in = (InputStream)o; InputStream in = (InputStream)o;
int tmp; int tmp;
while((tmp = in.read()) != -1){ while ((tmp = in.read()) != -1) {
buffer.append(nextHead); buffer.append(nextHead);
buffer.append( (char)tmp ); buffer.append((char)tmp);
} }
in.close(); in.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
buffer.append( "\n" ); buffer.append("\n");
buffer.append(head); buffer.append(head);
buffer.append( "}" ); buffer.append("}");
} }
// Prints out data from InputStream // Prints out data from InputStream
else if(o instanceof Reader){ else if (o instanceof Reader) {
buffer.append( " =>{\n" ); buffer.append(" =>{\n");
try { try {
Reader in = (Reader)o; Reader in = (Reader)o;
int tmp; int tmp;
while((tmp = in.read()) != -1){ while ((tmp = in.read()) != -1) {
buffer.append(nextHead); buffer.append(nextHead);
buffer.append( (char)tmp ); buffer.append((char)tmp);
} }
in.close(); in.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
buffer.append( "\n" ); buffer.append("\n");
buffer.append(head); buffer.append(head);
buffer.append( "}" ); buffer.append("}");
} }
// Prints out Object properties // Prints out Object properties
else{ else {
buffer.append( "{" ); buffer.append("{");
while ( oClass != null ) { while (oClass != null) {
Field[] fields = oClass.getDeclaredFields(); Field[] fields = oClass.getDeclaredFields();
for ( int i=0; i<fields.length; i++ ) { for (int i=0; i<fields.length; i++) {
if (Modifier.isFinal(fields[i].getModifiers())) // Skip constants if (Modifier.isFinal(fields[i].getModifiers())) // Skip constants
continue; continue;
fields[i].setAccessible( true ); fields[i].setAccessible(true);
buffer.append("\n"); buffer.append("\n");
buffer.append(nextHead); buffer.append(nextHead);
//buffer.append( fields[i].getType().getSimpleName() ); //buffer.append(fields[i].getType().getSimpleName());
//buffer.append( " " ); //buffer.append(" ");
buffer.append( fields[i].getName() ); buffer.append(fields[i].getName());
buffer.append( " = " ); buffer.append(" = ");
try { try {
Object value = fields[i].get(o); Object value = fields[i].get(o);
if (value != null) { if (value != null) {
buffer.append( (dumbCapable(value, depth-1) ? buffer.append((dumbCapable(value, depth-1) ?
dumpToString(value, nextHead, depth-1) : value) ); dumpToString(value, nextHead, depth-1) : value));
} }
} catch ( IllegalAccessException e ) {} } catch (IllegalAccessException e) {}
if ( i+1<fields.length ) if (i + 1 < fields.length)
buffer.append( "," ); buffer.append(",");
} }
oClass = oClass.getSuperclass(); oClass = oClass.getSuperclass();
} }
buffer.append( "\n" ); buffer.append("\n");
buffer.append(head); buffer.append(head);
buffer.append( "}" ); buffer.append("}");
} }
return buffer.toString(); return buffer.toString();
@ -364,7 +364,7 @@ public class MultiPrintStream extends PrintStream {
/** /**
* An helper function for the dump function. * An helper function for the dump function.
*/ */
private static boolean dumbCapable(Object o, int depth){ private static boolean dumbCapable(Object o, int depth) {
if (depth <= 0) if (depth <= 0)
return false; return false;
if (o == null) if (o == null)

View file

@ -40,7 +40,7 @@ public class StringInputStream extends InputStream{
/** /**
* Creates an new instance of this class * Creates an new instance of this class
*/ */
public StringInputStream(){ public StringInputStream() {
clear(); clear();
} }
@ -55,7 +55,7 @@ public class StringInputStream extends InputStream{
* input stream without blocking by the next * input stream without blocking by the next
* invocation of a method for this input stream. * invocation of a method for this input stream.
*/ */
public int available(){ public int available() {
return buffer.length(); return buffer.length();
} }
@ -63,12 +63,12 @@ public class StringInputStream extends InputStream{
/** /**
* Reads the next byte of data from the input stream. * Reads the next byte of data from the input stream.
*/ */
public int read(){ public int read() {
if(buffer.length() == 0) if (buffer.length() == 0)
return -1; return -1;
int ret = buffer.charAt( 0 ); int ret = buffer.charAt(0);
buffer.deleteCharAt( 0 ); buffer.deleteCharAt(0);
return ret; return ret;
} }
@ -76,19 +76,19 @@ public class StringInputStream extends InputStream{
* Reads some number of bytes from the input stream * Reads some number of bytes from the input stream
* and stores them into the buffer array b. * and stores them into the buffer array b.
*/ */
public int read(byte[] b){ public int read(byte[] b) {
return read( b, 0, b.length ); return read(b, 0, b.length);
} }
/** /**
* Reads up to len bytes of data from the input stream * Reads up to len bytes of data from the input stream
* into an array of bytes. * into an array of bytes.
*/ */
public int read(byte[] b, int off, int len){ public int read(byte[] b, int off, int len) {
if(buffer.length() == 0) if (buffer.length() == 0)
return -1; return -1;
if( buffer.length() < len ){ if (buffer.length() < len) {
len = buffer.length(); len = buffer.length();
} }
byte[] btmp = buffer.substring(0, len).getBytes(StandardCharsets.ISO_8859_1); byte[] btmp = buffer.substring(0, len).getBytes(StandardCharsets.ISO_8859_1);
@ -104,13 +104,13 @@ public class StringInputStream extends InputStream{
* *
* @param n is the amount characters to skip * @param n is the amount characters to skip
*/ */
public long skip(long n){ public long skip(long n) {
if( buffer.length() < n ){ if (buffer.length() < n) {
int len = buffer.length(); int len = buffer.length();
buffer.delete(0, len); buffer.delete(0, len);
return len; return len;
} }
else{ else {
buffer.delete(0, (int) n); buffer.delete(0, (int) n);
return n; return n;
} }
@ -120,7 +120,7 @@ public class StringInputStream extends InputStream{
* Tests if this input stream supports the mark and * Tests if this input stream supports the mark and
* reset methods. * reset methods.
*/ */
public boolean markSupported(){ public boolean markSupported() {
return false; return false;
} }
@ -129,15 +129,15 @@ public class StringInputStream extends InputStream{
* Closes this input stream and releases any system * Closes this input stream and releases any system
* resources associated with the stream. * resources associated with the stream.
*/ */
public void close(){ public void close() {
clear(); clear();
} }
public void clear(){ public void clear() {
buffer = new StringBuilder(); buffer = new StringBuilder();
} }
public void add( String data ){ public void add(String data) {
buffer.append( data ); buffer.append(data);
} }
} }

View file

@ -39,23 +39,23 @@ public class StringOutputStream extends OutputStream{
/** /**
* Creates an new instance of this class * Creates an new instance of this class
*/ */
public StringOutputStream(){ public StringOutputStream() {
clear(); clear();
} }
@Override @Override
public void write(int b) { public void write(int b) {
buffer.append( b ); buffer.append(b);
} }
@Override @Override
public void write(byte[] b) { public void write(byte[] b) {
buffer.append( new String(b) ); buffer.append(new String(b));
} }
@Override @Override
public void write(byte[] b, int off, int len) { public void write(byte[] b, int off, int len) {
buffer.append( new String(b, off, len) ); buffer.append(new String(b, off, len));
} }
/** /**
@ -67,7 +67,7 @@ public class StringOutputStream extends OutputStream{
/** /**
* Clears the String buffer * Clears the String buffer
*/ */
public void clear(){ public void clear() {
buffer = new StringBuilder(); buffer = new StringBuilder();
} }

View file

@ -58,7 +58,7 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
private boolean searchCompressedFiles = false; private boolean searchCompressedFiles = false;
public FileSearcher(File root){ public FileSearcher(File root) {
this.root = root; this.root = root;
} }
@ -66,7 +66,7 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
/** /**
* @param file Sets the exact file name to search for (includes extension) * @param file Sets the exact file name to search for (includes extension)
*/ */
public void setFileName(String file){ public void setFileName(String file) {
fileName = file; fileName = file;
} }
@ -75,14 +75,14 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
* *
* @param ext is a String containing the file extension * @param ext is a String containing the file extension
*/ */
public void setExtension(String ext){ public void setExtension(String ext) {
extension = ext; extension = ext;
} }
/** /**
* Defines if the search should go into sub-folders * Defines if the search should go into sub-folders
*/ */
public void setRecursive(boolean recursive){ public void setRecursive(boolean recursive) {
this.recursive = recursive; this.recursive = recursive;
} }
@ -90,26 +90,26 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
* Sets how deep into folders the search should go * Sets how deep into folders the search should go
* (Recursion needs to be enabled for this attribute to be used) * (Recursion needs to be enabled for this attribute to be used)
*/ */
//public void setDepth(int depth){ //public void setDepth(int depth) {
// this.depth = depth; // this.depth = depth;
//} //}
/** /**
* Sets if the searcher should match to files. * Sets if the searcher should match to files.
*/ */
public void searchFiles(boolean searchFiles){ public void searchFiles(boolean searchFiles) {
this.searchFiles = searchFiles; this.searchFiles = searchFiles;
} }
/** /**
* Sets if the searcher should match to folders. * Sets if the searcher should match to folders.
*/ */
public void searchFolders(boolean searchFolders){ public void searchFolders(boolean searchFolders) {
this.searchFolders = searchFolders; this.searchFolders = searchFolders;
} }
/** /**
* Sets if the searcher should go into compressed files. * Sets if the searcher should go into compressed files.
*/ */
public void searchCompressedFiles(boolean searchCompressedFiles){ public void searchCompressedFiles(boolean searchCompressedFiles) {
this.searchCompressedFiles = searchCompressedFiles; this.searchCompressedFiles = searchCompressedFiles;
} }
@ -125,7 +125,7 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
private int index; private int index;
private FileSearchItem nextItem; private FileSearchItem nextItem;
public FileSearchIterator(){ public FileSearchIterator() {
fileList = new ArrayList<>(); fileList = new ArrayList<>();
index = 0; index = 0;
@ -149,19 +149,19 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
FileSearchItem ret = nextItem; FileSearchItem ret = nextItem;
// Find the next file // Find the next file
for(; index <fileList.size(); index++){ for (; index <fileList.size(); index++) {
FileSearchItem file = fileList.get(index); FileSearchItem file = fileList.get(index);
// ---------------------------------------------- // ----------------------------------------------
// Folders // Folders
// ---------------------------------------------- // ----------------------------------------------
if(recursive && file.isDirectory()){ if (recursive && file.isDirectory()) {
addFiles(file, file.listFiles()); addFiles(file, file.listFiles());
if(searchFolders) { if (searchFolders) {
if(fileName == null) // Match all folders if (fileName == null) // Match all folders
break; break;
else if(file.getName().equalsIgnoreCase(fileName)) else if (file.getName().equalsIgnoreCase(fileName))
break; break;
} }
} }
@ -170,9 +170,9 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
// Compressed Files // Compressed Files
// ---------------------------------------------- // ----------------------------------------------
else if(searchCompressedFiles && file.isFile() && else if (searchCompressedFiles && file.isFile() &&
compressedFileExtensions.contains( compressedFileExtensions.contains(
FileUtil.getFileExtension(file.getName()).toLowerCase())){ FileUtil.getFileExtension(file.getName()).toLowerCase())) {
try { try {
/* TODO: Implement recursive file search /* TODO: Implement recursive file search
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file.getPath())); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file.getPath()));
@ -189,7 +189,7 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
ZipFile zipFile = new ZipFile(file.getPath()); ZipFile zipFile = new ZipFile(file.getPath());
Enumeration<? extends ZipEntry> e = zipFile.entries(); Enumeration<? extends ZipEntry> e = zipFile.entries();
while(e.hasMoreElements()){ while (e.hasMoreElements()) {
ZipEntry entry = e.nextElement(); ZipEntry entry = e.nextElement();
fileList.add(new FileSearchZipItem(file.getPath(), entry)); fileList.add(new FileSearchZipItem(file.getPath(), entry));
} }
@ -203,19 +203,19 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
// Regular Files // Regular Files
// ---------------------------------------------- // ----------------------------------------------
else if(searchFiles && file.isFile()){ else if (searchFiles && file.isFile()) {
if(extension == null && fileName == null) // Should we match all files if (extension == null && fileName == null) // Should we match all files
break; break;
else if(extension != null && else if (extension != null &&
FileUtil.getFileExtension(file.getName()).equalsIgnoreCase(extension)) FileUtil.getFileExtension(file.getName()).equalsIgnoreCase(extension))
break; break;
else if(fileName != null && else if (fileName != null &&
file.getName().equalsIgnoreCase(fileName)) file.getName().equalsIgnoreCase(fileName))
break; break;
} }
} }
if(index <fileList.size()) { if (index <fileList.size()) {
nextItem = fileList.get(index); nextItem = fileList.get(index);
++index; ++index;
} }
@ -225,8 +225,8 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
return ret; return ret;
} }
private void addFiles(FileSearchItem root, String[] list){ private void addFiles(FileSearchItem root, String[] list) {
if(root instanceof FileSearchFileItem) { if (root instanceof FileSearchFileItem) {
for (String file : list) { for (String file : list) {
fileList.add(new FileSearchFileItem( fileList.add(new FileSearchFileItem(
new File(((FileSearchFileItem)root).file, file))); new File(((FileSearchFileItem)root).file, file)));
@ -258,7 +258,7 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
protected static class FileSearchFileItem implements FileSearchItem{ protected static class FileSearchFileItem implements FileSearchItem{
private File file; private File file;
protected FileSearchFileItem(File file){ protected FileSearchFileItem(File file) {
this.file = file; this.file = file;
} }
@ -281,14 +281,14 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
private ZipEntry entry; private ZipEntry entry;
private String fileName; private String fileName;
protected FileSearchZipItem(String file, ZipEntry entry){ protected FileSearchZipItem(String file, ZipEntry entry) {
this.zipFile = file; this.zipFile = file;
this.entry = entry; this.entry = entry;
this.fileName = new File(entry.getName()).getName(); this.fileName = new File(entry.getName()).getName();
} }
public String getName() { return fileName; } 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 isCompressed() { return true; }
public boolean isFile() { return !entry.isDirectory(); } public boolean isFile() { return !entry.isDirectory(); }

View file

@ -52,8 +52,8 @@ public class FileUtil {
* @param path is the path * @param path is the path
* @return A String with a relative path * @return A String with a relative path
*/ */
public static String relativePath(File file, String path){ public static String relativePath(File file, String path) {
if(file == null || path == null) if (file == null || path == null)
return null; return null;
String absolute = file.getAbsolutePath(); String absolute = file.getAbsolutePath();
@ -75,14 +75,14 @@ public class FileUtil {
* @param path is the path to the file (no / if not absolute path) * @param path is the path to the file (no / if not absolute path)
* @return A File object for the file * @return A File object for the file
*/ */
public static File find(String path){ public static File find(String path) {
try { try {
File file = new File(path); File file = new File(path);
if(file.exists()) if (file.exists())
return file; return file;
URL url = findURL(path); URL url = findURL(path);
if(url != null && "file".equals(url.getProtocol())) if (url != null && "file".equals(url.getProtocol()))
return new File(url.toURI()); return new File(url.toURI());
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.FINE, "Unable to find file: " + path, 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{ public static void copy(File source, File destination) throws IOException{
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); 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); IOUtil.copyStream(in, out);
} }
@ -112,10 +112,10 @@ public class FileUtil {
* subsequent call will return a incremented the number * subsequent call will return a incremented the number
* if the previous file was created. * if the previous file was created.
*/ */
public static File getNextFile(File file){ public static File getNextFile(File file) {
for(int i = 1; i<10000; ++i){ for (int i = 1; i<10000; ++i) {
File next = new File(file.getParentFile(), file.getName() + "." + StringUtil.prefixInt(i, 4)); File next = new File(file.getParentFile(), file.getName() + "." + StringUtil.prefixInt(i, 4));
if(!next.exists()) if (!next.exists())
return next; return next;
} }
return null; return null;
@ -127,7 +127,7 @@ public class FileUtil {
* @param path is the path to the file (no / if not absolute path) * @param path is the path to the file (no / if not absolute path)
* @return A URL object for the file * @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); 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) * @param path is the path to the file (no / if not absolute path)
* @return A InputStream object for the file * @return A InputStream object for the file
*/ */
public static InputStream getInputStream(String path){ public static InputStream getInputStream(String path) {
try { try {
File file = new File(path); File file = new File(path);
if(file.exists()) if (file.exists())
return new BufferedInputStream(new FileInputStream(file)); return new BufferedInputStream(new FileInputStream(file));
return Thread.currentThread().getContextClassLoader() return Thread.currentThread().getContextClassLoader()
@ -217,7 +217,7 @@ public class FileUtil {
* @param dir is the directory to search in * @param dir is the directory to search in
* @return a List of files * @return a List of files
*/ */
public static List<File> search(File dir){ public static List<File> search(File dir) {
return search(dir, new LinkedList<>(), true); return search(dir, new LinkedList<>(), true);
} }
@ -229,7 +229,7 @@ public class FileUtil {
* @param recursive if the search should go into subdirectories * @param recursive if the search should go into subdirectories
* @return A List of files * @return A List of files
*/ */
public static List<File> search(File dir, List<File> fileList, boolean recursive){ public static List<File> search(File dir, List<File> fileList, boolean recursive) {
return search(dir, new LinkedList<>(), false, (recursive ? Integer.MAX_VALUE : 0)); 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 * @param recurse if the search should go into subdirectories
* @return A List with the files and/or folders * @return A List with the files and/or folders
*/ */
public static List<File> search(File dir, List<File> fileList, boolean folders, int recurse){ public static List<File> search(File dir, List<File> fileList, boolean folders, int recurse) {
if(recurse<0) if (recurse<0)
return fileList; return fileList;
--recurse; --recurse;
if(folders){ if (folders) {
fileList.add( dir ); fileList.add(dir);
} }
File file; File file;
String[] temp = dir.list(); String[] temp = dir.list();
if(temp != null){ if (temp != null) {
for(int i=0; i<temp.length ;i++){ for (int i=0; i<temp.length; i++) {
file = new File(dir.getPath()+File.separator+temp[i]); file = new File(dir.getPath()+File.separator+temp[i]);
if(file.isDirectory()){ if (file.isDirectory()) {
logger.finer("Found Folder: "+file); logger.finer("Found Folder: " +file);
search(new File(dir.getPath()+File.separator+temp[i]+File.separator), fileList, folders, recurse); search(new File(dir.getPath()+File.separator+temp[i]+File.separator), fileList, folders, recurse);
} }
else if(file.isFile()){ else if (file.isFile()) {
logger.finer("Found File: "+file); logger.finer("Found File: " +file);
fileList.add(file); fileList.add(file);
} }
} }
@ -275,7 +275,7 @@ public class FileUtil {
* @param file is the file * @param file is the file
* @return The extension * @return The extension
*/ */
public static String getFileExtension(File file){ public static String getFileExtension(File file) {
return getFileExtension(file.getName()); return getFileExtension(file.getName());
} }
@ -285,10 +285,10 @@ public class FileUtil {
* @param file is the file * @param file is the file
* @return The extension * @return The extension
*/ */
public static String getFileExtension(String file){ public static String getFileExtension(String file) {
if( file == null || file.lastIndexOf(".") == -1 ) if (file == null || file.lastIndexOf(".") == -1)
return ""; return "";
return file.substring(file.lastIndexOf(".")+1, file.length()); return file.substring(file.lastIndexOf(".")+1);
} }
/** /**
@ -298,11 +298,11 @@ public class FileUtil {
* @param ext is the new extension, without the dot * @param ext is the new extension, without the dot
*/ */
public static String replaceExtension(String file, String ext) { public static String replaceExtension(String file, String ext) {
if( file == null ) if (file == null)
return null; return null;
if( file.lastIndexOf(".") == -1 ) if (file.lastIndexOf(".") == -1)
return file+"."+ext; return file + "." + ext;
return file.substring(0, file.lastIndexOf(".")+1)+ext; return file.substring(0, file.lastIndexOf(".") + 1) + ext;
} }
/** /**
@ -318,14 +318,14 @@ public class FileUtil {
StringBuilder output = new StringBuilder(); StringBuilder output = new StringBuilder();
String line; String line;
while((line = in.readLine()) != null){ while ((line = in.readLine()) != null) {
// Found starting boundary // Found starting boundary
if(line.equals(boundary)){ if (line.equals(boundary)) {
while((line = in.readLine()) != null) while ((line = in.readLine()) != null)
// Find ending boundary // Find ending boundary
if(line.equals(boundary)) break; if (line.equals(boundary)) break;
// EOF and no ending boundary found // EOF and no ending boundary found
if(line == null){ if (line == null) {
in.close(); in.close();
throw new EOFException("No ending boundary found"); throw new EOFException("No ending boundary found");
} }

View file

@ -65,8 +65,8 @@ public class FileWatcher extends TimerTask{
* @param interval is the interval * @param interval is the interval
*/ */
public FileWatcher(File file, int interval) throws FileNotFoundException{ public FileWatcher(File file, int interval) throws FileNotFoundException{
if(file==null || !file.exists()) if (file==null || !file.exists())
throw new FileNotFoundException("File not found: "+file); throw new FileNotFoundException("File not found: " +file);
this.file = file; this.file = file;
lastChanged = file.lastModified(); lastChanged = file.lastModified();
@ -74,7 +74,7 @@ public class FileWatcher extends TimerTask{
t.schedule(this, 0, interval); t.schedule(this, 0, interval);
} }
public void setListener(FileChangeListener listener){ public void setListener(FileChangeListener listener) {
this.listener = listener; this.listener = listener;
} }
@ -82,11 +82,11 @@ public class FileWatcher extends TimerTask{
public void run() { public void run() {
if (lastChanged != file.lastModified()) { if (lastChanged != file.lastModified()) {
lastChanged = file.lastModified(); lastChanged = file.lastModified();
if(listener != null){ if (listener != null) {
listener.fileChangedEvent(file); listener.fileChangedEvent(file);
} }
else{ else {
logger.fine("File was modified ("+file+") but no listeners was registered."); logger.fine("File was modified (" + file + ") but no listeners was registered.");
} }
} }
} }

View file

@ -58,45 +58,45 @@ public class FileUploadListener implements ProgressListener{
private volatile long speedRead; private volatile long speedRead;
private volatile long speedTime; private volatile long speedTime;
public FileUploadListener(){ public FileUploadListener() {
id = ""+(int)(Math.random()*Integer.MAX_VALUE); id = "" +(int)(Math.random()*Integer.MAX_VALUE);
status = Status.Initializing; status = Status.Initializing;
filename = ""; filename = "";
message = ""; message = "";
} }
public void update(long pBytesRead, long pContentLength, int pItems) { public void update(long pBytesRead, long pContentLength, int pItems) {
if(pContentLength < 0) this.length = pBytesRead; if (pContentLength < 0) this.length = pBytesRead;
else this.length = pContentLength; else this.length = pContentLength;
this.bytes = pBytesRead; this.bytes = pBytesRead;
this.item = pItems; this.item = pItems;
// Calculate Speed // Calculate Speed
if(speedTime == 0 || speedTime+1000 < System.currentTimeMillis() || pBytesRead == pContentLength){ if (speedTime == 0 || speedTime+1000 < System.currentTimeMillis() || pBytesRead == pContentLength) {
speedTime = System.currentTimeMillis(); speedTime = System.currentTimeMillis();
speed = (int)(pBytesRead-speedRead); speed = (int)(pBytesRead-speedRead);
speedRead = pBytesRead; speedRead = pBytesRead;
} }
//try{Thread.sleep(10);}catch(Exception e){} //try {Thread.sleep(10);} catch (Exception e) {}
// Set Status // Set Status
status = Status.Uploading; status = Status.Uploading;
time = System.currentTimeMillis(); time = System.currentTimeMillis();
} }
protected void setFileName(String filename){ protected void setFileName(String filename) {
this.filename = filename; this.filename = filename;
} }
protected void setStatus(Status status){ protected void setStatus(Status status) {
this.status = status; this.status = status;
time = System.currentTimeMillis(); time = System.currentTimeMillis();
} }
protected void setMessage(String msg){ protected void setMessage(String msg) {
this.message = msg; this.message = msg;
} }
public String getID(){ public String getID() {
return id; return id;
} }
@ -116,46 +116,46 @@ public class FileUploadListener implements ProgressListener{
return item; return item;
} }
public Status getStatus(){ public Status getStatus() {
return status; return status;
} }
protected long getTime(){ protected long getTime() {
return time; return time;
} }
protected String getMessage(){ protected String getMessage() {
return message; return message;
} }
/** /**
* @return bytes per second * @return bytes per second
*/ */
public int getSpeed(){ public int getSpeed() {
return speed; return speed;
} }
/** /**
* Calculate the percent complete * Calculate the percent complete
*/ */
public int getPercentComplete(){ public int getPercentComplete() {
if(length == 0) if (length == 0)
return 0; return 0;
return (int)((100 * bytes) / length); return (int)((100 * bytes) / length);
} }
public DataNode getJSON() { public DataNode getJSON() {
DataNode node = new DataNode( DataType.Map ); DataNode node = new DataNode(DataType.Map);
node.set("id", id); node.set("id", id);
node.set("status", status.toString()); node.set("status", status.toString());
node.set("message", message.replaceAll("\"", "\\\"") ); node.set("message", message.replaceAll("\"", "\\\""));
node.set("filename", filename); node.set("filename", filename);
node.set("percent", getPercentComplete()); node.set("percent", getPercentComplete());
node.set("uploaded", StringUtil.formatByteSizeToString(bytes)); node.set("uploaded", StringUtil.formatByteSizeToString(bytes));
node.set("total", StringUtil.formatByteSizeToString(length)); node.set("total", StringUtil.formatByteSizeToString(length));
node.set("speed", StringUtil.formatByteSizeToString(speed)+"/s"); node.set("speed", StringUtil.formatByteSizeToString(speed) + "/s");
return node; return node;
} }
} }

View file

@ -58,13 +58,13 @@ public class CompactLogFormatter extends Formatter{
public String format(LogRecord record) { public String format(LogRecord record) {
StringBuilder prefix = new StringBuilder(); StringBuilder prefix = new StringBuilder();
if( timeStamp ){ if (timeStamp) {
date.setTime( record.getMillis() ); date.setTime(record.getMillis());
prefix.append(dateFormatter.format(date)); prefix.append(dateFormatter.format(date));
prefix.append(' '); prefix.append(' ');
} }
switch( record.getLevel().intValue() ){ switch(record.getLevel().intValue()) {
case /* SEVERE */ 1000: prefix.append("[SEVERE] "); break; case /* SEVERE */ 1000: prefix.append("[SEVERE] "); break;
case /* WARNING */ 900 : prefix.append("[WARNING]"); break; case /* WARNING */ 900 : prefix.append("[WARNING]"); break;
case /* INFO */ 800 : prefix.append("[INFO] "); break; case /* INFO */ 800 : prefix.append("[INFO] "); break;
@ -75,39 +75,39 @@ public class CompactLogFormatter extends Formatter{
} }
prefix.append(' '); prefix.append(' ');
if( className ){ if (className) {
prefix.append(paddClassName(record.getSourceClassName())); prefix.append(paddClassName(record.getSourceClassName()));
} }
if(methodName){ if (methodName) {
prefix.append(record.getSourceMethodName()); prefix.append(record.getSourceMethodName());
} }
prefix.append(": "); prefix.append(": ");
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
if( record.getMessage() != null ){ if (record.getMessage() != null) {
String[] array = splitter.split( record.getMessage() ); String[] array = splitter.split(record.getMessage());
for( int i=0; i<array.length ;++i ){ for (int i=0; i<array.length; ++i) {
if( i!=0 ) if (i != 0)
ret.append( '\n' ); ret.append('\n');
if( prefix.length() > 0 ) if (prefix.length() > 0)
ret.append( prefix ); ret.append(prefix);
ret.append( array[i] ); ret.append(array[i]);
} }
ret.append( '\n' ); ret.append('\n');
} }
if( record.getThrown() != null ){ if (record.getThrown() != null) {
StringOutputStream out = new StringOutputStream(); StringOutputStream out = new StringOutputStream();
record.getThrown().printStackTrace(new PrintStream(out)); record.getThrown().printStackTrace(new PrintStream(out));
String[] array = splitter.split( out.toString() ); String[] array = splitter.split(out.toString());
for( int i=0; i<array.length ;++i ){ for (int i=0; i<array.length; ++i) {
if( i!=0 ) if (i != 0)
ret.append( '\n' ); ret.append('\n');
if( prefix.length() > 0 ) if (prefix.length() > 0)
ret.append( prefix ); ret.append(prefix);
ret.append( array[i] ); ret.append(array[i]);
} }
ret.append( '\n' ); ret.append('\n');
} }
return ret.toString(); return ret.toString();
} }
@ -117,7 +117,7 @@ public class CompactLogFormatter extends Formatter{
* *
* @param enable set to True to activate time stamp * @param enable set to True to activate time stamp
*/ */
public void enableTimeStamp(boolean enable){ public void enableTimeStamp(boolean enable) {
timeStamp = enable; timeStamp = enable;
} }
@ -126,7 +126,7 @@ public class CompactLogFormatter extends Formatter{
* *
* @param ts is the String to send to SimpleDateFormat * @param ts is the String to send to SimpleDateFormat
*/ */
public void setTimeStamp(String ts){ public void setTimeStamp(String ts) {
dateFormatter = new SimpleDateFormat(ts); dateFormatter = new SimpleDateFormat(ts);
} }
@ -135,7 +135,7 @@ public class CompactLogFormatter extends Formatter{
* *
* @param enable set to True to activate class/source name * @param enable set to True to activate class/source name
*/ */
public void enableClassName(boolean enable){ public void enableClassName(boolean enable) {
className = enable; className = enable;
} }
@ -144,14 +144,14 @@ public class CompactLogFormatter extends Formatter{
* *
* @param enable set to True to activate class/source name * @param enable set to True to activate class/source name
*/ */
public void enableMethodName(boolean enable){ public void enableMethodName(boolean enable) {
methodName = enable; methodName = enable;
} }
/** /**
* @return the Class name * @return the Class name
*/ */
private String paddClassName(String source){ private String paddClassName(String source) {
String cStr = padd_cache.get(source); String cStr = padd_cache.get(source);
if (cStr == null || cStr.length() != max_class_name) { if (cStr == null || cStr.length() != max_class_name) {
cStr = source.substring(source.lastIndexOf('.') + 1); // Remove packages cStr = source.substring(source.lastIndexOf('.') + 1); // Remove packages

View file

@ -57,7 +57,7 @@ public class CounterManager {
} }
private static synchronized Counter getCounter(String clazz, String name) { private static synchronized Counter getCounter(String clazz, String name) {
Counter counter; Counter counter;
if ( ! counters.containsKey(clazz) || ! counters.get(clazz).containsKey(name)) { if (! counters.containsKey(clazz) || ! counters.get(clazz).containsKey(name)) {
// Get the platform MBeanServer // Get the platform MBeanServer
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
// Unique identification of MBeans // Unique identification of MBeans
@ -68,7 +68,7 @@ public class CounterManager {
ObjectName objectName = new ObjectName(clazz + ":name=" + counter.getName()); ObjectName objectName = new ObjectName(clazz + ":name=" + counter.getName());
mbs.registerMBean(counter, objectName); mbs.registerMBean(counter, objectName);
// Register the singleton // Register the singleton
if ( ! counters.containsKey(clazz)) if (! counters.containsKey(clazz))
counters.put(clazz, new HashMap<>()); counters.put(clazz, new HashMap<>());
counters.get(clazz).put(name, counter); counters.get(clazz).put(name, counter);
} catch (Exception e) { } catch (Exception e) {
@ -103,28 +103,28 @@ public class CounterManager {
private AtomicInteger counter = new AtomicInteger(); private AtomicInteger counter = new AtomicInteger();
protected Counter(String name){ protected Counter(String name) {
this.name = name; this.name = name;
} }
public void add(int i){ public void add(int i) {
int prev = counter.getAndAdd(i); int prev = counter.getAndAdd(i);
updateMetaData(prev + i); updateMetaData(prev + i);
} }
public void set(int i){ public void set(int i) {
counter.getAndSet(i); counter.getAndSet(i);
updateMetaData(i); updateMetaData(i);
} }
public void increment(){ public void increment() {
int i = counter.incrementAndGet(); int i = counter.incrementAndGet();
updateMetaData(i); updateMetaData(i);
} }
public void decrement(){ public void decrement() {
int i = counter.decrementAndGet(); int i = counter.decrementAndGet();
updateMetaData(i); updateMetaData(i);
} }
private void updateMetaData(int i){ private void updateMetaData(int i) {
if (max < i) if (max < i)
max = i; max = i;
if (min > i) if (min > i)
@ -142,7 +142,7 @@ public class CounterManager {
* @return current value of the counter * @return current value of the counter
*/ */
@Override @Override
public int getValue(){ public int getValue() {
return counter.intValue(); return counter.intValue();
} }
/** /**

View file

@ -41,19 +41,19 @@ public class InputStreamLogger extends InputStream implements StreamLogger.LogCa
private InputStream in; private InputStream in;
private StreamLogger log; private StreamLogger log;
public InputStreamLogger(InputStream in){ public InputStreamLogger(InputStream in) {
this(null, in); this(null, in);
} }
public InputStreamLogger(String prefix, InputStream in){ public InputStreamLogger(String prefix, InputStream in) {
this.in = in; this.in = in;
this.log = new StreamLogger(prefix, this); this.log = new StreamLogger(prefix, this);
} }
public boolean isLoggable(){ public boolean isLoggable() {
return logger.isLoggable(Level.FINEST); return logger.isLoggable(Level.FINEST);
} }
public void log(String msg){ public void log(String msg) {
logger.finest(msg); logger.finest(msg);
} }

View file

@ -37,15 +37,15 @@ import java.util.logging.*;
* @author Ziver * @author Ziver
*/ */
public class LogUtil { 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 * @return a new Logger for the calling class
*/ */
public static Logger getLogger(){ public static Logger getLogger() {
return Logger.getLogger(ClassUtil.getCallingClass(LogUtil.class)); return Logger.getLogger(ClassUtil.getCallingClass(LogUtil.class));
} }
@ -54,7 +54,7 @@ public class LogUtil {
* *
* @param f is the formatter class * @param f is the formatter class
*/ */
public static void setGlobalFormatter(Formatter f){ public static void setGlobalFormatter(Formatter f) {
Logger root = Logger.getLogger(""); Logger root = Logger.getLogger("");
for (Handler handler : root.getHandlers()) { for (Handler handler : root.getHandlers()) {
handler.setFormatter(f); handler.setFormatter(f);
@ -66,7 +66,7 @@ public class LogUtil {
* *
* @param f is the formatter class * @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); Logger root = Logger.getLogger(name);
for (Handler handler : root.getHandlers()) { for (Handler handler : root.getHandlers()) {
handler.setFormatter(f); handler.setFormatter(f);
@ -76,14 +76,14 @@ public class LogUtil {
/** /**
* Sets the global log level * Sets the global log level
*/ */
public static void setGlobalLevel(Level level){ public static void setGlobalLevel(Level level) {
setLevel("", level); setLevel("", level);
} }
/** /**
* Adds a Handler to the root namespace * Adds a Handler to the root namespace
*/ */
public static void addGlobalHandler(Handler handler){ public static void addGlobalHandler(Handler handler) {
Logger root = Logger.getLogger(""); Logger root = Logger.getLogger("");
root.addHandler(handler); root.addHandler(handler);
} }
@ -91,33 +91,33 @@ public class LogUtil {
/** /**
* Sets the log level for a specified class * 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); setLevel(c.getName(), level);
} }
/** /**
* Sets the log level for a specified logger * Sets the log level for a specified logger
*/ */
public static void setLevel(String name, Level level){ public static void setLevel(String name, Level level) {
logger.fine("Changing log level of \""+name+"\" to \""+level.getLocalizedName()+"\""); logger.fine("Changing log level of \"" + name + "\" to \"" + level.getLocalizedName() + "\"");
Logger newLogger = Logger.getLogger(name); Logger newLogger = Logger.getLogger(name);
newLogger.setLevel(level); newLogger.setLevel(level);
// Check if the logger has a handler // 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 // Set the level on the handlers if its level is higher
for (Handler handler : newLogger.getHandlers()) { for (Handler handler : newLogger.getHandlers()) {
if(handler.getLevel().intValue() > level.intValue()) if (handler.getLevel().intValue() > level.intValue())
handler.setLevel(level); 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); return Logger.getLogger(clazz.getName()).isLoggable(level);
} }
public static void readConfiguration(String file){ public static void readConfiguration(String file) {
try{ try {
File confFile = FileUtil.find(file); File confFile = FileUtil.find(file);
if (confFile != null) { if (confFile != null) {
FileInputStream in = new FileInputStream(confFile); FileInputStream in = new FileInputStream(confFile);
@ -125,9 +125,9 @@ public class LogUtil {
in.close(); in.close();
} }
else else
logger.warning("Unable to find logging configuration file: "+file); logger.warning("Unable to find logging configuration file: " +file);
} catch (Exception e){ } catch (Exception e) {
logger.log(Level.SEVERE, "Unable to load logging configuration: "+file, e); logger.log(Level.SEVERE, "Unable to load logging configuration: " +file, e);
} }
} }
} }

View file

@ -42,19 +42,19 @@ public class OutputStreamLogger extends OutputStream implements StreamLogger.Log
private StreamLogger log; private StreamLogger log;
public OutputStreamLogger(OutputStream out){ public OutputStreamLogger(OutputStream out) {
this(null, out); this(null, out);
} }
public OutputStreamLogger(String prefix, OutputStream out){ public OutputStreamLogger(String prefix, OutputStream out) {
this.out = out; this.out = out;
this.log = new StreamLogger(prefix, this); this.log = new StreamLogger(prefix, this);
} }
public boolean isLoggable(){ public boolean isLoggable() {
return logger.isLoggable(Level.FINEST); return logger.isLoggable(Level.FINEST);
} }
public void log(String msg){ public void log(String msg) {
logger.finest(msg); logger.finest(msg);
} }

View file

@ -37,8 +37,8 @@ public class StreamLogger {
private StringBuilder buffer; private StringBuilder buffer;
protected StreamLogger(String prefix, LogCallback logger){ protected StreamLogger(String prefix, LogCallback logger) {
if(logger == null) if (logger == null)
throw new NullPointerException("LogCallback can not be NULL"); throw new NullPointerException("LogCallback can not be NULL");
this.prefix = prefix; this.prefix = prefix;
this.logger = logger; this.logger = logger;
@ -46,29 +46,29 @@ public class StreamLogger {
} }
protected void log(int n){ protected void log(int n) {
if(n < 0 || n == DELIMETER) if (n < 0 || n == DELIMETER)
flushLog(); flushLog();
else else
buffer.append((char)n); buffer.append((char)n);
if(buffer.length() > MAX_BUFFER_SIZE) if (buffer.length() > MAX_BUFFER_SIZE)
flushLog(); flushLog();
} }
protected void log(byte[] b, int off, int len){ protected void log(byte[] b, int off, int len) {
if (logger.isLoggable()) { if (logger.isLoggable()) {
for(int i=0; i<len; ++i){ for (int i=0; i<len; ++i) {
if(b[off+i] == DELIMETER) if (b[off+i] == DELIMETER)
flushLog(); flushLog();
else else
buffer.append((char)b[off+i]); buffer.append((char)b[off+i]);
} }
if(buffer.length() > MAX_BUFFER_SIZE) if (buffer.length() > MAX_BUFFER_SIZE)
flushLog(); flushLog();
} }
} }
protected void flushLog(){ protected void flushLog() {
if(buffer.length() > 0) { if (buffer.length() > 0) {
if (prefix != null) if (prefix != null)
logger.log(prefix + ": " + buffer.toString()); logger.log(prefix + ": " + buffer.toString());
else else
@ -76,7 +76,7 @@ public class StreamLogger {
clearLog(); clearLog();
} }
} }
protected void clearLog(){ protected void clearLog() {
buffer.delete(0, buffer.length()); buffer.delete(0, buffer.length());
} }

View file

@ -39,11 +39,11 @@ public class Matrix {
* *
* @return a new matrix with the result * @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]; double[][] result = new double[matrix.length][matrix[0].length];
for (int y=0; y < matrix.length; ++y) { 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; result[y][x] = matrix[y][x] + num;
} }
} }
@ -56,11 +56,11 @@ public class Matrix {
* *
* @return a new matrix with the result * @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]; double[][] result = new double[matrix.length][matrix[0].length];
for (int y=0; y < matrix.length; ++y) { 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; result[y][x] = matrix[y][x] - num;
} }
} }
@ -73,11 +73,11 @@ public class Matrix {
* *
* @return a new matrix with the result * @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]; double[][] result = new double[matrix.length][matrix[0].length];
for (int y=0; y < matrix.length; ++y) { 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; result[y][x] = matrix[y][x] * num;
} }
} }
@ -90,7 +90,7 @@ public class Matrix {
* *
* @return a new matrix with the result * @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); return multiply(matrix, 1/num);
} }
@ -176,7 +176,7 @@ public class Matrix {
* *
* @return a new matrix with the result * @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); vectorPreCheck(matrix, vector);
double[][] result = new double[matrix.length][matrix[0].length]; double[][] result = new double[matrix.length][matrix[0].length];
@ -194,7 +194,7 @@ public class Matrix {
* *
* @return a new matrix with the result * @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); vectorPreCheck(matrix, vector);
double[][] result = new double[matrix.length][matrix[0].length]; double[][] result = new double[matrix.length][matrix[0].length];
@ -255,7 +255,7 @@ public class Matrix {
* *
* @return a new vector with subtracted elements * @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); vectorPreCheck(vector1, vector2);
double[] result = new double[vector1.length]; double[] result = new double[vector1.length];
@ -271,7 +271,7 @@ public class Matrix {
* *
* @return a new matrix with subtracted elements * @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); vectorPreCheck(matrix, vector);
double[][] result = new double[matrix.length][matrix[0].length]; double[][] result = new double[matrix.length][matrix[0].length];
@ -289,7 +289,7 @@ public class Matrix {
* *
* @return a new vector with subtracted elements * @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); vectorPreCheck(vector1, vector2);
double[] result = new double[vector1.length]; double[] result = new double[vector1.length];
@ -305,7 +305,7 @@ public class Matrix {
* *
* @return a new matrix with subtracted elements * @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); vectorPreCheck(matrix, vector);
double[][] result = new double[matrix.length][matrix[0].length]; double[][] result = new double[matrix.length][matrix[0].length];
@ -324,7 +324,7 @@ public class Matrix {
* *
* @return a new vector with the result * @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); vectorPreCheck(matrix, vector);
double[] result = new double[matrix.length]; double[] result = new double[matrix.length];
@ -342,12 +342,12 @@ public class Matrix {
* *
* @return a new vector with the result * @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); vectorPreCheck(matrix, vector);
double[] result = new double[matrix.length]; double[] result = new double[matrix.length];
for (int y=0; y < matrix.length; ++y) { 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]; result[y] += matrix[y][x] / vector[x];
} }
} }
@ -389,13 +389,13 @@ public class Matrix {
* *
* @return a new matrix with the result * @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); matrixPreCheck(matrix1, matrix2);
double[][] result = new double[matrix1.length][matrix2[0].length]; double[][] result = new double[matrix1.length][matrix2[0].length];
for (int y=0; y < result.length; ++y) { for (int y=0; y < result.length; ++y) {
for (int x=0; x<matrix1[0].length; ++x) { for (int x=0; x<matrix1[0].length; ++x) {
for (int i=0; i < result[y].length; ++i){ for (int i=0; i < result[y].length; ++i) {
result[y][i] += matrix1[y][x] * matrix2[x][i]; result[y][i] += matrix1[y][x] * matrix2[x][i];
} }
} }
@ -406,11 +406,11 @@ public class Matrix {
/** /**
* @return a new matrix with the transpose of the input matrix. * @return a new matrix with the transpose of the input matrix.
*/ */
public static double[][] transpose(double[][] matrix){ public static double[][] transpose(double[][] matrix) {
double[][] result = new double[matrix[0].length][matrix.length]; double[][] result = new double[matrix[0].length][matrix.length];
for (int y=0; y < result.length; ++y) { for (int y=0; y < result.length; ++y) {
for (int x=0; x < result[y].length; ++x){ for (int x=0; x < result[y].length; ++x) {
result[y][x] = matrix[x][y]; result[y][x] = matrix[x][y];
} }
} }
@ -444,7 +444,7 @@ public class Matrix {
/** /**
* @return a identity matrix (n x n) where the diagonal elements have the value 1 * @return a identity matrix (n x n) where the diagonal elements have the value 1
*/ */
public static double[][] identity(int n){ public static double[][] identity(int n) {
double[][] result = new double[n][n]; double[][] result = new double[n][n];
for (int i=0; i < n; ++i) { for (int i=0; i < n; ++i) {

View file

@ -33,23 +33,23 @@ public class Tick {
* @param maxChar is the maximum number of characters in the string * @param maxChar is the maximum number of characters in the string
* @return the ticked string * @return the ticked string
*/ */
public static String tick(String ts, int maxChar){ public static String tick(String ts, int maxChar) {
StringBuffer ret = new StringBuffer(ts.trim()); StringBuffer ret = new StringBuffer(ts.trim());
int index = ret.length()-1; int index = ret.length()-1;
if(ret.length() < maxChar){ if (ret.length() < maxChar) {
ret.append('a'); ret.append('a');
} }
else{ else {
while(index >= 0){ while (index >= 0) {
char c = increment(ret.charAt(index)); char c = increment(ret.charAt(index));
if(c != 0){ if (c != 0) {
if(index == 0 && ret.length() < maxChar) ret.append('a'); if (index == 0 && ret.length() < maxChar) ret.append('a');
if(index == 0) ret = new StringBuffer(""+c); if (index == 0) ret = new StringBuffer("" +c);
else ret.setCharAt(index,c); else ret.setCharAt(index,c);
break; break;
} }
else{ else {
//ret.setCharAt(index,'a'); //ret.setCharAt(index,'a');
ret.deleteCharAt(index); ret.deleteCharAt(index);
index--; index--;
@ -66,14 +66,14 @@ public class Tick {
* @param c is the char to increment * @param c is the char to increment
* @return the incremented char in lowercase 0 if it reached the end * @return the incremented char in lowercase 0 if it reached the end
*/ */
public static char increment(char c){ public static char increment(char c) {
switch(Character.toLowerCase(c)){ switch(Character.toLowerCase(c)) {
case 'z': return (char)134; case 'z': return (char)134;
case (char)134: return (char)132; case (char)134: return (char)132;
case (char)132: return (char)148; case (char)132: return (char)148;
} }
c = (char)(Character.toLowerCase(c) + 1); c = (char)(Character.toLowerCase(c) + 1);
if(isAlphabetic(c)){ if (isAlphabetic(c)) {
return c; return c;
} }
return 0; return 0;
@ -86,8 +86,8 @@ public class Tick {
* @param c is the char to check * @param c is the char to check
* @return true if the char is a valid letter * @return true if the char is a valid letter
*/ */
public static boolean isAlphabetic(char c){ public static boolean isAlphabetic(char c) {
switch(Character.toLowerCase(c)){ switch(Character.toLowerCase(c)) {
case 'a': case 'a':
case 'b': case 'b':
case 'c': case 'c':

View file

@ -36,7 +36,7 @@ public class ZMath {
/** /**
* Calculates the percentage of the values * 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; return ((double)(value-min)/(max-min))*100;
} }
@ -45,10 +45,10 @@ public class ZMath {
* *
* @return the two values of x as an array * @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[] ret = new double[2];
double t = (p/2); double t = (p/2);
ret[0] = Math.sqrt( t*t - q ); ret[0] = Math.sqrt(t*t - q);
ret[1] = -ret[0]; ret[1] = -ret[0];
t *= -1; t *= -1;
ret[0] += t; ret[0] += t;
@ -62,14 +62,14 @@ public class ZMath {
* *
* @return the two values of x as an array * @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[] ret = new BigInteger[2];
BigInteger t = p.divide( BigInteger.valueOf(2) ); BigInteger t = p.divide(BigInteger.valueOf(2));
ret[0] = sqrt( t.multiply( t ).subtract( q ) ); ret[0] = sqrt(t.multiply(t).subtract(q));
ret[1] = ret[0].negate(); ret[1] = ret[0].negate();
t = t.negate(); t = t.negate();
ret[0] = ret[0].add( t ); ret[0] = ret[0].add(t);
ret[1] = ret[1].add( t ); ret[1] = ret[1].add(t);
return ret; return ret;
} }
@ -77,23 +77,23 @@ public class ZMath {
* Calculates the square root of a big number * Calculates the square root of a big number
* *
*/ */
public static BigInteger sqrt(BigInteger value){ public static BigInteger sqrt(BigInteger value) {
BigInteger op = value; BigInteger op = value;
BigInteger res = BigInteger.ZERO; BigInteger res = BigInteger.ZERO;
BigInteger one = BigInteger.ONE; BigInteger one = BigInteger.ONE;
while( one.compareTo( op ) < 0 ){ while (one.compareTo(op) < 0) {
one = one.shiftLeft( 2 ); one = one.shiftLeft(2);
} }
one = one.shiftRight(2); one = one.shiftRight(2);
while( !one.equals( BigInteger.ZERO ) ){ while (!one.equals(BigInteger.ZERO)) {
if( op.compareTo( res.add( one ) ) >= 0 ){ if (op.compareTo(res.add(one)) >= 0) {
op = op.subtract( res.add( one ) ); op = op.subtract(res.add(one));
res = res.add( one.shiftLeft( 1 ) ); res = res.add(one.shiftLeft(1));
} }
res = res.shiftRight( 1 ); res = res.shiftRight(1);
one = one.shiftRight( 2 ); one = one.shiftRight(2);
} }
return res; return res;

View file

@ -43,7 +43,7 @@ public class LinearRegression {
* h(x) = theta0 * x0 + theta1 * x1 + ... + thetan * xn =&gt; transpose(theta) * x * h(x) = theta0 * x0 + theta1 * x1 + ... + thetan * xn =&gt; transpose(theta) * x
* </i> * </i>
*/ */
protected static double[] calculateHypothesis(double[][] x, double[] theta){ protected static double[] calculateHypothesis(double[][] x, double[] theta) {
return Matrix.multiply(x, theta); return Matrix.multiply(x, theta);
} }
@ -56,7 +56,7 @@ public class LinearRegression {
* m = learning data size (rows) * m = learning data size (rows)
* @return a number indicating the error rate * @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[] hypothesis = calculateHypothesis(x, theta);
double[] normalized = Matrix.subtract(hypothesis, y); double[] normalized = Matrix.subtract(hypothesis, y);
@ -64,14 +64,14 @@ public class LinearRegression {
Matrix.Elemental.pow(normalized,2)); 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)); return Math.abs(Matrix.sum(vector1) - Matrix.sum(vector2));
} }
/** /**
* Will try to find the best theta value. * 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[] newTheta = theta.clone();
double[] prevTheta = new double[newTheta.length]; double[] prevTheta = new double[newTheta.length];
double thetaDiff = 0; double thetaDiff = 0;
@ -96,7 +96,7 @@ public class LinearRegression {
* <br> * <br>
* @return the theta that was found to minimize the cost function * @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[] newTheta = new double[theta.length];
double m = y.length; double m = y.length;
double[] hypothesis = calculateHypothesis(x, theta); double[] hypothesis = calculateHypothesis(x, theta);

View file

@ -55,7 +55,7 @@ public class Perceptron {
private OutputConnection[] outputs; private OutputConnection[] outputs;
public Perceptron(int inputCount, int outputCount){ public Perceptron(int inputCount, int outputCount) {
inputs = new InputConnection[inputCount]; inputs = new InputConnection[inputCount];
outputs = new OutputConnection[outputCount]; outputs = new OutputConnection[outputCount];
} }

View file

@ -66,17 +66,17 @@ public class FTPClient extends Thread{
PATH_CREATED ( 257 ); PATH_CREATED ( 257 );
private int code; private int code;
FTPReturnCode(int code){ FTPReturnCode(int code) {
this.code = code; this.code = code;
} }
public boolean isError(){ public boolean isError() {
return code >= 400; return code >= 400;
} }
public static FTPReturnCode fromCode(int code){ public static FTPReturnCode fromCode(int code) {
for(FTPReturnCode type : FTPReturnCode.values()){ for (FTPReturnCode type : FTPReturnCode.values()) {
if(code == type.code) return type; if (code == type.code) return type;
} }
return UNKNOWN; return UNKNOWN;
} }
@ -105,10 +105,10 @@ public class FTPClient extends Thread{
connectionType = conn_type; connectionType = conn_type;
readCommand(); readCommand();
sendCommand("USER "+user); sendCommand("USER " +user);
sendNoReplyCommand("PASS "+pass); sendNoReplyCommand("PASS " +pass);
String tmp = readCommand(); String tmp = readCommand();
if(parseReturnCode(tmp) == FTPReturnCode.LOGIN_NO){ if (parseReturnCode(tmp) == FTPReturnCode.LOGIN_NO) {
close(); close();
throw new AccountException(tmp); throw new AccountException(tmp);
} }
@ -126,7 +126,7 @@ public class FTPClient extends Thread{
*/ */
private FTPReturnCode sendCommand(String cmd) throws IOException{ private FTPReturnCode sendCommand(String cmd) throws IOException{
sendNoReplyCommand(cmd); sendNoReplyCommand(cmd);
return parseReturnCode( readCommand( ) ); return parseReturnCode(readCommand());
} }
/** /**
@ -145,9 +145,9 @@ public class FTPClient extends Thread{
*/ */
private String readCommand() throws IOException{ private String readCommand() throws IOException{
String tmp = in.readLine(); String tmp = in.readLine();
while(!Character.isWhitespace(tmp.charAt(3))){ while (!Character.isWhitespace(tmp.charAt(3))) {
tmp = in.readLine(); tmp = in.readLine();
if(parseReturnCode(tmp).isError()) throw new IOException(tmp); if (parseReturnCode(tmp).isError()) throw new IOException(tmp);
} }
return tmp; return tmp;
} }
@ -158,7 +158,7 @@ public class FTPClient extends Thread{
* @param msg message String from the server * @param msg message String from the server
* @return a status code response * @return a status code response
*/ */
private FTPReturnCode parseReturnCode(String msg){ private FTPReturnCode parseReturnCode(String msg) {
return FTPReturnCode.fromCode(Integer.parseInt(msg.substring(0, 3))); 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{ public String[] getFileList(String path) throws IOException{
BufferedInputStream data_in = getDataInputStream(); BufferedInputStream data_in = getDataInputStream();
sendCommand("NLST "+path); sendCommand("NLST " +path);
String data = new String(IOUtil.readContent(data_in)); String data = new String(IOUtil.readContent(data_in));
@ -192,7 +192,7 @@ public class FTPClient extends Thread{
Pattern regex = Pattern.compile("\\s+"); Pattern regex = Pattern.compile("\\s+");
BufferedInputStream data_in = getDataInputStream(); BufferedInputStream data_in = getDataInputStream();
sendCommand("LIST "+path); sendCommand("LIST " +path);
String data = new String(IOUtil.readContent(data_in)); 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{ public void sendFile(String path, String data) throws IOException{
BufferedOutputStream data_out = getDataOutputStream(); BufferedOutputStream data_out = getDataOutputStream();
sendCommand("STOR "+path); sendCommand("STOR " +path);
byte[] byte_data = data.getBytes(); byte[] byte_data = data.getBytes();
data_out.write(byte_data, 0, byte_data.length); 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 * @param path The path to the directory
*/ */
public boolean createDir(String path) throws IOException{ public boolean createDir(String path) throws IOException{
if(sendCommand("MKD "+path) == FTPReturnCode.PATH_CREATED) if (sendCommand("MKD " +path) == FTPReturnCode.PATH_CREATED)
return true; return true;
return false; return false;
} }
@ -237,7 +237,7 @@ public class FTPClient extends Thread{
*/ */
private BufferedInputStream getFileInputStream(String path) throws IOException{ private BufferedInputStream getFileInputStream(String path) throws IOException{
BufferedInputStream input = getDataInputStream(); BufferedInputStream input = getDataInputStream();
sendCommand("RETR "+path); sendCommand("RETR " +path);
return input; return input;
} }
@ -261,7 +261,7 @@ public class FTPClient extends Thread{
* @return true if the command was successful, false otherwise * @return true if the command was successful, false otherwise
*/ */
public boolean removeFile(String path) throws IOException{ 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 true;
return false; return false;
} }
@ -272,7 +272,7 @@ public class FTPClient extends Thread{
* @return True if the command was successful or false otherwise * @return True if the command was successful or false otherwise
*/ */
public boolean removeDir(String path) throws IOException{ 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 true;
return false; return false;
} }
@ -286,12 +286,12 @@ public class FTPClient extends Thread{
* @return a PrintStream for the channel * @return a PrintStream for the channel
*/ */
public BufferedOutputStream getDataOutputStream() throws IOException{ public BufferedOutputStream getDataOutputStream() throws IOException{
if(connectionType == FTPConnectionType.PASSIVE){ // Passive Mode if (connectionType == FTPConnectionType.PASSIVE) { // Passive Mode
int port = setPassiveMode(); int port = setPassiveMode();
Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port); Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port);
return new BufferedOutputStream(data_socket.getOutputStream()); return new BufferedOutputStream(data_socket.getOutputStream());
} }
else{ // Active Mode else { // Active Mode
return null; return null;
} }
} }
@ -302,12 +302,12 @@ public class FTPClient extends Thread{
* @return a BufferedReader for the data channel * @return a BufferedReader for the data channel
*/ */
public BufferedInputStream getDataInputStream() throws IOException{ public BufferedInputStream getDataInputStream() throws IOException{
if(connectionType == FTPConnectionType.PASSIVE){ // Passive Mode if (connectionType == FTPConnectionType.PASSIVE) { // Passive Mode
int port = setPassiveMode(); int port = setPassiveMode();
Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port); Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port);
return new BufferedInputStream(data_socket.getInputStream()); return new BufferedInputStream(data_socket.getInputStream());
} }
else{ // Active Mode else { // Active Mode
return null; return null;
} }
} }
@ -321,13 +321,13 @@ public class FTPClient extends Thread{
private int setPassiveMode() throws IOException{ private int setPassiveMode() throws IOException{
sendNoReplyCommand("PASV"); sendNoReplyCommand("PASV");
String ret_msg = readCommand(); String ret_msg = readCommand();
if(parseReturnCode(ret_msg) != FTPReturnCode.ENTERING_PASSIVE){ if (parseReturnCode(ret_msg) != FTPReturnCode.ENTERING_PASSIVE) {
throw new IOException("Passive mode rejected by server: "+ret_msg); throw new IOException("Passive mode rejected by server: " +ret_msg);
} }
ret_msg = ret_msg.substring(ret_msg.indexOf('(')+1, ret_msg.indexOf(')')); ret_msg = ret_msg.substring(ret_msg.indexOf('(')+1, ret_msg.indexOf(')'));
String[] tmpArray = ret_msg.split("[,]"); String[] tmpArray = ret_msg.split("[,]");
if(tmpArray.length <= 1) if (tmpArray.length <= 1)
return Integer.parseInt(tmpArray[0]); return Integer.parseInt(tmpArray[0]);
else else
return Integer.parseInt(tmpArray[4])*256 + Integer.parseInt(tmpArray[5]); return Integer.parseInt(tmpArray[4])*256 + Integer.parseInt(tmpArray[5]);
@ -339,13 +339,13 @@ public class FTPClient extends Thread{
/** /**
* Keep the connection alive * Keep the connection alive
*/ */
public void run(){ public void run() {
try { try {
while(true){ while (true) {
if(last_sent > System.currentTimeMillis() + FTP_NOOP_INT*1000){ if (last_sent > System.currentTimeMillis() + FTP_NOOP_INT * 1000) {
sendCommand("NOOP"); sendCommand("NOOP");
} }
try{ Thread.sleep(5000); }catch(Exception e){} try { Thread.sleep(5000); } catch (Exception e) {}
} }
} catch (IOException e1) { } catch (IOException e1) {
e1.printStackTrace(); e1.printStackTrace();

View file

@ -43,7 +43,7 @@ public class InetScanner {
private boolean canceled; private boolean canceled;
public void setListener(InetScanListener listener){ public void setListener(InetScanListener listener) {
this.listener = listener; this.listener = listener;
} }
@ -53,7 +53,7 @@ public class InetScanner {
* *
* @param ip the network ip address * @param ip the network ip address
*/ */
public synchronized void scan(InetAddress ip){ public synchronized void scan(InetAddress ip) {
canceled = false; canceled = false;
String netAddr = ip.getHostAddress().substring(0, ip.getHostAddress().lastIndexOf('.')+1); String netAddr = ip.getHostAddress().substring(0, ip.getHostAddress().lastIndexOf('.')+1);
@ -76,7 +76,7 @@ public class InetScanner {
/** /**
* Cancels the ongoing ip scan * Cancels the ongoing ip scan
*/ */
public void cancel(){ public void cancel() {
canceled = true; canceled = true;
} }
@ -84,7 +84,7 @@ public class InetScanner {
/** /**
* Will check if the given IP is reachable (Pingable) * 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)); String[] output = OSAbstractionLayer.exec(platformPingCmd(host));
for (String line : output) { for (String line : output) {
@ -108,18 +108,18 @@ public class InetScanner {
} }
private static String platformPingCmd(String ip){ private static String platformPingCmd(String ip) {
switch (OSAbstractionLayer.getInstance().getOSType()){ switch (OSAbstractionLayer.getInstance().getOSType()) {
case Windows: case Windows:
return "ping -n 1 -w "+ TIMEOUT_SEC*1000 +" " + ip; return "ping -n 1 -w " + (TIMEOUT_SEC*1000) + " " + ip;
case Linux: case Linux:
case MacOS: case MacOS:
return "ping -c 1 -W "+ TIMEOUT_SEC +" " + ip; return "ping -c 1 -W " + TIMEOUT_SEC + " " + ip;
default: default:
return null; return null;
} }
} }
private static boolean platformPingCheck(String line){ private static boolean platformPingCheck(String line) {
return line.contains("TTL=") || line.contains("ttl="); return line.contains("TTL=") || line.contains("ttl=");
} }

View file

@ -275,7 +275,7 @@ public class POP3Client {
*/ */
private boolean parseReturnCode(String msg) { private boolean parseReturnCode(String msg) {
int endPos = (msg.indexOf(' ') < 0 ? msg.length() : msg.indexOf(' ')); int endPos = (msg.indexOf(' ') < 0 ? msg.length() : msg.indexOf(' '));
return msg.substring(0, endPos).equals("+OK"); return msg.substring(0, endPos).equals(" +OK");
} }
//********************************************************************************* //*********************************************************************************

View file

@ -63,12 +63,12 @@ public class ServerFind extends Thread {
start(); start();
} }
public void run (){ public void run() {
byte[] buf = new byte[256]; byte[] buf = new byte[256];
DatagramPacket packet; DatagramPacket packet;
DatagramSocket lan_socket; DatagramSocket lan_socket;
while (!shutdown){ while (!shutdown) {
try { try {
packet = new DatagramPacket(buf, buf.length); packet = new DatagramPacket(buf, buf.length);
mSocket.receive(packet); mSocket.receive(packet);
@ -89,7 +89,7 @@ public class ServerFind extends Thread {
/** /**
* Closes the broadcast socket * Closes the broadcast socket
*/ */
public void close(){ public void close() {
shutdown = true; shutdown = true;
mSocket.close(); mSocket.close();
} }

View file

@ -46,7 +46,7 @@ public class ServerFindClient{
* *
* @param port The port to contact the server on * @param port The port to contact the server on
*/ */
public ServerFindClient(int port){ public ServerFindClient(int port) {
this.port = port; this.port = port;
} }

View file

@ -38,14 +38,14 @@ public class ThroughputCalculator {
private long total_data_amount; private long total_data_amount;
private float frequency = UPDATES_PER_SEC; private float frequency = UPDATES_PER_SEC;
public void setTotalHandledData(long bytes){ public void setTotalHandledData(long bytes) {
setHandledData(bytes - total_data_amount); setHandledData(bytes - total_data_amount);
total_data_amount = bytes; total_data_amount = bytes;
} }
public void setHandledData(long bytes){ public void setHandledData(long bytes) {
long currentTimeStamp = System.nanoTime(); long currentTimeStamp = System.nanoTime();
data_amount += bytes; 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); throughput = data_amount / ((currentTimeStamp - previousTimeStamp) / NANOSEC_PER_SECOND);
previousTimeStamp = currentTimeStamp; previousTimeStamp = currentTimeStamp;
data_amount = 0; data_amount = 0;
@ -53,21 +53,21 @@ public class ThroughputCalculator {
} }
} }
public double getByteThroughput(){ public double getByteThroughput() {
setHandledData(0); // Update throughput setHandledData(0); // Update throughput
updated = false; updated = false;
return throughput; return throughput;
} }
public double getBitThroughput(){ public double getBitThroughput() {
return getByteThroughput()*8; return getByteThroughput()*8;
} }
public boolean isUpdated(){ public boolean isUpdated() {
return updated; return updated;
} }
public void setFrequency(float frequency) { public void setFrequency(float frequency) {
if(frequency < 0) if (frequency < 0)
this.frequency = UPDATES_PER_SEC; this.frequency = UPDATES_PER_SEC;
else else
this.frequency = frequency; this.frequency = frequency;

View file

@ -64,12 +64,12 @@ public class MulticastDnsClient extends ThreadedUDPNetwork implements ThreadedUD
public MulticastDnsClient() throws IOException { public MulticastDnsClient() throws IOException {
super(MDNS_MULTICAST_ADDR, MDNS_MULTICAST_PORT); super(MDNS_MULTICAST_ADDR, MDNS_MULTICAST_PORT);
setThread( this ); setThread(this);
this.activeProbes = new HashSet<>(); this.activeProbes = new HashSet<>();
} }
public void setListener(DnsResolutionListener listener){ public void setListener(DnsResolutionListener listener) {
this.listener = listener; this.listener = listener;
} }
@ -91,11 +91,11 @@ public class MulticastDnsClient extends ThreadedUDPNetwork implements ThreadedUD
DatagramPacket udpPacket = new DatagramPacket( DatagramPacket udpPacket = new DatagramPacket(
buffer.toByteArray(), buffer.size(), buffer.toByteArray(), buffer.size(),
InetAddress.getByName( MDNS_MULTICAST_ADDR ), InetAddress.getByName(MDNS_MULTICAST_ADDR),
MDNS_MULTICAST_PORT ); MDNS_MULTICAST_PORT);
logger.fine("Sending MDSN probe id: "+id+", for domain: " + domain); logger.fine("Sending MDSN probe id: " + id + ", for domain: " + domain);
//System.out.println("Sending:\n"+ByteUtil.toFormattedString(udpPacket.getData(), udpPacket.getOffset(), udpPacket.getLength())); //System.out.println("Sending:\n" +ByteUtil.toFormattedString(udpPacket.getData(), udpPacket.getOffset(), udpPacket.getLength()));
//MultiPrintStream.out.dump(dnsPacket,3); //MultiPrintStream.out.dump(dnsPacket,3);
send(udpPacket); send(udpPacket);
@ -109,19 +109,19 @@ public class MulticastDnsClient extends ThreadedUDPNetwork implements ThreadedUD
BinaryStructInputStream in = new BinaryStructInputStream(buffer); BinaryStructInputStream in = new BinaryStructInputStream(buffer);
DnsPacket dnsPacket = DnsPacket.read(in); 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); MultiPrintStream.out.dump(dnsPacket,3);
if (dnsPacket.getHeader().flagQueryResponse) { if (dnsPacket.getHeader().flagQueryResponse) {
if (activeProbes.contains(dnsPacket.getHeader().id)){ if (activeProbes.contains(dnsPacket.getHeader().id)) {
logger.fine("Received MDNS response from: "+packet.getAddress()+", msg id: " + dnsPacket.getHeader().id); logger.fine("Received MDNS response from: " + packet.getAddress() + ", msg id: " + dnsPacket.getHeader().id);
if (listener != null) if (listener != null)
listener.receivedResponse(dnsPacket); listener.receivedResponse(dnsPacket);
} else { } 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); logger.log(Level.WARNING, null, e);
} }
} }

View file

@ -66,7 +66,7 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD
public MulticastDnsServer() throws IOException { public MulticastDnsServer() throws IOException {
super(MDNS_MULTICAST_ADDR, MDNS_MULTICAST_PORT); 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 name is the domain name to add the entry under
* @param ip the IPv4 address to respond with * @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()); 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 clazz {@link zutil.net.dns.packet.DnsConstants.CLASS}
* @param data is the payload to include in client response * @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(); DnsPacketResource resource = new DnsPacketResource();
resource.name = name; resource.name = name;
resource.type = type; resource.type = type;
@ -100,7 +100,7 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD
} }
private void addEntry(DnsPacketResource resource) { private void addEntry(DnsPacketResource resource) {
if ( ! entries.containsKey(resource.name)) if (! entries.containsKey(resource.name))
entries.put(resource.name, new ArrayList<>()); entries.put(resource.name, new ArrayList<>());
entries.get(resource.name).add(resource); entries.get(resource.name).add(resource);
} }
@ -116,9 +116,9 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD
DnsPacket dnsPacket = DnsPacket.read(in); DnsPacket dnsPacket = DnsPacket.read(in);
// Just handle queries and no responses // Just handle queries and no responses
if ( ! dnsPacket.getHeader().flagQueryResponse) { if (! dnsPacket.getHeader().flagQueryResponse) {
DnsPacket response = handleReceivedPacket(packet.getAddress(), dnsPacket); DnsPacket response = handleReceivedPacket(packet.getAddress(), dnsPacket);
if (response != null){ if (response != null) {
ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
BinaryStructOutputStream out = new BinaryStructOutputStream(outBuffer); BinaryStructOutputStream out = new BinaryStructOutputStream(outBuffer);
response.write(out); response.write(out);
@ -126,29 +126,29 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD
DatagramPacket outPacket = new DatagramPacket( DatagramPacket outPacket = new DatagramPacket(
outBuffer.toByteArray(), outBuffer.size(), outBuffer.toByteArray(), outBuffer.size(),
InetAddress.getByName( MDNS_MULTICAST_ADDR ), InetAddress.getByName(MDNS_MULTICAST_ADDR),
MDNS_MULTICAST_PORT ); MDNS_MULTICAST_PORT);
send(outPacket); send(outPacket);
} }
} }
} catch (IOException e){ } catch (IOException e) {
logger.log(Level.WARNING, null, 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(); DnsPacket response = new DnsPacket();
response.getHeader().setDefaultResponseData(); response.getHeader().setDefaultResponseData();
for (DnsPacketQuestion question : request.getQuestions()){ for (DnsPacketQuestion question : request.getQuestions()) {
if (question.name == null) continue; if (question.name == null) continue;
switch (question.type){ switch (question.type) {
// ------------------------------------------ // ------------------------------------------
// Normal Domain Name Resolution // Normal Domain Name Resolution
// ------------------------------------------ // ------------------------------------------
case DnsConstants.TYPE.A: 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); logger.finer("Received request for domain: '" + question.name + "' from source: " + address);
response.addAnswerRecord(entries.get(question.name)); response.addAnswerRecord(entries.get(question.name));
} else { } else {
@ -163,7 +163,7 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD
case DnsConstants.TYPE.PTR: case DnsConstants.TYPE.PTR:
if (question.name.startsWith("_service.")) { if (question.name.startsWith("_service.")) {
String postFix = question.name.substring(9); String postFix = question.name.substring(9);
for (String domain : entries.keySet()){ for (String domain : entries.keySet()) {
if (domain.endsWith(postFix)) { if (domain.endsWith(postFix)) {
logger.finer("Received request for service: '" + question.name + "' from source: " + address); logger.finer("Received request for service: '" + question.name + "' from source: " + address);
response.addAnswerRecord(entries.get(domain)); 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); 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); logger.finer("Received request for service: '" + question.name + "' from source: " + address);
response.addAnswerRecord(entries.get(question.name)); response.addAnswerRecord(entries.get(question.name));
} else { } else {

View file

@ -46,7 +46,7 @@ public class DnsPacket {
private ArrayList<DnsPacketResource> additionalRecords; private ArrayList<DnsPacketResource> additionalRecords;
public DnsPacket(){ public DnsPacket() {
header = new DnsPacketHeader(); header = new DnsPacketHeader();
questions = new ArrayList<>(); questions = new ArrayList<>();
answerRecords = new ArrayList<>(); answerRecords = new ArrayList<>();
@ -55,40 +55,40 @@ public class DnsPacket {
} }
public DnsPacketHeader getHeader(){ public DnsPacketHeader getHeader() {
return header; return header;
} }
public List<DnsPacketQuestion> getQuestions(){ public List<DnsPacketQuestion> getQuestions() {
return Collections.unmodifiableList(questions); return Collections.unmodifiableList(questions);
} }
public List<DnsPacketResource> getAnswerRecords(){ public List<DnsPacketResource> getAnswerRecords() {
return Collections.unmodifiableList(answerRecords); return Collections.unmodifiableList(answerRecords);
} }
public List<DnsPacketResource> getNameServers(){ public List<DnsPacketResource> getNameServers() {
return Collections.unmodifiableList(nameServers); return Collections.unmodifiableList(nameServers);
} }
public List<DnsPacketResource> getAdditionalRecords(){ public List<DnsPacketResource> getAdditionalRecords() {
return Collections.unmodifiableList(additionalRecords); return Collections.unmodifiableList(additionalRecords);
} }
public void addQuestion(DnsPacketQuestion question){ public void addQuestion(DnsPacketQuestion question) {
questions.add(question); questions.add(question);
header.countQuestion = questions.size(); header.countQuestion = questions.size();
} }
public void addAnswerRecord(DnsPacketResource resource){ public void addAnswerRecord(DnsPacketResource resource) {
answerRecords.add(resource); answerRecords.add(resource);
header.countAnswerRecord = answerRecords.size(); header.countAnswerRecord = answerRecords.size();
} }
public void addAnswerRecord(List<DnsPacketResource> resources){ public void addAnswerRecord(List<DnsPacketResource> resources) {
answerRecords.addAll(resources); answerRecords.addAll(resources);
header.countAnswerRecord = answerRecords.size(); header.countAnswerRecord = answerRecords.size();
} }
public void addNameServer(DnsPacketResource resource){ public void addNameServer(DnsPacketResource resource) {
nameServers.add(resource); nameServers.add(resource);
header.countNameServer = nameServers.size(); header.countNameServer = nameServers.size();
} }
public void addAdditionalRecord(DnsPacketResource resource){ public void addAdditionalRecord(DnsPacketResource resource) {
additionalRecords.add(resource); additionalRecords.add(resource);
header.countAdditionalRecord = additionalRecords.size(); header.countAdditionalRecord = additionalRecords.size();
} }
@ -109,7 +109,7 @@ public class DnsPacket {
return packet; return packet;
} }
private static void readResource(BinaryStructInputStream structIn, int count, ArrayList<DnsPacketResource> list) throws IOException { private static void readResource(BinaryStructInputStream structIn, int count, ArrayList<DnsPacketResource> list) throws IOException {
for (int i=0; i<count; ++i){ for (int i=0; i<count; ++i) {
DnsPacketResource resource = new DnsPacketResource(); DnsPacketResource resource = new DnsPacketResource();
structIn.read(resource); structIn.read(resource);
list.add(resource); list.add(resource);

View file

@ -152,7 +152,7 @@ public class HttpClient implements AutoCloseable {
Socket conn; Socket conn;
if ("https".equals(url.getProtocol())) { if ("https".equals(url.getProtocol())) {
conn = SSLSocketFactory.getDefault().createSocket(url.getHost(), port); conn = SSLSocketFactory.getDefault().createSocket(url.getHost(), port);
((SSLSocket )conn).startHandshake(); ((SSLSocket)conn).startHandshake();
} else { } else {
conn = new Socket(url.getHost(), port); conn = new Socket(url.getHost(), port);
} }

View file

@ -71,7 +71,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
* *
* @param port The port that the server should listen to * @param port The port that the server should listen to
*/ */
public HttpServer(int port){ public HttpServer(int port) {
this(port, null, null); this(port, null, null);
} }
@ -83,8 +83,8 @@ public class HttpServer extends ThreadedTCPNetworkServer{
* @param keyStore If this is not null then the server will use SSL connection with this keyStore file path * @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 * @param keyStorePass If this is not null then the server will use a SSL connection with the given certificate
*/ */
public HttpServer(int port, File keyStore, String keyStorePass){ public HttpServer(int port, File keyStore, String keyStorePass) {
super( port, keyStore, keyStorePass ); super(port, keyStore, keyStorePass);
pages = new ConcurrentHashMap<>(); pages = new ConcurrentHashMap<>();
sessions = new ConcurrentHashMap<>(); sessions = new ConcurrentHashMap<>();
@ -93,7 +93,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleWithFixedDelay(new SessionGarbageCollector(), 10000, SESSION_TTL / 2, TimeUnit.MILLISECONDS); 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 * removes old sessions from the session HashMap
*/ */
private class SessionGarbageCollector implements Runnable { private class SessionGarbageCollector implements Runnable {
public void run(){ public void run() {
Object[] keys = sessions.keySet().toArray(); Object[] keys = sessions.keySet().toArray();
int count = 0; int count = 0;
for(Object key : keys){ for (Object key : keys) {
Map<String,Object> session = sessions.get(key); Map<String,Object> session = sessions.get(key);
// Check if session is still valid // 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); sessions.remove(key);
++count; ++count;
} }
} }
if (count > 0) 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 name The URL or name of the page
* @param page The page itself * @param page The page itself
*/ */
public void setPage(String name, HttpPage page){ public void setPage(String name, HttpPage page) {
if(name.charAt(0) != '/') if (name.charAt(0) != '/')
name = "/"+name; name = "/" +name;
pages.put(name, page); pages.put(name, page);
} }
@ -136,13 +136,13 @@ public class HttpServer extends ThreadedTCPNetworkServer{
* *
* @param page The HttpPage that will be shown * @param page The HttpPage that will be shown
*/ */
public void setDefaultPage(HttpPage page){ public void setDefaultPage(HttpPage page) {
defaultPage = page; defaultPage = page;
} }
protected ThreadedTCPNetworkServerThread getThreadInstance( Socket s ){ protected ThreadedTCPNetworkServerThread getThreadInstance(Socket s) {
try { try {
return new HttpServerThread( s ); return new HttpServerThread(s);
} catch (IOException e) { } catch (IOException e) {
logger.log(Level.SEVERE, "Could not start new Thread", e); logger.log(Level.SEVERE, "Could not start new Thread", e);
} }
@ -163,7 +163,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
this.socket = socket; this.socket = socket;
} }
public void run(){ public void run() {
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
HttpHeaderParser headerParser; HttpHeaderParser headerParser;
HttpHeader header = null; HttpHeader header = null;
@ -261,11 +261,11 @@ public class HttpServer extends ThreadedTCPNetworkServer{
} }
} }
finally { finally {
try{ try {
out.close(); out.close();
in.close(); in.close();
socket.close(); socket.close();
} catch( Exception e ) { } catch(Exception e) {
logger.log(Level.WARNING, "Could not close connection", 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, protected static void logRequest(HttpHeader header,
Map<String,Object> session, Map<String,Object> session,
long time){ long time) {
// Debug // Debug
if(logger.isLoggable(Level.FINEST) ){ if (logger.isLoggable(Level.FINEST)) {
StringBuilder buff = new StringBuilder(); StringBuilder buff = new StringBuilder();
buff.append("Received request: ").append(header==null ? null : header.getRequestURL()); buff.append("Received request: ").append(header==null ? null : header.getRequestURL());
buff.append(", ("); buff.append(", (");
@ -288,10 +288,10 @@ public class HttpServer extends ThreadedTCPNetworkServer{
buff.append(", time: ").append(StringUtil.formatTimeToString(System.currentTimeMillis() - time)); buff.append(", time: ").append(StringUtil.formatTimeToString(System.currentTimeMillis() - time));
logger.finer(buff.toString()); logger.finer(buff.toString());
} else if(logger.isLoggable(Level.FINER)){ } else if (logger.isLoggable(Level.FINER)) {
logger.finer( logger.finer(
"Received request: " + (header==null ? null : header.getRequestURL()) "Received request: " + (header==null ? null : header.getRequestURL())
+ ", time: "+ StringUtil.formatTimeToString(System.currentTimeMillis() - time)); + ", time: " + StringUtil.formatTimeToString(System.currentTimeMillis() - time));
} }
} }
} }

View file

@ -59,18 +59,18 @@ public class MultipartFileField implements MultipartField{
/** /**
* @return the amount of data received for this field * @return the amount of data received for this field
*/ */
public long getLength(){ public long getLength() {
return 0; //TODO: return 0; //TODO:
} }
/** /**
* @return the field name * @return the field name
*/ */
public String getName(){ public String getName() {
return fieldname; return fieldname;
} }
public String getFilename(){ public String getFilename() {
return filename; return filename;
} }

View file

@ -61,24 +61,24 @@ public class MultipartParser implements Iterable<MultipartField>{
private MultiPartIterator iterator; private MultiPartIterator iterator;
public MultipartParser(InputStream in, String delimiter, long length){ public MultipartParser(InputStream in, String delimiter, long length) {
this.in = in; this.in = in;
this.delimiter = delimiter; this.delimiter = delimiter;
this.contentLength = length; this.contentLength = length;
} }
public MultipartParser(HttpHeader header){ public MultipartParser(HttpHeader header) {
this(header.getInputStream(), this(header.getInputStream(),
parseDelimiter(header.getHeader("Content-type")), parseDelimiter(header.getHeader("Content-type")),
Long.parseLong(header.getHeader("Content-Length"))); Long.parseLong(header.getHeader("Content-Length")));
} }
private static String parseDelimiter(String contentTypeHeader){ private static String parseDelimiter(String contentTypeHeader) {
String delimiter = contentTypeHeader.split(" *; *")[1]; String delimiter = contentTypeHeader.split(" *; *")[1];
delimiter = delimiter.split(" *= *")[1]; delimiter = delimiter.split(" *= *")[1];
return delimiter; return delimiter;
} }
public long getContentLength(){ public long getContentLength() {
return contentLength; return contentLength;
} }
@ -97,10 +97,10 @@ public class MultipartParser implements Iterable<MultipartField>{
private boolean firstIteration; private boolean firstIteration;
protected MultiPartIterator(){ protected MultiPartIterator() {
this.boundaryIn = new BufferedBoundaryInputStream(in); this.boundaryIn = new BufferedBoundaryInputStream(in);
this.boundaryIn.setBoundary("--"+delimiter); this.boundaryIn.setBoundary("--" +delimiter);
firstIteration = true; firstIteration = true;
} }
@ -136,8 +136,8 @@ public class MultipartParser implements Iterable<MultipartField>{
public MultipartField next() { public MultipartField next() {
try { try {
boundaryIn.next(); boundaryIn.next();
if (firstIteration){ if (firstIteration) {
this.boundaryIn.setBoundary("\n--"+delimiter); // Add new-line to boundary after the first iteration this.boundaryIn.setBoundary("\n--" +delimiter); // Add new-line to boundary after the first iteration
firstIteration = false; firstIteration = false;
} }
String tmp = IOUtil.readLine(boundaryIn); // read the new line after the delimiter String tmp = IOUtil.readLine(boundaryIn); // read the new line after the delimiter
@ -151,13 +151,13 @@ public class MultipartParser implements Iterable<MultipartField>{
// Parse // Parse
String disposition = headers.get(HEADER_CONTENT_DISPOSITION); String disposition = headers.get(HEADER_CONTENT_DISPOSITION);
if (disposition != null){ if (disposition != null) {
HttpHeaderParser.parseCookieValues(headers, disposition); HttpHeaderParser.parseCookieValues(headers, disposition);
if (headers.containsKey("form-data")){ if (headers.containsKey("form-data")) {
if (headers.containsKey("filename")){ if (headers.containsKey("filename")) {
return new MultipartFileField(headers, boundaryIn); return new MultipartFileField(headers, boundaryIn);
} }
else{ else {
MultipartStringField field = new MultipartStringField(headers, boundaryIn); MultipartStringField field = new MultipartStringField(headers, boundaryIn);
return field; return field;
} }

View file

@ -67,12 +67,12 @@ public class HttpDigestAuthPage implements HttpPage{
public HttpDigestAuthPage(HttpPage page){ public HttpDigestAuthPage(HttpPage page) {
targetPage = page; targetPage = page;
} }
public void setRealm(String realm){ public void setRealm(String realm) {
this.realm = 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.setHeader(HTTP_AUTH_HEADER, generateAuthHeader((String) session.get(AUTH_NONCE)));
out.println("401 Unauthorized"); 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.setResponseStatusCode(501);
out.println("501 Not Implemented"); out.println("501 Not Implemented");
} }
else{ else {
HashMap<String,String> authMap = HttpHeaderParser.parseHeaderValues( HashMap<String,String> authMap = HttpHeaderParser.parseHeaderValues(
headers.getHeader(HTTP_CLIENT_HEADER).substring(AUTH_TYPE.length()+1), // Skip auth type headers.getHeader(HTTP_CLIENT_HEADER).substring(AUTH_TYPE.length()+1), // Skip auth type
AUTH_DELIMITER); AUTH_DELIMITER);
@ -111,10 +111,10 @@ public class HttpDigestAuthPage implements HttpPage{
(String)session.get(AUTH_NONCE), (String)session.get(AUTH_NONCE),
authMap.get(AUTH_RESPONSE))) { authMap.get(AUTH_RESPONSE))) {
// Safe area, user authenticated // 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); targetPage.respond(out, headers, session, cookie, request);
} }
else{ else {
out.setResponseStatusCode(403); out.setResponseStatusCode(403);
out.println("403 Forbidden"); 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? if (!userMap.containsKey(username)) // do user exist?
return false; return false;
@ -130,13 +130,13 @@ public class HttpDigestAuthPage implements HttpPage{
generateH1(username, userMap.get(username), realm), generateH1(username, userMap.get(username), realm),
generateH2(uri), generateH2(uri),
nonce); nonce);
if (generatedResponse.equals(clientResponse)){ if (generatedResponse.equals(clientResponse)) {
return true; return true;
} }
return false; return false;
} }
private String generateAuthHeader(String nonce){ private String generateAuthHeader(String nonce) {
StringBuilder str = new StringBuilder(); StringBuilder str = new StringBuilder();
str.append(AUTH_TYPE).append(' '); str.append(AUTH_TYPE).append(' ');
str.append(AUTH_REALM).append("=\"").append(realm).append("\", "); str.append(AUTH_REALM).append("=\"").append(realm).append("\", ");
@ -145,7 +145,7 @@ public class HttpDigestAuthPage implements HttpPage{
return str.toString(); return str.toString();
} }
private String generateNonce(){ private String generateNonce() {
byte[] buff = new byte[128/8]; byte[] buff = new byte[128/8];
secRandom.nextBytes(buff); secRandom.nextBytes(buff);
return Hasher.SHA1(buff); return Hasher.SHA1(buff);
@ -155,7 +155,7 @@ public class HttpDigestAuthPage implements HttpPage{
String ha1; String ha1;
// If the algorithm directive's value is "MD5" or unspecified, then HA1 is // If the algorithm directive's value is "MD5" or unspecified, then HA1 is
// HA1=MD5(username:realm:password) // 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 // If the algorithm directive's value is "MD5-sess", then HA1 is
// HA1=MD5(MD5(username:realm:password):nonce:cnonce) // HA1=MD5(MD5(username:realm:password):nonce:cnonce)
return ha1; return ha1;
@ -165,19 +165,19 @@ public class HttpDigestAuthPage implements HttpPage{
String ha2; String ha2;
// If the qop directive's value is "auth" or is unspecified, then HA2 is // If the qop directive's value is "auth" or is unspecified, then HA2 is
// HA2=MD5(method:digestURI) // 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 // If the qop directive's value is "auth-int", then HA2 is
// HA2=MD5(method:digestURI:MD5(entityBody)) // HA2=MD5(method:digestURI:MD5(entityBody))
return ha2; return ha2;
} }
private static String generateResponseHash(String ha1, String ha2, String nonce){ private static String generateResponseHash(String ha1, String ha2, String nonce) {
String response; String response;
// If the qop directive's value is "auth" or "auth-int", then compute the response as follows: // 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) // response=MD5(HA1:nonce:nonceCount:cnonce:qop:HA2)
// If the qop directive is unspecified, then compute the response as follows: // If the qop directive is unspecified, then compute the response as follows:
// response=MD5(HA1:nonce:HA2) // response=MD5(HA1:nonce:HA2)
response = Hasher.MD5(ha1 +":"+ nonce +":"+ ha2); response = Hasher.MD5(ha1 + ":" + nonce + ":" + ha2);
return response; return response;
} }

View file

@ -64,7 +64,7 @@ public class HttpFilePage implements HttpPage{
/** /**
* @param file a reference to a root directory or a file. * @param file a reference to a root directory or a file.
*/ */
public HttpFilePage(File file){ public HttpFilePage(File file) {
if (file == null) if (file == null)
throw new IllegalArgumentException("Root path cannot be null.");; throw new IllegalArgumentException("Root path cannot be null.");;
@ -108,7 +108,7 @@ public class HttpFilePage implements HttpPage{
String url = headers.getRequestURL(); String url = headers.getRequestURL();
out.println(" <li><a href='" + out.println(" <li><a href='" +
url + (url.endsWith("/") ? "" : "/") + containingFile url + (url.endsWith("/") ? "" : "/") + containingFile
+"'>" + containingFile + "</a></li>"); + "'>" + containingFile + "</a></li>");
} }
out.println(" </ul>"); out.println(" </ul>");
out.println(" <hr>"); out.println(" <hr>");
@ -137,7 +137,7 @@ public class HttpFilePage implements HttpPage{
if (!out.isHeaderSent()) if (!out.isHeaderSent())
out.setResponseStatusCode(500); out.setResponseStatusCode(500);
log.log(Level.WARNING, null, e); 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 * Enable or disable showing of folder contents
*/ */
public void showFolders(boolean enabled){ public void showFolders(boolean enabled) {
this.showFolders = enabled; this.showFolders = enabled;
} }
/** /**
* If directory links should be redirected to index files * If directory links should be redirected to index files
*/ */
public void redirectToIndexFile(boolean enabled){ public void redirectToIndexFile(boolean enabled) {
this.redirectToIndex = enabled; this.redirectToIndex = enabled;
} }
} }

View file

@ -40,11 +40,11 @@ public class HttpRedirectPage implements HttpPage{
private String redirectUrl; private String redirectUrl;
public HttpRedirectPage(String redirectUrl){ public HttpRedirectPage(String redirectUrl) {
this.redirectUrl = redirectUrl; this.redirectUrl = redirectUrl;
} }
public void setPermanentRedirect(boolean permanent){ public void setPermanentRedirect(boolean permanent) {
this.permanent = permanent; this.permanent = permanent;
} }
@ -63,14 +63,14 @@ public class HttpRedirectPage implements HttpPage{
"<html lang='en-US'>\n" + "<html lang='en-US'>\n" +
" <head>\n" + " <head>\n" +
" <meta charset='UTF-8'>\n" + " <meta charset='UTF-8'>\n" +
" <meta http-equiv='refresh' content='0;url="+ redirectUrl +"'>\n" + " <meta http-equiv='refresh' content='0;url=" + redirectUrl + "'>\n" +
" <script type='text/javascript'>\n" + " <script type='text/javascript'>\n" +
" window.location.href = '"+ redirectUrl +"'\n" + " window.location.href = '" + redirectUrl + "'\n" +
" </script>\n" + " </script>\n" +
" <title>Page Redirection</title>\n" + " <title>Page Redirection</title>\n" +
" </head>\n" + " </head>\n" +
" <body>\n" + " <body>\n" +
" If you are not redirected automatically, follow the <a href='"+ redirectUrl +"'>link to "+ redirectUrl +"</a>\n" + " If you are not redirected automatically, follow the <a href='" + redirectUrl + "'>link to " + redirectUrl + "</a>\n" +
" </body>\n" + " </body>\n" +
"</html>" "</html>"
); );

Some files were not shown because too many files have changed in this diff Show more