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/
/bin/
/target/

4
Jenkinsfile vendored
View file

@ -28,7 +28,9 @@ node {
stage('Deploy') {
// 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
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
*/
public static byte getBits(byte data, int index, int length){
byte ret = (byte) (data & getBitMask(index, length));
return ret;
return (byte) (data & getBitMask(index, length));
}
/**
@ -153,7 +152,7 @@ public class ByteUtil {
if (shiftBy == 0)
return data;
byte rest = 0;
byte rest;
for (int i=0; i<data.length; ++i){
rest = (byte)(getBits(data[i], shiftBy-1, shiftBy) << 8 - shiftBy);
data[i] = (byte)((data[i]&0xFF) >>> shiftBy);
@ -207,7 +206,7 @@ public class ByteUtil {
* @return A multiline String with human readable HEX and ASCII
*/
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 '........'
int maxOffset = (""+length).length();

View file

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

View file

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

View file

@ -166,8 +166,8 @@ public class Encrypter {
public byte[] encrypt(byte[] data){
try {
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);
return encryption;
} catch (Exception e) {

View file

@ -47,9 +47,9 @@ public class Hasher {
public static String hash(File file, String hashType) throws NoSuchAlgorithmException, IOException {
MessageDigest digest = MessageDigest.getInstance(hashType); //"MD5"
InputStream is = new FileInputStream(file);
String output = "";
String output;
byte[] buffer = new byte[8192];
int read = 0;
int read;
try {
while( (read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
@ -225,10 +225,9 @@ public class Hasher {
* @param data is the byte array to hash
* @param hashType is the hash method (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512 )
* @return an String containing the hash
* @throws Exception
*/
public static String hash(byte[] data, String hashType) throws Exception {
MessageDigest md = null;
MessageDigest md;
md = MessageDigest.getInstance(hashType); //MD5 || SHA
md.update(data);

View file

@ -37,12 +37,12 @@ public interface OneInstance {
*
* @return True if the file is locked else false
*/
public boolean check();
boolean check();
/**
* Locks the application so that another one can not run
*
* @return False if there are a error else true
*/
public boolean lockApp();
boolean lockApp();
}

View file

@ -63,8 +63,8 @@ public class OneInstanceNetwork extends Thread implements OneInstance{
* should not be cald outside the class
*/
public void run() {
ServerSocket serverSocket = null;
Socket clientSocket = null;
ServerSocket serverSocket;
Socket clientSocket;
try {
// Create the server socket
serverSocket = new ServerSocket(port, 1);

View file

@ -40,5 +40,5 @@ public interface ProgressListener<S,D> {
* @param info is some information from the source object
* @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

@ -57,7 +57,7 @@ public class StringUtil {
public static String formatTimeToString(long milisec){
StringBuilder str = new StringBuilder();
long tmp = 0;
long tmp;
// Years
if( milisec >= 31557032762.3361d ){
@ -69,9 +69,9 @@ public class StringUtil {
str.append(tmp).append(" year ");
}
// Months
if( milisec >= 2629743830l ){
tmp = (long) (milisec / 2629743830l);
milisec -= tmp * 2629743830l;
if( milisec >= 2629743830L){
tmp = milisec / 2629743830L;
milisec -= tmp * 2629743830L;
if( tmp > 1 )
str.append(tmp).append(" months ");
else
@ -79,7 +79,7 @@ public class StringUtil {
}
// Days
if( milisec >= 86400000 ){
tmp = (long) (milisec / 86400000);
tmp = milisec / 86400000;
milisec -= tmp * 86400000;
if( tmp > 1 )
str.append(tmp).append(" days ");
@ -88,7 +88,7 @@ public class StringUtil {
}
// Hours
if( milisec >= 3600000 ){
tmp = (long) (milisec / 3600000);
tmp = milisec / 3600000;
milisec -= tmp * 3600000;
if( tmp > 1 )
str.append(tmp).append(" hours ");
@ -97,13 +97,13 @@ public class StringUtil {
}
// Minutes
if( milisec >= 60000 ){
tmp = (long) (milisec / 60000);
tmp = milisec / 60000;
milisec -= tmp * 60000;
str.append(tmp).append(" min ");
}
// sec
if( milisec >= 1000 ){
tmp = (long) (milisec / 1000);
tmp = milisec / 1000;
milisec -= tmp * 1000;
str.append(tmp).append(" sec ");
}
@ -118,8 +118,6 @@ public class StringUtil {
* Generates a String where the number has been prefixed
* 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.
*/
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
* @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){
return join(delimiter, Arrays.asList(array));
}

View file

@ -40,7 +40,6 @@ public class EuclideansAlgo {
/**
* Simple Test
* @param args
*/
public static void main(String[] args){
MultiPrintStream.out.println("*** Correct Answer: ");
@ -104,7 +103,7 @@ public class EuclideansAlgo {
* @return a list of integers that is generators for a and b
*/
public static LinkedList<Integer> calcGenerators(int a, int b){
LinkedList<Integer> list = new LinkedList<Integer>();
LinkedList<Integer> list = new LinkedList<>();
int t;
while( b != 0 ){
@ -126,7 +125,7 @@ public class EuclideansAlgo {
* @return a list of BigIntegers that is generators of a and b
*/
public static LinkedList<BigInteger> calcGenerators(BigInteger a, BigInteger b){
LinkedList<BigInteger> list = new LinkedList<BigInteger>();
LinkedList<BigInteger> list = new LinkedList<>();
BigInteger t;
while( !b.equals(BigInteger.ZERO) ){

View file

@ -22,9 +22,6 @@
* THE SOFTWARE.
*/
/**
*
*/
package zutil.algo;
import java.math.BigInteger;

View file

@ -49,7 +49,7 @@ public class WienersAlgo {
* If no value was found then it returns null.
*/
public static BigInteger[] calc(BigInteger n, BigInteger e){
BigInteger[] ret = null;
BigInteger[] ret;
LinkedList<BigInteger> gen = EuclideansAlgo.calcGenerators(e, n);

View file

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

View file

@ -33,7 +33,7 @@ import java.util.LinkedList;
* @author Ziver
*/
public class DepthFirstSearch {
private HashSet<PathNode> visited = new HashSet<PathNode>();
private HashSet<PathNode> visited = new HashSet<>();
/**
* Returns the first path to the destination

View file

@ -29,86 +29,34 @@ public class DynamicProgramming {
"bibba".toCharArray(),
"bitas".toCharArray(),
"brott".toCharArray(),
"bl<EFBFBD>ja".toCharArray(),
"blaja".toCharArray(),
"boson".toCharArray()
};
public static void main(String[] args) {
new DynamicProgramming().search();
}
/*
int search(words[][][])
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 shortest = -1;
for(int w=0; w<words.length ;w++){ //lodr<EFBFBD>ta ordet
System.out.print("\n\n"+new String(words[w])+"\n ");
for(int y=0; y<words.length ;y++){ // v<EFBFBD>gr<EFBFBD>ta ordet
System.out.print("\n"+ new String(words[y])+": ");
for(int x=0; x<words.length ;x++){ // psition i y
// f<EFBFBD>rsta v<EFBFBD>gr<EFBFBD>ta ordet
for (int w = 0; w < words.length; w++) {
for (int y = 0; y < words.length; y++) {
for (int x = 0; x < words.length; x++) {
if (y == 0) {
if(words[0][x] != words[w][0]){
if (words[0][x] != words[w][0])
matrix[w][y][x] = -1;
}
else{
else
matrix[w][y][x] = 0;
}
}
//resten av de v<EFBFBD>gr<EFBFBD>ta orden
else{
} else {
if (matrix[w][y - 1][x] < 0) {
matrix[w][y][x] = -1;
}
else{
int tmp = minstaForskjutning(words[y], words[w][y], x);
} else {
int tmp = smallestChange(words[y], words[w][y], x);
if (tmp >= 0) {
matrix[w][y][x] = matrix[w][y - 1][x] + tmp;
}
else{
} else {
matrix[w][y][x] = -1;
}
}
@ -120,22 +68,20 @@ int minstaForskjutning(word[], find, index){
shortest = tmp;
}
}
System.out.print(" "+matrix[w][y][x]);
}
}
}
System.out.println("\n\nKortaste f<>rflyttningen: "+shortest);
return shortest;
}
private int minstaForskjutning(char[] word, char cfind, int index){
int minsta = -1;
private int smallestChange(char[] word, char cfind, int index) {
int smallest = -1;
for (int i = 0; i < word.length; i++) {
if(word[i] == cfind && (Math.abs(index-i)<minsta || minsta<0)){
minsta = Math.abs(index-i);
if (word[i] == cfind && (Math.abs(index - i) < smallest || smallest < 0)) {
smallest = Math.abs(index - i);
}
}
return minsta;
return smallest;
}
}

View file

@ -41,5 +41,5 @@ public interface PathFinder {
* @param goal is the search goal
* @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
*/
public Iterable<PathNode> getNeighbors();
Iterable<PathNode> getNeighbors();
/**
* @param neighbor is the neighbor
* @return the cost to the neighbor
*/
public int getNeighborCost(PathNode neighbor);
int getNeighborCost(PathNode neighbor);
/**
* Sets the parent node to this one
*/
public void setParentNeighbor(PathNode parent);
void setParentNeighbor(PathNode parent);
/**
* @return the parent node
*/
public PathNode getParentNeighbor();
PathNode getParentNeighbor();
/**
* Traverses the parent tree and returns the path.
@ -56,5 +56,5 @@ public interface PathNode {
* @param goal is the node to reach
* @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;
public StandardPathNode(){
neighbors = new HashMap<PathNode,Integer>();
neighbors = new HashMap<>();
}
public int getNeighborCost(PathNode neighbor) {
@ -57,7 +57,7 @@ public class StandardPathNode implements PathNode{
}
public LinkedList<PathNode> traversTo(PathNode goal) {
LinkedList<PathNode> path = new LinkedList<PathNode>();
LinkedList<PathNode> path = new LinkedList<>();
PathNode current = this;
while(current != null){
path.addFirst(current);
@ -67,7 +67,7 @@ public class StandardPathNode implements PathNode{
return path;
}
}
return new LinkedList<PathNode>();
return new LinkedList<>();
}
}

View file

@ -48,7 +48,6 @@ public class ExternalSort {
*
* @param orgFile File to sort
* @param sortedFile The sorted file
* @throws FileNotFoundException
*/
public ExternalSort(File orgFile, File sortedFile) throws FileNotFoundException{
in = new BufferedReader(new FileReader(orgFile));
@ -62,7 +61,6 @@ public class ExternalSort {
* @param orgFile File to sort
* @param sortedFile The sorted file
* @param chunk The chunk size
* @throws FileNotFoundException
*/
public ExternalSort(File orgFile, File sortedFile, int chunk) throws FileNotFoundException{
in = new BufferedReader(new FileReader(orgFile));
@ -88,7 +86,8 @@ public class ExternalSort {
/**
* Merges all the files to one
* @param files
*
* @param files a list of files to be merged
*/
private void mergeFiles(LinkedList<File> files){
try {
@ -116,7 +115,7 @@ public class ExternalSort {
String row;
while (someFileStillHasRows){
String min;
int minIndex = 0;
int minIndex;
row = rows[0];
if (row!=null) {
@ -208,8 +207,8 @@ public class ExternalSort {
* @throws IOException Some kind of error
*/
private LinkedList<File> sortChunks() throws IOException{
LinkedList<File> chunkFiles = new LinkedList<File>();
LinkedList<String> chunk = new LinkedList<String>();
LinkedList<File> chunkFiles = new LinkedList<>();
LinkedList<String> chunk;
do{
chunk = readChunk(in);
@ -227,13 +226,11 @@ public class ExternalSort {
/**
* Reads in a chunk of rows into a LinkedList
*
* @param list The list to populate
* @param in The BufferedReader to read from
* @return The LinkeList with the chunk
* @throws IOException Some kind of error
* @return a LinkedList with the chunks
*/
private LinkedList<String> readChunk(BufferedReader in) throws IOException{
LinkedList<String> list = new LinkedList<String>();
LinkedList<String> list = new LinkedList<>();
String tmp;
for(int i=0; i<CHUNK_SIZE ;i++){
tmp = in.readLine();
@ -252,18 +249,16 @@ public class ExternalSort {
*/
private void writeChunk(LinkedList<String> list, File file) throws IOException{
BufferedWriter out = new BufferedWriter(new FileWriter(file));
Iterator<String> it = list.iterator();
while(it.hasNext()){
out.write(it.next());
for (String str : list) {
out.write(str);
out.newLine();
}
out.close();
}
private void removeFiles(LinkedList<File> list){
Iterator<File> it = list.iterator();
while(it.hasNext()){
it.next().delete();
for (File file : list) {
file.delete();
}
}
}

View file

@ -73,9 +73,7 @@ public class MergeSort{
int length = pivot-start;
int[] tmp = new int[stop-start];
for(int i=0; i<tmp.length ;++i){
tmp[i] = list[start+i];
}
System.arraycopy(list, start + 0, tmp, 0, tmp.length);
int index1 = 0;
int index2 = length;
@ -127,7 +125,6 @@ public class MergeSort{
* This method is the merger, after the array
* has been split this method will merge the
* two parts of the array and sort it.
* @param <T>
*
* @param list is the list to merge
* @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 scale is the data scale
* @param bound is the drawing boundds
* @param bound is the drawing bounds
* @return a x pixel coordinate
*/
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 scale is the data scale
* @param bound is the drawing boundds
* @param bound is the drawing bounds
* @return a y pixel coordinate
*/
static protected double getYCoordinate(double y, double scale, Rectangle bound){

View file

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

View file

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

View file

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

View file

@ -56,7 +56,7 @@ public class WGS84Converter {
}
}
// 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]", "");
float tmpf = Float.parseFloat(coordinate);
deg = (int)(tmpf/100);

View file

@ -129,7 +129,7 @@ public class DBConnection implements Closeable{
*/
public long getLastInsertID(){
try{
return exec("SELECT LAST_INSERT_ID()", new SimpleSQLResult<Long>());
return exec("SELECT LAST_INSERT_ID()", new SimpleSQLResult<>());
}catch(SQLException e){
logger.log(Level.WARNING, null, e);
}
@ -212,7 +212,6 @@ public class DBConnection implements Closeable{
/**
* Executes an query and cleans up after itself.
*
* @param <T>
* @param query is the query
* @param handler is the result handler
* @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
* @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{
// Execute
boolean isResultSet = stmt.execute();
@ -253,7 +252,6 @@ public class DBConnection implements Closeable{
} catch (SQLException e) {
logger.log(Level.WARNING, null, e);
}
result = null;
}
}
}
@ -267,7 +265,6 @@ public class DBConnection implements Closeable{
} catch (SQLException e) {
logger.log(Level.WARNING, null, e);
}
stmt = null;
}
}
return null;
@ -293,7 +290,6 @@ public class DBConnection implements Closeable{
} catch (SQLException e) {
logger.log(Level.WARNING, null, e);
}
stmt = null;
}
}
return new int[0];

View file

@ -74,15 +74,15 @@ public class DBConnectionPool extends TimerTask implements Closeable{
* @param user is the user name 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.url = url;
this.db = db;
this.user = user;
this.password = password;
inusePool = new LinkedList<PoolItem>();
readyPool = new LinkedList<PoolItem>();
inusePool = new LinkedList<>();
readyPool = new LinkedList<>();
this.setTimeout(DEFAULT_TIMEOUT);
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
* 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){
this.forceUpgradeEnabled = enable;
@ -240,7 +240,7 @@ public class DBUpgradeHandler {
private List<String> getTableList(DBConnection db) throws SQLException {
return db.exec("SELECT name FROM sqlite_master WHERE type='table';", new SQLResultHandler<List<String>>() {
public List<String> handleQueryResult(Statement stmt, ResultSet result) throws SQLException {
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list = new ArrayList<>();
while( result.next() ) {
String table = result.getString(1);
if(!ignoredTablesSet.contains(table))
@ -253,7 +253,7 @@ public class DBUpgradeHandler {
private static String getTableSql(DBConnection db, String table) throws SQLException {
PreparedStatement stmt = db.getPreparedStatement("SELECT sql FROM sqlite_master WHERE name == ?");
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 {
return db.exec(

View file

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

View file

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

View file

@ -335,8 +335,7 @@ public abstract class DBBean {
logger.finest("Load all Beans("+c.getName()+") query: "+sql);
PreparedStatement stmt = db.getPreparedStatement( sql );
// Run query
List<T> list = DBConnection.exec(stmt, DBBeanSQLResultHandler.createList(c, db) );
return list;
return DBConnection.exec(stmt, DBBeanSQLResultHandler.createList(c, db) );
}
/**
@ -369,7 +368,7 @@ public abstract class DBBean {
// Generate the SQL
StringBuilder query = new StringBuilder();
query.append("CREATE TABLE "+config.getTableName()+" ( ");
query.append("CREATE TABLE ").append(config.getTableName()).append(" ( ");
// ID
query.append(" ").append(config.getIdColumnName()).append(" ");

View file

@ -126,8 +126,7 @@ class DBBeanCache {
public static DBBean get(Class<?> c, Long id) {
if(contains(c, id)){
CacheItem cacheItem = cache.get(c).get(id);
DBBean bean = cacheItem.bean.get();
return bean;
return cacheItem.bean.get();
}
logger.finer("Bean("+c.getName()+") cache miss for id: "+id);
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() == Byte.TYPE) field.setByte(obj, (byte) 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() == Double.TYPE) field.setDouble(obj, 0d);
else if (field.getType() == Boolean.TYPE) field.setBoolean(obj, false);

View file

@ -73,7 +73,7 @@ public abstract class ImageFilterProcessor {
* @param img The image to process
* @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();
processor.img = img;
return processor;

View file

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

View file

@ -92,7 +92,7 @@ public class MedianFilter extends ImageFilterProcessor{
int edgeY = windowSize / 2;
int[][] tmpArray = new int[4][256*2];
int pixelCount = 0;
int pixelCount;
for(int y=startY; y<stopY ;y++){
setProgress(ZMath.percent(0, stopY-startY-1, y));
for(int x=startX; x<stopX ;x++){

View file

@ -33,8 +33,6 @@ public class ResizeImage extends ImageFilterProcessor{
private int width;
private int height;
private int[][][] newData;
/**
* Will create a ResizeImage object and fix the height with the aspect
* of the width
@ -68,7 +66,7 @@ public class ResizeImage extends ImageFilterProcessor{
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 yScale = ((double)(stopY-startY)/height);

View file

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

View file

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

View file

@ -38,7 +38,6 @@ public class IOUtil {
* Reads and returns all the content of a stream.
* The InputStream will not be closed
*
* @param stream
* @return a byte array with the stream contents
*/
public static byte[] readContent(InputStream stream) throws IOException{
@ -48,14 +47,13 @@ public class IOUtil {
/**
* Reads and returns all the content of a stream.
*
* @param stream
* @param close true if the stream should be closed at the end
* @return a byte array with the stream contents
*/
public static byte[] readContent(InputStream stream, boolean close) throws IOException{
DynamicByteArrayStream dyn_buff = new DynamicByteArrayStream();
byte[] buff = new byte[8192];
int len = 0;
int len;
while((len = stream.read(buff)) != -1){
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.
* The InputStream will not be closed
*
* @param stream
* @return a String with the content of the stream
*/
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.
*
* @param stream
* @param close true if the stream should be closed at the end
* @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.
* The Reader will not be closed
*
* @param reader
* @return a String with the content of the stream
*/
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.
*
* @param reader
* @param close true if the stream should be closed at the end
* @return a String with the content of the stream
*/
public static String readContentAsString(Reader reader, boolean close) throws IOException{
StringBuilder str = new StringBuilder();
BufferedReader in = null;
BufferedReader in;
if(reader instanceof BufferedReader)
in = (BufferedReader) reader;
else
@ -131,7 +125,7 @@ public class IOUtil {
*/
public static String readLine(InputStream in) throws IOException {
StringBuilder str = new StringBuilder(80);
int c = 0;
int c;
while ((c=in.read()) >= 0 && (c != '\n') && (c != '\r'))
str.append((char)c);
if (c == '\r')
@ -150,7 +144,7 @@ public class IOUtil {
*/
public static String readLine(Reader in) throws IOException {
StringBuilder str = new StringBuilder(80);
int c = 0;
int c;
while ((c=in.read()) >= 0 && (c != '\n') && (c != '\r'))
str.append((char)c);
if (c == '\r')

View file

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

View file

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

View file

@ -38,5 +38,5 @@ public interface FileChangeListener{
*
* @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>{
// Constants
private static final List<String> compressedFileExtensions = Arrays.asList(new String[]{
"jar", "zip"
});
private static final List<String> compressedFileExtensions = Arrays.asList(
"jar", "zip");
// Constructor params
private File root;
@ -119,7 +118,7 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
private FileSearchItem nextItem;
public FileSearchIterator(){
fileList = new ArrayList<FileSearchItem>();
fileList = new ArrayList<>();
index = 0;
addFiles(new FileSearchFileItem(root), root.list());
@ -208,18 +207,18 @@ public class FileSearcher implements Iterable<FileSearcher.FileSearchItem>{
public interface FileSearchItem{
/** @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 **/
public String getPath();
String getPath();
public boolean isCompressed();
public boolean isFile();
public boolean isDirectory();
boolean isCompressed();
boolean isFile();
boolean isDirectory();
/** @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 **/
public String[] listFiles();
String[] listFiles();
}

View file

@ -90,9 +90,6 @@ public class FileUtil {
/**
* Copy the contents of a source file to another file.
* 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{
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)
* @return A URL object for the file
* @throws URISyntaxException
*/
public static URL findURL(String 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.
*
* @param file
* @return the file content
*/
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 file content
* @return the URL content
*/
public static String getContent(URL url) throws IOException{
String data = new String(IOUtil.readContent(url.openStream(), true));
return data;
return new String(IOUtil.readContent(url.openStream(), true));
}
/**
@ -195,7 +188,7 @@ public class FileUtil {
* @return a List of files
*/
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
*/
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

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

View file

@ -90,7 +90,7 @@ public abstract class AjaxFileUpload extends HttpServlet {
public static File TEMPFILE_PATH = null;
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 {
super.init(config);
@ -129,12 +129,12 @@ public abstract class AjaxFileUpload extends HttpServlet {
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
if(request.getParameter("js") != null){
response.setContentType("application/x-javascript");
String tmp = JAVASCRIPT;
tmp = JAVASCRIPT.replaceAll("\\{SERVLET_URL\\}", request.getRequestURI());
String tmp = JAVASCRIPT.replaceAll("\\{SERVLET_URL\\}", request.getRequestURI());
tmp = tmp.replaceAll("\\{BGUPLOAD\\}", "false");
tmp = tmp.replaceAll("\\{PROGHTML\\}", getProgressHTML());
out.print(tmp);
@ -178,15 +178,15 @@ public abstract class AjaxFileUpload extends HttpServlet {
FileUploadListener listener = new FileUploadListener();
try {
// Initiate list and HashMap that will contain the data
HashMap<String,String> fields = new HashMap<String,String>();
ArrayList<FileItem> files = new ArrayList<FileItem>();
HashMap<String,String> fields = new HashMap<>();
ArrayList<FileItem> files = new ArrayList<>();
// Add the listener to the session
HttpSession session = request.getSession();
LinkedList<FileUploadListener> list =
(LinkedList<FileUploadListener>)session.getAttribute(SESSION_FILEUPLOAD_LISTENER);
if(list == null){
list = new LinkedList<FileUploadListener>();
list = new LinkedList<>();
session.setAttribute(SESSION_FILEUPLOAD_LISTENER, list);
}
list.add(listener);
@ -258,8 +258,7 @@ public abstract class AjaxFileUpload extends HttpServlet {
public abstract String getProgressHTML();
/**
* Handle the uppload
* @throws ServletException
* Handle the upload
*/
public abstract void doUpload(HttpServletRequest request, HttpServletResponse response,
Map<String,String> fields, List<FileItem> files) throws ServletException;

View file

@ -36,7 +36,7 @@ import zutil.parser.DataNode.DataType;
* uploaded file.
*/
public class FileUploadListener implements ProgressListener{
public static enum Status{
public enum Status{
Initializing,
Uploading,
Processing,
@ -48,8 +48,8 @@ public class FileUploadListener implements ProgressListener{
private volatile Status status;
private volatile String filename;
private volatile String message;
private volatile long bytes = 0l;
private volatile long length = 0l;
private volatile long bytes = 0L;
private volatile long length = 0L;
private volatile int item = 0;
private volatile long time;

View file

@ -49,7 +49,7 @@ public class CompactLogFormatter extends Formatter{
/** Specifies the max length of the longest class name **/
private int max_class_name = 0;
/** 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 **/
private Date date = new Date();

View file

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

View file

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

View file

@ -26,8 +26,9 @@
<?import javafx.scene.control.*?>
<?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">
<children>
<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">
<MenuBar prefWidth="598.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<menus>
<Menu mnemonicParsing="false" text="File">
@ -58,6 +59,7 @@
</Menu>
</menus>
</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" />
</children>
<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"/>
</AnchorPane>

View file

@ -41,17 +41,15 @@ public class NetLogClient extends Thread{
private ConcurrentLinkedQueue<NetLogListener> listeners;
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);
out = new ObjectOutputStream(s.getOutputStream());
listeners = new ConcurrentLinkedQueue<NetLogListener>();
listeners = new ConcurrentLinkedQueue<>();
this.start();
}
public void addListener(NetLogListener listener){
logger.info("Registring new NetLogListener: "+listener.getClass().getName());
logger.info("Registering new NetLogListener: "+listener.getClass().getName());
listeners.add( listener );
}

View file

@ -37,60 +37,67 @@
</stylesheets>
<bottom>
<ToolBar maxHeight="22.0" minHeight="19.0" prefHeight="22.0" prefWidth="839.0">
<items>
<ProgressBar fx:id="progressBar" prefWidth="200.0" progress="0.0" style="" />
<Label fx:id="errorLabel" text="" textFill="RED">
<ProgressBar fx:id="progressBar" prefWidth="200.0" progress="0.0"/>
<Label fx:id="errorLabel" textFill="RED">
<font>
<Font size="11.0"/>
</font>
</Label>
<Region HBox.Hgrow="ALWAYS"/>
<Separator orientation="VERTICAL" prefHeight="200.0" valignment="CENTER" />
<Separator orientation="VERTICAL" prefHeight="200.0"/>
<Label fx:id="logCountLabel" text="0">
<graphic>
<Label text="Log Count:"/>
</graphic>
</Label>
</items>
</ToolBar>
</bottom>
<center>
<SplitPane dividerPositions="0.7491525423728813" focusTraversable="true" orientation="VERTICAL" prefHeight="297.0" prefWidth="600.0">
<items>
<SplitPane dividerPositions="0.7491525423728813" focusTraversable="true" orientation="VERTICAL" prefHeight="297.0"
prefWidth="600.0">
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<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"
AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="0.0">
<columns>
<TableColumn editable="false" prefWidth="130.0" sortable="false" text="Timestamp" fx:id="logTimestampColumn" />
<TableColumn editable="false" prefWidth="75.0" sortable="false" text="Level" fx:id="logLevelColumn" />
<TableColumn editable="false" prefWidth="400.0" sortable="false" text="Log" fx:id="logColumn" />
<TableColumn editable="false" prefWidth="130.0" sortable="false" text="Timestamp"
fx:id="logTimestampColumn"/>
<TableColumn editable="false" prefWidth="75.0" sortable="false" text="Level"
fx:id="logLevelColumn"/>
<TableColumn editable="false" prefWidth="400.0" sortable="false" text="Log"
fx:id="logColumn"/>
</columns>
</TableView>
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<children>
<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 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">
<columns>
<TableColumn editable="false" prefWidth="45.0" style="-fx-alignment: TOP_CENTER;" text="#" fx:id="exCountColumn" />
<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="45.0" style="-fx-alignment: TOP_CENTER;" text="#"
fx:id="exCountColumn"/>
<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>
</items>
</SplitPane>
</center>
<top>
<ToolBar maxHeight="30.0" minHeight="22.0" prefHeight="30.0" prefWidth="839.0">
<items>
<ToggleButton fx:id="pauseButton" mnemonicParsing="false" onAction="#handlePauseAction" text="Pause"/>
<Region HBox.Hgrow="ALWAYS"/>
<Group id="Group">
<children>
<Label fx:id="levelLabel" layoutX="0.0" layoutY="-7.0" text="Log Level: " />
<Label fx:id="levelLabel" layoutY="-7.0" text="Log Level: "/>
<ComboBox fx:id="levelComboBox" layoutX="60.0" layoutY="-9.0" onAction="#handleLevelChanged">
<items>
<FXCollections fx:factory="observableArrayList">
@ -107,7 +114,8 @@
</Group>
<Group id="Group">
<children>
<Label fx:id="intervalLabel" alignment="CENTER_RIGHT" layoutX="0.0" layoutY="-7.0" prefWidth="60.0" text="Interval: " />
<Label fx:id="intervalLabel" alignment="CENTER_RIGHT" layoutY="-7.0" prefWidth="60.0"
text="Interval: "/>
<ComboBox fx:id="intervalComboBox" layoutX="65.0" layoutY="-9.0" onAction="#handleIntervalChanged">
<items>
<FXCollections fx:factory="observableArrayList">
@ -122,7 +130,6 @@
</ComboBox>
</children>
</Group>
</items>
</ToolBar>
</top>
</BorderPane>

View file

@ -49,10 +49,12 @@ public class NetLogExceptionMessage implements Message {
this.count = 1;
this.name = exception.getClass().getName();
this.message = exception.getMessage();
this.stackTrace = "";
StringBuilder str = new StringBuilder();
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

@ -82,8 +82,7 @@ public class NetLogGuiClient extends Application{
public NetLoggerClientTab(String host, int port) throws IOException{
this.setText( host+":"+port );
FXMLLoader loader = new FXMLLoader();
Parent tabRoot = loader.load(getClass().getResource("NetLogClientInstance.fxml"));
Parent tabRoot = FXMLLoader.load(getClass().getResource("NetLogClientInstance.fxml"));
this.setContent(tabRoot);
AnchorPane.setRightAnchor(tabRoot, 0.0);
//this.setOnClosed(new EventHandler<Event>() {

View file

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

View file

@ -29,15 +29,15 @@ public interface NetLogListener {
/**
* Handle incoming log messages
*/
public void handleLogMessage( NetLogMessage log );
void handleLogMessage(NetLogMessage log);
/**
* Handle incoming exception messages
*/
public void handleExceptionMessage( NetLogExceptionMessage exception );
void handleExceptionMessage(NetLogExceptionMessage exception);
/**
* 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) {
super();
exceptions = new ConcurrentHashMap<NetLogExceptionMessage,NetLogExceptionMessage>();
exceptions = new ConcurrentHashMap<>();
net = new NetLogNetwork(port);
net.start();
}
@ -96,7 +96,7 @@ public class NetLogServer extends Handler {
public NetLogNetwork(int port) {
super(port);
threads = new ConcurrentLinkedQueue<NetLogServerThread>();
threads = new ConcurrentLinkedQueue<>();
}
public void sendMessage(Message log){
@ -108,8 +108,7 @@ public class NetLogServer extends Handler {
@Override
protected ThreadedTCPNetworkServerThread getThreadInstance(Socket s) {
try {
NetLogServerThread thread = new NetLogServerThread(s);
return thread;
return new NetLogServerThread(s);
} catch (IOException e) {
logger.log(Level.SEVERE, "Unable to start Client thread", e);
}

View file

@ -48,12 +48,12 @@ public class FTPClient extends Thread{
public static final int FTP_DATA_PORT = 20;
public static final int FTP_NOOP_INT = 120;
public static enum FTPConnectionType{
public enum FTPConnectionType{
ACTIVE,
PASSIVE
}
public static enum FTPReturnCode{
public enum FTPReturnCode{
UNKNOWN ( -1 ),
USER_OK ( 331 ),
@ -66,7 +66,7 @@ public class FTPClient extends Thread{
PATH_CREATED ( 257 );
private int code;
private FTPReturnCode(int code){
FTPReturnCode(int code){
this.code = code;
}
@ -98,7 +98,7 @@ public class FTPClient extends Thread{
* @param pass password
* @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);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new OutputStreamWriter(socket.getOutputStream());
@ -189,7 +189,7 @@ public class FTPClient extends Thread{
* @return a List of Strings with information
*/
public String getFileInfo(String path) throws IOException{
Pattern regex = Pattern.compile("\\s{1,}");
Pattern regex = Pattern.compile("\\s+");
BufferedInputStream data_in = getDataInputStream();
sendCommand("LIST "+path);

View file

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

View file

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

View file

@ -40,26 +40,25 @@ import java.net.MulticastSocket;
*
*/
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 MulticastSocket Msocket;
private MulticastSocket mSocket;
private boolean avsluta;
private boolean shutdown;
private int port;
/**
* Creates a ServerFind Thread an the specified port
*
* @param port The port to run the ServerFind Server on
* @throws IOException
*/
public ServerFind (int port) throws IOException {
this.port = port;
avsluta = false;
group = InetAddress.getByName(broadcastAddress);
Msocket = new MulticastSocket(port);
Msocket.joinGroup(group);
shutdown = false;
group = InetAddress.getByName(BROADCAST_ADDRESS);
mSocket = new MulticastSocket(port);
mSocket.joinGroup(group);
start();
}
@ -67,12 +66,12 @@ public class ServerFind extends Thread {
public void run (){
byte[] buf = new byte[256];
DatagramPacket packet;
DatagramSocket lan_socket = null;
DatagramSocket lan_socket;
while (!avsluta){
while (!shutdown){
try {
packet = new DatagramPacket(buf, buf.length);
Msocket.receive(packet);
mSocket.receive(packet);
lan_socket = new DatagramSocket(port , packet.getAddress());
packet = new DatagramPacket(buf, buf.length, group, port);
@ -91,7 +90,7 @@ public class ServerFind extends Thread {
* Closes the broadcast socket
*/
public void close(){
avsluta = true;
Msocket.close();
shutdown = true;
mSocket.close();
}
}

View file

@ -54,7 +54,6 @@ public class ServerFindClient{
* Requests IP from server
*
* @return The address of the server
* @throws IOException
*/
public InetAddress find() throws IOException{
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 type {@link zutil.net.dns.packet.DnsConstants.TYPE}
* @param clazz {@link zutil.net.dns.packet.DnsConstants.CLASS}
* @param data
*/
public void addEntry(String name, int type, int clazz, byte[] data){
DnsPacketResource resource = new DnsPacketResource();
@ -101,7 +100,7 @@ public class MulticastDnsServer extends ThreadedUDPNetwork implements ThreadedUD
private void addEntry(DnsPacketResource resource) {
if ( ! entries.containsKey(resource.name))
entries.put(resource.name, new ArrayList<DnsPacketResource>());
entries.put(resource.name, new ArrayList<>());
entries.get(resource.name).add(resource);
}

View file

@ -40,7 +40,7 @@ import java.util.HashMap;
* @author Ziver
*/
public class HttpClient implements AutoCloseable{
public static enum HttpRequestType{
public enum HttpRequestType{
GET, POST
}
@ -59,8 +59,8 @@ public class HttpClient implements AutoCloseable{
public HttpClient(HttpRequestType type){
this.type = type;
headers = new HashMap<String,String>();
cookies = new HashMap<String,String>();
headers = new HashMap<>();
cookies = new HashMap<>();
}
@ -112,7 +112,7 @@ public class HttpClient implements AutoCloseable{
request.setCookies( cookies );
if( type == HttpRequestType.POST ){
String postData = null;
String postData;
if(data != null)
postData = data;
else

View file

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

View file

@ -45,7 +45,7 @@ public interface HttpPage{
* @param cookie is cookie information 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,
Map<String, Object> session,
Map<String, String> cookie,

View file

@ -87,8 +87,8 @@ public class HttpPrintStream extends OutputStream{
this.httpVersion = "1.0";
this.message_type = type;
this.res_status_code = 200;
this.headers = new HashMap<String, String>();
this.cookies = new HashMap<String, String>();
this.headers = new HashMap<>();
this.cookies = new HashMap<>();
this.buffer = new StringBuffer();
this.buffer_enabled = false;
}
@ -99,11 +99,9 @@ public class HttpPrintStream extends OutputStream{
* is enabled until you close or flush the stream.
* This function will flush the stream if buffering is
* disabled.
*
* @param b
*/
public void enableBuffering(boolean b) throws IOException {
buffer_enabled = b;
public void enableBuffering(boolean enable) throws IOException {
buffer_enabled = enable;
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
*/
private void printOrBuffer(String s) throws IOException {
private void printOrBuffer(String s) {
if(buffer_enabled){
buffer.append(s);
}

View file

@ -272,7 +272,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
buff.append(", cookies: ").append(header==null ? null : header.toStringCookies());
buff.append(", session: ").append(session);
buff.append(")");
buff.append(", time: "+ StringUtil.formatTimeToString(System.currentTimeMillis() - time));
buff.append(", time: ").append(StringUtil.formatTimeToString(System.currentTimeMillis() - time));
logger.finer(buff.toString());
} else if(logger.isLoggable(Level.FINER)){

View file

@ -45,7 +45,7 @@ public class HttpURL {
private String path;
private String anchor;
private HashMap<String,String> parameters = new HashMap<String,String>();
private HashMap<String,String> parameters = new HashMap<>();
public HttpURL(){}

View file

@ -34,11 +34,11 @@ public interface MultipartField{
/**
* @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.
*/
public String getName();
String getName();
}

View file

@ -49,7 +49,7 @@ public class MultipartFileField implements MultipartField{
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.filename = headers.get("filename");
this.contentType = headers.get(HEADER_CONTENT_TYPE);

View file

@ -155,8 +155,7 @@ public class MultipartParser implements Iterable<MultipartField>{
HttpHeaderParser.parseCookieValues(headers, disposition);
if (headers.containsKey("form-data")){
if (headers.containsKey("filename")){
MultipartFileField field = new MultipartFileField(headers, boundaryIn);
return field;
return new MultipartFileField(headers, boundaryIn);
}
else{
MultipartStringField field = new MultipartStringField(headers, boundaryIn);

View file

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

View file

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

View file

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

View file

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

View file

@ -55,12 +55,12 @@ public abstract class NioNetwork implements Runnable {
protected Worker worker;
// 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
private List<ChangeRequest> pendingChanges = new LinkedList<ChangeRequest>();
private List<ChangeRequest> pendingChanges = new LinkedList<>();
// 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,9 +160,7 @@ public abstract class NioNetwork implements Runnable {
try {
// Handle any pending changes
synchronized (pendingChanges) {
Iterator<ChangeRequest> changes = pendingChanges.iterator();
while (changes.hasNext()) {
ChangeRequest change = changes.next();
for (ChangeRequest change : pendingChanges) {
switch (change.type) {
case ChangeRequest.CHANGEOPS:
SelectionKey key = change.socket.keyFor(selector);

View file

@ -30,5 +30,5 @@ package zutil.net.nio.worker.chat;
*
*/
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 {
private static final long serialVersionUID = 1L;
public static enum ChatMessageType {REGISTER, UNREGISTER, MESSAGE};
public enum ChatMessageType {REGISTER, UNREGISTER, MESSAGE};
public ChatMessageType type;
public String msg;

View file

@ -126,7 +126,7 @@ public class ChatService extends ThreadedEventWorker{
private void addRoom(String room){
if(!rooms.containsKey(room)){
logger.fine("New Chat Room: "+room);
rooms.put(room, new LinkedList<SocketAddress>());
rooms.put(room, new LinkedList<>());
}
}

View file

@ -54,7 +54,7 @@ public class GridClient extends ThreadedEventWorker {
* @param network the NioClient to use to communicate to the server
*/
public GridClient(GridThread thread, NioClient network){
jobQueue = new LinkedList<GridJob>();
jobQueue = new LinkedList<>();
GridClient.thread = thread;
GridClient.network = network;
@ -85,7 +85,7 @@ public class GridClient extends ThreadedEventWorker {
thread.setInitData(msg.getData());
break;
case GridMessage.COMP_DATA:
jobQueue.add(new GridJob(msg.getJobQueueID(), (Queue)msg.getData()));
jobQueue.add(new GridJob(msg.getJobQueueID(), msg.getData()));
break;
}
}

View file

@ -38,7 +38,6 @@ public abstract class ObjectSync {
/**
* Applies the SyncMessage to the object
* @param 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
*/
public synchronized void send(Email email) throws IOException{
public synchronized void send(Email email) {
if(email.getFromAddress() == null)
throw new IllegalArgumentException("From value cannot be null!");
if(email.getToAddress() == null)

View file

@ -63,8 +63,6 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork
/**
* Creates new instance of this class. An UDP
* listening socket at the SSDP port.
*
* @throws IOException
*/
public SSDPClient() throws IOException{
super( SSDP_MULTICAST_ADDR, SSDP_PORT );
@ -231,7 +229,7 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork
service = new StandardSSDPInfo();
services_usn.put(usn, service);
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);
}

View file

@ -32,7 +32,7 @@ import zutil.net.http.HttpPrintStream;
*/
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

@ -85,7 +85,7 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork
super( SSDP_MULTICAST_ADDR, SSDP_PORT );
super.setThread( this );
services = new HashMap<String, SSDPServiceInfo>();
services = new HashMap<>();
setCacheTime( DEFAULT_CACHE_TIME );
enableNotify( true );

View file

@ -35,25 +35,25 @@ public interface SSDPServiceInfo {
/**
* @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"
*/
public String getSearchTarget();
String getSearchTarget();
/**
* @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 "
*/
public String getUSN();
String getUSN();
/**
* @return only the USN UUID String
*/
public String getUUID();
String getUUID();
}

View file

@ -139,7 +139,7 @@ public abstract class ThreadedTCPNetworkServer extends Thread{
*
* @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.keyStorePassword", keyStorePass);
}

View file

@ -49,8 +49,6 @@ public class ThreadedUDPNetwork extends Thread{
/**
* Creates a new unicast Client instance of the class
*
* @throws SocketException
*/
public ThreadedUDPNetwork() throws SocketException{
this.type = UDPType.UNICAST;
@ -63,7 +61,6 @@ public class ThreadedUDPNetwork extends Thread{
* Creates a new unicast Server instance of the class
*
* @param port is the port that the server should listen to
* @throws SocketException
*/
public ThreadedUDPNetwork(int port) throws SocketException{
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 multicastAddr is the multicast address that the server will listen on
* @throws IOException
*/
public ThreadedUDPNetwork(String multicastAddr, int port ) throws IOException{
this.type = UDPType.MULTICAST;
@ -110,7 +106,6 @@ public class ThreadedUDPNetwork extends Thread{
* Sends the given packet
*
* @param packet is the packet to send
* @throws IOException
*/
public synchronized void send( DatagramPacket packet ) throws IOException{
socket.send(packet);

View file

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

View file

@ -44,7 +44,8 @@ class FileListMessage implements Serializable{
private ArrayList<FileInfo> fileList;
private long totalSize;
private FileListMessage(){}
private FileListMessage() {
}
/**
* Returns a ArrayList of FileInfo object for all the files in the specified folder
@ -52,7 +53,7 @@ class FileListMessage implements Serializable{
* @param path is the path to scan
**/
public FileListMessage(String path) throws IOException {
fileList = new ArrayList<FileInfo>();
fileList = new ArrayList<>();
List<File> files = FileUtil.search(FileUtil.find(path));
long totalSize = 0;
@ -74,16 +75,16 @@ class FileListMessage implements Serializable{
}
/**
* 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
* @return
* @return a list of files that diff
*/
public FileListMessage getDiff(FileListMessage comp) {
FileListMessage diff = new FileListMessage();
long diffSize = 0;
diff.fileList = new ArrayList<FileInfo>();
diff.fileList = new ArrayList<>();
for (FileInfo file : this.fileList) {
if (!comp.fileList.contains(file)) {
diff.fileList.add(file);

View file

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

View file

@ -102,7 +102,7 @@ public class UpdateServer extends ThreadedTCPNetworkServer{
// send file data
FileInputStream input = new FileInputStream( info.getFile() );
byte[] nextBytes = new byte[ socket.getSendBufferSize() ];
int bytesRead = 0;
int bytesRead;
while((bytesRead = input.read(nextBytes)) > 0){
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>{
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JLabel lblSpeed;
private JLabel lblFile;
private JProgressBar progressBar;
@ -68,7 +67,7 @@ public class Zupdater extends JFrame implements ProgressListener<UpdateClient, F
progressBar.setString( StringUtil.formatByteSizeToString(source.getTotalReceived()) +
" / "+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);
setTitle("Updating...");
setBounds(100, 100, 537, 124);
contentPane = new JPanel();
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);

View file

@ -52,7 +52,7 @@ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface
public UPnPContentDirectory(){}
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
* information listing the classes of objects available
* in any particular object container.
* @throws DocumentException
*
*/
//@WSNameSpace("urn:schemas-upnp-org:service:ContentDirectory:1")
@ -104,30 +103,30 @@ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface
@WSParamName("Filter") String Filter,
@WSParamName("StartingIndex") int StartingIndex,
@WSParamName("RequestedCount") int RequestedCount,
@WSParamName("SortCriteria") String SortCriteria) throws DocumentException{
@WSParamName("SortCriteria") String SortCriteria) {
BrowseRetObj ret = new BrowseRetObj();
if( BrowseFlag.equals("BrowseMetadata") ){
}
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/\" " +
"xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\" " +
"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){
xml.append(" <container id=\""+file_list.indexOf(file)+"\" ");
if(tmp.get(0) != file) xml.append("parentID=\""+file_list.indexOf(file.getParent())+"\" ");
if(file.isDirectory()) xml.append("childCount=\""+file.list().length+"\" ");
xml.append(" <container id=\"").append(file_list.indexOf(file)).append("\" ");
if(tmp.get(0) != file) xml.append("parentID=\"").append(file_list.indexOf(file.getParent())).append("\" ");
if(file.isDirectory()) xml.append("childCount=\"").append(file.list().length).append("\" ");
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() )
xml.append(" <upnp:class>object.container.storageFolder</upnp:class> ");
else
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> ");
ret.NumberReturned++;

View file

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

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