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

View file

@ -71,14 +71,14 @@ public class ClassUtil {
/**
* @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 if the given class is a primitive including String
*/
public static boolean isPrimitive(Class<?> type){
public static boolean isPrimitive(Class<?> type) {
return primitives.contains(type);
}
@ -86,7 +86,7 @@ public class ClassUtil {
* @return true if the given class is a type representing a number without any decimals.
* E.g. long, int, short, char, byte and corresponding wrapper.
*/
public static boolean isNumber(Class<?> type){
public static boolean isNumber(Class<?> type) {
return Long.class.isAssignableFrom(type) ||
long.class.isAssignableFrom(type) ||
Integer.class.isAssignableFrom(type) ||
@ -103,7 +103,7 @@ public class ClassUtil {
* @return true if the given class is a type representing a number with decimals.
* E.g. double, float and corresponding wrapper.
*/
public static boolean isDecimal(Class<?> type){
public static boolean isDecimal(Class<?> type) {
return Double.class.isAssignableFrom(type) ||
double.class.isAssignableFrom(type) ||
Float.class.isAssignableFrom(type) ||
@ -113,8 +113,8 @@ public class ClassUtil {
/**
* @return a bool value depending on if the given class is available in the classpath
*/
public boolean isAvailable(String clazz){
try{
public boolean isAvailable(String clazz) {
try {
Class.forName(clazz);
return true;
} catch (ClassNotFoundException e) {
@ -127,7 +127,7 @@ public class ClassUtil {
* @param field is the field to fetch the generics classes from.
* @return the generics class assigned to the specific field or a empty list if there are no generics.
*/
public static Class<?>[] getGenericClasses(Field field){
public static Class<?>[] getGenericClasses(Field field) {
return getGenericClasses(field.getGenericType());
}
@ -148,8 +148,8 @@ public class ClassUtil {
* @return the generics for a specific super class or a empty list if
* there is no generics or the super class is not found
*/
public static Class<?>[] getGenericClasses(Class<?> c, Class<?> superClass){
if(superClass != null) {
public static Class<?>[] getGenericClasses(Class<?> c, Class<?> superClass) {
if (superClass != null) {
// Search for the super class
while (c.getSuperclass() != null && c.getSuperclass() != Object.class) {
// Did we find the super class?
@ -160,13 +160,13 @@ public class ClassUtil {
}
return new Class[0];
}
private static Class<?>[] getGenericClasses(Type genericType){
if(genericType instanceof ParameterizedType){
private static Class<?>[] getGenericClasses(Type genericType) {
if (genericType instanceof ParameterizedType) {
ParameterizedType aType = (ParameterizedType) genericType;
Type[] argTypes = aType.getActualTypeArguments();
Class<?>[] classArray = new Class<?>[argTypes.length];
for(int i=0; i<classArray.length; ++i) {
if(argTypes[i] instanceof Class)
for (int i=0; i<classArray.length; ++i) {
if (argTypes[i] instanceof Class)
classArray[i] = (Class<?>) argTypes[i];
}
return classArray;
@ -178,16 +178,16 @@ public class ClassUtil {
/**
* @return the first class in the stack that do not match the filter
*/
public static String getCallingClass(Class... filter){
public static String getCallingClass(Class... filter) {
ArrayList filterStr = new ArrayList(filter.length + 1);
filterStr.add(ClassUtil.class.getName());
for (Class clazz : filter)
filterStr.add(clazz.getName());
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for(int i=1; i<stackTraceElements.length ;++i){
for (int i=1; i<stackTraceElements.length; ++i) {
String className = stackTraceElements[i].getClassName();
if( !filterStr.contains(className) ){
if (!filterStr.contains(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
*/
public CronTimer(String cron){
public CronTimer(String cron) {
String[] arr = cron.split("\\s");
if (arr.length < 5 || arr.length > 6)
throw new IllegalArgumentException(
"String must contain between 5-6 fields, but got("+arr.length+" fields): "+cron);
"String must contain between 5-6 fields, but got(" + arr.length + " fields): " + cron);
init(arr[0], arr[1], arr[2], arr[3], arr[4], (arr.length>5 ? arr[5]: "*"));
}
/**
* A Constructor that takes separate Strings for each field
*/
public CronTimer(String minute, String hour, String dayOfMonth, String monthOfYear, String dayOfWeek){
public CronTimer(String minute, String hour, String dayOfMonth, String monthOfYear, String dayOfWeek) {
this(minute, hour, dayOfMonth, monthOfYear, dayOfWeek, "*");
}
/**
* A Constructor that takes separate Strings for each field with an extended year field
*/
public CronTimer(String minute, String hour, String dayOfMonth, String monthOfYear, String dayOfWeek, String year){
public CronTimer(String minute, String hour, String dayOfMonth, String monthOfYear, String dayOfWeek, String year) {
init(minute, hour, dayOfMonth, monthOfYear, dayOfWeek, year);
}
private void init(String minute, String hour, String dayOfMonth, String monthOfYear, String dayOfWeek, String year){
private void init(String minute, String hour, String dayOfMonth, String monthOfYear, String dayOfWeek, String year) {
minutes = ArrayUtil.toIntArray(getRange(minute, 0, 59));
hours = ArrayUtil.toIntArray(getRange(hour, 0, 23));
dayOfMonths = ArrayUtil.toIntArray(getRange(dayOfMonth, 1, 31));
@ -105,14 +105,14 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
1970,
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())
return Collections.emptyList();
List<Integer> list = new LinkedList<>();
String[] commaArr = str.split(",");
if (commaArr.length > 1){
if (commaArr.length > 1) {
for (String section : commaArr)
list.addAll(getRange(section, from, to));
}
@ -128,20 +128,20 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
else {
String[] rangeArr;
if (str.equals("*"))
rangeArr = new String[]{""+from, ""+to};
rangeArr = new String[]{"" +from, "" +to};
else
rangeArr = str.split("-", 2);
if (rangeArr.length == 2) {
int rangeFrom = Integer.parseInt(rangeArr[0]);
int rangeTo = Integer.parseInt(rangeArr[1]);
if (from > rangeFrom || rangeTo > to)
throw new IllegalArgumentException("Invalid range "+rangeFrom+"-"+rangeTo+" must be between: "+from+"-"+to);
throw new IllegalArgumentException("Invalid range " + rangeFrom + "-" + rangeTo + " must be between: " + from + "-" + to);
for (int i = rangeFrom; i <= rangeTo; ++i)
list.add(i);
} else {
int value = Integer.parseInt(str);
if (from > value || value > to)
throw new IllegalArgumentException("Valid values are between "+from+"-"+to+" but got: "+value);
throw new IllegalArgumentException("Valid values are between " + from + "-" + to + " but got: " + value);
list.add(value);
}
}
@ -153,7 +153,7 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
/**
* Set the TimeZone that should be used by the cron algorithm
*/
public void setTimeZone(TimeZone timeZone){
public void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
}
@ -279,7 +279,7 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
return cal.getTimeInMillis();
}
protected Calendar getCalendar(long timestamp){
protected Calendar getCalendar(long timestamp) {
Calendar cal = Calendar.getInstance();
if (timeZone != null)
cal.setTimeZone(timeZone);
@ -290,8 +290,8 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
/**
* Converts Calendar DAY_OF_WEEK enum to id starting from 1 (Monday) to 7 (Sunday)
*/
private int getDayOfWeekID(int calDayOfWeek){
switch (calDayOfWeek){
private int getDayOfWeekID(int calDayOfWeek) {
switch (calDayOfWeek) {
case Calendar.MONDAY: return 1;
case Calendar.TUESDAY: return 2;
case Calendar.WEDNESDAY: return 3;
@ -302,8 +302,8 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
}
return -1;
}
private int getDayOfWeekEnum(int dayId){
switch (dayId){
private int getDayOfWeekEnum(int dayId) {
switch (dayId) {
case 1: return Calendar.MONDAY;
case 2: return Calendar.TUESDAY;
case 3: return Calendar.WEDNESDAY;

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

View file

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

View file

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

View file

@ -33,7 +33,7 @@ import java.nio.channels.OverlappingFileLockException;
/**
* This class checks if the application is already running
* by Locking a file
*
*
* @author Ziver Koc
*/
public class OneInstanceFile implements OneInstance{
@ -46,7 +46,7 @@ public class OneInstanceFile implements OneInstance{
*
* @param filename The name of the file to be locked
*/
public OneInstanceFile(String filename){
public OneInstanceFile(String filename) {
this.file = new File(System.getProperty("user.home"), filename);
}
@ -57,7 +57,7 @@ public class OneInstanceFile implements OneInstance{
*/
public boolean check() {
boolean tmp = lockApp();
if( tmp ) closeLock();
if (tmp) closeLock();
return !tmp;
}

View file

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

View file

@ -43,74 +43,74 @@ public class StringUtil {
* @param bytes size (in bytes)
* @return string
*/
public static String formatByteSizeToString(long bytes){
public static String formatByteSizeToString(long bytes) {
int total = sizes.length-1;
double value = bytes;
for(; value > 1024 ;total--) {
for (; value > 1024; total--) {
value /= 1024;
}
value = (double)( (int)(value*10) )/10;
return value+" "+sizes[total];
value = (double)((int)(value * 10)) / 10;
return value + " " + sizes[total];
}
/**
* @return a human readable String with year/month/day/hour/min/sec/milisec delimitation.
*/
public static String formatTimeToString(long milisec){
public static String formatTimeToString(long milisec) {
StringBuilder str = new StringBuilder();
long tmp;
// Years
if( milisec >= 31557032762.3361d ){
if (milisec >= 31557032762.3361d) {
tmp = (long) (milisec / 31557032762.3361d);
milisec -= tmp * 31557032762.3361d;
if( tmp > 1 )
if (tmp > 1)
str.append(tmp).append(" years ");
else
str.append(tmp).append(" year ");
}
// Months
if( milisec >= 2629743830L){
if (milisec >= 2629743830L) {
tmp = milisec / 2629743830L;
milisec -= tmp * 2629743830L;
if( tmp > 1 )
if (tmp > 1)
str.append(tmp).append(" months ");
else
str.append(tmp).append(" month ");
}
// Days
if( milisec >= 86400000 ){
if (milisec >= 86400000) {
tmp = milisec / 86400000;
milisec -= tmp * 86400000;
if( tmp > 1 )
if (tmp > 1)
str.append(tmp).append(" days ");
else
str.append(tmp).append(" day ");
}
// Hours
if( milisec >= 3600000 ){
if (milisec >= 3600000) {
tmp = milisec / 3600000;
milisec -= tmp * 3600000;
if( tmp > 1 )
if (tmp > 1)
str.append(tmp).append(" hours ");
else
str.append(tmp).append(" hour ");
}
// Minutes
if( milisec >= 60000 ){
if (milisec >= 60000) {
tmp = milisec / 60000;
milisec -= tmp * 60000;
str.append(tmp).append(" min ");
}
// sec
if( milisec >= 1000 ){
if (milisec >= 1000) {
tmp = milisec / 1000;
milisec -= tmp * 1000;
str.append(tmp).append(" sec ");
}
if( milisec > 0 ){
if (milisec > 0) {
str.append(milisec).append(" milisec ");
}
@ -123,7 +123,7 @@ public class StringUtil {
*
* @return a new String with the given length or longer if the number has more characters.
*/
public static String prefixInt(int number, int length){
public static String prefixInt(int number, int length) {
StringBuilder str = new StringBuilder().append(number).reverse();
while (str.length() < length)
str.append('0');
@ -137,7 +137,7 @@ public class StringUtil {
* @return a String containing all entries in the list with the specified delimiter in between entries
*/
@SafeVarargs
public static <T> String join(String delimiter, T... array){
public static <T> String join(String delimiter, T... array) {
return join(delimiter, Arrays.asList(array));
}
/**
@ -145,10 +145,10 @@ public class StringUtil {
* @param list a list of object that toString() will be called on
* @return a String containing all entries in the list with the specified delimiter in between entries
*/
public static String join(String delimiter, Iterable<?> list){
public static String join(String delimiter, Iterable<?> list) {
StringBuilder str = new StringBuilder();
Iterator<?> it = list.iterator();
if(it.hasNext()) {
if (it.hasNext()) {
str.append(it.next().toString());
while (it.hasNext()) {
str.append(delimiter).append(it.next().toString());
@ -164,30 +164,30 @@ public class StringUtil {
* @param trim is the char to trim
* @return a trimmed String
*/
public static String trim(String str, char trim){
if( str == null || str.isEmpty() )
public static String trim(String str, char trim) {
if (str == null || str.isEmpty())
return str;
int start=0, stop=str.length();
// The beginning
for(int i=0; i<str.length() ;i++){
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if(c <= ' ' || c == trim)
start = i+1;
if (c <= ' ' || c == trim)
start = i + 1;
else
break;
}
// 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);
if(c <= ' ' || c == trim)
if (c <= ' ' || c == trim)
stop = i;
else
break;
}
if(start >= str.length())
if (start >= str.length())
return "";
return str.substring(start, stop);
@ -198,12 +198,12 @@ public class StringUtil {
*
* @param str is the string to trim
*/
public static String trimQuotes(String str){
if( str == null )
public static String trimQuotes(String str) {
if (str == null)
return null;
str = str.trim();
if( str.length() >= 2 && str.charAt(0)=='\"' && str.charAt(str.length()-1)=='\"'){
if (str.length() >= 2 && str.charAt(0)=='\"' && str.charAt(str.length()-1)=='\"') {
str = str.substring(1, str.length()-1);
}
@ -216,10 +216,10 @@ public class StringUtil {
/**
* @return A string containing a specific amount of spaces
*/
public static String getSpaces(int i){
if(SPACES.size() <= i){ // Do we need to generate more spaces?
public static String getSpaces(int i) {
if (SPACES.size() <= i) { // Do we need to generate more spaces?
synchronized (SPACES) { // Make sure no one else updates the list at the same time
if(SPACES.size() <= i) { // Make sure the previous synchronized thread hasn't already generated strings
if (SPACES.size() <= i) { // Make sure the previous synchronized thread hasn't already generated strings
if (SPACES.isEmpty())
SPACES.add("");
for (int j = SPACES.size(); j <= i; j++) {
@ -242,7 +242,7 @@ public class StringUtil {
* @param delimiter a single character delimiter
* @return a List with all data between the delimiter
*/
public static List<String> split(String str, char delimiter){
public static List<String> split(String str, char delimiter) {
ArrayList<String> splitList = new ArrayList<>();
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.
*/
public Timer(long millisecond){
public Timer(long millisecond) {
this.period = millisecond;
reset();
}
@ -54,7 +54,7 @@ public class Timer {
*
* @return a reference of itself
*/
public Timer start(){
public Timer start() {
timestamp = System.currentTimeMillis();
return this;
}
@ -62,21 +62,21 @@ public class Timer {
/**
* Will reset the timer so that {@link #hasTimedOut()} returns true
*/
public void reset(){
public void reset() {
timestamp = -1;
}
/**
* @return true if the timer has timed out or has been reset, false if timer is running
*/
public boolean hasTimedOut(){
public boolean hasTimedOut() {
return timestamp + period < System.currentTimeMillis();
}
public String toString(){
public String toString() {
if (hasTimedOut())
return "Timed out";
else
return "Timeout in "+StringUtil.formatTimeToString((timestamp+period)-System.currentTimeMillis());
return "Timeout in " +StringUtil.formatTimeToString((timestamp+period)-System.currentTimeMillis());
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -27,17 +27,17 @@ package zutil.algo.search;
import zutil.algo.sort.sortable.SortableDataList;
/**
* This algorithm is a modified QuickSort
* This algorithm is a modified QuickSort
* to find the k smallest or biggest value
* http://en.wikipedia.org/wiki/Selection_algorithm
*
*
* @author Ziver
*
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class QuickSelect {
public static Object find(SortableDataList list, int k){
public static Object find(SortableDataList list, int k) {
return find(list, k, 0, list.size()-1);
}
@ -52,13 +52,13 @@ public class QuickSelect {
else
return select(list, k, pivotNewIndex+1, right)
*/
public static Object find(SortableDataList list, int k, int left, int right){
public static Object find(SortableDataList list, int k, int left, int right) {
// select a pivot
int pivot = right/2;
int newPivot = partition(list, left, right, pivot);
if(k == newPivot)
if (k == newPivot)
return list.get(k);
else if(k < newPivot)
else if (k < newPivot)
return find(list, k, left, newPivot-1);
else
return find(list, k, newPivot+1, right);
@ -76,14 +76,14 @@ public class QuickSelect {
swap list[right] and list[storeIndex] // Move pivot to its final place
return storeIndex
*/
private static int partition(SortableDataList list, int left, int right, int pivot){
private static int partition(SortableDataList list, int left, int right, int pivot) {
Object pivotValue = list.get(pivot);
list.swap(pivot, right);
int storeIndex = left;
for(int i=left; i<right ;i++){
if(list.compare(i, pivotValue) < 0){
for (int i=left; i<right; i++) {
if (list.compare(i, pivotValue) < 0) {
list.swap(storeIndex, i);
storeIndex = storeIndex+1;
storeIndex = storeIndex + 1;
}
}
list.swap(right, storeIndex);

View file

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

View file

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

View file

@ -29,7 +29,7 @@ import zutil.algo.sort.sortable.SortableDataList;
/**
* This class implements QuickSort to sort a array
*
*
* @author Ziver
*/
public class QuickSort{
@ -42,10 +42,10 @@ public class QuickSort{
*
* @param list is the list to sort.
*/
public static void sort(SortableDataList<?> list){
public static void sort(SortableDataList<?> list) {
sort(list, 0, list.size()-1, MIDDLE_PIVOT, true);
}
/**
* Sort the elements in ascending order using Quicksort.
*
@ -53,7 +53,7 @@ public class QuickSort{
* @param type is the type of pivot
* @param insert is if insertion sort will be used
*/
public static void sort(SortableDataList<?> list, int type, boolean insert){
public static void sort(SortableDataList<?> list, int type, boolean insert) {
sort(list, 0, list.size()-1, type, insert);
}
@ -66,43 +66,43 @@ public class QuickSort{
* @param start is the index to start from
* @param stop is the index to stop
* @param type is the type of pivot to use
*/
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void sort(SortableDataList list, int start, int stop, int type, boolean insertionSort){
if(stop-start <= 15 && insertionSort){
SimpleSort.insertionSort( list, start, stop);
public static void sort(SortableDataList list, int start, int stop, int type, boolean insertionSort) {
if (stop-start <= 15 && insertionSort) {
SimpleSort.insertionSort(list, start, stop);
}
int pivotIndex = pivot(list,start,stop,type);
Object pivot = list.get(pivotIndex);
int left=start, right=stop;
do{
while(list.compare(left, pivot) < 0){
while (list.compare(left, pivot) < 0) {
left++;
}
while(list.compare(right, pivot) > 0){
while (list.compare(right, pivot) > 0) {
right--;
}
if(left <= right){
if (left <= right) {
list.swap(left, right);
left++;
right--;
}
}while(left <= right);
}while (left <= right);
if(start < right){
if (start < right) {
sort(list, start, right, type, insertionSort);
}
if(left < stop){
if (left < stop) {
sort(list, left, stop, type, insertionSort);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static int pivot(SortableDataList<?> list, int start, int stop,int type){
switch(type){
private static int pivot(SortableDataList<?> list, int start, int stop,int type) {
switch(type) {
case RANDOM_PIVOT:
return start+(int)(Math.random()*(stop-start));
case MEDIAN_PIVOT:
@ -111,9 +111,9 @@ public class QuickSort{
(Comparable)list.get(list.size()/2),
(Comparable)list.get(list.size()-1)};
SimpleSort.insertionSort(new SortableComparableArray(i));
if(i[i.length/2].compareTo(list.get(start)) == 0)
if (i[i.length/2].compareTo(list.get(start)) == 0)
return start;
else if(i[i.length/2].compareTo(list.get(stop)) == 0)
else if (i[i.length/2].compareTo(list.get(stop)) == 0)
return stop;
else
return start+(stop-start)/2;

View file

@ -27,9 +27,9 @@ package zutil.algo.sort;
import zutil.algo.sort.sortable.SortableDataList;
/**
* This class randomizes the index of all the elements in
* This class randomizes the index of all the elements in
* the Sortable object
*
*
* @author Ziver
*/
public class Randomizer {
@ -38,11 +38,11 @@ public class Randomizer {
* Randomizes the index of all the elements
* @param list The list
*/
@SuppressWarnings({ "rawtypes" })
public static void sort(SortableDataList list){
@SuppressWarnings({"rawtypes"})
public static void sort(SortableDataList list) {
int size = list.size();
for(int i=0; i<size ;i++){
list.swap(i, (int)(Math.random()*size));
for (int i=0; i<size; i++) {
list.swap(i, (int) (Math.random() * size));
}
}
}

View file

@ -28,35 +28,35 @@ import zutil.algo.sort.sortable.SortableDataList;
/**
* A collection of simple and slow sorting algorithms.
*
*
* @author Ziver Koc
* @version 2006-10-31
*/
public class SimpleSort{
public class SimpleSort{
/**
* Sort the elements in ascending order using bubble sort
* Sort the elements in ascending order using bubble sort
* witch is the slowest of the algorithms.
* Complexity: O(n^2).
*
* @param list is the list to sort.
*/
public static void bubbleSort(SortableDataList<?> list){
public static void bubbleSort(SortableDataList<?> list) {
bubbleSort(list, 0, list.size());
}
}
/**
* Sort the elements in ascending order using bubble sort
* witch is the slowest of the algorithms.
* Complexity: O(n^2).
*
*
* @param list is an array of integers.
* @param start is the index to start from
* @param stop is the index to stop
*/
public static void bubbleSort(SortableDataList<?> list, int start, int stop){
for(int i=start; i<stop ;++i){
for(int j=stop-2; i<=j ;--j){
if(list.compare(j, j+1) > 0){
public static void bubbleSort(SortableDataList<?> list, int start, int stop) {
for (int i=start; i<stop; ++i) {
for (int j=stop-2; i<=j; --j) {
if (list.compare(j, j+1) > 0) {
list.swap(j, j+1);
}
}
@ -67,24 +67,24 @@ public class SimpleSort{
* Sort the elements in ascending order using selection sort
* witch in practice is 40% faster than bubble sort.
* Complexity: O(n^2).
*
*
* @param list is the list to sort.
*/
public static void selectionSort(SortableDataList<?> list){
public static void selectionSort(SortableDataList<?> list) {
selectionSort(list, 0, list.size());
}
}
/**
* Sort the elements in ascending order using selection sort
* witch in practice is 40% faster than bubble sort.
* Complexity: O(n^2).
*
*
* @param list is the list to sort.
* @param start is the index to start from
* @param stop is the index to stop
*/
public static void selectionSort(SortableDataList<?> list, int start, int stop){
public static void selectionSort(SortableDataList<?> list, int start, int stop) {
for (int i = start; i < stop - 1; i++) {
// find index m of the minimum element in v[i..n-1]
// find index m of the minimum element in v[i..n-1]
int m = i;
for (int j = i + 1; j < stop; j++) {
if (list.compare(j, m) < 0)
@ -102,24 +102,24 @@ public class SimpleSort{
*
* @param list is a list to sort.
*/
public static void insertionSort(SortableDataList<?> list){
public static void insertionSort(SortableDataList<?> list) {
insertionSort(list, 0, list.size());
}
}
/**
* Sort the elements in ascending order using insertion sort
* witch in practice is 5 times faster than bubble sort.
* Complexity: O(n^2).
*
*
* @param list is an array of integers.
* @param start is the index to start from
* @param stop is the index to stop
*/
public static void insertionSort(SortableDataList<?> list, int start, int stop){
for(int i=start; i<stop ;++i){
for(int j=i; start<j && list.compare(j-1, j)>0 ;--j){
public static void insertionSort(SortableDataList<?> list, int start, int stop) {
for (int i=start; i<stop; ++i) {
for (int j=i; start<j && list.compare(j-1, j)>0; --j) {
list.swap(j-1, j);
}
}
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -34,9 +34,9 @@ import java.util.List;
/**
* Adds the result of the query to a List.
*
*
* The handler will add the first column of every row to a list.
*
*
* @author Ziver
*/
public class ListSQLResult<T> implements SQLResultHandler<List<T>> {
@ -46,21 +46,21 @@ public class ListSQLResult<T> implements SQLResultHandler<List<T>> {
/**
* Creates a new List.
*/
public ListSQLResult(){
public ListSQLResult() {
this.list = new ArrayList<>();
}
/**
* Uses a existing list that items will be appended on.
*/
public ListSQLResult(List l){
public ListSQLResult(List l) {
this.list = l;
}
public List<T> handleQueryResult(Statement stmt, ResultSet result) throws SQLException{
while( result.next() )
while (result.next())
list.add((T)result.getObject(1));
return list;
}

View file

@ -33,10 +33,10 @@ import java.util.Properties;
/**
* Adds the result of the query to a Properties object,
*
* The handler sets the first column of the result as
*
* The handler sets the first column of the result as
* the key and the second column as the value
*
*
* @author Ziver
*/
public class PropertiesSQLResult implements SQLResultHandler<Properties> {
@ -46,14 +46,14 @@ public class PropertiesSQLResult implements SQLResultHandler<Properties> {
/**
* Creates a new Properties object to be filled
*/
public PropertiesSQLResult(){
public PropertiesSQLResult() {
this.prop = new Properties();
}
/**
* Adds data to a existing Properties object
*/
public PropertiesSQLResult(Properties p){
public PropertiesSQLResult(Properties p) {
this.prop = p;
}
@ -62,7 +62,7 @@ public class PropertiesSQLResult implements SQLResultHandler<Properties> {
* Is called to handle an result from an query.
*/
public Properties handleQueryResult(Statement stmt, ResultSet result) throws SQLException{
while( result.next() )
while (result.next())
prop.setProperty(result.getString(1), result.getString(2));
return prop;
}

View file

@ -32,7 +32,7 @@ import java.sql.Statement;
/**
* Returns the first column of the first row from the query
*
*
* @author Ziver
*/
public class SimpleSQLResult<T> implements SQLResultHandler<T> {
@ -44,7 +44,7 @@ public class SimpleSQLResult<T> implements SQLResultHandler<T> {
*/
@SuppressWarnings("unchecked")
public T handleQueryResult(Statement stmt, ResultSet result) throws SQLException{
if( result.next() )
if (result.next())
return (T) result.getObject(1);
return null;
}

View file

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

View file

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

View file

@ -53,11 +53,11 @@ public class RAWImageUtil {
*/
public static int getPeakValue(int[][][] data, int startX, int startY, int stopX, int stopY) {
int peak = 0;
for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){
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][3] > peak) peak = data[y][x][3];
for (int y=startY; y<stopY; y++) {
for (int x=startX; x<stopX; x++) {
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][3] > peak) peak = data[y][x][3];
}
}
return peak;
@ -74,8 +74,8 @@ public class RAWImageUtil {
* @param scale The scale to normalize the image by
*/
public static void normalize(int[][][] data, int startX, int startY, int stopX, int stopY, double scale) {
for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){
for (int y=startY; y<stopY; y++) {
for (int x=startX; x<stopX; x++) {
data[y][x][1] = (int)(data[y][x][1] * scale);
data[y][x][2] = (int)(data[y][x][2] * 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
*/
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 x=startX; x<stopX ;x++){
for (int y=startY; y<stopY; y++) {
for (int x=startX; x<stopX; x++) {
output[y][x][1] = (int)(data[y][x][1] * scale);
output[y][x][2] = (int)(data[y][x][2] * 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
* @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;
long accum = 0;
for(int y=startY; y <stopY ;y++){
for(int x=startX; x<stopX ;x++){
for (int y=startY; y <stopY; y++) {
for (int x=startX; x<stopX; x++) {
accum += data[y][x][1] * data[y][x][1];
accum += data[y][x][2] * data[y][x][2];
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 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){
for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){
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 x=startX; x<stopX; x++) {
data[y][x][1] *= scale;
data[y][x][2] *= scale;
data[y][x][3] *= scale;
@ -156,7 +156,7 @@ public class RAWImageUtil {
* @param data is the image data
* @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);
}
@ -170,7 +170,7 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop
* @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);
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
* @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];
for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){
for (int y=startY; y<stopY; y++) {
for (int x=startX; x<stopX; x++) {
mean[0] += data[y][x][1];
mean[1] += data[y][x][2];
mean[2] += data[y][x][3];
}
}
// calculate the mean value
int pixelCount = (stopY-startY)*(stopX-startX);
int pixelCount = (stopY - startY) * (stopX - startX);
mean[0] /= pixelCount;
mean[1] /= pixelCount;
mean[2] /= pixelCount;
@ -213,7 +213,7 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop
* @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);
}
@ -227,7 +227,7 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop
* @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});
}
@ -241,7 +241,7 @@ public class RAWImageUtil {
* @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
*/
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]});
}
@ -255,9 +255,9 @@ public class RAWImageUtil {
* @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
*/
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 x=startX; x<stopX ;x++){
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 x=startX; x<stopX; x++) {
data[y][x][1] += mean[0];
data[y][x][2] += mean[1];
data[y][x][3] += mean[2];
@ -275,7 +275,7 @@ public class RAWImageUtil {
* @param height The amount of pixels to copy
* @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);
}
@ -292,10 +292,12 @@ public class RAWImageUtil {
* @param height The amount of pixels to copy
* @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){
if(crop==null) crop = new int[width][height][4];
for(int y=0; y<width ;y++){
for(int x=0; x<height ;x++){
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];
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][1] = data[y+yCrop][x+xCrop][1];
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
* @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);
}
@ -325,7 +327,7 @@ public class RAWImageUtil {
* @param stopY is the y pixel of the image to stop
* @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];
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
* @return the dest array
*/
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 x=startX; x<stopX ;x++){
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 x=startX; x<stopX; x++) {
dest[y][x][0] = data[y][x][0];
dest[y][x][1] = data[y][x][1];
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 stopY is the y pixel of the image to stop
*/
public static void clip(int[][][] data, int startX, int startY, int stopX, int stopY){
for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){
public static void clip(int[][][] data, int startX, int startY, int stopX, int stopY) {
for (int y=startY; y<stopY; y++) {
for (int x=startX; x<stopX; x++) {
data[y][x][1] = clip(data[y][x][1]);
data[y][x][2] = clip(data[y][x][2]);
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
* is in the range 0-255
*/
public static int clip(int color){
if(color < 0)
public static int clip(int color) {
if (color < 0)
return 0;
else if(color > 255)
else if (color > 255)
return 255;
else
return color;

View file

@ -37,7 +37,7 @@ public class BlurFilter extends ImageFilterProcessor{
* Creates a blur effect on the image
* @param img The image to blur
*/
public BlurFilter(BufferedImage img){
public BlurFilter(BufferedImage img) {
this(img, 10);
}
@ -46,7 +46,7 @@ public class BlurFilter extends ImageFilterProcessor{
* @param img The image to blur
* @param blur The amount to blur
*/
public BlurFilter(BufferedImage img, int blur){
public BlurFilter(BufferedImage img, int blur) {
super(img);
blurValue = blur;
}
@ -59,17 +59,17 @@ public class BlurFilter extends ImageFilterProcessor{
int[][][] output = RAWImageUtil.copyArray(data);
//Perform the convolution one or more times in succession
int redSum, greenSum, blueSum, outputPeak;
for(int i=0; i<blurValue ;i++){
for (int i=0; i<blurValue; i++) {
//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));
for(int x=startX; x<stopX ;x++){
if(x == 0 || x == output[0].length-1 || y == 0 || y == output.length-1){
for (int x=startX; x<stopX; x++) {
if (x == 0 || x == output[0].length-1 || y == 0 || y == output.length-1) {
redSum = output[y][x][1] * 9;
greenSum = output[y][x][2] * 9;
blueSum = output[y][x][3] * 9;
}
else{
else {
redSum =
output[y - 1][x - 1][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
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;
}

View file

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

View file

@ -32,7 +32,7 @@ import java.awt.image.BufferedImage;
/**
* Applies an Convolution kernel to the specified image
*
*
* @author Ziver
*/
public class ConvolutionFilter extends ImageFilterProcessor{
@ -59,21 +59,21 @@ public class ConvolutionFilter extends ImageFilterProcessor{
@Override
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 xk_length = kernel[0].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));
for(int x=startX; x<stopX ;x++){
for (int x=startX; x<stopX; x++) {
tmpData[y][x][0] = data[y][x][0]; // alpha
for(int yk=0; yk<yk_length ;yk++){
for(int xk=0; xk<xk_length ;xk++){
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
for (int yk=0; yk<yk_length; yk++) {
for (int xk=0; xk<xk_length; xk++) {
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
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][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.
*/
public double[][] getKernel(){
public double[][] getKernel() {
return kernel;
}
@ -100,7 +100,7 @@ public class ConvolutionFilter extends ImageFilterProcessor{
*
* @return an special generated kernel
*/
protected double[][] generateKernel(){
protected double[][] generateKernel() {
return null;
}

View file

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

View file

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

View file

@ -28,7 +28,7 @@ import java.awt.image.BufferedImage;
/**
* The MedianFilter is used for noise reduction and things
*
*
* @author Ziver
*/
public class MeanBlurFilter extends ConvolutionFilter{
@ -54,12 +54,12 @@ public class MeanBlurFilter extends ConvolutionFilter{
this.windowSize = pixels;
}
protected double[][] generateKernel(){
protected double[][] generateKernel() {
double[][] kernel = new double[windowSize][windowSize];
double mean = 1.0/(windowSize*windowSize);
for(int y=0; y<windowSize ;y++){
for(int x=0; x<windowSize ;x++){
for (int y=0; y<windowSize; y++) {
for (int x=0; x<windowSize; x++) {
kernel[y][x] = mean;
}
}

View file

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

View file

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

View file

@ -31,7 +31,7 @@ import java.awt.image.BufferedImage;
/**
* Generates an image that contains the edges of the source image
*
*
* @author Ziver
* INFO: http://en.wikipedia.org/wiki/Sobel_operator
*/
@ -63,23 +63,23 @@ public class SobelEdgeDetectionFilter extends ImageFilterProcessor{
setProgress(66);
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);
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][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][3] = (int)Math.sqrt( xG[y][x][3]*xG[y][x][3] + yG[y][x][3]*yG[y][x][3] );
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][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][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][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][3] = Math.abs(xG[y][x][3]) + Math.abs(yG[y][x][3]);
*/
}
}
// gradient's direction:
// 0 = arctan( yG/xG )
// 0 = arctan(yG/xG)
return output;
}

View file

@ -39,7 +39,7 @@ public class SpotLightFilter extends ImageFilterProcessor{
* Sets up a default spotlight effect in
* the middle of the image
*/
public SpotLightFilter(BufferedImage img){
public SpotLightFilter(BufferedImage img) {
this(img, 100, -1, -1);
}
@ -47,7 +47,7 @@ public class SpotLightFilter extends ImageFilterProcessor{
* Sets up a custom spotlight
* @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);
}
@ -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 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);
radius = r;
xPos = x;
@ -66,24 +66,24 @@ public class SpotLightFilter extends ImageFilterProcessor{
@Override
public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) {
if(xPos < 0) xPos = data[0].length/2;
if(yPos < 0) yPos = data.length/2;
if (xPos < 0) xPos = data[0].length/2;
if (yPos < 0) yPos = data.length/2;
int[][][] output = new int[data.length][data[0].length][4];
double scale, dx, dy, distance;
for(int y=startY; y<stopY ;y++){
for (int y=startY; y<stopY; 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;
dy = y-yPos;
distance = Math.sqrt(dx*dx+dy*dy);
if(distance > radius){
if (distance > radius) {
scale = 0;
}
else{
else {
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
*/
public BufferedBoundaryInputStream(InputStream in){
public BufferedBoundaryInputStream(InputStream in) {
this(in, DEFAULT_BUF_SIZE);
}
@ -72,7 +72,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
* @param in is the InputStream that the buffer will use
* @param buf_size speifies the buffer size
*/
public BufferedBoundaryInputStream(InputStream in, int buf_size){
public BufferedBoundaryInputStream(InputStream in, int buf_size) {
super(in);
buffer = new byte[buf_size];
}
@ -85,7 +85,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
if (fillBuffer() < 0)
return -1;
if(isOnBoundary())
if (isOnBoundary())
return -1; // boundary
return buffer[buf_pos++];
}
@ -132,7 +132,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
/**
* @return if the current position in the buffer is a boundary
*/
public boolean isOnBoundary(){
public boolean isOnBoundary() {
return buf_bound_pos == buf_pos;
}
@ -163,7 +163,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
buf_pos = buf_end;
}
if (buf_bound_pos >= 0){ // is boundary in buffer?
if (buf_bound_pos >= 0) { // is boundary in buffer?
buf_pos += boundary.length;
findNextBoundary();
}
@ -181,7 +181,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
*/
public long skip(long n) throws IOException {
int leftover = available();
if(n > leftover){
if (n > leftover) {
buf_pos = buf_end;
return leftover;
}
@ -192,7 +192,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
/**
* Sets the boundary for the stream
*/
public void setBoundary(String b){
public void setBoundary(String b) {
this.boundary = b.getBytes();
findNextBoundary(); // redo the search with the new boundary
}
@ -200,7 +200,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
/**
* Sets the boundary for the stream
*/
public void setBoundary(byte[] b){
public void setBoundary(byte[] b) {
boundary = new byte[b.length];
System.arraycopy(b, 0, boundary, 0, b.length);
findNextBoundary(); // redo the search with the new boundary
@ -223,7 +223,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
/**
* @return true for BufferedBoundaryInputStream
*/
public boolean markSupported(){
public boolean markSupported() {
return true;
}
@ -267,7 +267,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
*/
private int fillBuffer() throws IOException {
// Do we need to fill the buffer
if(buf_pos < buf_end-boundary.length)
if (buf_pos < buf_end-boundary.length)
return 0;
int leftover = buf_end - buf_pos;
@ -288,7 +288,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
if (leftover > 0 && buf_pos != 0)
System.arraycopy(buffer, buf_pos, buffer, 0, leftover);
// Set new positions
if (buf_mark >= 0){
if (buf_mark >= 0) {
buf_pos = tmp_pos - buf_mark;
buf_mark = 0;
} else
@ -311,7 +311,7 @@ public class BufferedBoundaryInputStream extends FilterInputStream{
/**
* Searches for the nearest boundary from the current buffer position
*/
private void findNextBoundary(){
private void findNextBoundary() {
// No need to check for boundary if buffer is smaller than the boundary length
for (int i = buf_pos; i <= buf_end-boundary.length; i++) {
for (int b = 0; b < boundary.length; b++) {

View file

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

View file

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

View file

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

View file

@ -32,14 +32,14 @@ import java.io.InputStream;
* A simple Class that mirrors a InputStream but
* also has an additional Closeable objects that
* will be closed when the this object is closed.
*
*
* @author Ziver
*/
public class InputStreamCloser extends InputStream{
private Closeable[] c;
private InputStream in;
public InputStreamCloser(InputStream in, Closeable... c){
public InputStreamCloser(InputStream in, Closeable... c) {
this.c = c;
this.in = in;
}

View file

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

View file

@ -29,7 +29,7 @@ import java.nio.charset.StandardCharsets;
/**
* This class saves all the input data in to an StringBuffer
*
*
* @author Ziver
*
*/
@ -40,7 +40,7 @@ public class StringInputStream extends InputStream{
/**
* Creates an new instance of this class
*/
public StringInputStream(){
public StringInputStream() {
clear();
}
@ -55,7 +55,7 @@ public class StringInputStream extends InputStream{
* input stream without blocking by the next
* invocation of a method for this input stream.
*/
public int available(){
public int available() {
return buffer.length();
}
@ -63,32 +63,32 @@ public class StringInputStream extends InputStream{
/**
* Reads the next byte of data from the input stream.
*/
public int read(){
if(buffer.length() == 0)
public int read() {
if (buffer.length() == 0)
return -1;
int ret = buffer.charAt( 0 );
buffer.deleteCharAt( 0 );
int ret = buffer.charAt(0);
buffer.deleteCharAt(0);
return ret;
}
/**
* 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.
*/
public int read(byte[] b){
return read( b, 0, b.length );
public int read(byte[] b) {
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.
*/
public int read(byte[] b, int off, int len){
if(buffer.length() == 0)
public int read(byte[] b, int off, int len) {
if (buffer.length() == 0)
return -1;
if( buffer.length() < len ){
if (buffer.length() < len) {
len = buffer.length();
}
byte[] btmp = buffer.substring(0, len).getBytes(StandardCharsets.ISO_8859_1);
@ -96,48 +96,48 @@ public class StringInputStream extends InputStream{
buffer.delete(0, len);
return len;
}
/**
* Skips over and discards n bytes of data from this
* Skips over and discards n bytes of data from this
* input stream.
*
*
* @param n is the amount characters to skip
*/
public long skip(long n){
if( buffer.length() < n ){
public long skip(long n) {
if (buffer.length() < n) {
int len = buffer.length();
buffer.delete(0, len);
return len;
}
else{
else {
buffer.delete(0, (int) n);
return n;
}
}
/**
* Tests if this input stream supports the mark and
* Tests if this input stream supports the mark and
* reset methods.
*/
public boolean markSupported(){
public boolean markSupported() {
return false;
}
/**
* Closes this input stream and releases any system
* Closes this input stream and releases any system
* resources associated with the stream.
*/
public void close(){
public void close() {
clear();
}
public void clear(){
public void clear() {
buffer = new StringBuilder();
}
public void add( String data ){
buffer.append( data );
public void add(String data) {
buffer.append(data);
}
}

View file

@ -28,7 +28,7 @@ import java.io.OutputStream;
/**
* This class saves all the input data in to an StringBuffer
*
*
* @author Ziver
*
*/
@ -39,23 +39,23 @@ public class StringOutputStream extends OutputStream{
/**
* Creates an new instance of this class
*/
public StringOutputStream(){
public StringOutputStream() {
clear();
}
@Override
public void write(int b) {
buffer.append( b );
buffer.append(b);
}
@Override
public void write(byte[] b) {
buffer.append( new String(b) );
buffer.append(new String(b));
}
@Override
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
*/
public void clear(){
public void clear() {
buffer = new StringBuilder();
}

View file

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

View file

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

View file

@ -65,8 +65,8 @@ public class FileWatcher extends TimerTask{
* @param interval is the interval
*/
public FileWatcher(File file, int interval) throws FileNotFoundException{
if(file==null || !file.exists())
throw new FileNotFoundException("File not found: "+file);
if (file==null || !file.exists())
throw new FileNotFoundException("File not found: " +file);
this.file = file;
lastChanged = file.lastModified();
@ -74,7 +74,7 @@ public class FileWatcher extends TimerTask{
t.schedule(this, 0, interval);
}
public void setListener(FileChangeListener listener){
public void setListener(FileChangeListener listener) {
this.listener = listener;
}
@ -82,11 +82,11 @@ public class FileWatcher extends TimerTask{
public void run() {
if (lastChanged != file.lastModified()) {
lastChanged = file.lastModified();
if(listener != null){
if (listener != null) {
listener.fileChangedEvent(file);
}
else{
logger.fine("File was modified ("+file+") but no listeners was registered.");
else {
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 speedTime;
public FileUploadListener(){
id = ""+(int)(Math.random()*Integer.MAX_VALUE);
public FileUploadListener() {
id = "" +(int)(Math.random()*Integer.MAX_VALUE);
status = Status.Initializing;
filename = "";
message = "";
}
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;
this.bytes = pBytesRead;
this.item = pItems;
// Calculate Speed
if(speedTime == 0 || speedTime+1000 < System.currentTimeMillis() || pBytesRead == pContentLength){
if (speedTime == 0 || speedTime+1000 < System.currentTimeMillis() || pBytesRead == pContentLength) {
speedTime = System.currentTimeMillis();
speed = (int)(pBytesRead-speedRead);
speedRead = pBytesRead;
}
//try{Thread.sleep(10);}catch(Exception e){}
//try {Thread.sleep(10);} catch (Exception e) {}
// Set Status
status = Status.Uploading;
time = System.currentTimeMillis();
}
protected void setFileName(String filename){
protected void setFileName(String filename) {
this.filename = filename;
}
protected void setStatus(Status status){
protected void setStatus(Status status) {
this.status = status;
time = System.currentTimeMillis();
}
protected void setMessage(String msg){
protected void setMessage(String msg) {
this.message = msg;
}
public String getID(){
public String getID() {
return id;
}
@ -116,46 +116,46 @@ public class FileUploadListener implements ProgressListener{
return item;
}
public Status getStatus(){
public Status getStatus() {
return status;
}
protected long getTime(){
protected long getTime() {
return time;
}
protected String getMessage(){
protected String getMessage() {
return message;
}
/**
* @return bytes per second
*/
public int getSpeed(){
public int getSpeed() {
return speed;
}
/**
* Calculate the percent complete
*/
public int getPercentComplete(){
if(length == 0)
public int getPercentComplete() {
if (length == 0)
return 0;
return (int)((100 * bytes) / length);
}
public DataNode getJSON() {
DataNode node = new DataNode( DataType.Map );
DataNode node = new DataNode(DataType.Map);
node.set("id", id);
node.set("status", status.toString());
node.set("message", message.replaceAll("\"", "\\\"") );
node.set("message", message.replaceAll("\"", "\\\""));
node.set("filename", filename);
node.set("percent", getPercentComplete());
node.set("uploaded", StringUtil.formatByteSizeToString(bytes));
node.set("total", StringUtil.formatByteSizeToString(length));
node.set("speed", StringUtil.formatByteSizeToString(speed)+"/s");
node.set("speed", StringUtil.formatByteSizeToString(speed) + "/s");
return node;
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -39,11 +39,11 @@ public class Matrix {
*
* @return a new matrix with the result
*/
public static double[][] add(double[][] matrix, double num){
public static double[][] add(double[][] matrix, double num) {
double[][] result = new double[matrix.length][matrix[0].length];
for (int y=0; y < matrix.length; ++y) {
for (int x=0; x < matrix[y].length; ++x){
for (int x=0; x < matrix[y].length; ++x) {
result[y][x] = matrix[y][x] + num;
}
}
@ -56,11 +56,11 @@ public class Matrix {
*
* @return a new matrix with the result
*/
public static double[][] subtract(double[][] matrix, double num){
public static double[][] subtract(double[][] matrix, double num) {
double[][] result = new double[matrix.length][matrix[0].length];
for (int y=0; y < matrix.length; ++y) {
for (int x=0; x < matrix[y].length; ++x){
for (int x=0; x < matrix[y].length; ++x) {
result[y][x] = matrix[y][x] - num;
}
}
@ -73,11 +73,11 @@ public class Matrix {
*
* @return a new matrix with the result
*/
public static double[][] multiply(double[][] matrix, double num){
public static double[][] multiply(double[][] matrix, double num) {
double[][] result = new double[matrix.length][matrix[0].length];
for (int y=0; y < matrix.length; ++y) {
for (int x=0; x < matrix[y].length; ++x){
for (int x=0; x < matrix[y].length; ++x) {
result[y][x] = matrix[y][x] * num;
}
}
@ -90,7 +90,7 @@ public class Matrix {
*
* @return a new matrix with the result
*/
public static double[][] divide(double[][] matrix, double num){
public static double[][] divide(double[][] matrix, double num) {
return multiply(matrix, 1/num);
}
@ -176,7 +176,7 @@ public class Matrix {
*
* @return a new matrix with the result
*/
public static double[][] multiply(double[][] matrix, double[] vector){
public static double[][] multiply(double[][] matrix, double[] vector) {
vectorPreCheck(matrix, vector);
double[][] result = new double[matrix.length][matrix[0].length];
@ -194,7 +194,7 @@ public class Matrix {
*
* @return a new matrix with the result
*/
public static double[][] divide(double[][] matrix, double[] vector){
public static double[][] divide(double[][] matrix, double[] vector) {
vectorPreCheck(matrix, vector);
double[][] result = new double[matrix.length][matrix[0].length];
@ -255,7 +255,7 @@ public class Matrix {
*
* @return a new vector with subtracted elements
*/
public static double[] add(double[] vector1, double[] vector2){
public static double[] add(double[] vector1, double[] vector2) {
vectorPreCheck(vector1, vector2);
double[] result = new double[vector1.length];
@ -271,7 +271,7 @@ public class Matrix {
*
* @return a new matrix with subtracted elements
*/
public static double[][] add(double[][] matrix, double[] vector){
public static double[][] add(double[][] matrix, double[] vector) {
vectorPreCheck(matrix, vector);
double[][] result = new double[matrix.length][matrix[0].length];
@ -289,7 +289,7 @@ public class Matrix {
*
* @return a new vector with subtracted elements
*/
public static double[] subtract(double[] vector1, double[] vector2){
public static double[] subtract(double[] vector1, double[] vector2) {
vectorPreCheck(vector1, vector2);
double[] result = new double[vector1.length];
@ -305,7 +305,7 @@ public class Matrix {
*
* @return a new matrix with subtracted elements
*/
public static double[][] subtract(double[][] matrix, double[] vector){
public static double[][] subtract(double[][] matrix, double[] vector) {
vectorPreCheck(matrix, vector);
double[][] result = new double[matrix.length][matrix[0].length];
@ -324,7 +324,7 @@ public class Matrix {
*
* @return a new vector with the result
*/
public static double[] multiply(double[][] matrix, double[] vector){
public static double[] multiply(double[][] matrix, double[] vector) {
vectorPreCheck(matrix, vector);
double[] result = new double[matrix.length];
@ -342,12 +342,12 @@ public class Matrix {
*
* @return a new vector with the result
*/
public static double[] divide(double[][] matrix, double[] vector){
public static double[] divide(double[][] matrix, double[] vector) {
vectorPreCheck(matrix, vector);
double[] result = new double[matrix.length];
for (int y=0; y < matrix.length; ++y) {
for (int x=0; x < matrix[y].length; ++x){
for (int x=0; x < matrix[y].length; ++x) {
result[y] += matrix[y][x] / vector[x];
}
}
@ -389,13 +389,13 @@ public class Matrix {
*
* @return a new matrix with the result
*/
public static double[][] multiply(double[][] matrix1, double[][] matrix2){
public static double[][] multiply(double[][] matrix1, double[][] matrix2) {
matrixPreCheck(matrix1, matrix2);
double[][] result = new double[matrix1.length][matrix2[0].length];
for (int y=0; y < result.length; ++y) {
for (int x=0; x<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];
}
}
@ -406,11 +406,11 @@ public class 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];
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];
}
}
@ -444,7 +444,7 @@ public class Matrix {
/**
* @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];
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
* @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());
int index = ret.length()-1;
if(ret.length() < maxChar){
if (ret.length() < maxChar) {
ret.append('a');
}
else{
while(index >= 0){
else {
while (index >= 0) {
char c = increment(ret.charAt(index));
if(c != 0){
if(index == 0 && ret.length() < maxChar) ret.append('a');
if(index == 0) ret = new StringBuffer(""+c);
if (c != 0) {
if (index == 0 && ret.length() < maxChar) ret.append('a');
if (index == 0) ret = new StringBuffer("" +c);
else ret.setCharAt(index,c);
break;
}
else{
else {
//ret.setCharAt(index,'a');
ret.deleteCharAt(index);
index--;
@ -66,14 +66,14 @@ public class Tick {
* @param c is the char to increment
* @return the incremented char in lowercase 0 if it reached the end
*/
public static char increment(char c){
switch(Character.toLowerCase(c)){
public static char increment(char c) {
switch(Character.toLowerCase(c)) {
case 'z': return (char)134;
case (char)134: return (char)132;
case (char)132: return (char)148;
}
c = (char)(Character.toLowerCase(c) + 1);
if(isAlphabetic(c)){
if (isAlphabetic(c)) {
return c;
}
return 0;
@ -86,8 +86,8 @@ public class Tick {
* @param c is the char to check
* @return true if the char is a valid letter
*/
public static boolean isAlphabetic(char c){
switch(Character.toLowerCase(c)){
public static boolean isAlphabetic(char c) {
switch(Character.toLowerCase(c)) {
case 'a':
case 'b':
case 'c':

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -152,7 +152,7 @@ public class HttpClient implements AutoCloseable {
Socket conn;
if ("https".equals(url.getProtocol())) {
conn = SSLSocketFactory.getDefault().createSocket(url.getHost(), port);
((SSLSocket )conn).startHandshake();
((SSLSocket)conn).startHandshake();
} else {
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
*/
public HttpServer(int port){
public HttpServer(int port) {
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 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){
super( port, keyStore, keyStorePass );
public HttpServer(int port, File keyStore, String keyStorePass) {
super(port, keyStore, keyStorePass);
pages = new ConcurrentHashMap<>();
sessions = new ConcurrentHashMap<>();
@ -93,7 +93,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleWithFixedDelay(new SessionGarbageCollector(), 10000, SESSION_TTL / 2, TimeUnit.MILLISECONDS);
logger.info("HTTP"+(keyStore==null ? "" : "S")+" Server ready and listening to port: " + port);
logger.info("HTTP" + (keyStore==null ? "" : "S") + " Server ready and listening to port: " + port);
}
/**
@ -101,20 +101,20 @@ public class HttpServer extends ThreadedTCPNetworkServer{
* removes old sessions from the session HashMap
*/
private class SessionGarbageCollector implements Runnable {
public void run(){
public void run() {
Object[] keys = sessions.keySet().toArray();
int count = 0;
for(Object key : keys){
for (Object key : keys) {
Map<String,Object> session = sessions.get(key);
// Check if session is still valid
if(((Timer) session.get(SESSION_KEY_TTL)).hasTimedOut()){
if (((Timer) session.get(SESSION_KEY_TTL)).hasTimedOut()) {
sessions.remove(key);
++count;
}
}
if (count > 0)
logger.fine("Removed "+count+" old sessions");
logger.fine("Removed " + count + " old sessions");
}
}
@ -124,9 +124,9 @@ public class HttpServer extends ThreadedTCPNetworkServer{
* @param name The URL or name of the page
* @param page The page itself
*/
public void setPage(String name, HttpPage page){
if(name.charAt(0) != '/')
name = "/"+name;
public void setPage(String name, HttpPage page) {
if (name.charAt(0) != '/')
name = "/" +name;
pages.put(name, page);
}
@ -136,13 +136,13 @@ public class HttpServer extends ThreadedTCPNetworkServer{
*
* @param page The HttpPage that will be shown
*/
public void setDefaultPage(HttpPage page){
public void setDefaultPage(HttpPage page) {
defaultPage = page;
}
protected ThreadedTCPNetworkServerThread getThreadInstance( Socket s ){
protected ThreadedTCPNetworkServerThread getThreadInstance(Socket s) {
try {
return new HttpServerThread( s );
return new HttpServerThread(s);
} catch (IOException e) {
logger.log(Level.SEVERE, "Could not start new Thread", e);
}
@ -163,7 +163,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
this.socket = socket;
}
public void run(){
public void run() {
long time = System.currentTimeMillis();
HttpHeaderParser headerParser;
HttpHeader header = null;
@ -261,11 +261,11 @@ public class HttpServer extends ThreadedTCPNetworkServer{
}
}
finally {
try{
try {
out.close();
in.close();
socket.close();
} catch( Exception e ) {
} catch(Exception e) {
logger.log(Level.WARNING, "Could not close connection", e);
}
}
@ -275,9 +275,9 @@ public class HttpServer extends ThreadedTCPNetworkServer{
protected static void logRequest(HttpHeader header,
Map<String,Object> session,
long time){
long time) {
// Debug
if(logger.isLoggable(Level.FINEST) ){
if (logger.isLoggable(Level.FINEST)) {
StringBuilder buff = new StringBuilder();
buff.append("Received request: ").append(header==null ? null : header.getRequestURL());
buff.append(", (");
@ -288,10 +288,10 @@ public class HttpServer extends ThreadedTCPNetworkServer{
buff.append(", time: ").append(StringUtil.formatTimeToString(System.currentTimeMillis() - time));
logger.finer(buff.toString());
} else if(logger.isLoggable(Level.FINER)){
} else if (logger.isLoggable(Level.FINER)) {
logger.finer(
"Received request: " + (header==null ? null : header.getRequestURL())
+ ", time: "+ StringUtil.formatTimeToString(System.currentTimeMillis() - time));
+ ", time: " + StringUtil.formatTimeToString(System.currentTimeMillis() - time));
}
}
}

View file

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

View file

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

View file

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

View file

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

View file

@ -40,11 +40,11 @@ public class HttpRedirectPage implements HttpPage{
private String redirectUrl;
public HttpRedirectPage(String redirectUrl){
public HttpRedirectPage(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
public void setPermanentRedirect(boolean permanent){
public void setPermanentRedirect(boolean permanent) {
this.permanent = permanent;
}
@ -63,14 +63,14 @@ public class HttpRedirectPage implements HttpPage{
"<html lang='en-US'>\n" +
" <head>\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" +
" window.location.href = '"+ redirectUrl +"'\n" +
" window.location.href = '" + redirectUrl + "'\n" +
" </script>\n" +
" <title>Page Redirection</title>\n" +
" </head>\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" +
"</html>"
);

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