From ccecc067b27f865b5e7723e8fd5ae5c5ff0e134b Mon Sep 17 00:00:00 2001 From: Ziver Koc Date: Sun, 27 May 2018 01:23:21 +0200 Subject: [PATCH] Fixed many warnings --- .gitignore | 1 - Jenkinsfile | 4 +- src/zutil/ByteUtil.java | 7 +- src/zutil/ClassUtil.java | 4 +- src/zutil/CronTimer.java | 6 +- src/zutil/Encrypter.java | 2 +- src/zutil/Hasher.java | 13 +- src/zutil/OneInstance.java | 6 +- src/zutil/OneInstanceNetwork.java | 6 +- src/zutil/ProgressListener.java | 4 +- src/zutil/StringUtil.java | 21 +- src/zutil/algo/EuclideansAlgo.java | 9 +- src/zutil/algo/ShanksTonelliAlgo.java | 5 +- src/zutil/algo/WienersAlgo.java | 4 +- src/zutil/algo/path/BreadthFirstSearch.java | 4 +- src/zutil/algo/path/DepthFirstSearch.java | 4 +- src/zutil/algo/path/DynamicProgramming.java | 112 +++-------- src/zutil/algo/path/PathFinder.java | 4 +- src/zutil/algo/path/PathNode.java | 10 +- src/zutil/algo/path/StandardPathNode.java | 8 +- src/zutil/algo/sort/ExternalSort.java | 29 ++- src/zutil/algo/sort/MergeSort.java | 5 +- src/zutil/chart/AbstractChart.java | 4 +- src/zutil/chart/ChartData.java | 6 +- src/zutil/converter/Converter.java | 18 +- .../converter/NumberToWordsConverter.java | 62 +++--- src/zutil/converter/WGS84Converter.java | 2 +- src/zutil/db/DBConnection.java | 8 +- src/zutil/db/DBConnectionPool.java | 8 +- src/zutil/db/DBUpgradeHandler.java | 6 +- src/zutil/db/SQLQuery.java | 17 +- src/zutil/db/SQLResultHandler.java | 2 +- src/zutil/db/bean/DBBean.java | 13 +- src/zutil/db/bean/DBBeanCache.java | 3 +- src/zutil/db/bean/DBBeanConfig.java | 2 +- src/zutil/image/ImageFilterProcessor.java | 6 +- src/zutil/image/RAWImageUtil.java | 3 +- src/zutil/image/filter/MedianFilter.java | 4 +- src/zutil/image/filter/ResizeImage.java | 4 +- src/zutil/io/BufferedRandomAccessFile.java | 27 ++- src/zutil/io/DynamicByteArrayStream.java | 4 +- src/zutil/io/IOUtil.java | 16 +- src/zutil/io/MultiPrintStream.java | 17 +- src/zutil/io/NullWriter.java | 5 +- src/zutil/io/file/FileChangeListener.java | 4 +- src/zutil/io/file/FileSearcher.java | 21 +- src/zutil/io/file/FileUtil.java | 17 +- src/zutil/io/file/FileWatcher.java | 12 +- src/zutil/jee/upload/AjaxFileUpload.java | 31 ++- src/zutil/jee/upload/FileUploadListener.java | 8 +- src/zutil/log/CompactLogFormatter.java | 2 +- src/zutil/log/CounterManager.java | 2 +- src/zutil/log/StreamLogger.java | 4 +- src/zutil/log/net/NetLogClient.fxml | 64 ++++--- src/zutil/log/net/NetLogClient.java | 8 +- src/zutil/log/net/NetLogClientInstance.fxml | 175 +++++++++-------- src/zutil/log/net/NetLogExceptionMessage.java | 6 +- src/zutil/log/net/NetLogGuiClient.java | 13 +- .../log/net/NetLogGuiClientInstance.java | 16 +- src/zutil/log/net/NetLogListener.java | 6 +- src/zutil/log/net/NetLogServer.java | 7 +- src/zutil/net/FTPClient.java | 12 +- src/zutil/net/InetScanner.java | 10 +- src/zutil/net/POP3Client.java | 181 +++++++----------- src/zutil/net/ServerFind.java | 29 ++- src/zutil/net/ServerFindClient.java | 3 +- src/zutil/net/dns/MulticastDnsServer.java | 3 +- src/zutil/net/http/HttpClient.java | 12 +- src/zutil/net/http/HttpHeader.java | 6 +- src/zutil/net/http/HttpPage.java | 14 +- src/zutil/net/http/HttpPrintStream.java | 14 +- src/zutil/net/http/HttpServer.java | 4 +- src/zutil/net/http/HttpURL.java | 4 +- .../net/http/multipart/MultipartField.java | 6 +- .../http/multipart/MultipartFileField.java | 4 +- .../net/http/multipart/MultipartParser.java | 9 +- .../net/http/page/HttpDigestAuthPage.java | 5 +- src/zutil/net/http/page/HttpFilePage.java | 9 +- .../net/mqtt/packet/MqttPacketConnect.java | 9 +- src/zutil/net/nio/NioClient.java | 2 +- src/zutil/net/nio/NioNetwork.java | 28 ++- .../net/nio/worker/chat/ChatListener.java | 2 +- .../net/nio/worker/chat/ChatMessage.java | 2 +- .../net/nio/worker/chat/ChatService.java | 4 +- src/zutil/net/nio/worker/grid/GridClient.java | 6 +- src/zutil/net/nio/worker/sync/ObjectSync.java | 1 - src/zutil/net/smtp/SmtpClient.java | 2 +- src/zutil/net/ssdp/SSDPClient.java | 6 +- src/zutil/net/ssdp/SSDPCustomInfo.java | 6 +- src/zutil/net/ssdp/SSDPServer.java | 8 +- src/zutil/net/ssdp/SSDPServiceInfo.java | 12 +- .../threaded/ThreadedTCPNetworkServer.java | 4 +- .../net/threaded/ThreadedUDPNetwork.java | 7 +- src/zutil/net/torrent/TorrentMetainfo.java | 6 +- src/zutil/net/update/FileListMessage.java | 41 ++-- src/zutil/net/update/UpdateClient.java | 13 +- src/zutil/net/update/UpdateServer.java | 2 +- src/zutil/net/update/Zupdater.java | 5 +- .../upnp/service/UPnPContentDirectory.java | 19 +- src/zutil/net/ws/WSClientFactory.java | 9 +- src/zutil/net/ws/WSInterface.java | 24 +-- src/zutil/net/ws/WSMethodDef.java | 11 +- src/zutil/net/ws/WebServiceDef.java | 4 +- src/zutil/net/ws/soap/SOAPHttpPage.java | 14 +- src/zutil/osal/OSAbstractionLayer.java | 2 +- src/zutil/osal/linux/OsalLinuxImpl.java | 4 +- src/zutil/osal/linux/app/ProcDiskstats.java | 4 +- src/zutil/osal/linux/app/ProcNetArp.java | 2 +- src/zutil/osal/linux/app/ProcStat.java | 6 +- src/zutil/osal/linux/app/Ps.java | 3 +- src/zutil/parser/BBCodeParser.java | 2 +- src/zutil/parser/BEncodedParser.java | 12 +- src/zutil/parser/Base64Decoder.java | 3 +- src/zutil/parser/Base64Encoder.java | 9 +- src/zutil/parser/DataNode.java | 6 +- src/zutil/parser/MathParser.java | 148 +++++++------- src/zutil/parser/Templator.java | 14 +- src/zutil/parser/binary/BinaryFieldData.java | 2 +- .../binary/BinaryStructInputStream.java | 3 +- .../parser/json/JSONObjectInputStream.java | 47 ++--- .../parser/json/JSONObjectOutputStream.java | 36 ++-- src/zutil/parser/json/JSONParser.java | 10 +- src/zutil/parser/wsdl/WSDLWriter.java | 6 +- src/zutil/plugin/PluginData.java | 15 +- src/zutil/plugin/PluginManager.java | 22 +-- src/zutil/struct/HistoryList.java | 27 ++- src/zutil/ui/Configurator.java | 4 +- src/zutil/ui/Console.java | 6 +- src/zutil/ui/Navigation.java | 11 +- src/zutil/ui/wizard/Wizard.java | 15 +- src/zutil/ui/wizard/WizardActionHandler.java | 12 +- src/zutil/ui/wizard/WizardPage.java | 7 +- src/zutil/ui/wizard/page/SummaryPage.java | 4 +- .../wrapper/SerializableBufferedImage.java | 2 +- test/zutil/CronTimerTest.java | 6 +- test/zutil/StringUtilTest.java | 7 +- .../zutil/benchmark/StringSplitBenchmark.java | 2 +- test/zutil/db/DBConnectionTest.java | 4 +- test/zutil/image/ImageProcessorTest.java | 16 +- .../io/BufferedBoundaryInputStreamTest.java | 2 +- test/zutil/io/IOUtilTest.java | 5 +- test/zutil/io/file/FileChangedTest.java | 2 +- .../http/multipart/MultipartParserTest.java | 7 +- .../net/http/page/HttpDigestAuthPageTest.java | 2 +- .../net/http/page/HttpGuessTheNumber.java | 2 +- test/zutil/net/nio/NetworkClientTest.java | 2 +- test/zutil/net/nio/NetworkServerTest.java | 2 +- test/zutil/net/smtp/SmtpClientTest.java | 2 +- test/zutil/net/ws/soap/SOAPClientTest.java | 6 +- test/zutil/net/ws/soap/SOAPTest.java | 6 +- test/zutil/parser/CSVParserTest.java | 3 +- test/zutil/parser/URLDecoderTest.java | 3 +- .../binary/BinaryStructInputStreamTest.java | 19 +- .../binary/BinaryStructOutputStreamTest.java | 2 +- test/zutil/parser/json/JSONParserTest.java | 15 +- .../parser/json/JSONSerializerBenchmark.java | 14 +- .../zutil/parser/json/JSONSerializerTest.java | 33 ++-- test/zutil/struct/BloomFilterTest.java | 8 +- test/zutil/struct/CircularBufferTest.java | 12 +- test/zutil/struct/ObjectCacheTest.java | 3 +- 160 files changed, 951 insertions(+), 1151 deletions(-) diff --git a/.gitignore b/.gitignore index fd621eb..3a29440 100755 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ -Zutil.jar /build/ /bin/ /target/ diff --git a/Jenkinsfile b/Jenkinsfile index 09d756f..ded85db 100755 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -28,7 +28,9 @@ node { stage('Deploy') { // Figure out Pom version - def version = (readFile('pom.xml') =~ '(.+?)')[0][1] + def pom = readFile('pom.xml') + def versionMatch = pom =~ "(.+?)" + def version = versionMatch[0][1] // Start deployment sh 'mvn -DskipStatic -DskipTests deploy' diff --git a/src/zutil/ByteUtil.java b/src/zutil/ByteUtil.java index 4b046db..6f5413e 100755 --- a/src/zutil/ByteUtil.java +++ b/src/zutil/ByteUtil.java @@ -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>> 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(); diff --git a/src/zutil/ClassUtil.java b/src/zutil/ClassUtil.java index 8be10f2..2139105 100755 --- a/src/zutil/ClassUtil.java +++ b/src/zutil/ClassUtil.java @@ -39,7 +39,7 @@ public class ClassUtil { /** A Set that contains possible wrapper objects for primitives **/ private static final HashSet> wrappers; static { - wrappers = new HashSet>(); + 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> primitives; static { - primitives = new HashSet>(); + primitives = new HashSet<>(); primitives.add(boolean.class); primitives.add(char.class); primitives.add(byte.class); diff --git a/src/zutil/CronTimer.java b/src/zutil/CronTimer.java index 18c5a8c..8bd0229 100755 --- a/src/zutil/CronTimer.java +++ b/src/zutil/CronTimer.java @@ -96,10 +96,8 @@ public class CronTimer implements Iterator, Iterable{ String[] divisionArr = str.split("/", 2); if (divisionArr.length == 2) { float divider = Integer.parseInt(divisionArr[1]); - Iterator it = getRange(divisionArr[0], from, to).iterator(); - while (it.hasNext()) { - Integer i = it.next(); - if (i%divider == 0) + for (Integer i : getRange(divisionArr[0], from, to)) { + if (i % divider == 0) list.add(i); } } diff --git a/src/zutil/Encrypter.java b/src/zutil/Encrypter.java index 3ddce27..5cea8a5 100644 --- a/src/zutil/Encrypter.java +++ b/src/zutil/Encrypter.java @@ -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) { diff --git a/src/zutil/Hasher.java b/src/zutil/Hasher.java index 58f577a..296cfc2 100755 --- a/src/zutil/Hasher.java +++ b/src/zutil/Hasher.java @@ -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); @@ -165,14 +165,14 @@ public class Hasher { try { // Get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key, algo); - + // Get a MAC instance and initialize with the signing key Mac mac = Mac.getInstance(algo); mac.init(signingKey); - + // Compute the HMAC on input data bytes byte[] raw = mac.doFinal( data ); - + return Converter.toHexString(raw); } catch (Exception e) { e.printStackTrace(); @@ -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); diff --git a/src/zutil/OneInstance.java b/src/zutil/OneInstance.java index 7b87bcc..9989545 100644 --- a/src/zutil/OneInstance.java +++ b/src/zutil/OneInstance.java @@ -27,7 +27,7 @@ package zutil; /** * This interface is used to look if another instance of the * application is running - * + * * @author Ziver * */ @@ -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(); } diff --git a/src/zutil/OneInstanceNetwork.java b/src/zutil/OneInstanceNetwork.java index 62997e7..90c8232 100644 --- a/src/zutil/OneInstanceNetwork.java +++ b/src/zutil/OneInstanceNetwork.java @@ -33,7 +33,7 @@ import java.net.Socket; /** * This class checks if the app is alredy running * by Locking a port - * + * * @author Ziver Koc */ public class OneInstanceNetwork extends Thread implements OneInstance{ @@ -63,8 +63,8 @@ public class OneInstanceNetwork extends Thread implements OneInstance{ * should not be cald outside the class */ public void run() { - ServerSocket serverSocket = null; - Socket clientSocket = null; + ServerSocket serverSocket; + Socket clientSocket; try { // Create the server socket serverSocket = new ServerSocket(port, 1); diff --git a/src/zutil/ProgressListener.java b/src/zutil/ProgressListener.java index d842d49..a764f7c 100644 --- a/src/zutil/ProgressListener.java +++ b/src/zutil/ProgressListener.java @@ -27,7 +27,7 @@ package zutil; /** * This interface is used in some classes to handle the progress * of some action - * + * * @author Ziver * */ @@ -40,5 +40,5 @@ public interface ProgressListener { * @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); } diff --git a/src/zutil/StringUtil.java b/src/zutil/StringUtil.java index ca3ba0b..4001c92 100755 --- a/src/zutil/StringUtil.java +++ b/src/zutil/StringUtil.java @@ -31,7 +31,7 @@ import java.util.List; /** * This is a class whit utility methods. - * + * * @author Ziver * */ public class StringUtil { @@ -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 String join(String delimiter, T... array){ return join(delimiter, Arrays.asList(array)); } diff --git a/src/zutil/algo/EuclideansAlgo.java b/src/zutil/algo/EuclideansAlgo.java index 6f14145..3e53ed5 100644 --- a/src/zutil/algo/EuclideansAlgo.java +++ b/src/zutil/algo/EuclideansAlgo.java @@ -30,9 +30,9 @@ import java.math.BigInteger; import java.util.LinkedList; /** - * Euclidean algorithm is an algorithm to determine + * Euclidean algorithm is an algorithm to determine * the greatest common divisor (GCD) - * + * * @author Ziver * */ @@ -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 calcGenerators(int a, int b){ - LinkedList list = new LinkedList(); + LinkedList 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 calcGenerators(BigInteger a, BigInteger b){ - LinkedList list = new LinkedList(); + LinkedList list = new LinkedList<>(); BigInteger t; while( !b.equals(BigInteger.ZERO) ){ diff --git a/src/zutil/algo/ShanksTonelliAlgo.java b/src/zutil/algo/ShanksTonelliAlgo.java index e39da39..c2d7037 100644 --- a/src/zutil/algo/ShanksTonelliAlgo.java +++ b/src/zutil/algo/ShanksTonelliAlgo.java @@ -22,16 +22,13 @@ * THE SOFTWARE. */ -/** - * - */ package zutil.algo; import java.math.BigInteger; /** * The algorithm solves the discreet log equation x^2 = n mod p - * + * * @author Ziver * @see Wikipedia */ diff --git a/src/zutil/algo/WienersAlgo.java b/src/zutil/algo/WienersAlgo.java index fc3784d..d7e1058 100644 --- a/src/zutil/algo/WienersAlgo.java +++ b/src/zutil/algo/WienersAlgo.java @@ -33,7 +33,7 @@ import java.util.LinkedList; * The Wieners algorithm factorizes two big numbers a and b. * It uses the Euclidien algorithm to calculate the generator of the * numbers and then uses them to calculate the factorization. - * + * * @author Ziver * */ @@ -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 gen = EuclideansAlgo.calcGenerators(e, n); diff --git a/src/zutil/algo/path/BreadthFirstSearch.java b/src/zutil/algo/path/BreadthFirstSearch.java index 90d5f6f..166f084 100644 --- a/src/zutil/algo/path/BreadthFirstSearch.java +++ b/src/zutil/algo/path/BreadthFirstSearch.java @@ -43,8 +43,8 @@ public class BreadthFirstSearch implements PathFinder{ * @return A list with the path */ public LinkedList find(PathNode start, PathNode stop){ - Queue queue = new LinkedList(); - HashSet visited = new HashSet(); + Queue queue = new LinkedList<>(); + HashSet visited = new HashSet<>(); queue.add(start); visited.add( start ); diff --git a/src/zutil/algo/path/DepthFirstSearch.java b/src/zutil/algo/path/DepthFirstSearch.java index 197323d..8bbb765 100644 --- a/src/zutil/algo/path/DepthFirstSearch.java +++ b/src/zutil/algo/path/DepthFirstSearch.java @@ -29,11 +29,11 @@ import java.util.LinkedList; /** * A PathFinder class implemented with DFS - * + * * @author Ziver */ public class DepthFirstSearch { - private HashSet visited = new HashSet(); + private HashSet visited = new HashSet<>(); /** * Returns the first path to the destination diff --git a/src/zutil/algo/path/DynamicProgramming.java b/src/zutil/algo/path/DynamicProgramming.java index aa550a9..366c0bb 100644 --- a/src/zutil/algo/path/DynamicProgramming.java +++ b/src/zutil/algo/path/DynamicProgramming.java @@ -26,116 +26,62 @@ package zutil.algo.path; public class DynamicProgramming { public static char[][] words = new char[][]{ - "bibba".toCharArray(), - "bitas".toCharArray(), - "brott".toCharArray(), - "bl�ja".toCharArray(), - "boson".toCharArray() + "bibba".toCharArray(), + "bitas".toCharArray(), + "brott".toCharArray(), + "blaja".toCharArray(), + "boson".toCharArray() }; - public static void main(String[] args){ + 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�rsta raden i matrisen - if y == 0 - // finns f�rsta bokstaven i r�tt position i f�rsta ordet? - if words[0][x] != words[w][0] - matrix[w][y][x] = -1 - else - matrix[w][y][x] = 0 - else - // om f�reg�ende �r negativ s�tt nuvarande till negativ - if matrix[w][y-1][x] < 0 - matrix[w][y-1][x] = -1 - // h�r s� h�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 �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(){ + public int search() { int[][][] matrix = new int[words.length][words.length][words.length]; int shortest = -1; - for(int w=0; w= 0){ - matrix[w][y][x] = matrix[w][y-1][x] + tmp; - } - else{ + } else { + int tmp = smallestChange(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; } } } - if(y == words.length-1){ + if (y == words.length - 1) { int tmp = matrix[w][y][x]; - if((tmp= 0){ + if ((tmp < shortest || shortest < 0) + && tmp >= 0) { 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; - for(int i=0; i find(PathNode start, PathNode goal); + LinkedList find(PathNode start, PathNode goal); } diff --git a/src/zutil/algo/path/PathNode.java b/src/zutil/algo/path/PathNode.java index 13e94e1..89b09ea 100644 --- a/src/zutil/algo/path/PathNode.java +++ b/src/zutil/algo/path/PathNode.java @@ -32,23 +32,23 @@ public interface PathNode { /** * @return an Iterator with all its neighbors */ - public Iterable getNeighbors(); + Iterable 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 traversTo(PathNode goal); + LinkedList traversTo(PathNode goal); } diff --git a/src/zutil/algo/path/StandardPathNode.java b/src/zutil/algo/path/StandardPathNode.java index e828e6c..b7cb5db 100644 --- a/src/zutil/algo/path/StandardPathNode.java +++ b/src/zutil/algo/path/StandardPathNode.java @@ -37,7 +37,7 @@ public class StandardPathNode implements PathNode{ private PathNode parent; public StandardPathNode(){ - neighbors = new HashMap(); + neighbors = new HashMap<>(); } public int getNeighborCost(PathNode neighbor) { @@ -57,7 +57,7 @@ public class StandardPathNode implements PathNode{ } public LinkedList traversTo(PathNode goal) { - LinkedList path = new LinkedList(); + LinkedList path = new LinkedList<>(); PathNode current = this; while(current != null){ path.addFirst(current); @@ -66,8 +66,8 @@ public class StandardPathNode implements PathNode{ path.addFirst( goal ); return path; } - } - return new LinkedList(); + } + return new LinkedList<>(); } } diff --git a/src/zutil/algo/sort/ExternalSort.java b/src/zutil/algo/sort/ExternalSort.java index 3765ba5..1aee6f7 100644 --- a/src/zutil/algo/sort/ExternalSort.java +++ b/src/zutil/algo/sort/ExternalSort.java @@ -33,7 +33,7 @@ import java.util.LinkedList; * Sort very big files that doesn't fit in ram * Inspiration: * http://www.codeodor.com/index.cfm/2007/5/14/Re-Sorting-really-BIG-files---the-Java-source-code/1208 - * + * * @author Ziver */ public class ExternalSort { @@ -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 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 sortChunks() throws IOException{ - LinkedList chunkFiles = new LinkedList(); - LinkedList chunk = new LinkedList(); + LinkedList chunkFiles = new LinkedList<>(); + LinkedList 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 readChunk(BufferedReader in) throws IOException{ - LinkedList list = new LinkedList(); + LinkedList list = new LinkedList<>(); String tmp; for(int i=0; i list, File file) throws IOException{ BufferedWriter out = new BufferedWriter(new FileWriter(file)); - Iterator 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 list){ - Iterator it = list.iterator(); - while(it.hasNext()){ - it.next().delete(); + for (File file : list) { + file.delete(); } } } diff --git a/src/zutil/algo/sort/MergeSort.java b/src/zutil/algo/sort/MergeSort.java index 55195f8..5925050 100644 --- a/src/zutil/algo/sort/MergeSort.java +++ b/src/zutil/algo/sort/MergeSort.java @@ -73,9 +73,7 @@ public class MergeSort{ int length = pivot-start; int[] tmp = new int[stop-start]; - for(int i=0; i * * @param list is the list to merge * @param start is the start of the first sublist diff --git a/src/zutil/chart/AbstractChart.java b/src/zutil/chart/AbstractChart.java index 4c0162d..d671233 100755 --- a/src/zutil/chart/AbstractChart.java +++ b/src/zutil/chart/AbstractChart.java @@ -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){ diff --git a/src/zutil/chart/ChartData.java b/src/zutil/chart/ChartData.java index 5d159df..8a86ec6 100755 --- a/src/zutil/chart/ChartData.java +++ b/src/zutil/chart/ChartData.java @@ -42,10 +42,10 @@ public class ChartData { public ChartData(){ - xStrings = new HashMap(); - yStrings = new HashMap(); + xStrings = new HashMap<>(); + yStrings = new HashMap<>(); - points = new ArrayList(); + points = new ArrayList<>(); } public void setXValueString(int x, String name){ diff --git a/src/zutil/converter/Converter.java b/src/zutil/converter/Converter.java index 33df967..30f4393 100755 --- a/src/zutil/converter/Converter.java +++ b/src/zutil/converter/Converter.java @@ -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>> 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)) diff --git a/src/zutil/converter/NumberToWordsConverter.java b/src/zutil/converter/NumberToWordsConverter.java index 390a177..7482c2b 100755 --- a/src/zutil/converter/NumberToWordsConverter.java +++ b/src/zutil/converter/NumberToWordsConverter.java @@ -38,39 +38,39 @@ public class NumberToWordsConverter { private static final HashMap 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"); } diff --git a/src/zutil/converter/WGS84Converter.java b/src/zutil/converter/WGS84Converter.java index 9e14f53..12a59d7 100755 --- a/src/zutil/converter/WGS84Converter.java +++ b/src/zutil/converter/WGS84Converter.java @@ -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); diff --git a/src/zutil/db/DBConnection.java b/src/zutil/db/DBConnection.java index fffbf36..1bf9e58 100755 --- a/src/zutil/db/DBConnection.java +++ b/src/zutil/db/DBConnection.java @@ -129,7 +129,7 @@ public class DBConnection implements Closeable{ */ public long getLastInsertID(){ try{ - return exec("SELECT LAST_INSERT_ID()", new SimpleSQLResult()); + 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 * @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 exec(PreparedStatement stmt, SQLResultHandler handler) throws SQLException { + public static T exec(PreparedStatement stmt, SQLResultHandler 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]; diff --git a/src/zutil/db/DBConnectionPool.java b/src/zutil/db/DBConnectionPool.java index 8c0b24d..8b98133 100644 --- a/src/zutil/db/DBConnectionPool.java +++ b/src/zutil/db/DBConnectionPool.java @@ -33,7 +33,7 @@ import java.util.TimerTask; /** * This class is an connection pool - * + * * @author Ziver */ public class DBConnectionPool extends TimerTask implements Closeable{ @@ -74,15 +74,15 @@ public class DBConnectionPool extends TimerTask implements Closeable{ * @param user is the user name to the DB * @param 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(); - readyPool = new LinkedList(); + inusePool = new LinkedList<>(); + readyPool = new LinkedList<>(); this.setTimeout(DEFAULT_TIMEOUT); this.setMaxSize(DEFAULT_MAX_SIZE); diff --git a/src/zutil/db/DBUpgradeHandler.java b/src/zutil/db/DBUpgradeHandler.java index 763de7a..4661d03 100755 --- a/src/zutil/db/DBUpgradeHandler.java +++ b/src/zutil/db/DBUpgradeHandler.java @@ -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 getTableList(DBConnection db) throws SQLException { return db.exec("SELECT name FROM sqlite_master WHERE type='table';", new SQLResultHandler>() { public List handleQueryResult(Statement stmt, ResultSet result) throws SQLException { - ArrayList list = new ArrayList(); + ArrayList 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()); + return DBConnection.exec(stmt, new SimpleSQLResult<>()); } private static List getColumnList(DBConnection db, String table) throws SQLException { return db.exec( diff --git a/src/zutil/db/SQLQuery.java b/src/zutil/db/SQLQuery.java index 7c22e6c..ab885d2 100644 --- a/src/zutil/db/SQLQuery.java +++ b/src/zutil/db/SQLQuery.java @@ -24,11 +24,12 @@ package zutil.db; +import java.util.Collections; import java.util.LinkedList; /** * A class that generates a query by objects, minimizes errors - * + * * @author Ziver */ public class SQLQuery { @@ -157,13 +158,12 @@ public class SQLQuery { //******************************************* // Sub Types public static class SQLFrom extends SQLQueryItem{ - LinkedList tables = new LinkedList(); + LinkedList 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 conds = new LinkedList(); + LinkedList 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; } diff --git a/src/zutil/db/SQLResultHandler.java b/src/zutil/db/SQLResultHandler.java index c734aa4..3c16577 100644 --- a/src/zutil/db/SQLResultHandler.java +++ b/src/zutil/db/SQLResultHandler.java @@ -35,5 +35,5 @@ public interface SQLResultHandler { * @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; } diff --git a/src/zutil/db/bean/DBBean.java b/src/zutil/db/bean/DBBean.java index c4c045a..57c6e5a 100755 --- a/src/zutil/db/bean/DBBean.java +++ b/src/zutil/db/bean/DBBean.java @@ -42,12 +42,12 @@ import java.util.List; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; -/** +/** * The class that extends this will be able to save its state to a database. - * Fields that are transient will be ignored, and fields that extend - * DBBean will be replaced with the an id which corresponds to the field + * Fields that are transient will be ignored, and fields that extend + * DBBean will be replaced with the an id which corresponds to the field * of that object. - * + * * * Supported fields: * *Boolean @@ -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(" "); diff --git a/src/zutil/db/bean/DBBeanCache.java b/src/zutil/db/bean/DBBeanCache.java index f997f8f..9057b7d 100755 --- a/src/zutil/db/bean/DBBeanCache.java +++ b/src/zutil/db/bean/DBBeanCache.java @@ -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; diff --git a/src/zutil/db/bean/DBBeanConfig.java b/src/zutil/db/bean/DBBeanConfig.java index a51c212..9e4c7cb 100755 --- a/src/zutil/db/bean/DBBeanConfig.java +++ b/src/zutil/db/bean/DBBeanConfig.java @@ -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); diff --git a/src/zutil/image/ImageFilterProcessor.java b/src/zutil/image/ImageFilterProcessor.java index f8eb568..46a01b7 100644 --- a/src/zutil/image/ImageFilterProcessor.java +++ b/src/zutil/image/ImageFilterProcessor.java @@ -30,10 +30,10 @@ import java.awt.image.BufferedImage; /** * This is a abstract class for all the effects - * + * * Inspiration: * http://www.dickbaldwin.com/tocadv.htm - * + * * @author Ziver */ public abstract class ImageFilterProcessor { @@ -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; diff --git a/src/zutil/image/RAWImageUtil.java b/src/zutil/image/RAWImageUtil.java index 4402b8d..166719e 100644 --- a/src/zutil/image/RAWImageUtil.java +++ b/src/zutil/image/RAWImageUtil.java @@ -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)); } /** diff --git a/src/zutil/image/filter/MedianFilter.java b/src/zutil/image/filter/MedianFilter.java index cebfac4..ccee8ea 100755 --- a/src/zutil/image/filter/MedianFilter.java +++ b/src/zutil/image/filter/MedianFilter.java @@ -33,7 +33,7 @@ import java.awt.image.BufferedImage; /** * The MedianFilter is used for noise reduction and things - * + * * @author Ziver */ public class MedianFilter extends ImageFilterProcessor{ @@ -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++){ diff --git a/src/zutil/image/filter/ResizeImage.java b/src/zutil/image/filter/ResizeImage.java index 5e1f9d7..a1f0fd3 100755 --- a/src/zutil/image/filter/ResizeImage.java +++ b/src/zutil/image/filter/ResizeImage.java @@ -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); diff --git a/src/zutil/io/BufferedRandomAccessFile.java b/src/zutil/io/BufferedRandomAccessFile.java index 1c0b215..6423486 100644 --- a/src/zutil/io/BufferedRandomAccessFile.java +++ b/src/zutil/io/BufferedRandomAccessFile.java @@ -32,7 +32,7 @@ import java.io.RandomAccessFile; * This class is a buffer for the RandomeAccesFile * Inspiration: * http://www.javaworld.com/javaworld/javatips/jw-javatip26.html - * + * * @author Ziver */ public class BufferedRandomAccessFile extends RandomAccessFile{ @@ -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; } diff --git a/src/zutil/io/DynamicByteArrayStream.java b/src/zutil/io/DynamicByteArrayStream.java index 95b6e0b..52b3a64 100644 --- a/src/zutil/io/DynamicByteArrayStream.java +++ b/src/zutil/io/DynamicByteArrayStream.java @@ -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; diff --git a/src/zutil/io/IOUtil.java b/src/zutil/io/IOUtil.java index a4226d4..d2ddf74 100755 --- a/src/zutil/io/IOUtil.java +++ b/src/zutil/io/IOUtil.java @@ -28,7 +28,7 @@ import java.io.*; /** * Utility class for streams and general IO stuff - * + * * @author Ziver * */ @@ -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') diff --git a/src/zutil/io/MultiPrintStream.java b/src/zutil/io/MultiPrintStream.java index b624da4..06ca0eb 100755 --- a/src/zutil/io/MultiPrintStream.java +++ b/src/zutil/io/MultiPrintStream.java @@ -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"; diff --git a/src/zutil/io/NullWriter.java b/src/zutil/io/NullWriter.java index 329b911..7099cb8 100755 --- a/src/zutil/io/NullWriter.java +++ b/src/zutil/io/NullWriter.java @@ -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() { } } diff --git a/src/zutil/io/file/FileChangeListener.java b/src/zutil/io/file/FileChangeListener.java index e6694fa..a764791 100644 --- a/src/zutil/io/file/FileChangeListener.java +++ b/src/zutil/io/file/FileChangeListener.java @@ -28,7 +28,7 @@ import java.io.File; /** * Interface for the FileWatcher class - * + * * @author Ziver */ public interface FileChangeListener{ @@ -38,5 +38,5 @@ public interface FileChangeListener{ * * @param file The file that has changed */ - public void fileChangedEvent(File file); + void fileChangedEvent(File file); } diff --git a/src/zutil/io/file/FileSearcher.java b/src/zutil/io/file/FileSearcher.java index 4329ad6..b5cf3a2 100755 --- a/src/zutil/io/file/FileSearcher.java +++ b/src/zutil/io/file/FileSearcher.java @@ -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(); } diff --git a/src/zutil/io/file/FileUtil.java b/src/zutil/io/file/FileUtil.java index 5e7baea..c49a714 100755 --- a/src/zutil/io/file/FileUtil.java +++ b/src/zutil/io/file/FileUtil.java @@ -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)); } /** diff --git a/src/zutil/io/file/FileWatcher.java b/src/zutil/io/file/FileWatcher.java index f80e96f..a41df9d 100644 --- a/src/zutil/io/file/FileWatcher.java +++ b/src/zutil/io/file/FileWatcher.java @@ -32,9 +32,9 @@ import java.util.Timer; import java.util.TimerTask; /** - * This class calls a given listener + * This class calls a given listener * when a file is changed - * + * * @author Ziver * */ @@ -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){ diff --git a/src/zutil/jee/upload/AjaxFileUpload.java b/src/zutil/jee/upload/AjaxFileUpload.java index 12077a5..2176521 100644 --- a/src/zutil/jee/upload/AjaxFileUpload.java +++ b/src/zutil/jee/upload/AjaxFileUpload.java @@ -51,7 +51,7 @@ import java.util.logging.Logger; /** * <pre> - * Example web.xml: + * Example web.xml: * &lt;servlet&gt; * &lt;servlet-name&gt;Upload&lt;/servlet-name&gt; * &lt;servlet-class&gt;zall.util.AjaxFileUpload&lt;/servlet-class&gt; @@ -64,19 +64,19 @@ import java.util.logging.Logger; * &lt;param-value&gt;SYSTEM|SERVLET|{PATH}&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/servlet&gt; - * - * - * HTML Header: + * + * + * HTML Header: * &lt;script type='text/javascript' src='{PATH_TO_SERVLET}?js'&gt;&lt;/script&gt; * * - * HTML Body: + * HTML Body: * &lt;FORM id="AjaxFileUpload"&gt; * &lt;input type="file" multiple name="file" /&gt; * &lt;/FORM&gt; * &lt;UL id="UploadQueue"&gt;&lt;/UL&gt; - * - * + * + * * </pre> * @author Ziver * @@ -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; diff --git a/src/zutil/jee/upload/FileUploadListener.java b/src/zutil/jee/upload/FileUploadListener.java index 5400d84..365ca05 100644 --- a/src/zutil/jee/upload/FileUploadListener.java +++ b/src/zutil/jee/upload/FileUploadListener.java @@ -32,11 +32,11 @@ import zutil.parser.DataNode.DataType; /** * This is a File Upload Listener that is used by Apache - * Commons File Upload to monitor the progress of the + * Commons File Upload to monitor the progress of the * uploaded file. */ 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; diff --git a/src/zutil/log/CompactLogFormatter.java b/src/zutil/log/CompactLogFormatter.java index c833a7e..b7d0247 100755 --- a/src/zutil/log/CompactLogFormatter.java +++ b/src/zutil/log/CompactLogFormatter.java @@ -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(); diff --git a/src/zutil/log/CounterManager.java b/src/zutil/log/CounterManager.java index 85e50f1..1436f8a 100644 --- a/src/zutil/log/CounterManager.java +++ b/src/zutil/log/CounterManager.java @@ -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(); diff --git a/src/zutil/log/StreamLogger.java b/src/zutil/log/StreamLogger.java index e9e6731..4cec64b 100755 --- a/src/zutil/log/StreamLogger.java +++ b/src/zutil/log/StreamLogger.java @@ -82,7 +82,7 @@ public class StreamLogger { public interface LogCallback{ - public boolean isLoggable(); - public void log(String msg); + boolean isLoggable(); + void log(String msg); } } diff --git a/src/zutil/log/net/NetLogClient.fxml b/src/zutil/log/net/NetLogClient.fxml index 9657444..c23a2e0 100644 --- a/src/zutil/log/net/NetLogClient.fxml +++ b/src/zutil/log/net/NetLogClient.fxml @@ -26,38 +26,40 @@ <?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"> - <items> - <MenuItem mnemonicParsing="false" text="Open File" /> - <MenuItem mnemonicParsing="false" onAction="#handleConnectAction" text="Connect" /> - <Menu mnemonicParsing="false" text="Previous"> - <items> - <MenuItem mnemonicParsing="false" text="Koc.se:8080" /> - <MenuItem mnemonicParsing="false" text="localhost:8080" /> - </items> + <menus> + <Menu mnemonicParsing="false" text="File"> + <items> + <MenuItem mnemonicParsing="false" text="Open File"/> + <MenuItem mnemonicParsing="false" onAction="#handleConnectAction" text="Connect"/> + <Menu mnemonicParsing="false" text="Previous"> + <items> + <MenuItem mnemonicParsing="false" text="Koc.se:8080"/> + <MenuItem mnemonicParsing="false" text="localhost:8080"/> + </items> + </Menu> + <SeparatorMenuItem mnemonicParsing="false"/> + <MenuItem mnemonicParsing="false" text="Export"/> + <SeparatorMenuItem disable="true" mnemonicParsing="false"/> + <MenuItem mnemonicParsing="false" onAction="#handleExitAction" text="Exit"/> + </items> </Menu> - <SeparatorMenuItem mnemonicParsing="false" /> - <MenuItem mnemonicParsing="false" text="Export" /> - <SeparatorMenuItem disable="true" mnemonicParsing="false" /> - <MenuItem mnemonicParsing="false" onAction="#handleExitAction" text="Exit" /> - </items> - </Menu> - <Menu mnemonicParsing="false" text="Edit"> - <items> - <MenuItem disable="true" mnemonicParsing="false" text="Copy" /> - </items> - </Menu> - <Menu mnemonicParsing="false" text="Help"> - <items> - <MenuItem mnemonicParsing="false" onAction="#handleAboutAction" text="About" /> - </items> - </Menu> - </menus> + <Menu mnemonicParsing="false" text="Edit"> + <items> + <MenuItem disable="true" mnemonicParsing="false" text="Copy"/> + </items> + </Menu> + <Menu mnemonicParsing="false" text="Help"> + <items> + <MenuItem mnemonicParsing="false" onAction="#handleAboutAction" text="About"/> + </items> + </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> diff --git a/src/zutil/log/net/NetLogClient.java b/src/zutil/log/net/NetLogClient.java index 1fe9636..10c118b 100644 --- a/src/zutil/log/net/NetLogClient.java +++ b/src/zutil/log/net/NetLogClient.java @@ -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 ); } diff --git a/src/zutil/log/net/NetLogClientInstance.fxml b/src/zutil/log/net/NetLogClientInstance.fxml index 0205411..31edf82 100644 --- a/src/zutil/log/net/NetLogClientInstance.fxml +++ b/src/zutil/log/net/NetLogClientInstance.fxml @@ -36,93 +36,100 @@ <URL value="@NetLogClientInstance.css" /> </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"> - <font> - <Font size="11.0" /> - </font> - </Label> - <Region HBox.Hgrow="ALWAYS" /> - <Separator orientation="VERTICAL" prefHeight="200.0" valignment="CENTER" /> - <Label fx:id="logCountLabel" text="0"> - <graphic> - <Label text="Log Count:" /> - </graphic> - </Label> - </items> - </ToolBar> + <ToolBar maxHeight="22.0" minHeight="19.0" prefHeight="22.0" prefWidth="839.0"> + <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"/> + <Label fx:id="logCountLabel" text="0"> + <graphic> + <Label text="Log Count:"/> + </graphic> + </Label> + </ToolBar> </bottom> <center> - <SplitPane dividerPositions="0.7491525423728813" focusTraversable="true" orientation="VERTICAL" prefHeight="297.0" prefWidth="600.0"> - <items> - <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"> - <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" /> - </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"> - <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="450.0" text="StackTrace" fx:id="exStackTraceColumn" /> - </columns> - </TableView> - </children> - </AnchorPane> - </items> - </SplitPane> + <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"> + <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"/> + </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"> + <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="450.0" text="StackTrace" fx:id="exStackTraceColumn"/> + </columns> + </TableView> + </children> + </AnchorPane> + </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: " /> - <ComboBox fx:id="levelComboBox" layoutX="60.0" layoutY="-9.0" onAction="#handleLevelChanged"> - <items> - <FXCollections fx:factory="observableArrayList"> - <String fx:value="01 - ERROR" /> - <String fx:value="02 - WARNING" /> - <String fx:value="03 - INFO" /> - <String fx:value="04 - FINE" /> - <String fx:value="05 - FINER" /> - <String fx:value="06 - FINEST" /> - </FXCollections> - </items> - </ComboBox> - </children> - </Group> - <Group id="Group"> - <children> - <Label fx:id="intervalLabel" alignment="CENTER_RIGHT" layoutX="0.0" 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"> - <String fx:value="Instant" /> - <String fx:value="3 sec" /> - <String fx:value="5 sec" /> - <String fx:value="10 sec" /> - <String fx:value="30 sec" /> - <String fx:value="60 sec" /> - </FXCollections> - </items> - </ComboBox> - </children> - </Group> - </items> - </ToolBar> + <ToolBar maxHeight="30.0" minHeight="22.0" prefHeight="30.0" prefWidth="839.0"> + <ToggleButton fx:id="pauseButton" mnemonicParsing="false" onAction="#handlePauseAction" text="Pause"/> + <Region HBox.Hgrow="ALWAYS"/> + <Group id="Group"> + <children> + <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"> + <String fx:value="01 - ERROR"/> + <String fx:value="02 - WARNING"/> + <String fx:value="03 - INFO"/> + <String fx:value="04 - FINE"/> + <String fx:value="05 - FINER"/> + <String fx:value="06 - FINEST"/> + </FXCollections> + </items> + </ComboBox> + </children> + </Group> + <Group id="Group"> + <children> + <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"> + <String fx:value="Instant"/> + <String fx:value="3 sec"/> + <String fx:value="5 sec"/> + <String fx:value="10 sec"/> + <String fx:value="30 sec"/> + <String fx:value="60 sec"/> + </FXCollections> + </items> + </ComboBox> + </children> + </Group> + </ToolBar> </top> </BorderPane> diff --git a/src/zutil/log/net/NetLogExceptionMessage.java b/src/zutil/log/net/NetLogExceptionMessage.java index 6db4a0a..97ceaca 100755 --- a/src/zutil/log/net/NetLogExceptionMessage.java +++ b/src/zutil/log/net/NetLogExceptionMessage.java @@ -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(); } diff --git a/src/zutil/log/net/NetLogGuiClient.java b/src/zutil/log/net/NetLogGuiClient.java index efe72c9..6300e4d 100644 --- a/src/zutil/log/net/NetLogGuiClient.java +++ b/src/zutil/log/net/NetLogGuiClient.java @@ -36,30 +36,30 @@ import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.IOException; - + public class NetLogGuiClient extends Application{ public static final String VERSION = "0.1"; // UI elements - @FXML + @FXML private TabPane tabPane; public static void main(String[] args) { Application.launch(NetLogGuiClient.class, args); } - + @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("NetLogClient.fxml")); - + stage.setTitle("NetLoggerClient ("+VERSION+")"); stage.setScene(new Scene(root)); stage.show(); } // Menu Actions - @FXML + @FXML protected void handleConnectAction(ActionEvent event) { try{ tabPane.getTabs().add(new NetLoggerClientTab("koc.se", 8080)); @@ -82,8 +82,7 @@ public class NetLogGuiClient extends Application{ public NetLoggerClientTab(String host, int port) throws IOException{ 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>() { diff --git a/src/zutil/log/net/NetLogGuiClientInstance.java b/src/zutil/log/net/NetLogGuiClientInstance.java index 15fc819..bdd9d92 100644 --- a/src/zutil/log/net/NetLogGuiClientInstance.java +++ b/src/zutil/log/net/NetLogGuiClientInstance.java @@ -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 *****************/ diff --git a/src/zutil/log/net/NetLogListener.java b/src/zutil/log/net/NetLogListener.java index 1ad140b..c68129e 100644 --- a/src/zutil/log/net/NetLogListener.java +++ b/src/zutil/log/net/NetLogListener.java @@ -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); } diff --git a/src/zutil/log/net/NetLogServer.java b/src/zutil/log/net/NetLogServer.java index 052a2c9..d61c311 100755 --- a/src/zutil/log/net/NetLogServer.java +++ b/src/zutil/log/net/NetLogServer.java @@ -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); } diff --git a/src/zutil/net/FTPClient.java b/src/zutil/net/FTPClient.java index 6d3b773..40b4e1a 100755 --- a/src/zutil/net/FTPClient.java +++ b/src/zutil/net/FTPClient.java @@ -34,7 +34,7 @@ import java.util.regex.Pattern; /** * A simple FTP client class - * + * * @author Ziver * * http://en.wikipedia.org/wiki/List_of_FTP_commands @@ -48,12 +48,12 @@ public class FTPClient extends Thread{ public static final int FTP_DATA_PORT = 20; public static final int FTP_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); diff --git a/src/zutil/net/InetScanner.java b/src/zutil/net/InetScanner.java index 70d2c92..dffef99 100755 --- a/src/zutil/net/InetScanner.java +++ b/src/zutil/net/InetScanner.java @@ -31,13 +31,12 @@ 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; + String targetIp = netAddr + i; boolean online = isReachable(targetIp, exec); if (online && listener != null) listener.foundInetAddress(InetAddress.getByName(targetIp)); @@ -45,11 +44,8 @@ public class InetScanner { e.printStackTrace(); } } - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); - } finally { - exec.close(); } } diff --git a/src/zutil/net/POP3Client.java b/src/zutil/net/POP3Client.java index acfe00a..a244046 100644 --- a/src/zutil/net/POP3Client.java +++ b/src/zutil/net/POP3Client.java @@ -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,20 +33,19 @@ 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 * server and then can read and delete messages. * INFO: http://pages.prodigy.net/michael_santovec/pop3telnet.htm - * - * @author Ziver * + * @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,37 +55,31 @@ 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); } /** * Connect to a POP3 server with username and password * - * @param host The hostname of the server - * @param user The username + * @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); } /** * Connects to a POP3 server with username and password and SSL * - * @param host The hostname of the server - * @param user The username + * @param host The hostname of the server + * @param user The username * @param password the password - * @param ssl If SSL should be used - * @throws UnknownHostException - * @throws IOException + * @param ssl If SSL should be used */ - 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); } @@ -92,19 +87,17 @@ public class POP3Client { * Connects to a POP3 server with username and password and * SSL and with costume port. * - * @param host The hostname of the server - * @param port The port number to connect to on the server - * @param user The username + * @param host The hostname of the server + * @param port The port number to connect to on the server + * @param user The username * @param password the password - * @param ssl If SSL should be used - * @throws UnknownHostException - * @throws IOException + * @param ssl If SSL should be used */ - public POP3Client(String host, int port, String user, String password, boolean ssl) throws UnknownHostException, IOException{ - if(ssl) connectSSL(host, port); + public POP3Client(String host, int port, String user, String password, boolean ssl) throws IOException { + if (ssl) connectSSL(host, port); else connect(host, port); - if(user != null){ + if (user != null) { login(user, password); } } @@ -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,32 +122,29 @@ 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(); } /** * Logs in to the POP3 server with the username and password if the password is set * - * @param user The user name + * @param user The user name * @param password The password or null if no password is required - * @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); + private void login(String user, String password) throws IOException { + sendCommand("USER " + user); + if (password != null) { + sendNoReplyCommand("PASS " + password); + logger.finest("PASS ***"); + readCommand(); } } @@ -164,14 +152,13 @@ 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); + public int getMessageCount() throws IOException { + String msg = sendCommand("STAT"); return Integer.parseInt( msg.substring( - msg.indexOf(' ')+1, - msg.indexOf(' ', msg.indexOf(' ')+1))); + msg.indexOf(' ') + 1, + msg.indexOf(' ', 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); + public String getMessage(int id) throws IOException { + sendCommand("RETR " + id); + return readMultipleLines(); } /** @@ -191,18 +177,16 @@ public class POP3Client { * * @param id The message id * @return The title - * @throws IOException */ - public String getMessageTitle(int id) throws IOException{ + public String getMessageTitle(int id) throws IOException { String tmp = getMessageHeader(id); String tmp2 = tmp.toLowerCase(); - if(tmp2.contains("subject:")){ + if (tmp2.contains("subject:")) { return tmp.substring( - tmp2.indexOf("subject:")+8, + tmp2.indexOf("subject:") + 8, tmp2.indexOf('\n', tmp2.indexOf("subject:"))); - } - else + } else return null; } @@ -211,73 +195,54 @@ public class POP3Client { * * @param id The id of the message to get * @return The message - * @throws IOException */ - public String getMessageHeader(int id) throws IOException{ - sendCommand("TOP "+id+" 0"); - return readMultipleLines(DEBUG); + private String getMessageHeader(int id) throws IOException { + sendCommand("TOP " + id + " 0"); + 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); + public void delete(int id) throws IOException { + sendCommand("DELE " + id); } //*********************** 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); - if( !parseReturnCode(tmp) ) throw new IOException(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(".")){ + 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"); + private boolean parseReturnCode(String msg) { + 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); + public void reset() throws IOException { + sendCommand("RSET"); } /** * All the changes(DELETE) are performed and then the connection is closed - * - * @throws IOException */ - public void close() throws IOException{ - sendCommand("QUIT", DEBUG); + public void close() throws IOException { + sendCommand("QUIT"); in.close(); out.close(); socket.close(); diff --git a/src/zutil/net/ServerFind.java b/src/zutil/net/ServerFind.java index bf23618..bc95c3f 100644 --- a/src/zutil/net/ServerFind.java +++ b/src/zutil/net/ServerFind.java @@ -33,33 +33,32 @@ import java.net.InetAddress; import java.net.MulticastSocket; /** - * This class broadcast its address in the LAN so that + * This class broadcast its address in the LAN so that * the ServerFindClient can get the server IP - * + * * @author Ziver * */ 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(); } } diff --git a/src/zutil/net/ServerFindClient.java b/src/zutil/net/ServerFindClient.java index efead8b..22082dc 100644 --- a/src/zutil/net/ServerFindClient.java +++ b/src/zutil/net/ServerFindClient.java @@ -32,7 +32,7 @@ import java.net.MulticastSocket; /** * This class is the client for ServerFind that receives the server IP - * + * * @author Ziver * */ @@ -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); diff --git a/src/zutil/net/dns/MulticastDnsServer.java b/src/zutil/net/dns/MulticastDnsServer.java index c9a02bf..ba38ad9 100755 --- a/src/zutil/net/dns/MulticastDnsServer.java +++ b/src/zutil/net/dns/MulticastDnsServer.java @@ -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); } diff --git a/src/zutil/net/http/HttpClient.java b/src/zutil/net/http/HttpClient.java index 4561745..b0c69c3 100755 --- a/src/zutil/net/http/HttpClient.java +++ b/src/zutil/net/http/HttpClient.java @@ -34,13 +34,13 @@ import java.net.URL; import java.util.HashMap; /** - * This class connects to a HTTP server and + * This class connects to a HTTP server and * parses the result - * + * * @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 diff --git a/src/zutil/net/http/HttpHeader.java b/src/zutil/net/http/HttpHeader.java index bbdc61f..b082a0f 100755 --- a/src/zutil/net/http/HttpHeader.java +++ b/src/zutil/net/http/HttpHeader.java @@ -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<>(); } diff --git a/src/zutil/net/http/HttpPage.java b/src/zutil/net/http/HttpPage.java index 143ebfa..2b1956c 100755 --- a/src/zutil/net/http/HttpPage.java +++ b/src/zutil/net/http/HttpPage.java @@ -29,11 +29,11 @@ import java.util.Map; /** * This is a interface for a ordinary page for the HttpServer - * + * * @author Ziver * */ -public interface HttpPage{ +public interface HttpPage{ /** * This method has to be implemented for every page. * This method is called when a client wants a response @@ -45,9 +45,9 @@ public interface HttpPage{ * @param cookie is cookie information from the client * @param request is POST and GET requests from the client */ - public abstract void respond(HttpPrintStream out, - HttpHeader headers, - Map<String,Object> session, - Map<String,String> cookie, - Map<String,String> request) throws IOException; + void respond(HttpPrintStream out, + HttpHeader headers, + Map<String, Object> session, + Map<String, String> cookie, + Map<String, String> request) throws IOException; } diff --git a/src/zutil/net/http/HttpPrintStream.java b/src/zutil/net/http/HttpPrintStream.java index 4fd8316..771c49a 100755 --- a/src/zutil/net/http/HttpPrintStream.java +++ b/src/zutil/net/http/HttpPrintStream.java @@ -34,7 +34,7 @@ import java.util.HashMap; /** * This PrintStream is written for HTTP use * It has buffer capabilities and cookie management. - * + * * @author Ziver * */ @@ -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); } diff --git a/src/zutil/net/http/HttpServer.java b/src/zutil/net/http/HttpServer.java index 34dc203..304e799 100755 --- a/src/zutil/net/http/HttpServer.java +++ b/src/zutil/net/http/HttpServer.java @@ -46,7 +46,7 @@ import java.util.logging.Logger; /** * A simple web server that handles both cookies and * sessions for all the clients - * + * * @author Ziver */ public class HttpServer extends ThreadedTCPNetworkServer{ @@ -272,7 +272,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{ buff.append(", cookies: ").append(header==null ? null : header.toStringCookies()); buff.append(", 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)){ diff --git a/src/zutil/net/http/HttpURL.java b/src/zutil/net/http/HttpURL.java index 165a6fd..0803418 100755 --- a/src/zutil/net/http/HttpURL.java +++ b/src/zutil/net/http/HttpURL.java @@ -29,7 +29,7 @@ import java.util.HashMap; /** * Handles URLs in the HTTP protocol - * + * * @author Ziver */ public class HttpURL { @@ -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(){} diff --git a/src/zutil/net/http/multipart/MultipartField.java b/src/zutil/net/http/multipart/MultipartField.java index cdcecb9..36f172a 100755 --- a/src/zutil/net/http/multipart/MultipartField.java +++ b/src/zutil/net/http/multipart/MultipartField.java @@ -27,18 +27,18 @@ package zutil.net.http.multipart; /** * A interface representing a single field in a multipart message. - * + * * @author Ziver */ 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(); } diff --git a/src/zutil/net/http/multipart/MultipartFileField.java b/src/zutil/net/http/multipart/MultipartFileField.java index ffacf73..2d97700 100755 --- a/src/zutil/net/http/multipart/MultipartFileField.java +++ b/src/zutil/net/http/multipart/MultipartFileField.java @@ -36,7 +36,7 @@ import static zutil.net.http.multipart.MultipartParser.HEADER_CONTENT_TYPE; /** * A class for handling multipart files - * + * * @author Ziver */ public class MultipartFileField implements MultipartField{ @@ -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); diff --git a/src/zutil/net/http/multipart/MultipartParser.java b/src/zutil/net/http/multipart/MultipartParser.java index dbdaecd..2d30032 100755 --- a/src/zutil/net/http/multipart/MultipartParser.java +++ b/src/zutil/net/http/multipart/MultipartParser.java @@ -38,11 +38,11 @@ import java.util.logging.Level; import java.util.logging.Logger; /** - * Parses a multipart/form-data http request, + * Parses a multipart/form-data http request, * saves files to temporary location. - * + * * http://www.ietf.org/rfc/rfc1867.txt - * + * * @author Ziver * */ @@ -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); diff --git a/src/zutil/net/http/page/HttpDigestAuthPage.java b/src/zutil/net/http/page/HttpDigestAuthPage.java index 3a8525a..09e57cb 100755 --- a/src/zutil/net/http/page/HttpDigestAuthPage.java +++ b/src/zutil/net/http/page/HttpDigestAuthPage.java @@ -42,10 +42,7 @@ public class HttpDigestAuthPage implements HttpPage{ private HttpPage targetPage; - /** - * - * @param page - */ + public HttpDigestAuthPage(HttpPage page){ targetPage = page; } diff --git a/src/zutil/net/http/page/HttpFilePage.java b/src/zutil/net/http/page/HttpFilePage.java index fe713ea..776276b 100755 --- a/src/zutil/net/http/page/HttpFilePage.java +++ b/src/zutil/net/http/page/HttpFilePage.java @@ -119,17 +119,12 @@ public class HttpFilePage implements HttpPage{ } } - }catch (FileNotFoundException e){ + }catch (FileNotFoundException | SecurityException e){ if(!out.isHeaderSent()) out.setStatusCode(404); log.log(Level.WARNING, e.getMessage()); out.println("404 Page Not Found: " + headers.getRequestURL()); - }catch (SecurityException e){ - if(!out.isHeaderSent()) - out.setStatusCode(404); - log.log(Level.WARNING, e.getMessage()); - out.println("404 Page Not Found: " + headers.getRequestURL() ); - }catch (IOException e){ + } catch (IOException e){ if(!out.isHeaderSent()) out.setStatusCode(500); log.log(Level.WARNING, null, e); diff --git a/src/zutil/net/mqtt/packet/MqttPacketConnect.java b/src/zutil/net/mqtt/packet/MqttPacketConnect.java index 3083330..e808c0a 100755 --- a/src/zutil/net/mqtt/packet/MqttPacketConnect.java +++ b/src/zutil/net/mqtt/packet/MqttPacketConnect.java @@ -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; diff --git a/src/zutil/net/nio/NioClient.java b/src/zutil/net/nio/NioClient.java index 5928d78..7001fef 100755 --- a/src/zutil/net/nio/NioClient.java +++ b/src/zutil/net/nio/NioClient.java @@ -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); } diff --git a/src/zutil/net/nio/NioNetwork.java b/src/zutil/net/nio/NioNetwork.java index 652b059..db3af69 100755 --- a/src/zutil/net/nio/NioNetwork.java +++ b/src/zutil/net/nio/NioNetwork.java @@ -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,19 +160,17 @@ 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); - key.interestOps(change.ops); - logger.finest("change.ops "+change.ops); - break; - case ChangeRequest.REGISTER: - change.socket.register(selector, change.ops); - logger.finest("register socket "); - break; + case ChangeRequest.CHANGEOPS: + SelectionKey key = change.socket.keyFor(selector); + key.interestOps(change.ops); + logger.finest("change.ops " + change.ops); + break; + case ChangeRequest.REGISTER: + change.socket.register(selector, change.ops); + logger.finest("register socket "); + break; } } pendingChanges.clear(); diff --git a/src/zutil/net/nio/worker/chat/ChatListener.java b/src/zutil/net/nio/worker/chat/ChatListener.java index cdcb65b..a15325d 100755 --- a/src/zutil/net/nio/worker/chat/ChatListener.java +++ b/src/zutil/net/nio/worker/chat/ChatListener.java @@ -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); } diff --git a/src/zutil/net/nio/worker/chat/ChatMessage.java b/src/zutil/net/nio/worker/chat/ChatMessage.java index 278fa0c..884f965 100755 --- a/src/zutil/net/nio/worker/chat/ChatMessage.java +++ b/src/zutil/net/nio/worker/chat/ChatMessage.java @@ -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; diff --git a/src/zutil/net/nio/worker/chat/ChatService.java b/src/zutil/net/nio/worker/chat/ChatService.java index 7232283..08f68be 100755 --- a/src/zutil/net/nio/worker/chat/ChatService.java +++ b/src/zutil/net/nio/worker/chat/ChatService.java @@ -35,7 +35,7 @@ import java.util.logging.Logger; /** * A simple chat service with users and rooms - * + * * @author Ziver */ public class ChatService extends ThreadedEventWorker{ @@ -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<>()); } } diff --git a/src/zutil/net/nio/worker/grid/GridClient.java b/src/zutil/net/nio/worker/grid/GridClient.java index ebfbdbb..e34b397 100755 --- a/src/zutil/net/nio/worker/grid/GridClient.java +++ b/src/zutil/net/nio/worker/grid/GridClient.java @@ -37,7 +37,7 @@ import java.util.Queue; * This class is the client part of the grid. * It connects to a grid server and requests new job. * And then sends back the result to the server. - * + * * @author Ziver */ @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -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; } } diff --git a/src/zutil/net/nio/worker/sync/ObjectSync.java b/src/zutil/net/nio/worker/sync/ObjectSync.java index 68479d9..fc02427 100755 --- a/src/zutil/net/nio/worker/sync/ObjectSync.java +++ b/src/zutil/net/nio/worker/sync/ObjectSync.java @@ -38,7 +38,6 @@ public abstract class ObjectSync { /** * Applies the SyncMessage to the object - * @param message */ public abstract void syncObject(SyncMessage message); diff --git a/src/zutil/net/smtp/SmtpClient.java b/src/zutil/net/smtp/SmtpClient.java index fa31c20..768419b 100755 --- a/src/zutil/net/smtp/SmtpClient.java +++ b/src/zutil/net/smtp/SmtpClient.java @@ -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) diff --git a/src/zutil/net/ssdp/SSDPClient.java b/src/zutil/net/ssdp/SSDPClient.java index d0a82a2..5ef1f86 100755 --- a/src/zutil/net/ssdp/SSDPClient.java +++ b/src/zutil/net/ssdp/SSDPClient.java @@ -46,7 +46,7 @@ import static zutil.net.ssdp.SSDPServer.SSDP_PORT; /** * An SSDP client class that will request * service information. - * + * * @author Ziver */ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetworkThread{ @@ -63,8 +63,6 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork /** * Creates new instance of this class. An UDP * 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); } diff --git a/src/zutil/net/ssdp/SSDPCustomInfo.java b/src/zutil/net/ssdp/SSDPCustomInfo.java index e74be91..be6d268 100755 --- a/src/zutil/net/ssdp/SSDPCustomInfo.java +++ b/src/zutil/net/ssdp/SSDPCustomInfo.java @@ -24,7 +24,7 @@ package zutil.net.ssdp; -import zutil.net.http.HttpHeader; +import zutil.net.http.HttpHeader; import zutil.net.http.HttpPrintStream; /** @@ -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); } diff --git a/src/zutil/net/ssdp/SSDPServer.java b/src/zutil/net/ssdp/SSDPServer.java index 9cb0a26..a8fa01e 100755 --- a/src/zutil/net/ssdp/SSDPServer.java +++ b/src/zutil/net/ssdp/SSDPServer.java @@ -43,13 +43,13 @@ import java.util.logging.Level; import java.util.logging.Logger; /** - * A Server class that announces an service by the SSDP + * A Server class that announces an service by the SSDP * protocol specified at: * http://coherence.beebits.net/chrome/site/draft-cai-ssdp-v1-03.txt * ftp://ftp.pwg.org/pub/pwg/www/hypermail/ps/att-0188/01-psi_SSDP.pdf - * + * * @author Ziver - * + * * ********* Message clarification: * ****** Incoming: * ST: Search Target, this is object of the discovery request, (e.g., ssdp:all, etc.) @@ -85,7 +85,7 @@ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetwork super( SSDP_MULTICAST_ADDR, SSDP_PORT ); super.setThread( this ); - services = new HashMap<String, SSDPServiceInfo>(); + services = new HashMap<>(); setCacheTime( DEFAULT_CACHE_TIME ); enableNotify( true ); diff --git a/src/zutil/net/ssdp/SSDPServiceInfo.java b/src/zutil/net/ssdp/SSDPServiceInfo.java index 238f5a8..5fb0bb1 100755 --- a/src/zutil/net/ssdp/SSDPServiceInfo.java +++ b/src/zutil/net/ssdp/SSDPServiceInfo.java @@ -27,7 +27,7 @@ package zutil.net.ssdp; /** * This class contains information about a service from * or through the SSDP protocol - * + * * @author Ziver */ public interface SSDPServiceInfo { @@ -35,25 +35,25 @@ public interface SSDPServiceInfo { /** * @return the URL to the Service, e.g. "http://192.168.0.1:80/index.html" */ - 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(); } diff --git a/src/zutil/net/threaded/ThreadedTCPNetworkServer.java b/src/zutil/net/threaded/ThreadedTCPNetworkServer.java index c071c37..baf6e4a 100755 --- a/src/zutil/net/threaded/ThreadedTCPNetworkServer.java +++ b/src/zutil/net/threaded/ThreadedTCPNetworkServer.java @@ -43,7 +43,7 @@ import java.util.logging.Logger; /** * A simple network server that handles TCP communication - * + * * @author Ziver */ public abstract class ThreadedTCPNetworkServer extends Thread{ @@ -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); } diff --git a/src/zutil/net/threaded/ThreadedUDPNetwork.java b/src/zutil/net/threaded/ThreadedUDPNetwork.java index ad4f43b..0919e30 100755 --- a/src/zutil/net/threaded/ThreadedUDPNetwork.java +++ b/src/zutil/net/threaded/ThreadedUDPNetwork.java @@ -31,7 +31,7 @@ import java.net.*; /** * * A simple network server that handles UDP communication - * + * * @author Ziver */ public class ThreadedUDPNetwork extends Thread{ @@ -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); diff --git a/src/zutil/net/torrent/TorrentMetainfo.java b/src/zutil/net/torrent/TorrentMetainfo.java index f21368c..0f28aa2 100755 --- a/src/zutil/net/torrent/TorrentMetainfo.java +++ b/src/zutil/net/torrent/TorrentMetainfo.java @@ -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"); diff --git a/src/zutil/net/update/FileListMessage.java b/src/zutil/net/update/FileListMessage.java index 6dfeeb7..76eb7db 100644 --- a/src/zutil/net/update/FileListMessage.java +++ b/src/zutil/net/update/FileListMessage.java @@ -35,30 +35,31 @@ import java.util.List; /** * This class is used to store the files * and there hashes - * + * * @author Ziver */ -class FileListMessage implements Serializable{ +class FileListMessage implements Serializable { private static final long serialVersionUID = 1L; 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 * - * @param path is the path to scan + * @param path is the path to scan **/ - public FileListMessage(String path) throws IOException{ - fileList = new ArrayList<FileInfo>(); + public FileListMessage(String path) throws IOException { + fileList = new ArrayList<>(); List<File> files = FileUtil.search(FileUtil.find(path)); long totalSize = 0; - for(File file : files){ + for (File file : files) { FileInfo fileInfo = new FileInfo(path, file); - fileList.add( fileInfo ); + fileList.add(fileInfo); totalSize += fileInfo.getSize(); } this.totalSize = totalSize; @@ -69,24 +70,24 @@ class FileListMessage implements Serializable{ return totalSize; } - public ArrayList<FileInfo> getFileList(){ + public ArrayList<FileInfo> getFileList() { return fileList; } /** - * Compares the files and returns the files that differ from this file list + * Compares files and returns the ones that differ from this file list * - * @param comp is the file list to compare with - * @return + * @param comp is the file list to compare with + * @return a list of files that diff */ - public FileListMessage getDiff( FileListMessage comp){ + public FileListMessage getDiff(FileListMessage comp) { FileListMessage diff = new FileListMessage(); long diffSize = 0; - diff.fileList = new ArrayList<FileInfo>(); - for(FileInfo file : this.fileList){ - if( !comp.fileList.contains( file)){ - diff.fileList.add( file ); + diff.fileList = new ArrayList<>(); + for (FileInfo file : this.fileList) { + if (!comp.fileList.contains(file)) { + diff.fileList.add(file); diffSize += file.getSize(); } } @@ -96,9 +97,9 @@ class FileListMessage implements Serializable{ } - public boolean equals(Object comp){ - if(comp instanceof FileListMessage){ - FileListMessage tmp = (FileListMessage)comp; + public boolean equals(Object comp) { + if (comp instanceof FileListMessage) { + FileListMessage tmp = (FileListMessage) comp; return fileList.equals(tmp.fileList) && totalSize == tmp.totalSize; } return false; diff --git a/src/zutil/net/update/UpdateClient.java b/src/zutil/net/update/UpdateClient.java index f610e58..df2d8ac 100644 --- a/src/zutil/net/update/UpdateClient.java +++ b/src/zutil/net/update/UpdateClient.java @@ -36,7 +36,7 @@ import java.util.logging.Logger; /** * This class connects to a update server and updates a path * with the servers - * + * * @author Ziver * */ @@ -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(); diff --git a/src/zutil/net/update/UpdateServer.java b/src/zutil/net/update/UpdateServer.java index 3580e40..e95f002 100755 --- a/src/zutil/net/update/UpdateServer.java +++ b/src/zutil/net/update/UpdateServer.java @@ -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); } diff --git a/src/zutil/net/update/Zupdater.java b/src/zutil/net/update/Zupdater.java index 043e257..02042df 100644 --- a/src/zutil/net/update/Zupdater.java +++ b/src/zutil/net/update/Zupdater.java @@ -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); diff --git a/src/zutil/net/upnp/service/UPnPContentDirectory.java b/src/zutil/net/upnp/service/UPnPContentDirectory.java index 113f215..45b26ca 100755 --- a/src/zutil/net/upnp/service/UPnPContentDirectory.java +++ b/src/zutil/net/upnp/service/UPnPContentDirectory.java @@ -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++; diff --git a/src/zutil/net/ws/WSClientFactory.java b/src/zutil/net/ws/WSClientFactory.java index 0b90a0b..1e0c909 100755 --- a/src/zutil/net/ws/WSClientFactory.java +++ b/src/zutil/net/ws/WSClientFactory.java @@ -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){ diff --git a/src/zutil/net/ws/WSInterface.java b/src/zutil/net/ws/WSInterface.java index 7f0c3ff..4c265b9 100755 --- a/src/zutil/net/ws/WSInterface.java +++ b/src/zutil/net/ws/WSInterface.java @@ -29,7 +29,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * + * * Specifies web service definitions. Which methods that will * be published and other related metadata. * @@ -37,28 +37,28 @@ import java.lang.annotation.Target; * <pre> * private static class Test implements WSInterface{ * public Test(){} - * + * * &#64;WSDocumentation("blabla") * &#64;WSDLParamDocumentation("olle = a variable?") - * public void pubZ( + * public void pubZ( * &#64;WSParamName("olle") int lol) - * throws Exception{ + * throws Exception{ * .... * } - * + * * &#64;WSReturnName("param") - * public String pubA( + * public String pubA( * &#64;WSParamName(value="lol", optional=true) String lol) - * throws Exception{ + * throws Exception{ * .... * } - * + * * &#64;WSIgnore() - * public void privaZ(....){ + * public void privaZ(....){ * ... - * } + * } * } - * + * * </pre> * @author Ziver */ @@ -95,7 +95,7 @@ public interface WSInterface { */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) - public @interface WSIgnore { } + @interface WSIgnore { } /** * Method or Parameter comments for the WSDL. diff --git a/src/zutil/net/ws/WSMethodDef.java b/src/zutil/net/ws/WSMethodDef.java index ecff792..66aff63 100755 --- a/src/zutil/net/ws/WSMethodDef.java +++ b/src/zutil/net/ws/WSMethodDef.java @@ -31,6 +31,7 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; +import java.util.Collections; import java.util.List; /** @@ -67,9 +68,9 @@ public class WSMethodDef { throw new ClassCastException("Declaring class does not implement WSInterface!"); this.wsDef = wsDef; method = me; - inputs = new ArrayList<WSParameterDef>(); - outputs = new ArrayList<WSParameterDef>(); - exceptions = new ArrayList<Class<?>>(); + inputs = new ArrayList<>(); + outputs = new ArrayList<>(); + exceptions = new ArrayList<>(); name = method.getName(); //***** Documentation & Namespace @@ -84,9 +85,7 @@ public class WSMethodDef { namespace = wsDef.getNamespace()+"?#"+name; //***** Exceptions - for( Class<?> exc : method.getExceptionTypes() ){ - exceptions.add( exc ); - } + Collections.addAll(exceptions, method.getExceptionTypes()); //********* Get the input parameter names ********** Annotation[][] paramAnnotation = method.getParameterAnnotations(); diff --git a/src/zutil/net/ws/WebServiceDef.java b/src/zutil/net/ws/WebServiceDef.java index 3bb3d12..fc1b450 100755 --- a/src/zutil/net/ws/WebServiceDef.java +++ b/src/zutil/net/ws/WebServiceDef.java @@ -32,7 +32,7 @@ import java.util.Set; /** * Defines a web service from a class implementing the {@link zutil.net.ws.WSInterface} - * + * * @author Ziver */ public class WebServiceDef { @@ -48,7 +48,7 @@ public class WebServiceDef { public WebServiceDef(Class<? extends WSInterface> intf){ this.intf = intf; - methods = new HashMap<String,WSMethodDef>(); + methods = new HashMap<>(); name = intf.getSimpleName(); if( intf.getAnnotation( WSInterface.WSNamespace.class ) != null ) diff --git a/src/zutil/net/ws/soap/SOAPHttpPage.java b/src/zutil/net/ws/soap/SOAPHttpPage.java index 73be0f4..0ab967d 100755 --- a/src/zutil/net/ws/soap/SOAPHttpPage.java +++ b/src/zutil/net/ws/soap/SOAPHttpPage.java @@ -50,13 +50,13 @@ import java.util.logging.Level; import java.util.logging.Logger; /** - * This is an HTTPPage for the HTTPServer that + * This is an HTTPPage for the HTTPServer that * handles soap messages. - * + * * TODO: Header should be variables not methods * TODO: Read WSReturnObjects as input parameter * TODO: Ability to have multiple arrays of same WSReturnObject - * + * * Features: * Input: * <br>-int @@ -66,7 +66,7 @@ import java.util.logging.Logger; * <br>-String * <br>-byte[] * <br>-And the Wrappers Classes except for Byte - * + * * Output: * <br>-WSReturnObject * <br>-byte[] @@ -77,7 +77,7 @@ import java.util.logging.Logger; * <br>-String * <br>-Arrays of Output * <br>-And the Wrappers Classes except for Byte - * + * * @author Ziver */ public class SOAPHttpPage implements HttpPage{ @@ -142,7 +142,7 @@ public class SOAPHttpPage implements HttpPage{ out.setHeader("Content-Type", "text/xml"); out.flush(); - WSInterface obj = null; + WSInterface obj; if(session_enabled){ if( session.containsKey("SOAPInterface")) obj = (WSInterface)session.get("SOAPInterface"); @@ -185,7 +185,7 @@ public class SOAPHttpPage implements HttpPage{ */ public Document genSOAPResponse(String xml){ try { - WSInterface obj = null; + WSInterface obj; if( ws == null ) ws = wsDef.newInstance(); obj = ws; diff --git a/src/zutil/osal/OSAbstractionLayer.java b/src/zutil/osal/OSAbstractionLayer.java index 3ec2a16..b89ed1e 100755 --- a/src/zutil/osal/OSAbstractionLayer.java +++ b/src/zutil/osal/OSAbstractionLayer.java @@ -78,7 +78,7 @@ public abstract class OSAbstractionLayer { * @return a String list of the output of the command */ public static String[] exec(String cmd) { - ArrayList<String> ret = new ArrayList<String>(); + ArrayList<String> ret = new ArrayList<>(); try { Process proc = Runtime.getRuntime().exec(cmd); proc.waitFor(); diff --git a/src/zutil/osal/linux/OsalLinuxImpl.java b/src/zutil/osal/linux/OsalLinuxImpl.java index e2bc655..d2d98e6 100755 --- a/src/zutil/osal/linux/OsalLinuxImpl.java +++ b/src/zutil/osal/linux/OsalLinuxImpl.java @@ -49,7 +49,7 @@ public class OsalLinuxImpl extends OSAbstractionLayer { @Override public String getKernelVersion() { try{ - return super.getFirstLineFromExec("uname -r"); + return getFirstLineFromExec("uname -r"); } catch(Exception e){ e.printStackTrace(); } @@ -59,7 +59,7 @@ public class OsalLinuxImpl extends OSAbstractionLayer { @Override public String getUsername() { try{ - return super.getFirstLineFromExec("whoami"); + return getFirstLineFromExec("whoami"); } catch(Exception e){ e.printStackTrace(); } diff --git a/src/zutil/osal/linux/app/ProcDiskstats.java b/src/zutil/osal/linux/app/ProcDiskstats.java index b434971..541379e 100755 --- a/src/zutil/osal/linux/app/ProcDiskstats.java +++ b/src/zutil/osal/linux/app/ProcDiskstats.java @@ -46,7 +46,7 @@ public class ProcDiskstats { private static final String PROC_PATH = "/proc/diskstats"; private static final int TTL = 500; // update stats every 0.5 second - private static HashMap<String, HddStats> hdds = new HashMap<String, HddStats>(); + private static HashMap<String, HddStats> hdds = new HashMap<>(); private static Timer updateTimer = new Timer(TTL); @@ -64,7 +64,7 @@ public class ProcDiskstats { } protected static void parse(BufferedReader in) throws IOException { updateTimer.start(); - String line = null; + String line; while((line=in.readLine()) != null){ String[] str = line.trim().split("\\s+", 4); if(str.length >= 4) { diff --git a/src/zutil/osal/linux/app/ProcNetArp.java b/src/zutil/osal/linux/app/ProcNetArp.java index 3ba0e7d..8165218 100755 --- a/src/zutil/osal/linux/app/ProcNetArp.java +++ b/src/zutil/osal/linux/app/ProcNetArp.java @@ -65,7 +65,7 @@ public class ProcNetArp { } protected static void parse(BufferedReader in) throws IOException { updateTimer.start(); - String line = null; + String line; in.readLine(); // Skipp headers while ((line = in.readLine()) != null) { String[] str = line.split("\\s+"); diff --git a/src/zutil/osal/linux/app/ProcStat.java b/src/zutil/osal/linux/app/ProcStat.java index c3bd3c9..e173bd0 100755 --- a/src/zutil/osal/linux/app/ProcStat.java +++ b/src/zutil/osal/linux/app/ProcStat.java @@ -46,7 +46,7 @@ public class ProcStat { private static final int TTL = 500; // update stats every 0.5 second private static CpuStats cpuTotal = new CpuStats(); - private static ArrayList<CpuStats> cpus = new ArrayList<CpuStats>(); + private static ArrayList<CpuStats> cpus = new ArrayList<>(); private static long uptime; private static long processes; private static Timer updateTimer = new Timer(TTL); @@ -66,7 +66,7 @@ public class ProcStat { } protected static void parse(BufferedReader in) throws IOException { updateTimer.start(); - String line = null; + String line; while((line=in.readLine()) != null){ String[] str = line.split("\\s+"); if(str[0].equals("cpu")) { @@ -137,7 +137,7 @@ public class ProcStat { protected CpuStats(){} protected void update(String[] stats){ - long newUser=0, newNice=0, newSystem=0, newIdle=0, newIowait=0, newIrq=0, newSoftirq=0, newSteal=0, newGuest=0, newGuestNice=0; + long newUser, newNice, newSystem, newIdle, newIowait, newIrq, newSoftirq, newSteal=0, newGuest=0, newGuestNice=0; if(stats.length >= 1+8){ newUser = Long.parseLong(stats[1]); newNice = Long.parseLong(stats[2]); diff --git a/src/zutil/osal/linux/app/Ps.java b/src/zutil/osal/linux/app/Ps.java index e87d8a8..cee4119 100755 --- a/src/zutil/osal/linux/app/Ps.java +++ b/src/zutil/osal/linux/app/Ps.java @@ -30,10 +30,9 @@ import zutil.osal.OSAbstractionLayer; * Created by Ziver on 2014-12-23. */ public class Ps { - private static OSAbstractionLayer os = OSAbstractionLayer.getInstance(); public static boolean isRunning(int pid){ - String[] output = os.exec("ps -p "+pid); + String[] output = OSAbstractionLayer.exec("ps -p "+pid); return output.length > 1; } } diff --git a/src/zutil/parser/BBCodeParser.java b/src/zutil/parser/BBCodeParser.java index 32a0b7e..1bdccf4 100755 --- a/src/zutil/parser/BBCodeParser.java +++ b/src/zutil/parser/BBCodeParser.java @@ -42,7 +42,7 @@ public class BBCodeParser { * Initiates a instance of the parser with the most used BBCodes. */ public BBCodeParser(){ - bbcodes = new HashMap<String,String>(); + bbcodes = new HashMap<>(); addBBCode("b", "<b>%2</b>"); addBBCode("i", "<i>%2</i>"); addBBCode("u", "<u>%2</u>"); diff --git a/src/zutil/parser/BEncodedParser.java b/src/zutil/parser/BEncodedParser.java index 3dea590..1117ea1 100755 --- a/src/zutil/parser/BEncodedParser.java +++ b/src/zutil/parser/BEncodedParser.java @@ -50,15 +50,15 @@ public class BEncodedParser { * * @param data is the data to be decoded * @param index is the index in data to start from - * @return + * @return a DataNode representing the parsed content */ private static DataNode decode_BEncoded(MutableInt index, StringBuilder data) throws ParseException { String tmp; - char c = ' '; + char c; int end; switch (data.charAt(index.i)) { - /** + /* * Integers are prefixed with an i and terminated by an e. For * example, 123 would bEcode to i123e, -3272002 would bEncode to * i-3272002e. @@ -71,7 +71,7 @@ public class BEncodedParser { tmp = data.substring(index.i, end); index.i += tmp.length() + 1; return new DataNode( new Long(tmp)); - /** + /* * Lists are prefixed with a l and terminated by an e. The list * should contain a series of bEncoded elements. For example, the * list of strings ["Monduna", "Bit", "Torrents"] would bEncode to @@ -89,7 +89,7 @@ public class BEncodedParser { index.i++; if(list.size() == 1) return list.get(0); else return list; - /** + /* * Dictionaries are prefixed with a d and terminated by an e. They * are similar to list, except that items are in key value pairs. The * dictionary {"key":"value", "Monduna":"com", "bit":"Torrents", "number":7} @@ -108,7 +108,7 @@ public class BEncodedParser { } index.i++; return map; - /** + /* * Strings are prefixed with their length followed by a colon. * For example, "Monduna" would bEncode to 7:Monduna and "BitTorrents" * would bEncode to 11:BitTorrents. diff --git a/src/zutil/parser/Base64Decoder.java b/src/zutil/parser/Base64Decoder.java index 69547a6..d134327 100755 --- a/src/zutil/parser/Base64Decoder.java +++ b/src/zutil/parser/Base64Decoder.java @@ -122,7 +122,8 @@ public class Base64Decoder { } - private static byte getByte( char c ){ + @SuppressWarnings("PointlessBitwiseExpression") + private static byte getByte(char c ){ switch(c){ case 'A': return (byte)( 0 & 0xff); case 'B': return (byte)( 1 & 0xff); diff --git a/src/zutil/parser/Base64Encoder.java b/src/zutil/parser/Base64Encoder.java index b455fde..e4d4e66 100755 --- a/src/zutil/parser/Base64Encoder.java +++ b/src/zutil/parser/Base64Encoder.java @@ -28,12 +28,10 @@ package zutil.parser; public class Base64Encoder { public static String encode( byte[] data ){ - Base64Encoder base64 = new Base64Encoder(); - return base64.write( data ); + return write( data ); } public static String encode( String data ){ - Base64Encoder base64 = new Base64Encoder(); - return base64.write( data.getBytes() ); + return write( data.getBytes() ); } private static String write( byte[] data ){ @@ -88,7 +86,8 @@ public class Base64Encoder { } - private static char getChar( byte b ){ + @SuppressWarnings("PointlessBitwiseExpression") + private static char getChar(byte b ){ switch(b){ case (byte)( 0 & 0xff): return 'A'; case (byte)( 1 & 0xff): return 'B'; diff --git a/src/zutil/parser/DataNode.java b/src/zutil/parser/DataNode.java index b9e1d21..12f1e36 100644 --- a/src/zutil/parser/DataNode.java +++ b/src/zutil/parser/DataNode.java @@ -29,7 +29,7 @@ import java.util.*; /** * This is a data node used in JSON and BEncoding and other types - * + * * @author Ziver */ public class DataNode implements Iterable<DataNode>{ @@ -84,9 +84,9 @@ public class DataNode implements Iterable<DataNode>{ this.type = type; switch(type){ case Map: - map = new HashMap<String,DataNode>(); break; + map = new HashMap<>(); break; case List: - list = new LinkedList<DataNode>(); break; + list = new LinkedList<>(); break; default: break; } diff --git a/src/zutil/parser/MathParser.java b/src/zutil/parser/MathParser.java index a4bfac4..6802053 100644 --- a/src/zutil/parser/MathParser.java +++ b/src/zutil/parser/MathParser.java @@ -36,118 +36,112 @@ import java.io.InputStreamReader; */ public class MathParser { - public static MathNode parse(String functionString){ - StringBuffer functionStringBuffer = new StringBuffer(functionString+(char)0); + public static MathNode parse(String functionString) { + StringBuffer functionStringBuffer = new StringBuffer(functionString + (char) 0); MathNode node = new MathNode(); parse(functionStringBuffer, new StringBuffer(), null, node); - - System.out.println("----------------------------------------------------------------------"); - System.out.println(node+" = "+node.exec()); - System.out.println("----------------------------------------------------------------------"); return node; } - private static void parse(StringBuffer functionString, StringBuffer temp, MathOperation previus, MathNode rootNode){ - if(functionString.length() <= 0){ + private static void parse(StringBuffer functionString, StringBuffer temp, MathOperation previous, MathNode rootNode) { + if (functionString.length() <= 0) { return; } char c = functionString.charAt(0); functionString.deleteCharAt(0); - System.out.println("char: "+c); MathOperation current = null; - if(!Character.isWhitespace(c)){ - if(isNumber(c)){ + if (!Character.isWhitespace(c)) { + if (isNumber(c)) { temp.append(c); - } - else{ + } else { Math container = new MathNumber(); - if(temp.length() > 0){ - System.out.println("("+Double.parseDouble(temp.toString())+")"); - ((MathNumber)container).num = Double.parseDouble(temp.toString()); + if (temp.length() > 0) { + ((MathNumber) container).num = Double.parseDouble(temp.toString()); temp.delete(0, temp.length()); } - if(rootNode.math == null){ - System.out.println("Initializing rootNode"); - previus = getOperation(c); - System.out.println("operation: "+previus.getClass().getName()); - previus.math1 = container; - rootNode.math = previus; - } - else{ - if(c == '('){ - MathNode parenteses = new MathNode(); - MathOperation previousParanteses = previus; - parse(functionString, temp, previus, parenteses); - previousParanteses.math2 = parenteses; - System.out.println(parenteses); - container = parenteses; + if (rootNode.math == null) { + previous = getOperation(c); + previous.math1 = container; + rootNode.math = previous; + } else { + if (c == '(') { + MathNode parentheses = new MathNode(); + parse(functionString, temp, previous, parentheses); + previous.math2 = parentheses; + container = parentheses; // get the next operation c = functionString.charAt(0); functionString.deleteCharAt(0); - System.out.println("char: "+c); } current = getOperation(c); - System.out.println("operation: "+current.getClass().getName()); current.math1 = container; - previus.math2 = current; + previous.math2 = current; - if(c == ')'){ + if (c == ')') { return; } } } } - if(current != null) parse(functionString, temp, current, rootNode); - else parse(functionString, temp, previus, rootNode); - return; + if (current != null) + parse(functionString, temp, current, rootNode); + else + parse(functionString, temp, previous, rootNode); } - private static boolean isNumber(char c){ - if(Character.isDigit(c)){ - return true; - } - return false; + private static boolean isNumber(char c) { + return Character.isDigit(c); } - private static MathOperation getOperation(char c){ - switch(c){ - case '+': return new MathAddition(); - case '-': return new MathSubtraction(); - case '*': return new MathMultiplication(); - case '/': return new MathDivision(); - case '%': return new MathModulus(); - case '^': return new MathPow(); + private static MathOperation getOperation(char c) { + switch (c) { + case '+': + return new MathAddition(); + case '-': + return new MathSubtraction(); + case '*': + return new MathMultiplication(); + case '/': + return new MathDivision(); + case '%': + return new MathModulus(); + case '^': + return new MathPow(); case ')': - case (char)0: return new EmptyMath(); - default: return null; + case (char) 0: + return new EmptyMath(); + default: + return null; } } - public static void main(String[] args){ + public static void main(String[] args) { try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - while(true){ - System.out.print(">>Math: "); - parse(in.readLine()); + while (true) { + System.out.print("<< Math: "); + MathNode math = parse(in.readLine()); + System.out.println(">> = " + math.exec()); + } } catch (IOException e) { e.printStackTrace(); } } - static abstract class Math{ + static abstract class Math { public abstract double exec(); public abstract String toString(); } - static class MathNode extends Math{ + static class MathNode extends Math { Math math; public double exec() { @@ -155,11 +149,11 @@ public class MathParser { } public String toString() { - return "( "+math.toString()+" )"; + return "( " + math.toString() + " )"; } } - static class MathNumber extends Math{ + static class MathNumber extends Math { double num; public double exec() { @@ -167,84 +161,84 @@ public class MathParser { } public String toString() { - return ""+num; + return "" + num; } } - static abstract class MathOperation extends Math{ + static abstract class MathOperation extends Math { Math math1; Math math2; public abstract double exec(); } - static class MathAddition extends MathOperation{ + static class MathAddition extends MathOperation { public double exec() { return math1.exec() + math2.exec(); } public String toString() { - return math1.toString()+" + "+math2.toString(); + return math1.toString() + " + " + math2.toString(); } } - static class MathSubtraction extends MathOperation{ + static class MathSubtraction extends MathOperation { public double exec() { return math1.exec() - math2.exec(); } public String toString() { - return math1.toString()+" - "+math2.toString(); + return math1.toString() + " - " + math2.toString(); } } - static class MathMultiplication extends MathOperation{ + static class MathMultiplication extends MathOperation { public double exec() { return math1.exec() * math2.exec(); } public String toString() { - return math1.toString()+" * "+math2.toString(); + return math1.toString() + " * " + math2.toString(); } } - static class MathDivision extends MathOperation{ + static class MathDivision extends MathOperation { public double exec() { return math1.exec() / math2.exec(); } public String toString() { - return math1.toString()+" / "+math2.toString(); + return math1.toString() + " / " + math2.toString(); } } - static class MathModulus extends MathOperation{ + static class MathModulus extends MathOperation { public double exec() { return math1.exec() % math2.exec(); } public String toString() { - return math1.toString()+" % "+math2.toString(); + return math1.toString() + " % " + math2.toString(); } } - static class MathPow extends MathOperation{ + static class MathPow extends MathOperation { public double exec() { double ret = 1; double tmp1 = math1.exec(); double tmp2 = math2.exec(); - for(int i=0; i<tmp2 ;i++){ + for (int i = 0; i < tmp2; i++) { ret *= tmp1; } return ret; } public String toString() { - return math1.toString()+"^"+math2.toString(); + return math1.toString() + "^" + math2.toString(); } } - static class EmptyMath extends MathOperation{ + static class EmptyMath extends MathOperation { public double exec() { return math1.exec(); } diff --git a/src/zutil/parser/Templator.java b/src/zutil/parser/Templator.java index 9db62c3..bbe56a3 100755 --- a/src/zutil/parser/Templator.java +++ b/src/zutil/parser/Templator.java @@ -103,13 +103,13 @@ public class Templator { public Templator(File tmpl) throws IOException { if(tmpl == null) throw new IOException("File can not be null!"); - this.data = new HashMap<String, Object>(); + this.data = new HashMap<>(); this.file = tmpl; parseTemplate(FileUtil.getContent(file)); this.lastModified = file.lastModified(); } public Templator(String tmpl){ - this.data = new HashMap<String, Object>(); + this.data = new HashMap<>(); parseTemplate(tmpl); } @@ -226,14 +226,14 @@ public class Templator { /**************************** Template Helper Classes *************************************/ protected interface TemplateEntity { - public void compile(StringBuilder str); + void compile(StringBuilder str); } protected class TemplateNode implements TemplateEntity { private List<TemplateEntity> entities; public TemplateNode(){ - this.entities = new ArrayList<TemplateEntity>(); + this.entities = new ArrayList<>(); } public TemplateNode(TemplateNode node){ this.entities = node.entities; @@ -275,7 +275,7 @@ public class Templator { super.compile(str); } else if(obj instanceof Long){ - if ((Long) obj != 0l) + if ((Long) obj != 0L) super.compile(str); } else if(obj instanceof Float){ @@ -417,9 +417,7 @@ public class Templator { } } } - }catch (IllegalAccessException e){ - log.log(Level.WARNING, null, e); - } catch (InvocationTargetException e) { + }catch (IllegalAccessException | InvocationTargetException e){ log.log(Level.WARNING, null, e); } return null; diff --git a/src/zutil/parser/binary/BinaryFieldData.java b/src/zutil/parser/binary/BinaryFieldData.java index e9b82f4..417af4e 100755 --- a/src/zutil/parser/binary/BinaryFieldData.java +++ b/src/zutil/parser/binary/BinaryFieldData.java @@ -41,7 +41,7 @@ public class BinaryFieldData { list.add(new BinaryFieldData(field)); } } - Collections.sort(list, new Comparator<BinaryFieldData>(){ + list.sort(new Comparator<BinaryFieldData>() { @Override public int compare(BinaryFieldData o1, BinaryFieldData o2) { return o1.index - o2.index; diff --git a/src/zutil/parser/binary/BinaryStructInputStream.java b/src/zutil/parser/binary/BinaryStructInputStream.java index 0006d51..c7ab5f5 100755 --- a/src/zutil/parser/binary/BinaryStructInputStream.java +++ b/src/zutil/parser/binary/BinaryStructInputStream.java @@ -129,7 +129,6 @@ public class BinaryStructInputStream { protected static int shiftLeftBy(int bitIndex, int bitLength){ - int shiftBy = (8 - ((7-bitIndex) + bitLength) % 8) % 8; - return shiftBy; + return (8 - ((7-bitIndex) + bitLength) % 8) % 8; } } diff --git a/src/zutil/parser/json/JSONObjectInputStream.java b/src/zutil/parser/json/JSONObjectInputStream.java index 85e7b62..dabb625 100755 --- a/src/zutil/parser/json/JSONObjectInputStream.java +++ b/src/zutil/parser/json/JSONObjectInputStream.java @@ -93,34 +93,27 @@ public class JSONObjectInputStream extends InputStream implements ObjectInput, C * @return the object read from the stream */ @Override - public Object readObject() throws IOException { + public Object readObject() { return readObject(null); } /** * @param <T> is a simple cast to this type * @return the object read from the stream */ - public <T> T readGenericObject() throws IOException { + public <T> T readGenericObject() { return readObject(null); } /** * @param c will override the registered root class and use this value instead - * @param <T> * @return the object read from the stream */ - public synchronized <T> T readObject(Class<T> c) throws IOException { + public synchronized <T> T readObject(Class<T> c) { try{ DataNode root = parser.read(); if(root != null){ return (T)readObject(c, null, root); } - } catch (ClassNotFoundException e) { - logger.log(Level.WARNING, null, e); - } catch (NoSuchFieldException e) { - logger.log(Level.WARNING, null, e); - } catch (InstantiationException e) { - logger.log(Level.WARNING, null, e); - } catch (IllegalAccessException e) { + } catch (Exception e) { logger.log(Level.WARNING, null, e); } finally { objectCache.clear(); @@ -187,7 +180,7 @@ public class JSONObjectInputStream extends InputStream implements ObjectInput, C return objectCache.get(json.getInt(MD_OBJECT_ID)); // Resolve the class - Object obj = null; + Object obj; // Try using explicit class if(type != null){ obj = type.newInstance(); @@ -248,49 +241,49 @@ public class JSONObjectInputStream extends InputStream implements ObjectInput, C - @Override public void readFully(byte[] b) throws IOException { + @Override public void readFully(byte[] b) { throw new UnsupportedOperationException (); } - @Override public void readFully(byte[] b, int off, int len) throws IOException { + @Override public void readFully(byte[] b, int off, int len) { throw new UnsupportedOperationException (); } - @Override public int skipBytes(int n) throws IOException { + @Override public int skipBytes(int n) { throw new UnsupportedOperationException (); } - @Override public boolean readBoolean() throws IOException { + @Override public boolean readBoolean() { throw new UnsupportedOperationException (); } - @Override public byte readByte() throws IOException { + @Override public byte readByte() { throw new UnsupportedOperationException (); } - @Override public int readUnsignedByte() throws IOException { + @Override public int readUnsignedByte() { throw new UnsupportedOperationException (); } - @Override public short readShort() throws IOException { + @Override public short readShort() { throw new UnsupportedOperationException (); } - @Override public int readUnsignedShort() throws IOException { + @Override public int readUnsignedShort() { throw new UnsupportedOperationException (); } - @Override public char readChar() throws IOException { + @Override public char readChar() { throw new UnsupportedOperationException (); } - @Override public int readInt() throws IOException { + @Override public int readInt() { throw new UnsupportedOperationException (); } - @Override public long readLong() throws IOException { + @Override public long readLong() { throw new UnsupportedOperationException (); } - @Override public float readFloat() throws IOException { + @Override public float readFloat() { throw new UnsupportedOperationException (); } - @Override public double readDouble() throws IOException { + @Override public double readDouble() { throw new UnsupportedOperationException (); } - @Override public String readLine() throws IOException { + @Override public String readLine() { throw new UnsupportedOperationException (); } - @Override public String readUTF() throws IOException { + @Override public String readUTF() { throw new UnsupportedOperationException (); } @Override public int read() throws IOException { diff --git a/src/zutil/parser/json/JSONObjectOutputStream.java b/src/zutil/parser/json/JSONObjectOutputStream.java index babe523..0d0b175 100755 --- a/src/zutil/parser/json/JSONObjectOutputStream.java +++ b/src/zutil/parser/json/JSONObjectOutputStream.java @@ -169,8 +169,8 @@ public class JSONObjectOutputStream extends OutputStream implements ObjectOutput return root; } - private DataNode getPrimitiveDataNode(Class<?> type, Object value) throws UnsupportedDataTypeException, IllegalArgumentException, IllegalAccessException { - DataNode node = null; + private DataNode getPrimitiveDataNode(Class<?> type, Object value) throws UnsupportedDataTypeException, IllegalArgumentException { + DataNode node; if (type == int.class || type == Integer.class || type == long.class || @@ -179,10 +179,10 @@ public class JSONObjectOutputStream extends OutputStream implements ObjectOutput type == Double.class) node = new DataNode(DataType.Number); - else if(type == boolean.class || + else if(type == boolean.class || type == Boolean.class) node = new DataNode(DataType.Boolean); - + else if(type == String.class || type == char.class || type == Character.class) @@ -215,11 +215,11 @@ public class JSONObjectOutputStream extends OutputStream implements ObjectOutput ignoreNullFields = enable; } - public void flush() throws IOException { + public void flush() { out.flush(); } - public void close() throws IOException { + public void close() { if (out != null) { out.flush(); out.close(); @@ -228,40 +228,40 @@ public class JSONObjectOutputStream extends OutputStream implements ObjectOutput - @Override public void writeBoolean(boolean v) throws IOException { + @Override public void writeBoolean(boolean v) { out.write(new DataNode(v)); } - @Override public void writeByte(int v) throws IOException { + @Override public void writeByte(int v) { throw new UnsupportedOperationException (); } - @Override public void writeShort(int v) throws IOException { + @Override public void writeShort(int v) { out.write(new DataNode(v)); } - @Override public void writeChar(int v) throws IOException { + @Override public void writeChar(int v) { out.write(new DataNode((char)v)); } - @Override public void writeInt(int v) throws IOException { + @Override public void writeInt(int v) { out.write(new DataNode(v)); } - @Override public void writeLong(long v) throws IOException { + @Override public void writeLong(long v) { out.write(new DataNode(v)); } - @Override public void writeFloat(float v) throws IOException { + @Override public void writeFloat(float v) { out.write(new DataNode(v)); } - @Override public void writeDouble(double v) throws IOException { + @Override public void writeDouble(double v) { out.write(new DataNode(v)); } - @Override public void writeBytes(String s) throws IOException { + @Override public void writeBytes(String s) { throw new UnsupportedOperationException (); } - @Override public void writeChars(String s) throws IOException { + @Override public void writeChars(String s) { out.write(new DataNode(s)); } - @Override public void write(int b) throws IOException { + @Override public void write(int b) { out.write(new DataNode(b)); } - @Override public void writeUTF(String s) throws IOException { + @Override public void writeUTF(String s) { out.write(new DataNode(s)); } diff --git a/src/zutil/parser/json/JSONParser.java b/src/zutil/parser/json/JSONParser.java index d22ebb6..fdb4611 100755 --- a/src/zutil/parser/json/JSONParser.java +++ b/src/zutil/parser/json/JSONParser.java @@ -34,7 +34,7 @@ import java.util.regex.Pattern; /** * This is a JSON parser class - * + * * @author Ziver */ public class JSONParser extends Parser { @@ -87,12 +87,12 @@ public class JSONParser extends Parser { * This is the real recursive parsing method */ protected static DataNode parse(Reader in, MutableInt end) throws IOException { - DataNode root = null; - DataNode key = null; - DataNode node = null; + DataNode root; + DataNode key; + DataNode node; end.i = CONTINUE; - int c = '_'; + int c; while((c=in.read()) >= 0 && (Character.isWhitespace(c) || c == ',' || c == ':')); diff --git a/src/zutil/parser/wsdl/WSDLWriter.java b/src/zutil/parser/wsdl/WSDLWriter.java index da15e93..4720844 100644 --- a/src/zutil/parser/wsdl/WSDLWriter.java +++ b/src/zutil/parser/wsdl/WSDLWriter.java @@ -49,7 +49,7 @@ public class WSDLWriter{ private ArrayList<WSDLService> services; public WSDLWriter( WebServiceDef ws ){ - this.services = new ArrayList<WSDLService>(); + this.services = new ArrayList<>(); this.ws = ws; } @@ -86,8 +86,6 @@ public class WSDLWriter{ writer.flush(); this.cache = out.toString(); out.close(); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } @@ -269,7 +267,7 @@ public class WSDLWriter{ * </pre></b> */ private void generateType(Element definitions){ - ArrayList<Class<?>> types = new ArrayList<Class<?>>(); + ArrayList<Class<?>> types = new ArrayList<>(); // Find types for( WSMethodDef method : ws.getMethods() ){ if( method.getOutputCount() > 0 ){ diff --git a/src/zutil/plugin/PluginData.java b/src/zutil/plugin/PluginData.java index a6bd12e..66bf302 100755 --- a/src/zutil/plugin/PluginData.java +++ b/src/zutil/plugin/PluginData.java @@ -35,7 +35,7 @@ import java.util.logging.Logger; /** * This class contains information about a plugin * and implementation instances of the plugin interfaces - * + * * @author Ziver */ public class PluginData { @@ -47,9 +47,9 @@ public class PluginData { private HashMap<Class, Object> objectMap; - protected PluginData(DataNode data) throws ClassNotFoundException, MalformedURLException { + protected PluginData(DataNode data) { classMap = new HashMap<>(); - objectMap = new HashMap<Class, Object>(); + objectMap = new HashMap<>(); pluginVersion = data.getDouble("version"); pluginName = data.getString("name"); @@ -59,9 +59,8 @@ public class PluginData { if(node.isMap()) addInterfaces(node); else if(node.isList()) { - Iterator<DataNode> intfs_it = node.iterator(); - while (intfs_it.hasNext()) { - addInterfaces(intfs_it.next()); + for (DataNode childNode : node) { + addInterfaces(childNode); } } } @@ -84,7 +83,7 @@ public class PluginData { continue; if (!classMap.containsKey(intfClass)) - classMap.put(intfClass, new ArrayList<Class<?>>()); + classMap.put(intfClass, new ArrayList<>()); classMap.get(intfClass).add(pluginClass); } } @@ -109,7 +108,7 @@ public class PluginData { public <T> Iterator<T> getObjectIterator(Class<T> intf){ if(!classMap.containsKey(intf)) return Collections.emptyIterator(); - return new PluginObjectIterator<T>(classMap.get(intf).iterator()); + return new PluginObjectIterator<>(classMap.get(intf).iterator()); } public Iterator<Class<?>> getClassIterator(Class<?> intf){ if(!classMap.containsKey(intf)) diff --git a/src/zutil/plugin/PluginManager.java b/src/zutil/plugin/PluginManager.java index 67cc695..4294fa7 100755 --- a/src/zutil/plugin/PluginManager.java +++ b/src/zutil/plugin/PluginManager.java @@ -39,10 +39,10 @@ import java.util.logging.Logger; /** * This class will search the file system for files - * with the name "plugin.json" that defines data + * with the name "plugin.json" that defines data * parameters for a single plugin. * The class will only load the latest version of the specific plugin. - * + * * @author Ziver */ public class PluginManager<T> implements Iterable<PluginData>{ @@ -52,14 +52,14 @@ public class PluginManager<T> implements Iterable<PluginData>{ public static <T> PluginManager<T> load(String path){ - return new PluginManager<T>(path); + return new PluginManager<>(path); } public PluginManager(){ this("./"); } public PluginManager(String path){ - plugins = new HashMap<String, PluginData>(); + plugins = new HashMap<>(); FileSearcher search = new FileSearcher(new File(path)); search.setRecursive(true); @@ -97,21 +97,21 @@ public class PluginManager<T> implements Iterable<PluginData>{ public Iterator<PluginData> iterator() { return plugins.values().iterator(); } - public <T> Iterator<T> getObjectIterator(Class<T> intf) { - return new PluginObjectIterator<T>(plugins.values().iterator(), intf); + public <K> Iterator<K> getObjectIterator(Class<K> intf) { + return new PluginObjectIterator<>(plugins.values().iterator(), intf); } - public <T> Iterator<Class<? extends T>> getClassIterator(Class<T> intf) { - return new PluginClassIterator<T>(plugins.values().iterator(), intf); + public <K> Iterator<Class<? extends K>> getClassIterator(Class<K> intf) { + return new PluginClassIterator<>(plugins.values().iterator(), intf); } public ArrayList<PluginData> toArray() { return toGenericArray(iterator()); } - public <T> ArrayList<T> toArray(Class<T> intf) { + public <K> ArrayList<K> toArray(Class<K> intf) { return toGenericArray(getObjectIterator(intf)); } - private <T> ArrayList<T> toGenericArray(Iterator<T> it) { - ArrayList<T> list = new ArrayList<>(); + private <K> ArrayList<K> toGenericArray(Iterator<K> it) { + ArrayList<K> list = new ArrayList<>(); while(it.hasNext()) list.add(it.next()); return list; diff --git a/src/zutil/struct/HistoryList.java b/src/zutil/struct/HistoryList.java index c7cb7ae..f69023e 100644 --- a/src/zutil/struct/HistoryList.java +++ b/src/zutil/struct/HistoryList.java @@ -43,11 +43,11 @@ public class HistoryList<T> implements Iterable<T>{ /** * Creates an HistoryList object with an max size * - * @param histlength the maximum size of the list + * @param histLength the maximum size of the list */ - public HistoryList(int histlength){ - history_length = histlength; - history = new LinkedList<T>(); + public HistoryList(int histLength){ + history_length = histLength; + history = new LinkedList<>(); } /** @@ -67,11 +67,11 @@ public class HistoryList<T> implements Iterable<T>{ * @param item is the item to add */ public void add(T item){ - while(historyIndex < history.size()-1){ + while (historyIndex < history.size()-1){ history.removeLast(); } history.addLast(item); - if(history_length < history.size()){ + if (history_length < history.size()){ history.removeFirst(); } @@ -82,12 +82,10 @@ public class HistoryList<T> implements Iterable<T>{ * @return the previous item in the list */ public T getPrevious(){ - if(historyIndex > 0){ + if (historyIndex > 0) historyIndex -= 1; - } - else{ + else historyIndex = 0; - } return history.get(historyIndex); } @@ -95,7 +93,7 @@ public class HistoryList<T> implements Iterable<T>{ * @return the next item in the list */ public T getNext(){ - if(next()){ + if (next()){ historyIndex += 1; } else{ @@ -112,12 +110,9 @@ public class HistoryList<T> implements Iterable<T>{ * @return if there are items newer than the current */ public boolean next(){ - if(historyIndex < history.size()-1){ + if (historyIndex < history.size()-1) return true; - } - else{ - return false; - } + return false; } /** diff --git a/src/zutil/ui/Configurator.java b/src/zutil/ui/Configurator.java index 77e14a7..67524b7 100755 --- a/src/zutil/ui/Configurator.java +++ b/src/zutil/ui/Configurator.java @@ -107,7 +107,7 @@ public class Configurator<T> { return classConf.get(c); } protected static ConfigurationParam[] getConfiguration(Class c, Object obj){ - ArrayList<ConfigurationParam> conf = new ArrayList<ConfigurationParam>(); + ArrayList<ConfigurationParam> conf = new ArrayList<>(); for(Class<?> cc = c; cc != Object.class ;cc = cc.getSuperclass()) { // iterate through all super classes for (Field f : cc.getDeclaredFields()) { @@ -121,7 +121,7 @@ public class Configurator<T> { } } - ConfigurationParam[] list = conf.toArray(new ConfigurationParam[conf.size()]); + ConfigurationParam[] list = conf.toArray(new ConfigurationParam[0]); Arrays.sort(list); return list; } diff --git a/src/zutil/ui/Console.java b/src/zutil/ui/Console.java index a3caecd..2384f8d 100644 --- a/src/zutil/ui/Console.java +++ b/src/zutil/ui/Console.java @@ -38,9 +38,9 @@ import java.io.PrintStream; /** * Creates a Swing console window That takes System.in and - * System.out as Streams and has the ability to stay in the tray + * System.out as Streams and has the ability to stay in the tray * when closed - * + * * @author Ziver * */ @@ -256,7 +256,7 @@ public class Console{ private int input; @Override - public int read() throws IOException { + public int read() { if(input < 0) { input = 0; return -1; diff --git a/src/zutil/ui/Navigation.java b/src/zutil/ui/Navigation.java index 3271dbb..498b901 100755 --- a/src/zutil/ui/Navigation.java +++ b/src/zutil/ui/Navigation.java @@ -53,7 +53,7 @@ public class Navigation implements Iterable{ this.name = name; this.subNav = new ArrayList<>(); - this.navMap.put(this.id, this); + navMap.put(this.id, this); } @@ -83,7 +83,7 @@ public class Navigation implements Iterable{ return nav; } private void sortSubNavs(){ - Collections.sort(subNav, new Comparator<Navigation>() { + subNav.sort(new Comparator<Navigation>() { @Override public int compare(Navigation o1, Navigation o2) { if (o1.weight == o2.weight) @@ -149,8 +149,7 @@ public class Navigation implements Iterable{ public boolean equals(Object o){ if(o instanceof String) return this.name.equals(o); - return this == o || - (o != null && this.id == (((Navigation)o).id)); + return this == o || Objects.equals(this.id, ((Navigation) o).id); } @@ -192,7 +191,7 @@ public class Navigation implements Iterable{ return navMap.get(request.get(NAVIGATION_URL_KEY)); return null; } - + public NavInstance createPagedNavInstance(HttpHeader header){ @@ -216,7 +215,7 @@ public class Navigation implements Iterable{ } - + /** * @param nav the diff --git a/src/zutil/ui/wizard/Wizard.java b/src/zutil/ui/wizard/Wizard.java index d4cc90e..ed125e5 100644 --- a/src/zutil/ui/wizard/Wizard.java +++ b/src/zutil/ui/wizard/Wizard.java @@ -42,7 +42,7 @@ import java.util.ResourceBundle; /** * This class manages the whole wizard - * + * * @author Ziver */ public class Wizard implements ActionListener{ @@ -86,8 +86,8 @@ public class Wizard implements ActionListener{ public Wizard(WizardListener listener, final WizardPage start, final String bg){ try { this.listener = listener; - pages = new HistoryList<WizardPage>(); - values = new HashMap<String, Object>(); + pages = new HistoryList<>(); + values = new HashMap<>(); handler = new WizardActionHandler( values ); // GUI @@ -217,7 +217,7 @@ public class Wizard implements ActionListener{ JSeparator separator2 = new JSeparator(); pageTitle = new JLabel(); JSeparator separator3 = new JSeparator(); - error = new JLabel(); + JLabel error = new JLabel(); pageContainer = new JScrollPane(); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); @@ -326,8 +326,8 @@ public class Wizard implements ActionListener{ frame.pack(); } - - + + /** * @param args the command line arguments */ @@ -339,12 +339,11 @@ public class Wizard implements ActionListener{ wizard.start(); } }); - MultiPrintStream.out.dump( listener.getValues() ); + MultiPrintStream.out.dump(listener.getValues()); } // Variables declaration - do not modify - private JLabel error; private JButton back; private JButton cancel; private JButton finish; diff --git a/src/zutil/ui/wizard/WizardActionHandler.java b/src/zutil/ui/wizard/WizardActionHandler.java index 7a6b33b..277fa1f 100644 --- a/src/zutil/ui/wizard/WizardActionHandler.java +++ b/src/zutil/ui/wizard/WizardActionHandler.java @@ -61,7 +61,7 @@ public class WizardActionHandler implements ActionListener, FocusListener, ListS } public void registerListener(Component c){ - /** + /* * JToggleButton * JCheckBox * JRadioButton @@ -70,7 +70,7 @@ public class WizardActionHandler implements ActionListener, FocusListener, ListS JToggleButton o = (JToggleButton) c; o.addActionListener( this ); } - /** + /* * JEditorPane * JTextArea * JTextField @@ -79,7 +79,7 @@ public class WizardActionHandler implements ActionListener, FocusListener, ListS JTextComponent o = (JTextComponent) c; o.addFocusListener( this ); } - /** + /* * JList */ else if(c instanceof JList){ @@ -93,7 +93,7 @@ public class WizardActionHandler implements ActionListener, FocusListener, ListS * @param c is the event */ public void registerValue(Component c) { - /** + /* * JToggleButton * JCheckBox * JRadioButton @@ -102,7 +102,7 @@ public class WizardActionHandler implements ActionListener, FocusListener, ListS JToggleButton o = (JToggleButton) c; values.put( o.getName() , o.isSelected() ); } - /** + /* * JEditorPane * JTextArea * JTextField @@ -111,7 +111,7 @@ public class WizardActionHandler implements ActionListener, FocusListener, ListS JTextComponent o = (JTextComponent) c; values.put( o.getName() , o.getText() ); } - /** + /* * JList */ else if(c instanceof JList){ diff --git a/src/zutil/ui/wizard/WizardPage.java b/src/zutil/ui/wizard/WizardPage.java index 445c81e..e2a82cb 100644 --- a/src/zutil/ui/wizard/WizardPage.java +++ b/src/zutil/ui/wizard/WizardPage.java @@ -31,7 +31,7 @@ import java.util.LinkedList; /** * This abstract class is one step in the wizard - * + * * @author Ziver */ public abstract class WizardPage extends JPanel{ @@ -43,7 +43,7 @@ public abstract class WizardPage extends JPanel{ private boolean lastPage = false; public WizardPage(){ - components = new LinkedList<Component>(); + components = new LinkedList<>(); } /** @@ -111,7 +111,7 @@ public abstract class WizardPage extends JPanel{ /** * This class is for failed validations - * + * * @author Ziver */ class ValidationFail{ @@ -123,7 +123,6 @@ class ValidationFail{ /** * Creates an ValidationFail object * - * @param c is the component that failed the validation * @param msg is a message to the user about the fault */ public ValidationFail(String msg){ diff --git a/src/zutil/ui/wizard/page/SummaryPage.java b/src/zutil/ui/wizard/page/SummaryPage.java index 5ed2b9f..9730e03 100755 --- a/src/zutil/ui/wizard/page/SummaryPage.java +++ b/src/zutil/ui/wizard/page/SummaryPage.java @@ -32,7 +32,7 @@ import java.util.HashMap; /** * This class will show a summary of all the values * in the wizard - * + * * @author Ziver * */ @@ -47,7 +47,7 @@ public class SummaryPage extends WizardPage{ summary.setEnabled(false); this.add( summary ); - StringBuffer tmp = new StringBuffer(); + StringBuilder tmp = new StringBuilder(); for(String key : values.keySet()){ tmp.append(key); tmp.append(": "); diff --git a/src/zutil/wrapper/SerializableBufferedImage.java b/src/zutil/wrapper/SerializableBufferedImage.java index 1f161ea..326ce61 100644 --- a/src/zutil/wrapper/SerializableBufferedImage.java +++ b/src/zutil/wrapper/SerializableBufferedImage.java @@ -52,7 +52,7 @@ public class SerializableBufferedImage implements Serializable{ ImageIO.write(image,"jpeg",ImageIO.createImageOutputStream(out)); } - private void readObject(ObjectInputStream in)throws IOException, ClassNotFoundException{ + private void readObject(ObjectInputStream in) throws Exception { image = ImageIO.read(ImageIO.createImageInputStream(in)); } } diff --git a/test/zutil/CronTimerTest.java b/test/zutil/CronTimerTest.java index caeb2a5..965ad32 100755 --- a/test/zutil/CronTimerTest.java +++ b/test/zutil/CronTimerTest.java @@ -15,13 +15,13 @@ import static org.junit.Assert.fail; public class CronTimerTest { @Test - public void getRange() throws Exception { + public void getRange() { // invalid numbers assertEquals(Collections.EMPTY_LIST, CronTimer.getRange("", 0,60)); assertEquals(Collections.EMPTY_LIST, CronTimer.getRange(null, 0,60)); // individual numbers - assertEquals(Arrays.asList(55), CronTimer.getRange("55", 0,60)); + assertEquals(Collections.singletonList(55), CronTimer.getRange("55", 0,60)); assertEquals(Arrays.asList(5,10,15), CronTimer.getRange("5,10,15", 0, 60)); // ranges @@ -29,7 +29,7 @@ public class CronTimerTest { assertEquals(Arrays.asList(5,6,7,8,9,10), CronTimer.getRange("5-10", 0,60)); // intervals - assertEquals(Arrays.asList(), CronTimer.getRange("15/10", 0,60)); + assertEquals(Collections.emptyList(), CronTimer.getRange("15/10", 0,60)); assertEquals(Arrays.asList(0,10,20,30,40,50,60), CronTimer.getRange("0-60/10", 0,60)); // wildcards diff --git a/test/zutil/StringUtilTest.java b/test/zutil/StringUtilTest.java index 1b8a1c5..7f0049a 100755 --- a/test/zutil/StringUtilTest.java +++ b/test/zutil/StringUtilTest.java @@ -27,6 +27,7 @@ package zutil; import org.junit.Test; import java.util.Arrays; +import java.util.Collections; import static org.junit.Assert.assertEquals; @@ -43,9 +44,9 @@ public class StringUtilTest { public void formatTimeToStringTest() { assertEquals( "1 sec ", StringUtil.formatTimeToString( 1000 ) ); assertEquals( "1 month 1 day 1 hour 1 min 1 sec 1 milisec ", - StringUtil.formatTimeToString( 2629743830l+86400000+3600000+60000+1000+1 ) ); + StringUtil.formatTimeToString(2629743830L +86400000+3600000+60000+1000+1 ) ); assertEquals( "2 months 2 days 2 hours 2 min 2 sec 2 milisec ", - StringUtil.formatTimeToString( (2629743830l+86400000+3600000+60000+1000+1)*2 ) ); + StringUtil.formatTimeToString( (2629743830L +86400000+3600000+60000+1000+1)*2 ) ); } @Test @@ -72,7 +73,7 @@ public class StringUtilTest { @Test public void joinTest(){ - assertEquals("", StringUtil.join(",", Arrays.asList())); + assertEquals("", StringUtil.join(",", Collections.emptyList())); assertEquals("1,2,3,4,5", StringUtil.join(",", 1,2,3,4,5)); assertEquals("1,2,3,4,5", StringUtil.join(",", Arrays.asList(1,2,3,4,5))); assertEquals("animal,monkey,dog", StringUtil.join(",", "animal", "monkey", "dog")); diff --git a/test/zutil/benchmark/StringSplitBenchmark.java b/test/zutil/benchmark/StringSplitBenchmark.java index b3e0b73..a715039 100755 --- a/test/zutil/benchmark/StringSplitBenchmark.java +++ b/test/zutil/benchmark/StringSplitBenchmark.java @@ -40,7 +40,7 @@ public class StringSplitBenchmark { public void substring(){ for(int i=0; i<TEST_EXECUTIONS; i++) { List<String> splitList = StringUtil.split(str, delimiter.charAt(0)); - assertSplit(splitList.toArray(new String[splitList.size()])); + assertSplit(splitList.toArray(new String[0])); } } diff --git a/test/zutil/db/DBConnectionTest.java b/test/zutil/db/DBConnectionTest.java index 4fcb43e..101a6c6 100755 --- a/test/zutil/db/DBConnectionTest.java +++ b/test/zutil/db/DBConnectionTest.java @@ -44,13 +44,13 @@ public class DBConnectionTest { db.exec("UPDATE ..."); // Query 3 - String s = db.exec("SELECT hello", new SimpleSQLResult<String>()); + String s = db.exec("SELECT hello", new SimpleSQLResult<>()); System.out.println( s ); // Query 4 PreparedStatement sql2 = db.getPreparedStatement("SELECT ?"); sql2.setString(1, "hello"); - String s2 = DBConnection.exec(sql2, new SimpleSQLResult<String>()); + String s2 = DBConnection.exec(sql2, new SimpleSQLResult<>()); System.out.println( s2 ); db.close(); diff --git a/test/zutil/image/ImageProcessorTest.java b/test/zutil/image/ImageProcessorTest.java index e6a30b5..4352d35 100755 --- a/test/zutil/image/ImageProcessorTest.java +++ b/test/zutil/image/ImageProcessorTest.java @@ -41,11 +41,11 @@ import java.io.InputStream; @SuppressWarnings({ "unused", "rawtypes" }) public class ImageProcessorTest implements ProgressListener{ - private static String imgPath = "test.gif"; - //private static String imgPath = "test2.jpg"; + private static final String IMAGE_PATH = "test.gif"; + //private static final String IMAGE_PATH = "test2.jpg"; private JLabel processedLabel; - private JLabel orginalLabel; + private JLabel originalLabel; private JProgressBar progress; public static void main(String[] args){ @@ -59,15 +59,15 @@ public class ImageProcessorTest implements ProgressListener{ try { // Read from an input stream - InputStream is = new BufferedInputStream(new FileInputStream(imgPath)); + InputStream is = new BufferedInputStream(new FileInputStream(IMAGE_PATH)); img = ImageIO.read(is); } catch (IOException e) { e.printStackTrace(); System.exit(1); } - ImageIcon orginalIcon = new ImageIcon(img); - orginalLabel.setIcon(orginalIcon); + ImageIcon originalIcon = new ImageIcon(img); + originalLabel.setIcon(originalIcon); frame.setVisible(true); frame.pack(); @@ -98,7 +98,7 @@ public class ImageProcessorTest implements ProgressListener{ private JFrame getJFrame() { processedLabel = new JLabel("Processed"); - orginalLabel = new JLabel("Orginal"); + originalLabel = new JLabel("Original"); progress = new JProgressBar(); progress.setMaximum(100); @@ -108,7 +108,7 @@ public class ImageProcessorTest implements ProgressListener{ JPanel jPanel = new JPanel(); jPanel.setLayout(new BorderLayout()); - jPanel.add(orginalLabel, BorderLayout.NORTH); + jPanel.add(originalLabel, BorderLayout.NORTH); jPanel.add(processedLabel, BorderLayout.CENTER); jPanel.add(progress, BorderLayout.SOUTH); diff --git a/test/zutil/io/BufferedBoundaryInputStreamTest.java b/test/zutil/io/BufferedBoundaryInputStreamTest.java index e33e2e5..0d773dc 100755 --- a/test/zutil/io/BufferedBoundaryInputStreamTest.java +++ b/test/zutil/io/BufferedBoundaryInputStreamTest.java @@ -262,7 +262,7 @@ public class BufferedBoundaryInputStreamTest { "aaaaaaaaaaaa#aa#aaaaaaaaaaaaaaa#", "#", 10); byte[] buff = new byte[100]; - int n = 0; + int n; assertTrue(in.hasNext()); n = in.read(buff) + in.read(buff); assertEquals(12, n); diff --git a/test/zutil/io/IOUtilTest.java b/test/zutil/io/IOUtilTest.java index 8d479dd..1502b46 100755 --- a/test/zutil/io/IOUtilTest.java +++ b/test/zutil/io/IOUtilTest.java @@ -5,6 +5,7 @@ import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; /** * Created by Ziver on 2016-07-12. @@ -18,7 +19,7 @@ public class IOUtilTest { assertEquals("test", IOUtil.readLine(in)); assertEquals("test2", IOUtil.readLine(in)); assertEquals("test3", IOUtil.readLine(in)); - assertEquals(null, IOUtil.readLine(in)); + assertNull(IOUtil.readLine(in)); } @Test public void readLineCarriageReturn() throws IOException { @@ -26,6 +27,6 @@ public class IOUtilTest { assertEquals("test", IOUtil.readLine(in)); assertEquals("test2", IOUtil.readLine(in)); - assertEquals(null, IOUtil.readLine(in)); + assertNull(IOUtil.readLine(in)); } } diff --git a/test/zutil/io/file/FileChangedTest.java b/test/zutil/io/file/FileChangedTest.java index f4eca24..1307ebf 100755 --- a/test/zutil/io/file/FileChangedTest.java +++ b/test/zutil/io/file/FileChangedTest.java @@ -30,7 +30,7 @@ import java.net.URISyntaxException; public class FileChangedTest implements FileChangeListener{ - public static void main(String[] args) throws URISyntaxException, FileNotFoundException{ + public static void main(String[] args) throws FileNotFoundException{ FileWatcher watcher = new FileWatcher(FileUtil.find("test.txt")); watcher.setListener(new FileChangedTest()); diff --git a/test/zutil/net/http/multipart/MultipartParserTest.java b/test/zutil/net/http/multipart/MultipartParserTest.java index 7a64878..accecf3 100755 --- a/test/zutil/net/http/multipart/MultipartParserTest.java +++ b/test/zutil/net/http/multipart/MultipartParserTest.java @@ -7,8 +7,7 @@ import java.io.IOException; import java.util.Iterator; import static junit.framework.TestCase.assertFalse; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; /** * JUnit test for MultipartParser class @@ -41,8 +40,8 @@ public class MultipartParserTest { assertEquals("bar", stringField.getValue()); assertFalse(it.hasNext()); - assertEquals(null, it.next()); - assertEquals(null, it.next()); + assertNull(it.next()); + assertNull(it.next()); } @Test diff --git a/test/zutil/net/http/page/HttpDigestAuthPageTest.java b/test/zutil/net/http/page/HttpDigestAuthPageTest.java index afe1932..8ef30e4 100755 --- a/test/zutil/net/http/page/HttpDigestAuthPageTest.java +++ b/test/zutil/net/http/page/HttpDigestAuthPageTest.java @@ -37,7 +37,7 @@ public class HttpDigestAuthPageTest { HttpHeader rspHeader = HttpTestUtil.makeRequest(page); assertEquals(401, rspHeader.getHTTPCode()); - assertTrue(rspHeader.getHeader("WWW-Authenticate") != null); + assertNotNull(rspHeader.getHeader("WWW-Authenticate")); assertEquals("Digest", parseAuthType(rspHeader)); Map<String,String> authHeader = parseAuthHeader(rspHeader); assertTrue(authHeader.containsKey("realm")); diff --git a/test/zutil/net/http/page/HttpGuessTheNumber.java b/test/zutil/net/http/page/HttpGuessTheNumber.java index 3570c23..d13e0fd 100755 --- a/test/zutil/net/http/page/HttpGuessTheNumber.java +++ b/test/zutil/net/http/page/HttpGuessTheNumber.java @@ -46,7 +46,7 @@ public class HttpGuessTheNumber implements HttpPage { private static final String COOKIE_KEY_HIGH = "high"; - public static void main(String[] args) throws IOException{ + public static void main(String[] args) { LogUtil.setGlobalLevel(Level.ALL); LogUtil.setGlobalFormatter(new CompactLogFormatter()); diff --git a/test/zutil/net/nio/NetworkClientTest.java b/test/zutil/net/nio/NetworkClientTest.java index e217a8c..573e533 100755 --- a/test/zutil/net/nio/NetworkClientTest.java +++ b/test/zutil/net/nio/NetworkClientTest.java @@ -37,7 +37,7 @@ import java.security.NoSuchAlgorithmException; @SuppressWarnings("unused") public class NetworkClientTest { - public static void main(String[] args) throws NoSuchAlgorithmException, InterruptedException { + public static void main(String[] args) throws InterruptedException { try { //LogUtil.setGlobalLevel(Level.ALL); LogUtil.setGlobalFormatter(new CompactLogFormatter()); diff --git a/test/zutil/net/nio/NetworkServerTest.java b/test/zutil/net/nio/NetworkServerTest.java index d757377..44aeeef 100755 --- a/test/zutil/net/nio/NetworkServerTest.java +++ b/test/zutil/net/nio/NetworkServerTest.java @@ -34,7 +34,7 @@ import java.security.NoSuchAlgorithmException; @SuppressWarnings("unused") public class NetworkServerTest { - public static void main(String[] args) throws NoSuchAlgorithmException, InterruptedException { + public static void main(String[] args) throws InterruptedException { try { //LogUtil.setGlobalLevel(Level.ALL); LogUtil.setGlobalFormatter(new CompactLogFormatter()); diff --git a/test/zutil/net/smtp/SmtpClientTest.java b/test/zutil/net/smtp/SmtpClientTest.java index 4e6e43c..7e68ba5 100755 --- a/test/zutil/net/smtp/SmtpClientTest.java +++ b/test/zutil/net/smtp/SmtpClientTest.java @@ -9,7 +9,7 @@ import java.util.logging.Level; /** * Sends a test email with SmtpClient class. * - * @See <a href="https://nilhcem.github.io/FakeSMTP/">Fake SMTP Server</a> + * @see <a href="https://nilhcem.github.io/FakeSMTP/">Fake SMTP Server</a> */ public class SmtpClientTest { diff --git a/test/zutil/net/ws/soap/SOAPClientTest.java b/test/zutil/net/ws/soap/SOAPClientTest.java index 7d2facc..570c4a9 100755 --- a/test/zutil/net/ws/soap/SOAPClientTest.java +++ b/test/zutil/net/ws/soap/SOAPClientTest.java @@ -36,7 +36,7 @@ import java.util.logging.Level; // TODO: COnvert to JUnit public class SOAPClientTest { - public static void main(String[] args) throws InstantiationException, IllegalAccessException, MalformedURLException { + public static void main(String[] args) throws MalformedURLException { LogUtil.setGlobalLevel(Level.ALL); LogUtil.setFormatter("", new CompactLogFormatter()); @@ -47,9 +47,9 @@ public class SOAPClientTest { public interface TestClient extends WSInterface{ - public void m(); + void m(); - public void c(); + void c(); } } diff --git a/test/zutil/net/ws/soap/SOAPTest.java b/test/zutil/net/ws/soap/SOAPTest.java index 6cfb2de..af5f162 100755 --- a/test/zutil/net/ws/soap/SOAPTest.java +++ b/test/zutil/net/ws/soap/SOAPTest.java @@ -116,7 +116,7 @@ public class SOAPTest { @WSReturnName("stringArray") @WSParamDocumentation("Documentation of stringArrayMethod()") public String[][] stringArrayMethod ( - @WSParamName("StringName") String str) throws Exception{ + @WSParamName("StringName") String str) { System.out.println("Executing method: stringArrayMethod(String str='"+str+"')"); return new String[][]{{"test","test2"},{"test3","test4"}}; } @@ -124,7 +124,7 @@ public class SOAPTest { @WSReturnName("specialReturnClass") @WSParamDocumentation("Documentation of specialReturnMethod()") public SpecialReturnClass[] specialReturnMethod ( - @WSParamName("StringName2") String str) throws Exception{ + @WSParamName("StringName2") String str) { System.out.println("Executing method: specialReturnMethod(String str='"+str+"')"); return new SpecialReturnClass[]{new SpecialReturnClass(), new SpecialReturnClass()}; } @@ -132,7 +132,7 @@ public class SOAPTest { @WSReturnName("SimpleReturnClass") @WSParamDocumentation("null is the kala") public SimpleReturnClass simpleReturnClassMethod ( - @WSParamName("byte") String lol) throws Exception{ + @WSParamName("byte") String lol) { System.out.println("Executing method: simpleReturnClassMethod()"); SimpleReturnClass tmp = new SimpleReturnClass(); tmp.param1 = "newParam1"; diff --git a/test/zutil/parser/CSVParserTest.java b/test/zutil/parser/CSVParserTest.java index 42bfdf2..2a4f045 100755 --- a/test/zutil/parser/CSVParserTest.java +++ b/test/zutil/parser/CSVParserTest.java @@ -30,6 +30,7 @@ import java.io.IOException; import java.io.StringReader; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; /** @@ -41,7 +42,7 @@ public class CSVParserTest { @Test public void emptyTest(){ DataNode node = CSVParser.read(""); - assertEquals(null, node); + assertNull(node); } @Test diff --git a/test/zutil/parser/URLDecoderTest.java b/test/zutil/parser/URLDecoderTest.java index 52456b6..653530b 100755 --- a/test/zutil/parser/URLDecoderTest.java +++ b/test/zutil/parser/URLDecoderTest.java @@ -29,6 +29,7 @@ import org.junit.Test; import java.io.UnsupportedEncodingException; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; /** @@ -38,7 +39,7 @@ public class URLDecoderTest { @Test public void simpleTest(){ - assertEquals(null, URLDecoder.decode(null)); + assertNull(URLDecoder.decode(null)); assertEquals("", URLDecoder.decode("")); assertEquals("space space", URLDecoder.decode("space space")); assertEquals("space space", URLDecoder.decode("space+space")); diff --git a/test/zutil/parser/binary/BinaryStructInputStreamTest.java b/test/zutil/parser/binary/BinaryStructInputStreamTest.java index bbf69c1..4b840fb 100755 --- a/test/zutil/parser/binary/BinaryStructInputStreamTest.java +++ b/test/zutil/parser/binary/BinaryStructInputStreamTest.java @@ -30,8 +30,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.*; /** @@ -166,10 +165,10 @@ public class BinaryStructInputStreamTest { public void assertObj(){ assertEquals("i1", 6, i1); - assertEquals("b2", true, b2); - assertEquals("b3", true, b3); - assertEquals("b4", false, b4); - assertEquals("b5", true, b5); + assertTrue("b2", b2); + assertTrue("b3", b3); + assertFalse("b4", b4); + assertTrue("b5", b5); } }; @@ -194,12 +193,12 @@ public class BinaryStructInputStreamTest { } public static class ByteStringSerializer implements BinaryFieldSerializer<String>{ public String read(InputStream in, BinaryFieldData field) throws IOException { - String ret = ""; + StringBuilder ret = new StringBuilder(); for (int c; (c=in.read()) > 0; ) - ret += c; - return ret; + ret.append(c); + return ret.toString(); } - public void write(OutputStream out, String obj, BinaryFieldData field) throws IOException {} + public void write(OutputStream out, String obj, BinaryFieldData field) {} } diff --git a/test/zutil/parser/binary/BinaryStructOutputStreamTest.java b/test/zutil/parser/binary/BinaryStructOutputStreamTest.java index 4b2c70d..2a5d232 100755 --- a/test/zutil/parser/binary/BinaryStructOutputStreamTest.java +++ b/test/zutil/parser/binary/BinaryStructOutputStreamTest.java @@ -138,7 +138,7 @@ public class BinaryStructOutputStreamTest { assertArrayEquals(new byte[]{0b0000_0001,0b0000_0010,0b0000_0011,0b0000_0100}, data); } public static class ByteStringSerializer implements BinaryFieldSerializer<String>{ - public String read(InputStream in, BinaryFieldData field) throws IOException { + public String read(InputStream in, BinaryFieldData field) { return null; } public void write(OutputStream out, String obj, BinaryFieldData field) throws IOException { diff --git a/test/zutil/parser/json/JSONParserTest.java b/test/zutil/parser/json/JSONParserTest.java index dfd6181..1c43ac5 100755 --- a/test/zutil/parser/json/JSONParserTest.java +++ b/test/zutil/parser/json/JSONParserTest.java @@ -28,8 +28,7 @@ import org.junit.Test; import zutil.parser.DataNode; import zutil.parser.DataNode.DataType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; public class JSONParserTest { @@ -75,23 +74,23 @@ public class JSONParserTest { assertEquals( DataType.Number, data.getType()); assertEquals( 12.34, data.getDouble(), 0); } - + @Test public void valueBoolean(){ DataNode data = JSONParser.read("false"); assert(data.isValue()); assertEquals( DataType.Boolean, data.getType()); - assertEquals( false, data.getBoolean()); + assertFalse(data.getBoolean()); } - + @Test public void valueBooleanUpperCase(){ DataNode data = JSONParser.read("TRUE"); assert(data.isValue()); assertEquals( DataType.Boolean, data.getType()); - assertEquals( true, data.getBoolean()); + assertTrue(data.getBoolean()); } - + @Test public void valueStringNoQuotes(){ DataNode data = JSONParser.read("teststring"); @@ -99,7 +98,7 @@ public class JSONParserTest { assertEquals( DataType.String, data.getType()); assertEquals( "teststring", data.getString()); } - + @Test public void toManyCommasInList(){ DataNode data = JSONParser.read("[1,2,3,]"); diff --git a/test/zutil/parser/json/JSONSerializerBenchmark.java b/test/zutil/parser/json/JSONSerializerBenchmark.java index 2299615..eff02ad 100755 --- a/test/zutil/parser/json/JSONSerializerBenchmark.java +++ b/test/zutil/parser/json/JSONSerializerBenchmark.java @@ -39,7 +39,7 @@ public class JSONSerializerBenchmark { public BenchmarkRule benchmarkRun = new BenchmarkRule(); @Test - public void testJavaLegacySerialize() throws InterruptedException, IOException, ClassNotFoundException{ + public void testJavaLegacySerialize() throws IOException, ClassNotFoundException{ for(int i=0; i<TEST_EXECUTIONS; i++){ TestClass sourceObj = new TestClass().init(); @@ -60,7 +60,7 @@ public class JSONSerializerBenchmark { } @Test - public void testJavaJSONSerialize() throws InterruptedException, IOException, ClassNotFoundException{ + public void testJavaJSONSerialize() throws IOException { for(int i=0; i<TEST_EXECUTIONS; i++){ TestClass sourceObj = new TestClass().init(); @@ -71,7 +71,7 @@ public class JSONSerializerBenchmark { } @Test - public void testOutputJavaLegacySerialize() throws InterruptedException, IOException, ClassNotFoundException{ + public void testOutputJavaLegacySerialize() throws IOException { for(int i=0; i<TEST_EXECUTIONS; i++){ TestClass sourceObj = new TestClass().init(); @@ -85,7 +85,7 @@ public class JSONSerializerBenchmark { } @Test - public void testOutputJavaJSONSerialize() throws InterruptedException, IOException, ClassNotFoundException{ + public void testOutputJavaJSONSerialize() throws IOException { for(int i=0; i<TEST_EXECUTIONS; i++){ TestClass sourceObj = new TestClass().init(); @@ -94,7 +94,7 @@ public class JSONSerializerBenchmark { } @Test - public void testInputJavaLegacySerialize() throws InterruptedException, IOException, ClassNotFoundException{ + public void testInputJavaLegacySerialize() throws IOException, ClassNotFoundException{ TestClass sourceObj = new TestClass().init(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); @@ -113,12 +113,12 @@ public class JSONSerializerBenchmark { } @Test - public void testInputJavaJSONSerialize() throws InterruptedException, IOException, ClassNotFoundException{ + public void testInputJavaJSONSerialize() throws IOException { TestClass sourceObj = new TestClass().init(); String sourceStr = JSONSerializerTest.writeObjectToJson(sourceObj); for(int i=0; i<TEST_EXECUTIONS; i++){ - TestClass targetObj = JSONSerializerTest.readObjectFromJson(sourceStr); + JSONSerializerTest.readObjectFromJson(sourceStr); } } } diff --git a/test/zutil/parser/json/JSONSerializerTest.java b/test/zutil/parser/json/JSONSerializerTest.java index 4498c7d..346da10 100755 --- a/test/zutil/parser/json/JSONSerializerTest.java +++ b/test/zutil/parser/json/JSONSerializerTest.java @@ -41,7 +41,7 @@ import static org.junit.Assert.assertThat; public class JSONSerializerTest{ @Test - public void testOutputSerializerWithPrimitives() throws InterruptedException, IOException, ClassNotFoundException{ + public void testOutputSerializerWithPrimitives() throws IOException { TestClass sourceObj = new TestClass().init(); String data = writeObjectToJson(sourceObj); @@ -53,7 +53,7 @@ public class JSONSerializerTest{ } @Test - public void testInputSerializerWithPrimitives() throws InterruptedException, IOException, ClassNotFoundException{ + public void testInputSerializerWithPrimitives() throws IOException { TestClass sourceObj = new TestClass().init(); TestClass targetObj = sendReceiveObject(sourceObj); @@ -62,7 +62,7 @@ public class JSONSerializerTest{ } @Test - public void testOutputSerializerWithClones() throws InterruptedException, IOException, ClassNotFoundException{ + public void testOutputSerializerWithClones() throws IOException { TestClassObjClone sourceObj = new TestClassObjClone().init(); String data = writeObjectToJson(sourceObj); @@ -74,7 +74,7 @@ public class JSONSerializerTest{ } @Test - public void testInputSerializerWithClones() throws InterruptedException, IOException, ClassNotFoundException{ + public void testInputSerializerWithClones() throws IOException { TestClassObjClone sourceObj = new TestClassObjClone().init(); TestClassObjClone targetObj = sendReceiveObject(sourceObj); @@ -95,7 +95,7 @@ public class JSONSerializerTest{ } @Test - public void testInputSerializerWithArrays() throws InterruptedException, IOException, ClassNotFoundException{ + public void testInputSerializerWithArrays() throws IOException { TestClassArray sourceObj = new TestClassArray().init(); TestClassArray targetObj = sendReceiveObject(sourceObj); @@ -103,7 +103,7 @@ public class JSONSerializerTest{ } @Test - public void testInputSerializerWithStringArrays() throws InterruptedException, IOException, ClassNotFoundException{ + public void testInputSerializerWithStringArrays() throws IOException { TestClassStringArray sourceObj = new TestClassStringArray().init(); TestClassStringArray targetObj = sendReceiveObject(sourceObj); @@ -111,7 +111,7 @@ public class JSONSerializerTest{ } @Test - public void testSerializerWithNullFieldsHidden() throws InterruptedException, IOException, ClassNotFoundException{ + public void testSerializerWithNullFieldsHidden() throws IOException { TestClass sourceObj = new TestClass(); String data = writeObjectToJson(sourceObj, false); @@ -125,7 +125,7 @@ public class JSONSerializerTest{ } @Test - public void testSerializerWithMapField() throws InterruptedException, IOException, ClassNotFoundException{ + public void testSerializerWithMapField() throws IOException { TestClassMap sourceObj = new TestClassMap().init(); TestClassMap targetObj = sendReceiveObject(sourceObj); @@ -133,7 +133,7 @@ public class JSONSerializerTest{ } @Test - public void testSerializerWithMapFieldWithNullEntry() throws InterruptedException, IOException, ClassNotFoundException{ + public void testSerializerWithMapFieldWithNullEntry() throws IOException { TestClassMap sourceObj = new TestClassMap().init(); sourceObj.map.put("key1", null); @@ -143,7 +143,7 @@ public class JSONSerializerTest{ } @Test - public void testSerializerWithListField() throws InterruptedException, IOException, ClassNotFoundException{ + public void testSerializerWithListField() throws IOException { TestClassList sourceObj = new TestClassList().init(); String data = writeObjectToJson(sourceObj); @@ -155,7 +155,7 @@ public class JSONSerializerTest{ } @Test - public void testSerializerWithMultipleObj() throws InterruptedException, IOException, ClassNotFoundException{ + public void testSerializerWithMultipleObj() throws IOException { TestClass sourceObj1 = new TestClass().init(); TestClass sourceObj2 = new TestClass().init(); @@ -175,13 +175,13 @@ public class JSONSerializerTest{ /******************* Utility Functions ************************************/ - public static <T> T sendReceiveObject(T sourceObj) throws IOException{ + static <T> T sendReceiveObject(T sourceObj) throws IOException{ return readObjectFromJson( writeObjectToJson(sourceObj)); } @SuppressWarnings("unchecked") - public static <T> T readObjectFromJson(String json) throws IOException{ + static <T> T readObjectFromJson(String json) throws IOException{ StringReader bin = new StringReader(json); JSONObjectInputStream in = new JSONObjectInputStream(bin); T targetObj = (T) in.readObject(); @@ -190,10 +190,10 @@ public class JSONSerializerTest{ return targetObj; } - public static <T> String writeObjectToJson(T sourceObj) throws IOException{ + static <T> String writeObjectToJson(T sourceObj) throws IOException{ return writeObjectToJson(sourceObj, true); } - public static <T> String writeObjectToJson(T sourceObj, boolean metadata) throws IOException{ + private static <T> String writeObjectToJson(T sourceObj, boolean metadata) throws IOException{ StringOutputStream bout = new StringOutputStream(); JSONObjectOutputStream out = new JSONObjectOutputStream(bout); out.enableMetaData(metadata); @@ -202,8 +202,7 @@ public class JSONSerializerTest{ out.flush(); out.close(); - String data = bout.toString(); - return data; + return bout.toString(); } /******************** Test Classes ************************************/ diff --git a/test/zutil/struct/BloomFilterTest.java b/test/zutil/struct/BloomFilterTest.java index db09cbf..f869846 100755 --- a/test/zutil/struct/BloomFilterTest.java +++ b/test/zutil/struct/BloomFilterTest.java @@ -32,7 +32,7 @@ import java.util.Random; /** - * This code may be used, modified, and redistributed provided that the + * This code may be used, modified, and redistributed provided that the * author tag below remains intact. * * @author Ian Clarke <ian@uprizer.com> @@ -41,13 +41,13 @@ import java.util.Random; public class BloomFilterTest extends TestCase { public void testBloomFilter() { DecimalFormat df = new DecimalFormat("0.00000"); - Random r = new Random(124445l); + Random r = new Random(124445L); int bfSize = 400000; System.out.println("Testing " + bfSize + " bit SimpleBloomFilter"); for (int i = 5; i < 10; i++) { int addCount = 10000 * (i + 1); - BloomFilter<Integer> bf = new BloomFilter<Integer>(bfSize, addCount); - HashSet<Integer> added = new HashSet<Integer>(); + BloomFilter<Integer> bf = new BloomFilter<>(bfSize, addCount); + HashSet<Integer> added = new HashSet<>(); for (int x = 0; x < addCount; x++) { int num = r.nextInt(); added.add(num); diff --git a/test/zutil/struct/CircularBufferTest.java b/test/zutil/struct/CircularBufferTest.java index 8f6718e..a977938 100755 --- a/test/zutil/struct/CircularBufferTest.java +++ b/test/zutil/struct/CircularBufferTest.java @@ -40,7 +40,7 @@ public class CircularBufferTest { @Test public void addToEmpty() { - CircularBuffer<Integer> buff = new CircularBuffer<Integer>(0); + CircularBuffer<Integer> buff = new CircularBuffer<>(0); try { buff.add(10); fail("IndexOutOfBoundsException was not thrown"); @@ -49,7 +49,7 @@ public class CircularBufferTest { @Test public void addOneElement() { - CircularBuffer<Integer> buff = new CircularBuffer<Integer>(1); + CircularBuffer<Integer> buff = new CircularBuffer<>(1); assertEquals(0, buff.size()); buff.add(10); assertEquals(1, buff.size()); @@ -58,7 +58,7 @@ public class CircularBufferTest { @Test public void addThreeElements() { - CircularBuffer<Integer> buff = new CircularBuffer<Integer>(10); + CircularBuffer<Integer> buff = new CircularBuffer<>(10); buff.add(10); buff.add(11); buff.add(12); @@ -70,7 +70,7 @@ public class CircularBufferTest { @Test public void addOutOfRange() { - CircularBuffer<Integer> buff = new CircularBuffer<Integer>(2); + CircularBuffer<Integer> buff = new CircularBuffer<>(2); buff.add(10); buff.add(11); buff.add(12); @@ -85,7 +85,7 @@ public class CircularBufferTest { @Test(expected = NoSuchElementException.class) public void iteratorEmpty() { - CircularBuffer<Integer> buff = new CircularBuffer<Integer>(10); + CircularBuffer<Integer> buff = new CircularBuffer<>(10); Iterator<Integer> it = buff.iterator(); assert (!it.hasNext()); @@ -94,7 +94,7 @@ public class CircularBufferTest { @Test(expected = NoSuchElementException.class) public void iteratorThreeElements() { - CircularBuffer<Integer> buff = new CircularBuffer<Integer>(10); + CircularBuffer<Integer> buff = new CircularBuffer<>(10); buff.add(10); buff.add(11); buff.add(12); diff --git a/test/zutil/struct/ObjectCacheTest.java b/test/zutil/struct/ObjectCacheTest.java index 92570be..d43f041 100755 --- a/test/zutil/struct/ObjectCacheTest.java +++ b/test/zutil/struct/ObjectCacheTest.java @@ -42,7 +42,7 @@ public class ObjectCacheTest { @Test - public void emptyCache() throws InterruptedException { + public void emptyCache() { ObjectCache cache = new ObjectCache(10); assertFalse(cache.containsKey(KEY)); assertEquals(0, cache.size()); @@ -78,6 +78,7 @@ public class ObjectCacheTest { //@Test // This TC does not work + @SuppressWarnings("RedundantStringConstructorCall") public void javaGRC() throws InterruptedException { ObjectCache cache = new ObjectCache(10000); {