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 * Present a size (in bytes) as a human-readable value
* *
* @param bytes size (in bytes) * @param bytes size (in bytes)
* @return string * @return string
*/ */
public static String formatByteSizeToString(long bytes){ public static String formatByteSizeToString(long bytes){
int total = sizes.length-1; int total = sizes.length-1;
double value = bytes; double value = bytes;
for(; value > 1024 ;total--) { for(; value > 1024 ;total--) {
value /= 1024; value /= 1024;
} }
value = (double)( (int)(value*10) )/10; value = (double)( (int)(value*10) )/10;
return value+" "+sizes[total]; return value+" "+sizes[total];
} }
public static String formatTimeToString(long milisec){ public static String formatTimeToString(long milisec){
StringBuilder str = new StringBuilder(); StringBuilder str = new StringBuilder();
long tmp = 0; long tmp = 0;
// Years // Years
if( milisec >= 31557032762.3361d ){ if( milisec >= 31557032762.3361d ){
tmp = (long) (milisec / 31557032762.3361d); tmp = (long) (milisec / 31557032762.3361d);
milisec -= tmp * 31557032762.3361d; milisec -= tmp * 31557032762.3361d;
if( tmp > 1 ) if( tmp > 1 )
str.append(tmp).append(" years "); str.append(tmp).append(" years ");
else else
str.append(tmp).append(" year "); str.append(tmp).append(" year ");
} }
// Months // Months
if( milisec >= 2629743830l ){ if( milisec >= 2629743830l ){
tmp = (long) (milisec / 2629743830l); tmp = (long) (milisec / 2629743830l);
milisec -= tmp * 2629743830l; milisec -= tmp * 2629743830l;
if( tmp > 1 ) if( tmp > 1 )
str.append(tmp).append(" months "); str.append(tmp).append(" months ");
else else
str.append(tmp).append(" month "); str.append(tmp).append(" month ");
} }
// Days // Days
if( milisec >= 86400000 ){ if( milisec >= 86400000 ){
tmp = (long) (milisec / 86400000); tmp = (long) (milisec / 86400000);
milisec -= tmp * 86400000; milisec -= tmp * 86400000;
if( tmp > 1 ) if( tmp > 1 )
str.append(tmp).append(" days "); str.append(tmp).append(" days ");
else else
str.append(tmp).append(" day "); str.append(tmp).append(" day ");
} }
// Hours // Hours
if( milisec >= 3600000 ){ if( milisec >= 3600000 ){
tmp = (long) (milisec / 3600000); tmp = (long) (milisec / 3600000);
milisec -= tmp * 3600000; milisec -= tmp * 3600000;
if( tmp > 1 ) if( tmp > 1 )
str.append(tmp).append(" hours "); str.append(tmp).append(" hours ");
else else
str.append(tmp).append(" hour "); str.append(tmp).append(" hour ");
} }
// Minutes // Minutes
if( milisec >= 60000 ){ if( milisec >= 60000 ){
tmp = (long) (milisec / 60000); tmp = (long) (milisec / 60000);
milisec -= tmp * 60000; milisec -= tmp * 60000;
str.append(tmp).append(" min "); str.append(tmp).append(" min ");
} }
// sec // sec
if( milisec >= 1000 ){ if( milisec >= 1000 ){
tmp = (long) (milisec / 1000); tmp = (long) (milisec / 1000);
milisec -= tmp * 1000; milisec -= tmp * 1000;
str.append(tmp).append(" sec "); str.append(tmp).append(" sec ");
} }
if( milisec > 0 ){ if( milisec > 0 ){
str.append(milisec).append(" milisec "); str.append(milisec).append(" milisec ");
} }
return str.toString(); 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,25 +39,25 @@ 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);
} }
} }
} }
@ -68,21 +68,21 @@ public class SimpleSort{
* 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;
@ -100,26 +100,26 @@ public class SimpleSort{
* 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

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

@ -31,366 +31,359 @@ package zutil.image;
*/ */
public class RAWImageUtil { public class RAWImageUtil {
/** /**
* Returns the peek value in the image * 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);
* @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 * 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 * @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 peak value of the image
*/ */
public static int getPeakValue(int[][][] data, int startX, int startY, int stopX, int stopY) { public static int getPeakValue(int[][][] data, int startX, int startY, int stopX, int stopY) {
int peak = 0; int peak = 0;
for(int y=startY; y<stopY ;y++){ for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){ for(int x=startX; x<stopX ;x++){
if(data[y][x][1] > peak) peak = data[y][x][1]; if(data[y][x][1] > peak) peak = data[y][x][1];
if(data[y][x][2] > peak) peak = data[y][x][2]; if(data[y][x][2] > peak) peak = data[y][x][2];
if(data[y][x][3] > peak) peak = data[y][x][3]; if(data[y][x][3] > peak) peak = data[y][x][3];
} }
} }
return peak; return peak;
} }
/** /**
* Normalizes the image data by the given scale * Normalizes the image data by the given scale
* *
* @param data 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 The scale to normalize the image by * @param scale The scale to normalize the image by
*/ */
public static void normalize(int[][][] data, int startX, int startY, int stopX, int stopY, double scale) { public static void normalize(int[][][] data, int startX, int startY, int stopX, int stopY, double scale) {
for(int y=startY; y<stopY ;y++){ for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){ for(int x=startX; x<stopX ;x++){
data[y][x][1] = (int)(data[y][x][1] * scale); data[y][x][1] = (int)(data[y][x][1] * scale);
data[y][x][2] = (int)(data[y][x][2] * scale); data[y][x][2] = (int)(data[y][x][2] * scale);
data[y][x][3] = (int)(data[y][x][3] * scale); data[y][x][3] = (int)(data[y][x][3] * scale);
} }
} }
} }
/** /**
* Normalizes the image data by the given scale * Normalizes the image data by the given scale
* *
* @param output The output data array * @param output the output data array
* @param data 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 The scale to normalize the image by * @param scale the scale to normalize the image by
*/ */
public static void normalize(int[][][] output, int[][][] data, int startX, int startY, int stopX, int stopY, double scale) { public static void normalize(int[][][] output, int[][][] data, int startX, int startY, int stopX, int stopY, double scale) {
for(int y=startY; y<stopY ;y++){ for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){ for(int x=startX; x<stopX ;x++){
output[y][x][1] = (int)(data[y][x][1] * scale); output[y][x][1] = (int)(data[y][x][1] * scale);
output[y][x][2] = (int)(data[y][x][2] * scale); output[y][x][2] = (int)(data[y][x][2] * scale);
output[y][x][3] = (int)(data[y][x][3] * scale); output[y][x][3] = (int)(data[y][x][3] * scale);
} }
} }
} }
/** /**
* Returns the RMS value of the image * Returns the RMS value of the image
* (The RMS value is a measure of the width of the color distribution.) * (The RMS value is a measure of the width of the color distribution.)
* *
* @param data is 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 RMS value for the image * @return the RMS value for the image
*/ */
public static int getRMS(int[][][] data, int startX, int startY, int stopX, int stopY){ public static int getRMS(int[][][] data, int startX, int startY, int stopX, int stopY){
int pixelCount = 0; int pixelCount = 0;
long accum = 0; long accum = 0;
for(int y=startY; y <stopY ;y++){ for(int y=startY; y <stopY ;y++){
for(int x=startX; x<stopX ;x++){ for(int x=startX; x<stopX ;x++){
accum += data[y][x][1] * data[y][x][1]; accum += data[y][x][1] * data[y][x][1];
accum += data[y][x][2] * data[y][x][2]; accum += data[y][x][2] * data[y][x][2];
accum += data[y][x][3] * data[y][x][3]; accum += data[y][x][3] * data[y][x][3];
pixelCount += 3; pixelCount += 3;
} }
} }
int meanSquare = (int)(accum/pixelCount); int meanSquare = (int)(accum/pixelCount);
int rms = (int)(Math.sqrt(meanSquare)); int rms = (int)(Math.sqrt(meanSquare));
return rms; return rms;
} }
/** /**
* Multiplies the given image data by the given value * Multiplies the given image data by the given value
* *
* @param data is 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
* @param scale is the number to scale the image color by * @param scale is the number to scale the image color by
*/ */
public static void scale(int[][][] data, int startX, int startY, int stopX, int stopY, double scale){ public static void scale(int[][][] data, int startX, int startY, int stopX, int stopY, double scale){
for(int y=startY; y<stopY ;y++){ for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){ for(int x=startX; x<stopX ;x++){
data[y][x][1] *= scale; data[y][x][1] *= scale;
data[y][x][2] *= scale; data[y][x][2] *= scale;
data[y][x][3] *= scale; data[y][x][3] *= scale;
} }
} }
} }
/** /**
* Returns the mean value of the given image data * Returns the mean value of the given image data
* *
* @param data is the image data * @param data is the image data
* @return the mean value of the image * @return the mean value of the image
*/ */
public static int getMeanValue(int[][][] data){ public static int getMeanValue(int[][][] data){
return getMeanValue(data, 0, 0, data[0].length, data.length); return getMeanValue(data, 0, 0, data[0].length, data.length);
} }
/** /**
* Returns the mean value of the given image data * Returns the mean value of the given image data
* *
* @param data is 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 mean value of the image * @return the mean value of the image
*/ */
public static int getMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY){ public static int getMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY){
int[] tmp = getMeanArray(data, startX, startY, stopX, stopY); int[] tmp = getMeanArray(data, startX, startY, stopX, stopY);
return (tmp[0] + tmp[1] + tmp[2])/3; return (tmp[0] + tmp[1] + tmp[2])/3;
} }
/** /**
* Returns an mean array containing a mean value for each color * Returns an mean array containing a mean value for each color
* *
* @param data is 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 mean value of the image * @return the mean value of the image
*/ */
public static int[] getMeanArray(int[][][] data, int startX, int startY, int stopX, int stopY){ public static int[] getMeanArray(int[][][] data, int startX, int startY, int stopX, int stopY){
int mean[] = new int[3]; int mean[] = new int[3];
for(int y=startY; y<stopY ;y++){ for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){ for(int x=startX; x<stopX ;x++){
mean[0] += data[y][x][1]; mean[0] += data[y][x][1];
mean[1] += data[y][x][2]; mean[1] += data[y][x][2];
mean[2] += data[y][x][3]; mean[2] += data[y][x][3];
} }
} }
// calculate the mean value // calculate the mean value
int pixelCount = (stopY-startY)*(stopX-startX); int pixelCount = (stopY-startY)*(stopX-startX);
mean[0] /= pixelCount; mean[0] /= pixelCount;
mean[1] /= pixelCount; mean[1] /= pixelCount;
mean[2] /= pixelCount; mean[2] /= pixelCount;
return mean; return mean;
} }
/** /**
* removes the mean value from the image data * removes the mean value from the image data
* *
* @param data is 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
* @param mean is the mean value * @param mean is the mean value
*/ */
public static void remMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY, int mean){ public static void remMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY, int mean){
addMeanValue(data, startX, startY, stopX, stopY, -mean); addMeanValue(data, startX, startY, stopX, stopY, -mean);
} }
/** /**
* Adds the mean value to the image data * Adds the mean value to the image data
* *
* @param data is 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
* @param mean is the mean value * @param mean is the mean value
*/ */
public static void addMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY, int mean){ public static void addMeanValue(int[][][] data, int startX, int startY, int stopX, int stopY, int mean){
addMeanArray(data, startX, startY, stopX, stopY, new int[]{mean, mean, mean}); addMeanArray(data, startX, startY, stopX, stopY, new int[]{mean, mean, mean});
} }
/** /**
* removes an mean array containing a mean value for each color * removes an mean array containing a mean value for each color
* *
* @param data is 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
* @param mean is an array of length 3 containing a mean value for each color RGB * @param mean is an array of length 3 containing a mean value for each color RGB
*/ */
public static void remMeanArray(int[][][] data, int startX, int startY, int stopX, int stopY, int[] mean){ public static void remMeanArray(int[][][] data, int startX, int startY, int stopX, int stopY, int[] mean){
addMeanArray(data, startX, startY, stopX, stopY, new int[]{-mean[0], -mean[1], -mean[2]}); addMeanArray(data, startX, startY, stopX, stopY, new int[]{-mean[0], -mean[1], -mean[2]});
} }
/** /**
* Adds an mean array containing a mean value for each color * Adds an mean array containing a mean value for each color
* *
* @param data is 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
* @param mean is an array of length 3 containing a mean value for each color RGB * @param mean is an array of length 3 containing a mean value for each color RGB
*/ */
public static void addMeanArray(int[][][] data, int startX, int startY, int stopX, int stopY, int[] mean){ public static void addMeanArray(int[][][] data, int startX, int startY, int stopX, int stopY, int[] mean){
for(int y=startY; y<stopY ;y++){ for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){ for(int x=startX; x<stopX ;x++){
data[y][x][1] += mean[0]; data[y][x][1] += mean[0];
data[y][x][2] += mean[1]; data[y][x][2] += mean[1];
data[y][x][3] += mean[2]; data[y][x][3] += mean[2];
} }
} }
} }
/** /**
* Copies all the pixel data from the image to the new array * Copies all the pixel data from the image to the new array
* *
* @param data The data to copy * @param data The data to copy
* @param xStart X start position on the source * @param xStart X start position on the source
* @param yStart Y start position on the source * @param yStart Y start position on the source
* @param width The amount of pixels to copy * @param width The amount of pixels to copy
* @param hight The amount of pixels to copy * @param height The amount of pixels to copy
* @return A copy of the data array * @return A copy of the data array
*/ */
public static int[][][] crop(int[][][] data, int xStart, int yStart, int width, int hight){ public static int[][][] crop(int[][][] data, int xStart, int yStart, int width, int height){
return crop(data, xStart, yStart, null, 0, 0, width, hight); return crop(data, xStart, yStart, null, 0, 0, width, height);
} }
/** /**
* Copies all the pixel data from the image to the new array * Copies all the pixel data from the image to the new array
* *
* @param data The data to copy * @param data The data to copy
* @param xData X start position in the source * @param xData X start position in the source
* @param yData Y start position in the source * @param yData Y start position in the source
* @param crop The destination * @param crop The destination
* @param xCrop X start position in the destination * @param xCrop X start position in the destination
* @param yCrop Y start position in the destination * @param yCrop Y start position in the destination
* @param width The amount of pixels to copy * @param width The amount of pixels to copy
* @param hight The amount of pixels to copy * @param height The amount of pixels to copy
* @return A copy of the data array * @return A copy of the data array
*/ */
public static int[][][] crop(int[][][] data, int xData, int yData, int[][][] crop, int xCrop, int yCrop, int width, int hight){ 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][hight][4]; if(crop==null) crop = new int[width][height][4];
for(int y=0; y<width ;y++){ for(int y=0; y<width ;y++){
for(int x=0; x<hight ;x++){ for(int x=0; x<height ;x++){
crop[y+yData][x+xData][0] = data[y+yCrop][x+xCrop][0]; crop[y+yData][x+xData][0] = data[y+yCrop][x+xCrop][0];
crop[y+yData][x+xData][1] = data[y+yCrop][x+xCrop][1]; crop[y+yData][x+xData][1] = data[y+yCrop][x+xCrop][1];
crop[y+yData][x+xData][2] = data[y+yCrop][x+xCrop][2]; crop[y+yData][x+xData][2] = data[y+yCrop][x+xCrop][2];
crop[y+yData][x+xData][3] = data[y+yCrop][x+xCrop][3]; crop[y+yData][x+xData][3] = data[y+yCrop][x+xCrop][3];
} }
} }
return crop; return crop;
} }
/** /**
* Copies the given array to a new one that it returns * Copies the given array to a new one that it returns
* *
* @param data The data to duplicate * @param data The data to duplicate
* @return an copy of the array * @return an copy of the array
*/ */
public static int[][][] copyArray(int[][][] data){ public static int[][][] copyArray(int[][][] data){
return copyArray(data, 0, 0, data[0].length, data.length); return copyArray(data, 0, 0, data[0].length, data.length);
} }
/** /**
* Copies the given array to a new one that it returns * Copies the given array to a new one that it returns
* *
* @param data The data to duplicate * @param data The data to duplicate
* @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 array copy * @return The array copy
*/ */
public static int[][][] copyArray(int[][][] data, int startX, int startY, int stopX, int stopY){ public static int[][][] copyArray(int[][][] data, int startX, int startY, int stopX, int stopY){
int[][][] copy = new int[data.length][data[0].length][4]; int[][][] copy = new int[data.length][data[0].length][4];
return copyArray(data, copy, startX, startY, stopX, stopY); return copyArray(data, copy, startX, startY, stopX, stopY);
} }
/** /**
* Copies the given array to a new one that it returns * Copies the given array to a new one that it returns
* *
* @param data The data to duplicate * @param data The data to duplicate
* @param dest is the array to copy the data to * @param dest is the array to copy the data to
* @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 dest array * @return the dest array
*/ */
public static int[][][] copyArray(int[][][] data, int[][][] dest, int startX, int startY, int stopX, int stopY){ public static int[][][] copyArray(int[][][] data, int[][][] dest, int startX, int startY, int stopX, int stopY){
for(int y=startY; y<stopY ;y++){ for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){ for(int x=startX; x<stopX ;x++){
dest[y][x][0] = data[y][x][0]; dest[y][x][0] = data[y][x][0];
dest[y][x][1] = data[y][x][1]; dest[y][x][1] = data[y][x][1];
dest[y][x][2] = data[y][x][2]; dest[y][x][2] = data[y][x][2];
dest[y][x][3] = data[y][x][3]; dest[y][x][3] = data[y][x][3];
} }
} }
return dest; return dest;
} }
/** /**
* This method clips the values of the pixel so that they * This method clips the values of the pixel so that they
* are in the range 0-255 * are in the range 0-255
* *
* @param data 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
*/ */
public static void clip(int[][][] data, int startX, int startY, int stopX, int stopY){ public static void clip(int[][][] data, int startX, int startY, int stopX, int stopY){
for(int y=startY; y<stopY ;y++){ for(int y=startY; y<stopY ;y++){
for(int x=startX; x<stopX ;x++){ for(int x=startX; x<stopX ;x++){
data[y][x][1] = clip(data[y][x][1]); data[y][x][1] = clip(data[y][x][1]);
data[y][x][2] = clip(data[y][x][2]); data[y][x][2] = clip(data[y][x][2]);
data[y][x][3] = clip(data[y][x][3]); data[y][x][3] = clip(data[y][x][3]);
} }
} }
} }
/** /**
* This method clips the values of a color so that it * This method clips the values of a color so that it
* is in the range 0-255 * is in the range 0-255
* */
* @param color public static int clip(int color){
* @return if(color < 0)
*/ return 0;
public static int clip(int color){ else if(color > 255)
if(color < 0) return 255;
return 0; else
else if(color > 255) return color;
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 * Creates an new instance of this class
*/ */
public StringOutputStream(){ public StringOutputStream(){
clear(); clear();
} }
@Override @Override
public void write(int b) { public void write(int b) {
buffer.append( b ); buffer.append( b );
} }
@Override @Override
public void write(byte[] b) { public void write(byte[] b) {
buffer.append( new String(b) ); buffer.append( new String(b) );
} }
@Override @Override
public void write(byte[] b, int off, int len) { public void write(byte[] b, int off, int len) {
buffer.append( new String(b, off, len) ); buffer.append( new String(b, off, len) );
} }
/** /**
* Same as {@link OutputStream:clear()} * Same as {@link OutputStream#close()}
*/ */
@Override @Override
public void close() {} public void close() {}
/** /**
* Clears the String buffer * Clears the String buffer
*/ */
public void clear(){ public void clear(){
buffer = new StringBuilder(); buffer = new StringBuilder();
} }
/** /**
* @return the String with the data * @return the String with the data
*/ */
@Override @Override
public String toString() { public String toString() {
return buffer.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 // Read allowed file types
if(config.getInitParameter("ALLOWED_EXTENSIONS") != null){ if(config.getInitParameter("ALLOWED_EXTENSIONS") != null){
String[] tmp = config.getInitParameter("ALLOWED_EXTENSIONS").split(","); String[] tmp = config.getInitParameter("ALLOWED_EXTENSIONS").split(",");
StringBuilder ext_log = new StringBuilder("Allowed extensions: "); StringBuilder ext_log = new StringBuilder("Allowed extensions: ");
for( String ext : tmp ){ for( String ext : tmp ){
ALLOWED_EXTENSIONS.add(ext.trim().toLowerCase()); ALLOWED_EXTENSIONS.add(ext.trim().toLowerCase());
ext_log.append(ext).append(", "); ext_log.append(ext).append(", ");
} }
logger.info( ext_log.toString() ); logger.info( ext_log.toString() );
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest request, protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
if(request.getParameter("js") != null){ if(request.getParameter("js") != null){
response.setContentType("application/x-javascript"); response.setContentType("application/x-javascript");
String tmp = JAVASCRIPT; String tmp = JAVASCRIPT;
tmp = JAVASCRIPT.replaceAll("\\{SERVLET_URL\\}", request.getRequestURI()); tmp = JAVASCRIPT.replaceAll("\\{SERVLET_URL\\}", request.getRequestURI());
tmp = tmp.replaceAll("\\{BGUPLOAD\\}", "false"); tmp = tmp.replaceAll("\\{BGUPLOAD\\}", "false");
tmp = tmp.replaceAll("\\{PROGHTML\\}", getProgressHTML()); tmp = tmp.replaceAll("\\{PROGHTML\\}", getProgressHTML());
out.print(tmp); out.print(tmp);
return; return;
} }
response.setContentType("application/json"); response.setContentType("application/json");
HttpSession session = request.getSession(); HttpSession session = request.getSession();
LinkedList<FileUploadListener> list = LinkedList<FileUploadListener> list =
(LinkedList<FileUploadListener>)session.getAttribute(SESSION_FILEUPLOAD_LISTENER); (LinkedList<FileUploadListener>)session.getAttribute(SESSION_FILEUPLOAD_LISTENER);
if (list == null) { if (list == null) {
out.println("[]"); out.println("[]");
return; return;
} }
// Generate JSON // Generate JSON
DataNode root = new DataNode( DataType.List ); DataNode root = new DataNode( DataType.List );
Iterator<FileUploadListener> it = list.iterator(); Iterator<FileUploadListener> it = list.iterator();
while( it.hasNext() ) { while( it.hasNext() ) {
FileUploadListener listener = it.next(); FileUploadListener listener = it.next();
if( listener.getStatus() == Status.Done || listener.getStatus() == Status.Error ){ if( listener.getStatus() == Status.Done || listener.getStatus() == Status.Error ){
if( listener.getTime() + 5000 < System.currentTimeMillis() ){ if( listener.getTime() + 5000 < System.currentTimeMillis() ){
it.remove(); it.remove();
} }
} }
root.add( listener.getJSON() ); root.add( listener.getJSON() );
} }
// Write to the user // Write to the user
JSONWriter json_out = new JSONWriter( out ); JSONWriter json_out = new JSONWriter( out );
json_out.write(root); 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(); FileUploadListener listener = new FileUploadListener();
try { try {
// Initiate list and HashMap that will contain the data // Initiate list and HashMap that will contain the data
HashMap<String,String> fields = new HashMap<String,String>(); HashMap<String,String> fields = new HashMap<String,String>();
ArrayList<FileItem> files = new ArrayList<FileItem>(); ArrayList<FileItem> files = new ArrayList<FileItem>();
// Add the listener to the session // Add the listener to the session
HttpSession session = request.getSession(); HttpSession session = request.getSession();
LinkedList<FileUploadListener> list = LinkedList<FileUploadListener> list =
(LinkedList<FileUploadListener>)session.getAttribute(SESSION_FILEUPLOAD_LISTENER); (LinkedList<FileUploadListener>)session.getAttribute(SESSION_FILEUPLOAD_LISTENER);
if(list == null){ if(list == null){
list = new LinkedList<FileUploadListener>(); list = new LinkedList<FileUploadListener>();
session.setAttribute(SESSION_FILEUPLOAD_LISTENER, list); session.setAttribute(SESSION_FILEUPLOAD_LISTENER, list);
} }
list.add(listener); list.add(listener);
// Create a factory for disk-based file items // Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory(); DiskFileItemFactory factory = new DiskFileItemFactory();
if(TEMPFILE_PATH != null) if(TEMPFILE_PATH != null)
factory.setRepository( TEMPFILE_PATH ); factory.setRepository( TEMPFILE_PATH );
// Create a new file upload handler // Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory); ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener( listener ); upload.setProgressListener( listener );
// Set overall request size constraint // Set overall request size constraint
//upload.setSizeMax(yourMaxRequestSize); //upload.setSizeMax(yourMaxRequestSize);
// Parse the request // Parse the request
FileItemIterator it = upload.getItemIterator( request ); FileItemIterator it = upload.getItemIterator( request );
while( it.hasNext() ) { while( it.hasNext() ) {
FileItemStream item = it.next(); FileItemStream item = it.next();
// Is the file type allowed? // Is the file type allowed?
if( !item.isFormField() && !ALLOWED_EXTENSIONS.contains( FileUtil.getFileExtension(item.getName()).toLowerCase() )){ if( !item.isFormField() && !ALLOWED_EXTENSIONS.contains( FileUtil.getFileExtension(item.getName()).toLowerCase() )){
String msg = "Filetype '"+FileUtil.getFileExtension(item.getName())+"' is not allowed!"; String msg = "Filetype '"+FileUtil.getFileExtension(item.getName())+"' is not allowed!";
logger.warning( msg ); logger.warning( msg );
listener.setStatus(Status.Error); listener.setStatus(Status.Error);
listener.setFileName( item.getName() ); listener.setFileName( item.getName() );
listener.setMessage( msg ); listener.setMessage( msg );
return; return;
} }
listener.setFileName( item.getName() ); listener.setFileName( item.getName() );
FileItem fileItem = factory.createItem(item.getFieldName(), FileItem fileItem = factory.createItem(item.getFieldName(),
item.getContentType(), item.isFormField(), item.getName()); item.getContentType(), item.isFormField(), item.getName());
// Read the file data // Read the file data
Streams.copy(item.openStream(), fileItem.getOutputStream(), true); Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
if (fileItem instanceof FileItemHeadersSupport) { if (fileItem instanceof FileItemHeadersSupport) {
final FileItemHeaders fih = item.getHeaders(); final FileItemHeaders fih = item.getHeaders();
((FileItemHeadersSupport) fileItem).setHeaders(fih); ((FileItemHeadersSupport) fileItem).setHeaders(fih);
} }
//Handle the item //Handle the item
if(fileItem.isFormField()){ if(fileItem.isFormField()){
fields.put( fileItem.getFieldName(), fileItem.getString()); fields.put( fileItem.getFieldName(), fileItem.getString());
} }
else{ else{
files.add( fileItem ); files.add( fileItem );
logger.info("Recieved file: "+fileItem.getName()+" ("+StringUtil.formatByteSizeToString(fileItem.getSize())+")"); logger.info("Recieved file: "+fileItem.getName()+" ("+StringUtil.formatByteSizeToString(fileItem.getSize())+")");
} }
} }
// Process the upload // Process the upload
listener.setStatus( Status.Processing ); listener.setStatus( Status.Processing );
doUpload( request, response, fields, files ); doUpload( request, response, fields, files );
// Done // Done
listener.setStatus( Status.Done ); listener.setStatus( Status.Done );
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.SEVERE, null, e); logger.log(Level.SEVERE, null, e);
listener.setStatus(Status.Error); listener.setStatus(Status.Error);
listener.setFileName(""); listener.setFileName("");
listener.setMessage( e.getMessage() ); listener.setMessage( e.getMessage() );
} }
} }
/** /**
* @return the HTML for the progress bar. Special ID's: * @return the HTML for the progress bar. Special ID's:
* <br>-filename = String * <br>-filename = String
* <br>-progress = percent * <br>-progress = percent
* <br>-total = String * <br>-total = String
* <br>-uploaded = String * <br>-uploaded = String
* <br>-status = String (Uploading, Initializing etc) * <br>-status = String (Uploading, Initializing etc)
* <br>-speed = String * <br>-speed = String
*/ */
public abstract String getProgressHTML(); public abstract String getProgressHTML();
/** /**
* Handle the uppload * Handle the uppload
* @throws ServletException * @throws ServletException
*/ */
public abstract void doUpload(HttpServletRequest request, HttpServletResponse response, public abstract void doUpload(HttpServletRequest request, HttpServletResponse response,
Map<String,String> fields, List<FileItem> files) throws ServletException; 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){ public ChatMessage(String room){
this("", room, ChatMessageType.REGISTER); this("", room, ChatMessageType.REGISTER);
} }
/** /**
* Sends a message to the given room * Sends a message to the given room
* *
* @param msg The message * @param msg The message
* @param room The room * @param room The room
*/ */
public ChatMessage(String msg, String room){ public ChatMessage(String msg, String room){
this(msg, room, ChatMessageType.MESSAGE); this(msg, room, ChatMessageType.MESSAGE);
} }
public ChatMessage(String msg, String room, ChatMessageType type){ public ChatMessage(String msg, String room, ChatMessageType type){
this.msg = msg; this.msg = msg;
this.room = room; this.room = room;
this.type = type; 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 * Annotation that assigns a name to the return value
* in an method. * in an method.
* *
* @author Ziver * @author Ziver
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
public @interface WSReturnName { @interface WSReturnName {
String value(); String value();
} }
/** /**
* Skipp publication of the given method * Skipp publication of the given method
* *
* @author Ziver * @author Ziver
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
public @interface WSIgnore { } public @interface WSIgnore { }
/** /**
* Method or Parameter comments for the WSDL. * Method or Parameter comments for the WSDL.
* These comments are put in the message part of the WSDL * These comments are put in the message part of the WSDL
* *
* @author Ziver * @author Ziver
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface WSDocumentation{ @interface WSDocumentation{
String value(); String value();
} }
/** /**
* Parameter comments for the WSDL. * Parameter comments for the WSDL.
* These comments are put in the message part of the WSDL * These comments are put in the message part of the WSDL
* *
* @author Ziver * @author Ziver
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface WSParamDocumentation{ @interface WSParamDocumentation{
String value(); String value();
} }
/** /**
* This method will be used in the header. * This method will be used in the header.
* *
* @author Ziver * @author Ziver
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
public @interface WSHeader { } @interface WSHeader { }
/** /**
* Specifies the name space for method. * Specifies the name space for method.
* *
* @author Ziver * @author Ziver
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
//@Target(ElementType.TYPE) @interface WSNamespace {
public @interface WSNamespace { String value();
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 BitSet bits;
private int content_size; private int content_size;
private int optimal_size; private int optimal_size;
private int k; private int k;
/** /**
* Creates a bloom filter * Creates a bloom filter
* *
* @param size The amount of bits in the filter * @param size The amount of bits in the filter
* @param expected_data_count The estimated amount of data to * @param expected_data_count The estimated amount of data to
* be inserted(a bigger number is better than a smaller) * be inserted(a bigger number is better than a smaller)
*/ */
public BloomFilter(int size, int expected_data_count){ public BloomFilter(int size, int expected_data_count){
bits = new BitSet(size); bits = new BitSet(size);
k = (int)((size/expected_data_count) * Math.log(2)); k = (int)((size/expected_data_count) * Math.log(2));
content_size = 0; content_size = 0;
optimal_size = expected_data_count; optimal_size = expected_data_count;
} }
/** /**
* @param e A Serializable object * @param e A Serializable object
* @return If the optimal size has been reached * @return If the optimal size has been reached
*/ */
public boolean add(T e) { public boolean add(T e) {
try { try {
content_size++; content_size++;
int hash = 0; int hash = 0;
for(int i=0; i<k ;i++){ for(int i=0; i<k ;i++){
hash = Hasher.MurmurHash(e, hash); hash = Hasher.MurmurHash(e, hash);
hash = Math.abs(hash) % bits.size(); hash = Math.abs(hash) % bits.size();
bits.set(hash, true); bits.set(hash, true);
} }
} catch (Exception e1) { } catch (Exception e1) {
e1.printStackTrace(); e1.printStackTrace();
} }
return isFull(); return isFull();
} }
/** /**
* Adds a collection to the bloom filter * Adds a collection to the bloom filter
* *
* @return If the optimal size has been reached * @return If the optimal size has been reached
*/ */
public boolean addAll(Collection<? extends T> c) { public boolean addAll(Collection<? extends T> c) {
for(T t : c){ for(T t : c){
add(t); add(t);
} }
return isFull(); return isFull();
} }
/** /**
* @return clears the filter * Clears the filter
*/ */
public void clear() { public void clear() {
content_size = 0; content_size = 0;
bits.clear(); bits.clear();
} }
/** /**
* @param o is the Serializable object to search for * @param o is the Serializable object to search for
* @return If the object contains in the filter or * @return If the object contains in the filter or
* false if the Object is not Serializable * false if the Object is not Serializable
*/ */
public boolean contains(Object o) { public boolean contains(Object o) {
try { try {
if(!(o instanceof Serializable))return false; if(!(o instanceof Serializable))return false;
int hash = 0; int hash = 0;
for(int i=0; i<k ;i++){ for(int i=0; i<k ;i++){
hash = Hasher.MurmurHash((Serializable)o, hash); hash = Hasher.MurmurHash((Serializable)o, hash);
hash = Math.abs(hash) % bits.size(); hash = Math.abs(hash) % bits.size();
if(!bits.get(hash)) if(!bits.get(hash))
return false; return false;
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return true; return true;
} }
/** /**
* Checks if the whole collection contains in the filter * Checks if the whole collection contains in the filter
* *
* @param c The collection * @param c The collection
*/ */
public boolean containsAll(Collection<?> c) { public boolean containsAll(Collection<?> c) {
for(Object o : c){ for(Object o : c){
if(!contains(o)) return false; if(!contains(o)) return false;
} }
return true; return true;
} }
/** /**
* @return If the bloom filter is empty * @return If the bloom filter is empty
*/ */
public boolean isEmpty() { public boolean isEmpty() {
return content_size == 0; return content_size == 0;
} }
/** /**
* @return If the optimal size has been reached * @return If the optimal size has been reached
*/ */
public boolean isFull() { public boolean isFull() {
return content_size > optimal_size; return content_size > optimal_size;
} }
/** /**
* @return The number of data added * @return The number of data added
*/ */
public int size() { public int size() {
return content_size; return content_size;
} }
/** /**
* @return The false positive probability of the current state of the filter * @return The false positive probability of the current state of the filter
*/ */
public double falsePosetiveProbability(){ public double falsePositiveProbability(){
return Math.pow(0.6185, bits.size()/content_size); return Math.pow(0.6185, bits.size()/content_size);
} }
/** /**
* Set the hash count. Should be set before adding elements * Set the hash count. Should be set before adding elements
* or the already added elements will be lost * or the already added elements will be lost
* *
* @param k The hash count * @param k The hash count
*/ */
public void setHashCount(int k){ public void setHashCount(int k){
this.k = k; this.k = k;
} }
//*********************************************************************
//*********************************************************************
public Object[] toArray() {
throw new UnsupportedOperationException();
}
@SuppressWarnings("hiding") //*********************************************************************
public <T> T[] toArray(T[] a) { //*********************************************************************
throw new UnsupportedOperationException(); public Object[] toArray() {
} throw new UnsupportedOperationException();
}
public Iterator<T> iterator() { @SuppressWarnings("hiding")
throw new UnsupportedOperationException(); public <T> T[] toArray(T[] a) {
} throw new UnsupportedOperationException();
}
public boolean remove(Object o) { public Iterator<T> iterator() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public boolean removeAll(Collection<?> c) { public boolean remove(Object o) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public boolean retainAll(Collection<?> c) { public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException(); 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 = "