Fixed javadoc warnings

This commit is contained in:
Ziver Koc 2017-10-21 18:39:06 +02:00
parent 2db7cd2e49
commit 1cab6609c0
20 changed files with 1301 additions and 1305 deletions

View file

@ -43,6 +43,15 @@
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.36" level="project" /> <orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.36" level="project" />
<orderEntry type="library" name="Maven: org.xerial:sqlite-jdbc:3.8.11.2" level="project" /> <orderEntry type="library" name="Maven: org.xerial:sqlite-jdbc:3.8.11.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.12" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.12" level="project" />
<orderEntry type="library" name="Maven: com.carrotsearch:junit-benchmarks:0.7.2" level="project" />
<orderEntry type="library" name="Maven: commons-fileupload:commons-fileupload:1.2.1" level="project" />
<orderEntry type="library" name="Maven: commons-io:commons-io:2.5" level="project" />
<orderEntry type="library" name="Maven: dom4j:dom4j:1.6.1" level="project" />
<orderEntry type="library" name="Maven: xml-apis:xml-apis:1.0.b2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:javax.servlet-api:3.1.0" level="project" />
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.36" level="project" />
<orderEntry type="library" name="Maven: org.xerial:sqlite-jdbc:3.8.11.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.12" level="project" />
<orderEntry type="library" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" /> <orderEntry type="library" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
<orderEntry type="library" name="Maven: com.carrotsearch:junit-benchmarks:0.7.2" level="project" /> <orderEntry type="library" name="Maven: com.carrotsearch:junit-benchmarks:0.7.2" level="project" />
</component> </component>

View file

