Fixed many warnings

This commit is contained in:
Ziver Koc 2018-05-27 01:23:21 +02:00
parent c570847f3a
commit ccecc067b2
160 changed files with 951 additions and 1151 deletions

1
.gitignore vendored
View file

@ -1,4 +1,3 @@
Zutil.jar
/build/ /build/
/bin/ /bin/
/target/ /target/

4
Jenkinsfile vendored
View file

@ -28,7 +28,9 @@ node {
stage('Deploy') { stage('Deploy') {
// Figure out Pom version // Figure out Pom version
def version = (readFile('pom.xml') =~ '<version>(.+?)</version>')[0][1] def pom = readFile('pom.xml')
def versionMatch = pom =~ "<version>(.+?)</version>"
def version = versionMatch[0][1]
// Start deployment // Start deployment
sh 'mvn -DskipStatic -DskipTests deploy' sh 'mvn -DskipStatic -DskipTests deploy'

View file

@ -54,8 +54,7 @@ public class ByteUtil {
* @return a new byte containing a sub byte defined by the index and length * @return a new byte containing a sub byte defined by the index and length
*/ */
public static byte getBits(byte data, int index, int length){ public static byte getBits(byte data, int index, int length){
byte ret = (byte) (data & getBitMask(index, length)); return (byte) (data & getBitMask(index, length));
return ret;
} }
/** /**
@ -153,7 +152,7 @@ public class ByteUtil {
if (shiftBy == 0) if (shiftBy == 0)
return data; return data;
byte rest = 0; byte rest;
for (int i=0; i<data.length; ++i){ for (int i=0; i<data.length; ++i){
rest = (byte)(getBits(data[i], shiftBy-1, shiftBy) << 8 - shiftBy); rest = (byte)(getBits(data[i], shiftBy-1, shiftBy) << 8 - shiftBy);
data[i] = (byte)((data[i]&0xFF) >>> shiftBy); data[i] = (byte)((data[i]&0xFF) >>> shiftBy);
@ -207,7 +206,7 @@ public class ByteUtil {
* @return A multiline String with human readable HEX and ASCII * @return A multiline String with human readable HEX and ASCII
*/ */
public static String toFormattedString(byte[] data, int offset, int length){ public static String toFormattedString(byte[] data, int offset, int length){
StringBuffer output = new StringBuffer(); StringBuilder output = new StringBuilder();
//000 XX XX XX XX XX XX XX XX '........' //000 XX XX XX XX XX XX XX XX '........'
int maxOffset = (""+length).length(); int maxOffset = (""+length).length();

View file

@ -39,7 +39,7 @@ public class ClassUtil {
/** A Set that contains possible wrapper objects for primitives **/ /** A Set that contains possible wrapper objects for primitives **/
private static final HashSet<Class<?>> wrappers; private static final HashSet<Class<?>> wrappers;
static { static {
wrappers = new HashSet<Class<?>>(); wrappers = new HashSet<>();
wrappers.add(Boolean.class); wrappers.add(Boolean.class);
wrappers.add(Character.class); wrappers.add(Character.class);
wrappers.add(Byte.class); wrappers.add(Byte.class);
@ -54,7 +54,7 @@ public class ClassUtil {
/** A Set that contains possible primitives **/ /** A Set that contains possible primitives **/
private static final HashSet<Class<?>> primitives; private static final HashSet<Class<?>> primitives;
static { static {
primitives = new HashSet<Class<?>>(); primitives = new HashSet<>();
primitives.add(boolean.class); primitives.add(boolean.class);
primitives.add(char.class); primitives.add(char.class);
primitives.add(byte.class); primitives.add(byte.class);

View file

@ -96,10 +96,8 @@ public class CronTimer implements Iterator<Long>, Iterable<Long>{
String[] divisionArr = str.split("/", 2); String[] divisionArr = str.split("/", 2);
if (divisionArr.length == 2) { if (divisionArr.length == 2) {
float divider = Integer.parseInt(divisionArr[1]); float divider = Integer.parseInt(divisionArr[1]);
Iterator<Integer> it = getRange(divisionArr[0], from, to).iterator(); for (Integer i : getRange(divisionArr[0], from, to)) {
while (it.hasNext()) { if (i % divider == 0)
Integer i = it.next();
if (i%divider == 0)
list.add(i); list.add(i);
} }
} }

View file

@ -166,8 +166,8 @@ public class Encrypter {
public byte[] encrypt(byte[] data){ public byte[] encrypt(byte[] data){
try { try {
byte[] encryption = new byte[encipher.getOutputSize(data.length)]; byte[] encryption = new byte[encipher.getOutputSize(data.length)];
int ctLength = encipher.update(data, 0, data.length, encryption, 0);
int ctLength = encipher.update(data, 0, data.length, encryption, 0);
ctLength += encipher.doFinal(encryption, ctLength); ctLength += encipher.doFinal(encryption, ctLength);
return encryption; return encryption;
} catch (Exception e) { } catch (Exception e) {

View file

@ -47,9 +47,9 @@ public class Hasher {
public static String hash(File file, String hashType) throws NoSuchAlgorithmException, IOException { public static String hash(File file, String hashType) throws NoSuchAlgorithmException, IOException {
MessageDigest digest = MessageDigest.getInstance(hashType); //"MD5" MessageDigest digest = MessageDigest.getInstance(hashType); //"MD5"
InputStream is = new FileInputStream(file); InputStream is = new FileInputStream(file);
String output = ""; String output;
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
int read = 0; int read;
try { try {
while( (read = is.read(buffer)) > 0) { while( (read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read); digest.update(buffer, 0, read);
@ -165,14 +165,14 @@ public class Hasher {
try { try {
// Get an hmac_sha1 key from the raw key bytes // Get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key, algo); SecretKeySpec signingKey = new SecretKeySpec(key, algo);
// Get a MAC instance and initialize with the signing key // Get a MAC instance and initialize with the signing key
Mac mac = Mac.getInstance(algo); Mac mac = Mac.getInstance(algo);
mac.init(signingKey); mac.init(signingKey);
// Compute the HMAC on input data bytes // Compute the HMAC on input data bytes
byte[] raw = mac.doFinal( data ); byte[] raw = mac.doFinal( data );
return Converter.toHexString(raw); return Converter.toHexString(raw);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -225,10 +225,9 @@ public class Hasher {
* @param data is the byte array to hash * @param data is the byte array to hash
* @param hashType is the hash method (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512 ) * @param hashType is the hash method (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512 )
* @return an String containing the hash * @return an String containing the hash
* @throws Exception
*/ */
public static String hash(byte[] data, String hashType) throws Exception { public static String hash(byte[] data, String hashType) throws Exception {
MessageDigest md = null; MessageDigest md;
md = MessageDigest.getInstance(hashType); //MD5 || SHA md = MessageDigest.getInstance(hashType); //MD5 || SHA
md.update(data); md.update(data);

View file

@ -27,7 +27,7 @@ package zutil;
/** /**
* This interface is used to look if another instance of the * This interface is used to look if another instance of the
* application is running * application is running
* *
* @author Ziver * @author Ziver
* *
*/ */
@ -37,12 +37,12 @@ public interface OneInstance {
* *
* @return True if the file is locked else false * @return True if the file is locked else false
*/ */
public boolean check(); boolean check();
/** /**
* Locks the application so that another one can not run * Locks the application so that another one can not run
* *
* @return False if there are a error else true * @return False if there are a error else true
*/ */
public boolean lockApp(); boolean lockApp();
} }

View file

@ -33,7 +33,7 @@ import java.net.Socket;
/** /**
* This class checks if the app is alredy running * This class checks if the app is alredy running
* by Locking a port * by Locking a port
* *
* @author Ziver Koc * @author Ziver Koc
*/ */
public class OneInstanceNetwork extends Thread implements OneInstance{ public class OneInstanceNetwork extends Thread implements OneInstance{
@ -63,8 +63,8 @@ public class OneInstanceNetwork extends Thread implements OneInstance{
* should not be cald outside the class * should not be cald outside the class
*/ */
public void run() { public void run() {
ServerSocket serverSocket = null; ServerSocket serverSocket;
Socket clientSocket = null; Socket clientSocket;
try { try {
// Create the server socket // Create the server socket
serverSocket = new ServerSocket(port, 1); serverSocket = new ServerSocket(port, 1);

View file

@ -27,7 +27,7 @@ package zutil;
/** /**
* This interface is used in some classes to handle the progress * This interface is used in some classes to handle the progress
* of some action * of some action
* *
* @author Ziver * @author Ziver
* *
*/ */
@ -40,5 +40,5 @@ public interface ProgressListener<S,D> {
* @param info is some information from the source object * @param info is some information from the source object
* @param percent is the progress of the object (0-100) * @param percent is the progress of the object (0-100)
*/ */
public void progressUpdate(S source, D info, double percent); void progressUpdate(S source, D info, double percent);
} }

View file

@ -31,7 +31,7 @@ import java.util.List;
/** /**
* This is a class whit utility methods. * This is a class whit utility methods.
* *
* @author Ziver * * @author Ziver *
*/ */
public class StringUtil { public class StringUtil {
@ -57,7 +57,7 @@ public class StringUtil {
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;
// Years // Years
if( milisec >= 31557032762.3361d ){ if( milisec >= 31557032762.3361d ){
@ -69,9 +69,9 @@ public class StringUtil {
str.append(tmp).append(" year "); str.append(tmp).append(" year ");
} }
// Months // Months
if( milisec >= 2629743830l ){ if( milisec >= 2629743830L){
tmp = (long) (milisec / 2629743830l); tmp = milisec / 2629743830L;
milisec -= tmp * 2629743830l; milisec -= tmp * 2629743830L;
if( tmp > 1 ) if( tmp > 1 )
str.append(tmp).append(" months "); str.append(tmp).append(" months ");
else else
@ -79,7 +79,7 @@ public class StringUtil {
} }
// Days // Days
if( milisec >= 86400000 ){ if( milisec >= 86400000 ){
tmp = (long) (milisec / 86400000); tmp = milisec / 86400000;
milisec -= tmp * 86400000; milisec -= tmp * 86400000;
if( tmp > 1 ) if( tmp > 1 )
str.append(tmp).append(" days "); str.append(tmp).append(" days ");
@ -88,7 +88,7 @@ public class StringUtil {
} }
// Hours // Hours
if( milisec >= 3600000 ){ if( milisec >= 3600000 ){
tmp = (long) (milisec / 3600000); tmp = milisec / 3600000;
milisec -= tmp * 3600000; milisec -= tmp * 3600000;
if( tmp > 1 ) if( tmp > 1 )
str.append(tmp).append(" hours "); str.append(tmp).append(" hours ");
@ -97,13 +97,13 @@ public class StringUtil {
} }
// Minutes // Minutes
if( milisec >= 60000 ){ if( milisec >= 60000 ){
tmp = (long) (milisec / 60000); tmp = milisec / 60000;
milisec -= tmp * 60000; milisec -= tmp * 60000;
str.append(tmp).append(" min "); str.append(tmp).append(" min ");
} }
// sec // sec
if( milisec >= 1000 ){ if( milisec >= 1000 ){
tmp = (long) (milisec / 1000); tmp = milisec / 1000;
milisec -= tmp * 1000; milisec -= tmp * 1000;
str.append(tmp).append(" sec "); str.append(tmp).append(" sec ");
} }
@ -118,8 +118,6 @@ public class StringUtil {
* Generates a String where the number has been prefixed * Generates a String where the number has been prefixed
* with zeros until the string has the wanted size. * with zeros until the string has the wanted size.
* *
* @param number
* @param length
* @return a new String with the given length or longer if the number has more characters. * @return a new String with the given length or longer if the number has more characters.
*/ */
public static String prefixInt(int number, int length){ public static String prefixInt(int number, int length){
@ -135,6 +133,7 @@ public class StringUtil {
* @param array a array 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
*/ */
@SafeVarargs
public static <T> String join(String delimiter, T... array){ public static <T> String join(String delimiter, T... array){
return join(delimiter, Arrays.asList(array)); return join(delimiter, Arrays.asList(array));
} }

View file

@ -30,9 +30,9 @@ import java.math.BigInteger;
import java.util.LinkedList; import java.util.LinkedList;
/** /**
* Euclidean algorithm is an algorithm to determine * Euclidean algorithm is an algorithm to determine
* the greatest common divisor (GCD) * the greatest common divisor (GCD)
* *
* @author Ziver * @author Ziver
* *
*/ */
@ -40,7 +40,6 @@ public class EuclideansAlgo {
/** /**
* Simple Test * Simple Test
* @param args
*/ */
public static void main(String[] args){ public static void main(String[] args){
MultiPrintStream.out.println("*** Correct Answer: "); MultiPrintStream.out.println("*** Correct Answer: ");
@ -104,7 +103,7 @@ public class EuclideansAlgo {
* @return a list of integers that is generators for a and b * @return a list of integers that is generators for a and b
*/ */
public static LinkedList<Integer> calcGenerators(int a, int b){ public static LinkedList<Integer> calcGenerators(int a, int b){
LinkedList<Integer> list = new LinkedList<Integer>(); LinkedList<Integer> list = new LinkedList<>();
int t; int t;
while( b != 0 ){ while( b != 0 ){
@ -126,7 +125,7 @@ public class EuclideansAlgo {
* @return a list of BigIntegers that is generators of a and b * @return a list of BigIntegers that is generators of a and b
*/ */
public static LinkedList<BigInteger> calcGenerators(BigInteger a, BigInteger b){ public static LinkedList<BigInteger> calcGenerators(BigInteger a, BigInteger b){
LinkedList<BigInteger> list = new LinkedList<BigInteger>(); LinkedList<BigInteger> list = new LinkedList<>();
BigInteger t; BigInteger t;
while( !b.equals(BigInteger.ZERO) ){ while( !b.equals(BigInteger.ZERO) ){

View file

@ -22,16 +22,13 @@
* THE SOFTWARE. * THE SOFTWARE.
*/ */
/**
*
*/
package zutil.algo; package zutil.algo;
import java.math.BigInteger; 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 <a href="http://en.wikipedia.org/wiki/Shanks-Tonelli_algorithm">Wikipedia</a> * @see <a href="http://en.wikipedia.org/wiki/Shanks-Tonelli_algorithm">Wikipedia</a>
*/ */

View file

@ -33,7 +33,7 @@ import java.util.LinkedList;
* The Wieners algorithm factorizes two big numbers a and b. * The Wieners algorithm factorizes two big numbers a and b.
* It uses the Euclidien algorithm to calculate the generator of the * It uses the Euclidien algorithm to calculate the generator of the
* numbers and then uses them to calculate the factorization. * numbers and then uses them to calculate the factorization.
* *
* @author Ziver * @author Ziver
* *
*/ */
@ -49,7 +49,7 @@ public class WienersAlgo {
* If no value was found then it returns null. * If no value was found then it returns null.
*/ */
public static BigInteger[] calc(BigInteger n, BigInteger e){ public static BigInteger[] calc(BigInteger n, BigInteger e){
BigInteger[] ret = null; BigInteger[] ret;
LinkedList<BigInteger> gen = EuclideansAlgo.calcGenerators(e, n); LinkedList<BigInteger> gen = EuclideansAlgo.calcGenerators(e, n);

View file

@ -43,8 +43,8 @@ public class BreadthFirstSearch implements PathFinder{
* @return A list with the path * @return A list with the path
*/ */
public LinkedList<PathNode> find(PathNode start, PathNode stop){ public LinkedList<PathNode> find(PathNode start, PathNode stop){
Queue<PathNode> queue = new LinkedList<PathNode>(); Queue<PathNode> queue = new LinkedList<>();
HashSet<PathNode> visited = new HashSet<PathNode>(); HashSet<PathNode> visited = new HashSet<>();
queue.add(start); queue.add(start);
visited.add( start ); visited.add( start );

View file

@ -29,11 +29,11 @@ import java.util.LinkedList;
/** /**
* A PathFinder class implemented with DFS * A PathFinder class implemented with DFS
* *
* @author Ziver * @author Ziver
*/ */
public class DepthFirstSearch { public class DepthFirstSearch {
private HashSet<PathNode> visited = new HashSet<PathNode>(); private HashSet<PathNode> visited = new HashSet<>();
/** /**
* Returns the first path to the destination * Returns the first path to the destination

View file

@ -26,116 +26,62 @@ package zutil.algo.path;
public class DynamicProgramming { public class DynamicProgramming {
public static char[][] words = new char[][]{ public static char[][] words = new char[][]{
"bibba".toCharArray(), "bibba".toCharArray(),
"bitas".toCharArray(), "bitas".toCharArray(),
"brott".toCharArray(), "brott".toCharArray(),
"bl<EFBFBD>ja".toCharArray(), "blaja".toCharArray(),
"boson".toCharArray() "boson".toCharArray()
}; };
public static void main(String[] args){ public static void main(String[] args) {
new DynamicProgramming().search(); new DynamicProgramming().search();
} }
/*
int search(words[][][]) public int search() {
matrix[][][] = 0
shortest = -1
for w=0->length(words)
for y=0->length(words)
for x=0->length(words)
// f<EFBFBD>rsta raden i matrisen
if y == 0
// finns f<EFBFBD>rsta bokstaven i r<EFBFBD>tt position i f<EFBFBD>rsta ordet?
if words[0][x] != words[w][0]
matrix[w][y][x] = -1
else
matrix[w][y][x] = 0
else
// om f<EFBFBD>reg<EFBFBD>ende <EFBFBD>r negativ s<EFBFBD>tt nuvarande till negativ
if matrix[w][y-1][x] < 0
matrix[w][y-1][x] = -1
// h<EFBFBD>r s<EFBFBD> h<EFBFBD>nder det riktiga i algoritmen
else
tmp = minstaForskjutning(words[y], words[w][y], x)
if tmp >= 0
matrix[w][y][x] = matrix[w][y-1][x] + tmp
else
matrix[w][y][x] = -1
// kolla om det <EFBFBD>r sista raden i matrisen
if y == length(matrix)
if (tmp < shortest || shortest < 0) && tmp >= 0
shortest = tmp;
return shortest
int minstaForskjutning(word[], find, index){
minsta = -1
for i=0->length(word)
if word[i] == cfind && (abs(index-i) < minsta || minsta < 0)
minsta = abs(index-i)
return minsta
*/
public int search(){
int[][][] matrix = new int[words.length][words.length][words.length]; int[][][] matrix = new int[words.length][words.length][words.length];
int shortest = -1; int shortest = -1;
for(int w=0; w<words.length ;w++){ //lodr<EFBFBD>ta ordet for (int w = 0; w < words.length; w++) {
System.out.print("\n\n"+new String(words[w])+"\n "); for (int y = 0; y < words.length; y++) {
for(int y=0; y<words.length ;y++){ // v<EFBFBD>gr<EFBFBD>ta ordet for (int x = 0; x < words.length; x++) {
System.out.print("\n"+ new String(words[y])+": "); if (y == 0) {
for(int x=0; x<words.length ;x++){ // psition i y if (words[0][x] != words[w][0])
// f<EFBFBD>rsta v<EFBFBD>gr<EFBFBD>ta ordet
if(y == 0){
if(words[0][x] != words[w][0]){
matrix[w][y][x] = -1; matrix[w][y][x] = -1;
} else
else{
matrix[w][y][x] = 0; matrix[w][y][x] = 0;
} } else {
} if (matrix[w][y - 1][x] < 0) {
//resten av de v<EFBFBD>gr<EFBFBD>ta orden
else{
if(matrix[w][y-1][x] < 0){
matrix[w][y][x] = -1; matrix[w][y][x] = -1;
} } else {
else{ int tmp = smallestChange(words[y], words[w][y], x);
int tmp = minstaForskjutning(words[y], words[w][y], x); if (tmp >= 0) {
if(tmp >= 0){ matrix[w][y][x] = matrix[w][y - 1][x] + tmp;
matrix[w][y][x] = matrix[w][y-1][x] + tmp; } else {
}
else{
matrix[w][y][x] = -1; matrix[w][y][x] = -1;
} }
} }
} }
if(y == words.length-1){ if (y == words.length - 1) {
int tmp = matrix[w][y][x]; int tmp = matrix[w][y][x];
if((tmp<shortest || shortest<0) if ((tmp < shortest || shortest < 0)
&& tmp>= 0){ && tmp >= 0) {
shortest = tmp; shortest = tmp;
} }
} }
System.out.print(" "+matrix[w][y][x]);
} }
} }
} }
System.out.println("\n\nKortaste f<>rflyttningen: "+shortest);
return shortest; return shortest;
} }
private int minstaForskjutning(char[] word, char cfind, int index){ private int smallestChange(char[] word, char cfind, int index) {
int minsta = -1; int smallest = -1;
for(int i=0; i<word.length ;i++){ for (int i = 0; i < word.length; i++) {
if(word[i] == cfind && (Math.abs(index-i)<minsta || minsta<0)){ if (word[i] == cfind && (Math.abs(index - i) < smallest || smallest < 0)) {
minsta = Math.abs(index-i); smallest = Math.abs(index - i);
} }
} }
return minsta; return smallest;
} }
} }

View file

@ -28,7 +28,7 @@ import java.util.LinkedList;
/** /**
* All path finding algorithms should implement this interface * All path finding algorithms should implement this interface
* *
* @author Ziver * @author Ziver
*/ */
public interface PathFinder { public interface PathFinder {
@ -41,5 +41,5 @@ public interface PathFinder {
* @param goal is the search goal * @param goal is the search goal
* @return a LinkedList of the path, empty list if no path was found * @return a LinkedList of the path, empty list if no path was found
*/ */
public LinkedList<PathNode> find(PathNode start, PathNode goal); LinkedList<PathNode> find(PathNode start, PathNode goal);
} }

View file

@ -32,23 +32,23 @@ public interface PathNode {
/** /**
* @return an Iterator with all its neighbors * @return an Iterator with all its neighbors
*/ */
public Iterable<PathNode> getNeighbors(); Iterable<PathNode> getNeighbors();
/** /**
* @param neighbor is the neighbor * @param neighbor is the neighbor
* @return the cost to the neighbor * @return the cost to the neighbor
*/ */
public int getNeighborCost(PathNode neighbor); int getNeighborCost(PathNode neighbor);
/** /**
* Sets the parent node to this one * Sets the parent node to this one
*/ */
public void setParentNeighbor(PathNode parent); void setParentNeighbor(PathNode parent);
/** /**
* @return the parent node * @return the parent node
*/ */
public PathNode getParentNeighbor(); PathNode getParentNeighbor();
/** /**
* Traverses the parent tree and returns the path. * Traverses the parent tree and returns the path.
@ -56,5 +56,5 @@ public interface PathNode {
* @param goal is the node to reach * @param goal is the node to reach
* @return the path to the goal, empty list if there is no goal * @return the path to the goal, empty list if there is no goal
*/ */
public LinkedList<PathNode> traversTo(PathNode goal); LinkedList<PathNode> traversTo(PathNode goal);
} }

View file

@ -37,7 +37,7 @@ public class StandardPathNode implements PathNode{
private PathNode parent; private PathNode parent;
public StandardPathNode(){ public StandardPathNode(){
neighbors = new HashMap<PathNode,Integer>(); neighbors = new HashMap<>();
} }
public int getNeighborCost(PathNode neighbor) { public int getNeighborCost(PathNode neighbor) {
@ -57,7 +57,7 @@ public class StandardPathNode implements PathNode{
} }
public LinkedList<PathNode> traversTo(PathNode goal) { public LinkedList<PathNode> traversTo(PathNode goal) {
LinkedList<PathNode> path = new LinkedList<PathNode>(); LinkedList<PathNode> path = new LinkedList<>();
PathNode current = this; PathNode current = this;
while(current != null){ while(current != null){
path.addFirst(current); path.addFirst(current);
@ -66,8 +66,8 @@ public class StandardPathNode implements PathNode{
path.addFirst( goal ); path.addFirst( goal );
return path; return path;
} }
} }
return new LinkedList<PathNode>(); return new LinkedList<>();
} }
} }

View file

@ -33,7 +33,7 @@ import java.util.LinkedList;
* Sort very big files that doesn't fit in ram * Sort very big files that doesn't fit in ram
* Inspiration: * Inspiration:
* http://www.codeodor.com/index.cfm/2007/5/14/Re-Sorting-really-BIG-files---the-Java-source-code/1208 * http://www.codeodor.com/index.cfm/2007/5/14/Re-Sorting-really-BIG-files---the-Java-source-code/1208
* *
* @author Ziver * @author Ziver
*/ */
public class ExternalSort { public class ExternalSort {
@ -48,7 +48,6 @@ public class ExternalSort {
* *
* @param orgFile File to sort * @param orgFile File to sort
* @param sortedFile The sorted file * @param sortedFile The sorted file
* @throws FileNotFoundException
*/ */
public ExternalSort(File orgFile, File sortedFile) throws FileNotFoundException{ public ExternalSort(File orgFile, File sortedFile) throws FileNotFoundException{
in = new BufferedReader(new FileReader(orgFile)); in = new BufferedReader(new FileReader(orgFile));
@ -62,7 +61,6 @@ public class ExternalSort {
* @param orgFile File to sort * @param orgFile File to sort
* @param sortedFile The sorted file * @param sortedFile The sorted file
* @param chunk The chunk size * @param chunk The chunk size
* @throws FileNotFoundException
*/ */
public ExternalSort(File orgFile, File sortedFile, int chunk) throws FileNotFoundException{ public ExternalSort(File orgFile, File sortedFile, int chunk) throws FileNotFoundException{
in = new BufferedReader(new FileReader(orgFile)); in = new BufferedReader(new FileReader(orgFile));
@ -88,7 +86,8 @@ public class ExternalSort {
/** /**
* Merges all the files to one * Merges all the files to one
* @param files *
* @param files a list of files to be merged
*/ */
private void mergeFiles(LinkedList<File> files){ private void mergeFiles(LinkedList<File> files){
try { try {
@ -116,7 +115,7 @@ public class ExternalSort {
String row; String row;
while (someFileStillHasRows){ while (someFileStillHasRows){
String min; String min;
int minIndex = 0; int minIndex;
row = rows[0]; row = rows[0];
if (row!=null) { if (row!=null) {
@ -208,8 +207,8 @@ public class ExternalSort {
* @throws IOException Some kind of error * @throws IOException Some kind of error
*/ */
private LinkedList<File> sortChunks() throws IOException{ private LinkedList<File> sortChunks() throws IOException{
LinkedList<File> chunkFiles = new LinkedList<File>(); LinkedList<File> chunkFiles = new LinkedList<>();
LinkedList<String> chunk = new LinkedList<String>(); LinkedList<String> chunk;
do{ do{
chunk = readChunk(in); chunk = readChunk(in);
@ -227,13 +226,11 @@ public class ExternalSort {
/** /**
* Reads in a chunk of rows into a LinkedList * Reads in a chunk of rows into a LinkedList
* *
* @param list The list to populate
* @param in The BufferedReader to read from * @param in The BufferedReader to read from
* @return The LinkeList with the chunk * @return a LinkedList with the chunks
* @throws IOException Some kind of error
*/ */
private LinkedList<String> readChunk(BufferedReader in) throws IOException{ private LinkedList<String> readChunk(BufferedReader in) throws IOException{
LinkedList<String> list = new LinkedList<String>(); LinkedList<String> list = new LinkedList<>();
String tmp; String tmp;
for(int i=0; i<CHUNK_SIZE ;i++){ for(int i=0; i<CHUNK_SIZE ;i++){
tmp = in.readLine(); tmp = in.readLine();
@ -252,18 +249,16 @@ public class ExternalSort {
*/ */
private void writeChunk(LinkedList<String> list, File file) throws IOException{ private void writeChunk(LinkedList<String> list, File file) throws IOException{
BufferedWriter out = new BufferedWriter(new FileWriter(file)); BufferedWriter out = new BufferedWriter(new FileWriter(file));
Iterator<String> it = list.iterator(); for (String str : list) {
while(it.hasNext()){ out.write(str);
out.write(it.next());
out.newLine(); out.newLine();
} }
out.close(); out.close();
} }
private void removeFiles(LinkedList<File> list){ private void removeFiles(LinkedList<File> list){
Iterator<File> it = list.iterator(); for (File file : list) {
while(it.hasNext()){ file.delete();
it.next().delete();
} }
} }
} }

View file

@ -73,9 +73,7 @@ public class MergeSort{
int length = pivot-start; int length = pivot-start;
int[] tmp = new int[stop-start]; int[] tmp = new int[stop-start];
for(int i=0; i<tmp.length ;++i){ System.arraycopy(list, start + 0, tmp, 0, tmp.length);
tmp[i] = list[start+i];
}
int index1 = 0; int index1 = 0;
int index2 = length; int index2 = length;
@ -127,7 +125,6 @@ public class MergeSort{
* This method is the merger, after the array * This method is the merger, after the array
* has been split this method will merge the * has been split this method will merge the
* two parts of the array and sort it. * two parts of the array and sort it.
* @param <T>
* *
* @param list is the list to merge * @param list is the list to merge
* @param start is the start of the first sublist * @param start is the start of the first sublist

View file

@ -87,7 +87,7 @@ public abstract class AbstractChart extends JPanel{
* *
* @param x is the x data value * @param x is the x data value
* @param scale is the data scale * @param scale is the data scale
* @param bound is the drawing boundds * @param bound is the drawing bounds
* @return a x pixel coordinate * @return a x pixel coordinate
*/ */
static protected double getXCoordinate(double x, double scale, Rectangle bound){ static protected double getXCoordinate(double x, double scale, Rectangle bound){
@ -99,7 +99,7 @@ public abstract class AbstractChart extends JPanel{
* *
* @param y is the y data value * @param y is the y data value
* @param scale is the data scale * @param scale is the data scale
* @param bound is the drawing boundds * @param bound is the drawing bounds
* @return a y pixel coordinate * @return a y pixel coordinate
*/ */
static protected double getYCoordinate(double y, double scale, Rectangle bound){ static protected double getYCoordinate(double y, double scale, Rectangle bound){

View file

@ -42,10 +42,10 @@ public class ChartData {
public ChartData(){ public ChartData(){
xStrings = new HashMap<Integer,String>(); xStrings = new HashMap<>();
yStrings = new HashMap<Integer,String>(); yStrings = new HashMap<>();
points = new ArrayList<Point>(); points = new ArrayList<>();
} }
public void setXValueString(int x, String name){ public void setXValueString(int x, String name){

View file

@ -205,7 +205,7 @@ public class Converter {
* @return a hex String * @return a hex String
*/ */
public static String toHexString(byte[][] raw){ public static String toHexString(byte[][] raw){
StringBuffer ret = new StringBuffer(); StringBuilder ret = new StringBuilder();
for(byte[] a : raw){ for(byte[] a : raw){
for(byte b : a){ for(byte b : a){
@ -218,7 +218,7 @@ public class Converter {
} }
public static String toHexStringByColumn(byte[][] raw){ public static String toHexStringByColumn(byte[][] raw){
StringBuffer ret = new StringBuffer(); StringBuilder ret = new StringBuilder();
for(int col=0; col<raw[0].length ;col++){ for(int col=0; col<raw[0].length ;col++){
for(int row=0; row<raw.length ;row++){ for(int row=0; row<raw.length ;row++){
@ -237,7 +237,7 @@ public class Converter {
* @return a hex String * @return a hex String
*/ */
public static String toHexString(byte[] raw){ public static String toHexString(byte[] raw){
StringBuffer ret = new StringBuffer(); StringBuilder ret = new StringBuilder();
for(byte b : raw){ for(byte b : raw){
ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]); ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]);
@ -267,8 +267,8 @@ public class Converter {
* @return a String with 1's and 0's * @return a String with 1's and 0's
*/ */
public static String toString(byte raw){ public static String toString(byte raw){
StringBuffer ret = new StringBuffer(); StringBuilder ret = new StringBuilder();
for(int i=128; i>0 ;i=( i<1 ? i=0 : i/2 ) ){ for(int i=128; i>0 ;i=( i<1 ? 0 : i/2 ) ){
ret.append(( (raw & i) == 0 ? '0' : '1')); ret.append(( (raw & i) == 0 ? '0' : '1'));
} }
return ret.toString(); return ret.toString();
@ -281,9 +281,9 @@ public class Converter {
* @return a String with 1's and 0's * @return a String with 1's and 0's
*/ */
public static String toString(byte[] raw){ public static String toString(byte[] raw){
StringBuffer ret = new StringBuffer(); StringBuilder ret = new StringBuilder();
for(byte b : raw){ for(byte b : raw){
for(int i=128; i>0 ;i=( i<1 ? i=0 : i/2 ) ){ for(int i=128; i>0 ;i=( i<1 ? 0 : i/2 ) ){
ret.append(( (b & i) == 0 ? '0' : '1')); ret.append(( (b & i) == 0 ? '0' : '1'));
} }
} }
@ -419,8 +419,8 @@ public class Converter {
else if(c == float.class) return (T) new Float(data); else if(c == float.class) return (T) new Float(data);
else if(c == Double.class) return (T) new Double(data); else if(c == Double.class) return (T) new Double(data);
else if(c == double.class) return (T) new Double(data); else if(c == double.class) return (T) new Double(data);
else if(c == Boolean.class) return (T) new Boolean(data); else if(c == Boolean.class) return (T) Boolean.valueOf(data);
else if(c == boolean.class) return (T) new Boolean(data); else if(c == boolean.class) return (T) Boolean.valueOf(data);
else if(c == Byte.class) return (T) new Byte(data); else if(c == Byte.class) return (T) new Byte(data);
else if(c == byte.class) return (T) new Byte(data); else if(c == byte.class) return (T) new Byte(data);
else if(byte[].class.isAssignableFrom(c)) else if(byte[].class.isAssignableFrom(c))

View file

@ -38,39 +38,39 @@ public class NumberToWordsConverter {
private static final HashMap<Long, String> NUMERIC_STRINGS; private static final HashMap<Long, String> NUMERIC_STRINGS;
static{ static{
NUMERIC_STRINGS = new HashMap<>(); NUMERIC_STRINGS = new HashMap<>();
NUMERIC_STRINGS.put(1l, "one"); NUMERIC_STRINGS.put(1L, "one");
NUMERIC_STRINGS.put(2l, "two"); NUMERIC_STRINGS.put(2L, "two");
NUMERIC_STRINGS.put(3l, "three"); NUMERIC_STRINGS.put(3L, "three");
NUMERIC_STRINGS.put(4l, "four"); NUMERIC_STRINGS.put(4L, "four");
NUMERIC_STRINGS.put(5l, "five"); NUMERIC_STRINGS.put(5L, "five");
NUMERIC_STRINGS.put(6l, "six"); NUMERIC_STRINGS.put(6L, "six");
NUMERIC_STRINGS.put(7l, "seven"); NUMERIC_STRINGS.put(7L, "seven");
NUMERIC_STRINGS.put(8l, "eight"); NUMERIC_STRINGS.put(8L, "eight");
NUMERIC_STRINGS.put(9l, "nine"); NUMERIC_STRINGS.put(9L, "nine");
NUMERIC_STRINGS.put(10l, "ten"); NUMERIC_STRINGS.put(10L, "ten");
NUMERIC_STRINGS.put(11l, "eleven"); NUMERIC_STRINGS.put(11L, "eleven");
NUMERIC_STRINGS.put(12l, "twelve"); NUMERIC_STRINGS.put(12L, "twelve");
NUMERIC_STRINGS.put(13l, "thirteen"); NUMERIC_STRINGS.put(13L, "thirteen");
NUMERIC_STRINGS.put(14l, "fourteen"); NUMERIC_STRINGS.put(14L, "fourteen");
NUMERIC_STRINGS.put(15l, "fifteen"); NUMERIC_STRINGS.put(15L, "fifteen");
NUMERIC_STRINGS.put(16l, "sixteen"); NUMERIC_STRINGS.put(16L, "sixteen");
NUMERIC_STRINGS.put(17l, "seventeen"); NUMERIC_STRINGS.put(17L, "seventeen");
NUMERIC_STRINGS.put(18l, "eightteen"); NUMERIC_STRINGS.put(18L, "eightteen");
NUMERIC_STRINGS.put(19l, "nineteen"); NUMERIC_STRINGS.put(19L, "nineteen");
NUMERIC_STRINGS.put(20l, "twenty"); NUMERIC_STRINGS.put(20L, "twenty");
NUMERIC_STRINGS.put(30l, "thirty"); NUMERIC_STRINGS.put(30L, "thirty");
NUMERIC_STRINGS.put(40l, "forty"); NUMERIC_STRINGS.put(40L, "forty");
NUMERIC_STRINGS.put(50l, "fifty"); NUMERIC_STRINGS.put(50L, "fifty");
NUMERIC_STRINGS.put(60l, "sixty"); NUMERIC_STRINGS.put(60L, "sixty");
NUMERIC_STRINGS.put(70l, "seventy"); NUMERIC_STRINGS.put(70L, "seventy");
NUMERIC_STRINGS.put(80l, "eighty"); NUMERIC_STRINGS.put(80L, "eighty");
NUMERIC_STRINGS.put(90l, "ninety"); NUMERIC_STRINGS.put(90L, "ninety");
NUMERIC_STRINGS.put(100l, "hundred"); NUMERIC_STRINGS.put(100L, "hundred");
NUMERIC_STRINGS.put(1_000l, "thousand"); NUMERIC_STRINGS.put(1_000L, "thousand");
NUMERIC_STRINGS.put(1000_000l, "million"); NUMERIC_STRINGS.put(1000_000L, "million");
NUMERIC_STRINGS.put(1000_000_000l, "billion"); NUMERIC_STRINGS.put(1000_000_000L, "billion");
} }

View file

@ -56,7 +56,7 @@ public class WGS84Converter {
} }
} }
// 3444.0000S 13521.0000E // 3444.0000S 13521.0000E
else if(coordinate.matches("[0-9]{4,5}.[0-9]*[NSEW]{1}")){ else if(coordinate.matches("[0-9]{4,5}.[0-9]*[NSEW]")){
coordinate = coordinate.replaceAll("[NS EW]", ""); coordinate = coordinate.replaceAll("[NS EW]", "");
float tmpf = Float.parseFloat(coordinate); float tmpf = Float.parseFloat(coordinate);
deg = (int)(tmpf/100); deg = (int)(tmpf/100);

View file

@ -129,7 +129,7 @@ public class DBConnection implements Closeable{
*/ */
public long getLastInsertID(){ public long getLastInsertID(){
try{ try{
return exec("SELECT LAST_INSERT_ID()", new SimpleSQLResult<Long>()); return exec("SELECT LAST_INSERT_ID()", new SimpleSQLResult<>());
}catch(SQLException e){ }catch(SQLException e){
logger.log(Level.WARNING, null, e); logger.log(Level.WARNING, null, e);
} }
@ -212,7 +212,6 @@ public class DBConnection implements Closeable{
/** /**
* Executes an query and cleans up after itself. * Executes an query and cleans up after itself.
* *
* @param <T>
* @param query is the query * @param query is the query
* @param handler is the result handler * @param handler is the result handler
* @return update count or -1 if the query is not an update query * @return update count or -1 if the query is not an update query
@ -229,7 +228,7 @@ public class DBConnection implements Closeable{
* @param handler is the result handler that will be called with the output of the execution * @param handler is the result handler that will be called with the output of the execution
* @return the object from the handler * @return the object from the handler
*/ */
public static <T> T exec(PreparedStatement stmt, SQLResultHandler<T> handler) throws SQLException { public static <T> T exec(PreparedStatement stmt, SQLResultHandler<T> handler) {
try{ try{
// Execute // Execute
boolean isResultSet = stmt.execute(); boolean isResultSet = stmt.execute();
@ -253,7 +252,6 @@ public class DBConnection implements Closeable{
} catch (SQLException e) { } catch (SQLException e) {
logger.log(Level.WARNING, null, e); logger.log(Level.WARNING, null, e);
} }
result = null;
} }
} }
} }
@ -267,7 +265,6 @@ public class DBConnection implements Closeable{
} catch (SQLException e) { } catch (SQLException e) {
logger.log(Level.WARNING, null, e); logger.log(Level.WARNING, null, e);
} }
stmt = null;
} }
} }
return null; return null;
@ -293,7 +290,6 @@ public class DBConnection implements Closeable{
} catch (SQLException e) { } catch (SQLException e) {
logger.log(Level.WARNING, null, e); logger.log(Level.WARNING, null, e);
} }
stmt = null;
} }
} }
return new int[0]; return new int[0];

View file

@ -33,7 +33,7 @@ import java.util.TimerTask;
/** /**
* This class is an connection pool * This class is an connection pool
* *
* @author Ziver * @author Ziver
*/ */
public class DBConnectionPool extends TimerTask implements Closeable{ public class DBConnectionPool extends TimerTask implements Closeable{
@ -74,15 +74,15 @@ public class DBConnectionPool extends TimerTask implements Closeable{
* @param user is the user name to the DB * @param user is the user name to the DB
* @param password is the password to the DB * @param password is the password to the DB
*/ */
public DBConnectionPool(DBMS dbms, String url, String db, String user, String password) throws Exception{ public DBConnectionPool(DBMS dbms, String url, String db, String user, String password) {
this.dbms = dbms; this.dbms = dbms;
this.url = url; this.url = url;
this.db = db; this.db = db;
this.user = user; this.user = user;
this.password = password; this.password = password;
inusePool = new LinkedList<PoolItem>(); inusePool = new LinkedList<>();
readyPool = new LinkedList<PoolItem>(); readyPool = new LinkedList<>();
this.setTimeout(DEFAULT_TIMEOUT); this.setTimeout(DEFAULT_TIMEOUT);
this.setMaxSize(DEFAULT_MAX_SIZE); this.setMaxSize(DEFAULT_MAX_SIZE);

View file

@ -87,7 +87,7 @@ public class DBUpgradeHandler {
* But if forced upgrade is set to true then the upgrade handler will * But if forced upgrade is set to true then the upgrade handler will
* create a new table and migrate the data from the old one to the new table. * create a new table and migrate the data from the old one to the new table.
* *
* @param enable * @param enable true to enable forced upgrade
*/ */
public void setForcedDBUpgrade(boolean enable){ public void setForcedDBUpgrade(boolean enable){
this.forceUpgradeEnabled = enable; this.forceUpgradeEnabled = enable;
@ -240,7 +240,7 @@ public class DBUpgradeHandler {
private List<String> getTableList(DBConnection db) throws SQLException { private List<String> getTableList(DBConnection db) throws SQLException {
return db.exec("SELECT name FROM sqlite_master WHERE type='table';", new SQLResultHandler<List<String>>() { return db.exec("SELECT name FROM sqlite_master WHERE type='table';", new SQLResultHandler<List<String>>() {
public List<String> handleQueryResult(Statement stmt, ResultSet result) throws SQLException { public List<String> handleQueryResult(Statement stmt, ResultSet result) throws SQLException {
ArrayList<String> list = new ArrayList<String>(); ArrayList<String> list = new ArrayList<>();
while( result.next() ) { while( result.next() ) {
String table = result.getString(1); String table = result.getString(1);
if(!ignoredTablesSet.contains(table)) if(!ignoredTablesSet.contains(table))
@ -253,7 +253,7 @@ public class DBUpgradeHandler {
private static String getTableSql(DBConnection db, String table) throws SQLException { private static String getTableSql(DBConnection db, String table) throws SQLException {
PreparedStatement stmt = db.getPreparedStatement("SELECT sql FROM sqlite_master WHERE name == ?"); PreparedStatement stmt = db.getPreparedStatement("SELECT sql FROM sqlite_master WHERE name == ?");
stmt.setString(1, table); stmt.setString(1, table);
return DBConnection.exec(stmt, new SimpleSQLResult<String>()); return DBConnection.exec(stmt, new SimpleSQLResult<>());
} }
private static List<DBColumn> getColumnList(DBConnection db, String table) throws SQLException { private static List<DBColumn> getColumnList(DBConnection db, String table) throws SQLException {
return db.exec( return db.exec(

View file

@ -24,11 +24,12 @@
package zutil.db; package zutil.db;
import java.util.Collections;
import java.util.LinkedList; import java.util.LinkedList;
/** /**
* A class that generates a query by objects, minimizes errors * A class that generates a query by objects, minimizes errors
* *
* @author Ziver * @author Ziver
*/ */
public class SQLQuery { public class SQLQuery {
@ -157,13 +158,12 @@ public class SQLQuery {
//******************************************* //*******************************************
// Sub Types // Sub Types
public static class SQLFrom extends SQLQueryItem{ public static class SQLFrom extends SQLQueryItem{
LinkedList<String> tables = new LinkedList<String>(); LinkedList<String> tables = new LinkedList<>();
SQLQueryItem next; SQLQueryItem next;
protected SQLFrom(SQLQueryItem root, String ...tables){ protected SQLFrom(SQLQueryItem root, String ...tables){
setRoot(root); setRoot(root);
for( String table : tables ) Collections.addAll(this.tables, tables);
this.tables.add(table);
} }
public SQLFrom NATURAL_JOIN(String table){ public SQLFrom NATURAL_JOIN(String table){
@ -190,8 +190,7 @@ public class SQLQuery {
private SQLFrom joinLastTable(String type, String table){ private SQLFrom joinLastTable(String type, String table){
String last = tables.getLast(); String last = tables.getLast();
tables.removeLast(); tables.removeLast();
tables.add( tables.add(last + " " + type + " " + table);
new StringBuilder(last).append(" ").append(type).append(" ").append(table).toString());
return this; return this;
} }
@ -238,7 +237,7 @@ public class SQLQuery {
//******************************************* //*******************************************
// Condition Types // Condition Types
public static class SQLWhere extends SQLQueryItem{ public static class SQLWhere extends SQLQueryItem{
LinkedList<String> conds = new LinkedList<String>(); LinkedList<String> conds = new LinkedList<>();
SQLQueryItem next; SQLQueryItem next;
protected SQLWhere(SQLQueryItem root){ protected SQLWhere(SQLQueryItem root){
@ -283,9 +282,7 @@ public class SQLQuery {
} }
private SQLWhere cond(String cond, String arg1, String arg2){ private SQLWhere cond(String cond, String arg1, String arg2){
conds.add( conds.add(arg1 + cond + arg2);
//new StringBuilder(arg1).append(cond).append('\"').append(arg2).append('\"').toString());
new StringBuilder(arg1).append(cond).append(arg2).toString());
return this; return this;
} }

View file

@ -35,5 +35,5 @@ public interface SQLResultHandler<T> {
* @param stmt is the query * @param stmt is the query
* @param result is the ResultSet * @param result is the ResultSet
*/ */
public T handleQueryResult(Statement stmt, ResultSet result) throws SQLException; T handleQueryResult(Statement stmt, ResultSet result) throws SQLException;
} }

View file

@ -42,12 +42,12 @@ import java.util.List;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger; import java.util.logging.Logger;
/** /**
* The class that extends this will be able to save its state to a database. * The class that extends this will be able to save its state to a database.
* Fields that are transient will be ignored, and fields that extend * Fields that are transient will be ignored, and fields that extend
* DBBean will be replaced with the an id which corresponds to the field * DBBean will be replaced with the an id which corresponds to the field
* of that object. * of that object.
* *
* <XMP> * <XMP>
* Supported fields: * Supported fields:
* *Boolean * *Boolean
@ -335,8 +335,7 @@ public abstract class DBBean {
logger.finest("Load all Beans("+c.getName()+") query: "+sql); logger.finest("Load all Beans("+c.getName()+") query: "+sql);
PreparedStatement stmt = db.getPreparedStatement( sql ); PreparedStatement stmt = db.getPreparedStatement( sql );
// Run query // Run query
List<T> list = DBConnection.exec(stmt, DBBeanSQLResultHandler.createList(c, db) ); return DBConnection.exec(stmt, DBBeanSQLResultHandler.createList(c, db) );
return list;
} }
/** /**
@ -369,7 +368,7 @@ public abstract class DBBean {
// Generate the SQL // Generate the SQL
StringBuilder query = new StringBuilder(); StringBuilder query = new StringBuilder();
query.append("CREATE TABLE "+config.getTableName()+" ( "); query.append("CREATE TABLE ").append(config.getTableName()).append(" ( ");
// ID // ID
query.append(" ").append(config.getIdColumnName()).append(" "); query.append(" ").append(config.getIdColumnName()).append(" ");

View file

@ -126,8 +126,7 @@ class DBBeanCache {
public static DBBean get(Class<?> c, Long id) { public static DBBean get(Class<?> c, Long id) {
if(contains(c, id)){ if(contains(c, id)){
CacheItem cacheItem = cache.get(c).get(id); CacheItem cacheItem = cache.get(c).get(id);
DBBean bean = cacheItem.bean.get(); return cacheItem.bean.get();
return bean;
} }
logger.finer("Bean("+c.getName()+") cache miss for id: "+id); logger.finer("Bean("+c.getName()+") cache miss for id: "+id);
return null; return null;

View file

@ -164,7 +164,7 @@ class DBBeanConfig{
else if (field.getType() == Character.TYPE) field.setChar(obj, (char) 0); else if (field.getType() == Character.TYPE) field.setChar(obj, (char) 0);
else if (field.getType() == Byte.TYPE) field.setByte(obj, (byte) 0); else if (field.getType() == Byte.TYPE) field.setByte(obj, (byte) 0);
else if (field.getType() == Short.TYPE) field.setShort(obj, (short) 0); else if (field.getType() == Short.TYPE) field.setShort(obj, (short) 0);
else if (field.getType() == Long.TYPE) field.setLong(obj, 0l); else if (field.getType() == Long.TYPE) field.setLong(obj, 0L);
else if (field.getType() == Float.TYPE) field.setFloat(obj, 0f); else if (field.getType() == Float.TYPE) field.setFloat(obj, 0f);
else if (field.getType() == Double.TYPE) field.setDouble(obj, 0d); else if (field.getType() == Double.TYPE) field.setDouble(obj, 0d);
else if (field.getType() == Boolean.TYPE) field.setBoolean(obj, false); else if (field.getType() == Boolean.TYPE) field.setBoolean(obj, false);

View file

@ -30,10 +30,10 @@ import java.awt.image.BufferedImage;
/** /**
* This is a abstract class for all the effects * This is a abstract class for all the effects
* *
* Inspiration: * Inspiration:
* http://www.dickbaldwin.com/tocadv.htm * http://www.dickbaldwin.com/tocadv.htm
* *
* @author Ziver * @author Ziver
*/ */
public abstract class ImageFilterProcessor { public abstract class ImageFilterProcessor {
@ -73,7 +73,7 @@ public abstract class ImageFilterProcessor {
* @param img The image to process * @param img The image to process
* @return The processed image * @return The processed image
*/ */
public static ImageFilterProcessor getProcessor(String effect, BufferedImage img) throws InstantiationException, IllegalAccessException, ClassNotFoundException, InterruptedException{ public static ImageFilterProcessor getProcessor(String effect, BufferedImage img) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
ImageFilterProcessor processor = (ImageFilterProcessor)Class.forName(effect).newInstance(); ImageFilterProcessor processor = (ImageFilterProcessor)Class.forName(effect).newInstance();
processor.img = img; processor.img = img;
return processor; return processor;

View file

@ -127,8 +127,7 @@ public class RAWImageUtil {
} }
} }
int meanSquare = (int)(accum/pixelCount); int meanSquare = (int)(accum/pixelCount);
int rms = (int)(Math.sqrt(meanSquare)); return (int)(Math.sqrt(meanSquare));
return rms;
} }
/** /**

View file

@ -33,7 +33,7 @@ import java.awt.image.BufferedImage;
/** /**
* The MedianFilter is used for noise reduction and things * The MedianFilter is used for noise reduction and things
* *
* @author Ziver * @author Ziver
*/ */
public class MedianFilter extends ImageFilterProcessor{ public class MedianFilter extends ImageFilterProcessor{
@ -92,7 +92,7 @@ public class MedianFilter extends ImageFilterProcessor{
int edgeY = windowSize / 2; int edgeY = windowSize / 2;
int[][] tmpArray = new int[4][256*2]; int[][] tmpArray = new int[4][256*2];
int pixelCount = 0; int pixelCount;
for(int y=startY; y<stopY ;y++){ for(int y=startY; y<stopY ;y++){
setProgress(ZMath.percent(0, stopY-startY-1, y)); setProgress(ZMath.percent(0, stopY-startY-1, y));
for(int x=startX; x<stopX ;x++){ for(int x=startX; x<stopX ;x++){

View file

@ -33,8 +33,6 @@ public class ResizeImage extends ImageFilterProcessor{
private int width; private int width;
private int height; private int height;
private int[][][] newData;
/** /**
* Will create a ResizeImage object and fix the height with the aspect * Will create a ResizeImage object and fix the height with the aspect
* of the width * of the width
@ -68,7 +66,7 @@ public class ResizeImage extends ImageFilterProcessor{
width = (int)(((double)height/(stopY-startY))*(stopX-startY)); width = (int)(((double)height/(stopY-startY))*(stopX-startY));
} }
newData = new int[height][width][4]; int[][][] newData = new int[height][width][4];
double xScale = ((double)(stopX-startX)/width); double xScale = ((double)(stopX-startX)/width);
double yScale = ((double)(stopY-startY)/height); double yScale = ((double)(stopY-startY)/height);

View file

@ -32,7 +32,7 @@ import java.io.RandomAccessFile;
* This class is a buffer for the RandomeAccesFile * This class is a buffer for the RandomeAccesFile
* Inspiration: * Inspiration:
* http://www.javaworld.com/javaworld/javatips/jw-javatip26.html * http://www.javaworld.com/javaworld/javatips/jw-javatip26.html
* *
* @author Ziver * @author Ziver
*/ */
public class BufferedRandomAccessFile extends RandomAccessFile{ public class BufferedRandomAccessFile extends RandomAccessFile{
@ -76,7 +76,6 @@ public class BufferedRandomAccessFile extends RandomAccessFile{
* @param filename is the file to read from * @param filename is the file to read from
* @param mode as in {@link java.io.RandomAccessFile#RandomAccessFile(File file, String mode)} * @param mode as in {@link java.io.RandomAccessFile#RandomAccessFile(File file, String mode)}
* @param bufsize is the buffer size in bytes * @param bufsize is the buffer size in bytes
* @throws IOException
*/ */
public BufferedRandomAccessFile(String filename, String mode, int bufsize) throws IOException{ public BufferedRandomAccessFile(String filename, String mode, int bufsize) throws IOException{
this(new File(filename), mode, bufsize); this(new File(filename), mode, bufsize);
@ -88,7 +87,6 @@ public class BufferedRandomAccessFile extends RandomAccessFile{
* @param file is the file to read from * @param file is the file to read from
* @param mode as in {@link java.io.RandomAccessFile#RandomAccessFile(File file, String mode)} * @param mode as in {@link java.io.RandomAccessFile#RandomAccessFile(File file, String mode)}
* @param bufsize is the buffer size in bytes * @param bufsize is the buffer size in bytes
* @throws IOException
*/ */
public BufferedRandomAccessFile(File file, String mode, int bufsize) throws IOException{ public BufferedRandomAccessFile(File file, String mode, int bufsize) throws IOException{
super(file,mode); super(file,mode);
@ -101,7 +99,6 @@ public class BufferedRandomAccessFile extends RandomAccessFile{
* Reads in data from the file to the buffer * Reads in data from the file to the buffer
* *
* @return the buffer * @return the buffer
* @throws IOException
*/ */
private int fillBuffer() throws IOException { private int fillBuffer() throws IOException {
int n = super.read(buffer, 0, BUF_SIZE ); int n = super.read(buffer, 0, BUF_SIZE );
@ -115,8 +112,6 @@ public class BufferedRandomAccessFile extends RandomAccessFile{
/** /**
* Resets the buffer * Resets the buffer
*
* @throws IOException
*/ */
private void invalidate() throws IOException { private void invalidate() throws IOException {
buf_end = 0; buf_end = 0;
@ -192,7 +187,7 @@ public class BufferedRandomAccessFile extends RandomAccessFile{
/** /**
* @return the file pointer in the file * @return the file pointer in the file
*/ */
public long getFilePointer() throws IOException{ public long getFilePointer() {
long l = file_pos; long l = file_pos;
return (l - buf_end + buf_pos) ; return (l - buf_end + buf_pos) ;
} }
@ -218,21 +213,21 @@ public class BufferedRandomAccessFile extends RandomAccessFile{
* @return the next line in the file * @return the next line in the file
*/ */
public final String readNextLine() throws IOException { public final String readNextLine() throws IOException {
String str = null; String str;
if(buf_end-buf_pos <= 0) { if(buf_end-buf_pos <= 0) {
if(fillBuffer() < 0) { if(fillBuffer() < 0) {
throw new IOException("Error filling buffer!"); throw new IOException("Error filling buffer!");
} }
} }
int lineend = -1; int lineEnd = -1;
for(int i = buf_pos; i < buf_end; i++) { for(int i = buf_pos; i < buf_end; i++) {
if(buffer[i] == '\n') { if(buffer[i] == '\n') {
lineend = i; lineEnd = i;
break; break;
} }
} }
if(lineend < 0) { if(lineEnd < 0) {
StringBuffer input = new StringBuffer(256); StringBuilder input = new StringBuilder(256);
int c; int c;
while (((c = read()) != -1) && (c != '\n')) { while (((c = read()) != -1) && (c != '\n')) {
input.append((char)c); input.append((char)c);
@ -243,13 +238,13 @@ public class BufferedRandomAccessFile extends RandomAccessFile{
return input.toString(); return input.toString();
} }
if(lineend > 0 && buffer[lineend-1] == '\r'){ if(lineEnd > 0 && buffer[lineEnd-1] == '\r'){
str = new String(buffer, buf_pos, lineend - buf_pos -1); str = new String(buffer, buf_pos, lineEnd - buf_pos -1);
} }
else { else {
str = new String(buffer, buf_pos, lineend - buf_pos); str = new String(buffer, buf_pos, lineEnd - buf_pos);
} }
buf_pos = lineend +1; buf_pos = lineEnd +1;
return str; return str;
} }

View file

@ -45,7 +45,7 @@ public class DynamicByteArrayStream extends InputStream{
* Create a new instance of DynamicByteArrayStream * Create a new instance of DynamicByteArrayStream
*/ */
public DynamicByteArrayStream(){ public DynamicByteArrayStream(){
bytes = new ArrayList<byte[]>(); bytes = new ArrayList<>();
globalPos = 0; globalPos = 0;
globalSize = 0; globalSize = 0;
globalArrayIndex = 0; globalArrayIndex = 0;
@ -78,7 +78,7 @@ public class DynamicByteArrayStream extends InputStream{
} }
@Override @Override
public synchronized int read() throws IOException { public synchronized int read() {
if(globalPos >= globalSize) return -1; if(globalPos >= globalSize) return -1;
int ret = bytes.get(globalArrayIndex)[localArrayOffset] & 0xff; int ret = bytes.get(globalArrayIndex)[localArrayOffset] & 0xff;

View file

@ -28,7 +28,7 @@ import java.io.*;
/** /**
* Utility class for streams and general IO stuff * Utility class for streams and general IO stuff
* *
* @author Ziver * @author Ziver
* *
*/ */
@ -38,7 +38,6 @@ public class IOUtil {
* Reads and returns all the content of a stream. * Reads and returns all the content of a stream.
* The InputStream will not be closed * The InputStream will not be closed
* *
* @param stream
* @return a byte array with the stream contents * @return a byte array with the stream contents
*/ */
public static byte[] readContent(InputStream stream) throws IOException{ public static byte[] readContent(InputStream stream) throws IOException{
@ -48,14 +47,13 @@ public class IOUtil {
/** /**
* Reads and returns all the content of a stream. * Reads and returns all the content of a stream.
* *
* @param stream
* @param close true if the stream should be closed at the end * @param close true if the stream should be closed at the end
* @return a byte array with the stream contents * @return a byte array with the stream contents
*/ */
public static byte[] readContent(InputStream stream, boolean close) throws IOException{ public static byte[] readContent(InputStream stream, boolean close) throws IOException{
DynamicByteArrayStream dyn_buff = new DynamicByteArrayStream(); DynamicByteArrayStream dyn_buff = new DynamicByteArrayStream();
byte[] buff = new byte[8192]; byte[] buff = new byte[8192];
int len = 0; int len;
while((len = stream.read(buff)) != -1){ while((len = stream.read(buff)) != -1){
dyn_buff.append(buff, 0, len); dyn_buff.append(buff, 0, len);
} }
@ -68,7 +66,6 @@ public class IOUtil {
* Reads and returns all the content of a stream as a String. * Reads and returns all the content of a stream as a String.
* The InputStream will not be closed * The InputStream will not be closed
* *
* @param stream
* @return a String with the content of the stream * @return a String with the content of the stream
*/ */
public static String readContentAsString(InputStream stream) throws IOException{ public static String readContentAsString(InputStream stream) throws IOException{
@ -77,7 +74,6 @@ public class IOUtil {
/** /**
* Reads and returns all the content of a stream as a String. * Reads and returns all the content of a stream as a String.
* *
* @param stream
* @param close true if the stream should be closed at the end * @param close true if the stream should be closed at the end
* @return a String with the content of the stream * @return a String with the content of the stream
*/ */
@ -89,7 +85,6 @@ public class IOUtil {
* Reads and returns all the content of a stream as a String. * Reads and returns all the content of a stream as a String.
* The Reader will not be closed * The Reader will not be closed
* *
* @param reader
* @return a String with the content of the stream * @return a String with the content of the stream
*/ */
public static String readContentAsString(Reader reader) throws IOException{ public static String readContentAsString(Reader reader) throws IOException{
@ -98,13 +93,12 @@ public class IOUtil {
/** /**
* Reads and returns all the content of a stream as a String. * Reads and returns all the content of a stream as a String.
* *
* @param reader
* @param close true if the stream should be closed at the end * @param close true if the stream should be closed at the end
* @return a String with the content of the stream * @return a String with the content of the stream
*/ */
public static String readContentAsString(Reader reader, boolean close) throws IOException{ public static String readContentAsString(Reader reader, boolean close) throws IOException{
StringBuilder str = new StringBuilder(); StringBuilder str = new StringBuilder();
BufferedReader in = null; BufferedReader in;
if(reader instanceof BufferedReader) if(reader instanceof BufferedReader)
in = (BufferedReader) reader; in = (BufferedReader) reader;
else else
@ -131,7 +125,7 @@ public class IOUtil {
*/ */
public static String readLine(InputStream in) throws IOException { public static String readLine(InputStream in) throws IOException {
StringBuilder str = new StringBuilder(80); StringBuilder str = new StringBuilder(80);
int c = 0; int c;
while ((c=in.read()) >= 0 && (c != '\n') && (c != '\r')) while ((c=in.read()) >= 0 && (c != '\n') && (c != '\r'))
str.append((char)c); str.append((char)c);
if (c == '\r') if (c == '\r')
@ -150,7 +144,7 @@ public class IOUtil {
*/ */
public static String readLine(Reader in) throws IOException { public static String readLine(Reader in) throws IOException {
StringBuilder str = new StringBuilder(80); StringBuilder str = new StringBuilder(80);
int c = 0; int c;
while ((c=in.read()) >= 0 && (c != '\n') && (c != '\r')) while ((c=in.read()) >= 0 && (c != '\n') && (c != '\r'))
str.append((char)c); str.append((char)c);
if (c == '\r') if (c == '\r')

View file

@ -31,10 +31,7 @@ import java.io.*;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.ArrayList; import java.util.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/** /**
* @author Ziver * @author Ziver
@ -48,7 +45,7 @@ public class MultiPrintStream extends PrintStream {
public MultiPrintStream(){ public MultiPrintStream(){
super(new PrintStream(System.out)); super(new PrintStream(System.out));
streams = new ArrayList<PrintStream>(); streams = new ArrayList<>();
streams.add(new PrintStream(System.out)); streams.add(new PrintStream(System.out));
} }
@ -59,7 +56,7 @@ public class MultiPrintStream extends PrintStream {
public MultiPrintStream(String file){ public MultiPrintStream(String file){
super(new PrintStream(System.out)); super(new PrintStream(System.out));
try { try {
streams = new ArrayList<PrintStream>(); streams = new ArrayList<>();
streams.add(new PrintStream(System.out)); streams.add(new PrintStream(System.out));
streams.add(new PrintStream(new File(file))); streams.add(new PrintStream(new File(file)));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
@ -74,10 +71,8 @@ public class MultiPrintStream extends PrintStream {
*/ */
public MultiPrintStream(PrintStream[] streams){ public MultiPrintStream(PrintStream[] streams){
super(streams[0]); super(streams[0]);
this.streams = new ArrayList<PrintStream>(); this.streams = new ArrayList<>();
for(int i=0; i<streams.length ;i++){ Collections.addAll(this.streams, streams);
this.streams.add(streams[i]);
}
} }
/** /**
@ -238,7 +233,7 @@ public class MultiPrintStream extends PrintStream {
private static String dumpToString(Object o , String head, int depth) { private static String dumpToString(Object o , String head, int depth) {
if(o == null) if(o == null)
return "NULL"; return "NULL";
StringBuffer buffer = new StringBuffer(); StringBuilder buffer = new StringBuilder();
Class<?> oClass = o.getClass(); Class<?> oClass = o.getClass();
buffer.append( oClass.getName() ); buffer.append( oClass.getName() );
String nextHead = head + "\t"; String nextHead = head + "\t";

View file

@ -1,6 +1,5 @@
package zutil.io; package zutil.io;
import java.io.IOException;
import java.io.Writer; import java.io.Writer;
/** /**
@ -17,7 +16,7 @@ public class NullWriter extends Writer{
@Override @Override
public void write(char cbuf[], int off, int len) { } public void write(char cbuf[], int off, int len) { }
@Override @Override
public void write(String str) throws IOException { } public void write(String str) { }
@Override @Override
public void write(String str, int off, int len) { } public void write(String str, int off, int len) { }
@ -37,5 +36,5 @@ public class NullWriter extends Writer{
@Override @Override
public void flush() { } public void flush() { }
@Override @Override
public void close() { }; public void close() { }
} }

View file

@ -28,7 +28,7 @@ import java.io.File;
/** /**
* Interface for the FileWatcher class * Interface for the FileWatcher class
* *
* @author Ziver * @author Ziver
*/ */
public interface FileChangeListener{ public interface FileChangeListener{
@ -38,5 +38,5 @@ public interface FileChangeListener{
* *
* @param file The file that has changed * @param file The file that has changed
*/ */
public void fileChangedEvent(File file); void fileChangedEvent(File file);
} }

View file

@ -36,9 +36,8 @@ import java.util.zip.ZipFile;
public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
// Constants // Constants
private static final List<String> compressedFileExtensions = Arrays.asList(new String[]{ private static final List<String> compressedFileExtensions = Arrays.asList(
"jar", "zip" "jar", "zip");
});
// Constructor params // Constructor params
private File root; private File root;
@ -119,7 +118,7 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
private FileSearchItem nextItem; private FileSearchItem nextItem;
public FileSearchIterator(){ public FileSearchIterator(){
fileList = new ArrayList<FileSearchItem>(); fileList = new ArrayList<>();
index = 0; index = 0;
addFiles(new FileSearchFileItem(root), root.list()); addFiles(new FileSearchFileItem(root), root.list());
@ -208,18 +207,18 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
public interface FileSearchItem{ public interface FileSearchItem{
/** @return a file or folder name **/ /** @return a file or folder name **/
public String getName(); String getName();
/** @return a path to the file or folder, in case of a compressed file the path to the package will be returned **/ /** @return a path to the file or folder, in case of a compressed file the path to the package will be returned **/
public String getPath(); String getPath();
public boolean isCompressed(); boolean isCompressed();
public boolean isFile(); boolean isFile();
public boolean isDirectory(); boolean isDirectory();
/** @return an InputStream if this is a file otherwise null **/ /** @return an InputStream if this is a file otherwise null **/
public InputStream getInputStream() throws IOException; InputStream getInputStream() throws IOException;
/** @return an String array with all files if this is a folder otherwise null **/ /** @return an String array with all files if this is a folder otherwise null **/
public String[] listFiles(); String[] listFiles();
} }

View file

@ -90,9 +90,6 @@ public class FileUtil {
/** /**
* Copy the contents of a source file to another file. * Copy the contents of a source file to another file.
* NOTE: the method will replace the destination file if it exists. * NOTE: the method will replace the destination file if it exists.
*
* @param source
* @param destination
*/ */
public static void copy(File source, File destination) throws IOException{ public static void copy(File source, File destination) throws IOException{
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
@ -126,7 +123,6 @@ public class FileUtil {
* *
* @param path is the path to the file (no / if not absolute path) * @param path is the path to the file (no / if not absolute path)
* @return A URL object for the file * @return A URL object for the file
* @throws URISyntaxException
*/ */
public static URL findURL(String path){ public static URL findURL(String path){
return Thread.currentThread().getContextClassLoader().getResource(path); return Thread.currentThread().getContextClassLoader().getResource(path);
@ -155,7 +151,6 @@ public class FileUtil {
/** /**
* Reads and returns the content of a file as a String. * Reads and returns the content of a file as a String.
* *
* @param file
* @return the file content * @return the file content
*/ */
public static String getContent(File file) throws IOException{ public static String getContent(File file) throws IOException{
@ -166,14 +161,12 @@ public class FileUtil {
} }
/** /**
* Reads and returns the content of a file as a String. * Connects to a URL and returns the content of it as a String.
* *
* @param url * @return the URL content
* @return the file content
*/ */
public static String getContent(URL url) throws IOException{ public static String getContent(URL url) throws IOException{
String data = new String(IOUtil.readContent(url.openStream(), true)); return new String(IOUtil.readContent(url.openStream(), true));
return data;
} }
/** /**
@ -195,7 +188,7 @@ public class FileUtil {
* @return a List of files * @return a List of files
*/ */
public static List<File> search(File dir){ public static List<File> search(File dir){
return search(dir, new LinkedList<File>(), true); return search(dir, new LinkedList<>(), true);
} }
/** /**
@ -207,7 +200,7 @@ public class FileUtil {
* @return A List of files * @return A List of files
*/ */
public static List<File> search(File dir, List<File> fileList, boolean recursive){ public static List<File> search(File dir, List<File> fileList, boolean recursive){
return search(dir, new LinkedList<File>(), false, (recursive ? Integer.MAX_VALUE : 0)); return search(dir, new LinkedList<>(), false, (recursive ? Integer.MAX_VALUE : 0));
} }
/** /**

View file

@ -32,9 +32,9 @@ import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
/** /**
* This class calls a given listener * This class calls a given listener
* when a file is changed * when a file is changed
* *
* @author Ziver * @author Ziver
* *
*/ */
@ -48,7 +48,6 @@ public class FileWatcher extends TimerTask{
* interval of 1 second * interval of 1 second
* *
* @param file is the file to check * @param file is the file to check
* @throws FileNotFoundException
*/ */
public FileWatcher(File file) throws FileNotFoundException{ public FileWatcher(File file) throws FileNotFoundException{
this(file, 1000); this(file, 1000);
@ -59,17 +58,16 @@ public class FileWatcher extends TimerTask{
* check interval * check interval
* *
* @param file is the file * @param file is the file
* @param intervall is the interval * @param interval is the interval
* @throws FileNotFoundException
*/ */
public FileWatcher(File file, int intervall) throws FileNotFoundException{ public FileWatcher(File file, int interval) throws FileNotFoundException{
if(file==null || !file.exists()) if(file==null || !file.exists())
throw new FileNotFoundException("File not found: "+file); throw new FileNotFoundException("File not found: "+file);
this.file = file; this.file = file;
lastChanged = file.lastModified(); lastChanged = file.lastModified();
Timer t = new Timer(true); Timer t = new Timer(true);
t.schedule(this, 0, intervall); t.schedule(this, 0, interval);
} }
public void setListener(FileChangeListener listener){ public void setListener(FileChangeListener listener){

View file

@ -51,7 +51,7 @@ import java.util.logging.Logger;
/** /**
* <pre> * <pre>
* Example web.xml: * Example web.xml:
* &lt;servlet&gt; * &lt;servlet&gt;
* &lt;servlet-name&gt;Upload&lt;/servlet-name&gt; * &lt;servlet-name&gt;Upload&lt;/servlet-name&gt;
* &lt;servlet-class&gt;zall.util.AjaxFileUpload&lt;/servlet-class&gt; * &lt;servlet-class&gt;zall.util.AjaxFileUpload&lt;/servlet-class&gt;
@ -64,19 +64,19 @@ import java.util.logging.Logger;
* &lt;param-value&gt;SYSTEM|SERVLET|{PATH}&lt;/param-value&gt; * &lt;param-value&gt;SYSTEM|SERVLET|{PATH}&lt;/param-value&gt;
* &lt;/init-param&gt; * &lt;/init-param&gt;
* &lt;/servlet&gt; * &lt;/servlet&gt;
* *
* *
* HTML Header: * HTML Header:
* &lt;script type='text/javascript' src='{PATH_TO_SERVLET}?js'&gt;&lt;/script&gt; * &lt;script type='text/javascript' src='{PATH_TO_SERVLET}?js'&gt;&lt;/script&gt;
* *
* *
* HTML Body: * HTML Body:
* &lt;FORM id="AjaxFileUpload"&gt; * &lt;FORM id="AjaxFileUpload"&gt;
* &lt;input type="file" multiple name="file" /&gt; * &lt;input type="file" multiple name="file" /&gt;
* &lt;/FORM&gt; * &lt;/FORM&gt;
* &lt;UL id="UploadQueue"&gt;&lt;/UL&gt; * &lt;UL id="UploadQueue"&gt;&lt;/UL&gt;
* *
* *
* </pre> * </pre>
* @author Ziver * @author Ziver
* *
@ -90,7 +90,7 @@ public abstract class AjaxFileUpload extends HttpServlet {
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<>();
public void init(ServletConfig config) throws ServletException { public void init(ServletConfig config) throws ServletException {
super.init(config); super.init(config);
@ -129,12 +129,12 @@ public abstract class AjaxFileUpload extends HttpServlet {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest request, protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { HttpServletResponse response) throws 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;
tmp = JAVASCRIPT.replaceAll("\\{SERVLET_URL\\}", request.getRequestURI()); String 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);
@ -178,15 +178,15 @@ public abstract class AjaxFileUpload extends HttpServlet {
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<>();
ArrayList<FileItem> files = new ArrayList<FileItem>(); ArrayList<FileItem> files = new ArrayList<>();
// 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<>();
session.setAttribute(SESSION_FILEUPLOAD_LISTENER, list); session.setAttribute(SESSION_FILEUPLOAD_LISTENER, list);
} }
list.add(listener); list.add(listener);
@ -258,8 +258,7 @@ public abstract class AjaxFileUpload extends HttpServlet {
public abstract String getProgressHTML(); public abstract String getProgressHTML();
/** /**
* Handle the uppload * Handle the upload
* @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

@ -32,11 +32,11 @@ import zutil.parser.DataNode.DataType;
/** /**
* This is a File Upload Listener that is used by Apache * This is a File Upload Listener that is used by Apache
* Commons File Upload to monitor the progress of the * Commons File Upload to monitor the progress of the
* uploaded file. * uploaded file.
*/ */
public class FileUploadListener implements ProgressListener{ public class FileUploadListener implements ProgressListener{
public static enum Status{ public enum Status{
Initializing, Initializing,
Uploading, Uploading,
Processing, Processing,
@ -48,8 +48,8 @@ public class FileUploadListener implements ProgressListener{
private volatile Status status; private volatile Status status;
private volatile String filename; private volatile String filename;
private volatile String message; private volatile String message;
private volatile long bytes = 0l; private volatile long bytes = 0L;
private volatile long length = 0l; private volatile long length = 0L;
private volatile int item = 0; private volatile int item = 0;
private volatile long time; private volatile long time;

View file

@ -49,7 +49,7 @@ public class CompactLogFormatter extends Formatter{
/** Specifies the max length of the longest class name **/ /** Specifies the max length of the longest class name **/
private int max_class_name = 0; private int max_class_name = 0;
/** Cache for the class padding **/ /** Cache for the class padding **/
private static HashMap<String,String> padd_cache = new HashMap<String,String>(); private static HashMap<String,String> padd_cache = new HashMap<>();
/** Date temp file **/ /** Date temp file **/
private Date date = new Date(); private Date date = new Date();

View file

@ -69,7 +69,7 @@ public class CounterManager {
mbs.registerMBean(counter, objectName); mbs.registerMBean(counter, objectName);
// Register the singleton // Register the singleton
if ( ! counters.containsKey(clazz)) if ( ! counters.containsKey(clazz))
counters.put(clazz, new HashMap<String, Counter>()); counters.put(clazz, new HashMap<>());
counters.get(clazz).put(name, counter); counters.get(clazz).put(name, counter);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();

View file

@ -82,7 +82,7 @@ public class StreamLogger {
public interface LogCallback{ public interface LogCallback{
public boolean isLoggable(); boolean isLoggable();
public void log(String msg); void log(String msg);
} }
} }

View file

@ -26,38 +26,40 @@
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" fx:controller="zutil.log.net.NetLogGuiClient"> <AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity"
<children> prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml"
fx:controller="zutil.log.net.NetLogGuiClient">
<MenuBar prefWidth="598.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0"> <MenuBar prefWidth="598.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<menus> <menus>
<Menu mnemonicParsing="false" text="File"> <Menu mnemonicParsing="false" text="File">
<items> <items>
<MenuItem mnemonicParsing="false" text="Open File" /> <MenuItem mnemonicParsing="false" text="Open File"/>
<MenuItem mnemonicParsing="false" onAction="#handleConnectAction" text="Connect" /> <MenuItem mnemonicParsing="false" onAction="#handleConnectAction" text="Connect"/>
<Menu mnemonicParsing="false" text="Previous"> <Menu mnemonicParsing="false" text="Previous">
<items> <items>
<MenuItem mnemonicParsing="false" text="Koc.se:8080" /> <MenuItem mnemonicParsing="false" text="Koc.se:8080"/>
<MenuItem mnemonicParsing="false" text="localhost:8080" /> <MenuItem mnemonicParsing="false" text="localhost:8080"/>
</items> </items>
</Menu>
<SeparatorMenuItem mnemonicParsing="false"/>
<MenuItem mnemonicParsing="false" text="Export"/>
<SeparatorMenuItem disable="true" mnemonicParsing="false"/>
<MenuItem mnemonicParsing="false" onAction="#handleExitAction" text="Exit"/>
</items>
</Menu> </Menu>
<SeparatorMenuItem mnemonicParsing="false" /> <Menu mnemonicParsing="false" text="Edit">
<MenuItem mnemonicParsing="false" text="Export" /> <items>
<SeparatorMenuItem disable="true" mnemonicParsing="false" /> <MenuItem disable="true" mnemonicParsing="false" text="Copy"/>
<MenuItem mnemonicParsing="false" onAction="#handleExitAction" text="Exit" /> </items>
</items> </Menu>
</Menu> <Menu mnemonicParsing="false" text="Help">
<Menu mnemonicParsing="false" text="Edit"> <items>
<items> <MenuItem mnemonicParsing="false" onAction="#handleAboutAction" text="About"/>
<MenuItem disable="true" mnemonicParsing="false" text="Copy" /> </items>
</items> </Menu>
</Menu> </menus>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" onAction="#handleAboutAction" text="About" />
</items>
</Menu>
</menus>
</MenuBar> </MenuBar>
<TabPane fx:id="tabPane" prefHeight="364.0" prefWidth="586.0" tabClosingPolicy="ALL_TABS" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="22.0" /> <TabPane fx:id="tabPane" prefHeight="364.0" prefWidth="586.0" tabClosingPolicy="ALL_TABS"
</children> AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="22.0"/>
</AnchorPane> </AnchorPane>

View file

@ -41,17 +41,15 @@ public class NetLogClient extends Thread{
private ConcurrentLinkedQueue<NetLogListener> listeners; private ConcurrentLinkedQueue<NetLogListener> listeners;
private Socket s; private Socket s;
private ObjectOutputStream out;
public NetLogClient(String host, int port) throws UnknownHostException, IOException{ public NetLogClient(String host, int port) throws IOException{
s = new Socket(host, port); s = new Socket(host, port);
out = new ObjectOutputStream(s.getOutputStream()); listeners = new ConcurrentLinkedQueue<>();
listeners = new ConcurrentLinkedQueue<NetLogListener>();
this.start(); this.start();
} }
public void addListener(NetLogListener listener){ public void addListener(NetLogListener listener){
logger.info("Registring new NetLogListener: "+listener.getClass().getName()); logger.info("Registering new NetLogListener: "+listener.getClass().getName());
listeners.add( listener ); listeners.add( listener );
} }

View file

@ -36,93 +36,100 @@
<URL value="@NetLogClientInstance.css" /> <URL value="@NetLogClientInstance.css" />
</stylesheets> </stylesheets>
<bottom> <bottom>
<ToolBar maxHeight="22.0" minHeight="19.0" prefHeight="22.0" prefWidth="839.0"> <ToolBar maxHeight="22.0" minHeight="19.0" prefHeight="22.0" prefWidth="839.0">
<items> <ProgressBar fx:id="progressBar" prefWidth="200.0" progress="0.0"/>
<ProgressBar fx:id="progressBar" prefWidth="200.0" progress="0.0" style="" /> <Label fx:id="errorLabel" textFill="RED">
<Label fx:id="errorLabel" text="" textFill="RED"> <font>
<font> <Font size="11.0"/>
<Font size="11.0" /> </font>
</font> </Label>
</Label> <Region HBox.Hgrow="ALWAYS"/>
<Region HBox.Hgrow="ALWAYS" /> <Separator orientation="VERTICAL" prefHeight="200.0"/>
<Separator orientation="VERTICAL" prefHeight="200.0" valignment="CENTER" /> <Label fx:id="logCountLabel" text="0">
<Label fx:id="logCountLabel" text="0"> <graphic>
<graphic> <Label text="Log Count:"/>
<Label text="Log Count:" /> </graphic>
</graphic> </Label>
</Label> </ToolBar>
</items>
</ToolBar>
</bottom> </bottom>
<center> <center>
<SplitPane dividerPositions="0.7491525423728813" focusTraversable="true" orientation="VERTICAL" prefHeight="297.0" prefWidth="600.0"> <SplitPane dividerPositions="0.7491525423728813" focusTraversable="true" orientation="VERTICAL" prefHeight="297.0"
<items> prefWidth="600.0">
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0"> <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<children> <children>
<TableView fx:id="logTable" prefHeight="146.0" prefWidth="598.0" tableMenuButtonVisible="true" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0"> <TableView fx:id="logTable" prefHeight="146.0" prefWidth="598.0" tableMenuButtonVisible="true"
<columns> AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
<TableColumn editable="false" prefWidth="130.0" sortable="false" text="Timestamp" fx:id="logTimestampColumn" /> AnchorPane.topAnchor="0.0">
<TableColumn editable="false" prefWidth="75.0" sortable="false" text="Level" fx:id="logLevelColumn" /> <columns>
<TableColumn editable="false" prefWidth="400.0" sortable="false" text="Log" fx:id="logColumn" /> <TableColumn editable="false" prefWidth="130.0" sortable="false" text="Timestamp"
</columns> fx:id="logTimestampColumn"/>
</TableView> <TableColumn editable="false" prefWidth="75.0" sortable="false" text="Level"
</children> fx:id="logLevelColumn"/>
</AnchorPane> <TableColumn editable="false" prefWidth="400.0" sortable="false" text="Log"
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0"> fx:id="logColumn"/>
<children> </columns>
<TableView fx:id="exceptionTable" prefHeight="147.0" prefWidth="598.0" tableMenuButtonVisible="true" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0"> </TableView>
<columns> </children>
<TableColumn editable="false" prefWidth="45.0" style="-fx-alignment: TOP_CENTER;" text="#" fx:id="exCountColumn" /> </AnchorPane>
<TableColumn editable="false" prefWidth="250.0" style="-fx-alignment: TOP_LEFT;&#10;-fx-font-weight: bold;" text="Exception" fx:id="exNameColumn" /> <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<TableColumn editable="false" prefWidth="300.0" style="-fx-alignment: TOP_LEFT;" text="Message" fx:id="exMessageColumn" /> <children>
<TableColumn editable="false" prefWidth="450.0" text="StackTrace" fx:id="exStackTraceColumn" /> <TableView fx:id="exceptionTable" prefHeight="147.0" prefWidth="598.0" tableMenuButtonVisible="true"
</columns> AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
</TableView> AnchorPane.topAnchor="0.0">
</children> <columns>
</AnchorPane> <TableColumn editable="false" prefWidth="45.0" style="-fx-alignment: TOP_CENTER;" text="#"
</items> fx:id="exCountColumn"/>
</SplitPane> <TableColumn editable="false" prefWidth="250.0"
style="-fx-alignment: TOP_LEFT;&#10;-fx-font-weight: bold;" text="Exception"
fx:id="exNameColumn"/>
<TableColumn editable="false" prefWidth="300.0" style="-fx-alignment: TOP_LEFT;"
text="Message" fx:id="exMessageColumn"/>
<TableColumn editable="false" prefWidth="450.0" text="StackTrace" fx:id="exStackTraceColumn"/>
</columns>
</TableView>
</children>
</AnchorPane>
</SplitPane>
</center> </center>
<top> <top>
<ToolBar maxHeight="30.0" minHeight="22.0" prefHeight="30.0" prefWidth="839.0"> <ToolBar maxHeight="30.0" minHeight="22.0" prefHeight="30.0" prefWidth="839.0">
<items> <ToggleButton fx:id="pauseButton" mnemonicParsing="false" onAction="#handlePauseAction" text="Pause"/>
<ToggleButton fx:id="pauseButton" mnemonicParsing="false" onAction="#handlePauseAction" text="Pause" /> <Region HBox.Hgrow="ALWAYS"/>
<Region HBox.Hgrow="ALWAYS" /> <Group id="Group">
<Group id="Group"> <children>
<children> <Label fx:id="levelLabel" layoutY="-7.0" text="Log Level: "/>
<Label fx:id="levelLabel" layoutX="0.0" layoutY="-7.0" text="Log Level: " /> <ComboBox fx:id="levelComboBox" layoutX="60.0" layoutY="-9.0" onAction="#handleLevelChanged">
<ComboBox fx:id="levelComboBox" layoutX="60.0" layoutY="-9.0" onAction="#handleLevelChanged"> <items>
<items> <FXCollections fx:factory="observableArrayList">
<FXCollections fx:factory="observableArrayList"> <String fx:value="01 - ERROR"/>
<String fx:value="01 - ERROR" /> <String fx:value="02 - WARNING"/>
<String fx:value="02 - WARNING" /> <String fx:value="03 - INFO"/>
<String fx:value="03 - INFO" /> <String fx:value="04 - FINE"/>
<String fx:value="04 - FINE" /> <String fx:value="05 - FINER"/>
<String fx:value="05 - FINER" /> <String fx:value="06 - FINEST"/>
<String fx:value="06 - FINEST" /> </FXCollections>
</FXCollections> </items>
</items> </ComboBox>
</ComboBox> </children>
</children> </Group>
</Group> <Group id="Group">
<Group id="Group"> <children>
<children> <Label fx:id="intervalLabel" alignment="CENTER_RIGHT" layoutY="-7.0" prefWidth="60.0"
<Label fx:id="intervalLabel" alignment="CENTER_RIGHT" layoutX="0.0" layoutY="-7.0" prefWidth="60.0" text="Interval: " /> text="Interval: "/>
<ComboBox fx:id="intervalComboBox" layoutX="65.0" layoutY="-9.0" onAction="#handleIntervalChanged"> <ComboBox fx:id="intervalComboBox" layoutX="65.0" layoutY="-9.0" onAction="#handleIntervalChanged">
<items> <items>
<FXCollections fx:factory="observableArrayList"> <FXCollections fx:factory="observableArrayList">
<String fx:value="Instant" /> <String fx:value="Instant"/>
<String fx:value="3 sec" /> <String fx:value="3 sec"/>
<String fx:value="5 sec" /> <String fx:value="5 sec"/>
<String fx:value="10 sec" /> <String fx:value="10 sec"/>
<String fx:value="30 sec" /> <String fx:value="30 sec"/>
<String fx:value="60 sec" /> <String fx:value="60 sec"/>
</FXCollections> </FXCollections>
</items> </items>
</ComboBox> </ComboBox>
</children> </children>
</Group> </Group>
</items> </ToolBar>
</ToolBar>
</top> </top>
</BorderPane> </BorderPane>

View file

@ -49,10 +49,12 @@ public class NetLogExceptionMessage implements Message {
this.count = 1; this.count = 1;
this.name = exception.getClass().getName(); this.name = exception.getClass().getName();
this.message = exception.getMessage(); this.message = exception.getMessage();
this.stackTrace = "";
StringBuilder str = new StringBuilder();
for(int i=0; i<exception.getStackTrace().length; i++){ for(int i=0; i<exception.getStackTrace().length; i++){
this.stackTrace += exception.getStackTrace()[i].toString(); str.append(exception.getStackTrace()[i].toString());
} }
this.stackTrace = str.toString();
} }

View file

@ -36,30 +36,30 @@ import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage; import javafx.stage.Stage;
import java.io.IOException; import java.io.IOException;
public class NetLogGuiClient extends Application{ public class NetLogGuiClient extends Application{
public static final String VERSION = "0.1"; public static final String VERSION = "0.1";
// UI elements // UI elements
@FXML @FXML
private TabPane tabPane; private TabPane tabPane;
public static void main(String[] args) { public static void main(String[] args) {
Application.launch(NetLogGuiClient.class, args); Application.launch(NetLogGuiClient.class, args);
} }
@Override @Override
public void start(Stage stage) throws Exception { public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("NetLogClient.fxml")); Parent root = FXMLLoader.load(getClass().getResource("NetLogClient.fxml"));
stage.setTitle("NetLoggerClient ("+VERSION+")"); stage.setTitle("NetLoggerClient ("+VERSION+")");
stage.setScene(new Scene(root)); stage.setScene(new Scene(root));
stage.show(); stage.show();
} }
// Menu Actions // Menu Actions
@FXML @FXML
protected void handleConnectAction(ActionEvent event) { protected void handleConnectAction(ActionEvent event) {
try{ try{
tabPane.getTabs().add(new NetLoggerClientTab("koc.se", 8080)); tabPane.getTabs().add(new NetLoggerClientTab("koc.se", 8080));
@ -82,8 +82,7 @@ public class NetLogGuiClient extends Application{
public NetLoggerClientTab(String host, int port) throws IOException{ public NetLoggerClientTab(String host, int port) throws IOException{
this.setText( host+":"+port ); this.setText( host+":"+port );
FXMLLoader loader = new FXMLLoader(); Parent tabRoot = FXMLLoader.load(getClass().getResource("NetLogClientInstance.fxml"));
Parent tabRoot = loader.load(getClass().getResource("NetLogClientInstance.fxml"));
this.setContent(tabRoot); this.setContent(tabRoot);
AnchorPane.setRightAnchor(tabRoot, 0.0); AnchorPane.setRightAnchor(tabRoot, 0.0);
//this.setOnClosed(new EventHandler<Event>() { //this.setOnClosed(new EventHandler<Event>() {

View file

@ -41,7 +41,7 @@ import java.util.logging.Logger;
public class NetLogGuiClientInstance implements Initializable, NetLogListener { public class NetLogGuiClientInstance implements Initializable, NetLogListener {
private static final Logger logger = LogUtil.getLogger(); private static final Logger logger = LogUtil.getLogger();
private static enum Status{RUNNING, PAUSED, DISCONNECTED} private enum Status{RUNNING, PAUSED, DISCONNECTED}
// Logic variables // Logic variables
private NetLogClient net; private NetLogClient net;
@ -83,19 +83,19 @@ public class NetLogGuiClientInstance implements Initializable, NetLogListener {
updateStatus(); updateStatus();
// Setup Gui // Setup Gui
logTimestampColumn.setCellValueFactory(new PropertyValueFactory<NetLogMessage, Long>("timestamp")); logTimestampColumn.setCellValueFactory(new PropertyValueFactory<>("timestamp"));
logLevelColumn.setCellValueFactory(new PropertyValueFactory<NetLogMessage, String>("level")); logLevelColumn.setCellValueFactory(new PropertyValueFactory<>("level"));
logLevelColumn.setCellFactory(new RowCssCellFactory<NetLogMessage,String>(){ logLevelColumn.setCellFactory(new RowCssCellFactory<NetLogMessage,String>(){
public String getStyleName(String item){ public String getStyleName(String item){
return item; return item;
} }
}); });
logColumn.setCellValueFactory(new PropertyValueFactory<NetLogMessage, String>("log")); logColumn.setCellValueFactory(new PropertyValueFactory<>("log"));
exCountColumn.setCellValueFactory(new PropertyValueFactory<NetLogExceptionMessage, Long>("count")); exCountColumn.setCellValueFactory(new PropertyValueFactory<>("count"));
exNameColumn.setCellValueFactory(new PropertyValueFactory<NetLogExceptionMessage, String>("name")); exNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
exMessageColumn.setCellValueFactory(new PropertyValueFactory<NetLogExceptionMessage, String>("message")); exMessageColumn.setCellValueFactory(new PropertyValueFactory<>("message"));
exStackTraceColumn.setCellValueFactory(new PropertyValueFactory<NetLogExceptionMessage, String>("stackTrace")); exStackTraceColumn.setCellValueFactory(new PropertyValueFactory<>("stackTrace"));
} }
/************* NETWORK *****************/ /************* NETWORK *****************/

View file

@ -29,15 +29,15 @@ public interface NetLogListener {
/** /**
* Handle incoming log messages * Handle incoming log messages
*/ */
public void handleLogMessage( NetLogMessage log ); void handleLogMessage(NetLogMessage log);
/** /**
* Handle incoming exception messages * Handle incoming exception messages
*/ */
public void handleExceptionMessage( NetLogExceptionMessage exception ); void handleExceptionMessage(NetLogExceptionMessage exception);
/** /**
* Handle incoming status messages * Handle incoming status messages
*/ */
public void handleStatusMessage( NetLogStatusMessage status ); void handleStatusMessage(NetLogStatusMessage status);
} }

View file

@ -52,7 +52,7 @@ public class NetLogServer extends Handler {
*/ */
public NetLogServer(int port) { public NetLogServer(int port) {
super(); super();
exceptions = new ConcurrentHashMap<NetLogExceptionMessage,NetLogExceptionMessage>(); exceptions = new ConcurrentHashMap<>();
net = new NetLogNetwork(port); net = new NetLogNetwork(port);
net.start(); net.start();
} }
@ -96,7 +96,7 @@ public class NetLogServer extends Handler {
public NetLogNetwork(int port) { public NetLogNetwork(int port) {
super(port); super(port);
threads = new ConcurrentLinkedQueue<NetLogServerThread>(); threads = new ConcurrentLinkedQueue<>();
} }
public void sendMessage(Message log){ public void sendMessage(Message log){
@ -108,8 +108,7 @@ public class NetLogServer extends Handler {
@Override @Override
protected ThreadedTCPNetworkServerThread getThreadInstance(Socket s) { protected ThreadedTCPNetworkServerThread getThreadInstance(Socket s) {
try { try {
NetLogServerThread thread = new NetLogServerThread(s); return new NetLogServerThread(s);
return thread;
} catch (IOException e) { } catch (IOException e) {
logger.log(Level.SEVERE, "Unable to start Client thread", e); logger.log(Level.SEVERE, "Unable to start Client thread", e);
} }

View file

@ -34,7 +34,7 @@ import java.util.regex.Pattern;
/** /**
* A simple FTP client class * A simple FTP client class
* *
* @author Ziver * @author Ziver
* *
* http://en.wikipedia.org/wiki/List_of_FTP_commands * http://en.wikipedia.org/wiki/List_of_FTP_commands
@ -48,12 +48,12 @@ public class FTPClient extends Thread{
public static final int FTP_DATA_PORT = 20; public static final int FTP_DATA_PORT = 20;
public static final int FTP_NOOP_INT = 120; public static final int FTP_NOOP_INT = 120;
public static enum FTPConnectionType{ public enum FTPConnectionType{
ACTIVE, ACTIVE,
PASSIVE PASSIVE
} }
public static enum FTPReturnCode{ public enum FTPReturnCode{
UNKNOWN ( -1 ), UNKNOWN ( -1 ),
USER_OK ( 331 ), USER_OK ( 331 ),
@ -66,7 +66,7 @@ public class FTPClient extends Thread{
PATH_CREATED ( 257 ); PATH_CREATED ( 257 );
private int code; private int code;
private FTPReturnCode(int code){ FTPReturnCode(int code){
this.code = code; this.code = code;
} }
@ -98,7 +98,7 @@ public class FTPClient extends Thread{
* @param pass password * @param pass password
* @param conn_type connection type * @param conn_type connection type
*/ */
public FTPClient(String url, int port, String user, String pass, FTPConnectionType conn_type) throws UnknownHostException, IOException, AccountException{ public FTPClient(String url, int port, String user, String pass, FTPConnectionType conn_type) throws IOException, AccountException{
socket = new Socket(url, port); socket = new Socket(url, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream())); in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new OutputStreamWriter(socket.getOutputStream()); out = new OutputStreamWriter(socket.getOutputStream());
@ -189,7 +189,7 @@ public class FTPClient extends Thread{
* @return a List of Strings with information * @return a List of Strings with information
*/ */
public String getFileInfo(String path) throws IOException{ public String getFileInfo(String path) throws IOException{
Pattern regex = Pattern.compile("\\s{1,}"); Pattern regex = Pattern.compile("\\s+");
BufferedInputStream data_in = getDataInputStream(); BufferedInputStream data_in = getDataInputStream();
sendCommand("LIST "+path); sendCommand("LIST "+path);

View file

@ -31,13 +31,12 @@ public class InetScanner {
*/ */
public synchronized void scan(InetAddress ip){ public synchronized void scan(InetAddress ip){
canceled = false; canceled = false;
MultiCommandExecutor exec = new MultiCommandExecutor();
String netAddr = ip.getHostAddress().substring(0, ip.getHostAddress().lastIndexOf('.')+1); String netAddr = ip.getHostAddress().substring(0, ip.getHostAddress().lastIndexOf('.')+1);
try{ try (MultiCommandExecutor exec = new MultiCommandExecutor()) {
for (int i = 1; i < 255 && !canceled; i++) { for (int i = 1; i < 255 && !canceled; i++) {
try { try {
String targetIp = netAddr+i; String targetIp = netAddr + i;
boolean online = isReachable(targetIp, exec); boolean online = isReachable(targetIp, exec);
if (online && listener != null) if (online && listener != null)
listener.foundInetAddress(InetAddress.getByName(targetIp)); listener.foundInetAddress(InetAddress.getByName(targetIp));
@ -45,11 +44,8 @@ public class InetScanner {
e.printStackTrace(); e.printStackTrace();
} }
} }
} } catch (Exception e) {
catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
exec.close();
} }
} }

View file

@ -24,6 +24,8 @@
package zutil.net; package zutil.net;
import zutil.log.LogUtil;
import javax.net.SocketFactory; import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -31,20 +33,19 @@ import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.PrintStream; import java.io.PrintStream;
import java.net.Socket; import java.net.Socket;
import java.net.UnknownHostException; import java.util.logging.Logger;
/** /**
* A simple class that connects and logs in to a POP3 * A simple class that connects and logs in to a POP3
* server and then can read and delete messages. * server and then can read and delete messages.
* INFO: http://pages.prodigy.net/michael_santovec/pop3telnet.htm * INFO: http://pages.prodigy.net/michael_santovec/pop3telnet.htm
*
* @author Ziver
* *
* @author Ziver
*/ */
public class POP3Client { public class POP3Client {
public static boolean DEBUG = false; private static final Logger logger = LogUtil.getLogger();
public static final int POP3_PORT = 110; private static final int POP3_PORT = 110;
public static final int POP3_SSL_PORT = 995; private static final int POP3_SSL_PORT = 995;
private BufferedReader in; private BufferedReader in;
private PrintStream out; private PrintStream out;
@ -54,37 +55,31 @@ public class POP3Client {
* Connect to a POP3 server without username * Connect to a POP3 server without username
* *
* @param host The hostname of the server * @param host The hostname of the server
* @throws UnknownHostException
* @throws IOException
*/ */
public POP3Client(String host) throws UnknownHostException, IOException{ public POP3Client(String host) throws IOException {
this(host, POP3_PORT, null, null, false); this(host, POP3_PORT, null, null, false);
} }
/** /**
* Connect to a POP3 server with username and password * Connect to a POP3 server with username and password
* *
* @param host The hostname of the server * @param host The hostname of the server
* @param user The username * @param user The username
* @param password the password * @param password the password
* @throws UnknownHostException
* @throws IOException
*/ */
public POP3Client(String host, String user, String password) throws UnknownHostException, IOException{ public POP3Client(String host, String user, String password) throws IOException {
this(host, POP3_PORT, user, password, false); this(host, POP3_PORT, user, password, false);
} }
/** /**
* Connects to a POP3 server with username and password and SSL * Connects to a POP3 server with username and password and SSL
* *
* @param host The hostname of the server * @param host The hostname of the server
* @param user The username * @param user The username
* @param password the password * @param password the password
* @param ssl If SSL should be used * @param ssl If SSL should be used
* @throws UnknownHostException
* @throws IOException
*/ */
public POP3Client(String host, String user, String password, boolean ssl) throws UnknownHostException, IOException{ public POP3Client(String host, String user, String password, boolean ssl) throws IOException {
this(host, (ssl ? POP3_SSL_PORT : POP3_PORT), user, password, ssl); this(host, (ssl ? POP3_SSL_PORT : POP3_PORT), user, password, ssl);
} }
@ -92,19 +87,17 @@ public class POP3Client {
* Connects to a POP3 server with username and password and * Connects to a POP3 server with username and password and
* SSL and with costume port. * SSL and with costume port.
* *
* @param host The hostname of the server * @param host The hostname of the server
* @param port The port number to connect to on the server * @param port The port number to connect to on the server
* @param user The username * @param user The username
* @param password the password * @param password the password
* @param ssl If SSL should be used * @param ssl If SSL should be used
* @throws UnknownHostException
* @throws IOException
*/ */
public POP3Client(String host, int port, String user, String password, boolean ssl) throws UnknownHostException, IOException{ public POP3Client(String host, int port, String user, String password, boolean ssl) throws IOException {
if(ssl) connectSSL(host, port); if (ssl) connectSSL(host, port);
else connect(host, port); else connect(host, port);
if(user != null){ if (user != null) {
login(user, password); login(user, password);
} }
} }
@ -114,15 +107,13 @@ public class POP3Client {
* *
* @param host The hostname of the server * @param host The hostname of the server
* @param port The port to connect to on the server * @param port The port to connect to on the server
* @throws UnknownHostException
* @throws IOException
*/ */
private void connect(String host, int port) throws UnknownHostException, IOException{ private void connect(String host, int port) throws IOException {
socket = new Socket(host, port); socket = new Socket(host, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream())); in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintStream(socket.getOutputStream()); out = new PrintStream(socket.getOutputStream());
readCommand(true); readCommand();
} }
/** /**
@ -131,32 +122,29 @@ public class POP3Client {
* *
* @param host The hostname of the server * @param host The hostname of the server
* @param port The port to connect to on the server * @param port The port to connect to on the server
* @throws UnknownHostException
* @throws IOException
*/ */
private void connectSSL(String host, int port) throws UnknownHostException, IOException{ private void connectSSL(String host, int port) throws IOException {
SocketFactory socketFactory = SSLSocketFactory.getDefault(); SocketFactory socketFactory = SSLSocketFactory.getDefault();
socket = socketFactory.createSocket(host, port); socket = socketFactory.createSocket(host, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream())); in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintStream(socket.getOutputStream()); out = new PrintStream(socket.getOutputStream());
readCommand(DEBUG); readCommand();
} }
/** /**
* Logs in to the POP3 server with the username and password if the password is set * Logs in to the POP3 server with the username and password if the password is set
* *
* @param user The user name * @param user The user name
* @param password The password or null if no password is required * @param password The password or null if no password is required
* @throws IOException
*/ */
private void login(String user, String password) throws IOException{ private void login(String user, String password) throws IOException {
sendCommand("USER "+user); sendCommand("USER " + user);
if(password != null){ if (password != null) {
sendNoReplyCommand("PASS "+password, false); sendNoReplyCommand("PASS " + password);
if(DEBUG)System.out.println("PASS ***"); logger.finest("PASS ***");
readCommand(DEBUG); readCommand();
} }
} }
@ -164,14 +152,13 @@ public class POP3Client {
* Returns the number of messages that is on the server * Returns the number of messages that is on the server
* *
* @return Message count * @return Message count
* @throws IOException
*/ */
public int getMessageCount() throws IOException{ public int getMessageCount() throws IOException {
String msg = sendCommand("STAT", DEBUG); String msg = sendCommand("STAT");
return Integer.parseInt( return Integer.parseInt(
msg.substring( msg.substring(
msg.indexOf(' ')+1, msg.indexOf(' ') + 1,
msg.indexOf(' ', msg.indexOf(' ')+1))); msg.indexOf(' ', msg.indexOf(' ') + 1)));
} }
/** /**
@ -179,11 +166,10 @@ public class POP3Client {
* *
* @param id The id of the message to get * @param id The id of the message to get
* @return The message * @return The message
* @throws IOException
*/ */
public String getMessage(int id) throws IOException{ public String getMessage(int id) throws IOException {
sendCommand("RETR "+id); sendCommand("RETR " + id);
return readMultipleLines(DEBUG); return readMultipleLines();
} }
/** /**
@ -191,18 +177,16 @@ public class POP3Client {
* *
* @param id The message id * @param id The message id
* @return The title * @return The title
* @throws IOException
*/ */
public String getMessageTitle(int id) throws IOException{ public String getMessageTitle(int id) throws IOException {
String tmp = getMessageHeader(id); String tmp = getMessageHeader(id);
String tmp2 = tmp.toLowerCase(); String tmp2 = tmp.toLowerCase();
if(tmp2.contains("subject:")){ if (tmp2.contains("subject:")) {
return tmp.substring( return tmp.substring(
tmp2.indexOf("subject:")+8, tmp2.indexOf("subject:") + 8,
tmp2.indexOf('\n', tmp2.indexOf('\n',
tmp2.indexOf("subject:"))); tmp2.indexOf("subject:")));
} } else
else
return null; return null;
} }
@ -211,73 +195,54 @@ public class POP3Client {
* *
* @param id The id of the message to get * @param id The id of the message to get
* @return The message * @return The message
* @throws IOException
*/ */
public String getMessageHeader(int id) throws IOException{ private String getMessageHeader(int id) throws IOException {
sendCommand("TOP "+id+" 0"); sendCommand("TOP " + id + " 0");
return readMultipleLines(DEBUG); return readMultipleLines();
} }
/** /**
* Deletes the message with the given id * Deletes the message with the given id
* *
* @param id The id of the message to be deleted * @param id The id of the message to be deleted
* @throws IOException
*/ */
public void delete(int id) throws IOException{ public void delete(int id) throws IOException {
sendCommand("DELE "+id); sendCommand("DELE " + id);
} }
//*********************** IO Stuff ********************************************* //*********************** IO Stuff *********************************************
/**
* Sends the given line to the server and returns a status integer
*
* @param cmd The command to send
* @return The return code from the server
* @throws IOException if the cmd fails
*/
private boolean sendCommand(String cmd) throws IOException{
return parseReturnCode(sendCommand(cmd, DEBUG));
}
/** /**
* Sends the given line to the server and returns the last line * Sends the given line to the server and returns the last line
* *
* @param cmd The command to send * @param cmd The command to send
* @param print To print out the received lines
* @return Last String line from the server * @return Last String line from the server
* @throws IOException
*/ */
private String sendCommand(String cmd, boolean print) throws IOException{ private String sendCommand(String cmd) throws IOException {
sendNoReplyCommand(cmd, print); sendNoReplyCommand(cmd);
return readCommand(print); return readCommand();
} }
/** /**
* Sends a given command and don't cares about the reply * Sends a given command and don't cares about the reply
* *
* @param cmd The command * @param cmd The command
* @param print If it should print to System.out
* @throws IOException
*/ */
private void sendNoReplyCommand(String cmd, boolean print) throws IOException{ private void sendNoReplyCommand(String cmd) {
out.println(cmd); out.println(cmd);
if(print)System.out.println(cmd); logger.finest(cmd);
} }
/** /**
* Reads on line from the command channel * Reads on line from the command channel
* *
* @param print If the method should print the input line
* @return The input line * @return The input line
* @throws IOException if the server returns a error code
*/ */
private String readCommand(boolean print) throws IOException{ private String readCommand() throws IOException {
String tmp = in.readLine(); String tmp = in.readLine();
if(print)System.out.println(tmp); logger.finest(tmp);
if( !parseReturnCode(tmp) ) throw new IOException(tmp); if (!parseReturnCode(tmp)) throw new IOException(tmp);
return tmp; return tmp;
} }
@ -286,18 +251,16 @@ public class POP3Client {
* Reads from the server until there are a line with * Reads from the server until there are a line with
* only one '.' * only one '.'
* *
* @param print To print out the received lines
* @return String with the text * @return String with the text
* @throws IOException
*/ */
private String readMultipleLines(boolean print) throws IOException{ private String readMultipleLines() throws IOException {
StringBuffer msg = new StringBuffer(); StringBuilder msg = new StringBuilder();
String tmp = in.readLine(); String tmp = in.readLine();
while(!tmp.equals(".")){ while (!tmp.equals(".")) {
msg.append(tmp); msg.append(tmp);
msg.append('\n'); msg.append('\n');
tmp = in.readLine(); tmp = in.readLine();
if(print)System.out.println(tmp); logger.finest(tmp);
} }
return msg.toString(); return msg.toString();
@ -309,30 +272,26 @@ public class POP3Client {
* *
* @param msg The message from the server * @param msg The message from the server
* @return Returns true if return code is OK false if it is ERR * @return Returns true if return code is OK false if it is ERR
* @throws IOException
*/ */
private boolean parseReturnCode(String msg){ private boolean parseReturnCode(String msg) {
int endpos = (msg.indexOf(' ')<0 ? msg.length() : msg.indexOf(' ')); int endPos = (msg.indexOf(' ') < 0 ? msg.length() : msg.indexOf(' '));
return msg.substring(0, endpos).equals("+OK"); return msg.substring(0, endPos).equals("+OK");
} }
//********************************************************************************* //*********************************************************************************
/** /**
* All the delete marked messages are unmarkt * All the delete marked messages are unmarked
* @throws IOException
*/ */
public void reset() throws IOException{ public void reset() throws IOException {
sendCommand("RSET", DEBUG); sendCommand("RSET");
} }
/** /**
* All the changes(DELETE) are performed and then the connection is closed * All the changes(DELETE) are performed and then the connection is closed
*
* @throws IOException
*/ */
public void close() throws IOException{ public void close() throws IOException {
sendCommand("QUIT", DEBUG); sendCommand("QUIT");
in.close(); in.close();
out.close(); out.close();
socket.close(); socket.close();

View file

@ -33,33 +33,32 @@ import java.net.InetAddress;
import java.net.MulticastSocket; import java.net.MulticastSocket;
/** /**
* This class broadcast its address in the LAN so that * This class broadcast its address in the LAN so that
* the ServerFindClient can get the server IP * the ServerFindClient can get the server IP
* *
* @author Ziver * @author Ziver
* *
*/ */
public class ServerFind extends Thread { public class ServerFind extends Thread {
public String broadcastAddress = "230.0.0.1"; private static final String BROADCAST_ADDRESS = "230.0.0.1";
private InetAddress group; private InetAddress group;
private MulticastSocket Msocket; private MulticastSocket mSocket;
private boolean avsluta; private boolean shutdown;
private int port; private int port;
/** /**
* Creates a ServerFind Thread an the specified port * Creates a ServerFind Thread an the specified port
* *
* @param port The port to run the ServerFind Server on * @param port The port to run the ServerFind Server on
* @throws IOException
*/ */
public ServerFind (int port) throws IOException { public ServerFind (int port) throws IOException {
this.port = port; this.port = port;
avsluta = false; shutdown = false;
group = InetAddress.getByName(broadcastAddress); group = InetAddress.getByName(BROADCAST_ADDRESS);
Msocket = new MulticastSocket(port); mSocket = new MulticastSocket(port);
Msocket.joinGroup(group); mSocket.joinGroup(group);
start(); start();
} }
@ -67,12 +66,12 @@ public class ServerFind extends Thread {
public void run (){ public void run (){
byte[] buf = new byte[256]; byte[] buf = new byte[256];
DatagramPacket packet; DatagramPacket packet;
DatagramSocket lan_socket = null; DatagramSocket lan_socket;
while (!avsluta){ while (!shutdown){
try { try {
packet = new DatagramPacket(buf, buf.length); packet = new DatagramPacket(buf, buf.length);
Msocket.receive(packet); mSocket.receive(packet);
lan_socket = new DatagramSocket(port , packet.getAddress()); lan_socket = new DatagramSocket(port , packet.getAddress());
packet = new DatagramPacket(buf, buf.length, group, port); packet = new DatagramPacket(buf, buf.length, group, port);
@ -91,7 +90,7 @@ public class ServerFind extends Thread {
* Closes the broadcast socket * Closes the broadcast socket
*/ */
public void close(){ public void close(){
avsluta = true; shutdown = true;
Msocket.close(); mSocket.close();
} }
} }

View file

@ -32,7 +32,7 @@ import java.net.MulticastSocket;
/** /**
* This class is the client for ServerFind that receives the server IP * This class is the client for ServerFind that receives the server IP
* *
* @author Ziver * @author Ziver
* *
*/ */
@ -54,7 +54,6 @@ public class ServerFindClient{
* Requests IP from server * Requests IP from server
* *
* @return The address of the server * @return The address of the server
* @throws IOException
*/ */
public InetAddress find() throws IOException{ public InetAddress find() throws IOException{
InetAddress group = InetAddress.getByName(broadcastAddress); InetAddress group = InetAddress.getByName(broadcastAddress);

View file

@ -85,7 +85,6 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD
* @param name is the domain name to add the entry under * @param name is the domain name to add the entry under
* @param type {@link zutil.net.dns.packet.DnsConstants.TYPE} * @param type {@link zutil.net.dns.packet.DnsConstants.TYPE}
* @param clazz {@link zutil.net.dns.packet.DnsConstants.CLASS} * @param clazz {@link zutil.net.dns.packet.DnsConstants.CLASS}
* @param data
*/ */
public void addEntry(String name, int type, int clazz, byte[] data){ public void addEntry(String name, int type, int clazz, byte[] data){
DnsPacketResource resource = new DnsPacketResource(); DnsPacketResource resource = new DnsPacketResource();
@ -101,7 +100,7 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD
private void addEntry(DnsPacketResource resource) { private void addEntry(DnsPacketResource resource) {
if ( ! entries.containsKey(resource.name)) if ( ! entries.containsKey(resource.name))
entries.put(resource.name, new ArrayList<DnsPacketResource>()); entries.put(resource.name, new ArrayList<>());
entries.get(resource.name).add(resource); entries.get(resource.name).add(resource);
} }

View file

@ -34,13 +34,13 @@ import java.net.URL;
import java.util.HashMap; import java.util.HashMap;
/** /**
* This class connects to a HTTP server and * This class connects to a HTTP server and
* parses the result * parses the result
* *
* @author Ziver * @author Ziver
*/ */
public class HttpClient implements AutoCloseable{ public class HttpClient implements AutoCloseable{
public static enum HttpRequestType{ public enum HttpRequestType{
GET, POST GET, POST
} }
@ -59,8 +59,8 @@ public class HttpClient implements AutoCloseable{
public HttpClient(HttpRequestType type){ public HttpClient(HttpRequestType type){
this.type = type; this.type = type;
headers = new HashMap<String,String>(); headers = new HashMap<>();
cookies = new HashMap<String,String>(); cookies = new HashMap<>();
} }
@ -112,7 +112,7 @@ public class HttpClient implements AutoCloseable{
request.setCookies( cookies ); request.setCookies( cookies );
if( type == HttpRequestType.POST ){ if( type == HttpRequestType.POST ){
String postData = null; String postData;
if(data != null) if(data != null)
postData = data; postData = data;
else else

View file

@ -46,9 +46,9 @@ public class HttpHeader {
public HttpHeader(){ public HttpHeader(){
urlAttributes = new HashMap<String, String>(); urlAttributes = new HashMap<>();
headers = new HashMap<String, String>(); headers = new HashMap<>();
cookies = new HashMap<String, String>(); cookies = new HashMap<>();
} }

View file

@ -29,11 +29,11 @@ import java.util.Map;
/** /**
* This is a interface for a ordinary page for the HttpServer * This is a interface for a ordinary page for the HttpServer
* *
* @author Ziver * @author Ziver
* *
*/ */
public interface HttpPage{ public interface HttpPage{
/** /**
* This method has to be implemented for every page. * This method has to be implemented for every page.
* This method is called when a client wants a response * This method is called when a client wants a response
@ -45,9 +45,9 @@ public interface HttpPage{
* @param cookie is cookie information from the client * @param cookie is cookie information from the client
* @param request is POST and GET requests from the client * @param request is POST and GET requests from the client
*/ */
public abstract void respond(HttpPrintStream out, void respond(HttpPrintStream out,
HttpHeader headers, HttpHeader headers,
Map<String,Object> session, Map<String, Object> session,
Map<String,String> cookie, Map<String, String> cookie,
Map<String,String> request) throws IOException; Map<String, String> request) throws IOException;
} }

View file

@ -34,7 +34,7 @@ import java.util.HashMap;
/** /**
* This PrintStream is written for HTTP use * This PrintStream is written for HTTP use
* It has buffer capabilities and cookie management. * It has buffer capabilities and cookie management.
* *
* @author Ziver * @author Ziver
* *
*/ */
@ -87,8 +87,8 @@ public class HttpPrintStream extends OutputStream{
this.httpVersion = "1.0"; this.httpVersion = "1.0";
this.message_type = type; this.message_type = type;
this.res_status_code = 200; this.res_status_code = 200;
this.headers = new HashMap<String, String>(); this.headers = new HashMap<>();
this.cookies = new HashMap<String, String>(); this.cookies = new HashMap<>();
this.buffer = new StringBuffer(); this.buffer = new StringBuffer();
this.buffer_enabled = false; this.buffer_enabled = false;
} }
@ -99,11 +99,9 @@ public class HttpPrintStream extends OutputStream{
* is enabled until you close or flush the stream. * is enabled until you close or flush the stream.
* This function will flush the stream if buffering is * This function will flush the stream if buffering is
* disabled. * disabled.
*
* @param b
*/ */
public void enableBuffering(boolean b) throws IOException { public void enableBuffering(boolean enable) throws IOException {
buffer_enabled = b; buffer_enabled = enable;
if(!buffer_enabled) flush(); if(!buffer_enabled) flush();
} }
@ -211,7 +209,7 @@ public class HttpPrintStream extends OutputStream{
/** /**
* Will buffer String or directly output headers if needed and then the String * Will buffer String or directly output headers if needed and then the String
*/ */
private void printOrBuffer(String s) throws IOException { private void printOrBuffer(String s) {
if(buffer_enabled){ if(buffer_enabled){
buffer.append(s); buffer.append(s);
} }

View file

@ -46,7 +46,7 @@ import java.util.logging.Logger;
/** /**
* A simple web server that handles both cookies and * A simple web server that handles both cookies and
* sessions for all the clients * sessions for all the clients
* *
* @author Ziver * @author Ziver
*/ */
public class HttpServer extends ThreadedTCPNetworkServer{ public class HttpServer extends ThreadedTCPNetworkServer{
@ -272,7 +272,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
buff.append(", cookies: ").append(header==null ? null : header.toStringCookies()); buff.append(", cookies: ").append(header==null ? null : header.toStringCookies());
buff.append(", session: ").append(session); buff.append(", session: ").append(session);
buff.append(")"); buff.append(")");
buff.append(", time: "+ StringUtil.formatTimeToString(System.currentTimeMillis() - time)); buff.append(", time: ").append(StringUtil.formatTimeToString(System.currentTimeMillis() - time));
logger.finer(buff.toString()); logger.finer(buff.toString());
} else if(logger.isLoggable(Level.FINER)){ } else if(logger.isLoggable(Level.FINER)){

View file

@ -29,7 +29,7 @@ import java.util.HashMap;
/** /**
* Handles URLs in the HTTP protocol * Handles URLs in the HTTP protocol
* *
* @author Ziver * @author Ziver
*/ */
public class HttpURL { public class HttpURL {
@ -45,7 +45,7 @@ public class HttpURL {
private String path; private String path;
private String anchor; private String anchor;
private HashMap<String,String> parameters = new HashMap<String,String>(); private HashMap<String,String> parameters = new HashMap<>();
public HttpURL(){} public HttpURL(){}

View file

@ -27,18 +27,18 @@ package zutil.net.http.multipart;
/** /**
* A interface representing a single field in a multipart message. * A interface representing a single field in a multipart message.
* *
* @author Ziver * @author Ziver
*/ */
public interface MultipartField{ public interface MultipartField{
/** /**
* @return the amount of data received for this field. Might only be available when all data has been processed * @return the amount of data received for this field. Might only be available when all data has been processed
*/ */
public long getLength(); long getLength();
/** /**
* @return the name of the field. * @return the name of the field.
*/ */
public String getName(); String getName();
} }

View file

@ -36,7 +36,7 @@ import static zutil.net.http.multipart.MultipartParser.HEADER_CONTENT_TYPE;
/** /**
* A class for handling multipart files * A class for handling multipart files
* *
* @author Ziver * @author Ziver
*/ */
public class MultipartFileField implements MultipartField{ public class MultipartFileField implements MultipartField{
@ -49,7 +49,7 @@ public class MultipartFileField implements MultipartField{
private InputStream in; private InputStream in;
protected MultipartFileField(Map<String,String> headers, InputStream in) throws IOException { protected MultipartFileField(Map<String,String> headers, InputStream in) {
this.fieldname = headers.get("name"); this.fieldname = headers.get("name");
this.filename = headers.get("filename"); this.filename = headers.get("filename");
this.contentType = headers.get(HEADER_CONTENT_TYPE); this.contentType = headers.get(HEADER_CONTENT_TYPE);

View file

@ -38,11 +38,11 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
/** /**
* Parses a multipart/form-data http request, * Parses a multipart/form-data http request,
* saves files to temporary location. * saves files to temporary location.
* *
* http://www.ietf.org/rfc/rfc1867.txt * http://www.ietf.org/rfc/rfc1867.txt
* *
* @author Ziver * @author Ziver
* *
*/ */
@ -155,8 +155,7 @@ public class MultipartParser implements Iterable<MultipartField>{
HttpHeaderParser.parseCookieValues(headers, disposition); HttpHeaderParser.parseCookieValues(headers, disposition);
if (headers.containsKey("form-data")){ if (headers.containsKey("form-data")){
if (headers.containsKey("filename")){ if (headers.containsKey("filename")){
MultipartFileField field = new MultipartFileField(headers, boundaryIn); return new MultipartFileField(headers, boundaryIn);
return field;
} }
else{ else{
MultipartStringField field = new MultipartStringField(headers, boundaryIn); MultipartStringField field = new MultipartStringField(headers, boundaryIn);

View file

@ -42,10 +42,7 @@ public class HttpDigestAuthPage implements HttpPage{
private HttpPage targetPage; private HttpPage targetPage;
/**
*
* @param page
*/
public HttpDigestAuthPage(HttpPage page){ public HttpDigestAuthPage(HttpPage page){
targetPage = page; targetPage = page;
} }

View file

@ -119,17 +119,12 @@ public class HttpFilePage implements HttpPage{
} }
} }
}catch (FileNotFoundException e){ }catch (FileNotFoundException | SecurityException e){
if(!out.isHeaderSent()) if(!out.isHeaderSent())
out.setStatusCode(404); out.setStatusCode(404);
log.log(Level.WARNING, e.getMessage()); log.log(Level.WARNING, e.getMessage());
out.println("404 Page Not Found: " + headers.getRequestURL()); out.println("404 Page Not Found: " + headers.getRequestURL());
}catch (SecurityException e){ } catch (IOException e){
if(!out.isHeaderSent())
out.setStatusCode(404);
log.log(Level.WARNING, e.getMessage());
out.println("404 Page Not Found: " + headers.getRequestURL() );
}catch (IOException e){
if(!out.isHeaderSent()) if(!out.isHeaderSent())
out.setStatusCode(500); out.setStatusCode(500);
log.log(Level.WARNING, null, e); log.log(Level.WARNING, null, e);

View file

@ -34,20 +34,27 @@ public class MqttPacketConnect extends MqttPacketHeader {
/** Indicates that the controlHeader contains a username */ /** Indicates that the controlHeader contains a username */
@BinaryField(index = 2010, length = 1) @BinaryField(index = 2010, length = 1)
public boolean flagUsername; public boolean flagUsername;
/** Indicates that the controlHeader contains a password */ /** Indicates that the controlHeader contains a password */
@BinaryField(index = 2011, length = 1) @BinaryField(index = 2011, length = 1)
public boolean flagPassword; public boolean flagPassword;
/** Specifies if the Will Message is to be Retained when it is published. */ /** Specifies if the Will Message is to be Retained when it is published. */
@BinaryField(index = 2012, length = 1) @BinaryField(index = 2012, length = 1)
public boolean flagWillRetain; public boolean flagWillRetain;
/** Specifies the QoS level to be used when publishing the Will Message. */ /** Specifies the QoS level to be used when publishing the Will Message. */
@BinaryField(index = 2013, length = 2) @BinaryField(index = 2013, length = 2)
public int flagWillQoS; public int flagWillQoS;
@BinaryField(index = 2014, length = 1) @BinaryField(index = 2014, length = 1)
public boolean flagWillFlag; public boolean flagWillFlag;
@BinaryField(index = 2015, length = 1)
/** This bit specifies the handling of the Session state. */ /** This bit specifies the handling of the Session state. */
@BinaryField(index = 2015, length = 1)
public boolean flagCleanSession; public boolean flagCleanSession;
@BinaryField(index = 2016, length = 1) @BinaryField(index = 2016, length = 1)
private boolean reserved; private boolean reserved;

View file

@ -67,7 +67,7 @@ public class NioClient extends NioNetwork{
* *
* @param data the data to be sent * @param data the data to be sent
*/ */
public void send(byte[] data) throws IOException { public void send(byte[] data) {
send(remoteAddress, data); send(remoteAddress, data);
} }

View file

@ -55,12 +55,12 @@ public abstract class NioNetwork implements Runnable {
protected Worker worker; protected Worker worker;
// This map contains all the clients that are connected // This map contains all the clients that are connected
protected Map<InetSocketAddress, ClientData> clients = new HashMap<InetSocketAddress, ClientData>(); protected Map<InetSocketAddress, ClientData> clients = new HashMap<>();
// A list of PendingChange instances // A list of PendingChange instances
private List<ChangeRequest> pendingChanges = new LinkedList<ChangeRequest>(); private List<ChangeRequest> pendingChanges = new LinkedList<>();
// Maps a SocketChannel to a list of ByteBuffer instances // Maps a SocketChannel to a list of ByteBuffer instances
private Map<SocketChannel, List<ByteBuffer>> pendingWriteData = new HashMap<SocketChannel, List<ByteBuffer>>(); private Map<SocketChannel, List<ByteBuffer>> pendingWriteData = new HashMap<>();
@ -160,19 +160,17 @@ public abstract class NioNetwork implements Runnable {
try { try {
// Handle any pending changes // Handle any pending changes
synchronized (pendingChanges) { synchronized (pendingChanges) {
Iterator<ChangeRequest> changes = pendingChanges.iterator(); for (ChangeRequest change : pendingChanges) {
while (changes.hasNext()) {
ChangeRequest change = changes.next();
switch (change.type) { switch (change.type) {
case ChangeRequest.CHANGEOPS: case ChangeRequest.CHANGEOPS:
SelectionKey key = change.socket.keyFor(selector); SelectionKey key = change.socket.keyFor(selector);
key.interestOps(change.ops); key.interestOps(change.ops);
logger.finest("change.ops "+change.ops); logger.finest("change.ops " + change.ops);
break; break;
case ChangeRequest.REGISTER: case ChangeRequest.REGISTER:
change.socket.register(selector, change.ops); change.socket.register(selector, change.ops);
logger.finest("register socket "); logger.finest("register socket ");
break; break;
} }
} }
pendingChanges.clear(); pendingChanges.clear();

View file

@ -30,5 +30,5 @@ package zutil.net.nio.worker.chat;
* *
*/ */
public interface ChatListener { public interface ChatListener {
public void messageAction(String msg, String room); void messageAction(String msg, String room);
} }

View file

@ -29,7 +29,7 @@ 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 enum ChatMessageType {REGISTER, UNREGISTER, MESSAGE};
public ChatMessageType type; public ChatMessageType type;
public String msg; public String msg;

View file

@ -35,7 +35,7 @@ import java.util.logging.Logger;
/** /**
* A simple chat service with users and rooms * A simple chat service with users and rooms
* *
* @author Ziver * @author Ziver
*/ */
public class ChatService extends ThreadedEventWorker{ public class ChatService extends ThreadedEventWorker{
@ -126,7 +126,7 @@ public class ChatService extends ThreadedEventWorker{
private void addRoom(String room){ private void addRoom(String room){
if(!rooms.containsKey(room)){ if(!rooms.containsKey(room)){
logger.fine("New Chat Room: "+room); logger.fine("New Chat Room: "+room);
rooms.put(room, new LinkedList<SocketAddress>()); rooms.put(room, new LinkedList<>());
} }
} }

View file

@ -37,7 +37,7 @@ import java.util.Queue;
* This class is the client part of the grid. * This class is the client part of the grid.
* It connects to a grid server and requests new job. * It connects to a grid server and requests new job.
* And then sends back the result to the server. * And then sends back the result to the server.
* *
* @author Ziver * @author Ziver
*/ */
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
@ -54,7 +54,7 @@ public class GridClient extends ThreadedEventWorker {
* @param network the NioClient to use to communicate to the server * @param network the NioClient to use to communicate to the server
*/ */
public GridClient(GridThread thread, NioClient network){ public GridClient(GridThread thread, NioClient network){
jobQueue = new LinkedList<GridJob>(); jobQueue = new LinkedList<>();
GridClient.thread = thread; GridClient.thread = thread;
GridClient.network = network; GridClient.network = network;
@ -85,7 +85,7 @@ public class GridClient extends ThreadedEventWorker {
thread.setInitData(msg.getData()); thread.setInitData(msg.getData());
break; break;
case GridMessage.COMP_DATA: case GridMessage.COMP_DATA:
jobQueue.add(new GridJob(msg.getJobQueueID(), (Queue)msg.getData())); jobQueue.add(new GridJob(msg.getJobQueueID(), msg.getData()));
break; break;
} }
} }

View file

@ -38,7 +38,6 @@ public abstract class ObjectSync {
/** /**
* Applies the SyncMessage to the object * Applies the SyncMessage to the object
* @param message
*/ */
public abstract void syncObject(SyncMessage message); public abstract void syncObject(SyncMessage message);

View file

@ -104,7 +104,7 @@ public class SmtpClient {
* *
* @param email a email object containing message specific data * @param email a email object containing message specific data
*/ */
public synchronized void send(Email email) throws IOException{ public synchronized void send(Email email) {
if(email.getFromAddress() == null) if(email.getFromAddress() == null)
throw new IllegalArgumentException("From value cannot be null!"); throw new IllegalArgumentException("From value cannot be null!");
if(email.getToAddress() == null) if(email.getToAddress() == null)

View file

@ -46,7 +46,7 @@ import static zutil.net.ssdp.SSDPServer.SSDP_PORT;
/** /**
* An SSDP client class that will request * An SSDP client class that will request
* service information. * service information.
* *
* @author Ziver * @author Ziver
*/ */
public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetworkThread{ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetworkThread{
@ -63,8 +63,6 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork
/** /**
* Creates new instance of this class. An UDP * Creates new instance of this class. An UDP
* listening socket at the SSDP port. * listening socket at the SSDP port.
*
* @throws IOException
*/ */
public SSDPClient() throws IOException{ public SSDPClient() throws IOException{
super( SSDP_MULTICAST_ADDR, SSDP_PORT ); super( SSDP_MULTICAST_ADDR, SSDP_PORT );
@ -231,7 +229,7 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork
service = new StandardSSDPInfo(); service = new StandardSSDPInfo();
services_usn.put(usn, service); services_usn.put(usn, service);
if (!services_st.containsKey(st)) if (!services_st.containsKey(st))
services_st.put(st, new LinkedList<StandardSSDPInfo>()); services_st.put(st, new LinkedList<>());
services_st.get(header.getHeader("ST")).add(service); services_st.get(header.getHeader("ST")).add(service);
} }

View file

@ -24,7 +24,7 @@
package zutil.net.ssdp; package zutil.net.ssdp;
import zutil.net.http.HttpHeader; import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPrintStream; import zutil.net.http.HttpPrintStream;
/** /**
@ -32,7 +32,7 @@ import zutil.net.http.HttpPrintStream;
*/ */
public interface SSDPCustomInfo extends SSDPServiceInfo{ public interface SSDPCustomInfo extends SSDPServiceInfo{
public void readHeaders(HttpHeader http); void readHeaders(HttpHeader http);
public void writeHeaders(HttpPrintStream http); void writeHeaders(HttpPrintStream http);
} }

View file

@ -43,13 +43,13 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
/** /**
* A Server class that announces an service by the SSDP * A Server class that announces an service by the SSDP
* protocol specified at: * protocol specified at:
* http://coherence.beebits.net/chrome/site/draft-cai-ssdp-v1-03.txt * http://coherence.beebits.net/chrome/site/draft-cai-ssdp-v1-03.txt
* ftp://ftp.pwg.org/pub/pwg/www/hypermail/ps/att-0188/01-psi_SSDP.pdf * ftp://ftp.pwg.org/pub/pwg/www/hypermail/ps/att-0188/01-psi_SSDP.pdf
* *
* @author Ziver * @author Ziver
* *
* ********* Message clarification: * ********* Message clarification:
* ****** Incoming: * ****** Incoming:
* ST: Search Target, this is object of the discovery request, (e.g., ssdp:all, etc.) * ST: Search Target, this is object of the discovery request, (e.g., ssdp:all, etc.)
@ -85,7 +85,7 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork
super( SSDP_MULTICAST_ADDR, SSDP_PORT ); super( SSDP_MULTICAST_ADDR, SSDP_PORT );
super.setThread( this ); super.setThread( this );
services = new HashMap<String, SSDPServiceInfo>(); services = new HashMap<>();
setCacheTime( DEFAULT_CACHE_TIME ); setCacheTime( DEFAULT_CACHE_TIME );
enableNotify( true ); enableNotify( true );

View file

@ -27,7 +27,7 @@ package zutil.net.ssdp;
/** /**
* This class contains information about a service from * This class contains information about a service from
* or through the SSDP protocol * or through the SSDP protocol
* *
* @author Ziver * @author Ziver
*/ */
public interface SSDPServiceInfo { public interface SSDPServiceInfo {
@ -35,25 +35,25 @@ public interface SSDPServiceInfo {
/** /**
* @return the URL to the Service, e.g. "http://192.168.0.1:80/index.html" * @return the URL to the Service, e.g. "http://192.168.0.1:80/index.html"
*/ */
public String getLocation(); String getLocation();
/** /**
* @return the Search Target, e.g. "upnp:rootdevice" * @return the Search Target, e.g. "upnp:rootdevice"
*/ */
public String getSearchTarget(); String getSearchTarget();
/** /**
* @return the expiration time for the values in this object * @return the expiration time for the values in this object
*/ */
public long getExpirationTime(); long getExpirationTime();
/** /**
* @return the USN value, e.g. "uuid:abcdefgh-7dec-11d0-a765-00a0c91e6bf6 " * @return the USN value, e.g. "uuid:abcdefgh-7dec-11d0-a765-00a0c91e6bf6 "
*/ */
public String getUSN(); String getUSN();
/** /**
* @return only the USN UUID String * @return only the USN UUID String
*/ */
public String getUUID(); String getUUID();
} }

View file

@ -43,7 +43,7 @@ import java.util.logging.Logger;
/** /**
* A simple network server that handles TCP communication * A simple network server that handles TCP communication
* *
* @author Ziver * @author Ziver
*/ */
public abstract class ThreadedTCPNetworkServer extends Thread{ public abstract class ThreadedTCPNetworkServer extends Thread{
@ -139,7 +139,7 @@ public abstract class ThreadedTCPNetworkServer extends Thread{
* *
* @param keyStore The cert file * @param keyStore The cert file
*/ */
protected void registerCertificate(File keyStore, String keyStorePass) throws CertificateException, IOException, KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException{ protected void registerCertificate(File keyStore, String keyStorePass) {
System.setProperty("javax.net.ssl.keyStore", keyStore.getAbsolutePath()); System.setProperty("javax.net.ssl.keyStore", keyStore.getAbsolutePath());
System.setProperty("javax.net.ssl.keyStorePassword", keyStorePass); System.setProperty("javax.net.ssl.keyStorePassword", keyStorePass);
} }

View file

@ -31,7 +31,7 @@ import java.net.*;
/** /**
* * A simple network server that handles UDP communication * * A simple network server that handles UDP communication
* *
* @author Ziver * @author Ziver
*/ */
public class ThreadedUDPNetwork extends Thread{ public class ThreadedUDPNetwork extends Thread{
@ -49,8 +49,6 @@ public class ThreadedUDPNetwork extends Thread{
/** /**
* Creates a new unicast Client instance of the class * Creates a new unicast Client instance of the class
*
* @throws SocketException
*/ */
public ThreadedUDPNetwork() throws SocketException{ public ThreadedUDPNetwork() throws SocketException{
this.type = UDPType.UNICAST; this.type = UDPType.UNICAST;
@ -63,7 +61,6 @@ public class ThreadedUDPNetwork extends Thread{
* Creates a new unicast Server instance of the class * Creates a new unicast Server instance of the class
* *
* @param port is the port that the server should listen to * @param port is the port that the server should listen to
* @throws SocketException
*/ */
public ThreadedUDPNetwork(int port) throws SocketException{ public ThreadedUDPNetwork(int port) throws SocketException{
this.type = UDPType.UNICAST; this.type = UDPType.UNICAST;
@ -77,7 +74,6 @@ public class ThreadedUDPNetwork extends Thread{
* *
* @param port is the port that the server should listen to * @param port is the port that the server should listen to
* @param multicastAddr is the multicast address that the server will listen on * @param multicastAddr is the multicast address that the server will listen on
* @throws IOException
*/ */
public ThreadedUDPNetwork(String multicastAddr, int port ) throws IOException{ public ThreadedUDPNetwork(String multicastAddr, int port ) throws IOException{
this.type = UDPType.MULTICAST; this.type = UDPType.MULTICAST;
@ -110,7 +106,6 @@ public class ThreadedUDPNetwork extends Thread{
* Sends the given packet * Sends the given packet
* *
* @param packet is the packet to send * @param packet is the packet to send
* @throws IOException
*/ */
public synchronized void send( DatagramPacket packet ) throws IOException{ public synchronized void send( DatagramPacket packet ) throws IOException{
socket.send(packet); socket.send(packet);

View file

@ -85,7 +85,7 @@ public class TorrentMetainfo {
creation_date = metainfo.getLong("creation date"); creation_date = metainfo.getLong("creation date");
if( metainfo.get("announce-list") != null ){ if( metainfo.get("announce-list") != null ){
DataNode tmp = metainfo.get("announce-list"); DataNode tmp = metainfo.get("announce-list");
announce_list = new ArrayList<String>(); announce_list = new ArrayList<>();
for( DataNode tracker : tmp ) for( DataNode tracker : tmp )
announce_list.add( tracker.getString() ); announce_list.add( tracker.getString() );
} }
@ -98,7 +98,7 @@ public class TorrentMetainfo {
is_private = (info.getInt("private") != 0); is_private = (info.getInt("private") != 0);
// Split the hashes // Split the hashes
String hashes = info.getString("pieces"); String hashes = info.getString("pieces");
piece_hashes = new ArrayList<String>(); piece_hashes = new ArrayList<>();
for(int i=0; i<hashes.length(); ){ for(int i=0; i<hashes.length(); ){
StringBuilder hash = new StringBuilder(20); StringBuilder hash = new StringBuilder(20);
for(int k=0; k<20; ++i, ++k) for(int k=0; k<20; ++i, ++k)
@ -107,7 +107,7 @@ public class TorrentMetainfo {
} }
// File data // File data
file_list = new ArrayList<TorrentFile>(); file_list = new ArrayList<>();
// Single-file torrent // Single-file torrent
if( info.get("files") == null ){ if( info.get("files") == null ){
Long fileSize = size = info.getLong("length"); Long fileSize = size = info.getLong("length");

View file

@ -35,30 +35,31 @@ import java.util.List;
/** /**
* This class is used to store the files * This class is used to store the files
* and there hashes * and there hashes
* *
* @author Ziver * @author Ziver
*/ */
class FileListMessage implements Serializable{ class FileListMessage implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private ArrayList<FileInfo> fileList; private ArrayList<FileInfo> fileList;
private long totalSize; private long totalSize;
private FileListMessage(){} private FileListMessage() {
}
/** /**
* Returns a ArrayList of FileInfo object for all the files in the specified folder * Returns a ArrayList of FileInfo object for all the files in the specified folder
* *
* @param path is the path to scan * @param path is the path to scan
**/ **/
public FileListMessage(String path) throws IOException{ public FileListMessage(String path) throws IOException {
fileList = new ArrayList<FileInfo>(); fileList = new ArrayList<>();
List<File> files = FileUtil.search(FileUtil.find(path)); List<File> files = FileUtil.search(FileUtil.find(path));
long totalSize = 0; long totalSize = 0;
for(File file : files){ for (File file : files) {
FileInfo fileInfo = new FileInfo(path, file); FileInfo fileInfo = new FileInfo(path, file);
fileList.add( fileInfo ); fileList.add(fileInfo);
totalSize += fileInfo.getSize(); totalSize += fileInfo.getSize();
} }
this.totalSize = totalSize; this.totalSize = totalSize;
@ -69,24 +70,24 @@ class FileListMessage implements Serializable{
return totalSize; return totalSize;
} }
public ArrayList<FileInfo> getFileList(){ public ArrayList<FileInfo> getFileList() {
return fileList; return fileList;
} }
/** /**
* Compares the files and returns the files that differ from this file list * Compares files and returns the ones that differ from this file list
* *
* @param comp is the file list to compare with * @param comp is the file list to compare with
* @return * @return a list of files that diff
*/ */
public FileListMessage getDiff( FileListMessage comp){ public FileListMessage getDiff(FileListMessage comp) {
FileListMessage diff = new FileListMessage(); FileListMessage diff = new FileListMessage();
long diffSize = 0; long diffSize = 0;
diff.fileList = new ArrayList<FileInfo>(); diff.fileList = new ArrayList<>();
for(FileInfo file : this.fileList){ for (FileInfo file : this.fileList) {
if( !comp.fileList.contains( file)){ if (!comp.fileList.contains(file)) {
diff.fileList.add( file ); diff.fileList.add(file);
diffSize += file.getSize(); diffSize += file.getSize();
} }
} }
@ -96,9 +97,9 @@ class FileListMessage implements Serializable{
} }
public boolean equals(Object comp){ public boolean equals(Object comp) {
if(comp instanceof FileListMessage){ if (comp instanceof FileListMessage) {
FileListMessage tmp = (FileListMessage)comp; FileListMessage tmp = (FileListMessage) comp;
return fileList.equals(tmp.fileList) && totalSize == tmp.totalSize; return fileList.equals(tmp.fileList) && totalSize == tmp.totalSize;
} }
return false; return false;

View file

@ -36,7 +36,7 @@ import java.util.logging.Logger;
/** /**
* This class connects to a update server and updates a path * This class connects to a update server and updates a path
* with the servers * with the servers
* *
* @author Ziver * @author Ziver
* *
*/ */
@ -58,7 +58,6 @@ public class UpdateClient{
* @param address Address to the UpdateServer * @param address Address to the UpdateServer
* @param port The port on the server * @param port The port on the server
* @param path Path to the files to update * @param path Path to the files to update
* @throws Exception
*/ */
public UpdateClient(String address, int port, String path) throws Exception{ public UpdateClient(String address, int port, String path) throws Exception{
fileList = new FileListMessage(path); fileList = new FileListMessage(path);
@ -102,9 +101,9 @@ public class UpdateClient{
byte[] buffer = new byte[socket.getReceiveBufferSize()]; byte[] buffer = new byte[socket.getReceiveBufferSize()];
long bytesReceived = 0; long bytesReceived = 0;
int byteRead = 0; int byteRead;
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
long timeTotalRecived = 0; long timeTotalReceived = 0;
while( bytesReceived < info.getSize() ) { while( bytesReceived < info.getSize() ) {
byteRead = in.read(buffer); byteRead = in.read(buffer);
@ -113,8 +112,8 @@ public class UpdateClient{
if(time+1000 < System.currentTimeMillis()){ if(time+1000 < System.currentTimeMillis()){
time = System.currentTimeMillis(); time = System.currentTimeMillis();
speed = (int)(totalReceived - timeTotalRecived); speed = (int)(totalReceived - timeTotalReceived);
timeTotalRecived = totalReceived; timeTotalReceived = totalReceived;
} }
totalReceived += byteRead; totalReceived += byteRead;
@ -165,8 +164,6 @@ public class UpdateClient{
/** /**
* Closes the connection * Closes the connection
*
* @throws IOException
*/ */
public void close() throws IOException{ public void close() throws IOException{
socket.close(); socket.close();

View file

@ -102,7 +102,7 @@ public class UpdateServer extends ThreadedTCPNetworkServer{
// send file data // send file data
FileInputStream input = new FileInputStream( info.getFile() ); FileInputStream input = new FileInputStream( info.getFile() );
byte[] nextBytes = new byte[ socket.getSendBufferSize() ]; byte[] nextBytes = new byte[ socket.getSendBufferSize() ];
int bytesRead = 0; int bytesRead;
while((bytesRead = input.read(nextBytes)) > 0){ while((bytesRead = input.read(nextBytes)) > 0){
out.write(nextBytes,0,bytesRead); out.write(nextBytes,0,bytesRead);
} }

View file

@ -40,7 +40,6 @@ import java.awt.event.ActionListener;
public class Zupdater extends JFrame implements ProgressListener<UpdateClient, FileInfo>{ public class Zupdater extends JFrame implements ProgressListener<UpdateClient, FileInfo>{
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JLabel lblSpeed; private JLabel lblSpeed;
private JLabel lblFile; private JLabel lblFile;
private JProgressBar progressBar; private JProgressBar progressBar;
@ -68,7 +67,7 @@ public class Zupdater extends JFrame implements ProgressListener<UpdateClient, F
progressBar.setString( StringUtil.formatByteSizeToString(source.getTotalReceived()) + progressBar.setString( StringUtil.formatByteSizeToString(source.getTotalReceived()) +
" / "+StringUtil.formatByteSizeToString(source.getTotalSize())); " / "+StringUtil.formatByteSizeToString(source.getTotalSize()));
lblSpeed.setText( StringUtil.formatByteSizeToString(((UpdateClient) source).getSpeed())+"/s" ); lblSpeed.setText( StringUtil.formatByteSizeToString(source.getSpeed()) + "/s" );
} }
@ -82,7 +81,7 @@ public class Zupdater extends JFrame implements ProgressListener<UpdateClient, F
setResizable(false); setResizable(false);
setTitle("Updating..."); setTitle("Updating...");
setBounds(100, 100, 537, 124); setBounds(100, 100, 537, 124);
contentPane = new JPanel(); JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane); setContentPane(contentPane);

View file

@ -52,7 +52,7 @@ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface
public UPnPContentDirectory(){} public UPnPContentDirectory(){}
public UPnPContentDirectory(File dir){ public UPnPContentDirectory(File dir){
file_list = FileUtil.search(dir, new LinkedList<File>(), true, Integer.MAX_VALUE); file_list = FileUtil.search(dir, new LinkedList<>(), true, Integer.MAX_VALUE);
} }
/** /**
@ -94,7 +94,6 @@ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface
* exposed by the Content Directory Service, including * exposed by the Content Directory Service, including
* information listing the classes of objects available * information listing the classes of objects available
* in any particular object container. * in any particular object container.
* @throws DocumentException
* *
*/ */
//@WSNameSpace("urn:schemas-upnp-org:service:ContentDirectory:1") //@WSNameSpace("urn:schemas-upnp-org:service:ContentDirectory:1")
@ -104,30 +103,30 @@ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface
@WSParamName("Filter") String Filter, @WSParamName("Filter") String Filter,
@WSParamName("StartingIndex") int StartingIndex, @WSParamName("StartingIndex") int StartingIndex,
@WSParamName("RequestedCount") int RequestedCount, @WSParamName("RequestedCount") int RequestedCount,
@WSParamName("SortCriteria") String SortCriteria) throws DocumentException{ @WSParamName("SortCriteria") String SortCriteria) {
BrowseRetObj ret = new BrowseRetObj(); BrowseRetObj ret = new BrowseRetObj();
if( BrowseFlag.equals("BrowseMetadata") ){ if( BrowseFlag.equals("BrowseMetadata") ){
} }
else if( BrowseFlag.equals("BrowseDirectChildren") ){ else if( BrowseFlag.equals("BrowseDirectChildren") ){
StringBuffer xml = new StringBuffer(); StringBuilder xml = new StringBuilder();
xml.append( "<DIDL-Lite xmlns:dc=\"http://purl.org/dc/elements/1.1/\" " + xml.append( "<DIDL-Lite xmlns:dc=\"http://purl.org/dc/elements/1.1/\" " +
"xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\" " + "xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\" " +
"xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\">" ); "xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\">" );
List<File> tmp = FileUtil.search( file_list.get(Integer.parseInt(ObjectID)), new LinkedList<File>(), false ); List<File> tmp = FileUtil.search( file_list.get(Integer.parseInt(ObjectID)), new LinkedList<>(), false );
for(File file : tmp){ for(File file : tmp){
xml.append(" <container id=\""+file_list.indexOf(file)+"\" "); xml.append(" <container id=\"").append(file_list.indexOf(file)).append("\" ");
if(tmp.get(0) != file) xml.append("parentID=\""+file_list.indexOf(file.getParent())+"\" "); if(tmp.get(0) != file) xml.append("parentID=\"").append(file_list.indexOf(file.getParent())).append("\" ");
if(file.isDirectory()) xml.append("childCount=\""+file.list().length+"\" "); if(file.isDirectory()) xml.append("childCount=\"").append(file.list().length).append("\" ");
xml.append("restricted=\"1\" searchable=\"0\" >"); xml.append("restricted=\"1\" searchable=\"0\" >");
xml.append(" <dc:title>"+file.getName()+"</dc:title> "); xml.append(" <dc:title>").append(file.getName()).append("</dc:title> ");
if( file.isDirectory() ) if( file.isDirectory() )
xml.append(" <upnp:class>object.container.storageFolder</upnp:class> "); xml.append(" <upnp:class>object.container.storageFolder</upnp:class> ");
else else
xml.append(" <upnp:class>object.container</upnp:class> "); xml.append(" <upnp:class>object.container</upnp:class> ");
xml.append(" <upnp:storageUsed>"+(int)(file.length()/1000)+"</upnp:storageUsed> "); xml.append(" <upnp:storageUsed>").append((int) (file.length() / 1000)).append("</upnp:storageUsed> ");
xml.append(" </container> "); xml.append(" </container> ");
ret.NumberReturned++; ret.NumberReturned++;

View file

@ -54,12 +54,9 @@ public class WSClientFactory {
try { try {
Class proxyClass = Proxy.getProxyClass( Class proxyClass = Proxy.getProxyClass(
WSClientFactory.class.getClassLoader(), WSClientFactory.class.getClassLoader(), intf);
new Class[]{intf}); Constructor<T> constructor = proxyClass.getConstructor(InvocationHandler.class);
Constructor<T> constructor = proxyClass.getConstructor( T obj = constructor.newInstance(handler);
new Class[]{InvocationHandler.class});
T obj = constructor.newInstance(
new Object[]{handler});
return obj; return obj;
} catch (Exception e){ } catch (Exception e){

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