@ -99,8 +99,8 @@ public class Hasher {
/** /**
* Returns the MD5 hash of the given file * Returns the MD5 hash of the given file
* *
* @param object is the file to hash * @param file is the file to hash
* @return an String containing the hash * @return an String containing the hash
*/ */
public static String MD5(File file) throws IOException{ public static String MD5(File file) throws IOException{
try { try {

View file

@ -35,84 +35,84 @@ import java.util.List;
* @author Ziver * * @author Ziver *
*/ */
public class StringUtil { public class StringUtil {
public static final String[] sizes = new String[]{"YB", "ZB", "EB", "PB", "TB", "GB", "MB", "kB", "B"}; public static final String[] sizes = new String[]{"YB", "ZB", "EB", "PB", "TB", "GB", "MB", "kB", "B"};
/**
* Present a size (in bytes) as a human-readable value
*
* @param bytes size (in bytes)
* @return string
*/
public static String formatByteSizeToString(long bytes){
int total = sizes.length-1;
double value = bytes;
for(; value > 1024 ;total--) {
value /= 1024;
}
value = (double)( (int)(value*10) )/10; /**
return value+" "+sizes[total]; * Present a size (in bytes) as a human-readable value
} *
* @param bytes size (in bytes)
public static String formatTimeToString(long milisec){ * @return string
StringBuilder str = new StringBuilder(); */
long tmp = 0; public static String formatByteSizeToString(long bytes){
int total = sizes.length-1;
// Years double value = bytes;
if( milisec >= 31557032762.3361d ){
tmp = (long) (milisec / 31557032762.3361d); for(; value > 1024 ;total--) {
milisec -= tmp * 31557032762.3361d; value /= 1024;
if( tmp > 1 ) }
str.append(tmp).append(" years ");
else value = (double)( (int)(value*10) )/10;
str.append(tmp).append(" year "); return value+" "+sizes[total];
} }
// Months
if( milisec >= 2629743830l ){ public static String formatTimeToString(long milisec){
tmp = (long) (milisec / 2629743830l); StringBuilder str = new StringBuilder();
milisec -= tmp * 2629743830l; long tmp = 0;
if( tmp > 1 )
str.append(tmp).append(" months "); // Years
else if( milisec >= 31557032762.3361d ){
str.append(tmp).append(" month "); tmp = (long) (milisec / 31557032762.3361d);
} milisec -= tmp * 31557032762.3361d;
// Days if( tmp > 1 )
if( milisec >= 86400000 ){ str.append(tmp).append(" years ");
tmp = (long) (milisec / 86400000); else
milisec -= tmp * 86400000; str.append(tmp).append(" year ");
if( tmp > 1 ) }
str.append(tmp).append(" days "); // Months
else if( milisec >= 2629743830l ){
str.append(tmp).append(" day "); tmp = (long) (milisec / 2629743830l);
} milisec -= tmp * 2629743830l;
// Hours if( tmp > 1 )
if( milisec >= 3600000 ){ str.append(tmp).append(" months ");
tmp = (long) (milisec / 3600000); else
milisec -= tmp * 3600000; str.append(tmp).append(" month ");
if( tmp > 1 ) }
str.append(tmp).append(" hours "); // Days
else if( milisec >= 86400000 ){
str.append(tmp).append(" hour "); tmp = (long) (milisec / 86400000);
} milisec -= tmp * 86400000;
// Minutes if( tmp > 1 )
if( milisec >= 60000 ){ str.append(tmp).append(" days ");
tmp = (long) (milisec / 60000); else
milisec -= tmp * 60000; str.append(tmp).append(" day ");
str.append(tmp).append(" min "); }
} // Hours
// sec if( milisec >= 3600000 ){
if( milisec >= 1000 ){ tmp = (long) (milisec / 3600000);
tmp = (long) (milisec / 1000); milisec -= tmp * 3600000;
milisec -= tmp * 1000; if( tmp > 1 )
str.append(tmp).append(" sec "); str.append(tmp).append(" hours ");
} else
if( milisec > 0 ){ str.append(tmp).append(" hour ");
str.append(milisec).append(" milisec "); }
} // Minutes
if( milisec >= 60000 ){
return str.toString(); tmp = (long) (milisec / 60000);
} milisec -= tmp * 60000;
str.append(tmp).append(" min ");
}
// sec
if( milisec >= 1000 ){
tmp = (long) (milisec / 1000);
milisec -= tmp * 1000;
str.append(tmp).append(" sec ");
}
if( milisec > 0 ){
str.append(milisec).append(" milisec ");
}
return str.toString();
}
/** /**
* Generates a String where the number has been prefixed * Generates a String where the number has been prefixed
@ -130,20 +130,20 @@ public class StringUtil {
} }
/**
* @param delimiter a String delimiter that will be added between every entry in the list
* @param array a array 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 <T> String join(String delimiter, T... array){
return join(delimiter, Arrays.asList(array));
}
/** /**
* @param delimiter a String delimiter that will be added between every entry in the list * @param delimiter a String delimiter that will be added between every entry in the list
* @param list a list of object that toString() will be called on * @param array a array of object that toString() will be called on
* @return a String containing all entries in the list with the specified delimiter in between entries * @return a String containing all entries in the list with the specified delimiter in between entries
*/ */
public static String join(String delimiter, Iterable<?> list){ public static <T> String join(String delimiter, T... array){
return join(delimiter, Arrays.asList(array));
}
/**
* @param delimiter a String delimiter that will be added between every entry in the list
* @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){
StringBuilder str = new StringBuilder(); StringBuilder str = new StringBuilder();
Iterator<?> it = list.iterator(); Iterator<?> it = list.iterator();
if(it.hasNext()) { if(it.hasNext()) {
@ -155,74 +155,73 @@ public class StringUtil {
return str.toString(); return str.toString();
} }
/** /**
* Trims the given char and whitespace at the beginning and the end * Trims the given char and whitespace at the beginning and the end
* *
* @param str is the string to trim * @param str is the string to trim
* @param trim is the char to trim * @param trim is the char to trim
* @return a trimmed String * @return a trimmed String
*/ */
public static String trim(String str, char trim){ public static String trim(String str, char trim){
if( str == null || str.isEmpty() ) if( str == null || str.isEmpty() )
return str; return str;
int start=0, stop=str.length(); int start=0, stop=str.length();
// The beginning // The beginning
for(int i=0; i<str.length() ;i++){ for(int i=0; i<str.length() ;i++){
char c = str.charAt( i ); char c = str.charAt( i );
if( c <= ' ' || c == trim ) if( c <= ' ' || c == trim )
start = i+1; start = i+1;
else else
break; break;
} }
// The end // The end
for(int i=str.length()-1; i>start ;i--){ for(int i=str.length()-1; i>start ;i--){
char c = str.charAt( i ); char c = str.charAt( i );
if( c <= ' ' || c == trim ) if( c <= ' ' || c == trim )
stop = i; stop = i;
else else
break; break;
} }
if( start >= str.length() ) if( start >= str.length() )
return ""; return "";
//System.out.println("str: \""+str+"\" start: "+start+" stop: "+stop); //System.out.println("str: \""+str+"\" start: "+start+" stop: "+stop);
return str.substring(start, stop); return str.substring(start, stop);
} }
/** /**
* Trims the whitespace and quotes if the string starts and ends with one * Trims the whitespace and quotes if the string starts and ends with one
* *
* @param str is the string to trim * @param str is the string to trim
* @return */
*/ public static String trimQuotes(String str){
public static String trimQuotes(String str){ if( str == null )
if( str == null ) return null;
return null; str = str.trim();
str = str.trim(); if( str.length() >= 2 && str.charAt(0)=='\"' && str.charAt(str.length()-1)=='\"'){
if( str.length() >= 2 && str.charAt(0)=='\"' && str.charAt(str.length()-1)=='\"'){ str = str.substring(1, str.length()-1);
str = str.substring(1, str.length()-1); }
} return str;
return str; }
}
private static ArrayList<String> SPACES = new ArrayList<>(); private static ArrayList<String> SPACES = new ArrayList<>();
/** /**
* @return A string containing a specific amount of spaces * @return A string containing a specific amount of spaces
*/ */
public static String getSpaces(int i){ public static String getSpaces(int i){
if(SPACES.size() <= i){ // Do we need to generate more spaces? if(SPACES.size() <= i){ // Do we need to generate more spaces?
synchronized (SPACES) { // Make sure no one else updates the list at the same time synchronized (SPACES) { // Make sure no one else updates the list at the same time
if(SPACES.size() <= i) { // Make sure the previous synchronized thread hasn't already generated strings if(SPACES.size() <= i) { // Make sure the previous synchronized thread hasn't already generated strings
if (SPACES.isEmpty()) if (SPACES.isEmpty())
SPACES.add(""); SPACES.add("");
for (int j = SPACES.size(); j <= i; j++) { for (int j = SPACES.size(); j <= i; j++) {
SPACES.add(SPACES.get(j - 1) + " "); SPACES.add(SPACES.get(j - 1) + " ");
} }
} }
} }
} }
return SPACES.get(i); return SPACES.get(i);
} }
/** /**
@ -235,7 +234,7 @@ public class StringUtil {
* @param delimiter a single character delimiter * @param delimiter a single character delimiter
* @return a List with all data between the delimiter * @return a List with all data between the delimiter
*/ */
public static List<String> split(String str, char delimiter){ public static List<String> split(String str, char delimiter){
ArrayList<String> splitList = new ArrayList<>(); ArrayList<String> splitList = new ArrayList<>();
int from = 0, to = 0; int from = 0, to = 0;
while (to >= 0) { while (to >= 0) {

View file

@ -33,7 +33,7 @@ import java.math.BigInteger;
* The algorithm solves the discreet log equation x^2 = n mod p * The algorithm solves the discreet log equation x^2 = n mod p
* *
* @author Ziver * @author Ziver
* @see http://en.wikipedia.org/wiki/Shanks-Tonelli_algorithm * @see <a href="http://en.wikipedia.org/wiki/Shanks-Tonelli_algorithm">Wikipedia</a>
*/ */
public class ShanksTonelliAlgo { public class ShanksTonelliAlgo {
public static BigInteger calc(BigInteger n, BigInteger p){ public static BigInteger calc(BigInteger n, BigInteger p){

View file

@ -40,7 +40,7 @@ public class QuickSort{
/** /**
* Sort the elements in ascending order using Quicksort. * Sort the elements in ascending order using Quicksort.
* *
* @param A is the list to sort. * @param list is the list to sort.
*/ */
public static void sort(SortableDataList<?> list){ public static void sort(SortableDataList<?> list){
sort(list, 0, list.size()-1, MIDDLE_PIVOT, true); sort(list, 0, list.size()-1, MIDDLE_PIVOT, true);
@ -49,9 +49,9 @@ public class QuickSort{
/** /**
* Sort the elements in ascending order using Quicksort. * Sort the elements in ascending order using Quicksort.
* *
* @param A is the list to sort. * @param list is the list to sort.
* @param type is the type of pivot * @param type is the type of pivot
* @param insert is if insertion sort will be used * @param insert is if insertion sort will be used
*/ */
public static void sort(SortableDataList<?> list, int type, boolean insert){ public static void sort(SortableDataList<?> list, int type, boolean insert){
sort(list, 0, list.size()-1, type, insert); sort(list, 0, list.size()-1, type, insert);
@ -62,10 +62,10 @@ public class QuickSort{
* Reference: http://www.inf.fh-flensburg.de/lang/algorithmen/sortieren/quick/quicken.htm * Reference: http://www.inf.fh-flensburg.de/lang/algorithmen/sortieren/quick/quicken.htm
* Complexity: O(n*log n) normally, but O(n^2) if the pivot is bad * Complexity: O(n*log n) normally, but O(n^2) if the pivot is bad
* *
* @param A is the list to sort. * @param list is the list to sort.
* @param start is the index to start from * @param start is the index to start from
* @param stop is the index to stop * @param stop is the index to stop
* @param type is the type of pivot to use * @param type is the type of pivot to use
*/ */
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
public static void sort(SortableDataList list, int start, int stop, int type, boolean insertionSort){ public static void sort(SortableDataList list, int start, int stop, int type, boolean insertionSort){

View file

@ -39,50 +39,50 @@ public class SimpleSort{
* witch is the slowest of the algorithms. * witch is the slowest of the algorithms.
* Complexity: O(n^2). * Complexity: O(n^2).
* *
* @param A is the list to sort. * @param list is the list to sort.
*/ */
public static void bubbleSort(SortableDataList<?> list){ public static void bubbleSort(SortableDataList<?> list){
bubbleSort(list, 0, list.size()); bubbleSort(list, 0, list.size());
} }
/** /**
* 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. * witch is the slowest of the algorithms.
* Complexity: O(n^2). * Complexity: O(n^2).
* *
* @param A is an array of integers. * @param list is an array of integers.
* @param start is the index to start from * @param start is the index to start from
* @param stop is the index to stop * @param stop is the index to stop
*/ */
public static void bubbleSort(SortableDataList<?> list, int start, int stop){ public static void bubbleSort(SortableDataList<?> list, int start, int stop){
for(int i=start; i<stop ;++i){ for(int i=start; i<stop ;++i){
for(int j=stop-2; i<=j ;--j){ for(int j=stop-2; i<=j ;--j){
if(list.compare(j, j+1) > 0){ if(list.compare(j, j+1) > 0){
list.swap(j, j+1); list.swap(j, j+1);
} }
} }
} }
} }
/** /**
* Sort the elements in ascending order using selection sort * Sort the elements in ascending order using selection sort
* witch in practice is 40% faster than bubble sort. * witch in practice is 40% faster than bubble sort.
* Complexity: O(n^2). * Complexity: O(n^2).
* *
* @param list is the list to sort. * @param list is the list to sort.
*/ */
public static void selectionSort(SortableDataList<?> list){ public static void selectionSort(SortableDataList<?> list){
selectionSort(list, 0, list.size()); selectionSort(list, 0, list.size());
} }
/** /**
* Sort the elements in ascending order using selection sort * Sort the elements in ascending order using selection sort
* witch in practice is 40% faster than bubble sort. * witch in practice is 40% faster than bubble sort.
* Complexity: O(n^2). * Complexity: O(n^2).
* *
* @param list is the list to sort. * @param list is the list to sort.
* @param start is the index to start from * @param start is the index to start from
* @param stop is the index to stop * @param stop is the index to stop
*/ */
public static void selectionSort(SortableDataList<?> list, int start, int stop){ public static void selectionSort(SortableDataList<?> list, int start, int stop){
for (int i = start; i < stop - 1; i++) { for (int i = start; i < stop - 1; i++) {
// find index m of the minimum element in v[i..n-1] // find index m of the minimum element in v[i..n-1]
int m = i; int m = i;
@ -94,32 +94,32 @@ public class SimpleSort{
list.swap(i, m); list.swap(i, m);
} }
} }
/** /**
* Sort the elements in ascending order using insertion sort * Sort the elements in ascending order using insertion sort
* witch in practice is 5 times faster than bubble sort. * witch in practice is 5 times faster than bubble sort.
* Complexity: O(n^2). * Complexity: O(n^2).
* *
* @param A is a list to sort. * @param list is a list to sort.
*/ */
public static void insertionSort(SortableDataList<?> list){ public static void insertionSort(SortableDataList<?> list){
insertionSort(list, 0, list.size()); insertionSort(list, 0, list.size());
} }
/** /**
* Sort the elements in ascending order using insertion sort * Sort the elements in ascending order using insertion sort
* witch in practice is 5 times faster than bubble sort. * witch in practice is 5 times faster than bubble sort.
* Complexity: O(n^2). * Complexity: O(n^2).
* *
* @param A is an array of integers. * @param list is an array of integers.
* @param start is the index to start from * @param start is the index to start from
* @param stop is the index to stop * @param stop is the index to stop
*/ */
public static void insertionSort(SortableDataList<?> list, int start, int stop){ public static void insertionSort(SortableDataList<?> list, int start, int stop){
for(int i=start; i<stop ;++i){ for(int i=start; i<stop ;++i){
for(int j=i; start<j && list.compare(j-1, j)>0 ;--j){ for(int j=i; start<j && list.compare(j-1, j)>0 ;--j){
list.swap(j-1, j); list.swap(j-1, j);
} }
} }
} }
} }

View file

@ -25,60 +25,59 @@
package zutil.algo.sort.sortable; package zutil.algo.sort.sortable;
public interface SortableDataList<T>{ public interface SortableDataList<T>{
/** /**
* Returns a is a specific index i the list * Returns a is a specific index i the list
* *
* @param i is the index * @param i is the index
* @return */
*/ T get(int i);
public T get(int i);
/**
/** * Sets an Object in the specified index
* Sets an Object in the specified index *
* * @param i is the index
* @param i is the index * @param o is the Object
* @param o is the Object */
*/ void set(int i, T o);
public void set(int i, T o);
/**
/** * Returns the size of the list
* Returns the size of the list *
* * @return the size of the list
* @return the size of the list */
*/ int size();
public int size();
/**
/** * Swaps the given indexes
* Swaps the given indexes *
* * @param a is the first index
* @param a is the first index * @param b is the second index
* @param b is the second index */
*/ void swap(int a, int b);
public void swap(int a, int b);
/**
/** * Compares to indexes and returns:
* Compares to indexes and returns: * <0 if a<b ,
* <0 if a<b , * >0 if a>b ,
* >0 if a>b , * =0 if a=b
* =0 if a=b *
* * @param a is the first index to compare
* @param a is the first index to compare * @param b is the second index to compare
* @param b is the second index to compare * @return Look at the info
* @return Look at the info */
*/ int compare(int a, int b);
public int compare(int a, int b);
/**
/** * Compares to indexes and returns:
* Compares to indexes and returns: * <0 if a<b ,
* <0 if a<b , * >0 if a>b ,
* >0 if a>b , * =0 if a=b
* =0 if a=b *
* * @param a is the first index to compare
* @param a is the first index to compare * @param b is the second Object to compare
* @param b is the second Object to compare * @return Look at the info
* @return Look at the info */
*/ int compare(int a, T b);
public int compare(int a, T b);
} }

View file

@ -32,123 +32,123 @@ import java.awt.geom.Line2D;
import java.util.logging.Logger; import java.util.logging.Logger;
public abstract class AbstractChart extends JPanel{ public abstract class AbstractChart extends JPanel{
private static final Logger logger = LogUtil.getLogger(); private static final Logger logger = LogUtil.getLogger();
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** The offset from the borders of the panel in pixels */
public static final int PADDING = 20;
protected ChartData data;
protected int width;
protected int height;
protected Rectangle chartBound;
/** The offset from the borders of the panel in pixels */
public static final int PADDING = 20;
protected void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g; protected ChartData data;
protected int width;
Rectangle bound = drawScale( g2 ); protected int height;
drawChart( g2, bound ); protected Rectangle chartBound;
}
protected Rectangle drawScale(Graphics2D g2){
if( data == null ) protected void paintComponent(Graphics g){
return null; Graphics2D g2 = (Graphics2D)g;
// update values Rectangle bound = drawScale( g2 );
width = this.getWidth(); drawChart( g2, bound );
height = this.getHeight(); }
Rectangle bound = new Rectangle();
protected Rectangle drawScale(Graphics2D g2){
// Values if( data == null )
int stepLength = 7; return null;
/////// Temp values // update values
// Calculate Font sizes width = this.getWidth();
FontMetrics metric = g2.getFontMetrics(); height = this.getHeight();
int fontHeight = metric.getHeight(); Rectangle bound = new Rectangle();
int fontXWidth = 0;
int fontYWidth = 0; // Values
for( Point p : data.getPoints() ){ int stepLength = 7;
int length = 0;
String tmp = data.getXString( p.x ); /////// Temp values
if( tmp != null ) length = metric.stringWidth( tmp ); // Calculate Font sizes
else length = metric.stringWidth( ""+p.x ); FontMetrics metric = g2.getFontMetrics();
fontXWidth = Math.max(length, fontXWidth); int fontHeight = metric.getHeight();
int fontXWidth = 0;
tmp = data.getXString( p.y ); int fontYWidth = 0;
if( tmp != null ) length = metric.stringWidth( tmp ); for( Point p : data.getPoints() ){
else length = metric.stringWidth( ""+p.y ); int length = 0;
fontYWidth = Math.max(length, fontYWidth); String tmp = data.getXString( p.x );
} if( tmp != null ) length = metric.stringWidth( tmp );
// Calculate origo else length = metric.stringWidth( ""+p.x );
Point origo = new Point( PADDING+fontYWidth+stepLength, height-PADDING-fontHeight-stepLength ); fontXWidth = Math.max(length, fontXWidth);
bound.x = (int) (origo.getX()+1);
bound.y = PADDING; tmp = data.getXString( p.y );
bound.width = width-bound.x-PADDING; if( tmp != null ) length = metric.stringWidth( tmp );
bound.height = (int) (origo.getY()-PADDING-1); else length = metric.stringWidth( ""+p.y );
// Calculate Axis scales fontYWidth = Math.max(length, fontYWidth);
double xScale = (double)(Math.abs(data.getMaxX())+Math.abs(data.getMinX()))/bound.width; }
double yScale = (double)(Math.abs(data.getMaxY())+Math.abs(data.getMinY()))/bound.height; // Calculate origo
Point origo = new Point( PADDING+fontYWidth+stepLength, height-PADDING-fontHeight-stepLength );
bound.x = (int) (origo.getX()+1);
/////// Draw bound.y = PADDING;
// Y Axis bound.width = width-bound.x-PADDING;
g2.draw( new Line2D.Double( origo.getX(), PADDING, origo.getX(), origo.getY() )); bound.height = (int) (origo.getY()-PADDING-1);
// X Axis // Calculate Axis scales
g2.draw( new Line2D.Double( origo.getX(), origo.getY(), width-PADDING, origo.getY() )); double xScale = (double)(Math.abs(data.getMaxX())+Math.abs(data.getMinX()))/bound.width;
// Y Axis steps and labels double yScale = (double)(Math.abs(data.getMaxY())+Math.abs(data.getMinY()))/bound.height;
g2.draw( new Line2D.Double( origo.getX(), origo.getY(), origo.getX()-stepLength, origo.getY() ));
g2.draw( new Line2D.Double( origo.getX(), PADDING, origo.getX()-stepLength, PADDING ));
/////// Draw
// X Axis steps and labels // Y Axis
g2.draw( new Line2D.Double( width-PADDING, origo.getY(), width-PADDING, origo.getY()+stepLength )); g2.draw( new Line2D.Double( origo.getX(), PADDING, origo.getX(), origo.getY() ));
// X Axis
// DEBUG g2.draw( new Line2D.Double( origo.getX(), origo.getY(), width-PADDING, origo.getY() ));
/* // Y Axis steps and labels
g2.setColor(Color.red); g2.draw( new Line2D.Double( origo.getX(), origo.getY(), origo.getX()-stepLength, origo.getY() ));
g2.drawRect(bound.x, bound.y, bound.width, bound.height); g2.draw( new Line2D.Double( origo.getX(), PADDING, origo.getX()-stepLength, PADDING ));
*/
return bound; // X Axis steps and labels
} g2.draw( new Line2D.Double( width-PADDING, origo.getY(), width-PADDING, origo.getY()+stepLength ));
/** // DEBUG
* This method is called after the chart scale has been drawn. /*
* This method will draw the actual chart g2.setColor(Color.red);
* g2.drawRect(bound.x, bound.y, bound.width, bound.height);
* @param g is the Graphics object that will paint the chart */
* @param bound is the bounds of the chart, the drawing should not exceed this bound return bound;
*/ }
protected abstract void drawChart(Graphics2D g2, Rectangle bound);
/**
* This method is called after the chart scale has been drawn.
/** * This method will draw the actual chart
* Sets the data that will be drawn. *
* * @param g2 is the Graphics object that will paint the chart
* @param data is the data to draw * @param bound is the bounds of the chart, the drawing should not exceed this bound
*/ */
public void setChartData(ChartData data){ protected abstract void drawChart(Graphics2D g2, Rectangle bound);
this.data = data;
}
/**
/** * Sets the data that will be drawn.
* Converts a x value to ax pixel coordinate *
* * @param data is the data to draw
* @param x is the x data value */
* @return pixel coordinate, or 0 if the chart have not been drawn yet. public void setChartData(ChartData data){
*/ this.data = data;
protected int getXCoordinate(int x){ }
return 0;
} /**
* Converts a x value to ax pixel coordinate
/** *
* Converts a y value to a y pixel coordinate * @param x is the x data value
* * @return pixel coordinate, or 0 if the chart have not been drawn yet.
* @param y is the y data value */
* @return pixel coordinate, or 0 if the chart have not been drawn yet. protected int getXCoordinate(int x){
*/ return 0;
protected int getYCoordinate(int y){ }
return 0;
} /**
* Converts a y value to a y pixel coordinate
*
* @param y is the y data value
* @return pixel coordinate, or 0 if the chart have not been drawn yet.
*/
protected int getYCoordinate(int y){
return 0;
}
} }

View file

@ -13,7 +13,7 @@ import java.util.logging.Logger;
/** /**
* A intermediate class for loading Objects of generic Classes. * A intermediate class for loading Objects of generic Classes.
* The extending class must set the "superBean" parameter to true in {@link @DBBean.DBTable}. * The extending class must set the "superBean" parameter to true in {@link DBBean.DBTable}.
* The Object that is stored must use Configurator to define what fields that should be stored. * The Object that is stored must use Configurator to define what fields that should be stored.
* *
* This class needs to fields in DB: * This class needs to fields in DB:

View file

@ -30,367 +30,360 @@ package zutil.image;
* *
*/ */
public class RAWImageUtil { public class RAWImageUtil {
/**
* Returns the peek value in the image
*
* @param data The image data
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @param stopY is the y pixel of the image to stop
* @return The peak value of the image
*/
public static int getPeakValue(int[][][] data) {
return getPeakValue(data, 0, 0, data[0].length, data.length);
}
/**
* Returns the peek value in the image
*
* @param data The image data
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @param stopY is the y pixel of the image to stop
* @return The peak value of the image
*/
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];
}
}
return peak;
}
/** /**
* Normalizes the image data by the given scale * Returns the peek value in the image
* *
* @param data The image data * @param data The image data
* @param startX is the x pixel of the image to start from * @return The peak value of the image
* @param startY is the y pixel of the image to start from */
* @param stopX is the x pixel of the image to stop public static int getPeakValue(int[][][] data) {
* @param stopY is the y pixel of the image to stop return getPeakValue(data, 0, 0, data[0].length, data.length);
* @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++){
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);
}
}
}
/**
* Normalizes the image data by the given scale
*
* @param output The output data array
* @param data The image data
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @param stopY is the y pixel of the image to stop
* @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++){
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);
}
}
}
/** /**
* Returns the RMS value of the image * Returns the peek value in the image
* (The RMS value is a measure of the width of the color distribution.) *
* * @param data The image data
* @param data is the image data * @param startX is the x pixel of the image to start from
* @param startX is the x pixel of the image to start from * @param startY is the y pixel of the image to start from
* @param startY is the y pixel of the image to start from * @param stopX is the x pixel of the image to stop
* @param stopX is the x pixel of the image to stop * @param stopY is the y pixel of the image to stop
* @param stopY is the y pixel of the image to stop * @return the peak value of the image
* @return The RMS value for the image */
*/ public static int getPeakValue(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 peak = 0;
int pixelCount = 0; for(int y=startY; y<stopY ;y++){
long accum = 0; for(int x=startX; x<stopX ;x++){
for(int y=startY; y <stopY ;y++){ if(data[y][x][1] > peak) peak = data[y][x][1];
for(int x=startX; x<stopX ;x++){ if(data[y][x][2] > peak) peak = data[y][x][2];
accum += data[y][x][1] * data[y][x][1]; if(data[y][x][3] > peak) peak = data[y][x][3];
accum += data[y][x][2] * data[y][x][2]; }
accum += data[y][x][3] * data[y][x][3]; }
pixelCount += 3; return peak;
} }
}
int meanSquare = (int)(accum/pixelCount);
int rms = (int)(Math.sqrt(meanSquare));
return rms;
}
/** /**
* Multiplies the given image data by the given value * Normalizes the image data by the given scale
* *
* @param data is the image data * @param data the image data
* @param startX is the x pixel of the image to start from * @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from * @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop * @param stopX is the x pixel of the image to stop
* @param stopY is the y pixel of the image to stop * @param stopY is the y pixel of the image to stop
* @param scale is the number to scale the image color by * @param scale The scale to normalize the image by
*/ */
public static void scale(int[][][] data, int startX, int startY, int stopX, int stopY, double scale){ public static void normalize(int[][][] data, int startX, int startY, int stopX, int stopY, double scale) {
for(int y=startY; y<stopY ;y++){ for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){ for(int x=startX; x<stopX ;x++){
data[y][x][1] *= scale; data[y][x][1] = (int)(data[y][x][1] * scale);
data[y][x][2] *= scale; data[y][x][2] = (int)(data[y][x][2] * scale);
data[y][x][3] *= scale; data[y][x][3] = (int)(data[y][x][3] * scale);
} }
} }
} }
/** /**
* Returns the mean value of the given image data * Normalizes the image data by the given scale
* *
* @param data is the image data * @param output the output data array
* @return the mean value of the image * @param data the image data
*/ * @param startX is the x pixel of the image to start from
public static int getMeanValue(int[][][] data){ * @param startY is the y pixel of the image to start from
return getMeanValue(data, 0, 0, data[0].length, data.length); * @param stopX is the x pixel of the image to stop
} * @param stopY is the y pixel of the image to stop
* @param scale the scale to normalize the image by
/** */
* Returns the mean value of the given image data 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++){
* @param data is the image data for(int x=startX; x<stopX ;x++){
* @param startX is the x pixel of the image to start from output[y][x][1] = (int)(data[y][x][1] * scale);
* @param startY is the y pixel of the image to start from output[y][x][2] = (int)(data[y][x][2] * scale);
* @param stopX is the x pixel of the image to stop output[y][x][3] = (int)(data[y][x][3] * scale);
* @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){
int[] tmp = getMeanArray(data, startX, startY, stopX, stopY);
return (tmp[0] + tmp[1] + tmp[2])/3;
}
/**
* Returns an mean array containing a mean value for each color
*
* @param data is the image data
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @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){
int mean[] = new int[3];
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);
mean[0] /= pixelCount;
mean[1] /= pixelCount;
mean[2] /= pixelCount;
return mean;
}
/** /**
* removes the mean value from the image data * Returns the RMS value of the image
* * (The RMS value is a measure of the width of the color distribution.)
* @param data is the image data *
* @param startX is the x pixel of the image to start from * @param data is the image data
* @param startY is the y pixel of the image to start from * @param startX is the x pixel of the image to start from
* @param stopX is the x pixel of the image to stop * @param startY is the y pixel of the image to start from
* @param stopY is the y pixel of the image to stop * @param stopX is the x pixel of the image to stop
* @param mean is the mean value * @param stopY is the y pixel of the image to stop
*/ * @return the RMS value for the image
public static void remMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY, int mean){ */
addMeanValue(data, startX, startY, stopX, stopY, -mean); 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++){
* Adds the mean value to the image data for(int x=startX; x<stopX ;x++){
* accum += data[y][x][1] * data[y][x][1];
* @param data is the image data accum += data[y][x][2] * data[y][x][2];
* @param startX is the x pixel of the image to start from accum += data[y][x][3] * data[y][x][3];
* @param startY is the y pixel of the image to start from pixelCount += 3;
* @param stopX is the x pixel of the image to stop }
* @param stopY is the y pixel of the image to stop }
* @param mean is the mean value int meanSquare = (int)(accum/pixelCount);
*/ int rms = (int)(Math.sqrt(meanSquare));
public static void addMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY, int mean){ return rms;
addMeanArray(data, startX, startY, stopX, stopY, new int[]{mean, mean, mean}); }
}
/**
* removes an mean array containing a mean value for each color
*
* @param data is the image data
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @param stopY is the y pixel of the image to stop
* @param mean is an array of length 3 containing a mean value for each color RGB
*/
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]});
}
/**
* Adds an mean array containing a mean value for each color
*
* @param data is the image data
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @param stopY is the y pixel of the image to stop
* @param mean is an array of length 3 containing a mean value for each color RGB
*/
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];
}
}
}
/**
* Copies all the pixel data from the image to the new array
*
* @param data The data to copy
* @param xStart X start position on the source
* @param yStart Y start position on the source
* @param width The amount of pixels to copy
* @param hight 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 hight){
return crop(data, xStart, yStart, null, 0, 0, width, hight);
}
/**
* Copies all the pixel data from the image to the new array
*
* @param data The data to copy
* @param xData X start position in the source
* @param yData Y start position in the source
* @param crop The destination
* @param xCrop X start position in the destination
* @param yCrop Y start position in the destination
* @param width The amount of pixels to copy
* @param hight 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 hight){
if(crop==null) crop = new int[width][hight][4];
for(int y=0; y<width ;y++){
for(int x=0; x<hight ;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];
crop[y+yData][x+xData][3] = data[y+yCrop][x+xCrop][3];
}
}
return crop;
}
/**
* Copies the given array to a new one that it returns
*
* @param data The data to duplicate
* @return an copy of the array
*/
public static int[][][] copyArray(int[][][] data){
return copyArray(data, 0, 0, data[0].length, data.length);
}
/**
* Copies the given array to a new one that it returns
*
* @param data The data to duplicate
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @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){
int[][][] copy = new int[data.length][data[0].length][4];
return copyArray(data, copy, startX, startY, stopX, stopY);
}
/**
* Copies the given array to a new one that it returns
*
* @param data The data to duplicate
* @param dest is the array to copy the data to
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @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++){
dest[y][x][0] = data[y][x][0];
dest[y][x][1] = data[y][x][1];
dest[y][x][2] = data[y][x][2];
dest[y][x][3] = data[y][x][3];
}
}
return dest;
}
/** /**
* This method clips the values of the pixel so that they * Multiplies the given image data by the given value
* are in the range 0-255 *
* * @param data is the image data
* @param data The image data * @param startX is the x pixel of the image to start from
* @param startX is the x pixel of the image to start from * @param startY is the y pixel of the image to start from
* @param startY is the y pixel of the image to start from * @param stopX is the x pixel of the image to stop
* @param stopX is the x pixel of the image to stop * @param stopY is the y pixel of the image to stop
* @param stopY is the y pixel of the image to stop * @param scale is the number to scale the image color by
*/ */
public static void clip(int[][][] data, int startX, int startY, int stopX, int stopY){ public static void scale(int[][][] data, int startX, int startY, int stopX, int stopY, double scale){
for(int y=startY; y<stopY ;y++){ for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){ for(int x=startX; x<stopX ;x++){
data[y][x][1] = clip(data[y][x][1]); data[y][x][1] *= scale;
data[y][x][2] = clip(data[y][x][2]); data[y][x][2] *= scale;
data[y][x][3] = clip(data[y][x][3]); data[y][x][3] *= scale;
} }
} }
} }
/** /**
* This method clips the values of a color so that it * Returns the mean value of the given image data
* is in the range 0-255 *
* * @param data is the image data
* @param color * @return the mean value of the image
* @return */
*/ public static int getMeanValue(int[][][] data){
public static int clip(int color){ return getMeanValue(data, 0, 0, data[0].length, data.length);
if(color < 0) }
return 0;
else if(color > 255) /**
return 255; * Returns the mean value of the given image data
else *
return color; * @param data is the image data
} * @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @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){
int[] tmp = getMeanArray(data, startX, startY, stopX, stopY);
return (tmp[0] + tmp[1] + tmp[2])/3;
}
/**
* Returns an mean array containing a mean value for each color
*
* @param data is the image data
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @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){
int mean[] = new int[3];
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);
mean[0] /= pixelCount;
mean[1] /= pixelCount;
mean[2] /= pixelCount;
return mean;
}
/**
* removes the mean value from the image data
*
* @param data is the image data
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @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){
addMeanValue(data, startX, startY, stopX, stopY, -mean);
}
/**
* Adds the mean value to the image data
*
* @param data is the image data
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @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){
addMeanArray(data, startX, startY, stopX, stopY, new int[]{mean, mean, mean});
}
/**
* removes an mean array containing a mean value for each color
*
* @param data is the image data
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @param stopY is the y pixel of the image to stop
* @param mean is an array of length 3 containing a mean value for each color RGB
*/
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]});
}
/**
* Adds an mean array containing a mean value for each color
*
* @param data is the image data
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @param stopY is the y pixel of the image to stop
* @param mean is an array of length 3 containing a mean value for each color RGB
*/
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];
}
}
}
/**
* Copies all the pixel data from the image to the new array
*
* @param data The data to copy
* @param xStart X start position on the source
* @param yStart Y start position on the source
* @param width The amount of pixels to copy
* @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){
return crop(data, xStart, yStart, null, 0, 0, width, height);
}
/**
* Copies all the pixel data from the image to the new array
*
* @param data The data to copy
* @param xData X start position in the source
* @param yData Y start position in the source
* @param crop The destination
* @param xCrop X start position in the destination
* @param yCrop Y start position in the destination
* @param width The amount of pixels to copy
* @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++){
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];
crop[y+yData][x+xData][3] = data[y+yCrop][x+xCrop][3];
}
}
return crop;
}
/**
* Copies the given array to a new one that it returns
*
* @param data The data to duplicate
* @return an copy of the array
*/
public static int[][][] copyArray(int[][][] data){
return copyArray(data, 0, 0, data[0].length, data.length);
}
/**
* Copies the given array to a new one that it returns
*
* @param data The data to duplicate
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @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){
int[][][] copy = new int[data.length][data[0].length][4];
return copyArray(data, copy, startX, startY, stopX, stopY);
}
/**
* Copies the given array to a new one that it returns
*
* @param data The data to duplicate
* @param dest is the array to copy the data to
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @param stopX is the x pixel of the image to stop
* @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++){
dest[y][x][0] = data[y][x][0];
dest[y][x][1] = data[y][x][1];
dest[y][x][2] = data[y][x][2];
dest[y][x][3] = data[y][x][3];
}
}
return dest;
}
/**
* This method clips the values of the pixel so that they
* are in the range 0-255
*
* @param data The image data
* @param startX is the x pixel of the image to start from
* @param startY is the y pixel of the image to start from
* @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++){
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]);
}
}
}
/**
* 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)
return 0;
else if(color > 255)
return 255;
else
return color;
}
} }

View file

@ -33,49 +33,49 @@ import java.io.OutputStream;
* *
*/ */
public class StringOutputStream extends OutputStream{ public class StringOutputStream extends OutputStream{
// The buffer // The buffer
protected StringBuilder buffer; protected StringBuilder buffer;
/**
* Creates an new instance of this class
*/
public StringOutputStream(){
clear();
}
@Override
public void write(int b) {
buffer.append( b );
}
@Override /**
public void write(byte[] b) { * Creates an new instance of this class
buffer.append( new String(b) ); */
} public StringOutputStream(){
clear();
@Override }
public void write(byte[] b, int off, int len) {
buffer.append( new String(b, off, len) );
}
/** @Override
* Same as {@link OutputStream:clear()} public void write(int b) {
*/ buffer.append( b );
@Override }
public void close() {}
@Override
/** public void write(byte[] b) {
* Clears the String buffer buffer.append( new String(b) );
*/ }
public void clear(){
buffer = new StringBuilder(); @Override
} public void write(byte[] b, int off, int len) {
buffer.append( new String(b, off, len) );
/** }
* @return the String with the data
*/ /**
@Override * Same as {@link OutputStream#close()}
public String toString() { */
return buffer.toString(); @Override
} public void close() {}
/**
* Clears the String buffer
*/
public void clear(){
buffer = new StringBuilder();
}
/**
* @return the String with the data
*/
@Override
public String toString() {
return buffer.toString();
}
} }

View file

@ -273,7 +273,6 @@ public class FileUtil {
* *
* @param file is the name of the file * @param file is the name of the file
* @param ext is the new extension, without the dot * @param ext is the new extension, without the dot
* @return
*/ */
public static String replaceExtension(String file, String ext) { public static String replaceExtension(String file, String ext) {
if( file == null ) if( file == null )

View file

@ -50,217 +50,217 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
/** /**
* <XMP> * <pre>
* Example web.xml: * Example web.xml:
* <servlet> * &lt;servlet&gt;
* <servlet-name>Upload</servlet-name> * &lt;servlet-name&gt;Upload&lt;/servlet-name&gt;
* <servlet-class>zall.util.AjaxFileUpload</servlet-class> * &lt;servlet-class&gt;zall.util.AjaxFileUpload&lt;/servlet-class&gt;
* <init-param> * &lt;init-param&gt;
* <param-name>JAVASCRIPT</param-name> * &lt;param-name&gt;JAVASCRIPT&lt;/param-name&gt;
* <param-value>{FILE_PATH}</param-value> * &lt;param-value&gt;{FILE_PATH}&lt;/param-value&gt;
* </init-param> * &lt;/init-param&gt;
* <init-param> * &lt;init-param&gt;
* <param-name>TEMP_PATH</param-name> * &lt;param-name&gt;TEMP_PATH&lt;/param-name&gt;
* <param-value>SYSTEM|SERVLET|{PATH}</param-value> * &lt;param-value&gt;SYSTEM|SERVLET|{PATH}&lt;/param-value&gt;
* </init-param> * &lt;/init-param&gt;
* </servlet> * &lt;/servlet&gt;
* *
* *
* HTML Header: * HTML Header:
* <script type='text/javascript' src='{PATH_TO_SERVLET}?js'></script> * &lt;script type='text/javascript' src='{PATH_TO_SERVLET}?js'&gt;&lt;/script&gt;
* *
* *
* HTML Body: * HTML Body:
* <FORM id="AjaxFileUpload"> * &lt;FORM id="AjaxFileUpload"&gt;
* <input type="file" multiple name="file" /> * &lt;input type="file" multiple name="file" /&gt;
* </FORM> * &lt;/FORM&gt;
* <UL id="UploadQueue"></UL> * &lt;UL id="UploadQueue"&gt;&lt;/UL&gt;
* *
* *
* </XMP> * </pre>
* @author Ziver * @author Ziver
* *
*/ */
public abstract class AjaxFileUpload extends HttpServlet { public abstract class AjaxFileUpload extends HttpServlet {
private static final Logger logger = LogUtil.getLogger(); private static final Logger logger = LogUtil.getLogger();
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public static final String SESSION_FILEUPLOAD_LISTENER = "FILEUPLOAD_LISTENER"; public static final String SESSION_FILEUPLOAD_LISTENER = "FILEUPLOAD_LISTENER";
public static final String JAVASCRIPT_FILE = "zutil/jee/upload/AjaxFileUpload.js"; public static final String JAVASCRIPT_FILE = "zutil/jee/upload/AjaxFileUpload.js";
public static File TEMPFILE_PATH = null; public static File TEMPFILE_PATH = null;
public static String JAVASCRIPT = ""; public static String JAVASCRIPT = "";
public static HashSet<String> ALLOWED_EXTENSIONS = new HashSet<String>(); public static HashSet<String> ALLOWED_EXTENSIONS = new HashSet<String>();
public void init(ServletConfig config) throws ServletException { public void init(ServletConfig config) throws ServletException {
super.init(config); super.init(config);
try { try {
// Read the javascript file to memory // Read the javascript file to memory
String path = JAVASCRIPT_FILE; String path = JAVASCRIPT_FILE;
if(config.getInitParameter("JAVASCRIPT_FILE") != null) if(config.getInitParameter("JAVASCRIPT_FILE") != null)
path = config.getInitParameter("JAVASCRIPT_FILE"); path = config.getInitParameter("JAVASCRIPT_FILE");
JAVASCRIPT = FileUtil.getContent( FileUtil.findURL(path) ); JAVASCRIPT = FileUtil.getContent( FileUtil.findURL(path) );
// Read temp dir // Read temp dir
if(config.getInitParameter("TEMP_PATH") != null){ if(config.getInitParameter("TEMP_PATH") != null){
if( config.getInitParameter("TEMP_PATH").equalsIgnoreCase("SYSTEM") ) if( config.getInitParameter("TEMP_PATH").equalsIgnoreCase("SYSTEM") )
TEMPFILE_PATH = new File( System.getProperty("java.io.tmpdir") ); TEMPFILE_PATH = new File( System.getProperty("java.io.tmpdir") );
else if( config.getInitParameter("TEMP_PATH").equalsIgnoreCase("SERVLET") ) else if( config.getInitParameter("TEMP_PATH").equalsIgnoreCase("SERVLET") )
TEMPFILE_PATH = (File) config.getServletContext().getAttribute("javax.servlet.context.tempdir"); TEMPFILE_PATH = (File) config.getServletContext().getAttribute("javax.servlet.context.tempdir");
else else
TEMPFILE_PATH = new File( config.getInitParameter("TEMP_PATH") ); TEMPFILE_PATH = new File( config.getInitParameter("TEMP_PATH") );
} }
// Read allowed file types
if(config.getInitParameter("ALLOWED_EXTENSIONS") != null){
String[] tmp = config.getInitParameter("ALLOWED_EXTENSIONS").split(",");
StringBuilder ext_log = new StringBuilder("Allowed extensions: ");
for( String ext : tmp ){
ALLOWED_EXTENSIONS.add(ext.trim().toLowerCase());
ext_log.append(ext).append(", ");
}
logger.info( ext_log.toString() );
}
} catch (IOException e) { // Read allowed file types
e.printStackTrace(); if(config.getInitParameter("ALLOWED_EXTENSIONS") != null){
} String[] tmp = config.getInitParameter("ALLOWED_EXTENSIONS").split(",");
} StringBuilder ext_log = new StringBuilder("Allowed extensions: ");
for( String ext : tmp ){
ALLOWED_EXTENSIONS.add(ext.trim().toLowerCase());
ext_log.append(ext).append(", ");
}
logger.info( ext_log.toString() );
}
@SuppressWarnings("unchecked") } catch (IOException e) {
protected void doGet(HttpServletRequest request, e.printStackTrace();
HttpServletResponse response) throws ServletException, IOException { }
PrintWriter out = response.getWriter(); }
if(request.getParameter("js") != null){
response.setContentType("application/x-javascript");
String tmp = JAVASCRIPT;
tmp = JAVASCRIPT.replaceAll("\\{SERVLET_URL\\}", request.getRequestURI());
tmp = tmp.replaceAll("\\{BGUPLOAD\\}", "false");
tmp = tmp.replaceAll("\\{PROGHTML\\}", getProgressHTML());
out.print(tmp);
return;
}
response.setContentType("application/json"); @SuppressWarnings("unchecked")
HttpSession session = request.getSession(); protected void doGet(HttpServletRequest request,
LinkedList<FileUploadListener> list = HttpServletResponse response) throws ServletException, IOException {
(LinkedList<FileUploadListener>)session.getAttribute(SESSION_FILEUPLOAD_LISTENER); PrintWriter out = response.getWriter();
if (list == null) { if(request.getParameter("js") != null){
out.println("[]"); response.setContentType("application/x-javascript");
return; String tmp = JAVASCRIPT;
} tmp = JAVASCRIPT.replaceAll("\\{SERVLET_URL\\}", request.getRequestURI());
tmp = tmp.replaceAll("\\{BGUPLOAD\\}", "false");
tmp = tmp.replaceAll("\\{PROGHTML\\}", getProgressHTML());
out.print(tmp);
return;
}
// Generate JSON response.setContentType("application/json");
DataNode root = new DataNode( DataType.List ); HttpSession session = request.getSession();
Iterator<FileUploadListener> it = list.iterator(); LinkedList<FileUploadListener> list =
while( it.hasNext() ) { (LinkedList<FileUploadListener>)session.getAttribute(SESSION_FILEUPLOAD_LISTENER);
FileUploadListener listener = it.next(); if (list == null) {
if( listener.getStatus() == Status.Done || listener.getStatus() == Status.Error ){ out.println("[]");
if( listener.getTime() + 5000 < System.currentTimeMillis() ){ return;
it.remove(); }
}
}
root.add( listener.getJSON() );
}
// Write to the user // Generate JSON
JSONWriter json_out = new JSONWriter( out ); DataNode root = new DataNode( DataType.List );
json_out.write(root); Iterator<FileUploadListener> it = list.iterator();
} while( it.hasNext() ) {
FileUploadListener listener = it.next();
if( listener.getStatus() == Status.Done || listener.getStatus() == Status.Error ){
if( listener.getTime() + 5000 < System.currentTimeMillis() ){
it.remove();
}
}
root.add( listener.getJSON() );
}
// Write to the user
JSONWriter json_out = new JSONWriter( out );
json_out.write(root);
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { HttpServletResponse response) throws ServletException, IOException {
FileUploadListener listener = new FileUploadListener();
try {
// Initiate list and HashMap that will contain the data
HashMap<String,String> fields = new HashMap<String,String>();
ArrayList<FileItem> files = new ArrayList<FileItem>();
// Add the listener to the session
HttpSession session = request.getSession();
LinkedList<FileUploadListener> list =
(LinkedList<FileUploadListener>)session.getAttribute(SESSION_FILEUPLOAD_LISTENER);
if(list == null){
list = new LinkedList<FileUploadListener>();
session.setAttribute(SESSION_FILEUPLOAD_LISTENER, list);
}
list.add(listener);
// Create a factory for disk-based file items FileUploadListener listener = new FileUploadListener();
DiskFileItemFactory factory = new DiskFileItemFactory(); try {
if(TEMPFILE_PATH != null) // Initiate list and HashMap that will contain the data
factory.setRepository( TEMPFILE_PATH ); HashMap<String,String> fields = new HashMap<String,String>();
// Create a new file upload handler ArrayList<FileItem> files = new ArrayList<FileItem>();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener( listener );
// Set overall request size constraint
//upload.setSizeMax(yourMaxRequestSize);
// Parse the request // Add the listener to the session
FileItemIterator it = upload.getItemIterator( request ); HttpSession session = request.getSession();
while( it.hasNext() ) { LinkedList<FileUploadListener> list =
FileItemStream item = it.next(); (LinkedList<FileUploadListener>)session.getAttribute(SESSION_FILEUPLOAD_LISTENER);
// Is the file type allowed? if(list == null){
if( !item.isFormField() && !ALLOWED_EXTENSIONS.contains( FileUtil.getFileExtension(item.getName()).toLowerCase() )){ list = new LinkedList<FileUploadListener>();
String msg = "Filetype '"+FileUtil.getFileExtension(item.getName())+"' is not allowed!"; session.setAttribute(SESSION_FILEUPLOAD_LISTENER, list);
logger.warning( msg ); }
listener.setStatus(Status.Error); list.add(listener);
listener.setFileName( item.getName() );
listener.setMessage( msg );
return;
}
listener.setFileName( item.getName() );
FileItem fileItem = factory.createItem(item.getFieldName(),
item.getContentType(), item.isFormField(), item.getName());
// Read the file data
Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
if (fileItem instanceof FileItemHeadersSupport) {
final FileItemHeaders fih = item.getHeaders();
((FileItemHeadersSupport) fileItem).setHeaders(fih);
}
//Handle the item
if(fileItem.isFormField()){
fields.put( fileItem.getFieldName(), fileItem.getString());
}
else{
files.add( fileItem );
logger.info("Recieved file: "+fileItem.getName()+" ("+StringUtil.formatByteSizeToString(fileItem.getSize())+")");
}
}
// Process the upload
listener.setStatus( Status.Processing );
doUpload( request, response, fields, files );
// Done
listener.setStatus( Status.Done );
} catch (Exception e) {
logger.log(Level.SEVERE, null, e);
listener.setStatus(Status.Error);
listener.setFileName("");
listener.setMessage( e.getMessage() );
}
}
/** // Create a factory for disk-based file items
* @return the HTML for the progress bar. Special ID's: DiskFileItemFactory factory = new DiskFileItemFactory();
* <br>-filename = String if(TEMPFILE_PATH != null)
* <br>-progress = percent factory.setRepository( TEMPFILE_PATH );
* <br>-total = String // Create a new file upload handler
* <br>-uploaded = String ServletFileUpload upload = new ServletFileUpload(factory);
* <br>-status = String (Uploading, Initializing etc) upload.setProgressListener( listener );
* <br>-speed = String // Set overall request size constraint
*/ //upload.setSizeMax(yourMaxRequestSize);
public abstract String getProgressHTML();
/** // Parse the request
* Handle the uppload FileItemIterator it = upload.getItemIterator( request );
* @throws ServletException while( it.hasNext() ) {
*/ FileItemStream item = it.next();
public abstract void doUpload(HttpServletRequest request, HttpServletResponse response, // Is the file type allowed?
Map<String,String> fields, List<FileItem> files) throws ServletException; if( !item.isFormField() && !ALLOWED_EXTENSIONS.contains( FileUtil.getFileExtension(item.getName()).toLowerCase() )){
String msg = "Filetype '"+FileUtil.getFileExtension(item.getName())+"' is not allowed!";
logger.warning( msg );
listener.setStatus(Status.Error);
listener.setFileName( item.getName() );
listener.setMessage( msg );
return;
}
listener.setFileName( item.getName() );
FileItem fileItem = factory.createItem(item.getFieldName(),
item.getContentType(), item.isFormField(), item.getName());
// Read the file data
Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
if (fileItem instanceof FileItemHeadersSupport) {
final FileItemHeaders fih = item.getHeaders();
((FileItemHeadersSupport) fileItem).setHeaders(fih);
}
//Handle the item
if(fileItem.isFormField()){
fields.put( fileItem.getFieldName(), fileItem.getString());
}
else{
files.add( fileItem );
logger.info("Recieved file: "+fileItem.getName()+" ("+StringUtil.formatByteSizeToString(fileItem.getSize())+")");
}
}
// Process the upload
listener.setStatus( Status.Processing );
doUpload( request, response, fields, files );
// Done
listener.setStatus( Status.Done );
} catch (Exception e) {
logger.log(Level.SEVERE, null, e);
listener.setStatus(Status.Error);
listener.setFileName("");
listener.setMessage( e.getMessage() );
}
}
/**
* @return the HTML for the progress bar. Special ID's:
* <br>-filename = String
* <br>-progress = percent
* <br>-total = String
* <br>-uploaded = String
* <br>-status = String (Uploading, Initializing etc)
* <br>-speed = String
*/
public abstract String getProgressHTML();
/**
* Handle the uppload
* @throws ServletException
*/
public abstract void doUpload(HttpServletRequest request, HttpServletResponse response,
Map<String,String> fields, List<FileItem> files) throws ServletException;
} }

View file

@ -27,45 +27,43 @@ package zutil.net.nio.worker.chat;
import zutil.net.nio.message.Message; import zutil.net.nio.message.Message;
public class ChatMessage implements Message { public class ChatMessage implements Message {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public static enum ChatMessageType {REGISTER, UNREGISTER, MESSAGE}; public static enum ChatMessageType {REGISTER, UNREGISTER, MESSAGE};
public ChatMessageType type; public ChatMessageType type;
public String msg; public String msg;
public String room; public String room;
/** /**
* Registers the user to the main chat * Registers the user to the main chat
* */
* @param name Name of user public ChatMessage(){
*/ this("", "", ChatMessageType.REGISTER);
public ChatMessage(){ }
this("", "", ChatMessageType.REGISTER);
} /**
* Registers the user to the given room
/** *
* Registers the user to the given room * @param room The room to register to
* */
* @param room The room to register to public ChatMessage(String room){
*/ this("", room, ChatMessageType.REGISTER);
public ChatMessage(String room){ }
this("", room, ChatMessageType.REGISTER);
} /**
* Sends a message to the given room
/** *
* Sends a message to the given room * @param msg The message
* * @param room The room
* @param msg The message */
* @param room The room public ChatMessage(String msg, String room){
*/ this(msg, room, ChatMessageType.MESSAGE);
public ChatMessage(String msg, String room){ }
this(msg, room, ChatMessageType.MESSAGE);
} public ChatMessage(String msg, String room, ChatMessageType type){
this.msg = msg;
public ChatMessage(String msg, String room, ChatMessageType type){ this.room = room;
this.msg = msg; this.type = type;
this.room = room; }
this.type = type;
}
} }

View file

@ -38,22 +38,22 @@ import java.lang.annotation.Target;
* private static class Test implements WSInterface{ * private static class Test implements WSInterface{
* public Test(){} * public Test(){}
* *
* @WSDocumentation("blabla") * &#64;WSDocumentation("blabla")
* @WSDLParamDocumentation("olle = a variable?") * &#64;WSDLParamDocumentation("olle = a variable?")
* public void pubZ( * public void pubZ(
* @WSParamName("olle") int lol) * &#64;WSParamName("olle") int lol)
* throws Exception{ * throws Exception{
* .... * ....
* } * }
* *
* @WSReturnName("param") * &#64;WSReturnName("param")
* public String pubA( * public String pubA(
* @WSParamName(value="lol", optional=true) String lol) * &#64;WSParamName(value="lol", optional=true) String lol)
* throws Exception{ * throws Exception{
* .... * ....
* } * }
* *
* @WSIgnore() * &#64;WSIgnore()
* public void privaZ(....){ * public void privaZ(....){
* ... * ...
* } * }
@ -63,79 +63,78 @@ import java.lang.annotation.Target;
* @author Ziver * @author Ziver
*/ */
public interface WSInterface { public interface WSInterface {
/** /**
* Annotation that assigns a name to an parameters * Annotation that assigns a name to an parameters
* in an method. * in an method.
* *
* @author Ziver * @author Ziver
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER) @Target(ElementType.PARAMETER)
public @interface WSParamName { @interface WSParamName {
String value(); String value();
boolean optional() default false; boolean optional() default false;
} }
/**
* Annotation that assigns a name to the return value
* in an method.
*
* @author Ziver
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface WSReturnName {
String value();
}
/**
* Skipp publication of the given method
*
* @author Ziver
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface WSIgnore { }
/**
* Method or Parameter comments for the WSDL.
* These comments are put in the message part of the WSDL
*
* @author Ziver
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface WSDocumentation{
String value();
}
/** /**
* Parameter comments for the WSDL. * Annotation that assigns a name to the return value
* These comments are put in the message part of the WSDL * in an method.
* *
* @author Ziver * @author Ziver
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface WSParamDocumentation{ @Target(ElementType.METHOD)
String value(); @interface WSReturnName {
} String value();
}
/**
* This method will be used in the header. /**
* * Skipp publication of the given method
* @author Ziver *
*/ * @author Ziver
@Retention(RetentionPolicy.RUNTIME) */
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME)
public @interface WSHeader { } @Target(ElementType.METHOD)
public @interface WSIgnore { }
/**
* Specifies the name space for method. /**
* * Method or Parameter comments for the WSDL.
* @author Ziver * These comments are put in the message part of the WSDL
*/ *
@Retention(RetentionPolicy.RUNTIME) * @author Ziver
//@Target(ElementType.TYPE) */
public @interface WSNamespace { @Retention(RetentionPolicy.RUNTIME)
String value(); @interface WSDocumentation{
} String value();
}
/**
* Parameter comments for the WSDL.
* These comments are put in the message part of the WSDL
*
* @author Ziver
*/
@Retention(RetentionPolicy.RUNTIME)
@interface WSParamDocumentation{
String value();
}
/**
* This method will be used in the header.
*
* @author Ziver
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface WSHeader { }
/**
* Specifies the name space for method.
*
* @author Ziver
*/
@Retention(RetentionPolicy.RUNTIME)
@interface WSNamespace {
String value();
}
} }

View file

@ -38,9 +38,9 @@ import java.lang.reflect.Field;
* *
* <pre> * <pre>
* private static class TestObject implements WSReturnObject{ * private static class TestObject implements WSReturnObject{
* @WSValueName("name") * &#64;WSValueName("name")
* public String name; * public String name;
* @WSValueName("lastname") * &#64;WSValueName("lastname")
* public String lastname; * public String lastname;
* *
* public TestObject(String n, String l){ * public TestObject(String n, String l){

View file

@ -41,7 +41,6 @@ public class BEncodedParser {
* Returns the representation of the data in the BEncoded string * Returns the representation of the data in the BEncoded string
* *
* @param data is the data to be decoded * @param data is the data to be decoded
* @return
*/ */
public static DataNode read(String data) throws ParseException { public static DataNode read(String data) throws ParseException {
return decode_BEncoded(new MutableInt(), new StringBuilder(data)); return decode_BEncoded(new MutableInt(), new StringBuilder(data));

View file

@ -38,163 +38,164 @@ import java.util.Set;
* *
*/ */
public class BloomFilter<T extends Serializable> implements Set<T>, Serializable{ public class BloomFilter<T extends Serializable> implements Set<T>, Serializable{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private BitSet bits;
private int content_size;
private int optimal_size;
private int k;
private BitSet bits;
/** private int content_size;
* Creates a bloom filter private int optimal_size;
* private int k;
* @param size The amount of bits in the filter
* @param expected_data_count The estimated amount of data to
* be inserted(a bigger number is better than a smaller)
*/
public BloomFilter(int size, int expected_data_count){
bits = new BitSet(size);
k = (int)((size/expected_data_count) * Math.log(2));
content_size = 0;
optimal_size = expected_data_count;
}
/**
* @param e A Serializable object
* @return If the optimal size has been reached
*/
public boolean add(T e) {
try {
content_size++;
int hash = 0;
for(int i=0; i<k ;i++){
hash = Hasher.MurmurHash(e, hash);
hash = Math.abs(hash) % bits.size();
bits.set(hash, true);
}
} catch (Exception e1) {
e1.printStackTrace();
}
return isFull();
}
/** /**
* Adds a collection to the bloom filter * Creates a bloom filter
* *
* @return If the optimal size has been reached * @param size The amount of bits in the filter
*/ * @param expected_data_count The estimated amount of data to
public boolean addAll(Collection<? extends T> c) { * be inserted(a bigger number is better than a smaller)
for(T t : c){ */
add(t); public BloomFilter(int size, int expected_data_count){
} bits = new BitSet(size);
return isFull(); k = (int)((size/expected_data_count) * Math.log(2));
} content_size = 0;
optimal_size = expected_data_count;
}
/** /**
* @return clears the filter * @param e A Serializable object
*/ * @return If the optimal size has been reached
public void clear() { */
content_size = 0; public boolean add(T e) {
bits.clear(); try {
} content_size++;
int hash = 0;
for(int i=0; i<k ;i++){
hash = Hasher.MurmurHash(e, hash);
hash = Math.abs(hash) % bits.size();
bits.set(hash, true);
}
} catch (Exception e1) {
e1.printStackTrace();
}
return isFull();
}
/** /**
* @param o is the Serializable object to search for * Adds a collection to the bloom filter
* @return If the object contains in the filter or *
* false if the Object is not Serializable * @return If the optimal size has been reached
*/ */
public boolean contains(Object o) { public boolean addAll(Collection<? extends T> c) {
try { for(T t : c){
if(!(o instanceof Serializable))return false; add(t);
int hash = 0; }
for(int i=0; i<k ;i++){ return isFull();
hash = Hasher.MurmurHash((Serializable)o, hash); }
hash = Math.abs(hash) % bits.size();
if(!bits.get(hash))
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/** /**
* Checks if the whole collection contains in the filter * Clears the filter
* */
* @param c The collection public void clear() {
*/ content_size = 0;
public boolean containsAll(Collection<?> c) { bits.clear();
for(Object o : c){ }
if(!contains(o)) return false;
}
return true;
}
/** /**
* @return If the bloom filter is empty * @param o is the Serializable object to search for
*/ * @return If the object contains in the filter or
public boolean isEmpty() { * false if the Object is not Serializable
return content_size == 0; */
} public boolean contains(Object o) {
try {
/** if(!(o instanceof Serializable))return false;
* @return If the optimal size has been reached int hash = 0;
*/ for(int i=0; i<k ;i++){
public boolean isFull() { hash = Hasher.MurmurHash((Serializable)o, hash);
return content_size > optimal_size; hash = Math.abs(hash) % bits.size();
} if(!bits.get(hash))
return false;
/** }
* @return The number of data added } catch (Exception e) {
*/ e.printStackTrace();
public int size() { }
return content_size;
}
/**
* @return The false positive probability of the current state of the filter
*/
public double falsePosetiveProbability(){
return Math.pow(0.6185, bits.size()/content_size);
}
/**
* Set the hash count. Should be set before adding elements
* or the already added elements will be lost
*
* @param k The hash count
*/
public void setHashCount(int k){
this.k = k;
}
//*********************************************************************
//*********************************************************************
public Object[] toArray() {
throw new UnsupportedOperationException();
}
@SuppressWarnings("hiding") return true;
public <T> T[] toArray(T[] a) { }
throw new UnsupportedOperationException();
}
public Iterator<T> iterator() { /**
throw new UnsupportedOperationException(); * Checks if the whole collection contains in the filter
} *
* @param c The collection
*/
public boolean containsAll(Collection<?> c) {
for(Object o : c){
if(!contains(o)) return false;
}
return true;
}
public boolean remove(Object o) { /**
throw new UnsupportedOperationException(); * @return If the bloom filter is empty
} */
public boolean isEmpty() {
return content_size == 0;
}
public boolean removeAll(Collection<?> c) { /**
throw new UnsupportedOperationException(); * @return If the optimal size has been reached
} */
public boolean isFull() {
public boolean retainAll(Collection<?> c) { return content_size > optimal_size;
throw new UnsupportedOperationException(); }
}
/**
* @return The number of data added
*/
public int size() {
return content_size;
}
/**
* @return The false positive probability of the current state of the filter
*/
public double falsePositiveProbability(){
return Math.pow(0.6185, bits.size()/content_size);
}
/**
* Set the hash count. Should be set before adding elements
* or the already added elements will be lost
*
* @param k The hash count
*/
public void setHashCount(int k){
this.k = k;
}
//*********************************************************************
//*********************************************************************
public Object[] toArray() {
throw new UnsupportedOperationException();
}
@SuppressWarnings("hiding")
public <T> T[] toArray(T[] a) {
throw new UnsupportedOperationException();
}
public Iterator<T> iterator() {
throw new UnsupportedOperationException();
}
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
} }

View file

@ -36,87 +36,87 @@ import java.awt.event.FocusListener;
import java.util.HashMap; import java.util.HashMap;
public class WizardActionHandler implements ActionListener, FocusListener, ListSelectionListener{ public class WizardActionHandler implements ActionListener, FocusListener, ListSelectionListener{
private HashMap<String, Object> values; private HashMap<String, Object> values;
public WizardActionHandler(HashMap<String, Object> values){ public WizardActionHandler(HashMap<String, Object> values){
this.values = values; this.values = values;
} }
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
event(e); event(e);
} }
public void focusGained(FocusEvent e) { public void focusGained(FocusEvent e) {
event(e); event(e);
} }
public void focusLost(FocusEvent e) { public void focusLost(FocusEvent e) {
event(e); event(e);
} }
public void event(AWTEvent e){ public void event(AWTEvent e){
if(e.getSource() instanceof Component) if(e.getSource() instanceof Component)
registerValue( (Component)e.getSource() ); registerValue( (Component)e.getSource() );
} }
public void valueChanged(ListSelectionEvent e) { public void valueChanged(ListSelectionEvent e) {
if(e.getSource() instanceof Component) if(e.getSource() instanceof Component)
registerValue( (Component)e.getSource() ); registerValue( (Component)e.getSource() );
} }
public void registerListener(Component c){ public void registerListener(Component c){
/** /**
* JToggleButton * JToggleButton
* JCheckBox * JCheckBox
* JRadioButton * JRadioButton
*/ */
if(c instanceof JToggleButton){ if(c instanceof JToggleButton){
JToggleButton o = (JToggleButton) c; JToggleButton o = (JToggleButton) c;
o.addActionListener( this ); o.addActionListener( this );
} }
/** /**
* JEditorPane * JEditorPane
* JTextArea * JTextArea
* JTextField * JTextField
*/ */
else if(c instanceof JTextComponent){ else if(c instanceof JTextComponent){
JTextComponent o = (JTextComponent) c; JTextComponent o = (JTextComponent) c;
o.addFocusListener( this ); o.addFocusListener( this );
} }
/** /**
* JList * JList
*/ */
else if(c instanceof JList){ else if(c instanceof JList){
JList<?> o = (JList<?>) c; JList<?> o = (JList<?>) c;
o.addListSelectionListener( this ); o.addListSelectionListener( this );
} }
} }
/** /**
* Registers the state of the event source * Registers the state of the event source
* @param e is the event * @param c is the event
*/ */
public void registerValue(Component c) { public void registerValue(Component c) {
/** /**
* JToggleButton * JToggleButton
* JCheckBox * JCheckBox
* JRadioButton * JRadioButton
*/ */
if(c instanceof JToggleButton){ if(c instanceof JToggleButton){
JToggleButton o = (JToggleButton) c; JToggleButton o = (JToggleButton) c;
values.put( o.getName() , o.isSelected() ); values.put( o.getName() , o.isSelected() );
} }
/** /**
* JEditorPane * JEditorPane
* JTextArea * JTextArea
* JTextField * JTextField
*/ */
else if(c instanceof JTextComponent){ else if(c instanceof JTextComponent){
JTextComponent o = (JTextComponent) c; JTextComponent o = (JTextComponent) c;
values.put( o.getName() , o.getText() ); values.put( o.getName() , o.getText() );
} }
/** /**
* JList * JList
*/ */
else if(c instanceof JList){ else if(c instanceof JList){
JList<?> o = (JList<?>) c; JList<?> o = (JList<?>) c;
values.put( o.getName() , o.getSelectedValue() ); values.put( o.getName() , o.getSelectedValue() );
} }
} }
} }

View file

@ -70,7 +70,7 @@ public class BloomFilterTest extends TestCase {
falsePositives++; falsePositives++;
} }
} }
double expectedFP = bf.falsePosetiveProbability(); double expectedFP = bf.falsePositiveProbability();
double actualFP = (double) falsePositives / (double) addCount; double actualFP = (double) falsePositives / (double) addCount;
System.out.println("Got " + falsePositives System.out.println("Got " + falsePositives
+ " false positives out of " + addCount + " added items, rate = " + " false positives out of " + addCount + " added items, rate = "