From b1c53d88ae4d6b9424c85c60df17019d48e334fc Mon Sep 17 00:00:00 2001 From: Ziver Koc Date: Sat, 26 May 2018 23:01:03 +0200 Subject: [PATCH] Changed tas to spaces --- Zutil.iml | 10 - src/zutil/Encrypter.java | 350 +++--- src/zutil/Hasher.java | 418 +++---- src/zutil/OneInstance.java | 24 +- src/zutil/OneInstanceFile.java | 142 +-- src/zutil/OneInstanceNetwork.java | 114 +- src/zutil/ProgressListener.java | 18 +- src/zutil/algo/EuclideansAlgo.java | 192 +-- src/zutil/algo/ShanksTonelliAlgo.java | 130 +- src/zutil/algo/WienersAlgo.java | 104 +- src/zutil/algo/path/BreadthFirstSearch.java | 68 +- src/zutil/algo/path/DepthFirstSearch.java | 68 +- src/zutil/algo/path/DynamicProgramming.java | 210 ++-- src/zutil/algo/path/PathFinder.java | 18 +- src/zutil/algo/path/PathNode.java | 56 +- src/zutil/algo/path/StandardPathNode.java | 44 +- src/zutil/algo/search/QuickSelect.java | 106 +- src/zutil/algo/sort/ExternalSort.java | 412 +++---- src/zutil/algo/sort/MergeSort.java | 230 ++-- src/zutil/algo/sort/QuickSort.java | 122 +- src/zutil/algo/sort/Randomizer.java | 24 +- .../algo/sort/sortable/SortableArrayList.java | 63 +- .../sortable/SortableComparableArray.java | 75 +- .../algo/sort/sortable/SortableIntArray.java | 78 +- .../sort/sortable/SortableLinkedList.java | 66 +- src/zutil/converter/Converter.java | 706 +++++------ .../converter/NumberToWordsConverter.java | 168 +-- src/zutil/converter/WGS84Converter.java | 86 +- src/zutil/db/DBConnectionPool.java | 284 ++--- src/zutil/db/DBQueue.java | 290 ++--- src/zutil/db/SQLQuery.java | 772 ++++++------ src/zutil/db/SQLResultHandler.java | 14 +- src/zutil/db/bean/DBBeanConfig.java | 2 +- src/zutil/db/bean/DBBeanSQLResultHandler.java | 252 ++-- src/zutil/db/handler/ListSQLResult.java | 40 +- src/zutil/db/handler/PropertiesSQLResult.java | 52 +- src/zutil/db/handler/SimpleSQLResult.java | 24 +- src/zutil/image/ImageFilterProcessor.java | 290 ++--- src/zutil/image/ImageUtil.java | 136 +-- src/zutil/image/filter/BlurFilter.java | 156 +-- .../image/filter/ColorIntensityFilter.java | 144 +-- .../filter/ContrastBrightnessFilter.java | 66 +- src/zutil/image/filter/ConvolutionFilter.java | 128 +- src/zutil/image/filter/DitheringFilter.java | 114 +- .../image/filter/GaussianBlurFilter.java | 66 +- src/zutil/image/filter/MeanBlurFilter.java | 64 +- src/zutil/image/filter/MedianFilter.java | 240 ++-- src/zutil/image/filter/ResizeImage.java | 108 +- .../filter/SobelEdgeDetectionFilter.java | 94 +- src/zutil/image/filter/SpotLightFilter.java | 124 +- src/zutil/io/BufferedBoundaryInputStream.java | 229 ++-- src/zutil/io/BufferedRandomAccessFile.java | 418 +++---- src/zutil/io/DynamicByteArrayStream.java | 240 ++-- src/zutil/io/IOUtil.java | 26 +- src/zutil/io/InputStreamCloser.java | 42 +- src/zutil/io/MultiPrintStream.java | 554 ++++----- src/zutil/io/StringInputStream.java | 126 +- src/zutil/io/file/FileChangeListener.java | 14 +- src/zutil/io/file/FileSearcher.java | 336 ++--- src/zutil/io/file/FileWatcher.java | 96 +- src/zutil/jee/upload/FileUploadListener.java | 234 ++-- src/zutil/log/CompactLogFormatter.java | 234 ++-- src/zutil/log/LogUtil.java | 154 +-- src/zutil/log/net/NetLogClient.java | 88 +- src/zutil/log/net/NetLogExceptionMessage.java | 132 +- src/zutil/log/net/NetLogGuiClient.java | 74 +- .../log/net/NetLogGuiClientInstance.java | 264 ++-- src/zutil/log/net/NetLogListener.java | 28 +- src/zutil/log/net/NetLogMessage.java | 120 +- src/zutil/log/net/NetLogServer.java | 222 ++-- src/zutil/log/net/NetLogStatusMessage.java | 8 +- src/zutil/math/Tick.java | 188 +-- src/zutil/net/FTPClient.java | 490 ++++---- src/zutil/net/POP3Client.java | 552 ++++----- src/zutil/net/ServerFind.java | 96 +- src/zutil/net/ServerFindClient.java | 62 +- src/zutil/net/http/HttpClient.java | 132 +- src/zutil/net/http/HttpHeader.java | 222 ++-- src/zutil/net/http/HttpHeaderParser.java | 176 +-- src/zutil/net/http/HttpPage.java | 28 +- src/zutil/net/http/HttpPrintStream.java | 522 ++++---- src/zutil/net/http/HttpServer.java | 238 ++-- src/zutil/net/http/HttpURL.java | 246 ++-- .../net/http/multipart/MultipartField.java | 18 +- .../http/multipart/MultipartFileField.java | 56 +- .../net/http/multipart/MultipartParser.java | 32 +- src/zutil/net/nio/NioClient.java | 70 +- src/zutil/net/nio/NioNetwork.java | 302 ++--- src/zutil/net/nio/NioServer.java | 92 +- src/zutil/net/nio/message/EchoMessage.java | 32 +- .../nio/response/PrintResponseHandler.java | 8 +- .../nio/response/RequestResponseMessage.java | 10 +- .../net/nio/response/ResponseHandler.java | 44 +- .../nio/response/StringResponseMessage.java | 28 +- src/zutil/net/nio/server/ChangeRequest.java | 22 +- src/zutil/net/nio/server/ClientData.java | 40 +- src/zutil/net/nio/worker/StandardWorker.java | 84 +- .../net/nio/worker/ThreadedEventWorker.java | 32 +- src/zutil/net/nio/worker/Worker.java | 58 +- src/zutil/net/nio/worker/WorkerEventData.java | 16 +- .../net/nio/worker/chat/ChatListener.java | 2 +- .../net/nio/worker/chat/ChatService.java | 164 +-- src/zutil/net/nio/worker/grid/GridClient.java | 160 +-- src/zutil/net/nio/worker/grid/GridJob.java | 22 +- .../net/nio/worker/grid/GridJobGenerator.java | 16 +- .../net/nio/worker/grid/GridMessage.java | 154 +-- .../nio/worker/grid/GridResultHandler.java | 4 +- .../net/nio/worker/grid/GridServerWorker.java | 168 +-- src/zutil/net/nio/worker/grid/GridThread.java | 52 +- .../nio/worker/sync/GraphicsSyncMessage.java | 52 +- src/zutil/net/nio/worker/sync/ObjectSync.java | 40 +- .../net/nio/worker/sync/SyncMessage.java | 24 +- .../net/nio/worker/sync/SyncService.java | 68 +- src/zutil/net/smtp/Email.java | 150 +-- src/zutil/net/smtp/SmtpClient.java | 108 +- src/zutil/net/ssdp/SSDPClient.java | 280 ++--- src/zutil/net/ssdp/SSDPServer.java | 464 +++---- src/zutil/net/ssdp/SSDPServiceInfo.java | 48 +- src/zutil/net/ssdp/StandardSSDPInfo.java | 204 ++-- .../threaded/ThreadedTCPNetworkServer.java | 188 +-- .../net/threaded/ThreadedUDPNetwork.java | 186 +-- .../threaded/ThreadedUDPNetworkThread.java | 16 +- src/zutil/net/torrent/TorrentFile.java | 28 +- src/zutil/net/torrent/TorrentMetainfo.java | 250 ++-- src/zutil/net/torrent/TorrentTracker.java | 20 +- src/zutil/net/update/FileInfo.java | 66 +- src/zutil/net/update/FileListMessage.java | 112 +- src/zutil/net/update/UpdateClient.java | 226 ++-- src/zutil/net/update/UpdateConfigMessage.java | 8 +- src/zutil/net/update/UpdateServer.java | 148 +-- src/zutil/net/update/Zupdater.java | 208 ++-- src/zutil/net/upnp/UPnPMediaServer.java | 136 +-- src/zutil/net/upnp/service/BrowseRetObj.java | 18 +- .../upnp/service/UPnPContentDirectory.java | 1084 ++++++++--------- src/zutil/net/ws/WSMethodDef.java | 428 +++---- src/zutil/net/ws/WSParameterDef.java | 100 +- src/zutil/net/ws/WSReturnObject.java | 56 +- src/zutil/net/ws/WebServiceDef.java | 160 +-- .../ws/soap/SOAPClientInvocationHandler.java | 52 +- src/zutil/net/ws/soap/SOAPException.java | 10 +- src/zutil/net/ws/soap/SOAPHttpPage.java | 508 ++++---- src/zutil/parser/BBCodeParser.java | 302 ++--- src/zutil/parser/BEncodedParser.java | 172 +-- src/zutil/parser/Base64Decoder.java | 302 ++--- src/zutil/parser/Base64Encoder.java | 202 +-- src/zutil/parser/DataNode.java | 582 ++++----- src/zutil/parser/MathParser.java | 362 +++--- .../parser/json/JSONObjectOutputStream.java | 34 +- src/zutil/parser/json/JSONParser.java | 28 +- src/zutil/parser/wsdl/WSDLWriter.java | 546 ++++----- src/zutil/plugin/PluginData.java | 238 ++-- src/zutil/plugin/PluginManager.java | 240 ++-- src/zutil/plugin/plugin.json.example | 12 +- src/zutil/struct/HistoryList.java | 194 +-- src/zutil/struct/MutableInt.java | 14 +- src/zutil/ui/Console.java | 466 +++---- src/zutil/ui/JImagePanel.java | 128 +- src/zutil/ui/wizard/Wizard.java | 346 +++--- src/zutil/ui/wizard/WizardListener.java | 28 +- src/zutil/ui/wizard/WizardPage.java | 208 ++-- .../listener/BlockingWizardListener.java | 52 +- src/zutil/ui/wizard/page/SummaryPage.java | 54 +- .../wrapper/SerializableBufferedImage.java | 38 +- test/zutil/EncrypterTest.java | 22 +- test/zutil/HasherTest.java | 36 +- test/zutil/StringUtilTest.java | 80 +- test/zutil/algo/search/QuickSelectTest.java | 34 +- test/zutil/algo/sort/ExternalSortTest.java | 20 +- test/zutil/algo/sort/MergeSortTest.java | 74 +- test/zutil/converter/ConverterTest.java | 104 +- .../converter/NumberToWordsConverterTest.java | 100 +- test/zutil/db/DBConnectionTest.java | 54 +- test/zutil/db/SQLQueryTest.java | 170 +-- test/zutil/image/ImageProcessorTest.java | 152 +-- .../io/BufferedBoundaryInputStreamTest.java | 128 +- test/zutil/io/DynamicByteArrayStreamTest.java | 2 +- test/zutil/io/file/FileChangedTest.java | 32 +- test/zutil/jee/upload/upload_test.html | 86 +- test/zutil/log/net/NetLogServerTest.java | 36 +- test/zutil/net/ServerFindClientTest.java | 16 +- test/zutil/net/ServerFindServerTest.java | 14 +- test/zutil/net/http/HttpURLTest.java | 68 +- .../net/http/page/HttpGuessTheNumber.java | 78 +- test/zutil/net/nio/NetworkClientTest.java | 46 +- test/zutil/net/nio/NetworkServerTest.java | 24 +- test/zutil/net/update/UpdateClientTest.java | 72 +- test/zutil/net/update/UpdateServerTest.java | 20 +- test/zutil/net/upnp/UPnPServerTest.java | 48 +- test/zutil/net/ws/soap/SOAPClientTest.java | 30 +- test/zutil/net/ws/soap/SOAPTest.java | 188 +-- test/zutil/parser/BBCodeParserTest.java | 28 +- test/zutil/parser/Base64Test.java | 52 +- test/zutil/parser/json/JSONParserTest.java | 64 +- .../zutil/parser/json/JSONSerializerTest.java | 226 ++-- test/zutil/struct/BloomFilterTest.java | 84 +- test/zutil/ui/ConsoleTest.java | 30 +- 196 files changed, 14016 insertions(+), 14035 deletions(-) diff --git a/Zutil.iml b/Zutil.iml index 5454eb9..a2bde11 100755 --- a/Zutil.iml +++ b/Zutil.iml @@ -45,15 +45,5 @@ - - - - - - - - - - \ No newline at end of file diff --git a/src/zutil/Encrypter.java b/src/zutil/Encrypter.java index aa02e94..3ddce27 100644 --- a/src/zutil/Encrypter.java +++ b/src/zutil/Encrypter.java @@ -40,203 +40,203 @@ import java.util.Random; * Basic symmetric encryption example */ public class Encrypter { - // Choices are available at: http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html - public enum Algorithm { - /** Advanced Encryption Standard as specified by NIST in FIPS 197. Also known as the Rijndael algorithm by Joan Daemen and Vincent Rijmen, AES is a 128-bit block cipher supporting keys of 128, 192, and 256 bits. **/ - AES, - /** The AES key wrapping algorithm as described in RFC 3394. **/ - AESWrap, - /** A stream cipher believed to be fully interoperable with the RC4 cipher developed by Ron Rivest. For more information, see K. Kaukonen and R. Thayer, "A Stream Cipher Encryption Algorithm 'Arcfour'", Internet Draft (expired), draft-kaukonen-cipher-arcfour-03.txt. **/ - ARCFOUR, - /** The Blowfish block cipher designed by Bruce Schneier. **/ - Blowfish, - /** Counter/CBC Mode, as defined in NIST Special Publication SP 800-38C. **/ - CCM, - /** The Digital Encryption Standard as described in FIPS PUB 46-3. **/ - DES, - /** Triple DES Encryption (also known as DES-EDE, 3DES, or Triple-DES). Data is encrypted using the DES algorithm three separate times. It is first encrypted using the first subkey, then decrypted with the second subkey, and encrypted with the third subkey. **/ - DESede, - /** The DESede key wrapping algorithm as described in RFC 3217 . **/ - DESedeWrap, - /** Elliptic Curve Integrated Encryption Scheme **/ - ECIES, - /** Galois/Counter Mode, as defined in NIST Special Publication SP 800-38D. **/ - GCM, - /** Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. **/ - RC2, - /** Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. (See note prior for ARCFOUR.) **/ - RC4, - /** Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. **/ - RC5, - /** The RSA encryption algorithm as defined in PKCS #1 **/ - RSA - } - public enum Digest { - MD2, - MD5, - SHA1, - SHA256, - SHA384, - SHA512, - HmacMD5, - HmacSHA1, - HmacSHA256, - HmacSHA384, - HmacSHA512 - } + // Choices are available at: http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html + public enum Algorithm { + /** Advanced Encryption Standard as specified by NIST in FIPS 197. Also known as the Rijndael algorithm by Joan Daemen and Vincent Rijmen, AES is a 128-bit block cipher supporting keys of 128, 192, and 256 bits. **/ + AES, + /** The AES key wrapping algorithm as described in RFC 3394. **/ + AESWrap, + /** A stream cipher believed to be fully interoperable with the RC4 cipher developed by Ron Rivest. For more information, see K. Kaukonen and R. Thayer, "A Stream Cipher Encryption Algorithm 'Arcfour'", Internet Draft (expired), draft-kaukonen-cipher-arcfour-03.txt. **/ + ARCFOUR, + /** The Blowfish block cipher designed by Bruce Schneier. **/ + Blowfish, + /** Counter/CBC Mode, as defined in NIST Special Publication SP 800-38C. **/ + CCM, + /** The Digital Encryption Standard as described in FIPS PUB 46-3. **/ + DES, + /** Triple DES Encryption (also known as DES-EDE, 3DES, or Triple-DES). Data is encrypted using the DES algorithm three separate times. It is first encrypted using the first subkey, then decrypted with the second subkey, and encrypted with the third subkey. **/ + DESede, + /** The DESede key wrapping algorithm as described in RFC 3217 . **/ + DESedeWrap, + /** Elliptic Curve Integrated Encryption Scheme **/ + ECIES, + /** Galois/Counter Mode, as defined in NIST Special Publication SP 800-38D. **/ + GCM, + /** Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. **/ + RC2, + /** Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. (See note prior for ARCFOUR.) **/ + RC4, + /** Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. **/ + RC5, + /** The RSA encryption algorithm as defined in PKCS #1 **/ + RSA + } + public enum Digest { + MD2, + MD5, + SHA1, + SHA256, + SHA384, + SHA512, + HmacMD5, + HmacSHA1, + HmacSHA256, + HmacSHA384, + HmacSHA512 + } - // 8-byte Salt - public static byte[] salt = { - (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32, - (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03 - }; + // 8-byte Salt + public static byte[] salt = { + (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32, + (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03 + }; - private Cipher encipher; - private Cipher decipher; - private Key key; - private AlgorithmParameterSpec paramSpec; + private Cipher encipher; + private Cipher decipher; + private Key key; + private AlgorithmParameterSpec paramSpec; - /** - * Generates a random key - * @param crypto is algorithm to encrypt/decrypt with - */ - public Encrypter(Algorithm crypto) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException{ - KeyGenerator keygenerator = KeyGenerator.getInstance(crypto.toString()); + /** + * Generates a random key + * @param crypto is algorithm to encrypt/decrypt with + */ + public Encrypter(Algorithm crypto) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException{ + KeyGenerator keygenerator = KeyGenerator.getInstance(crypto.toString()); - key = keygenerator.generateKey(); - encipher = Cipher.getInstance(key.getAlgorithm()); - decipher = Cipher.getInstance(key.getAlgorithm()); - encipher.init(Cipher.ENCRYPT_MODE, key); - decipher.init(Cipher.DECRYPT_MODE, key); - } + key = keygenerator.generateKey(); + encipher = Cipher.getInstance(key.getAlgorithm()); + decipher = Cipher.getInstance(key.getAlgorithm()); + encipher.init(Cipher.ENCRYPT_MODE, key); + decipher.init(Cipher.DECRYPT_MODE, key); + } - /** - * Uses the given key for encryption - * @param key is an existing key to use for encrypting/decrypting - */ - public Encrypter(Key key) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException{ - this.key = key; - encipher = Cipher.getInstance(key.getAlgorithm()); - decipher = Cipher.getInstance(key.getAlgorithm()); - encipher.init(Cipher.ENCRYPT_MODE, key); - decipher.init(Cipher.DECRYPT_MODE, key); - } + /** + * Uses the given key for encryption + * @param key is an existing key to use for encrypting/decrypting + */ + public Encrypter(Key key) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException{ + this.key = key; + encipher = Cipher.getInstance(key.getAlgorithm()); + decipher = Cipher.getInstance(key.getAlgorithm()); + encipher.init(Cipher.ENCRYPT_MODE, key); + decipher.init(Cipher.DECRYPT_MODE, key); + } - /** - * Creates a encrypter with a passphrase. - * - * @param stringKey is a passphrase to use as key - * @param crypto is algorithm to encrypt/decrypt with - */ - public Encrypter(String stringKey, Algorithm crypto) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException { - this(stringKey, Digest.HmacSHA1, crypto, 500, - (crypto==Algorithm.DES ? 64 : 128)); - } + /** + * Creates a encrypter with a passphrase. + * + * @param stringKey is a passphrase to use as key + * @param crypto is algorithm to encrypt/decrypt with + */ + public Encrypter(String stringKey, Algorithm crypto) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException { + this(stringKey, Digest.HmacSHA1, crypto, 500, + (crypto==Algorithm.DES ? 64 : 128)); + } - public Encrypter(String stringKey, Digest digest, Algorithm crypto, int iteration, int keyBitSize) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException { - // Install SunJCE provider - Provider sunJce = new com.sun.crypto.provider.SunJCE(); - Security.addProvider(sunJce); + public Encrypter(String stringKey, Digest digest, Algorithm crypto, int iteration, int keyBitSize) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException { + // Install SunJCE provider + Provider sunJce = new com.sun.crypto.provider.SunJCE(); + Security.addProvider(sunJce); - // Generate the secret key specs. - //String instance = "PBEWith"+ digest +"And"+ crypto; - String instance = "PBKDF2With"+ digest; - SecretKeyFactory factory = SecretKeyFactory.getInstance(instance); - KeySpec keySpec = new PBEKeySpec(stringKey.toCharArray(), salt, iteration, keyBitSize); - SecretKey tmp = factory.generateSecret(keySpec); - key = new SecretKeySpec(tmp.getEncoded(), crypto.toString()); - //key = new SecretKeySpec(stringKey.getBytes(), crypto.toString()); + // Generate the secret key specs. + //String instance = "PBEWith"+ digest +"And"+ crypto; + String instance = "PBKDF2With"+ digest; + SecretKeyFactory factory = SecretKeyFactory.getInstance(instance); + KeySpec keySpec = new PBEKeySpec(stringKey.toCharArray(), salt, iteration, keyBitSize); + SecretKey tmp = factory.generateSecret(keySpec); + key = new SecretKeySpec(tmp.getEncoded(), crypto.toString()); + //key = new SecretKeySpec(stringKey.getBytes(), crypto.toString()); - encipher = Cipher.getInstance(key.getAlgorithm()); - decipher = Cipher.getInstance(key.getAlgorithm()); - encipher.init(Cipher.ENCRYPT_MODE, key); - decipher.init(Cipher.DECRYPT_MODE, key); - } + encipher = Cipher.getInstance(key.getAlgorithm()); + decipher = Cipher.getInstance(key.getAlgorithm()); + encipher.init(Cipher.ENCRYPT_MODE, key); + decipher.init(Cipher.DECRYPT_MODE, key); + } - /** - * Encrypts the given data - * - * @param data is the data to encrypt - * @return The encrypted data - */ - public byte[] encrypt(byte[] data){ - try { - byte[] encryption = new byte[encipher.getOutputSize(data.length)]; - int ctLength = encipher.update(data, 0, data.length, encryption, 0); + /** + * Encrypts the given data + * + * @param data is the data to encrypt + * @return The encrypted data + */ + public byte[] encrypt(byte[] data){ + try { + byte[] encryption = new byte[encipher.getOutputSize(data.length)]; + int ctLength = encipher.update(data, 0, data.length, encryption, 0); - ctLength += encipher.doFinal(encryption, ctLength); - return encryption; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } + ctLength += encipher.doFinal(encryption, ctLength); + return encryption; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } - /** - * Adds encryption to the OutputStream - * @param out is the OutputStream to enable encryption on - * @return A new encrypted OutputStream - */ - public OutputStream encrypt(OutputStream out) { - // Bytes written to out will be encrypted - return new CipherOutputStream(out, encipher); + /** + * Adds encryption to the OutputStream + * @param out is the OutputStream to enable encryption on + * @return A new encrypted OutputStream + */ + public OutputStream encrypt(OutputStream out) { + // Bytes written to out will be encrypted + return new CipherOutputStream(out, encipher); - } + } - /** - * Decrypts encrypted data - * @param encrypted is the encrypted data - * @return The decrypted data - */ - public byte[] decrypt(byte[] encrypted){ - try { - byte[] dataTmp = new byte[encrypted.length]; - int ptLength = decipher.update(encrypted, 0, encrypted.length, dataTmp, 0); - ptLength += decipher.doFinal(dataTmp, ptLength); + /** + * Decrypts encrypted data + * @param encrypted is the encrypted data + * @return The decrypted data + */ + public byte[] decrypt(byte[] encrypted){ + try { + byte[] dataTmp = new byte[encrypted.length]; + int ptLength = decipher.update(encrypted, 0, encrypted.length, dataTmp, 0); + ptLength += decipher.doFinal(dataTmp, ptLength); - byte[] data = new byte[ptLength]; - System.arraycopy(dataTmp, 0, data, 0, ptLength); - return data; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } + byte[] data = new byte[ptLength]; + System.arraycopy(dataTmp, 0, data, 0, ptLength); + return data; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } - /** - * Adds decryption to the InputStream - * @param in is the InputStream to enable decryption on - * @return A new decrypted InputStream - */ - public InputStream decrypt(InputStream in) { - // Bytes read from in will be decrypted - return new CipherInputStream(in, decipher); + /** + * Adds decryption to the InputStream + * @param in is the InputStream to enable decryption on + * @return A new decrypted InputStream + */ + public InputStream decrypt(InputStream in) { + // Bytes read from in will be decrypted + return new CipherInputStream(in, decipher); - } + } - /** - * @return The key for this encrypter - */ - public Key getKey(){ - return key; - } + /** + * @return The key for this encrypter + */ + public Key getKey(){ + return key; + } - /** - * @return the algorithm used by this encrypter - */ - public String getAlgorithm(){ - return key.getAlgorithm(); - } + /** + * @return the algorithm used by this encrypter + */ + public String getAlgorithm(){ + return key.getAlgorithm(); + } - /** - * Randomizes the salt for the key - */ - public static void randomizeSalt(){ - Random random = new Random(); - random.nextBytes(salt); - } + /** + * Randomizes the salt for the key + */ + public static void randomizeSalt(){ + Random random = new Random(); + random.nextBytes(salt); + } } diff --git a/src/zutil/Hasher.java b/src/zutil/Hasher.java index bcf465a..58f577a 100755 --- a/src/zutil/Hasher.java +++ b/src/zutil/Hasher.java @@ -37,133 +37,133 @@ import java.security.NoSuchAlgorithmException; public class Hasher { - /** - * Returns a hash of a file - * - * @param file is the path to the file - * @param hashType is the hash type - * @return a String with the hash - */ - public static String hash(File file, String hashType) throws NoSuchAlgorithmException, IOException { - MessageDigest digest = MessageDigest.getInstance(hashType); //"MD5" - InputStream is = new FileInputStream(file); - String output = ""; - byte[] buffer = new byte[8192]; - int read = 0; - try { - while( (read = is.read(buffer)) > 0) { - digest.update(buffer, 0, read); - } - byte[] md5sum = digest.digest(); - BigInteger bigInt = new BigInteger(1, md5sum); - output = bigInt.toString(16); - } - catch(IOException e) { - throw new RuntimeException("Unable to process file for "+hashType+" hash", e); - } - is.close(); + /** + * Returns a hash of a file + * + * @param file is the path to the file + * @param hashType is the hash type + * @return a String with the hash + */ + public static String hash(File file, String hashType) throws NoSuchAlgorithmException, IOException { + MessageDigest digest = MessageDigest.getInstance(hashType); //"MD5" + InputStream is = new FileInputStream(file); + String output = ""; + byte[] buffer = new byte[8192]; + int read = 0; + try { + while( (read = is.read(buffer)) > 0) { + digest.update(buffer, 0, read); + } + byte[] md5sum = digest.digest(); + BigInteger bigInt = new BigInteger(1, md5sum); + output = bigInt.toString(16); + } + catch(IOException e) { + throw new RuntimeException("Unable to process file for "+hashType+" hash", e); + } + is.close(); - return output; - } + return output; + } - /** - * Returns the MD5 hash of the given object - * - * @param str is the String to hash - * @return an String containing the hash - */ - public static String MD5(String str){ - try { - return hash(str, "MD5"); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } + /** + * Returns the MD5 hash of the given object + * + * @param str is the String to hash + * @return an String containing the hash + */ + public static String MD5(String str){ + try { + return hash(str, "MD5"); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } - /** - * Returns the MD5 hash of the given object - * - * @param object is the object to hash - * @return an String containing the hash - */ - public static String MD5(Serializable object){ - try { - return hash(object, "MD5"); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * Returns the MD5 hash of the given file - * - * @param file is the file to hash - * @return an String containing the hash - */ - public static String MD5(File file) throws IOException{ - try { - return hash(file, "MD5"); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } - return null; - } - + /** + * Returns the MD5 hash of the given object + * + * @param object is the object to hash + * @return an String containing the hash + */ + public static String MD5(Serializable object){ + try { + return hash(object, "MD5"); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } - /** - * Returns the SHA-1 hash of the given object - * - * @param str is the String to hash - * @return an String containing the hash - */ - public static String SHA1(String str){ - try { - return hash(str, "SHA-1"); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * Returns the SHA-1 hash of the given object - * - * @param object is the object to hash - * @return an String containing the hash - */ - public static String SHA1(Serializable object){ - try { - return hash(object, "SHA-1"); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * Returns the SHA-256 hash with a key for the given String - * - * @param str is the String to hash - * @param key is the key to use with the hash - * @return an String containing the hash - */ - public static String HMAC_SHA256(String str, String key){ - return HMAC("HmacSHA256", str.getBytes(), key.getBytes()); - } - - /** - * Returns a HMAC hash with a key for the given String - * - * @param algo specifies the algorithm to be used - * @param data is the String to hash - * @param key is the key to use with the hash - * @return an String containing the hash - */ - public static String HMAC(String algo, byte[] data, byte[] key){ - try { - // Get an hmac_sha1 key from the raw key bytes + /** + * Returns the MD5 hash of the given file + * + * @param file is the file to hash + * @return an String containing the hash + */ + public static String MD5(File file) throws IOException{ + try { + return hash(file, "MD5"); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return null; + } + + + /** + * Returns the SHA-1 hash of the given object + * + * @param str is the String to hash + * @return an String containing the hash + */ + public static String SHA1(String str){ + try { + return hash(str, "SHA-1"); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * Returns the SHA-1 hash of the given object + * + * @param object is the object to hash + * @return an String containing the hash + */ + public static String SHA1(Serializable object){ + try { + return hash(object, "SHA-1"); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * Returns the SHA-256 hash with a key for the given String + * + * @param str is the String to hash + * @param key is the key to use with the hash + * @return an String containing the hash + */ + public static String HMAC_SHA256(String str, String key){ + return HMAC("HmacSHA256", str.getBytes(), key.getBytes()); + } + + /** + * Returns a HMAC hash with a key for the given String + * + * @param algo specifies the algorithm to be used + * @param data is the String to hash + * @param key is the key to use with the hash + * @return an String containing the hash + */ + public static String HMAC(String algo, byte[] data, byte[] key){ + 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 @@ -174,11 +174,11 @@ public class Hasher { byte[] raw = mac.doFinal( data ); return Converter.toHexString(raw); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } public static String PBKDF2(String data, String salt, int iterations){ try { @@ -196,97 +196,97 @@ public class Hasher { } return null; } - - /** - * Hashes the given String as UTF8 - * - * @param object is the String - * @param hashType is the hash algorithm (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512 ) - * @return a hex String of the hash - */ - public static String hash(String object, String hashType) throws Exception { - return hash(object.getBytes(), hashType);//(new BASE64Encoder()).encode(raw); - } - - /** - * Returns the hash of the given object - * - * @param object is the object to hash - * @param hashType is the hash method (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512 ) - * @return an String containing the hash - */ - public static String hash(Serializable object, String hashType) throws Exception { - return hash(Converter.toBytes(object), hashType);//(new BASE64Encoder()).encode(raw); - } - /** - * Hashes a given byte array - * - * @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; - md = MessageDigest.getInstance(hashType); //MD5 || SHA - md.update(data); + /** + * Hashes the given String as UTF8 + * + * @param object is the String + * @param hashType is the hash algorithm (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512 ) + * @return a hex String of the hash + */ + public static String hash(String object, String hashType) throws Exception { + return hash(object.getBytes(), hashType);//(new BASE64Encoder()).encode(raw); + } - byte raw[] = md.digest(); - return Converter.toHexString(raw);//(new BASE64Encoder()).encode(raw); - } + /** + * Returns the hash of the given object + * + * @param object is the object to hash + * @param hashType is the hash method (MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512 ) + * @return an String containing the hash + */ + public static String hash(Serializable object, String hashType) throws Exception { + return hash(Converter.toBytes(object), hashType);//(new BASE64Encoder()).encode(raw); + } - /** - * MurmurHash2 ported from c++ source - * - * @param object is the Key - * @param seed is the seed - * @return A MurmurHash of the key - */ - public static int MurmurHash(Serializable object, int seed) throws Exception{ - byte[] data = Converter.toBytes(object); - int length = data.length; + /** + * Hashes a given byte array + * + * @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; + md = MessageDigest.getInstance(hashType); //MD5 || SHA + md.update(data); - //Constants - int m = 0x5bd1e995; - int r = 24; + byte raw[] = md.digest(); + return Converter.toHexString(raw);//(new BASE64Encoder()).encode(raw); + } - // Initialize the hash to a 'random' value - int h = seed ^ length; + /** + * MurmurHash2 ported from c++ source + * + * @param object is the Key + * @param seed is the seed + * @return A MurmurHash of the key + */ + public static int MurmurHash(Serializable object, int seed) throws Exception{ + byte[] data = Converter.toBytes(object); + int length = data.length; - int i=0; - for(; i+4>> r; - k *= m; + // Initialize the hash to a 'random' value + int h = seed ^ length; - h *= m; - h ^= k; - } + int i=0; + for(; i+4>> r; + k *= m; - switch(i){ - case 3: h ^= data[length-3] << 16; - case 2: h ^= data[length-2] << 8; - case 1: h ^= data[length-1]; - h *= m; - } + h *= m; + h ^= k; + } - h ^= h >>> 13; - h *= m; - h ^= h >>> 15; + // Handle the last few bytes of the input + i = length % 4; - return h; - } + switch(i){ + case 3: h ^= data[length-3] << 16; + case 2: h ^= data[length-2] << 8; + case 1: h ^= data[length-1]; + h *= m; + } + + h ^= h >>> 13; + h *= m; + h ^= h >>> 15; + + return h; + } } diff --git a/src/zutil/OneInstance.java b/src/zutil/OneInstance.java index c848208..7b87bcc 100644 --- a/src/zutil/OneInstance.java +++ b/src/zutil/OneInstance.java @@ -32,17 +32,17 @@ package zutil; * */ public interface OneInstance { - /** - * Checks if the application is already running - * - * @return True if the file is locked else false - */ - public boolean check(); + /** + * Checks if the application is already running + * + * @return True if the file is locked else false + */ + public boolean check(); - /** - * Locks the application so that another one can not run - * - * @return False if there are a error else true - */ - public boolean lockApp(); + /** + * Locks the application so that another one can not run + * + * @return False if there are a error else true + */ + public boolean lockApp(); } diff --git a/src/zutil/OneInstanceFile.java b/src/zutil/OneInstanceFile.java index 446881a..7404d27 100644 --- a/src/zutil/OneInstanceFile.java +++ b/src/zutil/OneInstanceFile.java @@ -37,85 +37,85 @@ import java.nio.channels.OverlappingFileLockException; * @author Ziver Koc */ public class OneInstanceFile implements OneInstance{ - private File file; - private FileChannel channel; - private FileLock lock; + private File file; + private FileChannel channel; + private FileLock lock; - /** - * Creates a OneApp class - * - * @param filename The name of the file to be locked - */ - public OneInstanceFile(String filename){ - this.file = new File(System.getProperty("user.home"), filename); - } + /** + * Creates a OneApp class + * + * @param filename The name of the file to be locked + */ + public OneInstanceFile(String filename){ + this.file = new File(System.getProperty("user.home"), filename); + } - /** - * Checks if the file have already bean locked - * - * @return True if the file is locked else false - */ - public boolean check() { - boolean tmp = lockApp(); - if( tmp ) closeLock(); - return !tmp; - } + /** + * Checks if the file have already bean locked + * + * @return True if the file is locked else false + */ + public boolean check() { + boolean tmp = lockApp(); + if( tmp ) closeLock(); + return !tmp; + } - /** - * Locks the file - * - * @return False if there are a error else true - */ - public boolean lockApp() { - try { - channel = new RandomAccessFile(file, "rw").getChannel(); + /** + * Locks the file + * + * @return False if there are a error else true + */ + public boolean lockApp() { + try { + channel = new RandomAccessFile(file, "rw").getChannel(); - try { - lock = channel.tryLock(); - } - catch (OverlappingFileLockException e) { - // already locked by this application - return false; - } + try { + lock = channel.tryLock(); + } + catch (OverlappingFileLockException e) { + // already locked by this application + return false; + } - if (lock == null || lock.isShared()) { - // already locked by another application - return false; - } + if (lock == null || lock.isShared()) { + // already locked by another application + return false; + } - Runtime.getRuntime().addShutdownHook(new Thread() { - // destroy the lock when the JVM is closing - public void run() { - closeLock(); - deleteFile(); - } - }); - return true; - } - catch (Exception e) { - closeLock(); - return false; - } - } + Runtime.getRuntime().addShutdownHook(new Thread() { + // destroy the lock when the JVM is closing + public void run() { + closeLock(); + deleteFile(); + } + }); + return true; + } + catch (Exception e) { + closeLock(); + return false; + } + } - private void closeLock() { - try { - lock.release(); - channel.close(); - } - catch (Exception e) { - e.printStackTrace(); - } - } + private void closeLock() { + try { + lock.release(); + channel.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + } - private void deleteFile() { - try { - file.delete(); - } - catch (Exception e) { - e.printStackTrace(); - } - } + private void deleteFile() { + try { + file.delete(); + } + catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/src/zutil/OneInstanceNetwork.java b/src/zutil/OneInstanceNetwork.java index 2b6a9c4..62997e7 100644 --- a/src/zutil/OneInstanceNetwork.java +++ b/src/zutil/OneInstanceNetwork.java @@ -37,62 +37,62 @@ import java.net.Socket; * @author Ziver Koc */ public class OneInstanceNetwork extends Thread implements OneInstance{ - private int port; - - /** - * Creates a One App objekt - * - * @param port The port to lock - */ - public OneInstanceNetwork(int port){ - this.port = port; - } - - /** - * Starts the port lock - * - * @return Always true - */ - public boolean lockApp(){ - this.start(); - return true; - } - - /** - * he port lock thread - * should not be cald outside the class - */ - public void run() { - ServerSocket serverSocket = null; - Socket clientSocket = null; - try { - // Create the server socket - serverSocket = new ServerSocket(port, 1); - while (true) { - // Wait for a connection - clientSocket = serverSocket.accept(); - clientSocket.close(); - } - } - catch (IOException ioe) { - MultiPrintStream.out.println("Error in JustOneServer: " + ioe); - } - } + private int port; - /** - * Checks if the port is locked - * - * @return True if port is locked else false - */ - public boolean check() { - try { - Socket clientSocket = new Socket("localhost", port); - MultiPrintStream.out.println("Already running!!!"); - clientSocket.close(); - return true; - } - catch (Exception e) { - return false; - } - } + /** + * Creates a One App objekt + * + * @param port The port to lock + */ + public OneInstanceNetwork(int port){ + this.port = port; + } + + /** + * Starts the port lock + * + * @return Always true + */ + public boolean lockApp(){ + this.start(); + return true; + } + + /** + * he port lock thread + * should not be cald outside the class + */ + public void run() { + ServerSocket serverSocket = null; + Socket clientSocket = null; + try { + // Create the server socket + serverSocket = new ServerSocket(port, 1); + while (true) { + // Wait for a connection + clientSocket = serverSocket.accept(); + clientSocket.close(); + } + } + catch (IOException ioe) { + MultiPrintStream.out.println("Error in JustOneServer: " + ioe); + } + } + + /** + * Checks if the port is locked + * + * @return True if port is locked else false + */ + public boolean check() { + try { + Socket clientSocket = new Socket("localhost", port); + MultiPrintStream.out.println("Already running!!!"); + clientSocket.close(); + return true; + } + catch (Exception e) { + return false; + } + } } diff --git a/src/zutil/ProgressListener.java b/src/zutil/ProgressListener.java index 633652f..d842d49 100644 --- a/src/zutil/ProgressListener.java +++ b/src/zutil/ProgressListener.java @@ -32,13 +32,13 @@ package zutil; * */ public interface ProgressListener { - - /** - * This method is called when the progress is updated - * - * @param source is the source object of the progress - * @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); + + /** + * This method is called when the progress is updated + * + * @param source is the source object of the progress + * @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); } diff --git a/src/zutil/algo/EuclideansAlgo.java b/src/zutil/algo/EuclideansAlgo.java index fad0554..6f14145 100644 --- a/src/zutil/algo/EuclideansAlgo.java +++ b/src/zutil/algo/EuclideansAlgo.java @@ -38,104 +38,104 @@ import java.util.LinkedList; */ public class EuclideansAlgo { - /** - * Simple Test - * @param args - */ - public static void main(String[] args){ - MultiPrintStream.out.println("*** Correct Answer: "); - MultiPrintStream.out.println("java.util.LinkedList{0, 2, 1, 1, 1, 4, 12, 102, 1, 1, 2, 3, 2, 2, 36}"); - MultiPrintStream.out.println("GCD: 1"); - - MultiPrintStream.out.println("*** Integer:"); - MultiPrintStream.out.dump(calcGenerators(60728973, 160523347)); - MultiPrintStream.out.println("GCD: "+calc(60728973, 160523347)); - - MultiPrintStream.out.println("*** BigInteger: "); - MultiPrintStream.out.dump(calcGenerators(new BigInteger("60728973"), new BigInteger("160523347"))); - MultiPrintStream.out.println("GCD: "+calc(new BigInteger("60728973"), new BigInteger("160523347"))); - } - - /** - * Runs the Euclidean algorithm on the two input - * values. - * - * @param a is the first integer - * @param b is the second integer - * @return a integer containing the GCD of the integers - */ - public static int calc(int a, int b){ - int t; - while( b != 0 ){ - t = b; - b = a % b; - a = t; - } + /** + * Simple Test + * @param args + */ + public static void main(String[] args){ + MultiPrintStream.out.println("*** Correct Answer: "); + MultiPrintStream.out.println("java.util.LinkedList{0, 2, 1, 1, 1, 4, 12, 102, 1, 1, 2, 3, 2, 2, 36}"); + MultiPrintStream.out.println("GCD: 1"); - return a; - } - - /** - * Runs the Euclidean algorithm on the two input - * values. - * - * @param a is the first BigInteger - * @param b is the second BigInteger - * @return a BigInteger containing the GCD of the BigIntegers - */ - public static BigInteger calc(BigInteger a, BigInteger b){ - BigInteger t; - - while( !b.equals(BigInteger.ZERO) ){ - t = b; - b = a.mod( b ); - a = t; - } + MultiPrintStream.out.println("*** Integer:"); + MultiPrintStream.out.dump(calcGenerators(60728973, 160523347)); + MultiPrintStream.out.println("GCD: "+calc(60728973, 160523347)); - return a; - } + MultiPrintStream.out.println("*** BigInteger: "); + MultiPrintStream.out.dump(calcGenerators(new BigInteger("60728973"), new BigInteger("160523347"))); + MultiPrintStream.out.println("GCD: "+calc(new BigInteger("60728973"), new BigInteger("160523347"))); + } - /** - * Runs the Euclidean algorithm on the two input - * values to find the generators for the values. - * - * @param a is the first integer - * @param b is the second integer - * @return a list of integers that is generators for a and b - */ - public static LinkedList calcGenerators(int a, int b){ - LinkedList list = new LinkedList(); - int t; - - while( b != 0 ){ - list.add( a/b ); - t = b; - b = a % b; - a = t; - } - - return list; - } - - /** - * Runs the Euclidean algorithm on the two input - * values to find the generators for the values. - * - * @param a is the first BigInteger - * @param b is the second BigInteger - * @return a list of BigIntegers that is generators of a and b - */ - public static LinkedList calcGenerators(BigInteger a, BigInteger b){ - LinkedList list = new LinkedList(); - BigInteger t; - - while( !b.equals(BigInteger.ZERO) ){ - list.add( new BigInteger("0").add( a.divide( b ) ) ); - t = b; - b = a.mod( b ); - a = t; - } + /** + * Runs the Euclidean algorithm on the two input + * values. + * + * @param a is the first integer + * @param b is the second integer + * @return a integer containing the GCD of the integers + */ + public static int calc(int a, int b){ + int t; + while( b != 0 ){ + t = b; + b = a % b; + a = t; + } - return list; - } + return a; + } + + /** + * Runs the Euclidean algorithm on the two input + * values. + * + * @param a is the first BigInteger + * @param b is the second BigInteger + * @return a BigInteger containing the GCD of the BigIntegers + */ + public static BigInteger calc(BigInteger a, BigInteger b){ + BigInteger t; + + while( !b.equals(BigInteger.ZERO) ){ + t = b; + b = a.mod( b ); + a = t; + } + + return a; + } + + /** + * Runs the Euclidean algorithm on the two input + * values to find the generators for the values. + * + * @param a is the first integer + * @param b is the second integer + * @return a list of integers that is generators for a and b + */ + public static LinkedList calcGenerators(int a, int b){ + LinkedList list = new LinkedList(); + int t; + + while( b != 0 ){ + list.add( a/b ); + t = b; + b = a % b; + a = t; + } + + return list; + } + + /** + * Runs the Euclidean algorithm on the two input + * values to find the generators for the values. + * + * @param a is the first BigInteger + * @param b is the second BigInteger + * @return a list of BigIntegers that is generators of a and b + */ + public static LinkedList calcGenerators(BigInteger a, BigInteger b){ + LinkedList list = new LinkedList(); + BigInteger t; + + while( !b.equals(BigInteger.ZERO) ){ + list.add( new BigInteger("0").add( a.divide( b ) ) ); + t = b; + b = a.mod( b ); + a = t; + } + + return list; + } } diff --git a/src/zutil/algo/ShanksTonelliAlgo.java b/src/zutil/algo/ShanksTonelliAlgo.java index dfb100d..e39da39 100644 --- a/src/zutil/algo/ShanksTonelliAlgo.java +++ b/src/zutil/algo/ShanksTonelliAlgo.java @@ -36,76 +36,76 @@ import java.math.BigInteger; * @see Wikipedia */ public class ShanksTonelliAlgo { - public static BigInteger calc(BigInteger n, BigInteger p){ - - BigInteger nOrg = n; - BigInteger S = null, V, R, U, X; - BigInteger ONE = BigInteger.ONE; - BigInteger TWO = BigInteger.valueOf( 2 ); - BigInteger Q = p.add( ONE ).divide( TWO ); + public static BigInteger calc(BigInteger n, BigInteger p){ - switch( p.mod( BigInteger.valueOf(4) ).intValue() ){ - case 3: - S = n.pow( Q.divide( TWO ).intValue() ).mod( p ); - break; - case 1: - S = ONE; - n = n.subtract( ONE ); - while (n.divide( p ).compareTo( ONE ) == 0) { - S = S.add( ONE ); - //n = (n-2s+1) mod p - n = n.subtract( TWO.multiply( S ) ).add( ONE ).mod( p ); - if (n.compareTo( BigInteger.ZERO ) == 0){ - return S; - } - } - Q = Q.divide( TWO ); - V = ONE; - R = S; - U = ONE; - while (Q.compareTo( BigInteger.ZERO ) > 0) { - X = R.pow(2).subtract( n.multiply( U.pow(2) ) ).mod( p ); - U = TWO.multiply( R ).multiply( U ).mod( p ); - R = X; - if ( Q.testBit(0) ){ - X = S.multiply( R ).subtract( n.multiply(V).multiply(U) ).mod( p ); - V = V.multiply(R).add( S.multiply(U) ).mod( p ); - S = X; - } - Q = Q.divide( TWO ); - } - } + BigInteger nOrg = n; + BigInteger S = null, V, R, U, X; + BigInteger ONE = BigInteger.ONE; + BigInteger TWO = BigInteger.valueOf( 2 ); + BigInteger Q = p.add( ONE ).divide( TWO ); - if( S != null && S.multiply( S ).mod( p ).compareTo( nOrg ) != 0 ){ - return null; - } + switch( p.mod( BigInteger.valueOf(4) ).intValue() ){ + case 3: + S = n.pow( Q.divide( TWO ).intValue() ).mod( p ); + break; + case 1: + S = ONE; + n = n.subtract( ONE ); + while (n.divide( p ).compareTo( ONE ) == 0) { + S = S.add( ONE ); + //n = (n-2s+1) mod p + n = n.subtract( TWO.multiply( S ) ).add( ONE ).mod( p ); + if (n.compareTo( BigInteger.ZERO ) == 0){ + return S; + } + } + Q = Q.divide( TWO ); + V = ONE; + R = S; + U = ONE; + while (Q.compareTo( BigInteger.ZERO ) > 0) { + X = R.pow(2).subtract( n.multiply( U.pow(2) ) ).mod( p ); + U = TWO.multiply( R ).multiply( U ).mod( p ); + R = X; + if ( Q.testBit(0) ){ + X = S.multiply( R ).subtract( n.multiply(V).multiply(U) ).mod( p ); + V = V.multiply(R).add( S.multiply(U) ).mod( p ); + S = X; + } + Q = Q.divide( TWO ); + } + } - return S; - /* - - //p-1 = Q*2^S - BigInteger S = null, Q = null, R = null, V = null, W = null; + if( S != null && S.multiply( S ).mod( p ).compareTo( nOrg ) != 0 ){ + return null; + } - //Q = ( 2^S )/( 1-p ); - p-1 = ( 2^S )/( 1-p ) * 2^S; + return S; + /* - // R = n^( (Q+1)/2 ) mod p - R = n.pow( Q.add(BigInteger.ONE).divide(BigInteger.valueOf(2)).intValue() ).mod( p ); - // V = W^Q mod p - V = W.pow( Q.intValue() ).mod( p ); + //p-1 = Q*2^S + BigInteger S = null, Q = null, R = null, V = null, W = null; - for(int i=S.intValue(); true ;){ - while( true ){ - i--; - // 1 = ( ( R^2 * n^-1 )^2^i ) mod p - if( ( R.pow(2).multiply( n.pow(-1) ) ).pow( (int)Math.pow(2, i) ).mod( p ).compareTo( BigInteger.ONE ) == 0 ) - break; - } + //Q = ( 2^S )/( 1-p ); + p-1 = ( 2^S )/( 1-p ) * 2^S; - if(i == 0) return R; - //R = ( RV^(2^(S-i-1)) ) mod p - else R = ( R.multiply( V.pow( (int)Math.pow( 2, S.intValue()-i-1) ) )).mod( p ); - } - */ - } + // R = n^( (Q+1)/2 ) mod p + R = n.pow( Q.add(BigInteger.ONE).divide(BigInteger.valueOf(2)).intValue() ).mod( p ); + // V = W^Q mod p + V = W.pow( Q.intValue() ).mod( p ); + + for(int i=S.intValue(); true ;){ + while( true ){ + i--; + // 1 = ( ( R^2 * n^-1 )^2^i ) mod p + if( ( R.pow(2).multiply( n.pow(-1) ) ).pow( (int)Math.pow(2, i) ).mod( p ).compareTo( BigInteger.ONE ) == 0 ) + break; + } + + if(i == 0) return R; + //R = ( RV^(2^(S-i-1)) ) mod p + else R = ( R.multiply( V.pow( (int)Math.pow( 2, S.intValue()-i-1) ) )).mod( p ); + } + */ + } } diff --git a/src/zutil/algo/WienersAlgo.java b/src/zutil/algo/WienersAlgo.java index 165db1c..fc3784d 100644 --- a/src/zutil/algo/WienersAlgo.java +++ b/src/zutil/algo/WienersAlgo.java @@ -38,56 +38,56 @@ import java.util.LinkedList; * */ public class WienersAlgo { - - /** - * Runs the Wieners algorithm for the given values. - * - * @param n is the first value - * @param e is the second value - * @return a BigInteger array of length two. - * First index is p and second is q. - * If no value was found then it returns null. - */ - public static BigInteger[] calc(BigInteger n, BigInteger e){ - BigInteger[] ret = null; - - LinkedList gen = EuclideansAlgo.calcGenerators(e, n); - - BigInteger c0 = BigInteger.ONE; - BigInteger c1 = gen.poll(); - BigInteger d0 = BigInteger.ZERO; - BigInteger d1 = BigInteger.ONE; - - BigInteger t, n1, g; - while(!gen.isEmpty()){ - g = gen.poll(); - - t = c1; - c1 = g.multiply( c1 ).add( c0 ); - c0 = t; - - t = d1; - d1 = g.multiply( d1 ).add( d0 ); - d0 = t; - - // (d1*e-1) % c1 == 0 - n1 = d1.multiply( e ).subtract( BigInteger.ONE ); - if( n1.mod( c1 ).equals( BigInteger.ZERO ) ){ - n1 = n1.divide( c1 ); - - // x^2 - ( n - n1 +1 )x + n = 0 - ret = ZMath.pqFormula( - n.subtract( n1 ).add( BigInteger.ONE ).negate(), - n); - - if(ret[0].compareTo( BigInteger.ZERO ) >= 0 && - ret[1].compareTo( BigInteger.ZERO ) >= 0 && - ret[0].multiply( ret[1] ).equals( n )){ - return ret; - } - } - } - - return null; - } + + /** + * Runs the Wieners algorithm for the given values. + * + * @param n is the first value + * @param e is the second value + * @return a BigInteger array of length two. + * First index is p and second is q. + * If no value was found then it returns null. + */ + public static BigInteger[] calc(BigInteger n, BigInteger e){ + BigInteger[] ret = null; + + LinkedList gen = EuclideansAlgo.calcGenerators(e, n); + + BigInteger c0 = BigInteger.ONE; + BigInteger c1 = gen.poll(); + BigInteger d0 = BigInteger.ZERO; + BigInteger d1 = BigInteger.ONE; + + BigInteger t, n1, g; + while(!gen.isEmpty()){ + g = gen.poll(); + + t = c1; + c1 = g.multiply( c1 ).add( c0 ); + c0 = t; + + t = d1; + d1 = g.multiply( d1 ).add( d0 ); + d0 = t; + + // (d1*e-1) % c1 == 0 + n1 = d1.multiply( e ).subtract( BigInteger.ONE ); + if( n1.mod( c1 ).equals( BigInteger.ZERO ) ){ + n1 = n1.divide( c1 ); + + // x^2 - ( n - n1 +1 )x + n = 0 + ret = ZMath.pqFormula( + n.subtract( n1 ).add( BigInteger.ONE ).negate(), + n); + + if(ret[0].compareTo( BigInteger.ZERO ) >= 0 && + ret[1].compareTo( BigInteger.ZERO ) >= 0 && + ret[0].multiply( ret[1] ).equals( n )){ + return ret; + } + } + } + + return null; + } } diff --git a/src/zutil/algo/path/BreadthFirstSearch.java b/src/zutil/algo/path/BreadthFirstSearch.java index 602543c..90d5f6f 100644 --- a/src/zutil/algo/path/BreadthFirstSearch.java +++ b/src/zutil/algo/path/BreadthFirstSearch.java @@ -30,42 +30,42 @@ import java.util.Queue; /** * A class that uses BFS to find a path - * + * * @author Ziver */ public class BreadthFirstSearch implements PathFinder{ - /** - * Returns the first path to the destination - * - * @param start is the start Node - * @param stop is the goal Node - * @return A list with the path - */ - public LinkedList find(PathNode start, PathNode stop){ - Queue queue = new LinkedList(); - HashSet visited = new HashSet(); - - queue.add(start); - visited.add( start ); - - PathNode tmp; - while(!queue.isEmpty()){ - tmp = queue.poll(); - - for(PathNode next : tmp.getNeighbors()){ - if(!visited.contains( next ) && tmp.getNeighborCost(next) > 0){ - queue.add(next); - visited.add( next ); - next.setParentNeighbor(tmp); - - if(next.equals(stop)){ - return stop.traversTo(start); - } - } - } - } - - return new LinkedList(); - } + /** + * Returns the first path to the destination + * + * @param start is the start Node + * @param stop is the goal Node + * @return A list with the path + */ + public LinkedList find(PathNode start, PathNode stop){ + Queue queue = new LinkedList(); + HashSet visited = new HashSet(); + + queue.add(start); + visited.add( start ); + + PathNode tmp; + while(!queue.isEmpty()){ + tmp = queue.poll(); + + for(PathNode next : tmp.getNeighbors()){ + if(!visited.contains( next ) && tmp.getNeighborCost(next) > 0){ + queue.add(next); + visited.add( next ); + next.setParentNeighbor(tmp); + + if(next.equals(stop)){ + return stop.traversTo(start); + } + } + } + } + + return new LinkedList<>(); + } } diff --git a/src/zutil/algo/path/DepthFirstSearch.java b/src/zutil/algo/path/DepthFirstSearch.java index 385d14a..197323d 100644 --- a/src/zutil/algo/path/DepthFirstSearch.java +++ b/src/zutil/algo/path/DepthFirstSearch.java @@ -33,42 +33,42 @@ import java.util.LinkedList; * @author Ziver */ public class DepthFirstSearch { - private HashSet visited = new HashSet(); + private HashSet visited = new HashSet(); - /** - * Returns the first path to the destination - * - * @param start Start Node - * @param stop Stop Node - * @return A list with the path - */ - public LinkedList find(PathNode start, PathNode stop){ - visited.clear(); - PathNode node = dfs(start, stop); - return node.traversTo( start ); - } + /** + * Returns the first path to the destination + * + * @param start Start Node + * @param stop Stop Node + * @return A list with the path + */ + public LinkedList find(PathNode start, PathNode stop){ + visited.clear(); + PathNode node = dfs(start, stop); + return node.traversTo( start ); + } - /** - * The DepthFirstSearch algorithm - * @param node The node to search from - * @return The stop PathNode if a path was found else null - */ - private PathNode dfs(PathNode node, PathNode stop){ - visited.add( node ); - if(node.equals(stop)){ - return node; - } + /** + * The DepthFirstSearch algorithm + * @param node The node to search from + * @return The stop PathNode if a path was found else null + */ + private PathNode dfs(PathNode node, PathNode stop){ + visited.add( node ); + if(node.equals(stop)){ + return node; + } - for(PathNode next : node.getNeighbors()){ - if(!visited.contains( next ) && node.getNeighborCost(next) > 0){ - next.setParentNeighbor(node); - PathNode tmp = dfs(next, stop); - if(tmp != null){ - return tmp; - } - } - } - return null; - } + for(PathNode next : node.getNeighbors()){ + if(!visited.contains( next ) && node.getNeighborCost(next) > 0){ + next.setParentNeighbor(node); + PathNode tmp = dfs(next, stop); + if(tmp != null){ + return tmp; + } + } + } + return null; + } } diff --git a/src/zutil/algo/path/DynamicProgramming.java b/src/zutil/algo/path/DynamicProgramming.java index 9652f5a..aa550a9 100644 --- a/src/zutil/algo/path/DynamicProgramming.java +++ b/src/zutil/algo/path/DynamicProgramming.java @@ -25,117 +25,117 @@ package zutil.algo.path; public class DynamicProgramming { - public static char[][] words = new char[][]{ - "bibba".toCharArray(), - "bitas".toCharArray(), - "brott".toCharArray(), - "bl�ja".toCharArray(), - "boson".toCharArray() - }; + public static char[][] words = new char[][]{ + "bibba".toCharArray(), + "bitas".toCharArray(), + "brott".toCharArray(), + "bl�ja".toCharArray(), + "boson".toCharArray() + }; - public static void main(String[] args){ - new DynamicProgramming().search(); - } - /* + 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 - + 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 - - */ + minsta = -1 + for i=0->length(word) + if word[i] == cfind && (abs(index-i) < minsta || minsta < 0) + minsta = abs(index-i) - public int search(){ - int[][][] matrix = new int[words.length][words.length][words.length]; - int shortest = -1; + return minsta - for(int w=0; w= 0){ - matrix[w][y][x] = matrix[w][y-1][x] + tmp; - } - else{ - matrix[w][y][x] = -1; - } - } - } - if(y == words.length-1){ - int tmp = matrix[w][y][x]; - if((tmp= 0){ - shortest = tmp; - } - } - System.out.print(" "+matrix[w][y][x]); - } - } - } + */ - System.out.println("\n\nKortaste f�rflyttningen: "+shortest); - return shortest; - } + public int search(){ + int[][][] matrix = new int[words.length][words.length][words.length]; + int shortest = -1; - private int minstaForskjutning(char[] word, char cfind, int index){ - int minsta = -1; - for(int i=0; i= 0){ + matrix[w][y][x] = matrix[w][y-1][x] + tmp; + } + else{ + matrix[w][y][x] = -1; + } + } + } + if(y == words.length-1){ + int tmp = matrix[w][y][x]; + if((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); + /** + * Starts the search for the path from the start + * node to the goal. + * + * @param start is the starting point of the search + * @param goal is the search goal + * @return a LinkedList of the path, empty list if no path was found + */ + public LinkedList find(PathNode start, PathNode goal); } diff --git a/src/zutil/algo/path/PathNode.java b/src/zutil/algo/path/PathNode.java index 4cce8ac..13e94e1 100644 --- a/src/zutil/algo/path/PathNode.java +++ b/src/zutil/algo/path/PathNode.java @@ -29,32 +29,32 @@ import java.util.LinkedList; public interface PathNode { - /** - * @return an Iterator with all its neighbors - */ - public Iterable getNeighbors(); - - /** - * @param neighbor is the neighbor - * @return the cost to the neighbor - */ - public int getNeighborCost(PathNode neighbor); - - /** - * Sets the parent node to this one - */ - public void setParentNeighbor(PathNode parent); - - /** - * @return the parent node - */ - public PathNode getParentNeighbor(); - - /** - * Traverses the parent tree and returns the path. - * - * @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); + /** + * @return an Iterator with all its neighbors + */ + public Iterable getNeighbors(); + + /** + * @param neighbor is the neighbor + * @return the cost to the neighbor + */ + public int getNeighborCost(PathNode neighbor); + + /** + * Sets the parent node to this one + */ + public void setParentNeighbor(PathNode parent); + + /** + * @return the parent node + */ + public PathNode getParentNeighbor(); + + /** + * Traverses the parent tree and returns the path. + * + * @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); } diff --git a/src/zutil/algo/path/StandardPathNode.java b/src/zutil/algo/path/StandardPathNode.java index 87c7409..e828e6c 100644 --- a/src/zutil/algo/path/StandardPathNode.java +++ b/src/zutil/algo/path/StandardPathNode.java @@ -33,32 +33,32 @@ import java.util.LinkedList; * */ public class StandardPathNode implements PathNode{ - private HashMap neighbors; - private PathNode parent; - - public StandardPathNode(){ - neighbors = new HashMap(); - } + private HashMap neighbors; + private PathNode parent; - public int getNeighborCost(PathNode neighbor) { - return neighbors.get(neighbor); - } + public StandardPathNode(){ + neighbors = new HashMap(); + } - public Iterable getNeighbors() { - return neighbors.keySet(); - } + public int getNeighborCost(PathNode neighbor) { + return neighbors.get(neighbor); + } - public PathNode getParentNeighbor() { - return parent; - } + public Iterable getNeighbors() { + return neighbors.keySet(); + } - public void setParentNeighbor(PathNode parent) { - this.parent = parent; - } + public PathNode getParentNeighbor() { + return parent; + } - public LinkedList traversTo(PathNode goal) { - LinkedList path = new LinkedList(); - PathNode current = this; + public void setParentNeighbor(PathNode parent) { + this.parent = parent; + } + + public LinkedList traversTo(PathNode goal) { + LinkedList path = new LinkedList(); + PathNode current = this; while(current != null){ path.addFirst(current); current = current.getParentNeighbor(); @@ -68,6 +68,6 @@ public class StandardPathNode implements PathNode{ } } return new LinkedList(); - } + } } diff --git a/src/zutil/algo/search/QuickSelect.java b/src/zutil/algo/search/QuickSelect.java index 7d70fc7..f966b0d 100644 --- a/src/zutil/algo/search/QuickSelect.java +++ b/src/zutil/algo/search/QuickSelect.java @@ -36,57 +36,57 @@ import zutil.algo.sort.sortable.SortableDataList; */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class QuickSelect { - - public static Object find(SortableDataList list, int k){ - return find(list, k, 0, list.size()-1); - } - - /* - function select(list, k, left, right) - select a pivot value list[pivotIndex] - pivotNewIndex := partition(list, left, right, pivotIndex) - if k = pivotNewIndex - return list[k] - else if k < pivotNewIndex - return select(list, k, left, pivotNewIndex-1) - else - return select(list, k, pivotNewIndex+1, right) - */ - public static Object find(SortableDataList list, int k, int left, int right){ - // select a pivot - int pivot = right/2; - int newPivot = partition(list, left, right, pivot); - if(k == newPivot) - return list.get(k); - else if(k < newPivot) - return find(list, k, left, newPivot-1); - else - return find(list, k, newPivot+1, right); - } - - /* - function partition(list, left, right, pivotIndex) - pivotValue := list[pivotIndex] - swap list[pivotIndex] and list[right] // Move pivot to end - storeIndex := left - for i from left to right-1 - if list[i] < pivotValue - swap list[storeIndex] and list[i] - storeIndex := storeIndex + 1 - swap list[right] and list[storeIndex] // Move pivot to its final place - return storeIndex - */ - private static int partition(SortableDataList list, int left, int right, int pivot){ - Object pivotValue = list.get(pivot); - list.swap(pivot, right); - int storeIndex = left; - for(int i=left; i chunkFiles = sortChunks(); + /** + * Creates a ExternalSort object that sort a big file + * with minimal use of ram + * + * @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)); + this.sortedFile = sortedFile; + CHUNK_SIZE = chunk; + } - //merging the chunks - mergeFiles(chunkFiles); + /** + * Sorts the given file + * + * @throws IOException Some kind of error + */ + public void sort() throws IOException{ + // sorting the chunks + LinkedList chunkFiles = sortChunks(); - //removing the chunks - removeFiles(chunkFiles); - } + //merging the chunks + mergeFiles(chunkFiles); - /** - * Merges all the files to one - * @param files - */ - private void mergeFiles(LinkedList files){ - try { - BufferedReader[] chunkReader = new BufferedReader[files.size()]; - String[] rows = new String[files.size()]; - BufferedWriter out = new BufferedWriter(new FileWriter(sortedFile)); + //removing the chunks + removeFiles(chunkFiles); + } - boolean someFileStillHasRows = false; + /** + * Merges all the files to one + * @param files + */ + private void mergeFiles(LinkedList files){ + try { + BufferedReader[] chunkReader = new BufferedReader[files.size()]; + String[] rows = new String[files.size()]; + BufferedWriter out = new BufferedWriter(new FileWriter(sortedFile)); - for (int i=0; i sortChunks() throws IOException{ - LinkedList chunkFiles = new LinkedList(); - LinkedList chunk = new LinkedList(); - do{ - chunk = readChunk(in); + // check if one still has rows + someFileStillHasRows = false; + for(int i=0; i sortChunks() throws IOException{ + LinkedList chunkFiles = new LinkedList(); + LinkedList chunk = new LinkedList(); + do{ + chunk = readChunk(in); - return chunkFiles; - } + //QuickSort.sort(new SortableLinkedList(chunk)); + Collections.sort(chunk); - /** - * 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 - */ - private LinkedList readChunk(BufferedReader in) throws IOException{ - 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()); - out.newLine(); - } - out.close(); - } + return chunkFiles; + } - private void removeFiles(LinkedList list){ - Iterator it = list.iterator(); - while(it.hasNext()){ - it.next().delete(); - } - } + /** + * 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 + */ + private LinkedList readChunk(BufferedReader in) throws IOException{ + 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()); + out.newLine(); + } + out.close(); + } + + private void removeFiles(LinkedList list){ + Iterator it = list.iterator(); + while(it.hasNext()){ + it.next().delete(); + } + } } diff --git a/src/zutil/algo/sort/MergeSort.java b/src/zutil/algo/sort/MergeSort.java index e151e0e..55195f8 100644 --- a/src/zutil/algo/sort/MergeSort.java +++ b/src/zutil/algo/sort/MergeSort.java @@ -29,131 +29,131 @@ import zutil.algo.sort.sortable.SortableDataList; public class MergeSort{ - /** - * Sorts the given list with Merge sort - * - * @param list is the list to sort - */ - public static void sort(int[] list){ - if(list == null) - return; - - sort(list, 0, list.length); - } + /** + * Sorts the given list with Merge sort + * + * @param list is the list to sort + */ + public static void sort(int[] list){ + if(list == null) + return; - /** - * This method is the array splitting method - * that recursively splits the array in two. - * - * @param list is the list to sort - * @param start is the starting index of the sub list - * @param stop is the end index of the sub list - */ - protected static void sort(int[] list, int start, int stop){ - if(stop-start <= 1) return; + sort(list, 0, list.length); + } - int pivot = start+(stop-start)/2; - sort(list, start, pivot); - sort(list, pivot, stop); + /** + * This method is the array splitting method + * that recursively splits the array in two. + * + * @param list is the list to sort + * @param start is the starting index of the sub list + * @param stop is the end index of the sub list + */ + protected static void sort(int[] list, int start, int stop){ + if(stop-start <= 1) return; - merge(list, start, stop, pivot); - } + int pivot = start+(stop-start)/2; + sort(list, start, pivot); + sort(list, pivot, stop); - /** - * This method is the merger, after the array - * has been split this method will merge the - * two parts of the array and sort it. - * - * @param list is the list to merge - * @param start is the start of the first sublist - * @param stop is the end of the second sublist - * @param pivot is the end index for the first list and the beginning of the second. - */ - protected static void merge(int[] list, int start, int stop, int pivot){ - int length = pivot-start; - int[] tmp = new int[stop-start]; + merge(list, start, stop, pivot); + } - for(int i=0; i= length || tmp[index1] > tmp[index2]) ){ - list[i] = tmp[index2]; - ++index2; - } - else { - list[i] = tmp[index1]; - ++index1; - } - } - } - - - /** - * Sorts the given list with Merge sort, - * this is slower than the one with int[] array - * - * @param list is the list to sort - */ - public static void sort(SortableDataList list){ - if(list == null) - return; - - sort(list, 0, list.size()); - } + for(int i=0; i list, int start, int stop){ - if(stop-start <= 1) return; + int index1 = 0; + int index2 = length; + for(int i=start; i= length || tmp[index1] > tmp[index2]) ){ + list[i] = tmp[index2]; + ++index2; + } + else { + list[i] = tmp[index1]; + ++index1; + } + } + } - int pivot = start+(stop-start)/2; - sort(list, start, pivot); - sort(list, pivot, stop); - merge(list, start, stop, pivot); - } + /** + * Sorts the given list with Merge sort, + * this is slower than the one with int[] array + * + * @param list is the list to sort + */ + public static void sort(SortableDataList list){ + if(list == null) + return; - /** - * This method is the merger, after the array - * has been split this method will merge the - * two parts of the array and sort it. - * @param - * - * @param list is the list to merge - * @param start is the start of the first sublist - * @param stop is the end of the second sublist - * @param pivot is the end index for the first list and the beginning of the second. - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - protected static void merge(SortableDataList list, int start, int stop, int pivot){ - int length = pivot-start; - Object[] tmp = new Object[stop-start]; + sort(list, 0, list.size()); + } - for(int i=0; i list, int start, int stop){ + if(stop-start <= 1) return; - int index1 = 0; - int index2 = length; - for(int i=start; i= length || ((Comparable)tmp[index1]).compareTo(tmp[index2]) > 0 )){ - list.set(i, (T)tmp[index2]); - ++index2; - } - else { - list.set(i, (T)tmp[index1]); - ++index1; - } - } - } + int pivot = start+(stop-start)/2; + sort(list, start, pivot); + sort(list, pivot, stop); + + merge(list, start, stop, pivot); + } + + /** + * This method is the merger, after the array + * has been split this method will merge the + * two parts of the array and sort it. + * @param + * + * @param list is the list to merge + * @param start is the start of the first sublist + * @param stop is the end of the second sublist + * @param pivot is the end index for the first list and the beginning of the second. + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + protected static void merge(SortableDataList list, int start, int stop, int pivot){ + int length = pivot-start; + Object[] tmp = new Object[stop-start]; + + for(int i=0; i= length || ((Comparable)tmp[index1]).compareTo(tmp[index2]) > 0 )){ + list.set(i, (T)tmp[index2]); + ++index2; + } + else { + list.set(i, (T)tmp[index1]); + ++index1; + } + } + } } diff --git a/src/zutil/algo/sort/QuickSort.java b/src/zutil/algo/sort/QuickSort.java index 59184e7..dd1ebef 100644 --- a/src/zutil/algo/sort/QuickSort.java +++ b/src/zutil/algo/sort/QuickSort.java @@ -33,17 +33,17 @@ import zutil.algo.sort.sortable.SortableDataList; * @author Ziver */ public class QuickSort{ - public static final int RANDOM_PIVOT = 0; - public static final int MEDIAN_PIVOT = 1; - public static final int MIDDLE_PIVOT = 2; - + public static final int RANDOM_PIVOT = 0; + public static final int MEDIAN_PIVOT = 1; + public static final int MIDDLE_PIVOT = 2; + /** * Sort the elements in ascending order using Quicksort. * * @param list is the list to sort. */ - public static void sort(SortableDataList list){ - sort(list, 0, list.size()-1, MIDDLE_PIVOT, true); + public static void sort(SortableDataList list){ + sort(list, 0, list.size()-1, MIDDLE_PIVOT, true); } /** @@ -53,10 +53,10 @@ public class QuickSort{ * @param type is the type of pivot * @param insert is if insertion sort will be used */ - public static void sort(SortableDataList list, int type, boolean insert){ - sort(list, 0, list.size()-1, type, insert); + public static void sort(SortableDataList list, int type, boolean insert){ + sort(list, 0, list.size()-1, type, insert); } - + /** * Sort the elements in ascending order using Quicksort. * Reference: http://www.inf.fh-flensburg.de/lang/algorithmen/sortieren/quick/quicken.htm @@ -67,59 +67,59 @@ public class QuickSort{ * @param stop is the index to stop * @param type is the type of pivot to use */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static void sort(SortableDataList list, int start, int stop, int type, boolean insertionSort){ - if(stop-start <= 15 && insertionSort){ - SimpleSort.insertionSort( list, start, stop); - } - int pivotIndex = pivot(list,start,stop,type); - Object pivot = list.get(pivotIndex); - int left=start, right=stop; - - do{ - while(list.compare(left, pivot) < 0){ - left++; - } - while(list.compare(right, pivot) > 0){ - right--; - } - - if(left <= right){ - list.swap(left, right); - left++; - right--; - } - }while(left <= right); - - if(start < right){ - sort(list, start, right, type, insertionSort); - } - if(left < stop){ - sort(list, left, stop, type, insertionSort); - } + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static void sort(SortableDataList list, int start, int stop, int type, boolean insertionSort){ + if(stop-start <= 15 && insertionSort){ + SimpleSort.insertionSort( list, start, stop); + } + int pivotIndex = pivot(list,start,stop,type); + Object pivot = list.get(pivotIndex); + int left=start, right=stop; - } + do{ + while(list.compare(left, pivot) < 0){ + left++; + } + while(list.compare(right, pivot) > 0){ + right--; + } - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static int pivot(SortableDataList list, int start, int stop,int type){ - switch(type){ - case RANDOM_PIVOT: - return start+(int)(Math.random()*(stop-start)); - case MEDIAN_PIVOT: - Comparable[] i = new Comparable[]{ - (Comparable)list.get(0), - (Comparable)list.get(list.size()/2), - (Comparable)list.get(list.size()-1)}; - SimpleSort.insertionSort(new SortableComparableArray(i)); - if(i[i.length/2].compareTo(list.get(start)) == 0) - return start; - else if(i[i.length/2].compareTo(list.get(stop)) == 0) - return stop; - else - return start+(stop-start)/2; - case MIDDLE_PIVOT: - return (start+stop)/2; - } - return 0; + if(left <= right){ + list.swap(left, right); + left++; + right--; + } + }while(left <= right); + + if(start < right){ + sort(list, start, right, type, insertionSort); + } + if(left < stop){ + sort(list, left, stop, type, insertionSort); + } + + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static int pivot(SortableDataList list, int start, int stop,int type){ + switch(type){ + case RANDOM_PIVOT: + return start+(int)(Math.random()*(stop-start)); + case MEDIAN_PIVOT: + Comparable[] i = new Comparable[]{ + (Comparable)list.get(0), + (Comparable)list.get(list.size()/2), + (Comparable)list.get(list.size()-1)}; + SimpleSort.insertionSort(new SortableComparableArray(i)); + if(i[i.length/2].compareTo(list.get(start)) == 0) + return start; + else if(i[i.length/2].compareTo(list.get(stop)) == 0) + return stop; + else + return start+(stop-start)/2; + case MIDDLE_PIVOT: + return (start+stop)/2; + } + return 0; } } diff --git a/src/zutil/algo/sort/Randomizer.java b/src/zutil/algo/sort/Randomizer.java index 77721a7..6887587 100644 --- a/src/zutil/algo/sort/Randomizer.java +++ b/src/zutil/algo/sort/Randomizer.java @@ -33,16 +33,16 @@ import zutil.algo.sort.sortable.SortableDataList; * @author Ziver */ public class Randomizer { - - /** - * Randomizes the index of all the elements - * @param list The list - */ - @SuppressWarnings({ "rawtypes" }) - public static void sort(SortableDataList list){ - int size = list.size(); - for(int i=0; i implements SortableDataList{ - private ArrayList list; - - public SortableArrayList(ArrayList list){ - this.list = list; - } + private ArrayList list; - public T get(int i) { - return list.get(i); - } - - public void set(int i, T o){ - list.set(i, o); - } + public SortableArrayList(ArrayList list){ + this.list = list; + } - public int size() { - return list.size(); - } + public T get(int i) { + return list.get(i); + } - public void swap(int a, int b) { - T temp = list.get(a); - list.set(a, list.get(b)); - list.set(b, temp); - } - - public int compare(int a, int b) { - Comparable aa = (Comparable)list.get(a); - Comparable bb = (Comparable)list.get(b); - return aa.compareTo(bb); - } + public void set(int i, T o){ + list.set(i, o); + } - public int compare(int a, T b) { - Comparable aa = (Comparable)list.get(a); - Comparable bb = (Comparable)b; - return aa.compareTo(bb); - } - - + public int size() { + return list.size(); + } + public void swap(int a, int b) { + T temp = list.get(a); + list.set(a, list.get(b)); + list.set(b, temp); + } + + public int compare(int a, int b) { + Comparable aa = (Comparable)list.get(a); + Comparable bb = (Comparable)list.get(b); + return aa.compareTo(bb); + } + + public int compare(int a, T b) { + Comparable aa = (Comparable)list.get(a); + Comparable bb = (Comparable)b; + return aa.compareTo(bb); + } } diff --git a/src/zutil/algo/sort/sortable/SortableComparableArray.java b/src/zutil/algo/sort/sortable/SortableComparableArray.java index 98899ae..7f1112a 100644 --- a/src/zutil/algo/sort/sortable/SortableComparableArray.java +++ b/src/zutil/algo/sort/sortable/SortableComparableArray.java @@ -26,50 +26,47 @@ package zutil.algo.sort.sortable; @SuppressWarnings({ "unchecked", "rawtypes" }) public class SortableComparableArray implements SortableDataList{ - private Comparable[] list; - - public SortableComparableArray(Comparable[] list){ - this.list = list; - } - - public Comparable get(int i) { - return list[i]; - } - - public void set(int i, Comparable o){ - list[i] = o; - } + private Comparable[] list; - public int size() { - return list.length; - } + public SortableComparableArray(Comparable[] list){ + this.list = list; + } - public void swap(int a, int b) { - Comparable temp = list[a]; - list[a] = list[b]; - list[b] = temp; - } + public Comparable get(int i) { + return list[i]; + } - public int compare(int a, int b) { - if(list[a].compareTo(list[b]) < 0){ - return -1; - } - else if(list[a].compareTo(list[b]) > 0){ - return 1; - } - return 0; - } + public void set(int i, Comparable o){ + list[i] = o; + } - public int compare(int a, Comparable b) { - if(list[a].compareTo(b) < 0){ - return -1; - } - else if(list[a].compareTo(b) > 0){ - return 1; - } - return 0; - } + public int size() { + return list.length; + } + public void swap(int a, int b) { + Comparable temp = list[a]; + list[a] = list[b]; + list[b] = temp; + } + public int compare(int a, int b) { + if(list[a].compareTo(list[b]) < 0){ + return -1; + } + else if(list[a].compareTo(list[b]) > 0){ + return 1; + } + return 0; + } + public int compare(int a, Comparable b) { + if(list[a].compareTo(b) < 0){ + return -1; + } + else if(list[a].compareTo(b) > 0){ + return 1; + } + return 0; + } } diff --git a/src/zutil/algo/sort/sortable/SortableIntArray.java b/src/zutil/algo/sort/sortable/SortableIntArray.java index 56a4f6d..2701850 100644 --- a/src/zutil/algo/sort/sortable/SortableIntArray.java +++ b/src/zutil/algo/sort/sortable/SortableIntArray.java @@ -25,49 +25,49 @@ package zutil.algo.sort.sortable; public class SortableIntArray implements SortableDataList{ - private int[] list; - - public SortableIntArray(int[] list){ - this.list = list; - } - - public Integer get(int i) { - return list[i]; - } + private int[] list; - public void set(int i, Integer o){ - list[i] = o; - } - - public int size() { - return list.length; - } + public SortableIntArray(int[] list){ + this.list = list; + } - public void swap(int a, int b) { - int temp = list[a]; - list[a] = list[b]; - list[b] = temp; - } + public Integer get(int i) { + return list[i]; + } - public int compare(int a, int b) { - if(list[a] < list[b]){ - return -1; - } - else if(list[a] > list[b]){ - return 1; - } - return 0; - } + public void set(int i, Integer o){ + list[i] = o; + } - public int compare(int a, Integer b) { - if(list[a] < b){ - return -1; - } - else if(list[a] > b){ - return 1; - } - return 0; - } + public int size() { + return list.length; + } + + public void swap(int a, int b) { + int temp = list[a]; + list[a] = list[b]; + list[b] = temp; + } + + public int compare(int a, int b) { + if(list[a] < list[b]){ + return -1; + } + else if(list[a] > list[b]){ + return 1; + } + return 0; + } + + public int compare(int a, Integer b) { + if(list[a] < b){ + return -1; + } + else if(list[a] > b){ + return 1; + } + return 0; + } diff --git a/src/zutil/algo/sort/sortable/SortableLinkedList.java b/src/zutil/algo/sort/sortable/SortableLinkedList.java index caee2e4..b4c83fd 100644 --- a/src/zutil/algo/sort/sortable/SortableLinkedList.java +++ b/src/zutil/algo/sort/sortable/SortableLinkedList.java @@ -28,42 +28,42 @@ import java.util.LinkedList; @SuppressWarnings({ "unchecked", "rawtypes" }) public class SortableLinkedList implements SortableDataList{ - private LinkedList list; - - public SortableLinkedList(LinkedList list){ - this.list = list; - } + private LinkedList list; - public T get(int i) { - return list.get(i); - } - - public void set(int i, T o){ - list.set(i, o); - } + public SortableLinkedList(LinkedList list){ + this.list = list; + } - public int size() { - return list.size(); - } + public T get(int i) { + return list.get(i); + } + + public void set(int i, T o){ + list.set(i, o); + } + + public int size() { + return list.size(); + } + + public void swap(int a, int b) { + T temp = list.get(a); + list.set(a, list.get(b)); + list.set(b, temp); + } + + public int compare(int a, int b) { + Comparable aa = (Comparable)list.get(a); + Comparable bb = (Comparable)list.get(b); + return aa.compareTo(bb); + } + + public int compare(int a, T b) { + Comparable aa = (Comparable)list.get(a); + Comparable bb = (Comparable)b; + return aa.compareTo(bb); + } - public void swap(int a, int b) { - T temp = list.get(a); - list.set(a, list.get(b)); - list.set(b, temp); - } - - public int compare(int a, int b) { - Comparable aa = (Comparable)list.get(a); - Comparable bb = (Comparable)list.get(b); - return aa.compareTo(bb); - } - public int compare(int a, T b) { - Comparable aa = (Comparable)list.get(a); - Comparable bb = (Comparable)b; - return aa.compareTo(bb); - } - - } diff --git a/src/zutil/converter/Converter.java b/src/zutil/converter/Converter.java index 0515760..96b5b3a 100755 --- a/src/zutil/converter/Converter.java +++ b/src/zutil/converter/Converter.java @@ -33,61 +33,61 @@ import java.util.Iterator; import java.util.Map; public class Converter { - private Converter(){} + private Converter(){} - /** - * Converts an object to an array of bytes. - * - * @param object the object to convert. - * @return the associated byte array. - */ - public static byte[] toBytes(Object object) throws IOException{ - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + /** + * Converts an object to an array of bytes. + * + * @param object the object to convert. + * @return the associated byte array. + */ + public static byte[] toBytes(Object object) throws IOException{ + ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(object); - oos.flush(); - oos.close(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(object); + oos.flush(); + oos.close(); - return baos.toByteArray(); - } - - /** - * Converts a Integer to an byte array - * - * @param num is the number to convert - * @return a byte array of four bytes - */ - public static byte[] toBytes(int num){ - return new byte[]{ - (byte)(num & 0xff), - (byte)((num >> 8)& 0xff), - (byte)((num >> 16)& 0xff), - (byte)((num >> 24)& 0xff)}; - } + return baos.toByteArray(); + } + + /** + * Converts a Integer to an byte array + * + * @param num is the number to convert + * @return a byte array of four bytes + */ + public static byte[] toBytes(int num){ + return new byte[]{ + (byte)(num & 0xff), + (byte)((num >> 8)& 0xff), + (byte)((num >> 16)& 0xff), + (byte)((num >> 24)& 0xff)}; + } /** * Converts a char array to a byte array. * * @return a byte array with the same binary value as the char. */ - public static byte[] toBytes(char[] arr){ + public static byte[] toBytes(char[] arr){ byte[] ret = new byte[arr.length]; - for (int i=0; i>>= 1; - } - return str.reverse().toString(); - } + public static String toBitString(byte raw){ + StringBuilder str = new StringBuilder(8); + for (int i=0; i<8; ++i) { + str.append(raw & 0x01); + raw >>>= 1; + } + return str.reverse().toString(); + } - /** array needed for byteToHex */ - private static char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; - /** - * Converts a byte Array to a Hex String - * - * @param raw the byte array to convert - * @return a hex String - */ - public static String toHexString(byte[][] raw){ - StringBuffer ret = new StringBuffer(); - - for(byte[] a : raw){ - for(byte b : a){ - ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]); - ret.append(HEX_CHARS[(int) b & 0x0F ]); - } - } + /** array needed for byteToHex */ + private static char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; + /** + * Converts a byte Array to a Hex String + * + * @param raw the byte array to convert + * @return a hex String + */ + public static String toHexString(byte[][] raw){ + StringBuffer ret = new StringBuffer(); - return ret.toString(); - } + for(byte[] a : raw){ + for(byte b : a){ + ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]); + ret.append(HEX_CHARS[(int) b & 0x0F ]); + } + } - public static String toHexStringByColumn(byte[][] raw){ - StringBuffer ret = new StringBuffer(); - - for(int col=0; col>> 0x04)& 0x0F ]); - ret.append(HEX_CHARS[(int) raw[row][col] & 0x0F ]); - } - } + return ret.toString(); + } - return ret.toString(); - } - - /** - * Converts a byte Array to a Hex String - * - * @param raw the byte array to convert - * @return a hex String - */ - public static String toHexString(byte[] raw){ - StringBuffer ret = new StringBuffer(); + public static String toHexStringByColumn(byte[][] raw){ + StringBuffer ret = new StringBuffer(); - for(byte b : raw){ - ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]); - ret.append(HEX_CHARS[(int) b & 0x0F ]); - } + for(int col=0; col>> 0x04)& 0x0F ]); + ret.append(HEX_CHARS[(int) raw[row][col] & 0x0F ]); + } + } - return ret.toString(); - } + return ret.toString(); + } - /** - * Converts a byte to a Hex String - * - * @param raw the byte to convert - * @return a hex String - */ - public static String toHexString(byte raw){ - String ret = ""+HEX_CHARS[(int) (raw >>> 0x04)& 0x0F ]; - ret += ""+HEX_CHARS[(int) raw & 0x0F ]; + /** + * Converts a byte Array to a Hex String + * + * @param raw the byte array to convert + * @return a hex String + */ + public static String toHexString(byte[] raw){ + StringBuffer ret = new StringBuffer(); - return ret; - } + for(byte b : raw){ + ret.append(HEX_CHARS[(int) (b >>> 0x04)& 0x0F ]); + ret.append(HEX_CHARS[(int) b & 0x0F ]); + } - /** - * Converts the given byte to a String with 1's and 0's - * - * @param raw the byte to convert - * @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 ) ){ - ret.append(( (raw & i) == 0 ? '0' : '1')); - } - return ret.toString(); - } + return ret.toString(); + } - /** - * Converts the given byte array to a String with 1's and 0's - * - * @param raw the byte array to convert - * @return a String with 1's and 0's - */ - public static String toString(byte[] raw){ - StringBuffer ret = new StringBuffer(); - for(byte b : raw){ - for(int i=128; i>0 ;i=( i<1 ? i=0 : i/2 ) ){ - ret.append(( (b & i) == 0 ? '0' : '1')); - } - } - return ret.toString(); - } + /** + * Converts a byte to a Hex String + * + * @param raw the byte to convert + * @return a hex String + */ + public static String toHexString(byte raw){ + String ret = ""+HEX_CHARS[(int) (raw >>> 0x04)& 0x0F ]; + ret += ""+HEX_CHARS[(int) raw & 0x0F ]; + + return ret; + } + + /** + * Converts the given byte to a String with 1's and 0's + * + * @param raw the byte to convert + * @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 ) ){ + ret.append(( (raw & i) == 0 ? '0' : '1')); + } + return ret.toString(); + } + + /** + * Converts the given byte array to a String with 1's and 0's + * + * @param raw the byte array to convert + * @return a String with 1's and 0's + */ + public static String toString(byte[] raw){ + StringBuffer ret = new StringBuffer(); + for(byte b : raw){ + for(int i=128; i>0 ;i=( i<1 ? i=0 : i/2 ) ){ + ret.append(( (b & i) == 0 ? '0' : '1')); + } + } + return ret.toString(); + } /** * Generates a comma separated string with key and value pairs * * @return a comma separated String */ - public static String toString(Map map){ - StringBuilder tmp = new StringBuilder(); - tmp.append("{"); - Iterator it = map.keySet().iterator(); - while(it.hasNext()){ - Object key = it.next(); + public static String toString(Map map){ + StringBuilder tmp = new StringBuilder(); + tmp.append("{"); + Iterator it = map.keySet().iterator(); + while(it.hasNext()){ + Object key = it.next(); Object value = map.get(key); - tmp.append(key); + tmp.append(key); if (value != null) { if (value instanceof String) tmp.append(": \"").append(value).append("\""); @@ -313,158 +313,158 @@ public class Converter { else tmp.append("null"); - if(it.hasNext()) - tmp.append(", "); - } - tmp.append('}'); - return tmp.toString(); - } + if(it.hasNext()) + tmp.append(", "); + } + tmp.append('}'); + return tmp.toString(); + } - /** - * Converts a BitSet to a Integer - * - * @param bits the BitSet to convert - * @return a Integer - */ - public static int toInt(BitSet bits){ - int ret = 0; + /** + * Converts a BitSet to a Integer + * + * @param bits the BitSet to convert + * @return a Integer + */ + public static int toInt(BitSet bits){ + int ret = 0; - for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i+1)) { - ret += Math.pow(2, i); - } + for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i+1)) { + ret += Math.pow(2, i); + } - return ret; - } - - /** - * Converts a boolean array(bit sequence whit most significant bit at index 0) to a Integer - * - * @param bits the boolean array to convert - * @return a Integer - */ - public static int toInt(boolean[] bits){ - int ret = 0; + return ret; + } - for (int i = bits.length-1; i >= 0; i--) { - if(bits[i])ret += Math.pow(2, bits.length-i-1); - } + /** + * Converts a boolean array(bit sequence whit most significant bit at index 0) to a Integer + * + * @param bits the boolean array to convert + * @return a Integer + */ + public static int toInt(boolean[] bits){ + int ret = 0; - return ret; - } - - /** - * Converts a byte to a integer - * - * @param b is the byte to convert - * @return the integer value of the byte - */ - public static int toInt(byte b){ - return (int)(b & 0xff); - } + for (int i = bits.length-1; i >= 0; i--) { + if(bits[i])ret += Math.pow(2, bits.length-i-1); + } - /** - * Converts a dynamic sized byte array to a integer - * - * @param b is the byte array of size 1-4 - * @return the int value of the byte array - */ - public static int toInt(byte[] b){ - int i = 0; - switch (b.length){ - default: - case 4: i |= 0xFF000000 & (b[3] << 24); - case 3: i |= 0x00FF0000 & (b[2] << 16); - case 2: i |= 0x0000FF00 & (b[1] << 8); - case 1: i |= 0x000000FF & b[0]; - case 0: break; - } - return i; - } + return ret; + } - /** - * Converts a Integer to a BitSet - * - * @param num the Integer to convert - * @return a BitSet object - */ - public static BitSet toBitSet(int num){ - BitSet ret = new BitSet(); - String tmp = Integer.toBinaryString(num); + /** + * Converts a byte to a integer + * + * @param b is the byte to convert + * @return the integer value of the byte + */ + public static int toInt(byte b){ + return (int)(b & 0xff); + } - for(int i=0; i is the resulting class - * @param data is the String data to be converted - * @param c is the class to convert to - * @return a instance of the class with the value in the string or null if there was an problem - */ - @SuppressWarnings("unchecked") - public static T fromString(String data, Class c){ - if(data == null || data.isEmpty()) - return null; - try{ - if( c == String.class) return (T) data; - else if(c == Integer.class) return (T) new Integer(data); - else if(c == int.class) return (T) new Integer(data); - else if(c == Long.class) return (T) new Long(data); - else if(c == long.class) return (T) new Long(data); - else if(c == Float.class) return (T) new Float(data); - else if(c == float.class) return (T) new Float(data); - else if(c == Double.class) return (T) new Double(data); - else if(c == double.class) return (T) new Double(data); - else if(c == Boolean.class) return (T) new Boolean(data); - else if(c == boolean.class) return (T) new Boolean(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)) - return (T) Base64Decoder.decode(data); - }catch(Exception e){ - e.printStackTrace(); - } - return null; - } - - /** - * Replaces reserved and unsafe characters in URLs with hex values - */ - public static String urlEncode( String str ){ - StringBuilder out = new StringBuilder(); - for( char c : str.toCharArray() ){ - if( c>='0' && c<='9' || c>='A' && c<='Z' || c>='a' && c<='z' || - c=='$' || c=='-' || c=='_' || c=='.' || c=='+' || c=='!' || - c=='*' || c=='\'' || c=='(' || c==')' || c==',' ) - out.append( c ); - else{ - out.append( '%' ).append( toHexString((byte)c) ); - } - } - - return out.toString(); - } - - /** - * Replaces hex values from a URL with the proper characters - */ - public static String urlDecode( String str ){ - StringBuilder out = new StringBuilder(); - char[] array = str.toCharArray(); - for( int i=0; i is the resulting class + * @param data is the String data to be converted + * @param c is the class to convert to + * @return a instance of the class with the value in the string or null if there was an problem + */ + @SuppressWarnings("unchecked") + public static T fromString(String data, Class c){ + if(data == null || data.isEmpty()) + return null; + try{ + if( c == String.class) return (T) data; + else if(c == Integer.class) return (T) new Integer(data); + else if(c == int.class) return (T) new Integer(data); + else if(c == Long.class) return (T) new Long(data); + else if(c == long.class) return (T) new Long(data); + else if(c == Float.class) return (T) new Float(data); + else if(c == float.class) return (T) new Float(data); + else if(c == Double.class) return (T) new Double(data); + else if(c == double.class) return (T) new Double(data); + else if(c == Boolean.class) return (T) new Boolean(data); + else if(c == boolean.class) return (T) new Boolean(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)) + return (T) Base64Decoder.decode(data); + }catch(Exception e){ + e.printStackTrace(); + } + return null; + } + + /** + * Replaces reserved and unsafe characters in URLs with hex values + */ + public static String urlEncode( String str ){ + StringBuilder out = new StringBuilder(); + for( char c : str.toCharArray() ){ + if( c>='0' && c<='9' || c>='A' && c<='Z' || c>='a' && c<='z' || + c=='$' || c=='-' || c=='_' || c=='.' || c=='+' || c=='!' || + c=='*' || c=='\'' || c=='(' || c==')' || c==',' ) + out.append( c ); + else{ + out.append( '%' ).append( toHexString((byte)c) ); + } + } + + return out.toString(); + } + + /** + * Replaces hex values from a URL with the proper characters + */ + public static String urlDecode( String str ){ + StringBuilder out = new StringBuilder(); + char[] array = str.toCharArray(); + for( int i=0; i 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(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"); - } - - - /** - * Given an integer in the range -20 to 20 will return a String with - * that number converted to words. For example, an input of 15 results in - * an output of "fifteen". An input of -4 returns "minus four". - * - * @param num a number to be converted to words. - * @return the number as words. - */ - public String convert(int num) { - if (num == 0) - return ZERO_STRINGS; - - long tmpNum = num; - StringBuilder buffer = new StringBuilder(); - if (tmpNum < 0){ // Negative number - tmpNum *= -1; - buffer.append("minus "); - } - - for(int i : NUMERIC_INDEXES){ - long pow = (int)Math.pow(10, i); - if (tmpNum >= pow){ - long numberAtIndex = tmpNum/pow; // The number at position 3 - tmpNum -= numberAtIndex*pow; - buffer.append( convert((int)numberAtIndex) ).append(" "); - buffer.append( NUMERIC_STRINGS.get( pow ) ).append(" "); - } - } - if (tmpNum >= 20){ // second number in the integer - long numberAtIndex = ((tmpNum % 100)/10)*10; // The number at position 2 - tmpNum -= numberAtIndex; - buffer.append( NUMERIC_STRINGS.get(numberAtIndex) ).append(" "); - } - if (NUMERIC_STRINGS.containsKey(tmpNum)) - buffer.append(NUMERIC_STRINGS.get(tmpNum)); - return buffer.toString().trim(); - } + + private static final String ZERO_STRINGS = "zero"; + // Indexes to lookup + private static final int[] NUMERIC_INDEXES = new int[]{ + 9,/*1000 000 000*/ + 6,/*1000 000*/ + 3,/*1000*/ + 2 /*100*/}; + 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(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"); + } + + + /** + * Given an integer in the range -20 to 20 will return a String with + * that number converted to words. For example, an input of 15 results in + * an output of "fifteen". An input of -4 returns "minus four". + * + * @param num a number to be converted to words. + * @return the number as words. + */ + public String convert(int num) { + if (num == 0) + return ZERO_STRINGS; + + long tmpNum = num; + StringBuilder buffer = new StringBuilder(); + if (tmpNum < 0){ // Negative number + tmpNum *= -1; + buffer.append("minus "); + } + + for(int i : NUMERIC_INDEXES){ + long pow = (int)Math.pow(10, i); + if (tmpNum >= pow){ + long numberAtIndex = tmpNum/pow; // The number at position 3 + tmpNum -= numberAtIndex*pow; + buffer.append( convert((int)numberAtIndex) ).append(" "); + buffer.append( NUMERIC_STRINGS.get( pow ) ).append(" "); + } + } + if (tmpNum >= 20){ // second number in the integer + long numberAtIndex = ((tmpNum % 100)/10)*10; // The number at position 2 + tmpNum -= numberAtIndex; + buffer.append( NUMERIC_STRINGS.get(numberAtIndex) ).append(" "); + } + if (NUMERIC_STRINGS.containsKey(tmpNum)) + buffer.append(NUMERIC_STRINGS.get(tmpNum)); + return buffer.toString().trim(); + } } diff --git a/src/zutil/converter/WGS84Converter.java b/src/zutil/converter/WGS84Converter.java index 963475e..9e14f53 100755 --- a/src/zutil/converter/WGS84Converter.java +++ b/src/zutil/converter/WGS84Converter.java @@ -25,48 +25,48 @@ package zutil.converter; public class WGS84Converter { - public static void main(String[] args){ - System.out.println(toWGS84Decimal("N 59� 47' 43\"")+" "+toWGS84Decimal(" E 17� 42' 55\"")); - System.out.println(toWGS84Decimal("55� 0' 0\"")+" "+toWGS84Decimal("68� 59' 59,999\"")); - System.out.println(toWGS84Decimal("55� 0.001'")+" "+toWGS84Decimal("68� 59.999'")); - System.out.println(toWGS84Decimal("3444.0000S")+" "+toWGS84Decimal("13521.0000E")); - System.out.println(toWGS84Decimal("-44.0001")+" "+toWGS84Decimal("521.0001")); - } + public static void main(String[] args){ + System.out.println(toWGS84Decimal("N 59� 47' 43\"")+" "+toWGS84Decimal(" E 17� 42' 55\"")); + System.out.println(toWGS84Decimal("55� 0' 0\"")+" "+toWGS84Decimal("68� 59' 59,999\"")); + System.out.println(toWGS84Decimal("55� 0.001'")+" "+toWGS84Decimal("68� 59.999'")); + System.out.println(toWGS84Decimal("3444.0000S")+" "+toWGS84Decimal("13521.0000E")); + System.out.println(toWGS84Decimal("-44.0001")+" "+toWGS84Decimal("521.0001")); + } - /** - * Converts an WGS84 coordinate to an WGS84 decimal coordinate - * - * @param coordinate is the coordinate to convert - * @return the new coordinate in decimal degrees, returns 0 if conversions fails - */ - public static float toWGS84Decimal(String coordinate){ - float deg=0, min=0, sec=0, neg=1; - coordinate = coordinate.trim().replaceAll(",", ".").toUpperCase(); - if(coordinate.contains("S") || coordinate.contains("W")) - neg = -1; - - // 55� 0' 68� 59,999 or 55� 0' 0" 68� 59' 59,999" - if(coordinate.matches("[NSWE ]? ?[0-9]{1,3}� [0-9]{1,2}.?[0-9]*'[ 0-9.\\\"]*")){ - coordinate = coordinate.replaceAll("[NSEW�'\\\"]", "").trim(); - String[] tmp = coordinate.split(" "); - deg = Float.parseFloat(tmp[0]); - min = Float.parseFloat(tmp[1]); - if(tmp.length > 2){ - sec = Float.parseFloat(tmp[2]); - } - } - // 3444.0000S 13521.0000E - else if(coordinate.matches("[0-9]{4,5}.[0-9]*[NSEW]{1}")){ - coordinate = coordinate.replaceAll("[NS EW]", ""); - float tmpf = Float.parseFloat(coordinate); - deg = (int)(tmpf/100); - min = tmpf-(deg*100); - } - // 55.0 68.99999 - else if(coordinate.matches("\\-?[0-9]{2,3}.[0-9]*")){ - return Float.parseFloat(coordinate); - } - - return neg*(deg + min/60 + sec/3600); - } + /** + * Converts an WGS84 coordinate to an WGS84 decimal coordinate + * + * @param coordinate is the coordinate to convert + * @return the new coordinate in decimal degrees, returns 0 if conversions fails + */ + public static float toWGS84Decimal(String coordinate){ + float deg=0, min=0, sec=0, neg=1; + coordinate = coordinate.trim().replaceAll(",", ".").toUpperCase(); + if(coordinate.contains("S") || coordinate.contains("W")) + neg = -1; + + // 55� 0' 68� 59,999 or 55� 0' 0" 68� 59' 59,999" + if(coordinate.matches("[NSWE ]? ?[0-9]{1,3}� [0-9]{1,2}.?[0-9]*'[ 0-9.\\\"]*")){ + coordinate = coordinate.replaceAll("[NSEW�'\\\"]", "").trim(); + String[] tmp = coordinate.split(" "); + deg = Float.parseFloat(tmp[0]); + min = Float.parseFloat(tmp[1]); + if(tmp.length > 2){ + sec = Float.parseFloat(tmp[2]); + } + } + // 3444.0000S 13521.0000E + else if(coordinate.matches("[0-9]{4,5}.[0-9]*[NSEW]{1}")){ + coordinate = coordinate.replaceAll("[NS EW]", ""); + float tmpf = Float.parseFloat(coordinate); + deg = (int)(tmpf/100); + min = tmpf-(deg*100); + } + // 55.0 68.99999 + else if(coordinate.matches("\\-?[0-9]{2,3}.[0-9]*")){ + return Float.parseFloat(coordinate); + } + + return neg*(deg + min/60 + sec/3600); + } } diff --git a/src/zutil/db/DBConnectionPool.java b/src/zutil/db/DBConnectionPool.java index 4c51c3c..8c0b24d 100644 --- a/src/zutil/db/DBConnectionPool.java +++ b/src/zutil/db/DBConnectionPool.java @@ -37,162 +37,162 @@ import java.util.TimerTask; * @author Ziver */ public class DBConnectionPool extends TimerTask implements Closeable{ - public static final long DEFAULT_TIMEOUT = 10*60*60*1000; // 10 minutes; - public static final int DEFAULT_MAX_SIZE = 5; - - // DB details - private DBMS dbms; - private String url; - private String db; - private String user; - private String password; + public static final long DEFAULT_TIMEOUT = 10*60*60*1000; // 10 minutes; + public static final int DEFAULT_MAX_SIZE = 5; - // Pool details - private int max_conn; - private long timeout; - private Timer timeout_timer; + // DB details + private DBMS dbms; + private String url; + private String db; + private String user; + private String password; - protected class PoolItem{ - public DBConnection conn; - public long timestamp; + // Pool details + private int max_conn; + private long timeout; + private Timer timeout_timer; - public boolean equals(Object o){ - return conn.equals(o); - } - } + protected class PoolItem{ + public DBConnection conn; + public long timestamp; - // The pool - private LinkedList inusePool; - private LinkedList readyPool; + public boolean equals(Object o){ + return conn.equals(o); + } + } - /** - * Creates a new pool of DB connections - * - * @param dbms is the DB type - * @param url is the URL to the DB - * @param db is the name of the database - * @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{ - this.dbms = dbms; - this.url = url; - this.db = db; - this.user = user; - this.password = password; + // The pool + private LinkedList inusePool; + private LinkedList readyPool; - inusePool = new LinkedList(); - readyPool = new LinkedList(); - - this.setTimeout(DEFAULT_TIMEOUT); - this.setMaxSize(DEFAULT_MAX_SIZE); - } + /** + * Creates a new pool of DB connections + * + * @param dbms is the DB type + * @param url is the URL to the DB + * @param db is the name of the database + * @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{ + this.dbms = dbms; + this.url = url; + this.db = db; + this.user = user; + this.password = password; - /** - * Registers a Connection to the pool - * - * @param conn is the Connection to register - */ - protected void addConnection(DBConnection conn){ - PoolItem item = new PoolItem(); - item.conn = conn; - readyPool.addLast(item); - } + inusePool = new LinkedList(); + readyPool = new LinkedList(); - /** - * Removes an connection from the pool - * - * @param conn is the connection to remove - */ - protected void removeConnection(DBConnection conn){ - inusePool.remove(conn); - readyPool.remove(conn); - } + this.setTimeout(DEFAULT_TIMEOUT); + this.setMaxSize(DEFAULT_MAX_SIZE); + } - /** - * Lease one connection from the pool - * - * @return an DB connection or null if the pool is empty - */ - public synchronized DBConnection getConnection() throws Exception{ - if(readyPool.isEmpty()){ - if( size() < max_conn ){ - DBConnection conn = new DBConnection(dbms, url, db, user, password); - conn.setPool( this ); - addConnection( conn ); - return conn; - } - return null; - } - else{ - PoolItem item = readyPool.poll(); - inusePool.addLast(item); - item.timestamp = System.currentTimeMillis(); - return item.conn; - } - } + /** + * Registers a Connection to the pool + * + * @param conn is the Connection to register + */ + protected void addConnection(DBConnection conn){ + PoolItem item = new PoolItem(); + item.conn = conn; + readyPool.addLast(item); + } - /** - * Registers the Connection as not used - * - * @param conn is the connection that is not used anymore - */ - protected synchronized void releaseConnection(DBConnection conn){ - int index = inusePool.indexOf(conn); - PoolItem item = inusePool.remove(index); - readyPool.addLast(item); - } + /** + * Removes an connection from the pool + * + * @param conn is the connection to remove + */ + protected void removeConnection(DBConnection conn){ + inusePool.remove(conn); + readyPool.remove(conn); + } - /** - * @return the current size of the pool - */ - public int size(){ - return inusePool.size() + readyPool.size(); - } + /** + * Lease one connection from the pool + * + * @return an DB connection or null if the pool is empty + */ + public synchronized DBConnection getConnection() throws Exception{ + if(readyPool.isEmpty()){ + if( size() < max_conn ){ + DBConnection conn = new DBConnection(dbms, url, db, user, password); + conn.setPool( this ); + addConnection( conn ); + return conn; + } + return null; + } + else{ + PoolItem item = readyPool.poll(); + inusePool.addLast(item); + item.timestamp = System.currentTimeMillis(); + return item.conn; + } + } - /** - * Closes all the connections - */ - public synchronized void close(){ - for( PoolItem item : inusePool ){ - item.conn.forceClose(); - } - inusePool.clear(); - for( PoolItem item : readyPool ){ - item.conn.forceClose(); - } - readyPool.clear(); - } + /** + * Registers the Connection as not used + * + * @param conn is the connection that is not used anymore + */ + protected synchronized void releaseConnection(DBConnection conn){ + int index = inusePool.indexOf(conn); + PoolItem item = inusePool.remove(index); + readyPool.addLast(item); + } - /** - * Set the max size of the pool - */ - public void setMaxSize(int max){ - this.max_conn = max; - } + /** + * @return the current size of the pool + */ + public int size(){ + return inusePool.size() + readyPool.size(); + } - /** - * Sets the timeout of the Connections - */ - public synchronized void setTimeout(long timeout){ - this.timeout = timeout; - if(timeout_timer!=null) - timeout_timer.cancel(); - timeout_timer = new Timer(); - timeout_timer.schedule(this, 0, timeout / 2); - } + /** + * Closes all the connections + */ + public synchronized void close(){ + for( PoolItem item : inusePool ){ + item.conn.forceClose(); + } + inusePool.clear(); + for( PoolItem item : readyPool ){ + item.conn.forceClose(); + } + readyPool.clear(); + } - /** - * Checks every DB connection if they are valid and has not timed out - */ - public void run(){ - long stale = System.currentTimeMillis() - timeout; + /** + * Set the max size of the pool + */ + public void setMaxSize(int max){ + this.max_conn = max; + } - for(PoolItem item : inusePool){ - if( !item.conn.valid() && stale > item.timestamp ) { - removeConnection(item.conn); - item.conn.forceClose(); - } - } - } + /** + * Sets the timeout of the Connections + */ + public synchronized void setTimeout(long timeout){ + this.timeout = timeout; + if(timeout_timer!=null) + timeout_timer.cancel(); + timeout_timer = new Timer(); + timeout_timer.schedule(this, 0, timeout / 2); + } + + /** + * Checks every DB connection if they are valid and has not timed out + */ + public void run(){ + long stale = System.currentTimeMillis() - timeout; + + for(PoolItem item : inusePool){ + if( !item.conn.valid() && stale > item.timestamp ) { + removeConnection(item.conn); + item.conn.forceClose(); + } + } + } } diff --git a/src/zutil/db/DBQueue.java b/src/zutil/db/DBQueue.java index d4c72d9..88b67d5 100755 --- a/src/zutil/db/DBQueue.java +++ b/src/zutil/db/DBQueue.java @@ -49,168 +49,168 @@ import java.util.Queue; * */ public class DBQueue implements Queue{ - private DBConnection db; - private String table; - - /** - * Initiates the queue.
- * - * @param db is the connection to the DB - * @param table is the name of the table - */ - public DBQueue(DBConnection db, String table){ - this.db = db; - this.table = table; - } + private DBConnection db; + private String table; - public boolean add(Object arg0){ - try { - PreparedStatement sql = db.getPreparedStatement("INSERT INTO ? (data) VALUES(?)"); + /** + * Initiates the queue.
+ * + * @param db is the connection to the DB + * @param table is the name of the table + */ + public DBQueue(DBConnection db, String table){ + this.db = db; + this.table = table; + } + + public boolean add(Object arg0){ + try { + PreparedStatement sql = db.getPreparedStatement("INSERT INTO ? (data) VALUES(?)"); sql.setObject(1, table); - sql.setObject(2, arg0); - DBConnection.exec(sql); - } catch (Exception e) { - e.printStackTrace(MultiPrintStream.out); - return false; - } - return true; - } - - public E element() { - return peek(); - } + sql.setObject(2, arg0); + DBConnection.exec(sql); + } catch (Exception e) { + e.printStackTrace(MultiPrintStream.out); + return false; + } + return true; + } - public boolean offer(Object arg0) { - return add(arg0); - } + public E element() { + return peek(); + } - public synchronized E peek() { - try { - return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler(){ - public E handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{ - if (rs.next()) - try { - return (E) Converter.toObject(rs.getBytes("data")); - } catch (Exception e) { - e.printStackTrace(MultiPrintStream.out); - } - return null; - } - }); - } catch (Exception e) { - e.printStackTrace(MultiPrintStream.out); - } - return null; - } + public boolean offer(Object arg0) { + return add(arg0); + } - public synchronized E poll() { - try { - return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler(){ - public E handleQueryResult(Statement stmt, ResultSet rs) { - try{ - if (rs.next()) { - db.exec("DELETE FROM "+table+" WHERE id="+rs.getInt("id")+" LIMIT 1"); - return (E) Converter.toObject(rs.getBytes("data")); - } - }catch(Exception e){ - e.printStackTrace(MultiPrintStream.out); - } - return null; - } - }); - } catch (Exception e) { - e.printStackTrace(MultiPrintStream.out); - } - return null; - } + public synchronized E peek() { + try { + return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler(){ + public E handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{ + if (rs.next()) + try { + return (E) Converter.toObject(rs.getBytes("data")); + } catch (Exception e) { + e.printStackTrace(MultiPrintStream.out); + } + return null; + } + }); + } catch (Exception e) { + e.printStackTrace(MultiPrintStream.out); + } + return null; + } - public E remove() { - return poll(); - } + public synchronized E poll() { + try { + return db.exec("SELECT * FROM "+table+" LIMIT 1", new SQLResultHandler(){ + public E handleQueryResult(Statement stmt, ResultSet rs) { + try{ + if (rs.next()) { + db.exec("DELETE FROM "+table+" WHERE id="+rs.getInt("id")+" LIMIT 1"); + return (E) Converter.toObject(rs.getBytes("data")); + } + }catch(Exception e){ + e.printStackTrace(MultiPrintStream.out); + } + return null; + } + }); + } catch (Exception e) { + e.printStackTrace(MultiPrintStream.out); + } + return null; + } - public boolean addAll(Collection arg0) { - // TODO Auto-generated method stub - return false; - } + public E remove() { + return poll(); + } - public void clear() { - try { - db.exec("TRUNCATE TABLE `"+table+"`"); - } catch (SQLException e) { - e.printStackTrace(MultiPrintStream.out); - } - } + public boolean addAll(Collection arg0) { + // TODO Auto-generated method stub + return false; + } - public boolean contains(Object arg0) { - try { - return db.exec("SELECT data FROM "+table+" WHERE data='"+Converter.toBytes(arg0)+"' LIMIT 1", new SQLResultHandler(){ - public Boolean handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{ - return rs.next(); - } - }); - } catch (Exception e) { - e.printStackTrace(MultiPrintStream.out); - } - return false; - } + public void clear() { + try { + db.exec("TRUNCATE TABLE `"+table+"`"); + } catch (SQLException e) { + e.printStackTrace(MultiPrintStream.out); + } + } - public boolean containsAll(Collection arg0) { - // TODO Auto-generated method stub - return false; - } + public boolean contains(Object arg0) { + try { + return db.exec("SELECT data FROM "+table+" WHERE data='"+Converter.toBytes(arg0)+"' LIMIT 1", new SQLResultHandler(){ + public Boolean handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{ + return rs.next(); + } + }); + } catch (Exception e) { + e.printStackTrace(MultiPrintStream.out); + } + return false; + } - public boolean isEmpty() { - return (peek() != null); - } + public boolean containsAll(Collection arg0) { + // TODO Auto-generated method stub + return false; + } - public Iterator iterator() { - // TODO: Auto-generated method stub - return null; - } + public boolean isEmpty() { + return (peek() != null); + } - public synchronized boolean remove(Object arg0) { - try { - db.exec("DELETE FROM "+table+" WHERE data='"+Converter.toBytes(arg0)+"' LIMIT 1"); - return true; - } catch (Exception e) { - e.printStackTrace(MultiPrintStream.out); - } - return false; - } + public Iterator iterator() { + // TODO: Auto-generated method stub + return null; + } - public synchronized boolean removeAll(Collection arg0) { - // TODO Auto-generated method stub - return false; - } + public synchronized boolean remove(Object arg0) { + try { + db.exec("DELETE FROM "+table+" WHERE data='"+Converter.toBytes(arg0)+"' LIMIT 1"); + return true; + } catch (Exception e) { + e.printStackTrace(MultiPrintStream.out); + } + return false; + } - public boolean retainAll(Collection arg0) { - // TODO Auto-generated method stub - return false; - } + public synchronized boolean removeAll(Collection arg0) { + // TODO Auto-generated method stub + return false; + } - public int size() { - try { - return db.exec("SELECT count(*) FROM "+table, new SQLResultHandler(){ - public Integer handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{ - if (rs.next()) - return rs.getInt(1); - return 0; - } - }); - } catch (Exception e) { - e.printStackTrace(MultiPrintStream.out); - } - return 0; - } + public boolean retainAll(Collection arg0) { + // TODO Auto-generated method stub + return false; + } - public E[] toArray() { - // TODO Auto-generated method stub - return null; - } + public int size() { + try { + return db.exec("SELECT count(*) FROM "+table, new SQLResultHandler(){ + public Integer handleQueryResult(Statement stmt, ResultSet rs) throws SQLException{ + if (rs.next()) + return rs.getInt(1); + return 0; + } + }); + } catch (Exception e) { + e.printStackTrace(MultiPrintStream.out); + } + return 0; + } - public E[] toArray(Object[] arg0) { - // TODO Auto-generated method stub - return null; - } + public E[] toArray() { + // TODO Auto-generated method stub + return null; + } + + public E[] toArray(Object[] arg0) { + // TODO Auto-generated method stub + return null; + } } diff --git a/src/zutil/db/SQLQuery.java b/src/zutil/db/SQLQuery.java index e14b363..7c22e6c 100644 --- a/src/zutil/db/SQLQuery.java +++ b/src/zutil/db/SQLQuery.java @@ -32,393 +32,393 @@ import java.util.LinkedList; * @author Ziver */ public class SQLQuery { - protected static abstract class SQLQueryItem{ - SQLQueryItem root; - - protected SQLQueryItem(){} - - protected void setRoot(SQLQueryItem root){ - this.root = root; - } - - protected abstract void build(StringBuilder query); - - public String toString(){ - StringBuilder query = new StringBuilder(); - root.build(query); - return query.toString(); - } - } + protected static abstract class SQLQueryItem{ + SQLQueryItem root; - //******************************************* - // Main Types - /** - * - * SELECT - * [ALL | DISTINCT | DISTINCTROW ] - * [FROM table_references - * [WHERE where_condition] - * [GROUP BY {col_name | expr | position} - * [ASC | DESC], ... [WITH ROLLUP]] - * [HAVING where_condition] - * [ORDER BY {col_name | expr | position} - * [ASC | DESC], ...] - * [LIMIT {[offset,] row_count | row_count OFFSET offset}] - * - */ - public static class SQLSelect extends SQLQueryItem{ - String[] params; - SQLFrom from; + protected SQLQueryItem(){} - /** - * @param params is the columns that you want out of the SELECT query, leave empty for all columns - */ - protected SQLSelect(String ...params ){ - setRoot(this); - this.params = params; - } - - protected void build(StringBuilder query) { - query.append("SELECT "); - if( params == null || params.length <= 0 ) - query.append("*"); - else{ - for(int i=0; i - * UPDATE [LOW_PRIORITY] [IGNORE] table_reference - * SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ... - * [WHERE where_condition] - * [ORDER BY ...] - * [LIMIT row_count] - * - */ - public static class SQLUpdate extends SQLQueryItem{ - protected SQLUpdate(){ - setRoot(this); - } - - protected void build(StringBuilder query) { - - } - } - - /* - * - * INSERT [INTO] tbl_name - * SET col_name={expr | DEFAULT}, ... - * - * INSERT [INTO] tbl_name [(col_name,...)] - * {VALUES | VALUE} ({expr | DEFAULT},...),(...),... - * - */ - public static class SQLInsert extends SQLQueryItem{ - protected SQLInsert(){ - setRoot(this); - } - - protected void build(StringBuilder query) { - - } - } - - /* - * - * DELETE FROM tbl_name - * [WHERE where_condition] - * [ORDER BY ...] - * [LIMIT row_count] - * - */ - public static class SQLDelete extends SQLQueryItem{ - protected SQLDelete(){ - setRoot(this); - } - - protected void build(StringBuilder query) { - - } - } - - //******************************************* - // Sub Types - public static class SQLFrom extends SQLQueryItem{ - LinkedList tables = new LinkedList(); - SQLQueryItem next; + protected void setRoot(SQLQueryItem root){ + this.root = root; + } + + protected abstract void build(StringBuilder query); + + public String toString(){ + StringBuilder query = new StringBuilder(); + root.build(query); + return query.toString(); + } + } + + //******************************************* + // Main Types + /** + * + * SELECT + * [ALL | DISTINCT | DISTINCTROW ] + * [FROM table_references + * [WHERE where_condition] + * [GROUP BY {col_name | expr | position} + * [ASC | DESC], ... [WITH ROLLUP]] + * [HAVING where_condition] + * [ORDER BY {col_name | expr | position} + * [ASC | DESC], ...] + * [LIMIT {[offset,] row_count | row_count OFFSET offset}] + * + */ + public static class SQLSelect extends SQLQueryItem{ + String[] params; + SQLFrom from; + + /** + * @param params is the columns that you want out of the SELECT query, leave empty for all columns + */ + protected SQLSelect(String ...params ){ + setRoot(this); + this.params = params; + } + + protected void build(StringBuilder query) { + query.append("SELECT "); + if( params == null || params.length <= 0 ) + query.append("*"); + else{ + for(int i=0; i + * UPDATE [LOW_PRIORITY] [IGNORE] table_reference + * SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ... + * [WHERE where_condition] + * [ORDER BY ...] + * [LIMIT row_count] + * + */ + public static class SQLUpdate extends SQLQueryItem{ + protected SQLUpdate(){ + setRoot(this); + } + + protected void build(StringBuilder query) { + + } + } + + /* + * + * INSERT [INTO] tbl_name + * SET col_name={expr | DEFAULT}, ... + * + * INSERT [INTO] tbl_name [(col_name,...)] + * {VALUES | VALUE} ({expr | DEFAULT},...),(...),... + * + */ + public static class SQLInsert extends SQLQueryItem{ + protected SQLInsert(){ + setRoot(this); + } + + protected void build(StringBuilder query) { + + } + } + + /* + * + * DELETE FROM tbl_name + * [WHERE where_condition] + * [ORDER BY ...] + * [LIMIT row_count] + * + */ + public static class SQLDelete extends SQLQueryItem{ + protected SQLDelete(){ + setRoot(this); + } + + protected void build(StringBuilder query) { + + } + } + + //******************************************* + // Sub Types + public static class SQLFrom extends SQLQueryItem{ + LinkedList tables = new LinkedList(); + SQLQueryItem next; + + protected SQLFrom(SQLQueryItem root, String ...tables){ + setRoot(root); + for( String table : tables ) + this.tables.add(table); + } + + public SQLFrom NATURAL_JOIN(String table){ + return joinLastTable("NATURAL JOIN", table); + } + public SQLFrom NATURAL_JOIN(String ...tables){ + return joinTable("NATURAL JOIN", tables); + } + + public SQLFrom JOIN(String table){ + return joinLastTable("JOIN", table); + } + public SQLFrom JOIN(String ...tables){ + return joinTable("JOIN", tables); + } + + public SQLFrom UNION(String table){ + return joinLastTable("UNION", table); + } + public SQLFrom UNION(String ...tables){ + return joinTable("UNION", tables); + } + + 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()); + return this; + } + + private SQLFrom joinTable(String type, String[] tables){ + if( tables.length < 2 ) + return this; + StringBuilder str = new StringBuilder(); + for(int i=0; i conds = new LinkedList(); + SQLQueryItem next; + + protected SQLWhere(SQLQueryItem root){ + setRoot(root); + } + + /** + * Equals (arg1 = arg2) + */ + public SQLWhere EQ(String arg1, String arg2){ + return cond("=", arg1, arg2); + } + /** + * Not Equal (arg1 != arg2) + */ + public SQLWhere NE(String arg1, String arg2){ + return cond("!=", arg1, arg2); + } + /** + * Less than (arg1 < arg2) + */ + public SQLWhere LT(String arg1, String arg2){ + return cond("<", arg1, arg2); + } + /** + * Greater than (arg1 > arg2) + */ + public SQLWhere GT(String arg1, String arg2){ + return cond(">", arg1, arg2); + } + /** + * Less than or equal (arg1 <= arg2) + */ + public SQLWhere LE(String arg1, String arg2){ + return cond("<=", arg1, arg2); + } + /** + * Greater than or equal (arg1 >= arg2) + */ + public SQLWhere GE(String arg1, String arg2){ + return cond(">=", arg1, arg2); + } + + 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()); + return this; + } + + + public SQLGroupBy GROUP_BY( String ...cols ){ + return (SQLGroupBy) (next = new SQLGroupBy(root, cols)); + } + public SQLOrderBy ORDER_BY( String ...cols ){ + return (SQLOrderBy) (next = new SQLOrderBy(root, cols)); + } + public SQLLimit LIMIT( long count ){ + return (SQLLimit) (next = new SQLLimit(root, count)); + } + + protected void build(StringBuilder query) { + query.append(" WHERE "); + if( conds.isEmpty() ) + throw new RuntimeException("The WHERE query item must hav atleast 1 condition!"); + for(int i=0; i extends SQLQueryItem{ + protected String[] cols; + protected String end; + SQLQueryItem next; + + protected SQLGroupOrderBy(SQLQueryItem root, String ...cols){ + setRoot(root); + this.cols = cols; + } + + @SuppressWarnings("unchecked") + public T ASC(){ + end = "ASC"; + return (T)this; + } + @SuppressWarnings("unchecked") + public T DESC(){ + end = "DESC"; + return (T)this; + } + + protected void build(String op, StringBuilder query) { + query.append(' ').append(op).append(' '); + if( cols == null || cols.length <= 0 ) + throw new RuntimeException("The "+op+" query item must hav atleast 1 column!"); + for(int i=0; i{ + + protected SQLGroupBy(SQLQueryItem root, String ...cols){ + super( root, cols ); + } + + + public SQLOrderBy ORDER_BY( String ...cols ){ + return (SQLOrderBy) (next = new SQLOrderBy(root, cols)); + } + public SQLLimit LIMIT( long count ){ + return (SQLLimit) (next = new SQLLimit(root, count)); + } + + protected void build(StringBuilder query) { + build("GROUP BY", query); + } + } + public static class SQLOrderBy extends SQLGroupOrderBy{ + + protected SQLOrderBy(SQLQueryItem root, String ...cols){ + super( root, cols ); + } + + + public SQLLimit LIMIT( long count ){ + return (SQLLimit) (next = new SQLLimit(root, count)); + } + + protected void build(StringBuilder query) { + build("ORDER BY", query); + } + } + + public static class SQLLimit extends SQLQueryItem{ + long start; + Long count; + + protected SQLLimit(SQLQueryItem root, long start){ + setRoot( root ); + this.start = start; + } + + public SQLLimit TO( long count ){ + this.count = count; + return this; + } + + protected void build(StringBuilder query) { + query.append(" LIMIT ").append( start ); + if( count != null ) query.append(' ').append( count ); + } + } + + //******************************************* + public static SQLSelect SELECT( String ...params ){ + return new SQLSelect( params ); + } + + public static SQLUpdate UPDATE(){ + return new SQLUpdate(); + } + + public static SQLInsert INSERT(){ + return new SQLInsert(); + } + + public static SQLDelete DELETE(){ + return new SQLDelete(); + } - protected SQLFrom(SQLQueryItem root, String ...tables){ - setRoot(root); - for( String table : tables ) - this.tables.add(table); - } - - public SQLFrom NATURAL_JOIN(String table){ - return joinLastTable("NATURAL JOIN", table); - } - public SQLFrom NATURAL_JOIN(String ...tables){ - return joinTable("NATURAL JOIN", tables); - } - - public SQLFrom JOIN(String table){ - return joinLastTable("JOIN", table); - } - public SQLFrom JOIN(String ...tables){ - return joinTable("JOIN", tables); - } - - public SQLFrom UNION(String table){ - return joinLastTable("UNION", table); - } - public SQLFrom UNION(String ...tables){ - return joinTable("UNION", tables); - } - - 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()); - return this; - } - - private SQLFrom joinTable(String type, String[] tables){ - if( tables.length < 2 ) - return this; - StringBuilder str = new StringBuilder(); - for(int i=0; i conds = new LinkedList(); - SQLQueryItem next; - - protected SQLWhere(SQLQueryItem root){ - setRoot(root); - } - - /** - * Equals (arg1 = arg2) - */ - public SQLWhere EQ(String arg1, String arg2){ - return cond("=", arg1, arg2); - } - /** - * Not Equal (arg1 != arg2) - */ - public SQLWhere NE(String arg1, String arg2){ - return cond("!=", arg1, arg2); - } - /** - * Less than (arg1 < arg2) - */ - public SQLWhere LT(String arg1, String arg2){ - return cond("<", arg1, arg2); - } - /** - * Greater than (arg1 > arg2) - */ - public SQLWhere GT(String arg1, String arg2){ - return cond(">", arg1, arg2); - } - /** - * Less than or equal (arg1 <= arg2) - */ - public SQLWhere LE(String arg1, String arg2){ - return cond("<=", arg1, arg2); - } - /** - * Greater than or equal (arg1 >= arg2) - */ - public SQLWhere GE(String arg1, String arg2){ - return cond(">=", arg1, arg2); - } - - 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()); - return this; - } - - - public SQLGroupBy GROUP_BY( String ...cols ){ - return (SQLGroupBy) (next = new SQLGroupBy(root, cols)); - } - public SQLOrderBy ORDER_BY( String ...cols ){ - return (SQLOrderBy) (next = new SQLOrderBy(root, cols)); - } - public SQLLimit LIMIT( long count ){ - return (SQLLimit) (next = new SQLLimit(root, count)); - } - - protected void build(StringBuilder query) { - query.append(" WHERE "); - if( conds.isEmpty() ) - throw new RuntimeException("The WHERE query item must hav atleast 1 condition!"); - for(int i=0; i extends SQLQueryItem{ - protected String[] cols; - protected String end; - SQLQueryItem next; - - protected SQLGroupOrderBy(SQLQueryItem root, String ...cols){ - setRoot(root); - this.cols = cols; - } - - @SuppressWarnings("unchecked") - public T ASC(){ - end = "ASC"; - return (T)this; - } - @SuppressWarnings("unchecked") - public T DESC(){ - end = "DESC"; - return (T)this; - } - - protected void build(String op, StringBuilder query) { - query.append(' ').append(op).append(' '); - if( cols == null || cols.length <= 0 ) - throw new RuntimeException("The "+op+" query item must hav atleast 1 column!"); - for(int i=0; i{ - - protected SQLGroupBy(SQLQueryItem root, String ...cols){ - super( root, cols ); - } - - - public SQLOrderBy ORDER_BY( String ...cols ){ - return (SQLOrderBy) (next = new SQLOrderBy(root, cols)); - } - public SQLLimit LIMIT( long count ){ - return (SQLLimit) (next = new SQLLimit(root, count)); - } - - protected void build(StringBuilder query) { - build("GROUP BY", query); - } - } - public static class SQLOrderBy extends SQLGroupOrderBy{ - - protected SQLOrderBy(SQLQueryItem root, String ...cols){ - super( root, cols ); - } - - - public SQLLimit LIMIT( long count ){ - return (SQLLimit) (next = new SQLLimit(root, count)); - } - - protected void build(StringBuilder query) { - build("ORDER BY", query); - } - } - - public static class SQLLimit extends SQLQueryItem{ - long start; - Long count; - - protected SQLLimit(SQLQueryItem root, long start){ - setRoot( root ); - this.start = start; - } - - public SQLLimit TO( long count ){ - this.count = count; - return this; - } - - protected void build(StringBuilder query) { - query.append(" LIMIT ").append( start ); - if( count != null ) query.append(' ').append( count ); - } - } - - //******************************************* - public static SQLSelect SELECT( String ...params ){ - return new SQLSelect( params ); - } - - public static SQLUpdate UPDATE(){ - return new SQLUpdate(); - } - - public static SQLInsert INSERT(){ - return new SQLInsert(); - } - - public static SQLDelete DELETE(){ - return new SQLDelete(); - } - } diff --git a/src/zutil/db/SQLResultHandler.java b/src/zutil/db/SQLResultHandler.java index b6caae1..c734aa4 100644 --- a/src/zutil/db/SQLResultHandler.java +++ b/src/zutil/db/SQLResultHandler.java @@ -29,11 +29,11 @@ import java.sql.SQLException; import java.sql.Statement; public interface SQLResultHandler { - /** - * Is called to handle an result from an query. - * - * @param stmt is the query - * @param result is the ResultSet - */ - public T handleQueryResult(Statement stmt, ResultSet result) throws SQLException; + /** + * Is called to handle an result from an query. + * + * @param stmt is the query + * @param result is the ResultSet + */ + public T handleQueryResult(Statement stmt, ResultSet result) throws SQLException; } diff --git a/src/zutil/db/bean/DBBeanConfig.java b/src/zutil/db/bean/DBBeanConfig.java index b9fd86e..a51c212 100755 --- a/src/zutil/db/bean/DBBeanConfig.java +++ b/src/zutil/db/bean/DBBeanConfig.java @@ -40,7 +40,7 @@ class DBBeanConfig{ private static HashMap beanConfigs = new HashMap<>(); - /** The name of the table in the DB **/ + /** The name of the table in the DB **/ private String tableName; /** The name of the id column **/ private String idColumnName; diff --git a/src/zutil/db/bean/DBBeanSQLResultHandler.java b/src/zutil/db/bean/DBBeanSQLResultHandler.java index 6af324e..f0fb754 100755 --- a/src/zutil/db/bean/DBBeanSQLResultHandler.java +++ b/src/zutil/db/bean/DBBeanSQLResultHandler.java @@ -39,111 +39,111 @@ import java.util.logging.Logger; public class DBBeanSQLResultHandler implements SQLResultHandler{ - private static final Logger logger = LogUtil.getLogger(); - - private Class beanClass; - private DBBeanConfig beanConfig; - private DBConnection db; - private boolean list; + private static final Logger logger = LogUtil.getLogger(); + + private Class beanClass; + private DBBeanConfig beanConfig; + private DBConnection db; + private boolean list; - /** - * Creates a new instance of this class that returns only one bean - * - * @param cl is the DBBean class that will be parsed from the SQL result - * @return a new instance of this class - */ - public static DBBeanSQLResultHandler create(Class cl){ - return new DBBeanSQLResultHandler<>(cl, null, false); - } + /** + * Creates a new instance of this class that returns only one bean + * + * @param cl is the DBBean class that will be parsed from the SQL result + * @return a new instance of this class + */ + public static DBBeanSQLResultHandler create(Class cl){ + return new DBBeanSQLResultHandler<>(cl, null, false); + } - /** - * Creates a new instance of this class that returns a bean with all its containing beans - * - * @param cl is the DBBean class that will be parsed from the SQL result - * @param db is the DB connection for loading internal beans - * @return a new instance of this class - */ - public static DBBeanSQLResultHandler create(Class cl, DBConnection db){ - return new DBBeanSQLResultHandler<>(cl, db, false); - } + /** + * Creates a new instance of this class that returns a bean with all its containing beans + * + * @param cl is the DBBean class that will be parsed from the SQL result + * @param db is the DB connection for loading internal beans + * @return a new instance of this class + */ + public static DBBeanSQLResultHandler create(Class cl, DBConnection db){ + return new DBBeanSQLResultHandler<>(cl, db, false); + } - /** - * Creates a new instance of this class that returns a list of beans - * - * @param cl is the DBBean class that will be parsed from the SQL result - * @return a new instance of this class - */ - public static DBBeanSQLResultHandler> createList(Class cl){ - return new DBBeanSQLResultHandler<>(cl, null, true); - } + /** + * Creates a new instance of this class that returns a list of beans + * + * @param cl is the DBBean class that will be parsed from the SQL result + * @return a new instance of this class + */ + public static DBBeanSQLResultHandler> createList(Class cl){ + return new DBBeanSQLResultHandler<>(cl, null, true); + } - /** - * Creates a new instance of this class that returns a list of beans with all the internal beans - * - * @param cl is the DBBean class that will be parsed from the SQL result - * @param db is the DB connection for loading internal beans - * @return a new instance of this class - */ - public static DBBeanSQLResultHandler> createList(Class cl, DBConnection db){ - return new DBBeanSQLResultHandler<>(cl, db, true); - } + /** + * Creates a new instance of this class that returns a list of beans with all the internal beans + * + * @param cl is the DBBean class that will be parsed from the SQL result + * @param db is the DB connection for loading internal beans + * @return a new instance of this class + */ + public static DBBeanSQLResultHandler> createList(Class cl, DBConnection db){ + return new DBBeanSQLResultHandler<>(cl, db, true); + } - /** - * Creates a new instance of this class - * - * @param cl is the DBBean class that will be parsed from the SQL result - * @param db is the DB connection for loading internal beans, may be null to disable internal beans - * @param list is if the handler should return a list of beans instead of one - */ - protected DBBeanSQLResultHandler(Class cl, DBConnection db, boolean list) { - this.beanClass = cl; - this.list = list; - this.db = db; - this.beanConfig = DBBeanConfig.getBeanConfig( cl ); - } + /** + * Creates a new instance of this class + * + * @param cl is the DBBean class that will be parsed from the SQL result + * @param db is the DB connection for loading internal beans, may be null to disable internal beans + * @param list is if the handler should return a list of beans instead of one + */ + protected DBBeanSQLResultHandler(Class cl, DBConnection db, boolean list) { + this.beanClass = cl; + this.list = list; + this.db = db; + this.beanConfig = DBBeanConfig.getBeanConfig( cl ); + } - /** - * Is called to handle a result from a query. - * - * @param stmt is the query - * @param result is the ResultSet - */ - @SuppressWarnings("unchecked") - public T handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ - if( list ){ - List bean_list = new LinkedList<>(); - while( result.next() ){ - DBBean obj = createBean(result); - bean_list.add( obj ); - } - return (T) bean_list; - } - else{ - if( result.next() ){ - return (T) createBean(result); - } - return null; - } + /** + * Is called to handle a result from a query. + * + * @param stmt is the query + * @param result is the ResultSet + */ + @SuppressWarnings("unchecked") + public T handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ + if( list ){ + List bean_list = new LinkedList<>(); + while( result.next() ){ + DBBean obj = createBean(result); + bean_list.add( obj ); + } + return (T) bean_list; + } + else{ + if( result.next() ){ + return (T) createBean(result); + } + return null; + } - } - - - /** - * Instantiates a new bean and assigns field values from the ResultSet - * - * @param result is where the field values for the bean will bee read from, the cursor should be in front of the data - * @return a new instance of the bean - */ - private DBBean createBean(ResultSet result) throws SQLException{ - try { - Long id = result.getLong( "id" ); - // Check cache first - DBBean obj = DBBeanCache.get(beanClass, id); - if ( obj == null ) { + } + + + /** + * Instantiates a new bean and assigns field values from the ResultSet + * + * @param result is where the field values for the bean will bee read from, the cursor should be in front of the data + * @return a new instance of the bean + */ + private DBBean createBean(ResultSet result) throws SQLException{ + try { + Long id = result.getLong( "id" ); + // Check cache first + DBBean obj = DBBeanCache.get(beanClass, id); + if ( obj == null ) { // Cache miss create a new bean logger.fine("Creating new Bean(" + beanClass.getName() + ") with id: " + id); obj = beanClass.newInstance(); @@ -155,23 +155,23 @@ public class DBBeanSQLResultHandler implements SQLResultHandler{ logger.finer("Bean(" + beanClass.getName() + ") cache to old for id: " + id); updateBean(result, obj); } - return obj; - } catch (SQLException e) { - throw e; - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** - * Updates an existing bean and assigns field values from the ResultSet - * - * @param result is where the field values for the bean will be read from, the cursor should be in front of the data - * @param obj is the bean that will be updated - */ - @SuppressWarnings("unchecked") - private void updateBean(ResultSet result, DBBean obj) throws SQLException{ - if (obj.readLock.tryLock()) { + return obj; + } catch (SQLException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Updates an existing bean and assigns field values from the ResultSet + * + * @param result is where the field values for the bean will be read from, the cursor should be in front of the data + * @param obj is the bean that will be updated + */ + @SuppressWarnings("unchecked") + private void updateBean(ResultSet result, DBBean obj) throws SQLException{ + if (obj.readLock.tryLock()) { try { logger.fine("Updating Bean("+ beanClass.getName() +") with id: "+ obj.getId()); // Read fields @@ -198,25 +198,25 @@ public class DBBeanSQLResultHandler implements SQLResultHandler{ DBBeanCache.add(obj); // Read sub beans - if (db != null) { - for (DBBeanSubBeanConfig subBeanField : beanConfig.getSubBeans()) { - DBBeanConfig subBeanConfig = subBeanField.getSubBeanConfig(); + if (db != null) { + for (DBBeanSubBeanConfig subBeanField : beanConfig.getSubBeans()) { + DBBeanConfig subBeanConfig = subBeanField.getSubBeanConfig(); - // Load List from link table - String subSql = "SELECT subBeanTable.* FROM "+ + // Load List from link table + String subSql = "SELECT subBeanTable.* FROM "+ subBeanField.getLinkTableName() +" as linkTable, "+ subBeanConfig.getTableName() +" as subBeanTable " + "WHERE linkTable."+subBeanField.getParentIdColumnName()+"=? AND " + "linkTable."+subBeanConfig.getIdColumnName()+"=subBeanTable."+subBeanConfig.getIdColumnName(); - logger.finest("List Load Query: " + subSql); - PreparedStatement subStmt = db.getPreparedStatement(subSql); - subStmt.setObject(1, obj.getId()); - List list = DBConnection.exec(subStmt, - DBBeanSQLResultHandler.createList(subBeanField.getSubBeanClass(), db)); + logger.finest("List Load Query: " + subSql); + PreparedStatement subStmt = db.getPreparedStatement(subSql); + subStmt.setObject(1, obj.getId()); + List list = DBConnection.exec(subStmt, + DBBeanSQLResultHandler.createList(subBeanField.getSubBeanClass(), db)); subBeanField.setValue(obj, list); - } - } else - logger.warning("No DB available to read sub beans"); + } + } else + logger.warning("No DB available to read sub beans"); // Call post listener obj.postUpdateAction(); @@ -227,7 +227,7 @@ public class DBBeanSQLResultHandler implements SQLResultHandler{ obj.readLock.lock(); obj.readLock.unlock(); } - } + } + - } diff --git a/src/zutil/db/handler/ListSQLResult.java b/src/zutil/db/handler/ListSQLResult.java index 727a113..81ce4ed 100755 --- a/src/zutil/db/handler/ListSQLResult.java +++ b/src/zutil/db/handler/ListSQLResult.java @@ -41,27 +41,27 @@ import java.util.List; */ public class ListSQLResult implements SQLResultHandler> { - private List list; + private List list; - /** - * Creates a new List. - */ - public ListSQLResult(){ - this.list = new ArrayList<>(); - } + /** + * Creates a new List. + */ + public ListSQLResult(){ + this.list = new ArrayList<>(); + } - /** - * Uses a existing list that items will be appended on. - */ - public ListSQLResult(List l){ - this.list = l; - } - - + /** + * Uses a existing list that items will be appended on. + */ + public ListSQLResult(List l){ + this.list = l; + } - public List handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ - while( result.next() ) - list.add((T)result.getObject(1)); - return list; - } + + + public List handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ + while( result.next() ) + list.add((T)result.getObject(1)); + return list; + } } diff --git a/src/zutil/db/handler/PropertiesSQLResult.java b/src/zutil/db/handler/PropertiesSQLResult.java index 28f5005..7339163 100755 --- a/src/zutil/db/handler/PropertiesSQLResult.java +++ b/src/zutil/db/handler/PropertiesSQLResult.java @@ -40,30 +40,30 @@ import java.util.Properties; * @author Ziver */ public class PropertiesSQLResult implements SQLResultHandler { - - private Properties prop; - - /** - * Creates a new Properties object to be filled - */ - public PropertiesSQLResult(){ - this.prop = new Properties(); - } - - /** - * Adds data to a existing Properties object - */ - public PropertiesSQLResult(Properties p){ - this.prop = p; - } - - - /** - * Is called to handle an result from an query. - */ - public Properties handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ - while( result.next() ) - prop.setProperty(result.getString(1), result.getString(2)); - return prop; - } + + private Properties prop; + + /** + * Creates a new Properties object to be filled + */ + public PropertiesSQLResult(){ + this.prop = new Properties(); + } + + /** + * Adds data to a existing Properties object + */ + public PropertiesSQLResult(Properties p){ + this.prop = p; + } + + + /** + * Is called to handle an result from an query. + */ + public Properties handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ + while( result.next() ) + prop.setProperty(result.getString(1), result.getString(2)); + return prop; + } } diff --git a/src/zutil/db/handler/SimpleSQLResult.java b/src/zutil/db/handler/SimpleSQLResult.java index e30949e..39a5df4 100755 --- a/src/zutil/db/handler/SimpleSQLResult.java +++ b/src/zutil/db/handler/SimpleSQLResult.java @@ -36,16 +36,16 @@ import java.sql.Statement; * @author Ziver */ public class SimpleSQLResult implements SQLResultHandler { - /** - * Is called to handle an result from an query. - * - * @param stmt is the query - * @param result is the ResultSet - */ - @SuppressWarnings("unchecked") - public T handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ - if( result.next() ) - return (T) result.getObject(1); - return null; - } + /** + * Is called to handle an result from an query. + * + * @param stmt is the query + * @param result is the ResultSet + */ + @SuppressWarnings("unchecked") + public T handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ + if( result.next() ) + return (T) result.getObject(1); + return null; + } } diff --git a/src/zutil/image/ImageFilterProcessor.java b/src/zutil/image/ImageFilterProcessor.java index 99e0be6..f8eb568 100644 --- a/src/zutil/image/ImageFilterProcessor.java +++ b/src/zutil/image/ImageFilterProcessor.java @@ -37,163 +37,163 @@ import java.awt.image.BufferedImage; * @author Ziver */ public abstract class ImageFilterProcessor { - private BufferedImage img; - private ProgressListener progress; + private BufferedImage img; + private ProgressListener progress; - public ImageFilterProcessor(BufferedImage img){ - this.img = img; - } - - /** - * Sets the listener - * @param listener is the listener, null to disable the progress - */ - public void setProgressListener(ProgressListener listener){ - this.progress = listener; - } - - /** - * Returns the listener - */ - public ProgressListener getProgressListener(){ - return this.progress; - } - - /** - * Sets the progress in percent - */ - protected void setProgress(double percent){ - if(progress != null) progress.progressUpdate(this, null, percent); - } - - /** - * Applies a effect to a given image - * - * @param effect The effect to use - * @param img The image to process - * @return The processed image - */ - public static ImageFilterProcessor getProcessor(String effect, BufferedImage img) throws InstantiationException, IllegalAccessException, ClassNotFoundException, InterruptedException{ - ImageFilterProcessor processor = (ImageFilterProcessor)Class.forName(effect).newInstance(); - processor.img = img; - return processor; - } + public ImageFilterProcessor(BufferedImage img){ + this.img = img; + } - /** - * Adds the chosen effect to the image - * - * @return The Image with the effect - */ - public BufferedImage process() throws InterruptedException{ - int cols = img.getWidth(); - int rows = img.getHeight(); + /** + * Sets the listener + * @param listener is the listener, null to disable the progress + */ + public void setProgressListener(ProgressListener listener){ + this.progress = listener; + } - if(cols < 0 || rows < 0){ - throw new InterruptedException("Image not Loaded!!!"); - } + /** + * Returns the listener + */ + public ProgressListener getProgressListener(){ + return this.progress; + } - // converts the img to raw data - int[][][] data = convertToArray(img, cols, rows); - //processes the image - data = process(data); - //converts back the image - return convertToImage(data, data[0].length, data.length); - } + /** + * Sets the progress in percent + */ + protected void setProgress(double percent){ + if(progress != null) progress.progressUpdate(this, null, percent); + } - /** - * Creates a Integer array with the pixel data of the image - * int[row][col][4] - * 0 -> Alpha data - * Red data - * Green data - * 4 -> Blue data - * - * @param img is the image to convert - * @param cols is the columns of the image - * @param rows is the rows of the image - * @return A is the integer array - */ - public static int[][][] convertToArray(BufferedImage img, int cols, int rows) throws InterruptedException{ - int[][][] data = new int[rows][cols][4]; - // Reads in the image to a one dim array - int[] pixels = img.getRGB(0, 0, cols, rows, null, 0, cols); + /** + * Applies a effect to a given image + * + * @param effect The effect to use + * @param img The image to process + * @return The processed image + */ + public static ImageFilterProcessor getProcessor(String effect, BufferedImage img) throws InstantiationException, IllegalAccessException, ClassNotFoundException, InterruptedException{ + ImageFilterProcessor processor = (ImageFilterProcessor)Class.forName(effect).newInstance(); + processor.img = img; + return processor; + } - // Read the pixel data and put it in the data array - for(int y=0; y> 24) & 0xFF); - //Red data - data[y][x][1] = ((aRow[x] >> 16) & 0xFF); - //Green data - data[y][x][2] = ((aRow[x] >> 8) & 0xFF); - //Blue data - data[y][x][3] = ((aRow[x])& 0xFF); - } - } - return data; - } + if(cols < 0 || rows < 0){ + throw new InterruptedException("Image not Loaded!!!"); + } + + // converts the img to raw data + int[][][] data = convertToArray(img, cols, rows); + //processes the image + data = process(data); + //converts back the image + return convertToImage(data, data[0].length, data.length); + } + + /** + * Creates a Integer array with the pixel data of the image + * int[row][col][4] + * 0 -> Alpha data + * Red data + * Green data + * 4 -> Blue data + * + * @param img is the image to convert + * @param cols is the columns of the image + * @param rows is the rows of the image + * @return A is the integer array + */ + public static int[][][] convertToArray(BufferedImage img, int cols, int rows) throws InterruptedException{ + int[][][] data = new int[rows][cols][4]; + // Reads in the image to a one dim array + int[] pixels = img.getRGB(0, 0, cols, rows, null, 0, cols); + + // Read the pixel data and put it in the data array + for(int y=0; y> 24) & 0xFF); + //Red data + data[y][x][1] = ((aRow[x] >> 16) & 0xFF); + //Green data + data[y][x][2] = ((aRow[x] >> 8) & 0xFF); + //Blue data + data[y][x][3] = ((aRow[x])& 0xFF); + } + } + return data; + } - /** - * Converts a pixel data array to a java Image object - * - * @param pixels is the pixel data array - * @param cols is the columns of the image - * @param rows is the rows of the image - * @return A Image - */ - public static BufferedImage convertToImage(int[][][] pixels, int cols, int rows){ - int[] data = new int[cols * rows * 4]; + /** + * Converts a pixel data array to a java Image object + * + * @param pixels is the pixel data array + * @param cols is the columns of the image + * @param rows is the rows of the image + * @return A Image + */ + public static BufferedImage convertToImage(int[][][] pixels, int cols, int rows){ + int[] data = new int[cols * rows * 4]; - //Move the data into the 1D array. Note the - // use of the bitwise OR operator and the - // bitwise left-shift operators to put the - // four 8-bit bytes into each int. - int index = 0; - for(int y=0; y height){ - scale_width = scale_height; - }else{ - scale_height = scale_width; - } - } + // aspect calculation + if(keep_aspect){ + if(scale_width * source.getHeight() > height){ + scale_width = scale_height; + }else{ + scale_height = scale_width; + } + } - BufferedImage tmp = new BufferedImage( - (int)(scale_width * source.getWidth()), - (int)(scale_height * source.getHeight()), - BufferedImage.TYPE_INT_RGB); - Graphics2D g2d = tmp.createGraphics(); + BufferedImage tmp = new BufferedImage( + (int)(scale_width * source.getWidth()), + (int)(scale_height * source.getHeight()), + BufferedImage.TYPE_INT_RGB); + Graphics2D g2d = tmp.createGraphics(); - AffineTransform at = AffineTransform.getScaleInstance(scale_width, scale_height); - g2d.drawRenderedImage(source, at); - g2d.dispose(); - return tmp; - } + AffineTransform at = AffineTransform.getScaleInstance(scale_width, scale_height); + g2d.drawRenderedImage(source, at); + g2d.dispose(); + return tmp; + } - /** - * Crops a image to a specific aspect ration - * - * @param image is the actual image to crop - * @param aspect is the aspect ratio to convert the image to - * @return a new image with the specified aspect ratio - */ - public static BufferedImage cropToAspectRatio(BufferedImage image, float aspect){ - int x = 0, y = 0; - int width = image.getWidth(); - int height = image.getHeight(); + /** + * Crops a image to a specific aspect ration + * + * @param image is the actual image to crop + * @param aspect is the aspect ratio to convert the image to + * @return a new image with the specified aspect ratio + */ + public static BufferedImage cropToAspectRatio(BufferedImage image, float aspect){ + int x = 0, y = 0; + int width = image.getWidth(); + int height = image.getHeight(); - // Check if the width is larger than the heigth - if( width > height ){ - width = (int) (height * aspect); - x = image.getWidth()/2 - width/2; - } - else{ - height = (int) (width * aspect); - y = image.getHeight()/2 - height/2; - } + // Check if the width is larger than the heigth + if( width > height ){ + width = (int) (height * aspect); + x = image.getWidth()/2 - width/2; + } + else{ + height = (int) (width * aspect); + y = image.getHeight()/2 - height/2; + } - return image.getSubimage(x, y, width, height); - } + return image.getSubimage(x, y, width, height); + } - /** - * This function crops the image to the aspect ratio of - * the width and height and then scales the image to the - * given values - * - * @param source is the image to resize - * @param width is the wanted width - * @param height is the wanted height - * @return a new image with the specified width and height - */ - public static BufferedImage cropScale(BufferedImage source, int width, int height){ - float aspect = width/height; - BufferedImage tmp = cropToAspectRatio(source, aspect); - tmp = scale(tmp, width, height, false); - return tmp; - } + /** + * This function crops the image to the aspect ratio of + * the width and height and then scales the image to the + * given values + * + * @param source is the image to resize + * @param width is the wanted width + * @param height is the wanted height + * @return a new image with the specified width and height + */ + public static BufferedImage cropScale(BufferedImage source, int width, int height){ + float aspect = width/height; + BufferedImage tmp = cropToAspectRatio(source, aspect); + tmp = scale(tmp, width, height, false); + return tmp; + } } diff --git a/src/zutil/image/filter/BlurFilter.java b/src/zutil/image/filter/BlurFilter.java index 0edaeda..1b8ceb1 100755 --- a/src/zutil/image/filter/BlurFilter.java +++ b/src/zutil/image/filter/BlurFilter.java @@ -31,87 +31,87 @@ import zutil.math.ZMath; import java.awt.image.BufferedImage; public class BlurFilter extends ImageFilterProcessor{ - private int blurValue; + private int blurValue; - /** - * Creates a blur effect on the image - * @param img The image to blur - */ - public BlurFilter(BufferedImage img){ - this(img, 10); - } + /** + * Creates a blur effect on the image + * @param img The image to blur + */ + public BlurFilter(BufferedImage img){ + this(img, 10); + } - /** - * Creates a blur effect on the image - * @param img The image to blur - * @param blur The amount to blur - */ - public BlurFilter(BufferedImage img, int blur){ - super(img); - blurValue = blur; - } + /** + * Creates a blur effect on the image + * @param img The image to blur + * @param blur The amount to blur + */ + public BlurFilter(BufferedImage img, int blur){ + super(img); + blurValue = blur; + } - @Override - public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { - int inputPeak = RAWImageUtil.getPeakValue(data); + @Override + public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { + int inputPeak = RAWImageUtil.getPeakValue(data); - int[][][] tmpData = new int[data.length][data[0].length][4]; - int[][][] output = RAWImageUtil.copyArray(data); - //Perform the convolution one or more times in succession - int redSum, greenSum, blueSum, outputPeak; - for(int i=0; i 1) redScale = 1; - else if(redScale < 0) redScale = 0; + @Override + public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { + int[][][] output = new int[data.length][data[0].length][4]; + // making sure the scales are right + if(redScale > 1) redScale = 1; + else if(redScale < 0) redScale = 0; - if(greenScale > 1) greenScale = 1; - else if(greenScale < 0) greenScale = 0; + if(greenScale > 1) greenScale = 1; + else if(greenScale < 0) greenScale = 0; - if(blueScale > 1) blueScale = 1; - else if(blueScale < 0) blueScale = 0; - - // Applying the color intensity to the image - for(int y=startY; y 1) blueScale = 1; + else if(blueScale < 0) blueScale = 0; + + // Applying the color intensity to the image + for(int y=startY; y Alpha data - * Red data - * Green data - * 4 -> Blue data - */ - public DitheringFilter(BufferedImage img, int[][] palette){ - super(img); - this.palette = palette; - } + /** + * Sets up a default DitheringEffect + */ + public DitheringFilter(BufferedImage img){ + super(img); + } - @Override - public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { - int error, index; - int[] currentPixel; - int[][][] output = RAWImageUtil.copyArray(data); - - for(int y=startY; y Alpha data + * Red data + * Green data + * 4 -> Blue data + */ + public DitheringFilter(BufferedImage img, int[][] palette){ + super(img); + this.palette = palette; + } + + @Override + public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { + int error, index; + int[] currentPixel; + int[][][] output = RAWImageUtil.copyArray(data); + + for(int y=startY; y 0) + output[y+1][x-1][i] = RAWImageUtil.clip( output[y+1][x-1][i] + (error*3)/16 ); + output[y+1][x+0][i] = RAWImageUtil.clip( output[y+1][x+0][i] + (error*5)/16 ); + if (x + 1 < data[0].length) + output[y+1][x+1][i] = RAWImageUtil.clip( output[y+1][x+1][i] + (error*1)/16 ); + } + } + } + } + + return output; + } - for (int i = 1; i < 4; i++) { - error = currentPixel[i] - palette[index][i]; - if (x + 1 < output[0].length) { - output[y+0][x+1][i] = RAWImageUtil.clip( output[y+0][x+1][i] + (error*7)/16 ); - } - if (y + 1 < data.length) { - if (x - 1 > 0) - output[y+1][x-1][i] = RAWImageUtil.clip( output[y+1][x-1][i] + (error*3)/16 ); - output[y+1][x+0][i] = RAWImageUtil.clip( output[y+1][x+0][i] + (error*5)/16 ); - if (x + 1 < data[0].length) - output[y+1][x+1][i] = RAWImageUtil.clip( output[y+1][x+1][i] + (error*1)/16 ); - } - } - } - } - - return output; - } - private static int findNearestColor(int[] color, int[][] palette) { int minDistanceSquared = 255*255 + 255*255 + 255*255 + 1; int bestIndex = 0; diff --git a/src/zutil/image/filter/GaussianBlurFilter.java b/src/zutil/image/filter/GaussianBlurFilter.java index 0cb4733..a6d371a 100755 --- a/src/zutil/image/filter/GaussianBlurFilter.java +++ b/src/zutil/image/filter/GaussianBlurFilter.java @@ -32,40 +32,40 @@ import java.awt.image.BufferedImage; * @author Ziver */ public class GaussianBlurFilter extends ConvolutionFilter{ - private int size; - private double sigma; + private int size; + private double sigma; - public GaussianBlurFilter(BufferedImage img) { - this(img, 5, 1.4); - } - - public GaussianBlurFilter(BufferedImage img, int size, double sigma) { - super(img); - this.size = size; - this.sigma = sigma; - } + public GaussianBlurFilter(BufferedImage img) { + this(img, 5, 1.4); + } - protected double[][] generateKernel(){ - return gaussianFunction(size, size, sigma); - } - - /** - * Generates the kernel from the specified values - */ - public static double[][] gaussianFunction(int size_x, int size_y, double sigma){ - double[][] kernel; - int center_x = size_x/2; - int center_y = size_y/2; - - kernel = new double[size_y][size_x]; - for(int y=0; y= 0 && y+fy-edgeY < data.length && x+fx-edgeX >= 0 && x+fx-edgeX < data[0].length){ - //colorArray[fx][fy] := pixelvalue[x + fx - edgex][y + fy - edgey] - if(channels[0]) tmpArray[0][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][0] ) ]++; - if(channels[1]) tmpArray[1][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][1] ) ]++; - if(channels[2]) tmpArray[2][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][2] ) ]++; - if(channels[3]) tmpArray[3][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][3] ) ]++; - pixelCount++; - } - } - } + pixelCount = 0; + for(int fy=0; fy= 0 && y+fy-edgeY < data.length && x+fx-edgeX >= 0 && x+fx-edgeX < data[0].length){ + //colorArray[fx][fy] := pixelvalue[x + fx - edgex][y + fy - edgey] + if(channels[0]) tmpArray[0][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][0] ) ]++; + if(channels[1]) tmpArray[1][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][1] ) ]++; + if(channels[2]) tmpArray[2][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][2] ) ]++; + if(channels[3]) tmpArray[3][ getMedianIndex( tmpData[y + fy - edgeY][x + fx - edgeX][3] ) ]++; + pixelCount++; + } + } + } - if(channels[0]) tmpData[y][x][0] = findMedian(tmpArray[0], pixelCount/2); - if(channels[1]) tmpData[y][x][1] = findMedian(tmpArray[1], pixelCount/2); - if(channels[2]) tmpData[y][x][2] = findMedian(tmpArray[2], pixelCount/2); - if(channels[3]) tmpData[y][x][3] = findMedian(tmpArray[3], pixelCount/2); - } - } - - return tmpData; - } + if(channels[0]) tmpData[y][x][0] = findMedian(tmpArray[0], pixelCount/2); + if(channels[1]) tmpData[y][x][1] = findMedian(tmpArray[1], pixelCount/2); + if(channels[2]) tmpData[y][x][2] = findMedian(tmpArray[2], pixelCount/2); + if(channels[3]) tmpData[y][x][3] = findMedian(tmpArray[3], pixelCount/2); + } + } - private int getMedianIndex(int i){ - if(i < 0) return Math.abs(i); - else return i+256; - } + return tmpData; + } - private int findMedian(int[] median, int medianCount){ - int sum = 0; - int ret = 0; - for(int i=0; i= medianCount && ret == 0){ - ret = i-256; - } - } + private int getMedianIndex(int i){ + if(i < 0) return Math.abs(i); + else return i+256; + } - return ret; - } + private int findMedian(int[] median, int medianCount){ + int sum = 0; + int ret = 0; + for(int i=0; i= medianCount && ret == 0){ + ret = i-256; + } + } + + return ret; + } - class SortableARGB implements SortableDataList{ - private int[][][] data; - private int cols; - private int rows; - private int channel; + class SortableARGB implements SortableDataList{ + private int[][][] data; + private int cols; + private int rows; + private int channel; - public SortableARGB(int[][][] data, int cols, int rows, int channel){ - this.data = data; - this.cols = cols; - this.rows = rows; - this.channel = channel; - } + public SortableARGB(int[][][] data, int cols, int rows, int channel){ + this.data = data; + this.cols = cols; + this.rows = rows; + this.channel = channel; + } - public int compare(int a, int b) { - return compare(a, data[ getY(b) ][ getX(b) ][ channel ]); - } + public int compare(int a, int b) { + return compare(a, data[ getY(b) ][ getX(b) ][ channel ]); + } - public int compare(int a, Integer b) { - return ((Integer)data[ getY(a) ][ getX(a) ][ channel ]).compareTo(b); - } + public int compare(int a, Integer b) { + return ((Integer)data[ getY(a) ][ getX(a) ][ channel ]).compareTo(b); + } - public Integer get(int i) { - return data[ getY(i) ][ getX(i) ][ channel ]; - } - - public void set(int i, Integer o){ - data[ getY(i) ][ getX(i) ][ channel ] = o; - } + public Integer get(int i) { + return data[ getY(i) ][ getX(i) ][ channel ]; + } - public int size() { - return cols * rows; - } + public void set(int i, Integer o){ + data[ getY(i) ][ getX(i) ][ channel ] = o; + } - public void swap(int a, int b) { - int tmp = data[ getY(a) ][ getX(a) ][ channel ]; - data[ getY(a) ][ getX(a) ][ channel ] = data[ getY(b) ][ getX(b) ][ channel ]; - data[ getY(b) ][ getX(b) ][ channel ] = tmp; - } + public int size() { + return cols * rows; + } + + public void swap(int a, int b) { + int tmp = data[ getY(a) ][ getX(a) ][ channel ]; + data[ getY(a) ][ getX(a) ][ channel ] = data[ getY(b) ][ getX(b) ][ channel ]; + data[ getY(b) ][ getX(b) ][ channel ] = tmp; + } - private int getX(int a){ - return a % cols; - } + private int getX(int a){ + return a % cols; + } - private int getY(int a){ - return a / cols; - } + private int getY(int a){ + return a / cols; + } - } + } } diff --git a/src/zutil/image/filter/ResizeImage.java b/src/zutil/image/filter/ResizeImage.java index 232f4c4..5e1f9d7 100755 --- a/src/zutil/image/filter/ResizeImage.java +++ b/src/zutil/image/filter/ResizeImage.java @@ -30,58 +30,58 @@ import zutil.math.ZMath; import java.awt.image.BufferedImage; 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 - * - * @param img The image to resize - * @param w The new width - */ - public ResizeImage(BufferedImage img, int w){ - this(img, w, -1); - } - - /** - * Will create a ResizeImage object - * - * @param img The image to resize - * @param w The new width if -1 then it will be scaled whit aspect of the hight - * @param h The new height if -1 then it will be scaled whit aspect of the width - */ - public ResizeImage(BufferedImage img, int w, int h){ - super(img); - width = w; - height = h; - } - - @Override - public int[][][] process(final int[][][] data, int startX, int startY, int stopX, int stopY) { - if(width < 1){ - height = (int)(((double)width/(stopX-startX))*(stopY-startY)); - } - else if(height < 1){ - width = (int)(((double)height/(stopY-startY))*(stopX-startY)); - } - - newData = new int[height][width][4]; - double xScale = ((double)(stopX-startX)/width); - double yScale = ((double)(stopY-startY)/height); - - for(int y=0; y radius){ - scale = 0; - } - else{ - scale = 1-(distance/radius); - } - - output[y][x][0] = data[y][x][0]; - output[y][x][1] = RAWImageUtil.clip((int)(scale * data[y][x][1])); - output[y][x][2] = RAWImageUtil.clip((int)(scale * data[y][x][2])); - output[y][x][3] = RAWImageUtil.clip((int)(scale * data[y][x][3])); - } - } - return output; - } + /** + * Sets up a custom spotlight + * @param r The radius of the spotlight in pixels + */ + public SpotLightFilter(BufferedImage img, int r){ + this(img, r, -1, -1); + } + + /** + * Sets up a custom spotlight + * @param r The radius of the spotlight in pixels + * @param x The x position of the spotlight, if -1 then it will be centered + * @param y The y position of the spotlight, if -1 then it will be centered + */ + public SpotLightFilter(BufferedImage img, int r, int x, int y){ + super(img); + radius = r; + xPos = x; + yPos = y; + } + + @Override + public int[][][] process(int[][][] data, int startX, int startY, int stopX, int stopY) { + if(xPos < 0) xPos = data[0].length/2; + if(yPos < 0) yPos = data.length/2; + + int[][][] output = new int[data.length][data[0].length][4]; + + double scale, dx, dy, distance; + for(int y=startY; y radius){ + scale = 0; + } + else{ + scale = 1-(distance/radius); + } + + output[y][x][0] = data[y][x][0]; + output[y][x][1] = RAWImageUtil.clip((int)(scale * data[y][x][1])); + output[y][x][2] = RAWImageUtil.clip((int)(scale * data[y][x][2])); + output[y][x][3] = RAWImageUtil.clip((int)(scale * data[y][x][3])); + } + } + return output; + } } diff --git a/src/zutil/io/BufferedBoundaryInputStream.java b/src/zutil/io/BufferedBoundaryInputStream.java index 0ac5d09..5807baf 100755 --- a/src/zutil/io/BufferedBoundaryInputStream.java +++ b/src/zutil/io/BufferedBoundaryInputStream.java @@ -33,23 +33,23 @@ import java.io.InputStream; * until it gets to a boundary and will return -1 (end of stream). * The stream will not return any data until the {@link #next()} * method is called. - * + * * @author Ziver * */ public class BufferedBoundaryInputStream extends FilterInputStream{ - /** The size of the buffer in bytes */ - protected static final int DEFAULT_BUF_SIZE = 8192; + /** The size of the buffer in bytes */ + protected static final int DEFAULT_BUF_SIZE = 8192; - /** The raw buffer */ + /** The raw buffer */ private byte buffer[]; /** The current position in the buffer */ private int buf_pos = 0; - /** The end position of the buffer */ + /** The end position of the buffer */ private int buf_end = 0; /** Boundary position, 0< means no boundary found */ private int buf_bound_pos = -1; - /** The boundary (the delimiter) */ + /** The boundary (the delimiter) */ private byte[] boundary; /** The position in the buffer where user has marked, -1 if no mark is set **/ private int buf_mark = -1; @@ -57,77 +57,76 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ private int buf_mark_limit = 0; - /** - * Creates a instance of this class with a default buffer size of 64K - * - * @param in is the InputStream that the buffer will use - */ - public BufferedBoundaryInputStream(InputStream in){ - this(in, DEFAULT_BUF_SIZE); - } + /** + * Creates a instance of this class with a default buffer size of 64K + * + * @param in is the InputStream that the buffer will use + */ + public BufferedBoundaryInputStream(InputStream in){ + this(in, DEFAULT_BUF_SIZE); + } - /** - * Creates a instance of this class - * - * @param in is the InputStream that the buffer will use - * @param buf_size speifies the buffer size - */ - public BufferedBoundaryInputStream(InputStream in, int buf_size){ - super(in); - buffer = new byte[buf_size]; - } + /** + * Creates a instance of this class + * + * @param in is the InputStream that the buffer will use + * @param buf_size speifies the buffer size + */ + public BufferedBoundaryInputStream(InputStream in, int buf_size){ + super(in); + buffer = new byte[buf_size]; + } - - /** + /** * @return the next byte from the stream or -1 if EOF or stream has encountered a boundary - */ - public int read() throws IOException{ + */ + public int read() throws IOException{ if (fillBuffer() < 0) return -1; if(isOnBoundary()) - return -1; // boundary - return buffer[buf_pos++]; - } + return -1; // boundary + return buffer[buf_pos++]; + } - /** - * Fills the given array with data from the buffer - * - * @param b is the array that will be filled - * @return the amount of bytes read or -1 if EOF or stream is on a boundary - */ - public int read(byte b[]) throws IOException { - return read(b, 0, b.length); - } - - /** - * Reads a given length of bytes from the buffer - * - * @param b is the array that will be filled - * @param off is the offset in the array - * @param len is the amount to read + /** + * Fills the given array with data from the buffer + * + * @param b is the array that will be filled * @return the amount of bytes read or -1 if EOF or stream is on a boundary - */ - public int read(byte b[], int off, int len) throws IOException { + */ + public int read(byte b[]) throws IOException { + return read(b, 0, b.length); + } + + /** + * Reads a given length of bytes from the buffer + * + * @param b is the array that will be filled + * @param off is the offset in the array + * @param len is the amount to read + * @return the amount of bytes read or -1 if EOF or stream is on a boundary + */ + public int read(byte b[], int off, int len) throws IOException { if (fillBuffer() < 0) return -1; // EOF if (isOnBoundary()) - return -1; // boundary + return -1; // boundary - // The request is larger then the buffer size - int leftover = available(); - if (len > leftover) - len = leftover; + // The request is larger then the buffer size + int leftover = available(); + if (len > leftover) + len = leftover; - // the boundary is in the read range - if (buf_pos < buf_bound_pos && buf_bound_pos < buf_pos+len) - len = buf_bound_pos - buf_pos; - - System.arraycopy(buffer, buf_pos, b, off, len); - buf_pos += len; - return len; - } + // the boundary is in the read range + if (buf_pos < buf_bound_pos && buf_bound_pos < buf_pos+len) + len = buf_bound_pos - buf_pos; + + System.arraycopy(buffer, buf_pos, b, off, len); + buf_pos += len; + return len; + } /** @@ -157,76 +156,76 @@ public class BufferedBoundaryInputStream extends FilterInputStream{ /** * Skips over the closest boundary */ - public void next() throws IOException { - // read data until we find the next boundary or get to the end of the stream - if (buf_bound_pos < 0) { + public void next() throws IOException { + // read data until we find the next boundary or get to the end of the stream + if (buf_bound_pos < 0) { while (fillBuffer() >= 0 && buf_bound_pos < 0) buf_pos = buf_end; } - if (buf_bound_pos >= 0){ // is boundary in buffer? - buf_pos += boundary.length; - findNextBoundary(); - } - } - + if (buf_bound_pos >= 0){ // is boundary in buffer? + buf_pos += boundary.length; + findNextBoundary(); + } + } - /** - * Skips a specific amounts of bytes in the buffer. - * Note that his method does not check for boundaries + + /** + * Skips a specific amounts of bytes in the buffer. + * Note that his method does not check for boundaries * and it will only skip in the local buffer. - * + * * @param n the number of bytes to be skipped. * @return the actual number of bytes skipped, * 0 if it has reach the end of the buffer but does not mean end of stream. - */ - public long skip(long n) throws IOException { - int leftover = available(); - if(n > leftover){ - buf_pos = buf_end; - return leftover; - } - return buf_pos += n; - } - - - /** - * Sets the boundary for the stream - */ - public void setBoundary(String b){ - this.boundary = b.getBytes(); - findNextBoundary(); // redo the search with the new boundary - } - - /** - * Sets the boundary for the stream - */ - public void setBoundary(byte[] b){ - boundary = new byte[b.length]; - System.arraycopy(b, 0, boundary, 0, b.length); - findNextBoundary(); // redo the search with the new boundary - } + */ + public long skip(long n) throws IOException { + int leftover = available(); + if(n > leftover){ + buf_pos = buf_end; + return leftover; + } + return buf_pos += n; + } - /** - * @return an estimate of the number of bytes that can be read (or skipped - * over) from this buffered input stream without blocking. - */ - public int available() throws IOException { - if (super.available() <= 0) - return buf_end - buf_pos; // return the whole stream as there are no more boundaries + + /** + * Sets the boundary for the stream + */ + public void setBoundary(String b){ + this.boundary = b.getBytes(); + findNextBoundary(); // redo the search with the new boundary + } + + /** + * Sets the boundary for the stream + */ + public void setBoundary(byte[] b){ + boundary = new byte[b.length]; + System.arraycopy(b, 0, boundary, 0, b.length); + findNextBoundary(); // redo the search with the new boundary + } + + /** + * @return an estimate of the number of bytes that can be read (or skipped + * over) from this buffered input stream without blocking. + */ + public int available() throws IOException { + if (super.available() <= 0) + return buf_end - buf_pos; // return the whole stream as there are no more boundaries else if (buf_end < boundary.length) - return 0; // we need a safety block in case boundary is split - return buf_end - boundary.length - buf_pos; - } + return 0; // we need a safety block in case boundary is split + return buf_end - boundary.length - buf_pos; + } /** * @return true for BufferedBoundaryInputStream */ - public boolean markSupported(){ - return true; - } + public boolean markSupported(){ + return true; + } /** * See {@link InputStream#mark(int)} for details diff --git a/src/zutil/io/BufferedRandomAccessFile.java b/src/zutil/io/BufferedRandomAccessFile.java index bed5833..1c0b215 100644 --- a/src/zutil/io/BufferedRandomAccessFile.java +++ b/src/zutil/io/BufferedRandomAccessFile.java @@ -36,221 +36,221 @@ import java.io.RandomAccessFile; * @author Ziver */ public class BufferedRandomAccessFile extends RandomAccessFile{ - // The size of the buffer in Byte - private int BUF_SIZE = 64*1024; + // The size of the buffer in Byte + private int BUF_SIZE = 64*1024; - // The Buffer - byte buffer[]; - // The end of the buffer - int buf_end = 0; - // The position in the buffer - int buf_pos = 0; - // The real file pointer position where the buffer starts - long file_pos = 0; + // The Buffer + byte buffer[]; + // The end of the buffer + int buf_end = 0; + // The position in the buffer + int buf_pos = 0; + // The real file pointer position where the buffer starts + long file_pos = 0; - /** - * Create a instance of this buffer - * - * @param filename is the file to read from - * @param mode as in {@link java.io.RandomAccessFile#RandomAccessFile(File file, String mode)} - */ - public BufferedRandomAccessFile(String filename, String mode) throws IOException{ - this(new File(filename), mode); - } - - /** - * Create a instance of this buffer - * - * @param file is the file to read from - * @param mode as in {@link java.io.RandomAccessFile#RandomAccessFile(File file, String mode)} - */ - public BufferedRandomAccessFile(File file, String mode) throws IOException{ - super(file,mode); - invalidate(); - buffer = new byte[BUF_SIZE]; - } - - /** - * Create a instance of this buffer - * - * @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); - } - - /** - * Create a instance of this buffer - * - * @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); - invalidate(); - BUF_SIZE = bufsize; - buffer = new byte[BUF_SIZE]; - } + /** + * Create a instance of this buffer + * + * @param filename is the file to read from + * @param mode as in {@link java.io.RandomAccessFile#RandomAccessFile(File file, String mode)} + */ + public BufferedRandomAccessFile(String filename, String mode) throws IOException{ + this(new File(filename), mode); + } - /** - * 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 ); - if(n >= 0) { - file_pos +=n; - buf_end = n; - buf_pos = 0; - } - return n; - } + /** + * Create a instance of this buffer + * + * @param file is the file to read from + * @param mode as in {@link java.io.RandomAccessFile#RandomAccessFile(File file, String mode)} + */ + public BufferedRandomAccessFile(File file, String mode) throws IOException{ + super(file,mode); + invalidate(); + buffer = new byte[BUF_SIZE]; + } - /** - * Resets the buffer - * - * @throws IOException - */ - private void invalidate() throws IOException { - buf_end = 0; - buf_pos = 0; - file_pos = super.getFilePointer(); - } + /** + * Create a instance of this buffer + * + * @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); + } - /** - * @return the next byte in the buffer - */ - public final int read() throws IOException{ - if(buf_pos >= buf_end) { - if(fillBuffer() < 0) - return -1; - } - if(buf_end == 0) { - return -1; - } else { - buf_pos++; - return buffer[buf_pos-1]; - } - } - - /** - * Fills the given array with data from the buffer - * - * @param b is the array that will be filled - * @return the amount of bytes read or -1 if eof - */ - public int read(byte b[]) throws IOException { - return read(b, 0, b.length); - } - - /** - * Reads a given length of bytes from the buffer - * - * @param b is the array that will be filled - * @param off is the offset in the array - * @param len is the amount to read - * @return the amount of bytes read or -1 if eof - */ - public int read(byte b[], int off, int len) throws IOException { - if(buf_pos >= buf_end) { - if(fillBuffer() < 0) - return -1; // EOF - } - - // Copy from buffer - int leftover = buf_end - buf_pos; - if(len <= leftover) { - System.arraycopy(buffer, buf_pos, b, off, len); - buf_pos += len; - return len; - } - - System.arraycopy(buffer, buf_pos, b, off, leftover); - int n = super.read(b, off+leftover, len-leftover ); - fillBuffer(); - if( n >= 0 ) - return leftover + n; - return leftover; - /*for(int i = 0; i < len; i++) { - int c = this.read(); - if(c != -1) - b[off+i] = (byte)c; - else { - return i; - } - } - return len;*/ - } + /** + * Create a instance of this buffer + * + * @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); + invalidate(); + BUF_SIZE = bufsize; + buffer = new byte[BUF_SIZE]; + } - /** - * @return the file pointer in the file - */ - public long getFilePointer() throws IOException{ - long l = file_pos; - return (l - buf_end + buf_pos) ; - } - - /** - * Changes the file pointer to another position - * - * @param pos The position to move the pointer to - */ - public void seek(long pos) throws IOException { - int n = (int)(file_pos - pos); - if(n >= 0 && n <= buf_end) { - buf_pos = buf_end - n; - } else { - super.seek(pos); - invalidate(); - } - } + /** + * 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 ); + if(n >= 0) { + file_pos +=n; + buf_end = n; + buf_pos = 0; + } + return n; + } - /** - * This method is a replacement for readLine() - * - * @return the next line in the file - */ - public final String readNextLine() throws IOException { - String str = null; - if(buf_end-buf_pos <= 0) { - if(fillBuffer() < 0) { - throw new IOException("Error filling buffer!"); - } - } - int lineend = -1; - for(int i = buf_pos; i < buf_end; i++) { - if(buffer[i] == '\n') { - lineend = i; - break; - } - } - if(lineend < 0) { - StringBuffer input = new StringBuffer(256); - int c; - while (((c = read()) != -1) && (c != '\n')) { - input.append((char)c); - } - if ((c == -1) && (input.length() == 0)) { - return null; - } - return input.toString(); - } - - 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); - } - buf_pos = lineend +1; - return str; - } + /** + * Resets the buffer + * + * @throws IOException + */ + private void invalidate() throws IOException { + buf_end = 0; + buf_pos = 0; + file_pos = super.getFilePointer(); + } + + /** + * @return the next byte in the buffer + */ + public final int read() throws IOException{ + if(buf_pos >= buf_end) { + if(fillBuffer() < 0) + return -1; + } + if(buf_end == 0) { + return -1; + } else { + buf_pos++; + return buffer[buf_pos-1]; + } + } + + /** + * Fills the given array with data from the buffer + * + * @param b is the array that will be filled + * @return the amount of bytes read or -1 if eof + */ + public int read(byte b[]) throws IOException { + return read(b, 0, b.length); + } + + /** + * Reads a given length of bytes from the buffer + * + * @param b is the array that will be filled + * @param off is the offset in the array + * @param len is the amount to read + * @return the amount of bytes read or -1 if eof + */ + public int read(byte b[], int off, int len) throws IOException { + if(buf_pos >= buf_end) { + if(fillBuffer() < 0) + return -1; // EOF + } + + // Copy from buffer + int leftover = buf_end - buf_pos; + if(len <= leftover) { + System.arraycopy(buffer, buf_pos, b, off, len); + buf_pos += len; + return len; + } + + System.arraycopy(buffer, buf_pos, b, off, leftover); + int n = super.read(b, off+leftover, len-leftover ); + fillBuffer(); + if( n >= 0 ) + return leftover + n; + return leftover; + /*for(int i = 0; i < len; i++) { + int c = this.read(); + if(c != -1) + b[off+i] = (byte)c; + else { + return i; + } + } + return len;*/ + } + + /** + * @return the file pointer in the file + */ + public long getFilePointer() throws IOException{ + long l = file_pos; + return (l - buf_end + buf_pos) ; + } + + /** + * Changes the file pointer to another position + * + * @param pos The position to move the pointer to + */ + public void seek(long pos) throws IOException { + int n = (int)(file_pos - pos); + if(n >= 0 && n <= buf_end) { + buf_pos = buf_end - n; + } else { + super.seek(pos); + invalidate(); + } + } + + /** + * This method is a replacement for readLine() + * + * @return the next line in the file + */ + public final String readNextLine() throws IOException { + String str = null; + if(buf_end-buf_pos <= 0) { + if(fillBuffer() < 0) { + throw new IOException("Error filling buffer!"); + } + } + int lineend = -1; + for(int i = buf_pos; i < buf_end; i++) { + if(buffer[i] == '\n') { + lineend = i; + break; + } + } + if(lineend < 0) { + StringBuffer input = new StringBuffer(256); + int c; + while (((c = read()) != -1) && (c != '\n')) { + input.append((char)c); + } + if ((c == -1) && (input.length() == 0)) { + return null; + } + return input.toString(); + } + + 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); + } + buf_pos = lineend +1; + return str; + } } diff --git a/src/zutil/io/DynamicByteArrayStream.java b/src/zutil/io/DynamicByteArrayStream.java index 98bb015..95b6e0b 100644 --- a/src/zutil/io/DynamicByteArrayStream.java +++ b/src/zutil/io/DynamicByteArrayStream.java @@ -29,137 +29,137 @@ import java.io.InputStream; import java.util.ArrayList; public class DynamicByteArrayStream extends InputStream{ - /** The byte array container */ - private ArrayList bytes; - /** Current virtual position of the stream */ - private int globalPos; - /** Current virtual size of the stream */ - private int globalSize; - /** Points the current byte array index */ - private int globalArrayIndex; - /** Points to a local index in the current byte array */ - private int localArrayOffset; + /** The byte array container */ + private ArrayList bytes; + /** Current virtual position of the stream */ + private int globalPos; + /** Current virtual size of the stream */ + private int globalSize; + /** Points the current byte array index */ + private int globalArrayIndex; + /** Points to a local index in the current byte array */ + private int localArrayOffset; - /** - * Create a new instance of DynamicByteArrayStream - */ - public DynamicByteArrayStream(){ - bytes = new ArrayList(); - globalPos = 0; - globalSize = 0; - globalArrayIndex = 0; - localArrayOffset = 0; - } + /** + * Create a new instance of DynamicByteArrayStream + */ + public DynamicByteArrayStream(){ + bytes = new ArrayList(); + globalPos = 0; + globalSize = 0; + globalArrayIndex = 0; + localArrayOffset = 0; + } - /** - * Append an byte array to the stream - * - * @param b is the byte array to add. - */ - public synchronized void append(byte[] b){ - bytes.add(b); - globalSize += b.length; - } - - /** - * Append an byte array to the stream. - * NOTE: This function will copy data. - * - * @param b is the byte array to add - * @param offset is the offset in the byte array - * @param length is the amount of data to add - */ - public synchronized void append(byte[] b, int offset, int length){ - byte[] new_b = new byte[length]; - System.arraycopy(b, offset, new_b, 0, length); - bytes.add(new_b); - globalSize += length; - } + /** + * Append an byte array to the stream + * + * @param b is the byte array to add. + */ + public synchronized void append(byte[] b){ + bytes.add(b); + globalSize += b.length; + } - @Override - public synchronized int read() throws IOException { - if(globalPos >= globalSize) return -1; - - int ret = bytes.get(globalArrayIndex)[localArrayOffset] & 0xff; - globalPos++; - localArrayOffset++; - if(localArrayOffset >= bytes.get(globalArrayIndex).length){ - globalArrayIndex++; - localArrayOffset = 0; - } - return ret; - } + /** + * Append an byte array to the stream. + * NOTE: This function will copy data. + * + * @param b is the byte array to add + * @param offset is the offset in the byte array + * @param length is the amount of data to add + */ + public synchronized void append(byte[] b, int offset, int length){ + byte[] new_b = new byte[length]; + System.arraycopy(b, offset, new_b, 0, length); + bytes.add(new_b); + globalSize += length; + } - public synchronized int read(byte b[], int off, int len) { - if(len <= 0) return 0; - if(globalPos >= globalSize) return -1; + @Override + public synchronized int read() throws IOException { + if(globalPos >= globalSize) return -1; + + int ret = bytes.get(globalArrayIndex)[localArrayOffset] & 0xff; + globalPos++; + localArrayOffset++; + if(localArrayOffset >= bytes.get(globalArrayIndex).length){ + globalArrayIndex++; + localArrayOffset = 0; + } + return ret; + } + + public synchronized int read(byte b[], int off, int len) { + if(len <= 0) return 0; + if(globalPos >= globalSize) return -1; int bytes_read=0; - if(globalPos+len >= globalSize) len = globalSize - globalPos; - while(bytes_read= globalSize) len = globalSize - globalPos; + while(bytes_read src.length){ - int length = src.length- localArrayOffset; - System.arraycopy(src, localArrayOffset, b, off+bytes_read, length); - - localArrayOffset = 0; - globalArrayIndex++; - bytes_read += length; - } + if(localArrayOffset +len-bytes_read > src.length){ + int length = src.length- localArrayOffset; + System.arraycopy(src, localArrayOffset, b, off+bytes_read, length); + + localArrayOffset = 0; + globalArrayIndex++; + bytes_read += length; + } // Read length is SHORTER than local array - else{ - int length = len-bytes_read; - System.arraycopy(src, localArrayOffset, b, off+bytes_read, length); - - localArrayOffset += length; - bytes_read += length; - } - } - globalPos += len; - return bytes_read; - } + else{ + int length = len-bytes_read; + System.arraycopy(src, localArrayOffset, b, off+bytes_read, length); - public synchronized int available() { - return globalSize - globalPos; - } + localArrayOffset += length; + bytes_read += length; + } + } + globalPos += len; + return bytes_read; + } - /** - * Clears this stream from the byte arrays - */ - public synchronized void clear(){ - globalSize = 0; - reset(); - bytes.clear(); - } - - public synchronized void reset() { - globalArrayIndex = 0; - localArrayOffset = 0; - globalPos = 0; - } + public synchronized int available() { + return globalSize - globalPos; + } - public void close() throws IOException { - clear(); - } - - /** - * @return all of the buffers content as a byte array. - */ - public byte[] getBytes(){ - byte[] data = new byte[globalSize]; - this.read(data, 0, globalSize); - return data; - } - - - /** - * WARNING: This function might return a malformed String. - * - * @return all the contents of the buffers as a String. - */ - public String toString(){ + /** + * Clears this stream from the byte arrays + */ + public synchronized void clear(){ + globalSize = 0; + reset(); + bytes.clear(); + } + + public synchronized void reset() { + globalArrayIndex = 0; + localArrayOffset = 0; + globalPos = 0; + } + + public void close() throws IOException { + clear(); + } + + /** + * @return all of the buffers content as a byte array. + */ + public byte[] getBytes(){ + byte[] data = new byte[globalSize]; + this.read(data, 0, globalSize); + return data; + } + + + /** + * WARNING: This function might return a malformed String. + * + * @return all the contents of the buffers as a String. + */ + public String toString(){ return new String( this.getBytes() ); - } + } } diff --git a/src/zutil/io/IOUtil.java b/src/zutil/io/IOUtil.java index e3f8962..a4226d4 100755 --- a/src/zutil/io/IOUtil.java +++ b/src/zutil/io/IOUtil.java @@ -45,24 +45,24 @@ public class IOUtil { return readContent(stream, false); } - /** - * Reads and returns all the content of a stream. - * - * @param stream + /** + * 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{ + * @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; - while((len = stream.read(buff)) != -1){ - dyn_buff.append(buff, 0, len); - } + while((len = stream.read(buff)) != -1){ + dyn_buff.append(buff, 0, len); + } - if (close) stream.close(); - return dyn_buff.getBytes(); - } + if (close) stream.close(); + return dyn_buff.getBytes(); + } /** * Reads and returns all the content of a stream as a String. diff --git a/src/zutil/io/InputStreamCloser.java b/src/zutil/io/InputStreamCloser.java index 62971cc..dfd3251 100755 --- a/src/zutil/io/InputStreamCloser.java +++ b/src/zutil/io/InputStreamCloser.java @@ -36,27 +36,27 @@ import java.io.InputStream; * @author Ziver */ public class InputStreamCloser extends InputStream{ - private Closeable[] c; - private InputStream in; - - public InputStreamCloser(InputStream in, Closeable... c){ - this.c = c; - this.in = in; - } + private Closeable[] c; + private InputStream in; - public void close() throws IOException { - in.close(); - for (Closeable stream : c) - stream.close(); - } + public InputStreamCloser(InputStream in, Closeable... c){ + this.c = c; + this.in = in; + } - // Mirror functions - public int read() throws IOException { return in.read(); } - public int read(byte b[]) throws IOException { return in.read(b); } - public int read(byte b[], int off, int len) throws IOException { return in.read(b, off, len); } - public long skip(long n) throws IOException { return in.skip(n); } - public int available() throws IOException { return in.available(); } - public synchronized void mark(int readlimit) { in.mark(readlimit); } - public synchronized void reset() throws IOException { in.reset(); } - public boolean markSupported() { return in.markSupported(); } + public void close() throws IOException { + in.close(); + for (Closeable stream : c) + stream.close(); + } + + // Mirror functions + public int read() throws IOException { return in.read(); } + public int read(byte b[]) throws IOException { return in.read(b); } + public int read(byte b[], int off, int len) throws IOException { return in.read(b, off, len); } + public long skip(long n) throws IOException { return in.skip(n); } + public int available() throws IOException { return in.available(); } + public synchronized void mark(int readlimit) { in.mark(readlimit); } + public synchronized void reset() throws IOException { in.reset(); } + public boolean markSupported() { return in.markSupported(); } } \ No newline at end of file diff --git a/src/zutil/io/MultiPrintStream.java b/src/zutil/io/MultiPrintStream.java index 1acaa28..b624da4 100755 --- a/src/zutil/io/MultiPrintStream.java +++ b/src/zutil/io/MultiPrintStream.java @@ -41,154 +41,154 @@ import java.util.Map; * this class can print strings to multiple PrintStreams */ public class MultiPrintStream extends PrintStream { - //the print streams that will print - private ArrayList streams; - //a instance of this class - public static MultiPrintStream out = new MultiPrintStream(); + //the print streams that will print + private ArrayList streams; + //a instance of this class + public static MultiPrintStream out = new MultiPrintStream(); - public MultiPrintStream(){ - super(new PrintStream(System.out)); - streams = new ArrayList(); - streams.add(new PrintStream(System.out)); - } + public MultiPrintStream(){ + super(new PrintStream(System.out)); + streams = new ArrayList(); + streams.add(new PrintStream(System.out)); + } - /** - * This constructor makes a simple PrintStream that prints to the console and to a file - * @param file is the file name to output to - */ - public MultiPrintStream(String file){ - super(new PrintStream(System.out)); - try { - streams = new ArrayList(); - streams.add(new PrintStream(System.out)); - streams.add(new PrintStream(new File(file))); - } catch (FileNotFoundException e) { - System.out.println("Error when declaring PrintStream!!"); - e.printStackTrace(); - } - } + /** + * This constructor makes a simple PrintStream that prints to the console and to a file + * @param file is the file name to output to + */ + public MultiPrintStream(String file){ + super(new PrintStream(System.out)); + try { + streams = new ArrayList(); + streams.add(new PrintStream(System.out)); + streams.add(new PrintStream(new File(file))); + } catch (FileNotFoundException e) { + System.out.println("Error when declaring PrintStream!!"); + e.printStackTrace(); + } + } - /** - * This constructor takes a array of PrintStreams to be used - * @param streams is a array of the streams that will be used - */ - public MultiPrintStream(PrintStream[] streams){ - super(streams[0]); - this.streams = new ArrayList(); - for(int i=0; i(); + for(int i=0; i oClass = o.getClass(); - buffer.append( oClass.getName() ); - String nextHead = head + "\t"; - // Prints out Arrays - if ( oClass.isArray() ) { - buffer.append( "[" ); - for ( int i=0; i oClass = o.getClass(); + buffer.append( oClass.getName() ); + String nextHead = head + "\t"; + // Prints out Arrays + if ( oClass.isArray() ) { + buffer.append( "[" ); + for ( int i=0; i it = ((Collection)o).iterator(); - buffer.append( "[" ); - while(it.hasNext()){ - Object value = it.next(); - buffer.append("\n"); - buffer.append(nextHead); - buffer.append( (dumbCapable(value, depth-1) ? + if ( i+1 it = ((Collection)o).iterator(); + buffer.append( "[" ); + while(it.hasNext()){ + Object value = it.next(); + buffer.append("\n"); + buffer.append(nextHead); + buffer.append( (dumbCapable(value, depth-1) ? dumpToString(value, nextHead, depth-1) : value) ); - if(it.hasNext()) - buffer.append( "," ); - } - buffer.append( "\n" ); - buffer.append(head); - buffer.append( "]" ); - } - // Prints out a Map - else if(o instanceof Map){ - Iterator it = ((Map)o).keySet().iterator(); - buffer.append( "{" ); - while(it.hasNext()){ - Object key = it.next(); - Object value = ((Map)o).get(key); - buffer.append("\n"); - buffer.append(nextHead); - buffer.append( key ); - buffer.append( "=>" ); - buffer.append( (dumbCapable(value, depth-1) ? + if(it.hasNext()) + buffer.append( "," ); + } + buffer.append( "\n" ); + buffer.append(head); + buffer.append( "]" ); + } + // Prints out a Map + else if(o instanceof Map){ + Iterator it = ((Map)o).keySet().iterator(); + buffer.append( "{" ); + while(it.hasNext()){ + Object key = it.next(); + Object value = ((Map)o).get(key); + buffer.append("\n"); + buffer.append(nextHead); + buffer.append( key ); + buffer.append( "=>" ); + buffer.append( (dumbCapable(value, depth-1) ? dumpToString(value, nextHead, depth-1) : value) ); - if(it.hasNext()) - buffer.append( "," ); - } - buffer.append( "\n" ); - buffer.append(head); - buffer.append( "}" ); - } - // Prints out data from InputStream - else if(o instanceof InputStream){ - buffer.append( " =>{\n" ); - try { - InputStream in = (InputStream)o; - int tmp; - while((tmp = in.read()) != -1){ - buffer.append(nextHead); - buffer.append( (char)tmp ); - } - in.close(); - } catch (IOException e) { - e.printStackTrace(); - } - buffer.append( "\n" ); - buffer.append(head); - buffer.append( "}" ); - } - // Prints out data from InputStream - else if(o instanceof Reader){ - buffer.append( " =>{\n" ); - try { - Reader in = (Reader)o; - int tmp; - while((tmp = in.read()) != -1){ - buffer.append(nextHead); - buffer.append( (char)tmp ); - } - in.close(); - } catch (IOException e) { - e.printStackTrace(); - } - buffer.append( "\n" ); - buffer.append(head); - buffer.append( "}" ); - } - // Prints out Object properties - else{ - buffer.append( "{" ); - while ( oClass != null ) { - Field[] fields = oClass.getDeclaredFields(); - for ( int i=0; i{\n" ); + try { + InputStream in = (InputStream)o; + int tmp; + while((tmp = in.read()) != -1){ + buffer.append(nextHead); + buffer.append( (char)tmp ); + } + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + buffer.append( "\n" ); + buffer.append(head); + buffer.append( "}" ); + } + // Prints out data from InputStream + else if(o instanceof Reader){ + buffer.append( " =>{\n" ); + try { + Reader in = (Reader)o; + int tmp; + while((tmp = in.read()) != -1){ + buffer.append(nextHead); + buffer.append( (char)tmp ); + } + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + buffer.append( "\n" ); + buffer.append(head); + buffer.append( "}" ); + } + // Prints out Object properties + else{ + buffer.append( "{" ); + while ( oClass != null ) { + Field[] fields = oClass.getDeclaredFields(); + for ( int i=0; i{ - // Constants - private static final List compressedFileExtensions = Arrays.asList(new String[]{ - "jar", "zip" - }); + // Constants + private static final List compressedFileExtensions = Arrays.asList(new String[]{ + "jar", "zip" + }); - // Constructor params - private File root; + // Constructor params + private File root; - // Search parameters - private String fileName = null; - private String extension = null; - private boolean recursive = false; - //private int depth; - private boolean searchFiles = true; + // Search parameters + private String fileName = null; + private String extension = null; + private boolean recursive = false; + //private int depth; + private boolean searchFiles = true; private boolean searchFolders = true; - private boolean searchCompressedFiles = false; + private boolean searchCompressedFiles = false; - public FileSearcher(File root){ - this.root = root; - } + public FileSearcher(File root){ + this.root = root; + } - /** - * @param file Sets the exact file name to search for (includes extension) - */ - public void setFileName(String file){ - fileName = file; - } - - /** - * Sets the file extensions to search for (should not include . at the beginning) - */ - public void setExtension(String ext){ - extension = ext; - } - - /** - * Defines if the search should go into sub-folders - */ - public void setRecursive(boolean recursive){ - this.recursive = recursive; - } - - /** - * Sets how deep into folders the search should go - * (Recursion needs to be enabled for this attribute to be used) - */ - //public void setDepth(int depth){ - // this.depth = depth; - //} - - /** - * Sets if the searcher should match to files. + /** + * @param file Sets the exact file name to search for (includes extension) + */ + public void setFileName(String file){ + fileName = file; + } + + /** + * Sets the file extensions to search for (should not include . at the beginning) + */ + public void setExtension(String ext){ + extension = ext; + } + + /** + * Defines if the search should go into sub-folders + */ + public void setRecursive(boolean recursive){ + this.recursive = recursive; + } + + /** + * Sets how deep into folders the search should go + * (Recursion needs to be enabled for this attribute to be used) + */ + //public void setDepth(int depth){ + // this.depth = depth; + //} + + /** + * Sets if the searcher should match to files. + */ + public void searchFiles(boolean searchFiles){ + this.searchFiles = searchFiles; + } + /** + * Sets if the searcher should match to folders. */ - public void searchFiles(boolean searchFiles){ - this.searchFiles = searchFiles; - } - /** - * Sets if the searcher should match to folders. - */ public void searchFolders(boolean searchFolders){ this.searchFolders = searchFolders; } @@ -103,85 +103,85 @@ public class FileSearcher implements Iterable{ * Sets if the searcher should go into compressed files. */ public void searchCompressedFiles(boolean searchCompressedFiles){ - this.searchCompressedFiles = searchCompressedFiles; - } + this.searchCompressedFiles = searchCompressedFiles; + } - @Override - public Iterator iterator() { - return new FileSearchIterator(); - } + @Override + public Iterator iterator() { + return new FileSearchIterator(); + } - protected class FileSearchIterator implements Iterator{ - private ArrayList fileList; - private int index; - private FileSearchItem nextItem; + protected class FileSearchIterator implements Iterator{ + private ArrayList fileList; + private int index; + private FileSearchItem nextItem; - public FileSearchIterator(){ - fileList = new ArrayList(); - index = 0; + public FileSearchIterator(){ + fileList = new ArrayList(); + index = 0; - addFiles(new FileSearchFileItem(root), root.list()); - next(); - } + addFiles(new FileSearchFileItem(root), root.list()); + next(); + } - @Override - public boolean hasNext() { - return nextItem != null; - } + @Override + public boolean hasNext() { + return nextItem != null; + } - @Override - public void remove() { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } - @Override - public FileSearchItem next() { - // Temporarily save the current file - FileSearchItem ret = nextItem; + @Override + public FileSearchItem next() { + // Temporarily save the current file + FileSearchItem ret = nextItem; - // Find the next file - for(; index e = zipFile.entries(); - while(e.hasMoreElements()){ - ZipEntry entry = e.nextElement(); - fileList.add(new FileSearchZipItem(file.getPath(), entry)); - } - zipFile.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - //#### REGULAR FILES - else if(searchFiles && file.isFile()){ + } + //#### COMPRESSED FILES + else if(searchCompressedFiles && file.isFile() && + compressedFileExtensions.contains( + FileUtil.getFileExtension(file.getName()).toLowerCase())){ + try { + ZipFile zipFile = new ZipFile(file.getPath()); + Enumeration e = zipFile.entries(); + while(e.hasMoreElements()){ + ZipEntry entry = e.nextElement(); + fileList.add(new FileSearchZipItem(file.getPath(), entry)); + } + zipFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + //#### REGULAR FILES + else if(searchFiles && file.isFile()){ if(extension == null && fileName == null) // Should we match all files break; else if(extension != null && FileUtil.getFileExtension(file.getName()).equalsIgnoreCase(extension)) - break; - else if(fileName != null && + break; + else if(fileName != null && file.getName().equalsIgnoreCase(fileName)) - break; - } - } + break; + } + } if(index { else nextItem = null; - return ret; - } + return ret; + } - private void addFiles(FileSearchItem root, String[] list){ - if(root instanceof FileSearchFileItem) { - for (String file : list) { - fileList.add(new FileSearchFileItem( - new File(((FileSearchFileItem)root).file, file))); - } - } - } + private void addFiles(FileSearchItem root, String[] list){ + if(root instanceof FileSearchFileItem) { + for (String file : list) { + fileList.add(new FileSearchFileItem( + new File(((FileSearchFileItem)root).file, file))); + } + } + } - } + } - public interface FileSearchItem{ - /** @return a file or folder name **/ - public 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(); + public interface FileSearchItem{ + /** @return a file or folder name **/ + public 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(); - public boolean isCompressed(); - public boolean isFile(); - public boolean isDirectory(); + public boolean isCompressed(); + public boolean isFile(); + public boolean isDirectory(); - /** @return an InputStream if this is a file otherwise null **/ - public InputStream getInputStream() throws IOException; - /** @return an String array with all files if this is a folder otherwise null **/ - public String[] listFiles(); - } + /** @return an InputStream if this is a file otherwise null **/ + public InputStream getInputStream() throws IOException; + /** @return an String array with all files if this is a folder otherwise null **/ + public String[] listFiles(); + } - protected static class FileSearchFileItem implements FileSearchItem{ - private File file; + protected static class FileSearchFileItem implements FileSearchItem{ + private File file; - protected FileSearchFileItem(File file){ - this.file = file; - } + protected FileSearchFileItem(File file){ + this.file = file; + } - public String getName() { return file.getName(); } - public String getPath() { return file.getAbsolutePath(); } + public String getName() { return file.getName(); } + public String getPath() { return file.getAbsolutePath(); } - public boolean isCompressed() { return false; } - public boolean isFile() { return file.isFile(); } - public boolean isDirectory() { return file.isDirectory(); } + public boolean isCompressed() { return false; } + public boolean isFile() { return file.isFile(); } + public boolean isDirectory() { return file.isDirectory(); } - public InputStream getInputStream() throws IOException { return new FileInputStream(file); } - public String[] listFiles() { return file.list(); } + public InputStream getInputStream() throws IOException { return new FileInputStream(file); } + public String[] listFiles() { return file.list(); } - public File getFile() { return file; } + public File getFile() { return file; } - } + } - protected static class FileSearchZipItem implements FileSearchItem{ - private String zipFile; - private ZipEntry entry; + protected static class FileSearchZipItem implements FileSearchItem{ + private String zipFile; + private ZipEntry entry; private String fileName; - protected FileSearchZipItem(String file, ZipEntry entry){ - this.zipFile = file; - this.entry = entry; + protected FileSearchZipItem(String file, ZipEntry entry){ + this.zipFile = file; + this.entry = entry; this.fileName = new File(entry.getName()).getName(); - } + } - public String getName() { return fileName; } - public String getPath() { return "zip://"+zipFile+":"+entry.getName(); } + public String getName() { return fileName; } + public String getPath() { return "zip://"+zipFile+":"+entry.getName(); } - public boolean isCompressed() { return true; } - public boolean isFile() { return !entry.isDirectory(); } - public boolean isDirectory() { return entry.isDirectory(); } + public boolean isCompressed() { return true; } + public boolean isFile() { return !entry.isDirectory(); } + public boolean isDirectory() { return entry.isDirectory(); } - public InputStream getInputStream() throws IOException { - ZipFile zip = new ZipFile(zipFile); - return new InputStreamCloser(zip.getInputStream(entry), zip); - } - public String[] listFiles() { return null; } + public InputStream getInputStream() throws IOException { + ZipFile zip = new ZipFile(zipFile); + return new InputStreamCloser(zip.getInputStream(entry), zip); + } + public String[] listFiles() { return null; } - } + } } \ No newline at end of file diff --git a/src/zutil/io/file/FileWatcher.java b/src/zutil/io/file/FileWatcher.java index d9be78c..f80e96f 100644 --- a/src/zutil/io/file/FileWatcher.java +++ b/src/zutil/io/file/FileWatcher.java @@ -39,53 +39,53 @@ import java.util.TimerTask; * */ public class FileWatcher extends TimerTask{ - private FileChangeListener listener; - private long lastChanged; - private File file; - - /** - * Creates a watcher for the given file whit the check - * interval of 1 second - * - * @param file is the file to check - * @throws FileNotFoundException - */ - public FileWatcher(File file) throws FileNotFoundException{ - this(file, 1000); - } - - /** - * Creates a watcher for the given file whit the given - * check interval - * - * @param file is the file - * @param intervall is the interval - * @throws FileNotFoundException - */ - public FileWatcher(File file, int intervall) 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); - } - - public void setListener(FileChangeListener listener){ - this.listener = listener; - } + private FileChangeListener listener; + private long lastChanged; + private File file; - @Override - public void run() { - if (lastChanged != file.lastModified()) { - lastChanged = file.lastModified(); - if(listener != null){ - listener.fileChangedEvent(file); - } - else{ - MultiPrintStream.out.println("File Changed: "+file); - } - } - } + /** + * Creates a watcher for the given file whit the check + * interval of 1 second + * + * @param file is the file to check + * @throws FileNotFoundException + */ + public FileWatcher(File file) throws FileNotFoundException{ + this(file, 1000); + } + + /** + * Creates a watcher for the given file whit the given + * check interval + * + * @param file is the file + * @param intervall is the interval + * @throws FileNotFoundException + */ + public FileWatcher(File file, int intervall) 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); + } + + public void setListener(FileChangeListener listener){ + this.listener = listener; + } + + @Override + public void run() { + if (lastChanged != file.lastModified()) { + lastChanged = file.lastModified(); + if(listener != null){ + listener.fileChangedEvent(file); + } + else{ + MultiPrintStream.out.println("File Changed: "+file); + } + } + } } diff --git a/src/zutil/jee/upload/FileUploadListener.java b/src/zutil/jee/upload/FileUploadListener.java index b4aede8..5400d84 100644 --- a/src/zutil/jee/upload/FileUploadListener.java +++ b/src/zutil/jee/upload/FileUploadListener.java @@ -36,126 +36,126 @@ import zutil.parser.DataNode.DataType; * uploaded file. */ public class FileUploadListener implements ProgressListener{ - public static enum Status{ - Initializing, - Uploading, - Processing, - Done, - Error - } - - private String id; - private volatile Status status; - private volatile String filename; - private volatile String message; - private volatile long bytes = 0l; - private volatile long length = 0l; - private volatile int item = 0; - private volatile long time; - - // Speed - private volatile int speed; - private volatile long speedRead; - private volatile long speedTime; - - public FileUploadListener(){ - id = ""+(int)(Math.random()*Integer.MAX_VALUE); - status = Status.Initializing; - filename = ""; - message = ""; - } - - public void update(long pBytesRead, long pContentLength, int pItems) { - if(pContentLength < 0) this.length = pBytesRead; - else this.length = pContentLength; - this.bytes = pBytesRead; - this.item = pItems; - - // Calculate Speed - if(speedTime == 0 || speedTime+1000 < System.currentTimeMillis() || pBytesRead == pContentLength){ - speedTime = System.currentTimeMillis(); - speed = (int)(pBytesRead-speedRead); - speedRead = pBytesRead; - } - //try{Thread.sleep(10);}catch(Exception e){} + public static enum Status{ + Initializing, + Uploading, + Processing, + Done, + Error + } - // Set Status - status = Status.Uploading; - time = System.currentTimeMillis(); - } - - protected void setFileName(String filename){ - this.filename = filename; - } - protected void setStatus(Status status){ - this.status = status; - time = System.currentTimeMillis(); - } - protected void setMessage(String msg){ - this.message = msg; - } - - - public String getID(){ - return id; - } - - public String getFilename() { - return filename; - } - - public long getBytesRead() { - return bytes; - } + private String id; + private volatile Status status; + private volatile String filename; + private volatile String message; + private volatile long bytes = 0l; + private volatile long length = 0l; + private volatile int item = 0; + private volatile long time; - public long getContentLength() { - return length; - } + // Speed + private volatile int speed; + private volatile long speedRead; + private volatile long speedTime; - public long getItem() { - return item; - } - - public Status getStatus(){ - return status; - } - - protected long getTime(){ - return time; - } - - protected String getMessage(){ - return message; - } - - /** - * @return bytes per second - */ - public int getSpeed(){ - return speed; - } + public FileUploadListener(){ + id = ""+(int)(Math.random()*Integer.MAX_VALUE); + status = Status.Initializing; + filename = ""; + message = ""; + } - /** - * Calculate the percent complete - */ - public int getPercentComplete(){ - if(length == 0) - return 0; - return (int)((100 * bytes) / length); - } + public void update(long pBytesRead, long pContentLength, int pItems) { + if(pContentLength < 0) this.length = pBytesRead; + else this.length = pContentLength; + this.bytes = pBytesRead; + this.item = pItems; - public DataNode getJSON() { - DataNode node = new DataNode( DataType.Map ); - node.set("id", id); - - node.set("status", status.toString()); - node.set("message", message.replaceAll("\"", "\\\"") ); - node.set("filename", filename); - node.set("percent", getPercentComplete()); - - node.set("uploaded", StringUtil.formatByteSizeToString(bytes)); - node.set("total", StringUtil.formatByteSizeToString(length)); - node.set("speed", StringUtil.formatByteSizeToString(speed)+"/s"); - return node; - } + // Calculate Speed + if(speedTime == 0 || speedTime+1000 < System.currentTimeMillis() || pBytesRead == pContentLength){ + speedTime = System.currentTimeMillis(); + speed = (int)(pBytesRead-speedRead); + speedRead = pBytesRead; + } + //try{Thread.sleep(10);}catch(Exception e){} + + // Set Status + status = Status.Uploading; + time = System.currentTimeMillis(); + } + + protected void setFileName(String filename){ + this.filename = filename; + } + protected void setStatus(Status status){ + this.status = status; + time = System.currentTimeMillis(); + } + protected void setMessage(String msg){ + this.message = msg; + } + + + public String getID(){ + return id; + } + + public String getFilename() { + return filename; + } + + public long getBytesRead() { + return bytes; + } + + public long getContentLength() { + return length; + } + + public long getItem() { + return item; + } + + public Status getStatus(){ + return status; + } + + protected long getTime(){ + return time; + } + + protected String getMessage(){ + return message; + } + + /** + * @return bytes per second + */ + public int getSpeed(){ + return speed; + } + + /** + * Calculate the percent complete + */ + public int getPercentComplete(){ + if(length == 0) + return 0; + return (int)((100 * bytes) / length); + } + + public DataNode getJSON() { + DataNode node = new DataNode( DataType.Map ); + node.set("id", id); + + node.set("status", status.toString()); + node.set("message", message.replaceAll("\"", "\\\"") ); + node.set("filename", filename); + node.set("percent", getPercentComplete()); + + node.set("uploaded", StringUtil.formatByteSizeToString(bytes)); + node.set("total", StringUtil.formatByteSizeToString(length)); + node.set("speed", StringUtil.formatByteSizeToString(speed)+"/s"); + return node; + } } diff --git a/src/zutil/log/CompactLogFormatter.java b/src/zutil/log/CompactLogFormatter.java index 5c53571..c833a7e 100755 --- a/src/zutil/log/CompactLogFormatter.java +++ b/src/zutil/log/CompactLogFormatter.java @@ -36,138 +36,138 @@ import java.util.logging.LogRecord; import java.util.regex.Pattern; public class CompactLogFormatter extends Formatter{ - /** The split pattern where the **/ - private static final Pattern splitter = Pattern.compile("\n"); - /** the stream should print time stamp **/ - private boolean timeStamp = true; - /** The time stamp style **/ - private SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - /** If displaying class names are enabled **/ - private boolean className = true; - /** If displaying method names are enabled **/ - private boolean methodName = false; - /** Specifies the max length of the longest class name **/ - private int max_class_name = 0; - /** Cache for the class padding **/ - private static HashMap padd_cache = new HashMap(); - /** Date temp file **/ - private Date date = new Date(); + /** The split pattern where the **/ + private static final Pattern splitter = Pattern.compile("\n"); + /** the stream should print time stamp **/ + private boolean timeStamp = true; + /** The time stamp style **/ + private SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); + /** If displaying class names are enabled **/ + private boolean className = true; + /** If displaying method names are enabled **/ + private boolean methodName = false; + /** Specifies the max length of the longest class name **/ + private int max_class_name = 0; + /** Cache for the class padding **/ + private static HashMap padd_cache = new HashMap(); + /** Date temp file **/ + private Date date = new Date(); - @Override - public String format(LogRecord record) { - StringBuilder prefix = new StringBuilder(); + @Override + public String format(LogRecord record) { + StringBuilder prefix = new StringBuilder(); - if( timeStamp ){ - date.setTime( record.getMillis() ); - prefix.append(dateFormatter.format(date)); - prefix.append(' '); - } + if( timeStamp ){ + date.setTime( record.getMillis() ); + prefix.append(dateFormatter.format(date)); + prefix.append(' '); + } - switch( record.getLevel().intValue() ){ - case /* SEVERE */ 1000: prefix.append("[SEVERE] "); break; - case /* WARNING */ 900 : prefix.append("[WARNING]"); break; - case /* INFO */ 800 : prefix.append("[INFO] "); break; - case /* CONFIG */ 700 : prefix.append("[CONFIG] "); break; - case /* FINE */ 500 : prefix.append("[FINE] "); break; - case /* FINER */ 400 : prefix.append("[FINER] "); break; - case /* FINEST */ 300 : prefix.append("[FINEST] "); break; - } - prefix.append(' '); + switch( record.getLevel().intValue() ){ + case /* SEVERE */ 1000: prefix.append("[SEVERE] "); break; + case /* WARNING */ 900 : prefix.append("[WARNING]"); break; + case /* INFO */ 800 : prefix.append("[INFO] "); break; + case /* CONFIG */ 700 : prefix.append("[CONFIG] "); break; + case /* FINE */ 500 : prefix.append("[FINE] "); break; + case /* FINER */ 400 : prefix.append("[FINER] "); break; + case /* FINEST */ 300 : prefix.append("[FINEST] "); break; + } + prefix.append(' '); - if( className ){ - prefix.append(paddClassName(record.getSourceClassName())); - } - if(methodName){ - prefix.append(record.getSourceMethodName()); - } - prefix.append(": "); + if( className ){ + prefix.append(paddClassName(record.getSourceClassName())); + } + if(methodName){ + prefix.append(record.getSourceMethodName()); + } + prefix.append(": "); - StringBuilder ret = new StringBuilder(); - if( record.getMessage() != null ){ - String[] array = splitter.split( record.getMessage() ); - for( int i=0; i 0 ) - ret.append( prefix ); - ret.append( array[i] ); - } - ret.append( '\n' ); - } + StringBuilder ret = new StringBuilder(); + if( record.getMessage() != null ){ + String[] array = splitter.split( record.getMessage() ); + for( int i=0; i 0 ) + ret.append( prefix ); + ret.append( array[i] ); + } + ret.append( '\n' ); + } - if( record.getThrown() != null ){ - StringOutputStream out = new StringOutputStream(); - record.getThrown().printStackTrace(new PrintStream(out)); - String[] array = splitter.split( out.toString() ); - for( int i=0; i 0 ) - ret.append( prefix ); - ret.append( array[i] ); - } - ret.append( '\n' ); - } - return ret.toString(); - } + if( record.getThrown() != null ){ + StringOutputStream out = new StringOutputStream(); + record.getThrown().printStackTrace(new PrintStream(out)); + String[] array = splitter.split( out.toString() ); + for( int i=0; i 0 ) + ret.append( prefix ); + ret.append( array[i] ); + } + ret.append( '\n' ); + } + return ret.toString(); + } - /** - * If the formatter should add a time stamp in front of the log message - * - * @param enable set to True to activate time stamp - */ - public void enableTimeStamp(boolean enable){ - timeStamp = enable; - } + /** + * If the formatter should add a time stamp in front of the log message + * + * @param enable set to True to activate time stamp + */ + public void enableTimeStamp(boolean enable){ + timeStamp = enable; + } - /** - * The DateFormat to print in the time stamp - * - * @param ts is the String to send to SimpleDateFormat - */ - public void setTimeStamp(String ts){ - dateFormatter = new SimpleDateFormat(ts); - } + /** + * The DateFormat to print in the time stamp + * + * @param ts is the String to send to SimpleDateFormat + */ + public void setTimeStamp(String ts){ + dateFormatter = new SimpleDateFormat(ts); + } - /** - * If the formatter should add the class/source name in front of the log message - * - * @param enable set to True to activate class/source name - */ - public void enableClassName(boolean enable){ - className = enable; - } + /** + * If the formatter should add the class/source name in front of the log message + * + * @param enable set to True to activate class/source name + */ + public void enableClassName(boolean enable){ + className = enable; + } - /** - * If the formatter should add the class/source name in front of the log message - * - * @param enable set to True to activate class/source name - */ - public void enableMethodName(boolean enable){ - methodName = enable; - } + /** + * If the formatter should add the class/source name in front of the log message + * + * @param enable set to True to activate class/source name + */ + public void enableMethodName(boolean enable){ + methodName = enable; + } - /** - * @return the Class name - */ - private String paddClassName(String source){ - String cStr = padd_cache.get(source); - if (cStr == null || cStr.length() != max_class_name) { - cStr = source.substring(source.lastIndexOf('.') + 1); // Remove packages - if (cStr.lastIndexOf('$') >= 0) { // extract subclass name - String subClass = cStr.substring(cStr.lastIndexOf('$') + 1); + /** + * @return the Class name + */ + private String paddClassName(String source){ + String cStr = padd_cache.get(source); + if (cStr == null || cStr.length() != max_class_name) { + cStr = source.substring(source.lastIndexOf('.') + 1); // Remove packages + if (cStr.lastIndexOf('$') >= 0) { // extract subclass name + String subClass = cStr.substring(cStr.lastIndexOf('$') + 1); if (!Pattern.matches("\\d+", subClass)) // Don'n substring for anonymous classes cStr = subClass; - } + } - if (cStr.length() > max_class_name) - max_class_name = cStr.length(); + if (cStr.length() > max_class_name) + max_class_name = cStr.length(); - cStr += StringUtil.getSpaces(max_class_name - cStr.length()); - padd_cache.put(source, cStr); - } - return cStr; - } + cStr += StringUtil.getSpaces(max_class_name - cStr.length()); + padd_cache.put(source, cStr); + } + return cStr; + } } diff --git a/src/zutil/log/LogUtil.java b/src/zutil/log/LogUtil.java index 2e640da..8218705 100755 --- a/src/zutil/log/LogUtil.java +++ b/src/zutil/log/LogUtil.java @@ -37,95 +37,95 @@ import java.util.logging.*; * @author Ziver */ public class LogUtil { - private static final Logger logger = Logger.getLogger( LogUtil.class.getName() ); + private static final Logger logger = Logger.getLogger( LogUtil.class.getName() ); - private LogUtil(){} + private LogUtil(){} - /** - * @return a new Logger for the calling class - */ - public static Logger getLogger(){ - return Logger.getLogger(ClassUtil.getCallingClass(LogUtil.class)); - } + /** + * @return a new Logger for the calling class + */ + public static Logger getLogger(){ + return Logger.getLogger(ClassUtil.getCallingClass(LogUtil.class)); + } - /** - * Sets the log formatter to all root Handlers - * - * @param f is the formatter class - */ - public static void setGlobalFormatter(Formatter f){ - Logger root = Logger.getLogger(""); - for (Handler handler : root.getHandlers()) { - handler.setFormatter(f); - } - } - - /** - * Adds the log formatter to all handlers in the namespace - * - * @param f is the formatter class - */ - public static void setFormatter(String name, Formatter f){ - Logger root = Logger.getLogger(name); - for (Handler handler : root.getHandlers()) { - handler.setFormatter(f); - } - } + /** + * Sets the log formatter to all root Handlers + * + * @param f is the formatter class + */ + public static void setGlobalFormatter(Formatter f){ + Logger root = Logger.getLogger(""); + for (Handler handler : root.getHandlers()) { + handler.setFormatter(f); + } + } - /** - * Sets the global log level - */ - public static void setGlobalLevel(Level level){ - setLevel("", level); - } + /** + * Adds the log formatter to all handlers in the namespace + * + * @param f is the formatter class + */ + public static void setFormatter(String name, Formatter f){ + Logger root = Logger.getLogger(name); + for (Handler handler : root.getHandlers()) { + handler.setFormatter(f); + } + } - /** - * Adds a Handler to the root namespace - */ - public static void addGlobalHandler(Handler handler){ - Logger root = Logger.getLogger(""); - root.addHandler(handler); - } - - /** - * Sets the log level for a specified class - */ - public static void setLevel(Class c, Level level){ - setLevel(c.getName(), level); - } + /** + * Sets the global log level + */ + public static void setGlobalLevel(Level level){ + setLevel("", level); + } - /** - * Sets the log level for a specified logger - */ - public static void setLevel(String name, Level level){ - logger.fine("Changing log level of \""+name+"\" to \""+level.getLocalizedName()+"\""); - Logger newLogger = Logger.getLogger(name); - newLogger.setLevel(level); - // Check if the logger has a handler - if( newLogger.getHandlers().length > 0 ){ - // Set the level on the handlers if its level is higher - for (Handler handler : newLogger.getHandlers()) { - if(handler.getLevel().intValue() > level.intValue()) + /** + * Adds a Handler to the root namespace + */ + public static void addGlobalHandler(Handler handler){ + Logger root = Logger.getLogger(""); + root.addHandler(handler); + } + + /** + * Sets the log level for a specified class + */ + public static void setLevel(Class c, Level level){ + setLevel(c.getName(), level); + } + + /** + * Sets the log level for a specified logger + */ + public static void setLevel(String name, Level level){ + logger.fine("Changing log level of \""+name+"\" to \""+level.getLocalizedName()+"\""); + Logger newLogger = Logger.getLogger(name); + newLogger.setLevel(level); + // Check if the logger has a handler + if( newLogger.getHandlers().length > 0 ){ + // Set the level on the handlers if its level is higher + for (Handler handler : newLogger.getHandlers()) { + if(handler.getLevel().intValue() > level.intValue()) handler.setLevel(level); - } - } - } + } + } + } - public static boolean isLoggable(Class clazz, Level level){ - return Logger.getLogger(clazz.getName()).isLoggable(level); - } + public static boolean isLoggable(Class clazz, Level level){ + return Logger.getLogger(clazz.getName()).isLoggable(level); + } public static void readConfiguration(String file){ try{ - File confFile = FileUtil.find(file); - if (confFile != null) { - FileInputStream in = new FileInputStream(confFile); - LogManager.getLogManager().readConfiguration(in); - in.close(); - } - else - logger.warning("Unable to find logging configuration file: "+file); + File confFile = FileUtil.find(file); + if (confFile != null) { + FileInputStream in = new FileInputStream(confFile); + LogManager.getLogManager().readConfiguration(in); + in.close(); + } + else + logger.warning("Unable to find logging configuration file: "+file); } catch (Exception e){ logger.log(Level.SEVERE, "Unable to load logging configuration: "+file, e); } diff --git a/src/zutil/log/net/NetLogClient.java b/src/zutil/log/net/NetLogClient.java index f091226..1fe9636 100644 --- a/src/zutil/log/net/NetLogClient.java +++ b/src/zutil/log/net/NetLogClient.java @@ -37,55 +37,55 @@ import java.util.logging.Logger; public class NetLogClient extends Thread{ - private static final Logger logger = LogUtil.getLogger(); - - private ConcurrentLinkedQueue listeners; - private Socket s; - private ObjectOutputStream out; + private static final Logger logger = LogUtil.getLogger(); - public NetLogClient(String host, int port) throws UnknownHostException, IOException{ - s = new Socket(host, port); - out = new ObjectOutputStream(s.getOutputStream()); - listeners = new ConcurrentLinkedQueue(); - this.start(); - } + private ConcurrentLinkedQueue listeners; + private Socket s; + private ObjectOutputStream out; - public void addListener(NetLogListener listener){ - logger.info("Registring new NetLogListener: "+listener.getClass().getName()); - listeners.add( listener ); - } + public NetLogClient(String host, int port) throws UnknownHostException, IOException{ + s = new Socket(host, port); + out = new ObjectOutputStream(s.getOutputStream()); + listeners = new ConcurrentLinkedQueue(); + this.start(); + } - public void run(){ - try{ - ObjectInputStream in = new ObjectInputStream(s.getInputStream()); - while( true ){ - Object o = in.readObject(); + public void addListener(NetLogListener listener){ + logger.info("Registring new NetLogListener: "+listener.getClass().getName()); + listeners.add( listener ); + } - for( NetLogListener listener : listeners ){ - if( o instanceof NetLogMessage ) - listener.handleLogMessage((NetLogMessage)o); - else if( o instanceof NetLogExceptionMessage ) - listener.handleExceptionMessage((NetLogExceptionMessage)o); - else if( o instanceof NetLogStatusMessage ) - listener.handleStatusMessage((NetLogStatusMessage)o); - else - logger.warning("Received unknown message: "+o.getClass().getName()); - } - } - } catch( Exception e ){ - logger.log(Level.SEVERE, null, e); - close(); - } - } + public void run(){ + try{ + ObjectInputStream in = new ObjectInputStream(s.getInputStream()); + while( true ){ + Object o = in.readObject(); + + for( NetLogListener listener : listeners ){ + if( o instanceof NetLogMessage ) + listener.handleLogMessage((NetLogMessage)o); + else if( o instanceof NetLogExceptionMessage ) + listener.handleExceptionMessage((NetLogExceptionMessage)o); + else if( o instanceof NetLogStatusMessage ) + listener.handleStatusMessage((NetLogStatusMessage)o); + else + logger.warning("Received unknown message: "+o.getClass().getName()); + } + } + } catch( Exception e ){ + logger.log(Level.SEVERE, null, e); + close(); + } + } - public void close(){ - try{ - this.interrupt(); - s.close(); - } catch (Exception e){ - logger.log(Level.SEVERE, "Unable to close Client Socket.", e); - } - } + public void close(){ + try{ + this.interrupt(); + s.close(); + } catch (Exception e){ + logger.log(Level.SEVERE, "Unable to close Client Socket.", e); + } + } } diff --git a/src/zutil/log/net/NetLogExceptionMessage.java b/src/zutil/log/net/NetLogExceptionMessage.java index 670ca60..6db4a0a 100755 --- a/src/zutil/log/net/NetLogExceptionMessage.java +++ b/src/zutil/log/net/NetLogExceptionMessage.java @@ -29,77 +29,77 @@ import zutil.net.nio.message.Message; import java.util.logging.LogRecord; public class NetLogExceptionMessage implements Message { - private static final long serialVersionUID = 1L; - - private int count; - private String name; - private String message; - private String stackTrace; - - NetLogExceptionMessage(String name, String message, String stackTrace){ - this.count = 1; - this.name = name; - this.message = message; - this.stackTrace = stackTrace; - } + private static final long serialVersionUID = 1L; - public NetLogExceptionMessage(LogRecord record) { - Throwable exception = record.getThrown(); - - this.count = 1; - this.name = exception.getClass().getName(); - this.message = exception.getMessage(); - this.stackTrace = ""; - for(int i=0; i() { - // public void handle(Event e) { - // handleDisconnectAction(e); - // } - //}); - } - } + Parent tabRoot = loader.load(getClass().getResource("NetLogClientInstance.fxml")); + this.setContent(tabRoot); + AnchorPane.setRightAnchor(tabRoot, 0.0); + //this.setOnClosed(new EventHandler() { + // public void handle(Event e) { + // handleDisconnectAction(e); + // } + //}); + } + } } \ No newline at end of file diff --git a/src/zutil/log/net/NetLogGuiClientInstance.java b/src/zutil/log/net/NetLogGuiClientInstance.java index 81aec96..15fc819 100644 --- a/src/zutil/log/net/NetLogGuiClientInstance.java +++ b/src/zutil/log/net/NetLogGuiClientInstance.java @@ -40,15 +40,15 @@ import java.util.logging.Level; 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 static final Logger logger = LogUtil.getLogger(); + private static enum Status{RUNNING, PAUSED, DISCONNECTED} - // Logic variables - private NetLogClient net; - private Status status; + // Logic variables + private NetLogClient net; + private Status status; - // UI elements - @FXML private ToggleButton pauseButton; + // UI elements + @FXML private ToggleButton pauseButton; @FXML private Label levelLabel; @FXML private ComboBox levelComboBox; @FXML private Label intervalLabel; @@ -57,120 +57,120 @@ public class NetLogGuiClientInstance implements Initializable, NetLogListener { @FXML private Label errorLabel; @FXML private Label logCountLabel; - @FXML private TableView logTable; - @FXML private TableColumn logTimestampColumn; - @FXML private TableColumn logLevelColumn; - @FXML private TableColumn logColumn; + @FXML private TableView logTable; + @FXML private TableColumn logTimestampColumn; + @FXML private TableColumn logLevelColumn; + @FXML private TableColumn logColumn; - @FXML private TableView exceptionTable; - @FXML private TableColumn exCountColumn; - @FXML private TableColumn exNameColumn; - @FXML private TableColumn exMessageColumn; - @FXML private TableColumn exStackTraceColumn; + @FXML private TableView exceptionTable; + @FXML private TableColumn exCountColumn; + @FXML private TableColumn exNameColumn; + @FXML private TableColumn exMessageColumn; + @FXML private TableColumn exStackTraceColumn; - public void initialize(URL arg0, ResourceBundle arg1) { - // Connect to Server - try{ - net = new NetLogClient("127.0.0.1", 5050); - net.addListener( this ); - status = Status.RUNNING; - }catch(Exception e){ - logger.log(Level.SEVERE, null, e); - status = Status.DISCONNECTED; - errorLabel.setText(e.getMessage()); - } - updateStatus(); + public void initialize(URL arg0, ResourceBundle arg1) { + // Connect to Server + try{ + net = new NetLogClient("127.0.0.1", 5050); + net.addListener( this ); + status = Status.RUNNING; + }catch(Exception e){ + logger.log(Level.SEVERE, null, e); + status = Status.DISCONNECTED; + errorLabel.setText(e.getMessage()); + } + updateStatus(); - // Setup Gui - logTimestampColumn.setCellValueFactory(new PropertyValueFactory("timestamp")); - logLevelColumn.setCellValueFactory(new PropertyValueFactory("level")); - logLevelColumn.setCellFactory(new RowCssCellFactory(){ - public String getStyleName(String item){ - return item; - } - }); - logColumn.setCellValueFactory(new PropertyValueFactory("log")); + // Setup Gui + logTimestampColumn.setCellValueFactory(new PropertyValueFactory("timestamp")); + logLevelColumn.setCellValueFactory(new PropertyValueFactory("level")); + logLevelColumn.setCellFactory(new RowCssCellFactory(){ + public String getStyleName(String item){ + return item; + } + }); + logColumn.setCellValueFactory(new PropertyValueFactory("log")); - exCountColumn.setCellValueFactory(new PropertyValueFactory("count")); - exNameColumn.setCellValueFactory(new PropertyValueFactory("name")); - exMessageColumn.setCellValueFactory(new PropertyValueFactory("message")); - exStackTraceColumn.setCellValueFactory(new PropertyValueFactory("stackTrace")); - } + exCountColumn.setCellValueFactory(new PropertyValueFactory("count")); + exNameColumn.setCellValueFactory(new PropertyValueFactory("name")); + exMessageColumn.setCellValueFactory(new PropertyValueFactory("message")); + exStackTraceColumn.setCellValueFactory(new PropertyValueFactory("stackTrace")); + } - /************* NETWORK *****************/ - public void handleLogMessage(NetLogMessage msg) { - if(status == Status.RUNNING){ - logTable.getItems().add(msg); + /************* NETWORK *****************/ + public void handleLogMessage(NetLogMessage msg) { + if(status == Status.RUNNING){ + logTable.getItems().add(msg); Platform.runLater(new Runnable() { public void run() { logCountLabel.setText("" + (Long.parseLong(logCountLabel.getText()) + 1)); } }); - } - } + } + } - public void handleExceptionMessage(NetLogExceptionMessage msg) { - if(status == Status.RUNNING){ - exceptionTable.getItems().remove(msg); - exceptionTable.getItems().add(msg); - } - } + public void handleExceptionMessage(NetLogExceptionMessage msg) { + if(status == Status.RUNNING){ + exceptionTable.getItems().remove(msg); + exceptionTable.getItems().add(msg); + } + } - public void handleStatusMessage(NetLogStatusMessage msg) { - if(status == Status.RUNNING){ - - } - } + public void handleStatusMessage(NetLogStatusMessage msg) { + if(status == Status.RUNNING){ - /*************** GUI *******************/ - @FXML - protected void handlePauseAction(ActionEvent event) { - if(status == Status.RUNNING){ - status = Status.PAUSED; - logger.info("Logging paused"); - } - else if(status == Status.PAUSED){ - status = Status.RUNNING; - logger.info("Logging Unpaused"); - } - updateStatus(); - } + } + } - @FXML - protected void handleDisconnectAction(Event event) { - logger.info("Disconnecting from Log Server"); - net.close(); - status = Status.DISCONNECTED; - updateStatus(); - } + /*************** GUI *******************/ + @FXML + protected void handlePauseAction(ActionEvent event) { + if(status == Status.RUNNING){ + status = Status.PAUSED; + logger.info("Logging paused"); + } + else if(status == Status.PAUSED){ + status = Status.RUNNING; + logger.info("Logging Unpaused"); + } + updateStatus(); + } - @FXML - protected void handleLevelChanged(ActionEvent event) { - logger.info("Updating Log Level"); - } + @FXML + protected void handleDisconnectAction(Event event) { + logger.info("Disconnecting from Log Server"); + net.close(); + status = Status.DISCONNECTED; + updateStatus(); + } - @FXML - protected void handleIntervalChanged(ActionEvent event) { - logger.info("Updating Log Interval"); - } + @FXML + protected void handleLevelChanged(ActionEvent event) { + logger.info("Updating Log Level"); + } - private void updateStatus(){ - if(progressBar == null || pauseButton == null){ - return; - } + @FXML + protected void handleIntervalChanged(ActionEvent event) { + logger.info("Updating Log Interval"); + } - if(status == Status.RUNNING){ - progressBar.setProgress(-1.0); - pauseButton.setText("Pause"); - } - else if(status == Status.PAUSED){ - progressBar.setProgress(1.0); - pauseButton.setText("Unpause"); - } - else if(status == Status.DISCONNECTED){ - pauseButton.setDisable(true); + private void updateStatus(){ + if(progressBar == null || pauseButton == null){ + return; + } + + if(status == Status.RUNNING){ + progressBar.setProgress(-1.0); + pauseButton.setText("Pause"); + } + else if(status == Status.PAUSED){ + progressBar.setProgress(1.0); + pauseButton.setText("Unpause"); + } + else if(status == Status.DISCONNECTED){ + pauseButton.setDisable(true); levelLabel.setDisable(true); levelComboBox.setDisable(true); intervalLabel.setDisable(true); @@ -181,42 +181,42 @@ public class NetLogGuiClientInstance implements Initializable, NetLogListener { progressBar.setProgress(0); logCountLabel.setDisable(true); - } - } + } + } - /** - * http://stackoverflow.com/questions/13697115/javafx-tableview-colors - */ - public abstract class RowCssCellFactory implements Callback, TableCell> { + /** + * http://stackoverflow.com/questions/13697115/javafx-tableview-colors + */ + public abstract class RowCssCellFactory implements Callback, TableCell> { - public TableCell call(TableColumn p) { - TableCell cell = new TableCell() { - @Override - public void updateItem(T item, boolean empty) { - super.updateItem(item, empty); - setText(empty ? null : getString()); - setGraphic(null); + public TableCell call(TableColumn p) { + TableCell cell = new TableCell() { + @Override + public void updateItem(T item, boolean empty) { + super.updateItem(item, empty); + setText(empty ? null : getString()); + setGraphic(null); - String style = getStyleName(item); - if(style != null){ - TableRow row = getTableRow(); - row.getStyleClass().add(style); - } - } + String style = getStyleName(item); + if(style != null){ + TableRow row = getTableRow(); + row.getStyleClass().add(style); + } + } - @Override - public void updateSelected(boolean upd){ - super.updateSelected(upd); - } + @Override + public void updateSelected(boolean upd){ + super.updateSelected(upd); + } - private String getString() { - return getItem() == null ? "NULL" : getItem().toString(); - } - }; - return cell; - } + private String getString() { + return getItem() == null ? "NULL" : getItem().toString(); + } + }; + return cell; + } - public abstract String getStyleName(T item); - } + public abstract String getStyleName(T item); + } } \ No newline at end of file diff --git a/src/zutil/log/net/NetLogListener.java b/src/zutil/log/net/NetLogListener.java index f9095e9..1ad140b 100644 --- a/src/zutil/log/net/NetLogListener.java +++ b/src/zutil/log/net/NetLogListener.java @@ -26,18 +26,18 @@ package zutil.log.net; public interface NetLogListener { - /** - * Handle incoming log messages - */ - public void handleLogMessage( NetLogMessage log ); - - /** - * Handle incoming exception messages - */ - public void handleExceptionMessage( NetLogExceptionMessage exception ); - - /** - * Handle incoming status messages - */ - public void handleStatusMessage( NetLogStatusMessage status ); + /** + * Handle incoming log messages + */ + public void handleLogMessage( NetLogMessage log ); + + /** + * Handle incoming exception messages + */ + public void handleExceptionMessage( NetLogExceptionMessage exception ); + + /** + * Handle incoming status messages + */ + public void handleStatusMessage( NetLogStatusMessage status ); } diff --git a/src/zutil/log/net/NetLogMessage.java b/src/zutil/log/net/NetLogMessage.java index ce5ecf0..a6f0589 100755 --- a/src/zutil/log/net/NetLogMessage.java +++ b/src/zutil/log/net/NetLogMessage.java @@ -31,82 +31,82 @@ import java.util.Date; import java.util.logging.LogRecord; public class NetLogMessage implements Message { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; private static final SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy--MM-dd HH:mm:ss"); - - private long timestamp; - private String level; - private int threadID; - private String className; - private String methodName; - private String log; + + private long timestamp; + private String level; + private int threadID; + private String className; + private String methodName; + private String log; - public NetLogMessage(String level, long timestamp, String log){ - this.level = level; - this.timestamp = timestamp; - this.log = log; - } + public NetLogMessage(String level, long timestamp, String log){ + this.level = level; + this.timestamp = timestamp; + this.log = log; + } - public NetLogMessage( LogRecord record ){ - timestamp = record.getMillis(); - level = record.getLevel().getName(); - threadID = record.getThreadID(); - className = record.getSourceClassName(); - methodName = record.getSourceMethodName(); - log = record.getMessage(); - } + public NetLogMessage( LogRecord record ){ + timestamp = record.getMillis(); + level = record.getLevel().getName(); + threadID = record.getThreadID(); + className = record.getSourceClassName(); + methodName = record.getSourceMethodName(); + log = record.getMessage(); + } - - - public String getTimestamp() { - return dataFormat.format(new Date(timestamp)); - } - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } - public String getLevel() { - return level; - } + public String getTimestamp() { + return dataFormat.format(new Date(timestamp)); + } - public void setLevel(String level) { - this.level = level; - } + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } - public int getThreadID() { - return threadID; - } + public String getLevel() { + return level; + } - public void setThreadID(int threadID) { - this.threadID = threadID; - } + public void setLevel(String level) { + this.level = level; + } - public String getClassName() { - return className; - } + public int getThreadID() { + return threadID; + } - public void setClassName(String className) { - this.className = className; - } + public void setThreadID(int threadID) { + this.threadID = threadID; + } - public String getMethodName() { - return methodName; - } + public String getClassName() { + return className; + } - public void setMethodName(String methodName) { - this.methodName = methodName; - } + public void setClassName(String className) { + this.className = className; + } - public String getLog() { - return log; - } + public String getMethodName() { + return methodName; + } + + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + public String getLog() { + return log; + } + + public void setLog(String log) { + this.log = log; + } - public void setLog(String log) { - this.log = log; - } - } diff --git a/src/zutil/log/net/NetLogServer.java b/src/zutil/log/net/NetLogServer.java index 3acebc2..052a2c9 100755 --- a/src/zutil/log/net/NetLogServer.java +++ b/src/zutil/log/net/NetLogServer.java @@ -42,135 +42,135 @@ import java.util.logging.Logger; public class NetLogServer extends Handler { - private static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); - private NetLogNetwork net; - private ConcurrentHashMap exceptions; + private NetLogNetwork net; + private ConcurrentHashMap exceptions; - /** - * @param port the port the server will listen on - */ - public NetLogServer(int port) { - super(); - exceptions = new ConcurrentHashMap(); - net = new NetLogNetwork(port); - net.start(); - } + /** + * @param port the port the server will listen on + */ + public NetLogServer(int port) { + super(); + exceptions = new ConcurrentHashMap(); + net = new NetLogNetwork(port); + net.start(); + } - public void publish(LogRecord record) { - // ensure that this log record should be logged by this Handler - if (!isLoggable(record)) - return; + public void publish(LogRecord record) { + // ensure that this log record should be logged by this Handler + if (!isLoggable(record)) + return; - // Output the formatted data to the file - if(record.getThrown() != null){ - NetLogExceptionMessage exception = new NetLogExceptionMessage(record); - if(!exceptions.containsKey(exception)){ - logger.finest("Received new exception: "+exception); - exceptions.put(exception, exception); - net.sendMessage( exception ); - } - else{ - exception = exceptions.get(exception); - exception.addCount(1); - logger.finest("Received known exception(Count: "+exception.getCount()+"): "+exception); - net.sendMessage( exception ); - } - } - else{ - NetLogMessage log = new NetLogMessage(record); - net.sendMessage( log ); - } - } + // Output the formatted data to the file + if(record.getThrown() != null){ + NetLogExceptionMessage exception = new NetLogExceptionMessage(record); + if(!exceptions.containsKey(exception)){ + logger.finest("Received new exception: "+exception); + exceptions.put(exception, exception); + net.sendMessage( exception ); + } + else{ + exception = exceptions.get(exception); + exception.addCount(1); + logger.finest("Received known exception(Count: "+exception.getCount()+"): "+exception); + net.sendMessage( exception ); + } + } + else{ + NetLogMessage log = new NetLogMessage(record); + net.sendMessage( log ); + } + } - public void flush() {} + public void flush() {} - public void close() { - net.close(); - } + public void close() { + net.close(); + } - class NetLogNetwork extends ThreadedTCPNetworkServer{ - private ConcurrentLinkedQueue threads; + class NetLogNetwork extends ThreadedTCPNetworkServer{ + private ConcurrentLinkedQueue threads; - public NetLogNetwork(int port) { - super(port); - threads = new ConcurrentLinkedQueue(); - } + public NetLogNetwork(int port) { + super(port); + threads = new ConcurrentLinkedQueue(); + } - public void sendMessage(Message log){ - for( NetLogServerThread thread : threads ){ - thread.sendMessage( log ); - } - } + public void sendMessage(Message log){ + for( NetLogServerThread thread : threads ){ + thread.sendMessage( log ); + } + } - @Override - protected ThreadedTCPNetworkServerThread getThreadInstance(Socket s) { - try { - NetLogServerThread thread = new NetLogServerThread(s); - return thread; - } catch (IOException e) { - logger.log(Level.SEVERE, "Unable to start Client thread", e); - } - return null; - } + @Override + protected ThreadedTCPNetworkServerThread getThreadInstance(Socket s) { + try { + NetLogServerThread thread = new NetLogServerThread(s); + return thread; + } catch (IOException e) { + logger.log(Level.SEVERE, "Unable to start Client thread", e); + } + return null; + } - class NetLogServerThread implements ThreadedTCPNetworkServerThread{ - private ObjectOutputStream out; - private ObjectInputStream in; - private Socket s; + class NetLogServerThread implements ThreadedTCPNetworkServerThread{ + private ObjectOutputStream out; + private ObjectInputStream in; + private Socket s; - public NetLogServerThread(Socket s) throws IOException{ - this.s = s; - logger.info("Client connected: "+s.getInetAddress()); - out = new ObjectOutputStream( s.getOutputStream() ); - in = new ObjectInputStream( s.getInputStream() ); - - sendAllExceptions(); - threads.add( this ); - } + public NetLogServerThread(Socket s) throws IOException{ + this.s = s; + logger.info("Client connected: "+s.getInetAddress()); + out = new ObjectOutputStream( s.getOutputStream() ); + in = new ObjectInputStream( s.getInputStream() ); - public void sendMessage(Message msg){ - try { - out.writeObject( msg ); - out.reset(); - } catch (Exception e) { - this.close(); - logger.log(Level.SEVERE, "Unable to send message to client: "+s.getInetAddress(), e); - } - } + sendAllExceptions(); + threads.add( this ); + } - public void sendAllExceptions(){ - logger.fine("Sending all exceptions to client: "+s.getInetAddress()); - for(NetLogExceptionMessage e : exceptions.values()) - sendMessage(e); - } + public void sendMessage(Message msg){ + try { + out.writeObject( msg ); + out.reset(); + } catch (Exception e) { + this.close(); + logger.log(Level.SEVERE, "Unable to send message to client: "+s.getInetAddress(), e); + } + } - public void run() { - try { - while( true ){ - in.readObject(); - } - } catch (Exception e) { - logger.log(Level.SEVERE, null, e); - } finally { - this.close(); - } - } + public void sendAllExceptions(){ + logger.fine("Sending all exceptions to client: "+s.getInetAddress()); + for(NetLogExceptionMessage e : exceptions.values()) + sendMessage(e); + } + + public void run() { + try { + while( true ){ + in.readObject(); + } + } catch (Exception e) { + logger.log(Level.SEVERE, null, e); + } finally { + this.close(); + } + } - public void close(){ - try { - threads.remove(this); - logger.info("Client disconnected: "+s.getInetAddress()); - out.close(); - s.close(); - } catch (IOException e) { - logger.log(Level.SEVERE, "Unable to close Client Socket", e); - } - } - } - } + public void close(){ + try { + threads.remove(this); + logger.info("Client disconnected: "+s.getInetAddress()); + out.close(); + s.close(); + } catch (IOException e) { + logger.log(Level.SEVERE, "Unable to close Client Socket", e); + } + } + } + } } diff --git a/src/zutil/log/net/NetLogStatusMessage.java b/src/zutil/log/net/NetLogStatusMessage.java index 32e4a7a..c2d41bb 100755 --- a/src/zutil/log/net/NetLogStatusMessage.java +++ b/src/zutil/log/net/NetLogStatusMessage.java @@ -27,8 +27,8 @@ package zutil.log.net; import zutil.net.nio.message.Message; public class NetLogStatusMessage implements Message{ - private static final long serialVersionUID = 1L; - - public long totalMemory; - public long freememory; + private static final long serialVersionUID = 1L; + + public long totalMemory; + public long freememory; } diff --git a/src/zutil/math/Tick.java b/src/zutil/math/Tick.java index c406760..589a1b3 100644 --- a/src/zutil/math/Tick.java +++ b/src/zutil/math/Tick.java @@ -26,100 +26,100 @@ package zutil.math; public class Tick { - /** - * Ticks a given string(increments the string with one) - * - * @param ts is the string to tick - * @param maxChar is the maximum number of characters in the string - * @return the ticked string - */ - public static String tick(String ts, int maxChar){ - StringBuffer ret = new StringBuffer(ts.trim()); - int index = ret.length()-1; - - if(ret.length() < maxChar){ - ret.append('a'); - } - else{ - while(index >= 0){ - char c = increment(ret.charAt(index)); - if(c != 0){ - if(index == 0 && ret.length() < maxChar) ret.append('a'); - if(index == 0) ret = new StringBuffer(""+c); - else ret.setCharAt(index,c); - break; - } - else{ - //ret.setCharAt(index,'a'); - ret.deleteCharAt(index); - index--; - } - } - } - - return ret.toString(); - } - - /** - * Increments the char with one after the swedish alfabet - * - * @param c is the char to increment - * @return the incremented char in lowercase 0 if it reached the end - */ - public static char increment(char c){ - switch(Character.toLowerCase(c)){ - case 'z': return (char)134; - case (char)134: return (char)132; - case (char)132: return (char)148; - } - c = (char)(Character.toLowerCase(c) + 1); - if(isAlphabetic(c)){ - return c; - } - return 0; - } - - /** - * Checks if the char is a valid character in - * the Swedish alphabet - * - * @param c is the char to check - * @return true if the char is a valid letter - */ - public static boolean isAlphabetic(char c){ - switch(Character.toLowerCase(c)){ - case 'a': - case 'b': - case 'c': - case 'd': - case 'e': - case 'f': - case 'g': - case 'h': - case 'i': - case 'j': - case 'k': - case 'l': - case 'm': - case 'n': - case 'o': - case 'p': - case 'q': - case 'r': - case 's': - case 't': - case 'u': - case 'v': - case 'w': - case 'x': - case 'y': - case 'z': - case (char)134: - case (char)132: - case (char)148: + /** + * Ticks a given string(increments the string with one) + * + * @param ts is the string to tick + * @param maxChar is the maximum number of characters in the string + * @return the ticked string + */ + public static String tick(String ts, int maxChar){ + StringBuffer ret = new StringBuffer(ts.trim()); + int index = ret.length()-1; + + if(ret.length() < maxChar){ + ret.append('a'); + } + else{ + while(index >= 0){ + char c = increment(ret.charAt(index)); + if(c != 0){ + if(index == 0 && ret.length() < maxChar) ret.append('a'); + if(index == 0) ret = new StringBuffer(""+c); + else ret.setCharAt(index,c); + break; + } + else{ + //ret.setCharAt(index,'a'); + ret.deleteCharAt(index); + index--; + } + } + } + + return ret.toString(); + } + + /** + * Increments the char with one after the swedish alfabet + * + * @param c is the char to increment + * @return the incremented char in lowercase 0 if it reached the end + */ + public static char increment(char c){ + switch(Character.toLowerCase(c)){ + case 'z': return (char)134; + case (char)134: return (char)132; + case (char)132: return (char)148; + } + c = (char)(Character.toLowerCase(c) + 1); + if(isAlphabetic(c)){ + return c; + } + return 0; + } + + /** + * Checks if the char is a valid character in + * the Swedish alphabet + * + * @param c is the char to check + * @return true if the char is a valid letter + */ + public static boolean isAlphabetic(char c){ + switch(Character.toLowerCase(c)){ + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + case 'g': + case 'h': + case 'i': + case 'j': + case 'k': + case 'l': + case 'm': + case 'n': + case 'o': + case 'p': + case 'q': + case 'r': + case 's': + case 't': + case 'u': + case 'v': + case 'w': + case 'x': + case 'y': + case 'z': + case (char)134: + case (char)132: + case (char)148: return true; - default: + default: return false; - } - } + } + } } diff --git a/src/zutil/net/FTPClient.java b/src/zutil/net/FTPClient.java index 9bc3d17..6d3b773 100755 --- a/src/zutil/net/FTPClient.java +++ b/src/zutil/net/FTPClient.java @@ -81,285 +81,285 @@ public class FTPClient extends Thread{ return UNKNOWN; } } - //*************************************************** + //*************************************************** private FTPConnectionType connectionType; - private BufferedReader in; - private Writer out; - private Socket socket; - private long last_sent; + private BufferedReader in; + private Writer out; + private Socket socket; + private long last_sent; - /** - * Creates a FTP connection and logs in - * - * @param url the address to server - * @param port port number - * @param user login username - * @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{ - socket = new Socket(url, port); - in = new BufferedReader(new InputStreamReader(socket.getInputStream())); - out = new OutputStreamWriter(socket.getOutputStream()); + /** + * Creates a FTP connection and logs in + * + * @param url the address to server + * @param port port number + * @param user login username + * @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{ + socket = new Socket(url, port); + in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + out = new OutputStreamWriter(socket.getOutputStream()); connectionType = conn_type; - - readCommand(); - sendCommand("USER "+user); - sendNoReplyCommand("PASS "+pass); - String tmp = readCommand(); - if(parseReturnCode(tmp) == FTPReturnCode.LOGIN_NO){ - close(); - throw new AccountException(tmp); - } - - start(); - } + + readCommand(); + sendCommand("USER "+user); + sendNoReplyCommand("PASS "+pass); + String tmp = readCommand(); + if(parseReturnCode(tmp) == FTPReturnCode.LOGIN_NO){ + close(); + throw new AccountException(tmp); + } + + start(); + } //************************************************************************************** //********************************* Command channel ************************************ - - /** - * Sends the given command to the server and returns a status integer - * - * @return last line received from the server - */ - private FTPReturnCode sendCommand(String cmd) throws IOException{ - sendNoReplyCommand(cmd); - return parseReturnCode( readCommand( ) ); - } - - /** - * Sends a command and don't cares about the reply - */ - private void sendNoReplyCommand(String cmd) throws IOException{ - last_sent = System.currentTimeMillis(); - out.append(cmd).append('\n'); - } - /** - * Reads from the command channel until there are nothing - * left to read and returns the last line - * - * @return last line received by the server - */ - private String readCommand() throws IOException{ - String tmp = in.readLine(); - while(!Character.isWhitespace(tmp.charAt(3))){ - tmp = in.readLine(); + /** + * Sends the given command to the server and returns a status integer + * + * @return last line received from the server + */ + private FTPReturnCode sendCommand(String cmd) throws IOException{ + sendNoReplyCommand(cmd); + return parseReturnCode( readCommand( ) ); + } + + /** + * Sends a command and don't cares about the reply + */ + private void sendNoReplyCommand(String cmd) throws IOException{ + last_sent = System.currentTimeMillis(); + out.append(cmd).append('\n'); + } + + /** + * Reads from the command channel until there are nothing + * left to read and returns the last line + * + * @return last line received by the server + */ + private String readCommand() throws IOException{ + String tmp = in.readLine(); + while(!Character.isWhitespace(tmp.charAt(3))){ + tmp = in.readLine(); if(parseReturnCode(tmp).isError()) throw new IOException(tmp); - } - return tmp; - } - - /** - * Parses the return line from the server and returns the status code - * - * @param msg message String from the server - * @return a status code response - */ - private FTPReturnCode parseReturnCode(String msg){ - return FTPReturnCode.fromCode(Integer.parseInt(msg.substring(0, 3))); - } + } + return tmp; + } + + /** + * Parses the return line from the server and returns the status code + * + * @param msg message String from the server + * @return a status code response + */ + private FTPReturnCode parseReturnCode(String msg){ + return FTPReturnCode.fromCode(Integer.parseInt(msg.substring(0, 3))); + } //************************************************************************************** //****************************** File system actions ************************************ - - /** - * Returns a LinkedList with names of all the files in the directory - * + + /** + * Returns a LinkedList with names of all the files in the directory + * * @deprecated - * @return List with filenames - */ - public String[] getFileList(String path) throws IOException{ - BufferedInputStream data_in = getDataInputStream(); - sendCommand("NLST "+path); - - String data = new String(IOUtil.readContent(data_in)); - - data_in.close(); - readCommand(); - return data.split("[\n\r]"); - } - - /** - * Returns information about a file or directory - * - * @deprecated - * @return a List of Strings with information - */ - public String getFileInfo(String path) throws IOException{ - Pattern regex = Pattern.compile("\\s{1,}"); - - BufferedInputStream data_in = getDataInputStream(); - sendCommand("LIST "+path); + * @return List with filenames + */ + public String[] getFileList(String path) throws IOException{ + BufferedInputStream data_in = getDataInputStream(); + sendCommand("NLST "+path); String data = new String(IOUtil.readContent(data_in)); - data_in.close(); - readCommand(); - return data; - } - - /** - * Creates a file in the server with the given data - * - * @param path filepath - * @param data data to put in the file - */ - public void sendFile(String path, String data) throws IOException{ - BufferedOutputStream data_out = getDataOutputStream(); - sendCommand("STOR "+path); + data_in.close(); + readCommand(); + return data.split("[\n\r]"); + } + + /** + * Returns information about a file or directory + * + * @deprecated + * @return a List of Strings with information + */ + public String getFileInfo(String path) throws IOException{ + Pattern regex = Pattern.compile("\\s{1,}"); + + BufferedInputStream data_in = getDataInputStream(); + sendCommand("LIST "+path); + + String data = new String(IOUtil.readContent(data_in)); + + data_in.close(); + readCommand(); + return data; + } + + /** + * Creates a file in the server with the given data + * + * @param path filepath + * @param data data to put in the file + */ + public void sendFile(String path, String data) throws IOException{ + BufferedOutputStream data_out = getDataOutputStream(); + sendCommand("STOR "+path); byte[] byte_data = data.getBytes(); - data_out.write(byte_data, 0, byte_data.length); - data_out.close(); + data_out.write(byte_data, 0, byte_data.length); + data_out.close(); - readCommand(); - } - - /** - * Creates a directory in the server - * - * @param path The path to the directory - */ - public boolean createDir(String path) throws IOException{ - if(sendCommand("MKD "+path) == FTPReturnCode.PATH_CREATED) - return true; - return false; - } - - /** - * Returns a InputStream for a file on the server - * WARNING: you must run readCommand(); after you close the stream - * - * @return a stream with file data - */ - private BufferedInputStream getFileInputStream(String path) throws IOException{ + readCommand(); + } + + /** + * Creates a directory in the server + * + * @param path The path to the directory + */ + public boolean createDir(String path) throws IOException{ + if(sendCommand("MKD "+path) == FTPReturnCode.PATH_CREATED) + return true; + return false; + } + + /** + * Returns a InputStream for a file on the server + * WARNING: you must run readCommand(); after you close the stream + * + * @return a stream with file data + */ + private BufferedInputStream getFileInputStream(String path) throws IOException{ BufferedInputStream input = getDataInputStream(); - sendCommand("RETR "+path); - return input; - } - - /** - * Download a file from the server to a local file - * - * @param source source file on the server - * @param destination local destination file - */ - public void getFile(String source, String destination) throws IOException{ + sendCommand("RETR "+path); + return input; + } + + /** + * Download a file from the server to a local file + * + * @param source source file on the server + * @param destination local destination file + */ + public void getFile(String source, String destination) throws IOException{ BufferedInputStream ext_file_in = getFileInputStream(source); - BufferedOutputStream local_file_out = new BufferedOutputStream(new FileOutputStream(new File(destination))); + BufferedOutputStream local_file_out = new BufferedOutputStream(new FileOutputStream(new File(destination))); IOUtil.copyStream(ext_file_in, local_file_out); - readCommand(); - } - - /** - * Remove a file from the FTP server - * - * @return true if the command was successful, false otherwise - */ - public boolean removeFile(String path) throws IOException{ - if(sendCommand("DELE "+path) == FTPReturnCode.FILE_ACTION_OK) - return true; - return false; - } - - /** - * Removes a directory from the FTP server - * - * @return True if the command was successful or false otherwise - */ - public boolean removeDir(String path) throws IOException{ - if(sendCommand("RMD "+path) == FTPReturnCode.FILE_ACTION_OK) - return true; - return false; - } + readCommand(); + } + + /** + * Remove a file from the FTP server + * + * @return true if the command was successful, false otherwise + */ + public boolean removeFile(String path) throws IOException{ + if(sendCommand("DELE "+path) == FTPReturnCode.FILE_ACTION_OK) + return true; + return false; + } + + /** + * Removes a directory from the FTP server + * + * @return True if the command was successful or false otherwise + */ + public boolean removeDir(String path) throws IOException{ + if(sendCommand("RMD "+path) == FTPReturnCode.FILE_ACTION_OK) + return true; + return false; + } //************************************************************************************** //******************************** Data Connection ************************************* - - /** - * Start a data connection to the server. - * - * @return a PrintStream for the channel - */ - public BufferedOutputStream getDataOutputStream() throws IOException{ + + /** + * Start a data connection to the server. + * + * @return a PrintStream for the channel + */ + public BufferedOutputStream getDataOutputStream() throws IOException{ if(connectionType == FTPConnectionType.PASSIVE){ // Passive Mode int port = setPassiveMode(); Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port); return new BufferedOutputStream(data_socket.getOutputStream()); - } - else{ // Active Mode - return null; - } - } - - /** - * Start a data connection to the server. - * - * @return a BufferedReader for the data channel - */ - public BufferedInputStream getDataInputStream() throws IOException{ - if(connectionType == FTPConnectionType.PASSIVE){ // Passive Mode - int port = setPassiveMode(); + } + else{ // Active Mode + return null; + } + } + + /** + * Start a data connection to the server. + * + * @return a BufferedReader for the data channel + */ + public BufferedInputStream getDataInputStream() throws IOException{ + if(connectionType == FTPConnectionType.PASSIVE){ // Passive Mode + int port = setPassiveMode(); Socket data_socket = new Socket(socket.getInetAddress().getHostAddress(), port); return new BufferedInputStream(data_socket.getInputStream()); - } - else{ // Active Mode - return null; - } - } + } + else{ // Active Mode + return null; + } + } - - /** - * Sets Passive mode to the server - * - * @return a port number for data channel - */ - private int setPassiveMode() throws IOException{ - sendNoReplyCommand("PASV"); + + /** + * Sets Passive mode to the server + * + * @return a port number for data channel + */ + private int setPassiveMode() throws IOException{ + sendNoReplyCommand("PASV"); String ret_msg = readCommand(); - if(parseReturnCode(ret_msg) != FTPReturnCode.ENTERING_PASSIVE){ - throw new IOException("Passive mode rejected by server: "+ret_msg); - } + if(parseReturnCode(ret_msg) != FTPReturnCode.ENTERING_PASSIVE){ + throw new IOException("Passive mode rejected by server: "+ret_msg); + } ret_msg = ret_msg.substring(ret_msg.indexOf('(')+1, ret_msg.indexOf(')')); - String[] tmpArray = ret_msg.split("[,]"); - - if(tmpArray.length <= 1) - return Integer.parseInt(tmpArray[0]); - else - return Integer.parseInt(tmpArray[4])*256 + Integer.parseInt(tmpArray[5]); - } - -//************************************************************************************** -//************************************************************************************** - - /** - * Keep the connection alive - */ - public void run(){ - try { - while(true){ - if(last_sent > System.currentTimeMillis() + FTP_NOOP_INT*1000){ - sendCommand("NOOP"); - } - try{ Thread.sleep(5000); }catch(Exception e){} - } - } catch (IOException e1) { - e1.printStackTrace(); - } - } + String[] tmpArray = ret_msg.split("[,]"); - /** - * Close the FTP connection - */ - public void close() throws IOException{ - sendCommand("QUIT"); - in.close(); - out.close(); - socket.close(); - this.interrupt(); - } + if(tmpArray.length <= 1) + return Integer.parseInt(tmpArray[0]); + else + return Integer.parseInt(tmpArray[4])*256 + Integer.parseInt(tmpArray[5]); + } + +//************************************************************************************** +//************************************************************************************** + + /** + * Keep the connection alive + */ + public void run(){ + try { + while(true){ + if(last_sent > System.currentTimeMillis() + FTP_NOOP_INT*1000){ + sendCommand("NOOP"); + } + try{ Thread.sleep(5000); }catch(Exception e){} + } + } catch (IOException e1) { + e1.printStackTrace(); + } + } + + /** + * Close the FTP connection + */ + public void close() throws IOException{ + sendCommand("QUIT"); + in.close(); + out.close(); + socket.close(); + this.interrupt(); + } } diff --git a/src/zutil/net/POP3Client.java b/src/zutil/net/POP3Client.java index d160845..acfe00a 100644 --- a/src/zutil/net/POP3Client.java +++ b/src/zutil/net/POP3Client.java @@ -42,299 +42,299 @@ import java.net.UnknownHostException; * */ public class POP3Client { - public static boolean DEBUG = false; - public static final int POP3_PORT = 110; - public static final int POP3_SSL_PORT = 995; + public static boolean DEBUG = false; + public static final int POP3_PORT = 110; + public static final int POP3_SSL_PORT = 995; - private BufferedReader in; - private PrintStream out; - private Socket socket; + private BufferedReader in; + private PrintStream out; + private Socket socket; - /** - * 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{ - 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 password the password - * @throws UnknownHostException - * @throws IOException - */ - public POP3Client(String host, String user, String password) throws UnknownHostException, 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 password the password - * @param ssl If SSL should be used - * @throws UnknownHostException - * @throws IOException - */ - public POP3Client(String host, String user, String password, boolean ssl) throws UnknownHostException, IOException{ - this(host, (ssl ? POP3_SSL_PORT : POP3_PORT), user, password, ssl); - } + /** + * 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{ + this(host, POP3_PORT, null, null, false); + } - /** - * 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 password the password - * @param ssl If SSL should be used - * @throws UnknownHostException - * @throws IOException - */ - public POP3Client(String host, int port, String user, String password, boolean ssl) throws UnknownHostException, IOException{ - if(ssl) connectSSL(host, port); - else connect(host, port); - - if(user != null){ - login(user, password); - } - } - - /** - * Connects to the server - * - * @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{ - socket = new Socket(host, port); - in = new BufferedReader(new InputStreamReader(socket.getInputStream())); - out = new PrintStream(socket.getOutputStream()); + /** + * Connect to a POP3 server with username and password + * + * @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{ + this(host, POP3_PORT, user, password, false); + } - readCommand(true); - } - - /** - * Connects to the server with SSL. - * http://www.exampledepot.com/egs/javax.net.ssl/Client.html - * - * @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{ - SocketFactory socketFactory = SSLSocketFactory.getDefault(); - socket = socketFactory.createSocket(host, port); + /** + * Connects to a POP3 server with username and password and SSL + * + * @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 + */ + public POP3Client(String host, String user, String password, boolean ssl) throws UnknownHostException, IOException{ + this(host, (ssl ? POP3_SSL_PORT : POP3_PORT), user, password, ssl); + } + + /** + * 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 password the password + * @param ssl If SSL should be used + * @throws UnknownHostException + * @throws IOException + */ + public POP3Client(String host, int port, String user, String password, boolean ssl) throws UnknownHostException, IOException{ + if(ssl) connectSSL(host, port); + else connect(host, port); + + if(user != null){ + login(user, password); + } + } + + /** + * Connects to the server + * + * @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{ + socket = new Socket(host, port); + in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + out = new PrintStream(socket.getOutputStream()); + + readCommand(true); + } + + /** + * Connects to the server with SSL. + * http://www.exampledepot.com/egs/javax.net.ssl/Client.html + * + * @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{ + SocketFactory socketFactory = SSLSocketFactory.getDefault(); + socket = socketFactory.createSocket(host, port); - in = new BufferedReader(new InputStreamReader(socket.getInputStream())); - out = new PrintStream(socket.getOutputStream()); + in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + out = new PrintStream(socket.getOutputStream()); - readCommand(DEBUG); - } + readCommand(DEBUG); + } - /** - * Logs in to the POP3 server with the username and password if the password is set - * - * @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); - } - } - - /** - * 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); - return Integer.parseInt( - msg.substring( - msg.indexOf(' ')+1, - msg.indexOf(' ', msg.indexOf(' ')+1))); - } - - /** - * Retrieves the message with the given id. - * - * @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); - } - - /** - * Returns the title of the message - * - * @param id The message id - * @return The title - * @throws IOException - */ - public String getMessageTitle(int id) throws IOException{ - String tmp = getMessageHeader(id); - String tmp2 = tmp.toLowerCase(); - if(tmp2.contains("subject:")){ - return tmp.substring( - tmp2.indexOf("subject:")+8, - tmp2.indexOf('\n', - tmp2.indexOf("subject:"))); - } - else - return null; - } - - /** - * Returns the header of the given message id. - * - * @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); - } - - /** - * 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); - } + /** + * Logs in to the POP3 server with the username and password if the password is set + * + * @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); + } + } + + /** + * 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); + return Integer.parseInt( + msg.substring( + msg.indexOf(' ')+1, + msg.indexOf(' ', msg.indexOf(' ')+1))); + } + + /** + * Retrieves the message with the given id. + * + * @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); + } + + /** + * Returns the title of the message + * + * @param id The message id + * @return The title + * @throws IOException + */ + public String getMessageTitle(int id) throws IOException{ + String tmp = getMessageHeader(id); + String tmp2 = tmp.toLowerCase(); + if(tmp2.contains("subject:")){ + return tmp.substring( + tmp2.indexOf("subject:")+8, + tmp2.indexOf('\n', + tmp2.indexOf("subject:"))); + } + else + return null; + } + + /** + * Returns the header of the given message id. + * + * @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); + } + + /** + * 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); + } //*********************** 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); - } + /** + * 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 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{ - out.println(cmd); - if(print)System.out.println(cmd); - } + /** + * 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); + } - /** - * 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{ - String tmp = in.readLine(); - if(print)System.out.println(tmp); - if( !parseReturnCode(tmp) ) throw new IOException(tmp); + /** + * 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{ + out.println(cmd); + if(print)System.out.println(cmd); + } - return tmp; - } + /** + * 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{ + String tmp = in.readLine(); + if(print)System.out.println(tmp); + if( !parseReturnCode(tmp) ) throw new IOException(tmp); - /** - * 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(); - String tmp = in.readLine(); - while(!tmp.equals(".")){ - msg.append(tmp); - msg.append('\n'); - tmp = in.readLine(); - if(print)System.out.println(tmp); - } - - return msg.toString(); - } + return tmp; + } + + /** + * 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(); + String tmp = in.readLine(); + while(!tmp.equals(".")){ + msg.append(tmp); + msg.append('\n'); + tmp = in.readLine(); + if(print)System.out.println(tmp); + } + + return msg.toString(); + } + + + /** + * Parses the return line from the server and returns the status code + * + * @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"); + } - - /** - * Parses the return line from the server and returns the status code - * - * @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"); - } - //********************************************************************************* - /** - * All the delete marked messages are unmarkt - * @throws IOException - */ - public void reset() throws IOException{ - sendCommand("RSET", DEBUG); - } + /** + * All the delete marked messages are unmarkt + * @throws IOException + */ + public void reset() throws IOException{ + sendCommand("RSET", DEBUG); + } - /** - * All the changes(DELETE) are performed and then the connection is closed - * - * @throws IOException - */ - public void close() throws IOException{ - sendCommand("QUIT", DEBUG); - in.close(); - out.close(); - socket.close(); - } + /** + * All the changes(DELETE) are performed and then the connection is closed + * + * @throws IOException + */ + public void close() throws IOException{ + sendCommand("QUIT", DEBUG); + in.close(); + out.close(); + socket.close(); + } } diff --git a/src/zutil/net/ServerFind.java b/src/zutil/net/ServerFind.java index 1893a63..bf23618 100644 --- a/src/zutil/net/ServerFind.java +++ b/src/zutil/net/ServerFind.java @@ -40,58 +40,58 @@ import java.net.MulticastSocket; * */ public class ServerFind extends Thread { - public String broadcastAddress = "230.0.0.1"; - - private InetAddress group; - private MulticastSocket Msocket; + public String broadcastAddress = "230.0.0.1"; - private boolean avsluta; - private int port; + private InetAddress group; + private MulticastSocket Msocket; - /** - * 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); + private boolean avsluta; + private int port; - start(); - } + /** + * 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); - public void run (){ - byte[] buf = new byte[256]; - DatagramPacket packet; - DatagramSocket lan_socket = null; - - while (!avsluta){ - try { - packet = new DatagramPacket(buf, buf.length); - Msocket.receive(packet); + start(); + } - lan_socket = new DatagramSocket(port , packet.getAddress()); - packet = new DatagramPacket(buf, buf.length, group, port); - lan_socket.send(packet); - lan_socket.close(); - } catch (Exception e) { - MultiPrintStream.out.println("Error Establishing ServerFind Connection!!!\n" + e); - e.printStackTrace(); - } - } - - close(); - } + public void run (){ + byte[] buf = new byte[256]; + DatagramPacket packet; + DatagramSocket lan_socket = null; - /** - * Closes the broadcast socket - */ - public void close(){ - avsluta = true; - Msocket.close(); - } + while (!avsluta){ + try { + packet = new DatagramPacket(buf, buf.length); + Msocket.receive(packet); + + lan_socket = new DatagramSocket(port , packet.getAddress()); + packet = new DatagramPacket(buf, buf.length, group, port); + lan_socket.send(packet); + lan_socket.close(); + } catch (Exception e) { + MultiPrintStream.out.println("Error Establishing ServerFind Connection!!!\n" + e); + e.printStackTrace(); + } + } + + close(); + } + + /** + * Closes the broadcast socket + */ + public void close(){ + avsluta = true; + Msocket.close(); + } } diff --git a/src/zutil/net/ServerFindClient.java b/src/zutil/net/ServerFindClient.java index bee2a53..efead8b 100644 --- a/src/zutil/net/ServerFindClient.java +++ b/src/zutil/net/ServerFindClient.java @@ -37,38 +37,38 @@ import java.net.MulticastSocket; * */ public class ServerFindClient{ - public String broadcastAddress = "230.0.0.1"; - - private int port; + public String broadcastAddress = "230.0.0.1"; - /** - * Creates a ServerFind Client - * - * @param port The port to contact the server on - */ - public ServerFindClient(int port){ - this.port = port; - } - - /** - * Requests IP from server - * - * @return The address of the server - * @throws IOException - */ - public InetAddress find() throws IOException{ - InetAddress group = InetAddress.getByName(broadcastAddress); - DatagramSocket lan_socket = new DatagramSocket(); - MulticastSocket Msocket = new MulticastSocket(port); - Msocket.joinGroup(group); + private int port; - byte[] buf = new byte[256]; - DatagramPacket packet = new DatagramPacket(buf, buf.length, group, port); - lan_socket.send(packet); - - packet = new DatagramPacket(buf, buf.length); - Msocket.receive(packet); + /** + * Creates a ServerFind Client + * + * @param port The port to contact the server on + */ + public ServerFindClient(int port){ + this.port = port; + } - return packet.getAddress(); - } + /** + * Requests IP from server + * + * @return The address of the server + * @throws IOException + */ + public InetAddress find() throws IOException{ + InetAddress group = InetAddress.getByName(broadcastAddress); + DatagramSocket lan_socket = new DatagramSocket(); + MulticastSocket Msocket = new MulticastSocket(port); + Msocket.joinGroup(group); + + byte[] buf = new byte[256]; + DatagramPacket packet = new DatagramPacket(buf, buf.length, group, port); + lan_socket.send(packet); + + packet = new DatagramPacket(buf, buf.length); + Msocket.receive(packet); + + return packet.getAddress(); + } } diff --git a/src/zutil/net/http/HttpClient.java b/src/zutil/net/http/HttpClient.java index 6b266d3..4561745 100755 --- a/src/zutil/net/http/HttpClient.java +++ b/src/zutil/net/http/HttpClient.java @@ -41,53 +41,53 @@ import java.util.HashMap; */ public class HttpClient implements AutoCloseable{ public static enum HttpRequestType{ - GET, POST - } + GET, POST + } - // Request variables - private HttpURL url; - private HttpRequestType type; - private HashMap headers; - private HashMap cookies; + // Request variables + private HttpURL url; + private HttpRequestType type; + private HashMap headers; + private HashMap cookies; private String data; - // Response variables + // Response variables private HttpHeaderParser rspHeader; private InputStream rspStream; - - - public HttpClient(HttpRequestType type){ - this.type = type; - headers = new HashMap(); - cookies = new HashMap(); - } - - - public void setURL( URL url){ - this.url = new HttpURL( url ); - } - - /** - * Adds a parameter to the request - */ - public void setParameter( String key, String value ){ - url.setParameter(key, value); - } - - /** - * Adds a cookie to the request - */ - public void setCookie( String key, String value ){ - cookies.put(key, value); - } - - /** - * Adds a header value to the request - */ - public void setHeader( String key, String value ){ - headers.put(key, value); - } + + + public HttpClient(HttpRequestType type){ + this.type = type; + headers = new HashMap(); + cookies = new HashMap(); + } + + + public void setURL( URL url){ + this.url = new HttpURL( url ); + } + + /** + * Adds a parameter to the request + */ + public void setParameter( String key, String value ){ + url.setParameter(key, value); + } + + /** + * Adds a cookie to the request + */ + public void setCookie( String key, String value ){ + cookies.put(key, value); + } + + /** + * Adds a header value to the request + */ + public void setHeader( String key, String value ){ + headers.put(key, value); + } /** * Sets the content data that will be included in the request. @@ -101,38 +101,38 @@ public class HttpClient implements AutoCloseable{ * Will send a HTTP request to the target host. * NOTE: any previous request connections will be closed */ - public HttpHeaderParser send() throws IOException{ - Socket conn = new Socket( url.getHost(), url.getPort()); - - // Request - HttpPrintStream request = new HttpPrintStream( conn.getOutputStream(), HttpMessageType.REQUEST ); - request.setRequestType( type.toString() ); - request.setRequestURL( url.getHttpURL() ); - request.setHeaders( headers ); - request.setCookies( cookies ); - - if( type == HttpRequestType.POST ){ - String postData = null; + public HttpHeaderParser send() throws IOException{ + Socket conn = new Socket( url.getHost(), url.getPort()); + + // Request + HttpPrintStream request = new HttpPrintStream( conn.getOutputStream(), HttpMessageType.REQUEST ); + request.setRequestType( type.toString() ); + request.setRequestURL( url.getHttpURL() ); + request.setHeaders( headers ); + request.setCookies( cookies ); + + if( type == HttpRequestType.POST ){ + String postData = null; if(data != null) postData = data; else postData = url.getParameterString(); - request.setHeader("Content-Length", ""+postData.length()); - request.println(); - request.print( postData ); - } - else - request.println(); - request.close(); - - // Response + request.setHeader("Content-Length", ""+postData.length()); + request.println(); + request.print( postData ); + } + else + request.println(); + request.close(); + + // Response if(rspHeader != null || rspStream != null) // Close previous request this.close(); - rspStream = new BufferedInputStream(conn.getInputStream()); - rspHeader = new HttpHeaderParser(rspStream); + rspStream = new BufferedInputStream(conn.getInputStream()); + rspHeader = new HttpHeaderParser(rspStream); - return rspHeader; - } + return rspHeader; + } public HttpHeaderParser getResponseHeader(){ return rspHeader; diff --git a/src/zutil/net/http/HttpHeader.java b/src/zutil/net/http/HttpHeader.java index 83b57f8..bbdc61f 100755 --- a/src/zutil/net/http/HttpHeader.java +++ b/src/zutil/net/http/HttpHeader.java @@ -31,18 +31,18 @@ import java.util.HashMap; import java.util.Iterator; public class HttpHeader { - // HTTP info - private boolean request = true; - private String type = "GET"; - private String url = "/"; - private HashMap urlAttributes; - private float version = 1.0f; - private int httpCode = 200; - private InputStream in; + // HTTP info + private boolean request = true; + private String type = "GET"; + private String url = "/"; + private HashMap urlAttributes; + private float version = 1.0f; + private int httpCode = 200; + private InputStream in; - // Parameters - private HashMap headers; - private HashMap cookies; + // Parameters + private HashMap headers; + private HashMap cookies; public HttpHeader(){ @@ -52,58 +52,58 @@ public class HttpHeader { } - /** - * @return true if this header represents a server response - */ - public boolean isResponse(){ - return !request; - } - /** - * @return true if this header represents a client request + /** + * @return true if this header represents a server response */ - public boolean isRequest(){ - return request; - } - /** - * @return the HTTP message type( ex. GET,POST...) - */ - public String getRequestType(){ - return type; - } - /** - * @return the HTTP version of this header - */ - public float getHTTPVersion(){ - return version; - } - /** - * @return the HTTP Return Code from a Server - */ - public int getHTTPCode(){ - return httpCode; - } - /** - * @return the URL that the client sent the server - */ - public String getRequestURL(){ - return url; - } - /** - * @return parses out the page name from the request url and returns it. + public boolean isResponse(){ + return !request; + } + /** + * @return true if this header represents a client request */ - public String getRequestPage() { - if (url != null){ + public boolean isRequest(){ + return request; + } + /** + * @return the HTTP message type( ex. GET,POST...) + */ + public String getRequestType(){ + return type; + } + /** + * @return the HTTP version of this header + */ + public float getHTTPVersion(){ + return version; + } + /** + * @return the HTTP Return Code from a Server + */ + public int getHTTPCode(){ + return httpCode; + } + /** + * @return the URL that the client sent the server + */ + public String getRequestURL(){ + return url; + } + /** + * @return parses out the page name from the request url and returns it. + */ + public String getRequestPage() { + if (url != null){ int start = 0; if (url.charAt(0) == '/') start = 1; - int end = url.indexOf('?'); - if (end < 0) + int end = url.indexOf('?'); + if (end < 0) end = url.length(); return url.substring(start, end); - } - return null; - } + } + return null; + } /** * @return a Iterator with all defined url keys */ @@ -111,35 +111,35 @@ public class HttpHeader { return urlAttributes.keySet().iterator(); } /** - * @return the URL attribute value of the given name. null if there is no such attribute - */ - public String getURLAttribute(String name){ - return urlAttributes.get( name ); - } + * @return the URL attribute value of the given name. null if there is no such attribute + */ + public String getURLAttribute(String name){ + return urlAttributes.get( name ); + } /** * @return a Iterator with all defined headers */ public Iterator getHeaderKeys(){ return headers.keySet().iterator(); } - /** - * @return the HTTP attribute value of the given name. null if there is no such attribute - */ - public String getHeader(String name){ - return headers.get( name.toUpperCase() ); - } + /** + * @return the HTTP attribute value of the given name. null if there is no such attribute + */ + public String getHeader(String name){ + return headers.get( name.toUpperCase() ); + } /** * @return a Iterator with all defined cookies */ public Iterator getCookieKeys(){ return cookies.keySet().iterator(); } - /** - * @return the cookie value of the given name. null if there is no such attribute. - */ - public String getCookie(String name){ - return cookies.get( name ); - } + /** + * @return the cookie value of the given name. null if there is no such attribute. + */ + public String getCookie(String name){ + return cookies.get( name ); + } /** * @return a Reader that contains the body of the http request. */ @@ -148,62 +148,62 @@ public class HttpHeader { } - public void setIsRequest(boolean request) { this.request = request; } - public void setRequestType(String type){ + public void setIsRequest(boolean request) { this.request = request; } + public void setRequestType(String type){ this.type = type; } - public void setHTTPVersion(float version){ + public void setHTTPVersion(float version){ this.version = version; } - public void setHTTPCode(int code){ + public void setHTTPCode(int code){ this.httpCode = code; } - public void setRequestURL(String url){ + public void setRequestURL(String url){ this.url = url.trim().replaceAll("//", "/"); } public void setHeader(String key, String value){ - this.headers.put(key.toUpperCase(), value); - } + this.headers.put(key.toUpperCase(), value); + } protected void setInputStream(InputStream in){ this.in = in; } - protected HashMap getHeaderMap(){ - return headers; - } - protected HashMap getCookieMap(){ - return cookies; - } - protected HashMap getUrlAttributeMap(){ - return urlAttributes; - } + protected HashMap getHeaderMap(){ + return headers; + } + protected HashMap getCookieMap(){ + return cookies; + } + protected HashMap getUrlAttributeMap(){ + return urlAttributes; + } - public String toString(){ - StringBuilder tmp = new StringBuilder(); - tmp.append("{Type: ").append(type); - tmp.append(", HTTP_version: HTTP/").append(version); - if(url == null) - tmp.append(", URL: null"); - else - tmp.append(", URL: \"").append(url).append('\"'); + public String toString(){ + StringBuilder tmp = new StringBuilder(); + tmp.append("{Type: ").append(type); + tmp.append(", HTTP_version: HTTP/").append(version); + if(url == null) + tmp.append(", URL: null"); + else + tmp.append(", URL: \"").append(url).append('\"'); - tmp.append(", URL_attr: ").append(toStringAttributes()); - tmp.append(", Headers: ").append(toStringHeaders()); - tmp.append(", Cookies: ").append(toStringCookies()); + tmp.append(", URL_attr: ").append(toStringAttributes()); + tmp.append(", Headers: ").append(toStringHeaders()); + tmp.append(", Cookies: ").append(toStringCookies()); - tmp.append('}'); - return tmp.toString(); - } - public String toStringHeaders(){ - return Converter.toString(headers); - } - public String toStringCookies(){ - return Converter.toString(cookies); - } - public String toStringAttributes(){ - return Converter.toString(urlAttributes); - } + tmp.append('}'); + return tmp.toString(); + } + public String toStringHeaders(){ + return Converter.toString(headers); + } + public String toStringCookies(){ + return Converter.toString(cookies); + } + public String toStringAttributes(){ + return Converter.toString(urlAttributes); + } } diff --git a/src/zutil/net/http/HttpHeaderParser.java b/src/zutil/net/http/HttpHeaderParser.java index d4bd52c..3a542d5 100755 --- a/src/zutil/net/http/HttpHeaderParser.java +++ b/src/zutil/net/http/HttpHeaderParser.java @@ -38,33 +38,33 @@ import java.util.regex.Pattern; public class HttpHeaderParser { private static final String HEADER_COOKIE = "COOKIE"; - private static final Pattern PATTERN_COLON = Pattern.compile(":"); - private static final Pattern PATTERN_EQUAL = Pattern.compile("="); - private static final Pattern PATTERN_AND = Pattern.compile("&"); + private static final Pattern PATTERN_COLON = Pattern.compile(":"); + private static final Pattern PATTERN_EQUAL = Pattern.compile("="); + private static final Pattern PATTERN_AND = Pattern.compile("&"); private InputStream in; private boolean skipStatusLine; - /** - * Parses the HTTP header information from a stream - * - * @param in is the stream - */ - public HttpHeaderParser(InputStream in){ - this.in = in; + /** + * Parses the HTTP header information from a stream + * + * @param in is the stream + */ + public HttpHeaderParser(InputStream in){ + this.in = in; this.skipStatusLine = false; - } + } - /** - * Parses the HTTP header information from a String - * - * @param in is the String - */ - public HttpHeaderParser(String in){ + /** + * Parses the HTTP header information from a String + * + * @param in is the String + */ + public HttpHeaderParser(String in){ this(new StringInputStream(in)); - } + } public HttpHeader read() throws IOException { @@ -84,7 +84,7 @@ public class HttpHeaderParser { } // Post processing - parseCookieValues(header.getCookieMap(), header.getHeader(HEADER_COOKIE)); + parseCookieValues(header.getCookieMap(), header.getHeader(HEADER_COOKIE)); header.setInputStream(in); return header; } @@ -96,38 +96,38 @@ public class HttpHeaderParser { this.skipStatusLine = skipStatusLine; } - /** - * Parses the first line of a http request/response and stores the values in a HttpHeader object - * + /** + * Parses the first line of a http request/response and stores the values in a HttpHeader object + * * @param header the header object where the cookies will be stored. - * @param statusLine the status line String - */ - private static void parseStatusLine(HttpHeader header, String statusLine){ - // Server Response - if( statusLine.startsWith("HTTP/") ){ - header.setIsRequest(false); - header.setHTTPVersion( Float.parseFloat( statusLine.substring( 5 , 8))); - header.setHTTPCode( Integer.parseInt( statusLine.substring( 9, statusLine.indexOf(' ', 9) ))); - } - // Client Request - else if(statusLine.contains("HTTP/")){ - header.setIsRequest(true); - header.setRequestType( statusLine.substring(0, statusLine.indexOf(" ")).trim() ); - header.setHTTPVersion( Float.parseFloat( statusLine.substring(statusLine.lastIndexOf("HTTP/")+5 , statusLine.length()).trim())); - statusLine = (statusLine.substring(header.getRequestType().length()+1, statusLine.lastIndexOf("HTTP/"))); + * @param statusLine the status line String + */ + private static void parseStatusLine(HttpHeader header, String statusLine){ + // Server Response + if( statusLine.startsWith("HTTP/") ){ + header.setIsRequest(false); + header.setHTTPVersion( Float.parseFloat( statusLine.substring( 5 , 8))); + header.setHTTPCode( Integer.parseInt( statusLine.substring( 9, statusLine.indexOf(' ', 9) ))); + } + // Client Request + else if(statusLine.contains("HTTP/")){ + header.setIsRequest(true); + header.setRequestType( statusLine.substring(0, statusLine.indexOf(" ")).trim() ); + header.setHTTPVersion( Float.parseFloat( statusLine.substring(statusLine.lastIndexOf("HTTP/")+5 , statusLine.length()).trim())); + statusLine = (statusLine.substring(header.getRequestType().length()+1, statusLine.lastIndexOf("HTTP/"))); - // parse URL and attributes - int index = statusLine.indexOf('?'); - if(index > -1){ - header.setRequestURL( statusLine.substring(0, index)); - statusLine = statusLine.substring( index+1, statusLine.length()); - parseURLParameters(header.getUrlAttributeMap(), statusLine); - } - else{ - header.setRequestURL(statusLine); - } - } - } + // parse URL and attributes + int index = statusLine.indexOf('?'); + if(index > -1){ + header.setRequestURL( statusLine.substring(0, index)); + statusLine = statusLine.substring( index+1, statusLine.length()); + parseURLParameters(header.getUrlAttributeMap(), statusLine); + } + else{ + header.setRequestURL(statusLine); + } + } + } /** * Parses a http key value paired header line. @@ -144,15 +144,15 @@ public class HttpHeaderParser { (data.length>1 ? data[1] : "").trim()); //Value } - /** - * Parses a raw cookie header into key and value pairs - * - * @param map the Map where the cookies will be stored. - * @param cookieValue the raw cookie header value String that will be parsed - */ - public static void parseCookieValues(Map map, String cookieValue){ - parseHeaderValues(map, cookieValue, ";"); - } + /** + * Parses a raw cookie header into key and value pairs + * + * @param map the Map where the cookies will be stored. + * @param cookieValue the raw cookie header value String that will be parsed + */ + public static void parseCookieValues(Map map, String cookieValue){ + parseHeaderValues(map, cookieValue, ";"); + } /** @@ -173,11 +173,11 @@ public class HttpHeaderParser { * Parses a header value string that contains key and value paired data and * stores them in a HashMap. If a pair only contain a key then the value * will be set as a empty string. - * - * TODO: method is not quote aware - * @param map the Map where key and values will be stored. + * + * TODO: method is not quote aware + * @param map the Map where key and values will be stored. * @param headerValue the raw header value String that will be parsed. - * @param delimiter the delimiter that separates key and value pairs (e.g. ';' for Cookies or ',' for Cache-Control) + * @param delimiter the delimiter that separates key and value pairs (e.g. ';' for Cookies or ',' for Cache-Control) */ public static void parseHeaderValues(Map map, String headerValue, String delimiter){ if(headerValue != null && !headerValue.isEmpty()){ @@ -192,31 +192,31 @@ public class HttpHeaderParser { } - /** - * Parses a string with variables from a get or post request that was sent from a client - * - * @param header the header object where the url attributes key and value will be stored. - * @param urlAttributes is the String containing all the attributes - */ - public static void parseURLParameters(HttpHeader header, String urlAttributes){ - parseURLParameters(header.getUrlAttributeMap(), urlAttributes); - } - /** - * Parses a string with variables from a get or post request that was sent from a client - * + /** + * Parses a string with variables from a get or post request that was sent from a client + * + * @param header the header object where the url attributes key and value will be stored. + * @param urlAttributes is the String containing all the attributes + */ + public static void parseURLParameters(HttpHeader header, String urlAttributes){ + parseURLParameters(header.getUrlAttributeMap(), urlAttributes); + } + /** + * Parses a string with variables from a get or post request that was sent from a client + * * @param map a map where the url attributes key and value will be stored. - * @param urlAttributes is the String containing all the attributes - */ - public static void parseURLParameters(Map map, String urlAttributes){ - String[] tmp; - urlAttributes = URLDecoder.decode(urlAttributes); - // get the variables - String[] data = PATTERN_AND.split( urlAttributes ); - for(String element : data){ - tmp = PATTERN_EQUAL.split(element, 2); - map.put( - tmp[0].trim(), // Key - (tmp.length>1 ? tmp[1] : "").trim()); //Value - } - } + * @param urlAttributes is the String containing all the attributes + */ + public static void parseURLParameters(Map map, String urlAttributes){ + String[] tmp; + urlAttributes = URLDecoder.decode(urlAttributes); + // get the variables + String[] data = PATTERN_AND.split( urlAttributes ); + for(String element : data){ + tmp = PATTERN_EQUAL.split(element, 2); + map.put( + tmp[0].trim(), // Key + (tmp.length>1 ? tmp[1] : "").trim()); //Value + } + } } diff --git a/src/zutil/net/http/HttpPage.java b/src/zutil/net/http/HttpPage.java index 84f7286..143ebfa 100755 --- a/src/zutil/net/http/HttpPage.java +++ b/src/zutil/net/http/HttpPage.java @@ -34,20 +34,20 @@ import java.util.Map; * */ public interface HttpPage{ - /** - * This method has to be implemented for every page. - * This method is called when a client wants a response - * from this specific page. - * - * @param out is a output stream to the client - * @param headers is the header received from the client + /** + * This method has to be implemented for every page. + * This method is called when a client wants a response + * from this specific page. + * + * @param out is a output stream to the client + * @param headers is the header received from the client * @param session is the session associated with the current client - * @param cookie is cookie information from the client - * @param request is POST and GET requests from the client + * @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 session, - Map cookie, - Map request) throws IOException; + public abstract void respond(HttpPrintStream out, + HttpHeader headers, + Map session, + Map cookie, + Map request) throws IOException; } diff --git a/src/zutil/net/http/HttpPrintStream.java b/src/zutil/net/http/HttpPrintStream.java index 98cd56e..4fd8316 100755 --- a/src/zutil/net/http/HttpPrintStream.java +++ b/src/zutil/net/http/HttpPrintStream.java @@ -39,73 +39,73 @@ import java.util.HashMap; * */ public class HttpPrintStream extends OutputStream{ - // Defines the type of message - public enum HttpMessageType{ - REQUEST, - RESPONSE - } + // Defines the type of message + public enum HttpMessageType{ + REQUEST, + RESPONSE + } - /** The actual output stream */ - private PrintStream out; - /** This defines the supported http version */ - private String httpVersion; - /** This defines the type of message that will be generated */ - private HttpMessageType message_type; - /** The status code of the message, ONLY for response */ - private Integer res_status_code; - /** The request type of the message ONLY for request */ - private String req_type; - /** The requesting url ONLY for request */ - private String req_url; - /** An Map of all the header values */ - private HashMap headers; - /** An Map of all the cookies */ - private HashMap cookies; - /** The buffered header */ - private StringBuffer buffer; - /** If the header buffering is enabled */ - private boolean buffer_enabled; + /** The actual output stream */ + private PrintStream out; + /** This defines the supported http version */ + private String httpVersion; + /** This defines the type of message that will be generated */ + private HttpMessageType message_type; + /** The status code of the message, ONLY for response */ + private Integer res_status_code; + /** The request type of the message ONLY for request */ + private String req_type; + /** The requesting url ONLY for request */ + private String req_url; + /** An Map of all the header values */ + private HashMap headers; + /** An Map of all the cookies */ + private HashMap cookies; + /** The buffered header */ + private StringBuffer buffer; + /** If the header buffering is enabled */ + private boolean buffer_enabled; - /** - * Creates an new instance of HttpPrintStream with - * message type of RESPONSE and buffering disabled. - * - * @param out is the OutputStream where the data will be written to - */ - public HttpPrintStream(OutputStream out) { - this( out, HttpMessageType.RESPONSE ); - } - /** - * Creates an new instance of HttpPrintStream with - * message type buffering disabled. - * - * @param out is the OutputStream where the data will be written to - * @param type is the type of message - */ - public HttpPrintStream(OutputStream out, HttpMessageType type) { - this.out = new PrintStream(out); + /** + * Creates an new instance of HttpPrintStream with + * message type of RESPONSE and buffering disabled. + * + * @param out is the OutputStream where the data will be written to + */ + public HttpPrintStream(OutputStream out) { + this( out, HttpMessageType.RESPONSE ); + } + /** + * Creates an new instance of HttpPrintStream with + * message type buffering disabled. + * + * @param out is the OutputStream where the data will be written to + * @param type is the type of message + */ + public HttpPrintStream(OutputStream out, HttpMessageType type) { + this.out = new PrintStream(out); this.httpVersion = "1.0"; - this.message_type = type; - this.res_status_code = 200; - this.headers = new HashMap(); - this.cookies = new HashMap(); - this.buffer = new StringBuffer(); - this.buffer_enabled = false; - } + this.message_type = type; + this.res_status_code = 200; + this.headers = new HashMap(); + this.cookies = new HashMap(); + this.buffer = new StringBuffer(); + this.buffer_enabled = false; + } - /** - * Enable the buffering capability of the PrintStream. - * Nothing will be sent to the client when buffering - * 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; - if(!buffer_enabled) flush(); - } + /** + * Enable the buffering capability of the PrintStream. + * Nothing will be sent to the client when buffering + * 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; + if(!buffer_enabled) flush(); + } /** * Set the http version that will be used in the http header @@ -114,225 +114,225 @@ public class HttpPrintStream extends OutputStream{ this.httpVersion = version; } - /** - * Adds a cookie that will be sent to the client - * - * @param key is the name of the cookie - * @param value is the value of the cookie - * @throws IOException if the header has already been sent - */ - public void setCookie(String key, String value) throws IOException{ - if(cookies == null) - throw new IOException("Header already sent!"); - cookies.put(key, value); - } + /** + * Adds a cookie that will be sent to the client + * + * @param key is the name of the cookie + * @param value is the value of the cookie + * @throws IOException if the header has already been sent + */ + public void setCookie(String key, String value) throws IOException{ + if(cookies == null) + throw new IOException("Header already sent!"); + cookies.put(key, value); + } - /** - * Adds an header value - * - * @param key is the header name - * @param value is the value of the header - * @throws IOException if the header has already been sent - */ - public void setHeader(String key, String value) throws IOException{ - if(headers == null) - throw new IOException("Header already sent!"); - headers.put(key, value); - } + /** + * Adds an header value + * + * @param key is the header name + * @param value is the value of the header + * @throws IOException if the header has already been sent + */ + public void setHeader(String key, String value) throws IOException{ + if(headers == null) + throw new IOException("Header already sent!"); + headers.put(key, value); + } - /** - * Sets the status code of the message, ONLY available in HTTP RESPONSE - * - * @param code the code from 100 up to 599 - * @throws IOException if the header has already been sent or the message type is wrong - */ - public void setStatusCode(int code) throws IOException{ - if( res_status_code == null ) - throw new IOException("Header already sent!"); - if( message_type != HttpMessageType.RESPONSE ) - throw new IOException("Status Code is only available in HTTP RESPONSE!"); - res_status_code = code; - } + /** + * Sets the status code of the message, ONLY available in HTTP RESPONSE + * + * @param code the code from 100 up to 599 + * @throws IOException if the header has already been sent or the message type is wrong + */ + public void setStatusCode(int code) throws IOException{ + if( res_status_code == null ) + throw new IOException("Header already sent!"); + if( message_type != HttpMessageType.RESPONSE ) + throw new IOException("Status Code is only available in HTTP RESPONSE!"); + res_status_code = code; + } - /** - * Sets the request type of the message, ONLY available in HTTP REQUEST - * - * @param req_type is the type of the message, e.g. GET, POST... - * @throws IOException if the header has already been sent or the message type is wrong - */ - public void setRequestType(String req_type) throws IOException{ - if( req_type == null ) - throw new IOException("Header already sent!"); - if( message_type != HttpMessageType.REQUEST ) - throw new IOException("Request Message Type is only available in HTTP REQUEST!"); - this.req_type = req_type; - } - /** - * Sets the requesting URL of the message, ONLY available in HTTP REQUEST - * - * @param req_url is the URL - * @throws IOException if the header has already been sent or the message type is wrong - */ - public void setRequestURL(String req_url) throws IOException{ - if( req_url == null ) - throw new IOException("Header already sent!"); - if( message_type != HttpMessageType.REQUEST ) - throw new IOException("Request URL is only available in HTTP REQUEST!"); - this.req_url = req_url; - } + /** + * Sets the request type of the message, ONLY available in HTTP REQUEST + * + * @param req_type is the type of the message, e.g. GET, POST... + * @throws IOException if the header has already been sent or the message type is wrong + */ + public void setRequestType(String req_type) throws IOException{ + if( req_type == null ) + throw new IOException("Header already sent!"); + if( message_type != HttpMessageType.REQUEST ) + throw new IOException("Request Message Type is only available in HTTP REQUEST!"); + this.req_type = req_type; + } + /** + * Sets the requesting URL of the message, ONLY available in HTTP REQUEST + * + * @param req_url is the URL + * @throws IOException if the header has already been sent or the message type is wrong + */ + public void setRequestURL(String req_url) throws IOException{ + if( req_url == null ) + throw new IOException("Header already sent!"); + if( message_type != HttpMessageType.REQUEST ) + throw new IOException("Request URL is only available in HTTP REQUEST!"); + this.req_url = req_url; + } - protected void setHeaders( HashMap map ){ - headers = map; - } - protected void setCookies( HashMap map ){ - cookies = map; - } + protected void setHeaders( HashMap map ){ + headers = map; + } + protected void setCookies( HashMap map ){ + cookies = map; + } - /** - * Prints a new line - */ - public void println() throws IOException { - printOrBuffer(System.lineSeparator()); - } - /** - * Prints with a new line - */ - public void println(String s) throws IOException { - printOrBuffer(s + System.lineSeparator()); - } - /** - * Prints an string - */ - public void print(String s) throws IOException { - printOrBuffer(s); - } + /** + * Prints a new line + */ + public void println() throws IOException { + printOrBuffer(System.lineSeparator()); + } + /** + * Prints with a new line + */ + public void println(String s) throws IOException { + printOrBuffer(s + System.lineSeparator()); + } + /** + * Prints an string + */ + public void print(String s) throws IOException { + printOrBuffer(s); + } - /** - * Will buffer String or directly output headers if needed and then the String - */ - private void printOrBuffer(String s) throws IOException { - if(buffer_enabled){ - buffer.append(s); - } - else{ - if(res_status_code != null){ - if( message_type==HttpMessageType.REQUEST ) - out.print(req_type + " " + req_url + " HTTP/"+httpVersion); - else - out.print("HTTP/"+httpVersion+" " + res_status_code + " " + getStatusString(res_status_code)); - out.println(); - res_status_code = null; - req_type = null; - req_url = null; - } - if(headers != null){ - for(String key : headers.keySet()){ - out.println(key + ": " + headers.get(key)); - } - headers = null; - } - if(cookies != null){ - if( !cookies.isEmpty() ){ - if( message_type==HttpMessageType.REQUEST ){ - out.print("Cookie: "); - for(String key : cookies.keySet()){ - out.print(key + "=" + cookies.get(key) + "; "); - } - out.println(); - } - else{ - for(String key : cookies.keySet()){ - out.print("Set-Cookie: " + key + "=" + cookies.get(key) + ";"); - out.println(); - } - } - } - out.println(); - cookies = null; - } - out.print(s); - } - } + /** + * Will buffer String or directly output headers if needed and then the String + */ + private void printOrBuffer(String s) throws IOException { + if(buffer_enabled){ + buffer.append(s); + } + else{ + if(res_status_code != null){ + if( message_type==HttpMessageType.REQUEST ) + out.print(req_type + " " + req_url + " HTTP/"+httpVersion); + else + out.print("HTTP/"+httpVersion+" " + res_status_code + " " + getStatusString(res_status_code)); + out.println(); + res_status_code = null; + req_type = null; + req_url = null; + } + if(headers != null){ + for(String key : headers.keySet()){ + out.println(key + ": " + headers.get(key)); + } + headers = null; + } + if(cookies != null){ + if( !cookies.isEmpty() ){ + if( message_type==HttpMessageType.REQUEST ){ + out.print("Cookie: "); + for(String key : cookies.keySet()){ + out.print(key + "=" + cookies.get(key) + "; "); + } + out.println(); + } + else{ + for(String key : cookies.keySet()){ + out.print("Set-Cookie: " + key + "=" + cookies.get(key) + ";"); + out.println(); + } + } + } + out.println(); + cookies = null; + } + out.print(s); + } + } - /** - * @return if headers has been sent. The setHeader, setStatusCode, setCookie method will throw Exceptions - */ - public boolean isHeaderSent() { - return res_status_code == null && headers == null && cookies == null; - } + /** + * @return if headers has been sent. The setHeader, setStatusCode, setCookie method will throw Exceptions + */ + public boolean isHeaderSent() { + return res_status_code == null && headers == null && cookies == null; + } - /** - * Sends out the buffer and clears it - */ - @Override - public void flush() throws IOException { - flushBuffer(); - out.flush(); - } + /** + * Sends out the buffer and clears it + */ + @Override + public void flush() throws IOException { + flushBuffer(); + out.flush(); + } - @Override - public void close() throws IOException { - flush(); - out.close(); - } + @Override + public void close() throws IOException { + flush(); + out.close(); + } - protected void flushBuffer() throws IOException { - if(buffer_enabled){ - buffer_enabled = false; - printOrBuffer(buffer.toString()); - buffer.delete(0, buffer.length()); - buffer_enabled = true; - } - else if(res_status_code != null || headers != null || cookies != null){ - printOrBuffer(""); - } - } + protected void flushBuffer() throws IOException { + if(buffer_enabled){ + buffer_enabled = false; + printOrBuffer(buffer.toString()); + buffer.delete(0, buffer.length()); + buffer_enabled = true; + } + else if(res_status_code != null || headers != null || cookies != null){ + printOrBuffer(""); + } + } - /** - * Will flush all buffers and write binary data to stream - */ - @Override - public void write(int b) throws IOException { - flushBuffer(); - out.write(b); - } - /** - * * Will flush all buffers and write binary data to stream - */ - @Override - public void write(byte[] buf, int off, int len) throws IOException { - flushBuffer(); - out.write(buf, off, len); - } + /** + * Will flush all buffers and write binary data to stream + */ + @Override + public void write(int b) throws IOException { + flushBuffer(); + out.write(b); + } + /** + * * Will flush all buffers and write binary data to stream + */ + @Override + public void write(byte[] buf, int off, int len) throws IOException { + flushBuffer(); + out.write(buf, off, len); + } - private String getStatusString(int type){ - switch(type){ - case 100: return "Continue"; - case 200: return "OK"; - case 301: return "Moved Permanently"; - case 304: return "Not Modified"; - case 307: return "Temporary Redirect"; - case 400: return "Bad Request"; - case 401: return "Unauthorized"; - case 403: return "Forbidden"; - case 404: return "Not Found"; - case 500: return "Internal Server Error"; - case 501: return "Not Implemented"; - default: return ""; - } - } + private String getStatusString(int type){ + switch(type){ + case 100: return "Continue"; + case 200: return "OK"; + case 301: return "Moved Permanently"; + case 304: return "Not Modified"; + case 307: return "Temporary Redirect"; + case 400: return "Bad Request"; + case 401: return "Unauthorized"; + case 403: return "Forbidden"; + case 404: return "Not Found"; + case 500: return "Internal Server Error"; + case 501: return "Not Implemented"; + default: return ""; + } + } - public String toString() { + public String toString() { StringBuilder str = new StringBuilder(); str.append("{http_type: ").append(message_type); if (res_status_code != null) { if (message_type == HttpMessageType.REQUEST) { str.append(", req_type: ").append(req_type); - if(req_url == null) + if(req_url == null) str.append(", req_url: null"); - else + else str.append(", req_url: \"").append(req_url).append('\"'); } else if (message_type == HttpMessageType.RESPONSE){ str.append(", status_code: ").append(res_status_code); diff --git a/src/zutil/net/http/HttpServer.java b/src/zutil/net/http/HttpServer.java index ed0330d..34dc203 100755 --- a/src/zutil/net/http/HttpServer.java +++ b/src/zutil/net/http/HttpServer.java @@ -50,122 +50,122 @@ import java.util.logging.Logger; * @author Ziver */ public class HttpServer extends ThreadedTCPNetworkServer{ - private static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); - public static final String SESSION_KEY_ID = "session_id"; - public static final String SESSION_KEY_TTL = "session_ttl"; - public static final String SERVER_NAME = "Zutil HttpServer"; - public static final int SESSION_TTL = 10*60*1000; // in milliseconds + public static final String SESSION_KEY_ID = "session_id"; + public static final String SESSION_KEY_TTL = "session_ttl"; + public static final String SERVER_NAME = "Zutil HttpServer"; + public static final int SESSION_TTL = 10*60*1000; // in milliseconds - private Map pages; - private HttpPage defaultPage; - private Map> sessions; - private int nextSessionId; + private Map pages; + private HttpPage defaultPage; + private Map> sessions; + private int nextSessionId; - /** - * Creates a new instance of the sever - * - * @param port The port that the server should listen to - */ - public HttpServer(int port){ - this(port, null, null); - } + /** + * Creates a new instance of the sever + * + * @param port The port that the server should listen to + */ + public HttpServer(int port){ + this(port, null, null); + } - /** - * Creates a new instance of the sever - * - * @param port The port that the server should listen to - * @param keyStore If this is not null then the server will use SSL connection with this keyStore file path - * @param keyStorePass If this is not null then the server will use a SSL connection with the given certificate - */ - public HttpServer(int port, File keyStore, String keyStorePass){ - super( port, keyStore, keyStorePass ); + /** + * Creates a new instance of the sever + * + * @param port The port that the server should listen to + * @param keyStore If this is not null then the server will use SSL connection with this keyStore file path + * @param keyStorePass If this is not null then the server will use a SSL connection with the given certificate + */ + public HttpServer(int port, File keyStore, String keyStorePass){ + super( port, keyStore, keyStorePass ); - pages = new ConcurrentHashMap<>(); - sessions = new ConcurrentHashMap<>(); - nextSessionId = 0; + pages = new ConcurrentHashMap<>(); + sessions = new ConcurrentHashMap<>(); + nextSessionId = 0; ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); - exec.scheduleWithFixedDelay(new SessionGarbageCollector(), 10000, SESSION_TTL / 2, TimeUnit.MILLISECONDS); + exec.scheduleWithFixedDelay(new SessionGarbageCollector(), 10000, SESSION_TTL / 2, TimeUnit.MILLISECONDS); - logger.info("HTTP"+(keyStore==null?"":"S")+" Server ready!"); - } + logger.info("HTTP"+(keyStore==null?"":"S")+" Server ready!"); + } - /** - * This class acts as an garbage collector that - * removes old sessions from the session HashMap - */ - private class SessionGarbageCollector implements Runnable { - public void run(){ - Object[] keys = sessions.keySet().toArray(); - int count = 0; - for(Object key : keys){ - Map session = sessions.get(key); + /** + * This class acts as an garbage collector that + * removes old sessions from the session HashMap + */ + private class SessionGarbageCollector implements Runnable { + public void run(){ + Object[] keys = sessions.keySet().toArray(); + int count = 0; + for(Object key : keys){ + Map session = sessions.get(key); - // Check if session is still valid - if(((Timer) session.get(SESSION_KEY_TTL)).hasTimedOut()){ - sessions.remove(key); - ++count; - } - } - if (count > 0) - logger.fine("Removed "+count+" old sessions"); - } - } + // Check if session is still valid + if(((Timer) session.get(SESSION_KEY_TTL)).hasTimedOut()){ + sessions.remove(key); + ++count; + } + } + if (count > 0) + logger.fine("Removed "+count+" old sessions"); + } + } - /** - * Add a HttpPage to a specific URL - * - * @param name The URL or name of the page - * @param page The page itself - */ - public void setPage(String name, HttpPage page){ - if(name.charAt(0) != '/') - name = "/"+name; - pages.put(name, page); - } + /** + * Add a HttpPage to a specific URL + * + * @param name The URL or name of the page + * @param page The page itself + */ + public void setPage(String name, HttpPage page){ + if(name.charAt(0) != '/') + name = "/"+name; + pages.put(name, page); + } - /** - * This is a default page that will be shown - * if there is no other matching page, - * - * @param page The HttpPage that will be shown - */ - public void setDefaultPage(HttpPage page){ - defaultPage = page; - } + /** + * This is a default page that will be shown + * if there is no other matching page, + * + * @param page The HttpPage that will be shown + */ + public void setDefaultPage(HttpPage page){ + defaultPage = page; + } - protected ThreadedTCPNetworkServerThread getThreadInstance( Socket s ){ - try { - return new HttpServerThread( s ); - } catch (IOException e) { - logger.log(Level.SEVERE, "Could not start new Thread", e); - } - return null; - } + protected ThreadedTCPNetworkServerThread getThreadInstance( Socket s ){ + try { + return new HttpServerThread( s ); + } catch (IOException e) { + logger.log(Level.SEVERE, "Could not start new Thread", e); + } + return null; + } - /** - * Internal class that handles all the requests - */ - protected class HttpServerThread implements ThreadedTCPNetworkServerThread{ - private HttpPrintStream out; - private BufferedInputStream in; - private Socket socket; + /** + * Internal class that handles all the requests + */ + protected class HttpServerThread implements ThreadedTCPNetworkServerThread{ + private HttpPrintStream out; + private BufferedInputStream in; + private Socket socket; - public HttpServerThread(Socket socket) throws IOException{ - out = new HttpPrintStream(socket.getOutputStream()); - in = new BufferedInputStream(socket.getInputStream()); - this.socket = socket; - } + public HttpServerThread(Socket socket) throws IOException{ + out = new HttpPrintStream(socket.getOutputStream()); + in = new BufferedInputStream(socket.getInputStream()); + this.socket = socket; + } - public void run(){ + public void run(){ long time = System.currentTimeMillis(); HttpHeaderParser headerParser; HttpHeader header = null; Map session = null; - try { + try { //**************************** PARSE REQUEST ********************************* headerParser = new HttpHeaderParser(in); header = headerParser.read(); @@ -176,8 +176,8 @@ public class HttpServer extends ThreadedTCPNetworkServer{ //******* Read in the post data if available if (header.getHeader("Content-Length") != null && - header.getHeader("Content-Type") != null && - header.getHeader("Content-Type").contains("application/x-www-form-urlencoded")) { + header.getHeader("Content-Type") != null && + header.getHeader("Content-Type").contains("application/x-www-form-urlencoded")) { // Reads the post data size int postDataLength = Integer.parseInt(header.getHeader("Content-Length")); // read the data @@ -186,8 +186,8 @@ public class HttpServer extends ThreadedTCPNetworkServer{ for (int i = 0; i < postDataLength; i++) { tmpBuff.append((char) in.read()); } - // get the variables - HttpHeaderParser.parseURLParameters(header, tmpBuff.toString()); + // get the variables + HttpHeaderParser.parseURLParameters(header, tmpBuff.toString()); } //**************************** HANDLE REQUEST ********************************* @@ -228,25 +228,25 @@ public class HttpServer extends ThreadedTCPNetworkServer{ out.setStatusCode(404); out.println("404 Page Not Found: " + header.getRequestURL()); logger.warning("Page not defined: " + header.getRequestURL()); - } - //******************************************************************************** - } catch (Exception e) { - logRequest(header, session, time); - logger.log(Level.SEVERE, "500 Internal Server Error", e); - try { - if (!out.isHeaderSent()) - out.setStatusCode(500); - if (e.getMessage() != null) - out.println("500 Internal Server Error: " + e.getMessage()); - else if (e.getCause() != null) { - out.println("500 Internal Server Error: " + e.getCause().getMessage()); - } else { - out.println("500 Internal Server Error: " + e); - } - }catch(IOException ioe){ - logger.log(Level.SEVERE, null, ioe); - } - } + } + //******************************************************************************** + } catch (Exception e) { + logRequest(header, session, time); + logger.log(Level.SEVERE, "500 Internal Server Error", e); + try { + if (!out.isHeaderSent()) + out.setStatusCode(500); + if (e.getMessage() != null) + out.println("500 Internal Server Error: " + e.getMessage()); + else if (e.getCause() != null) { + out.println("500 Internal Server Error: " + e.getCause().getMessage()); + } else { + out.println("500 Internal Server Error: " + e); + } + }catch(IOException ioe){ + logger.log(Level.SEVERE, null, ioe); + } + } finally { try{ out.close(); @@ -256,8 +256,8 @@ public class HttpServer extends ThreadedTCPNetworkServer{ logger.log(Level.WARNING, "Could not close connection", e); } } - } - } + } + } protected static void logRequest(HttpHeader header, diff --git a/src/zutil/net/http/HttpURL.java b/src/zutil/net/http/HttpURL.java index 0e852d9..165a6fd 100755 --- a/src/zutil/net/http/HttpURL.java +++ b/src/zutil/net/http/HttpURL.java @@ -33,130 +33,130 @@ import java.util.HashMap; * @author Ziver */ public class HttpURL { - public static final String PROTOCOL_SEPARATOR = "://"; - public static final String PORT_SEPARATOR = ":"; - public static final String PATH_SEPARATOR = "/"; - public static final String PARAMETER_SEPARATOR = "?"; - public static final String ANCHOR_SEPARATOR = "#"; + public static final String PROTOCOL_SEPARATOR = "://"; + public static final String PORT_SEPARATOR = ":"; + public static final String PATH_SEPARATOR = "/"; + public static final String PARAMETER_SEPARATOR = "?"; + public static final String ANCHOR_SEPARATOR = "#"; - private String protocol = ""; - private String host = "127.0.0.1"; - private int port = -1; - private String path; - private String anchor; - - private HashMap parameters = new HashMap(); + private String protocol = ""; + private String host = "127.0.0.1"; + private int port = -1; + private String path; + private String anchor; - - public HttpURL(){} - - public HttpURL( URL url ){ - this.setProtocol( url.getProtocol() ); - this.setHost( url.getHost() ); - this.setPort( url.getPort() ); - this.setPath( url.getPath() ); - } - - - public String getProtocol( ){ - return protocol; - } - public String getHost( ){ - return host; - } - public int getPort( ){ - return port; - } - public String getPath( ){ - return path; - } - public String getAnchor( ){ - return anchor; - } - - public void setProtocol( String prot ){ - this.protocol = prot; - } - public void setHost( String host ){ - this.host = host; - } - public void setPort( int port ){ - this.port = port; - } - public void setPath( String path ){ - if( path.length() >= 1 && !path.startsWith(PATH_SEPARATOR)) - path = PATH_SEPARATOR + path; - this.path = path; - } - public void setAnchor( String anch ){ - this.anchor = anch; - } - public void setParameter( String key, String value ){ - this.parameters.put(key, value); - } - - protected void setParameters( HashMap pars ){ - this.parameters = pars; - } - - /** - * Generates the parameter string in a URL. - * - * e.g. - * "key=value&key2=value&..." - */ - public String getParameterString(){ - StringBuilder param = new StringBuilder(); - for(String key : parameters.keySet()){ - if (param.length() > 0) - param.append('&'); - param.append(key); - param.append('='); - param.append( parameters.get(key) ); - } - return param.toString(); - } + private HashMap parameters = new HashMap(); - /** - * Generates a path that are used in the HTTP header - */ - public String getHttpURL(){ - StringBuilder url = new StringBuilder(); - url.append( path ); - if( !parameters.isEmpty() ) - url.append( PARAMETER_SEPARATOR ).append( getParameterString() ); - - return url.toString(); - } - - /** - * Generates a full URL - */ - public String getURL(){ - return toString(); - } - - /** - * Generates the whole URL - */ - public String toString(){ - StringBuilder url = new StringBuilder(); - url.append( protocol ); - url.append( PROTOCOL_SEPARATOR ); - url.append( host ); - if( port > 0 ) - url.append( PORT_SEPARATOR ).append( port ); - - if( path != null ) - url.append( path ); - else - url.append( PATH_SEPARATOR ); - - if( !parameters.isEmpty() ) - url.append( PARAMETER_SEPARATOR ).append( getParameterString() ); - if( anchor != null ) - url.append( ANCHOR_SEPARATOR ).append( anchor ); - - return url.toString(); - } + + public HttpURL(){} + + public HttpURL( URL url ){ + this.setProtocol( url.getProtocol() ); + this.setHost( url.getHost() ); + this.setPort( url.getPort() ); + this.setPath( url.getPath() ); + } + + + public String getProtocol( ){ + return protocol; + } + public String getHost( ){ + return host; + } + public int getPort( ){ + return port; + } + public String getPath( ){ + return path; + } + public String getAnchor( ){ + return anchor; + } + + public void setProtocol( String prot ){ + this.protocol = prot; + } + public void setHost( String host ){ + this.host = host; + } + public void setPort( int port ){ + this.port = port; + } + public void setPath( String path ){ + if( path.length() >= 1 && !path.startsWith(PATH_SEPARATOR)) + path = PATH_SEPARATOR + path; + this.path = path; + } + public void setAnchor( String anch ){ + this.anchor = anch; + } + public void setParameter( String key, String value ){ + this.parameters.put(key, value); + } + + protected void setParameters( HashMap pars ){ + this.parameters = pars; + } + + /** + * Generates the parameter string in a URL. + * + * e.g. + * "key=value&key2=value&..." + */ + public String getParameterString(){ + StringBuilder param = new StringBuilder(); + for(String key : parameters.keySet()){ + if (param.length() > 0) + param.append('&'); + param.append(key); + param.append('='); + param.append( parameters.get(key) ); + } + return param.toString(); + } + + /** + * Generates a path that are used in the HTTP header + */ + public String getHttpURL(){ + StringBuilder url = new StringBuilder(); + url.append( path ); + if( !parameters.isEmpty() ) + url.append( PARAMETER_SEPARATOR ).append( getParameterString() ); + + return url.toString(); + } + + /** + * Generates a full URL + */ + public String getURL(){ + return toString(); + } + + /** + * Generates the whole URL + */ + public String toString(){ + StringBuilder url = new StringBuilder(); + url.append( protocol ); + url.append( PROTOCOL_SEPARATOR ); + url.append( host ); + if( port > 0 ) + url.append( PORT_SEPARATOR ).append( port ); + + if( path != null ) + url.append( path ); + else + url.append( PATH_SEPARATOR ); + + if( !parameters.isEmpty() ) + url.append( PARAMETER_SEPARATOR ).append( getParameterString() ); + if( anchor != null ) + url.append( ANCHOR_SEPARATOR ).append( anchor ); + + return url.toString(); + } } diff --git a/src/zutil/net/http/multipart/MultipartField.java b/src/zutil/net/http/multipart/MultipartField.java index 9dae5a4..cdcecb9 100755 --- a/src/zutil/net/http/multipart/MultipartField.java +++ b/src/zutil/net/http/multipart/MultipartField.java @@ -31,14 +31,14 @@ package zutil.net.http.multipart; * @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(); - - /** - * @return the name of the field. - */ - public String getName(); + /** + * @return the amount of data received for this field. Might only be available when all data has been processed + */ + public long getLength(); + + /** + * @return the name of the field. + */ + public String getName(); } diff --git a/src/zutil/net/http/multipart/MultipartFileField.java b/src/zutil/net/http/multipart/MultipartFileField.java index dc91459..ffacf73 100755 --- a/src/zutil/net/http/multipart/MultipartFileField.java +++ b/src/zutil/net/http/multipart/MultipartFileField.java @@ -42,26 +42,26 @@ import static zutil.net.http.multipart.MultipartParser.HEADER_CONTENT_TYPE; public class MultipartFileField implements MultipartField{ private static final Logger logger = LogUtil.getLogger(); - private String fieldname; - private String filename; + private String fieldname; + private String filename; private String contentType; private byte[] content; private InputStream in; - protected MultipartFileField(Map headers, InputStream in) throws IOException { - this.fieldname = headers.get("name"); - this.filename = headers.get("filename"); - this.contentType = headers.get(HEADER_CONTENT_TYPE); + protected MultipartFileField(Map headers, InputStream in) throws IOException { + this.fieldname = headers.get("name"); + this.filename = headers.get("filename"); + this.contentType = headers.get(HEADER_CONTENT_TYPE); this.in = in; - } - - /** - * @return the amount of data received for this field - */ - public long getLength(){ - return 0; //TODO: - } + } + + /** + * @return the amount of data received for this field + */ + public long getLength(){ + return 0; //TODO: + } /** * @return the field name @@ -70,13 +70,13 @@ public class MultipartFileField implements MultipartField{ return fieldname; } - public String getFilename(){ - return filename; - } + public String getFilename(){ + return filename; + } - public String getContentType() { - return contentType; - } + public String getContentType() { + return contentType; + } @@ -100,20 +100,20 @@ public class MultipartFileField implements MultipartField{ } /** - * Reads in all data and save it into the specified file. + * Reads in all data and save it into the specified file. * * Note: Only one of the methods {@link #getContent()} or * {@link #saveToFile(File)} can be used as they will consume the data in the stream. - * - * @param file is the new file where the data will be stored - */ - public void saveToFile(File file) throws IOException { - if (in == null) - throw new IOException("Stream already consumed."); + * + * @param file is the new file where the data will be stored + */ + public void saveToFile(File file) throws IOException { + if (in == null) + throw new IOException("Stream already consumed."); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); IOUtil.copyStream(in, out); out.close(); in = null; // reset InputStream - } + } } diff --git a/src/zutil/net/http/multipart/MultipartParser.java b/src/zutil/net/http/multipart/MultipartParser.java index 0fa5cfd..dbdaecd 100755 --- a/src/zutil/net/http/multipart/MultipartParser.java +++ b/src/zutil/net/http/multipart/MultipartParser.java @@ -51,12 +51,12 @@ public class MultipartParser implements Iterable{ protected static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition".toUpperCase(); protected static final String HEADER_CONTENT_TYPE = "Content-Type".toUpperCase(); - /** This is the delimiter that will separate the fields */ - private String delimiter; - /** The length of the HTTP Body */ - private long contentLength; - /** This is the input stream */ - private InputStream in; + /** This is the delimiter that will separate the fields */ + private String delimiter; + /** The length of the HTTP Body */ + private long contentLength; + /** This is the input stream */ + private InputStream in; private MultiPartIterator iterator; @@ -66,11 +66,11 @@ public class MultipartParser implements Iterable{ this.delimiter = delimiter; this.contentLength = length; } - public MultipartParser(HttpHeader header){ - this(header.getInputStream(), + public MultipartParser(HttpHeader header){ + this(header.getInputStream(), parseDelimiter(header.getHeader("Content-type")), Long.parseLong(header.getHeader("Content-Length"))); - } + } private static String parseDelimiter(String contentTypeHeader){ String delimiter = contentTypeHeader.split(" *; *")[1]; @@ -78,18 +78,18 @@ public class MultipartParser implements Iterable{ return delimiter; } - public long getContentLength(){ - return contentLength; - } + public long getContentLength(){ + return contentLength; + } - @Override - public Iterator iterator() { + @Override + public Iterator iterator() { if (iterator == null) iterator = new MultiPartIterator(); - return iterator; - } + return iterator; + } protected class MultiPartIterator implements Iterator{ diff --git a/src/zutil/net/nio/NioClient.java b/src/zutil/net/nio/NioClient.java index 0e36ee0..5928d78 100755 --- a/src/zutil/net/nio/NioClient.java +++ b/src/zutil/net/nio/NioClient.java @@ -35,43 +35,43 @@ import java.nio.channels.spi.SelectorProvider; public class NioClient extends NioNetwork{ - private InetSocketAddress remoteAddress; - - /** - * Creates a NioClient that connects to a server - * - * @param remoteAddress the server address - * @param remotePort the port to listen on - */ - public NioClient(InetAddress remoteAddress, int remotePort) throws IOException { - this.remoteAddress = new InetSocketAddress(remoteAddress, remotePort); - connect(this.remoteAddress); - } + private InetSocketAddress remoteAddress; - protected Selector initSelector() throws IOException { - // Create a new selector - return SelectorProvider.provider().openSelector(); - } - - /** - * Sends a Message to the connected server - * - * @param data the data to be sent - */ - public void send(Message data) throws IOException { - send(remoteAddress, data); - } + /** + * Creates a NioClient that connects to a server + * + * @param remoteAddress the server address + * @param remotePort the port to listen on + */ + public NioClient(InetAddress remoteAddress, int remotePort) throws IOException { + this.remoteAddress = new InetSocketAddress(remoteAddress, remotePort); + connect(this.remoteAddress); + } - /** - * Sends a Message to the connected server - * - * @param data the data to be sent - */ - public void send(byte[] data) throws IOException { - send(remoteAddress, data); - } + protected Selector initSelector() throws IOException { + // Create a new selector + return SelectorProvider.provider().openSelector(); + } - public SocketAddress getRemoteAddress(){ - return remoteAddress; + /** + * Sends a Message to the connected server + * + * @param data the data to be sent + */ + public void send(Message data) throws IOException { + send(remoteAddress, data); + } + + /** + * Sends a Message to the connected server + * + * @param data the data to be sent + */ + public void send(byte[] data) throws IOException { + send(remoteAddress, data); + } + + public SocketAddress getRemoteAddress(){ + return remoteAddress; } } diff --git a/src/zutil/net/nio/NioNetwork.java b/src/zutil/net/nio/NioNetwork.java index 9971c7b..652b059 100755 --- a/src/zutil/net/nio/NioNetwork.java +++ b/src/zutil/net/nio/NioNetwork.java @@ -43,33 +43,33 @@ import java.util.logging.Logger; public abstract class NioNetwork implements Runnable { - private static Logger logger = LogUtil.getLogger(); + private static Logger logger = LogUtil.getLogger(); - protected SocketAddress localAddress; - // The channel on which we'll accept connections - protected ServerSocketChannel serverChannel; - // The selector we will be monitoring - private Selector selector; - // The buffer into which we'll read data when it's available - private ByteBuffer readBuffer = ByteBuffer.allocate(8192); - protected Worker worker; + protected SocketAddress localAddress; + // The channel on which we'll accept connections + protected ServerSocketChannel serverChannel; + // The selector we will be monitoring + private Selector selector; + // The buffer into which we'll read data when it's available + private ByteBuffer readBuffer = ByteBuffer.allocate(8192); + protected Worker worker; - // This map contains all the clients that are connected - protected Map clients = new HashMap(); + // This map contains all the clients that are connected + protected Map clients = new HashMap(); - // A list of PendingChange instances - private List pendingChanges = new LinkedList(); - // Maps a SocketChannel to a list of ByteBuffer instances - private Map> pendingWriteData = new HashMap>(); + // A list of PendingChange instances + private List pendingChanges = new LinkedList(); + // Maps a SocketChannel to a list of ByteBuffer instances + private Map> pendingWriteData = new HashMap>(); - /** - * Create a client based Network object - */ - public NioNetwork() throws IOException { - this(null); - } + /** + * Create a client based Network object + */ + public NioNetwork() throws IOException { + this(null); + } /** * Create a server based Network object @@ -77,25 +77,25 @@ public abstract class NioNetwork implements Runnable { * @param localAddress the address the server will listen on */ public NioNetwork(SocketAddress localAddress) throws IOException { - this.localAddress = localAddress; - // init selector + this.localAddress = localAddress; + // init selector this.selector = initSelector(); // init traffic thread new Thread(this).start(); } - protected abstract Selector initSelector() throws IOException; + protected abstract Selector initSelector() throws IOException; - /** - * Sets the default worker for non System messages. - * - * @param worker the worker that should handle incoming messages - */ - public void setDefaultWorker(Worker worker){ - this.worker = worker; - } + /** + * Sets the default worker for non System messages. + * + * @param worker the worker that should handle incoming messages + */ + public void setDefaultWorker(Worker worker){ + this.worker = worker; + } /** @@ -118,9 +118,9 @@ public abstract class NioNetwork implements Runnable { } - public void send(SocketAddress address, Object data) throws IOException{ - send(address, Converter.toBytes(data)); - } + public void send(SocketAddress address, Object data) throws IOException{ + send(address, Converter.toBytes(data)); + } /** * Queues a message to be sent @@ -128,61 +128,61 @@ public abstract class NioNetwork implements Runnable { * @param address the target address where the message should be sent * @param data the data to send */ - public void send(SocketAddress address, byte[] data){ + public void send(SocketAddress address, byte[] data){ logger.finest("Sending Queue..."); - SocketChannel socket = getSocketChannel(address); + SocketChannel socket = getSocketChannel(address); - // And queue the data we want written - synchronized (pendingWriteData) { - List queue = pendingWriteData.get(socket); - if (queue == null) { - queue = new ArrayList<>(); - pendingWriteData.put(socket, queue); - } - queue.add(ByteBuffer.wrap(data)); - } - // Changing the key state to write - synchronized (pendingChanges) { - // Indicate we want the interest ops set changed - pendingChanges.add(new ChangeRequest(socket, ChangeRequest.CHANGEOPS, SelectionKey.OP_WRITE)); - } - // Finally, wake up our selecting thread so it can make the required changes - selector.wakeup(); - } + // And queue the data we want written + synchronized (pendingWriteData) { + List queue = pendingWriteData.get(socket); + if (queue == null) { + queue = new ArrayList<>(); + pendingWriteData.put(socket, queue); + } + queue.add(ByteBuffer.wrap(data)); + } + // Changing the key state to write + synchronized (pendingChanges) { + // Indicate we want the interest ops set changed + pendingChanges.add(new ChangeRequest(socket, ChangeRequest.CHANGEOPS, SelectionKey.OP_WRITE)); + } + // Finally, wake up our selecting thread so it can make the required changes + selector.wakeup(); + } - public void run() { - logger.info("NioNetwork Started."); - while (selector.isOpen()) { - try { - // Handle any pending changes - synchronized (pendingChanges) { - Iterator changes = pendingChanges.iterator(); - while (changes.hasNext()) { - ChangeRequest change = changes.next(); - 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; - } - } - pendingChanges.clear(); - } + public void run() { + logger.info("NioNetwork Started."); + while (selector.isOpen()) { + try { + // Handle any pending changes + synchronized (pendingChanges) { + Iterator changes = pendingChanges.iterator(); + while (changes.hasNext()) { + ChangeRequest change = changes.next(); + 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; + } + } + pendingChanges.clear(); + } - // Wait for an event from one of the channels - selector.select(); - logger.finest("selector is awake"); + // Wait for an event from one of the channels + selector.select(); + logger.finest("selector is awake"); - // Iterate over the set of keys for which events are available + // Iterate over the set of keys for which events are available if (selector.isOpen()) { Iterator selectedKeys = selector.selectedKeys().iterator(); while (selectedKeys.hasNext()) { @@ -208,33 +208,33 @@ public abstract class NioNetwork implements Runnable { } } } - } catch (Exception e) { - e.printStackTrace(); - } - } - logger.info("Shutting down NioNetwork"); - } + } catch (Exception e) { + e.printStackTrace(); + } + } + logger.info("Shutting down NioNetwork"); + } - /** - * Handle an accept event from a remote host. Channel can only be a server socket. - */ - private void accept(SelectionKey key) throws IOException { - // For an accept to be pending the channel must be a server socket channel. - ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); + /** + * Handle an accept event from a remote host. Channel can only be a server socket. + */ + private void accept(SelectionKey key) throws IOException { + // For an accept to be pending the channel must be a server socket channel. + ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); - // Accept the connection and make it non-blocking - SocketChannel socketChannel = serverSocketChannel.accept(); - socketChannel.socket().setReuseAddress(true); - socketChannel.configureBlocking(false); + // Accept the connection and make it non-blocking + SocketChannel socketChannel = serverSocketChannel.accept(); + socketChannel.socket().setReuseAddress(true); + socketChannel.configureBlocking(false); - // Register the new SocketChannel with our Selector, indicating - // we'd like to be notified when there's data waiting to be read - socketChannel.register(selector, SelectionKey.OP_READ); + // Register the new SocketChannel with our Selector, indicating + // we'd like to be notified when there's data waiting to be read + socketChannel.register(selector, SelectionKey.OP_READ); - // adds the client to the clients list + // adds the client to the clients list registerSocketChannel(socketChannel); logger.fine("New Connection("+socketChannel.getRemoteAddress()+")!!! Count: "+clients.size()); - } + } /** * Finnish an ongoing remote connection establishment procedure @@ -291,47 +291,47 @@ public abstract class NioNetwork implements Runnable { } } - /** - * Handle a read event from a socket specified by the key. - */ - private void read(SelectionKey key) throws IOException { - SocketChannel socketChannel = (SocketChannel) key.channel(); - SocketAddress remoteAdr = socketChannel.socket().getRemoteSocketAddress(); + /** + * Handle a read event from a socket specified by the key. + */ + private void read(SelectionKey key) throws IOException { + SocketChannel socketChannel = (SocketChannel) key.channel(); + SocketAddress remoteAdr = socketChannel.socket().getRemoteSocketAddress(); - // Clear out our read buffer so it's ready for new data - readBuffer.clear(); + // Clear out our read buffer so it's ready for new data + readBuffer.clear(); - // Attempt to read off the channel - int numRead; - try { - numRead = socketChannel.read(readBuffer); - } catch (IOException e) { - // The remote forcibly closed the connection, cancel - // the selection key and close the channel. - key.cancel(); - socketChannel.close(); - clients.remove(remoteAdr); - pendingWriteData.remove(socketChannel); - logger.fine("Connection forcibly closed("+remoteAdr+")! Remaining connections: "+clients.size()); - throw new IOException("Remote forcibly closed the connection"); - } + // Attempt to read off the channel + int numRead; + try { + numRead = socketChannel.read(readBuffer); + } catch (IOException e) { + // The remote forcibly closed the connection, cancel + // the selection key and close the channel. + key.cancel(); + socketChannel.close(); + clients.remove(remoteAdr); + pendingWriteData.remove(socketChannel); + logger.fine("Connection forcibly closed("+remoteAdr+")! Remaining connections: "+clients.size()); + throw new IOException("Remote forcibly closed the connection"); + } - if (numRead == -1) { - // Remote entity shut the socket down cleanly. Do the - // same from our end and cancel the channel. - key.channel().close(); - key.cancel(); - clients.remove(remoteAdr); - pendingWriteData.remove(socketChannel); - logger.fine("Connection Closed("+remoteAdr+")! Remaining connections: "+clients.size()); + if (numRead == -1) { + // Remote entity shut the socket down cleanly. Do the + // same from our end and cancel the channel. + key.channel().close(); + key.cancel(); + clients.remove(remoteAdr); + pendingWriteData.remove(socketChannel); + logger.fine("Connection Closed("+remoteAdr+")! Remaining connections: "+clients.size()); throw new IOException("Remote closed the connection"); - } + } - // Make a correctly sized copy of the data before handing it to the client - //byte[] rspByteData = new byte[numRead]; - //System.arraycopy(readBuffer.array(), 0, rspByteData, 0, numRead); + // Make a correctly sized copy of the data before handing it to the client + //byte[] rspByteData = new byte[numRead]; + //System.arraycopy(readBuffer.array(), 0, rspByteData, 0, numRead); - try{ + try{ Object rspData = Converter.toObject(readBuffer.array()); // Hand the data off to our worker thread @@ -341,10 +341,10 @@ public abstract class NioNetwork implements Runnable { } else { logger.fine("No worker set, message unhandled!"); } - }catch(Exception e){ - e.printStackTrace(); - } - } + }catch(Exception e){ + e.printStackTrace(); + } + } @@ -370,22 +370,22 @@ public abstract class NioNetwork implements Runnable { closeConnection(getSocketChannel(address)); } - private void closeConnection(SocketChannel socketChannel) throws IOException{ - socketChannel.close(); - socketChannel.keyFor(selector).cancel(); - } + private void closeConnection(SocketChannel socketChannel) throws IOException{ + socketChannel.close(); + socketChannel.keyFor(selector).cancel(); + } /** * Close all connections */ - public void close() throws IOException{ - if(serverChannel != null){ - serverChannel.close(); - serverChannel.keyFor(selector).cancel(); - } + public void close() throws IOException{ + if(serverChannel != null){ + serverChannel.close(); + serverChannel.keyFor(selector).cancel(); + } clients.clear(); pendingChanges.clear(); pendingWriteData.clear(); selector.close(); - } + } } diff --git a/src/zutil/net/nio/NioServer.java b/src/zutil/net/nio/NioServer.java index 93ca788..256c322 100755 --- a/src/zutil/net/nio/NioServer.java +++ b/src/zutil/net/nio/NioServer.java @@ -35,56 +35,56 @@ import java.util.Iterator; public class NioServer extends NioNetwork{ - - /** - * Creates a NioServer object which listens on localhost - * - * @param port the port to listen to - */ - public NioServer(int port) throws IOException { - this(null, port); - } - - /** - * Creates a NioServer object which listens to a specific address - * - * @param address the address to listen to - * @param port the port to listen to - */ - public NioServer(InetAddress address, int port) throws IOException { - super(new InetSocketAddress(address, port)); - } - protected Selector initSelector() throws IOException { - // Create a new selector - Selector socketSelector = SelectorProvider.provider().openSelector(); + /** + * Creates a NioServer object which listens on localhost + * + * @param port the port to listen to + */ + public NioServer(int port) throws IOException { + this(null, port); + } - // Create a new non-blocking server socket channel - serverChannel = ServerSocketChannel.open(); - serverChannel.socket().setReuseAddress(true); - serverChannel.configureBlocking(false); + /** + * Creates a NioServer object which listens to a specific address + * + * @param address the address to listen to + * @param port the port to listen to + */ + public NioServer(InetAddress address, int port) throws IOException { + super(new InetSocketAddress(address, port)); + } - // Bind the server socket to the specified address and port - serverChannel.socket().bind(localAddress); + protected Selector initSelector() throws IOException { + // Create a new selector + Selector socketSelector = SelectorProvider.provider().openSelector(); - // Register the server socket channel, indicating an interest in - // accepting new connections - serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT); + // Create a new non-blocking server socket channel + serverChannel = ServerSocketChannel.open(); + serverChannel.socket().setReuseAddress(true); + serverChannel.configureBlocking(false); - return socketSelector; - } + // Bind the server socket to the specified address and port + serverChannel.socket().bind(localAddress); + + // Register the server socket channel, indicating an interest in + // accepting new connections + serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT); + + return socketSelector; + } + + /** + * Broadcasts the message to all the connected clients + * + * @param data the data to broadcast + */ + public void broadcast(byte[] data){ + synchronized(clients){ + for(InetSocketAddress target : clients.keySet()){ + send(target, data); + } + } + } - /** - * Broadcasts the message to all the connected clients - * - * @param data the data to broadcast - */ - public void broadcast(byte[] data){ - synchronized(clients){ - for(InetSocketAddress target : clients.keySet()){ - send(target, data); - } - } - } - } diff --git a/src/zutil/net/nio/message/EchoMessage.java b/src/zutil/net/nio/message/EchoMessage.java index a182a4c..3bf08b8 100755 --- a/src/zutil/net/nio/message/EchoMessage.java +++ b/src/zutil/net/nio/message/EchoMessage.java @@ -30,22 +30,22 @@ package zutil.net.nio.message; * @author Ziver */ public abstract class EchoMessage implements Message{ - private static final long serialVersionUID = 1L; - - private boolean echo = false; + private static final long serialVersionUID = 1L; + + private boolean echo = false; - /** - * @return true if this message is an echo/copy of an original message - */ - public boolean echo() { - return echo; - } - - /** - * Called by the receiver to mark this message as an echo copy - */ - public void received() { - echo = true; - } + /** + * @return true if this message is an echo/copy of an original message + */ + public boolean echo() { + return echo; + } + + /** + * Called by the receiver to mark this message as an echo copy + */ + public void received() { + echo = true; + } } diff --git a/src/zutil/net/nio/response/PrintResponseHandler.java b/src/zutil/net/nio/response/PrintResponseHandler.java index e346fed..380052c 100755 --- a/src/zutil/net/nio/response/PrintResponseHandler.java +++ b/src/zutil/net/nio/response/PrintResponseHandler.java @@ -27,9 +27,9 @@ package zutil.net.nio.response; public class PrintResponseHandler extends ResponseHandler { - @Override - protected void responseEvent(Object rsp) { - System.out.println(rsp); - } + @Override + protected void responseEvent(Object rsp) { + System.out.println(rsp); + } } diff --git a/src/zutil/net/nio/response/RequestResponseMessage.java b/src/zutil/net/nio/response/RequestResponseMessage.java index 1d955ee..a4096e4 100755 --- a/src/zutil/net/nio/response/RequestResponseMessage.java +++ b/src/zutil/net/nio/response/RequestResponseMessage.java @@ -33,9 +33,9 @@ package zutil.net.nio.response; */ public interface RequestResponseMessage { - /** - * @return a unique id for this message - */ - long getResponseId(); - + /** + * @return a unique id for this message + */ + long getResponseId(); + } diff --git a/src/zutil/net/nio/response/ResponseHandler.java b/src/zutil/net/nio/response/ResponseHandler.java index d3091b1..0c659ef 100755 --- a/src/zutil/net/nio/response/ResponseHandler.java +++ b/src/zutil/net/nio/response/ResponseHandler.java @@ -26,33 +26,33 @@ package zutil.net.nio.response; // TODO: this class has a strange structure, should be refactored public abstract class ResponseHandler { - private Object rsp = null; + private Object rsp = null; - public synchronized void handleResponse(Object rsp) { - this.rsp = rsp; + public synchronized void handleResponse(Object rsp) { + this.rsp = rsp; responseEvent(rsp); - notify(); - } + notify(); + } - /** - * Blocks the calling thread until there is a response - */ - public void waitForResponse() { - while(!gotResponse()) { - try { - synchronized (this) { + /** + * Blocks the calling thread until there is a response + */ + public void waitForResponse() { + while(!gotResponse()) { + try { + synchronized (this) { this.wait(); } - } catch (InterruptedException e) {} - } - } + } catch (InterruptedException e) {} + } + } - /** - * @return true if a response has been received - */ - public boolean gotResponse(){ - return (rsp != null); - } + /** + * @return true if a response has been received + */ + public boolean gotResponse(){ + return (rsp != null); + } - protected abstract void responseEvent(Object rsp); + protected abstract void responseEvent(Object rsp); } diff --git a/src/zutil/net/nio/response/StringResponseMessage.java b/src/zutil/net/nio/response/StringResponseMessage.java index f447d15..b6095a7 100755 --- a/src/zutil/net/nio/response/StringResponseMessage.java +++ b/src/zutil/net/nio/response/StringResponseMessage.java @@ -28,27 +28,27 @@ package zutil.net.nio.response; import zutil.net.nio.message.EchoMessage; public class StringResponseMessage extends EchoMessage implements RequestResponseMessage { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private long responseId; - private String msg; + private long responseId; + private String msg; - public StringResponseMessage(String msg){ - this.msg = msg; - responseId = (long)(Math.random()*Long.MAX_VALUE); - } + public StringResponseMessage(String msg){ + this.msg = msg; + responseId = (long)(Math.random()*Long.MAX_VALUE); + } public long getResponseId() { return responseId; } - public void setString(String msg){ - this.msg = msg; - } - - public String toString(){ - return msg; - } + public void setString(String msg){ + this.msg = msg; + } + + public String toString(){ + return msg; + } } \ No newline at end of file diff --git a/src/zutil/net/nio/server/ChangeRequest.java b/src/zutil/net/nio/server/ChangeRequest.java index ee59c61..92eafd4 100755 --- a/src/zutil/net/nio/server/ChangeRequest.java +++ b/src/zutil/net/nio/server/ChangeRequest.java @@ -28,17 +28,17 @@ import java.nio.channels.SocketChannel; public class ChangeRequest { - public static final int REGISTER = 1; - public static final int CHANGEOPS = 2; - - public SocketChannel socket; - public int type; - public int ops; + public static final int REGISTER = 1; + public static final int CHANGEOPS = 2; + + public SocketChannel socket; + public int type; + public int ops; - public ChangeRequest(SocketChannel socket, int type, int ops) { - this.socket = socket; - this.type = type; - this.ops = ops; - } + public ChangeRequest(SocketChannel socket, int type, int ops) { + this.socket = socket; + this.type = type; + this.ops = ops; + } } diff --git a/src/zutil/net/nio/server/ClientData.java b/src/zutil/net/nio/server/ClientData.java index e590acb..fcda9ad 100755 --- a/src/zutil/net/nio/server/ClientData.java +++ b/src/zutil/net/nio/server/ClientData.java @@ -28,28 +28,28 @@ import java.net.InetSocketAddress; import java.nio.channels.SocketChannel; public class ClientData { - private SocketChannel socketChannel; - private long lastMessageReceived; + private SocketChannel socketChannel; + private long lastMessageReceived; - public ClientData(SocketChannel socketChannel){ - this.socketChannel = socketChannel; - } + public ClientData(SocketChannel socketChannel){ + this.socketChannel = socketChannel; + } - public SocketChannel getSocketChannel(){ - return socketChannel; - } - - public InetSocketAddress getAddress(){ - return (InetSocketAddress) socketChannel.socket().getRemoteSocketAddress(); - } - - public void setLastMessageReceived(long time){ - lastMessageReceived = time; - } - - public long getLastMessageReceived(){ - return lastMessageReceived; - } + public SocketChannel getSocketChannel(){ + return socketChannel; + } + + public InetSocketAddress getAddress(){ + return (InetSocketAddress) socketChannel.socket().getRemoteSocketAddress(); + } + + public void setLastMessageReceived(long time){ + lastMessageReceived = time; + } + + public long getLastMessageReceived(){ + return lastMessageReceived; + } } diff --git a/src/zutil/net/nio/worker/StandardWorker.java b/src/zutil/net/nio/worker/StandardWorker.java index e66192f..30a4f15 100755 --- a/src/zutil/net/nio/worker/StandardWorker.java +++ b/src/zutil/net/nio/worker/StandardWorker.java @@ -40,29 +40,29 @@ import java.util.logging.Logger; public class StandardWorker extends ThreadedEventWorker { - private static Logger logger = LogUtil.getLogger(); + private static Logger logger = LogUtil.getLogger(); - private NioNetwork nio; - // Maps a responseId to a RspHandler - private Map rspEvents = new HashMap<>(); - // Different services listening on specific messages - private Map, ThreadedEventWorker> services = new HashMap<>(); + private NioNetwork nio; + // Maps a responseId to a RspHandler + private Map rspEvents = new HashMap<>(); + // Different services listening on specific messages + private Map, ThreadedEventWorker> services = new HashMap<>(); - /** - * Creates a new StandardWorker - */ - public StandardWorker(NioNetwork nio){ - this.nio = nio; - } + /** + * Creates a new StandardWorker + */ + public StandardWorker(NioNetwork nio){ + this.nio = nio; + } - @Override - public void messageEvent(WorkerEventData event) { - try { - logger.finer("Message: "+event.data.getClass().getName()); + @Override + public void messageEvent(WorkerEventData event) { + try { + logger.finer("Message: "+event.data.getClass().getName()); if(event.data instanceof EchoMessage && !((EchoMessage)event.data).echo()){ // Echo back the received message @@ -86,29 +86,29 @@ public class StandardWorker extends ThreadedEventWorker { services.get(event.data.getClass()).messageEvent(event); } } - } catch (Exception e) { - e.printStackTrace(); - } - } + } catch (Exception e) { + e.printStackTrace(); + } + } - /** - * Maps a Worker to a specific message - * - * @param messageClass the received message class - * @param worker the worker that should handle the specified message type - */ - public void registerWorker(Class messageClass, ThreadedEventWorker worker){ - services.put(messageClass, worker); - } - - /** - * Un-maps a message class to a worker - * + /** + * Maps a Worker to a specific message + * * @param messageClass the received message class - */ - public void unregisterWorker(Class messageClass){ - services.remove(messageClass); - } + * @param worker the worker that should handle the specified message type + */ + public void registerWorker(Class messageClass, ThreadedEventWorker worker){ + services.put(messageClass, worker); + } + + /** + * Un-maps a message class to a worker + * + * @param messageClass the received message class + */ + public void unregisterWorker(Class messageClass){ + services.remove(messageClass); + } /** * Send a message with a defined response handler @@ -117,10 +117,10 @@ public class StandardWorker extends ThreadedEventWorker { * @param message the message object * @param handler the handler that should be called when a response is received */ - public void send(SocketAddress address, RequestResponseMessage message, ResponseHandler handler) throws IOException { - // Register the response handler - rspEvents.put(message.getResponseId(), handler); + public void send(SocketAddress address, RequestResponseMessage message, ResponseHandler handler) throws IOException { + // Register the response handler + rspEvents.put(message.getResponseId(), handler); - nio.send(address, Converter.toBytes(message)); - } + nio.send(address, Converter.toBytes(message)); + } } diff --git a/src/zutil/net/nio/worker/ThreadedEventWorker.java b/src/zutil/net/nio/worker/ThreadedEventWorker.java index 3603ecc..06bdff6 100755 --- a/src/zutil/net/nio/worker/ThreadedEventWorker.java +++ b/src/zutil/net/nio/worker/ThreadedEventWorker.java @@ -25,24 +25,24 @@ package zutil.net.nio.worker; public abstract class ThreadedEventWorker extends Worker implements Runnable{ - private Thread thread; + private Thread thread; - public ThreadedEventWorker(){ - thread = new Thread(this); - thread.start(); - } + public ThreadedEventWorker(){ + thread = new Thread(this); + thread.start(); + } - public void run() { - while(true) { - try{ - // Wait for data to become available - messageEvent(pollEvent()); - } catch (Exception e) { - e.printStackTrace(); - } - } - } + public void run() { + while(true) { + try{ + // Wait for data to become available + messageEvent(pollEvent()); + } catch (Exception e) { + e.printStackTrace(); + } + } + } - public abstract void messageEvent(WorkerEventData e); + public abstract void messageEvent(WorkerEventData e); } diff --git a/src/zutil/net/nio/worker/Worker.java b/src/zutil/net/nio/worker/Worker.java index 8d2b390..622b545 100755 --- a/src/zutil/net/nio/worker/Worker.java +++ b/src/zutil/net/nio/worker/Worker.java @@ -32,37 +32,37 @@ import java.util.List; public abstract class Worker { - private LinkedList queue = new LinkedList<>(); + private LinkedList queue = new LinkedList<>(); - public void processData(NioNetwork server, SocketAddress remote, Object data) { - synchronized(queue) { - queue.add(new WorkerEventData(server, remote, data)); - queue.notify(); - } - } - + public void processData(NioNetwork server, SocketAddress remote, Object data) { + synchronized(queue) { + queue.add(new WorkerEventData(server, remote, data)); + queue.notify(); + } + } - /** - * @return true if there is a event in the queue - */ - protected boolean hasEvent(){ - return !queue.isEmpty(); - } - - /** - * Polls a event from the list or blocks until there is a event available + + /** + * @return true if there is a event in the queue + */ + protected boolean hasEvent(){ + return !queue.isEmpty(); + } + + /** + * Polls a event from the list or blocks until there is a event available * - * @return the next event - */ - protected WorkerEventData pollEvent(){ - synchronized(queue) { - while (queue.isEmpty()) { - try { - queue.wait(); - } catch (InterruptedException e) {} - } - } - return queue.poll(); - } + * @return the next event + */ + protected WorkerEventData pollEvent(){ + synchronized(queue) { + while (queue.isEmpty()) { + try { + queue.wait(); + } catch (InterruptedException e) {} + } + } + return queue.poll(); + } } diff --git a/src/zutil/net/nio/worker/WorkerEventData.java b/src/zutil/net/nio/worker/WorkerEventData.java index 6a484a5..6b52934 100755 --- a/src/zutil/net/nio/worker/WorkerEventData.java +++ b/src/zutil/net/nio/worker/WorkerEventData.java @@ -31,14 +31,14 @@ import java.nio.channels.SocketChannel; public class WorkerEventData { - public NioNetwork network; - public SocketAddress remoteAddress; - public Object data; + public NioNetwork network; + public SocketAddress remoteAddress; + public Object data; - public WorkerEventData(NioNetwork server, SocketAddress remoteAddress, Object data) { - this.network = server; - this.remoteAddress = remoteAddress; - this.data = data; - } + public WorkerEventData(NioNetwork server, SocketAddress remoteAddress, Object data) { + this.network = server; + this.remoteAddress = remoteAddress; + this.data = data; + } } diff --git a/src/zutil/net/nio/worker/chat/ChatListener.java b/src/zutil/net/nio/worker/chat/ChatListener.java index 3d99d9c..cdcb65b 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); + public void messageAction(String msg, String room); } diff --git a/src/zutil/net/nio/worker/chat/ChatService.java b/src/zutil/net/nio/worker/chat/ChatService.java index 4c4850d..7232283 100755 --- a/src/zutil/net/nio/worker/chat/ChatService.java +++ b/src/zutil/net/nio/worker/chat/ChatService.java @@ -39,24 +39,24 @@ import java.util.logging.Logger; * @author Ziver */ public class ChatService extends ThreadedEventWorker{ - private static Logger logger = LogUtil.getLogger(); + private static Logger logger = LogUtil.getLogger(); - private HashMap> rooms = new HashMap<>(); - private ChatListener listener; + private HashMap> rooms = new HashMap<>(); + private ChatListener listener; - @Override + @Override public void messageEvent(WorkerEventData event) { - try { - // New message - if(event.data instanceof ChatMessage){ - ChatMessage chatmessage = (ChatMessage)event.data; - //is this a new message - if(chatmessage.type == ChatMessage.ChatMessageType.MESSAGE){ - // Is this the server + try { + // New message + if(event.data instanceof ChatMessage){ + ChatMessage chatmessage = (ChatMessage)event.data; + //is this a new message + if(chatmessage.type == ChatMessage.ChatMessageType.MESSAGE){ + // Is this the server if(rooms.containsKey(chatmessage.room)){ LinkedList tmpList = rooms.get(chatmessage.room); @@ -65,81 +65,81 @@ public class ChatService extends ThreadedEventWorker{ event.network.send(remote, chatmessage); // TODO: should not be done for clients } } - logger.finer("New Chat Message: "+chatmessage.msg); - listener.messageAction(chatmessage.msg, chatmessage.room); - } - // register to a room - else if(chatmessage.type == ChatMessage.ChatMessageType.REGISTER){ - registerUser(chatmessage.room, event.remoteAddress); - } - // unregister to a room - else if(chatmessage.type == ChatMessage.ChatMessageType.UNREGISTER){ - unRegisterUser(chatmessage.room, event.remoteAddress); - } - } - } catch (Exception e) { - e.printStackTrace(); - } + logger.finer("New Chat Message: "+chatmessage.msg); + listener.messageAction(chatmessage.msg, chatmessage.room); + } + // register to a room + else if(chatmessage.type == ChatMessage.ChatMessageType.REGISTER){ + registerUser(chatmessage.room, event.remoteAddress); + } + // unregister to a room + else if(chatmessage.type == ChatMessage.ChatMessageType.UNREGISTER){ + unRegisterUser(chatmessage.room, event.remoteAddress); + } + } + } catch (Exception e) { + e.printStackTrace(); + } - } + } - /** - * Registers a user to the main room - * - * @param remoteAddress the address of the remote user - */ - public void registerUser(SocketAddress remoteAddress){ - registerUser("", remoteAddress); - } + /** + * Registers a user to the main room + * + * @param remoteAddress the address of the remote user + */ + public void registerUser(SocketAddress remoteAddress){ + registerUser("", remoteAddress); + } - /** - * Registers the given user to a specific room - * - * @param room the room name - * @param remoteAddress the address of the remote user - */ - public void registerUser(String room, SocketAddress remoteAddress){ - addRoom(room); - logger.fine("New Chat User: "+remoteAddress); - rooms.get(room).add(remoteAddress); - } + /** + * Registers the given user to a specific room + * + * @param room the room name + * @param remoteAddress the address of the remote user + */ + public void registerUser(String room, SocketAddress remoteAddress){ + addRoom(room); + logger.fine("New Chat User: "+remoteAddress); + rooms.get(room).add(remoteAddress); + } - /** - * Unregisters a user from a room and removes the room if its empty - * - * @param room the room name - * @param remoteAddress the address of the remote user - */ - public void unRegisterUser(String room, SocketAddress remoteAddress){ - if(rooms.containsKey(room)){ - logger.fine("Remove Chat User: "+remoteAddress); - rooms.get(room).remove(remoteAddress); - removeRoom(room); - } - } + /** + * Unregisters a user from a room and removes the room if its empty + * + * @param room the room name + * @param remoteAddress the address of the remote user + */ + public void unRegisterUser(String room, SocketAddress remoteAddress){ + if(rooms.containsKey(room)){ + logger.fine("Remove Chat User: "+remoteAddress); + rooms.get(room).remove(remoteAddress); + removeRoom(room); + } + } - /** - * Adds a room into the list - * - * @param room The name of the room - */ - private void addRoom(String room){ - if(!rooms.containsKey(room)){ - logger.fine("New Chat Room: "+room); - rooms.put(room, new LinkedList()); - } - } - - /** - * Removes the given room if its empty - * - * @param room The room - */ - private void removeRoom(String room){ - if(rooms.get(room).isEmpty()){ - logger.fine("Remove Chat Room: "+room); - rooms.remove(room); - } - } + /** + * Adds a room into the list + * + * @param room The name of the room + */ + private void addRoom(String room){ + if(!rooms.containsKey(room)){ + logger.fine("New Chat Room: "+room); + rooms.put(room, new LinkedList()); + } + } + + /** + * Removes the given room if its empty + * + * @param room The room + */ + private void removeRoom(String room){ + if(rooms.get(room).isEmpty()){ + logger.fine("Remove Chat Room: "+room); + rooms.remove(room); + } + } } diff --git a/src/zutil/net/nio/worker/grid/GridClient.java b/src/zutil/net/nio/worker/grid/GridClient.java index 2a47905..ebfbdbb 100755 --- a/src/zutil/net/nio/worker/grid/GridClient.java +++ b/src/zutil/net/nio/worker/grid/GridClient.java @@ -42,93 +42,93 @@ import java.util.Queue; */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class GridClient extends ThreadedEventWorker { - private static LinkedList jobQueue; - private static GridThread thread; - private static NioClient network; + private static LinkedList jobQueue; + private static GridThread thread; + private static NioClient network; - /** - * Creates a new GridClient object and registers itself at the server - * and sets itself as a worker in NioClient - * - * @param thread the Thread interface to run for the jobs - * @param network the NioClient to use to communicate to the server - */ - public GridClient(GridThread thread, NioClient network){ - jobQueue = new LinkedList(); - GridClient.thread = thread; - GridClient.network = network; + /** + * Creates a new GridClient object and registers itself at the server + * and sets itself as a worker in NioClient + * + * @param thread the Thread interface to run for the jobs + * @param network the NioClient to use to communicate to the server + */ + public GridClient(GridThread thread, NioClient network){ + jobQueue = new LinkedList(); + GridClient.thread = thread; + GridClient.network = network; - } + } - /** - * Starts up the client and a couple of GridThreads. - * And registers itself as a worker in NioClient - */ - public void initiate() throws IOException{ - network.setDefaultWorker(this); - network.send(new GridMessage(GridMessage.REGISTER)); + /** + * Starts up the client and a couple of GridThreads. + * And registers itself as a worker in NioClient + */ + public void initiate() throws IOException{ + network.setDefaultWorker(this); + network.send(new GridMessage(GridMessage.REGISTER)); - for(int i=0; i { - /** - * @return static and final values that do not change for every job - */ - Object initValues(); - /** - * @return a new generated job - */ - T generateJob(); + /** + * @return static and final values that do not change for every job + */ + Object initValues(); + /** + * @return a new generated job + */ + T generateJob(); } diff --git a/src/zutil/net/nio/worker/grid/GridMessage.java b/src/zutil/net/nio/worker/grid/GridMessage.java index 7a0f9bb..345e113 100755 --- a/src/zutil/net/nio/worker/grid/GridMessage.java +++ b/src/zutil/net/nio/worker/grid/GridMessage.java @@ -27,83 +27,83 @@ package zutil.net.nio.worker.grid; import zutil.net.nio.message.Message; public class GridMessage implements Message { - private static final long serialVersionUID = 1L; - - // Client type messages - /** Computation job return right answer **/ - public static final int COMP_SUCCESSFUL = 1; // - /** Initial static data **/ - public static final int COMP_INCORRECT = 2; // - /** Computation job return wrong answer **/ - public static final int COMP_ERROR = 3; // - /** There was an error computing **/ - public static final int REGISTER = 4; // - /** Register at the server **/ - public static final int UNREGISTER = 5; // - /** Request new computation data **/ - public static final int NEW_DATA = 6; // - - // Server type messages - /** Sending initial static data **/ - public static final int INIT_DATA = 100; - /** Sending new dynamic data **/ - public static final int COMP_DATA = 101; + private static final long serialVersionUID = 1L; - - private int type; - private int jobId; - private T data; + // Client type messages + /** Computation job return right answer **/ + public static final int COMP_SUCCESSFUL = 1; // + /** Initial static data **/ + public static final int COMP_INCORRECT = 2; // + /** Computation job return wrong answer **/ + public static final int COMP_ERROR = 3; // + /** There was an error computing **/ + public static final int REGISTER = 4; // + /** Register at the server **/ + public static final int UNREGISTER = 5; // + /** Request new computation data **/ + public static final int NEW_DATA = 6; // - /** - * Creates a new GridMessage - * - * @param type is the type of message - */ - public GridMessage(int type){ - this(type, 0, null); - } - - /** - * Creates a new GridMessage - * - * @param type is the type of message - * @param jobId is the id of the job - */ - public GridMessage(int type, int jobId){ - this(type, jobId, null); - } - - /** - * Creates a new GridMessage - * - * @param type is the type of message - * @param jobId is the id of the job - * @param data is the data to send with this message - */ - public GridMessage(int type, int jobId, T data){ - this.type = type; - this.jobId = jobId; - this.data = data; - } - - /** - * @return the type of message - */ - public int messageType(){ - return type; - } - - /** - * @return the job id for this message - */ - public int getJobQueueID(){ - return jobId; - } - - /** - * @return the data in this message, may not always carry any data. - */ - public T getData(){ - return data; - } + // Server type messages + /** Sending initial static data **/ + public static final int INIT_DATA = 100; + /** Sending new dynamic data **/ + public static final int COMP_DATA = 101; + + + private int type; + private int jobId; + private T data; + + /** + * Creates a new GridMessage + * + * @param type is the type of message + */ + public GridMessage(int type){ + this(type, 0, null); + } + + /** + * Creates a new GridMessage + * + * @param type is the type of message + * @param jobId is the id of the job + */ + public GridMessage(int type, int jobId){ + this(type, jobId, null); + } + + /** + * Creates a new GridMessage + * + * @param type is the type of message + * @param jobId is the id of the job + * @param data is the data to send with this message + */ + public GridMessage(int type, int jobId, T data){ + this.type = type; + this.jobId = jobId; + this.data = data; + } + + /** + * @return the type of message + */ + public int messageType(){ + return type; + } + + /** + * @return the job id for this message + */ + public int getJobQueueID(){ + return jobId; + } + + /** + * @return the data in this message, may not always carry any data. + */ + public T getData(){ + return data; + } } diff --git a/src/zutil/net/nio/worker/grid/GridResultHandler.java b/src/zutil/net/nio/worker/grid/GridResultHandler.java index d83cd78..63b760f 100755 --- a/src/zutil/net/nio/worker/grid/GridResultHandler.java +++ b/src/zutil/net/nio/worker/grid/GridResultHandler.java @@ -30,6 +30,6 @@ package zutil.net.nio.worker.grid; * @author Ziver */ public interface GridResultHandler { - - void resultEvent(int jobID, boolean correct, T result); + + void resultEvent(int jobID, boolean correct, T result); } diff --git a/src/zutil/net/nio/worker/grid/GridServerWorker.java b/src/zutil/net/nio/worker/grid/GridServerWorker.java index a6d4ece..41096a9 100755 --- a/src/zutil/net/nio/worker/grid/GridServerWorker.java +++ b/src/zutil/net/nio/worker/grid/GridServerWorker.java @@ -39,98 +39,98 @@ import java.util.Queue; */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class GridServerWorker extends ThreadedEventWorker{ - // Job timeout after 30 min - public int jobTimeout = 1000*60*30; - private HashMap jobs; // contains all the ongoing jobs - private Queue resendJobQueue; // Contains all the jobs that will be recalculated - private GridJobGenerator jobGenerator; // The job generator - private GridResultHandler resHandler; - private int nextJobID; + // Job timeout after 30 min + public int jobTimeout = 1000*60*30; + private HashMap jobs; // contains all the ongoing jobs + private Queue resendJobQueue; // Contains all the jobs that will be recalculated + private GridJobGenerator jobGenerator; // The job generator + private GridResultHandler resHandler; + private int nextJobID; - public GridServerWorker(GridResultHandler resHandler, GridJobGenerator jobGenerator){ - this.resHandler = resHandler; - this.jobGenerator = jobGenerator; - nextJobID = 0; + public GridServerWorker(GridResultHandler resHandler, GridJobGenerator jobGenerator){ + this.resHandler = resHandler; + this.jobGenerator = jobGenerator; + nextJobID = 0; - jobs = new HashMap<>(); - resendJobQueue = new LinkedList<>(); - GridMaintainer maintainer = new GridMaintainer(); - maintainer.start(); - } + jobs = new HashMap<>(); + resendJobQueue = new LinkedList<>(); + GridMaintainer maintainer = new GridMaintainer(); + maintainer.start(); + } - @Override - public void messageEvent(WorkerEventData e) { - try { - // ignores other messages than GridMessage - if(e.data instanceof GridMessage){ - GridMessage msg = (GridMessage)e.data; - GridJob job; + @Override + public void messageEvent(WorkerEventData e) { + try { + // ignores other messages than GridMessage + if(e.data instanceof GridMessage){ + GridMessage msg = (GridMessage)e.data; + GridJob job; - switch(msg.messageType()){ - case GridMessage.REGISTER: - e.network.send(e.remoteAddress, new GridMessage(GridMessage.INIT_DATA, 0, jobGenerator.initValues())); - break; - // Sending new data to compute to the client - case GridMessage.NEW_DATA: - if(!resendJobQueue.isEmpty()){ // checks first if there is a job for recalculation - job = resendJobQueue.poll(); - job.renewTimeStamp(); - } - else{ // generates new job - job = new GridJob(nextJobID, - jobGenerator.generateJob()); - jobs.put(job.jobID, job); - nextJobID++; - } - GridMessage newMsg = new GridMessage(GridMessage.COMP_DATA, job.jobID, job.job); - e.network.send(e.remoteAddress, newMsg); - break; + switch(msg.messageType()){ + case GridMessage.REGISTER: + e.network.send(e.remoteAddress, new GridMessage(GridMessage.INIT_DATA, 0, jobGenerator.initValues())); + break; + // Sending new data to compute to the client + case GridMessage.NEW_DATA: + if(!resendJobQueue.isEmpty()){ // checks first if there is a job for recalculation + job = resendJobQueue.poll(); + job.renewTimeStamp(); + } + else{ // generates new job + job = new GridJob(nextJobID, + jobGenerator.generateJob()); + jobs.put(job.jobID, job); + nextJobID++; + } + GridMessage newMsg = new GridMessage(GridMessage.COMP_DATA, job.jobID, job.job); + e.network.send(e.remoteAddress, newMsg); + break; - // Received computation results - case GridMessage.COMP_SUCCESSFUL: - resHandler.resultEvent(msg.getJobQueueID(), true, msg.getData()); - break; - case GridMessage.COMP_INCORRECT: - resHandler.resultEvent(msg.getJobQueueID(), false, msg.getData()); - break; - case GridMessage.COMP_ERROR: // marks the job for recalculation - job = jobs.get(msg.getJobQueueID()); - resendJobQueue.add(job); - break; - } - } - } catch (IOException e1) { - e1.printStackTrace(); - } - } + // Received computation results + case GridMessage.COMP_SUCCESSFUL: + resHandler.resultEvent(msg.getJobQueueID(), true, msg.getData()); + break; + case GridMessage.COMP_INCORRECT: + resHandler.resultEvent(msg.getJobQueueID(), false, msg.getData()); + break; + case GridMessage.COMP_ERROR: // marks the job for recalculation + job = jobs.get(msg.getJobQueueID()); + resendJobQueue.add(job); + break; + } + } + } catch (IOException e1) { + e1.printStackTrace(); + } + } - /** - * Changes the job timeout value - * - * @param timeout is the timeout in minutes - */ - public void setJobTimeout(int timeout){ - jobTimeout = 1000*60*timeout; - } + /** + * Changes the job timeout value + * + * @param timeout is the timeout in minutes + */ + public void setJobTimeout(int timeout){ + jobTimeout = 1000*60*timeout; + } - class GridMaintainer extends Thread{ - /** - * Runs some behind the scenes stuff - * like job garbage collection. - */ - public void run(){ - while(true){ - long time = System.currentTimeMillis(); - for(int jobID : jobs.keySet()){ - if(time-jobs.get(jobID).timestamp > jobTimeout){ - resendJobQueue.add(jobs.get(jobID)); - } - } - try{Thread.sleep(1000*60*1);}catch(Exception e){}; - } - } - } + class GridMaintainer extends Thread{ + /** + * Runs some behind the scenes stuff + * like job garbage collection. + */ + public void run(){ + while(true){ + long time = System.currentTimeMillis(); + for(int jobID : jobs.keySet()){ + if(time-jobs.get(jobID).timestamp > jobTimeout){ + resendJobQueue.add(jobs.get(jobID)); + } + } + try{Thread.sleep(1000*60*1);}catch(Exception e){}; + } + } + } } diff --git a/src/zutil/net/nio/worker/grid/GridThread.java b/src/zutil/net/nio/worker/grid/GridThread.java index 28d6103..1123e55 100755 --- a/src/zutil/net/nio/worker/grid/GridThread.java +++ b/src/zutil/net/nio/worker/grid/GridThread.java @@ -31,30 +31,30 @@ package zutil.net.nio.worker.grid; * @author Ziver */ public abstract class GridThread implements Runnable{ - /** - * The initial static and final data will be sent to this method. - * - * @param data is the static and or final data - */ - public abstract void setInitData(Object data); - - public void run(){ - while(true){ - GridJob tmp = null; - try { - tmp = GridClient.getNextJob(); - compute(tmp); - } catch (Exception e) { - e.printStackTrace(); - if(tmp != null){ - GridClient.jobError(tmp.jobID); - } - } - } - } - - /** - * Compute the given data and return - */ - public abstract void compute(GridJob data) throws Exception; + /** + * The initial static and final data will be sent to this method. + * + * @param data is the static and or final data + */ + public abstract void setInitData(Object data); + + public void run(){ + while(true){ + GridJob tmp = null; + try { + tmp = GridClient.getNextJob(); + compute(tmp); + } catch (Exception e) { + e.printStackTrace(); + if(tmp != null){ + GridClient.jobError(tmp.jobID); + } + } + } + } + + /** + * Compute the given data and return + */ + public abstract void compute(GridJob data) throws Exception; } diff --git a/src/zutil/net/nio/worker/sync/GraphicsSyncMessage.java b/src/zutil/net/nio/worker/sync/GraphicsSyncMessage.java index c46bfa8..31f6a6e 100755 --- a/src/zutil/net/nio/worker/sync/GraphicsSyncMessage.java +++ b/src/zutil/net/nio/worker/sync/GraphicsSyncMessage.java @@ -26,30 +26,30 @@ package zutil.net.nio.worker.sync; public class GraphicsSyncMessage extends SyncMessage{ - private static final long serialVersionUID = 1L; - - public float locX; - public float locY; - public float locZ; - - public float rotX; - public float rotY; - public float rotZ; - public float rotW; - - public GraphicsSyncMessage(String id){ - this.type = MessageType.SYNC; - this.id = id; - } - - public boolean equals(Object obj){ - if(obj instanceof GraphicsSyncMessage){ - GraphicsSyncMessage tmp = (GraphicsSyncMessage)obj; - return (tmp.locX == locX && tmp.locY == locY && - tmp.locZ == locZ && tmp.rotX == rotX && - tmp.rotY == rotY && tmp.rotZ == rotZ && - tmp.rotW == rotW); - } - return false; - } + private static final long serialVersionUID = 1L; + + public float locX; + public float locY; + public float locZ; + + public float rotX; + public float rotY; + public float rotZ; + public float rotW; + + public GraphicsSyncMessage(String id){ + this.type = MessageType.SYNC; + this.id = id; + } + + public boolean equals(Object obj){ + if(obj instanceof GraphicsSyncMessage){ + GraphicsSyncMessage tmp = (GraphicsSyncMessage)obj; + return (tmp.locX == locX && tmp.locY == locY && + tmp.locZ == locZ && tmp.rotX == rotX && + tmp.rotY == rotY && tmp.rotZ == rotZ && + tmp.rotW == rotW); + } + return false; + } } diff --git a/src/zutil/net/nio/worker/sync/ObjectSync.java b/src/zutil/net/nio/worker/sync/ObjectSync.java index c7d9001..68479d9 100755 --- a/src/zutil/net/nio/worker/sync/ObjectSync.java +++ b/src/zutil/net/nio/worker/sync/ObjectSync.java @@ -25,25 +25,25 @@ package zutil.net.nio.worker.sync; public abstract class ObjectSync { - public String id; + public String id; - public ObjectSync(String id){ - this.id = id; - } - - /** - * Sends sync message if the object has bean changed - */ - public abstract void sendSync(); - - /** - * Applies the SyncMessage to the object - * @param message - */ - public abstract void syncObject(SyncMessage message); - - /** - * Called when the object is removed from the sync list - */ - public abstract void remove(); + public ObjectSync(String id){ + this.id = id; + } + + /** + * Sends sync message if the object has bean changed + */ + public abstract void sendSync(); + + /** + * Applies the SyncMessage to the object + * @param message + */ + public abstract void syncObject(SyncMessage message); + + /** + * Called when the object is removed from the sync list + */ + public abstract void remove(); } diff --git a/src/zutil/net/nio/worker/sync/SyncMessage.java b/src/zutil/net/nio/worker/sync/SyncMessage.java index e699a33..2aa04a5 100755 --- a/src/zutil/net/nio/worker/sync/SyncMessage.java +++ b/src/zutil/net/nio/worker/sync/SyncMessage.java @@ -27,16 +27,16 @@ package zutil.net.nio.worker.sync; import zutil.net.nio.message.Message; public class SyncMessage implements Message { - private static final long serialVersionUID = 1L; - public enum MessageType { - REQUEST_ID, - NEW, - REMOVE, - SYNC - } - - // type of message - public MessageType type; - // id of the Object - public String id; + private static final long serialVersionUID = 1L; + public enum MessageType { + REQUEST_ID, + NEW, + REMOVE, + SYNC + } + + // type of message + public MessageType type; + // id of the Object + public String id; } diff --git a/src/zutil/net/nio/worker/sync/SyncService.java b/src/zutil/net/nio/worker/sync/SyncService.java index f67dc05..6fcad5e 100755 --- a/src/zutil/net/nio/worker/sync/SyncService.java +++ b/src/zutil/net/nio/worker/sync/SyncService.java @@ -32,44 +32,44 @@ import java.util.HashMap; import java.util.logging.Logger; public class SyncService extends ThreadedEventWorker{ - private static Logger logger = LogUtil.getLogger(); + private static Logger logger = LogUtil.getLogger(); - // list of objects to sync - private HashMap sync = new HashMap<>(); + // list of objects to sync + private HashMap sync = new HashMap<>(); - /** - * Adds a object to be synced - */ - public void addSyncObject(ObjectSync os){ - sync.put(os.id, os); - logger.fine("New Sync object: "+os); - } + /** + * Adds a object to be synced + */ + public void addSyncObject(ObjectSync os){ + sync.put(os.id, os); + logger.fine("New Sync object: "+os); + } - @Override - public void messageEvent(WorkerEventData event){ - if(event.data instanceof SyncMessage){ - SyncMessage syncMessage = (SyncMessage)event.data; - if(syncMessage.type == SyncMessage.MessageType.SYNC){ - ObjectSync obj = sync.get(syncMessage.id); - if(obj != null){ - logger.finer("Syncing Message..."); - obj.syncObject(syncMessage); - } - } - else if(syncMessage.type == SyncMessage.MessageType.REMOVE){ - sync.remove(syncMessage.id).remove(); - } - } - } + @Override + public void messageEvent(WorkerEventData event){ + if(event.data instanceof SyncMessage){ + SyncMessage syncMessage = (SyncMessage)event.data; + if(syncMessage.type == SyncMessage.MessageType.SYNC){ + ObjectSync obj = sync.get(syncMessage.id); + if(obj != null){ + logger.finer("Syncing Message..."); + obj.syncObject(syncMessage); + } + } + else if(syncMessage.type == SyncMessage.MessageType.REMOVE){ + sync.remove(syncMessage.id).remove(); + } + } + } - /** - * Syncs all the objects whit the server - */ - public void sync(){ - for(String id : sync.keySet()){ - sync.get(id).sendSync(); - } - } + /** + * Syncs all the objects whit the server + */ + public void sync(){ + for(String id : sync.keySet()){ + sync.get(id).sendSync(); + } + } } diff --git a/src/zutil/net/smtp/Email.java b/src/zutil/net/smtp/Email.java index 0038220..b2f036a 100755 --- a/src/zutil/net/smtp/Email.java +++ b/src/zutil/net/smtp/Email.java @@ -18,34 +18,34 @@ import static zutil.net.smtp.SmtpClient.NEWLINE; public class Email { public enum ContentType{ - PLAIN, HTML - } - private static final SimpleDateFormat dateFormatter = - new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH); + PLAIN, HTML + } + private static final SimpleDateFormat dateFormatter = + new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH); private static final Pattern PATTERN_NEWLINE = Pattern.compile("(\\r\\n|\\n)"); - private String fromAddress; - private String fromName = null; - private String toAddress; + private String fromAddress; + private String fromName = null; + private String toAddress; private String toName = null; - private String replyToAddress = null; - private Date date = null; - private ContentType type = ContentType.PLAIN; - private String subject; - private String message; + private String replyToAddress = null; + private Date date = null; + private ContentType type = ContentType.PLAIN; + private String subject; + private String message; - public Email(){ } - - - public void setFrom(String address){ - this.fromAddress = sanitizeParam(address); - } - public void setFrom(String address, String niceName){ - fromAddress = sanitizeParam(address); - fromName = sanitizeParam(niceName); - } + public Email(){ } + + + public void setFrom(String address){ + this.fromAddress = sanitizeParam(address); + } + public void setFrom(String address, String niceName){ + fromAddress = sanitizeParam(address); + fromName = sanitizeParam(niceName); + } public String getFromAddress(){ return fromAddress; } @@ -53,52 +53,52 @@ public class Email { return fromName; } - public void setReplyTo(String address){ - this.replyToAddress = sanitizeParam(address); - } + public void setReplyTo(String address){ + this.replyToAddress = sanitizeParam(address); + } public String getReplyToAddress() { return replyToAddress; } - public void setTo(String address){ - this.toAddress = sanitizeParam(address); - } - public void setTo(String address, String niceName){ - this.toAddress = sanitizeParam(address); - this.toName = sanitizeParam(niceName); - } - public String getToAddress(){ - return toAddress; - } + public void setTo(String address){ + this.toAddress = sanitizeParam(address); + } + public void setTo(String address, String niceName){ + this.toAddress = sanitizeParam(address); + this.toName = sanitizeParam(niceName); + } + public String getToAddress(){ + return toAddress; + } public String getToName() { return toName; } - public void setDate(Date date){ - this.date = date; - } - public void setContentType(ContentType t){ - type = t; - } + public void setDate(Date date){ + this.date = date; + } + public void setContentType(ContentType t){ + type = t; + } - public void setSubject(String subject){ - this.subject = sanitizeParam(subject); - } + public void setSubject(String subject){ + this.subject = sanitizeParam(subject); + } public String getSubject(){ return subject; } - public void setMessage(String msg){ - message = msg.replaceAll("(\\r\\n|\\n)", NEWLINE); - message = message.replaceAll(NEWLINE+"\\.", NEWLINE +".."); - } + public void setMessage(String msg){ + message = msg.replaceAll("(\\r\\n|\\n)", NEWLINE); + message = message.replaceAll(NEWLINE+"\\.", NEWLINE +".."); + } public String getMessage(){ return message; } - private String sanitizeParam(String param){ - return PATTERN_NEWLINE.matcher(param).replaceAll(""); + private String sanitizeParam(String param){ + return PATTERN_NEWLINE.matcher(param).replaceAll(""); } @@ -107,48 +107,48 @@ public class Email { * * @throws IllegalArgumentException if from address and to address has not been set */ - public void write(Writer out) throws IOException{ + public void write(Writer out) throws IOException{ if(fromAddress == null) throw new IllegalArgumentException("From value cannot be null!"); if(toAddress == null) throw new IllegalArgumentException("To value cannot be null!"); - //************ Headers + //************ Headers // From - if (fromName !=null) - out.write("From: "+ fromName +" <"+ fromAddress +">"+ NEWLINE); - else - out.write("From: "+ fromAddress + NEWLINE); + if (fromName !=null) + out.write("From: "+ fromName +" <"+ fromAddress +">"+ NEWLINE); + else + out.write("From: "+ fromAddress + NEWLINE); - // Reply-To - if ( replyToAddress != null ) - out.write("Reply-To: <"+ replyToAddress +">"+ NEWLINE); + // Reply-To + if ( replyToAddress != null ) + out.write("Reply-To: <"+ replyToAddress +">"+ NEWLINE); - // To + // To if (toName !=null) out.write("To: "+ toName +" <"+ toAddress +">"+ NEWLINE); else out.write("To: "+ toAddress + NEWLINE); - // Date + // Date if (date != null) out.write("Date: "+dateFormatter.format(date) + NEWLINE); else - out.write("Date: "+dateFormatter.format(new Date(System.currentTimeMillis())) + NEWLINE); + out.write("Date: "+dateFormatter.format(new Date(System.currentTimeMillis())) + NEWLINE); - // Content type - switch( type ){ - case HTML: - out.write("Content-Type: text/html;"+ NEWLINE); break; - default: - out.write("Content-Type: text/plain;"+ NEWLINE); break; - } + // Content type + switch( type ){ + case HTML: + out.write("Content-Type: text/html;"+ NEWLINE); break; + default: + out.write("Content-Type: text/plain;"+ NEWLINE); break; + } - // Subject - out.write("Subject: "+(subject!=null ? subject : "") + NEWLINE); + // Subject + out.write("Subject: "+(subject!=null ? subject : "") + NEWLINE); - out.write(NEWLINE); - //*********** Mesasge - out.write( message ); - } + out.write(NEWLINE); + //*********** Mesasge + out.write( message ); + } } \ No newline at end of file diff --git a/src/zutil/net/smtp/SmtpClient.java b/src/zutil/net/smtp/SmtpClient.java index 9c0f636..fa31c20 100755 --- a/src/zutil/net/smtp/SmtpClient.java +++ b/src/zutil/net/smtp/SmtpClient.java @@ -41,22 +41,22 @@ import java.util.logging.Logger; * */ public class SmtpClient { - private static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); - protected static final String NEWLINE = "\r\n"; - private static final String CMD_HELO = "HELO"; - private static final String CMD_FROM = "MAIL FROM"; - private static final String CMD_TO = "RCPT TO"; - private static final String CMD_DATA = "DATA"; - private static final String CMD_DATA_END = "."; - private static final String CMD_RESET = "RSET"; - private static final String CMD_NOOP = "NOOP"; - private static final String CMD_QUIT = "QUIT"; + protected static final String NEWLINE = "\r\n"; + private static final String CMD_HELO = "HELO"; + private static final String CMD_FROM = "MAIL FROM"; + private static final String CMD_TO = "RCPT TO"; + private static final String CMD_DATA = "DATA"; + private static final String CMD_DATA_END = "."; + private static final String CMD_RESET = "RSET"; + private static final String CMD_NOOP = "NOOP"; + private static final String CMD_QUIT = "QUIT"; private Socket socket; - private BufferedReader in; - private Writer out; + private BufferedReader in; + private Writer out; /** @@ -68,36 +68,36 @@ public class SmtpClient { /** * Will look for a SMTP server on specified host on port 25 */ - public SmtpClient(String host) throws IOException { - this(host, 25); - } - public SmtpClient(String host, int port) throws IOException { + public SmtpClient(String host) throws IOException { + this(host, 25); + } + public SmtpClient(String host, int port) throws IOException { socket = new Socket(host, port); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new OutputStreamWriter(socket.getOutputStream()); readCommand(); sendCommand(CMD_HELO + " " + InetAddress.getLocalHost().getHostName()); - } + } - /** - * Sends a basic email to the smtp server - * - * @param from the senders email address - * @param to the recipients email address - * @param subj the email subject line - * @param msg the email body message - */ - public synchronized void send(String from, String to, String subj, String msg) throws IOException{ + /** + * Sends a basic email to the smtp server + * + * @param from the senders email address + * @param to the recipients email address + * @param subj the email subject line + * @param msg the email body message + */ + public synchronized void send(String from, String to, String subj, String msg) throws IOException{ Email email = new Email(); email.setFrom(from); email.setTo(to); email.setSubject(subj); email.setMessage(msg); send(email); - } + } /** * Sends a email to the connected SMTP server @@ -126,33 +126,33 @@ public class SmtpClient { - /** - * Sends the given line to the server and return the last line of the response - * - * @param cmd a String command that will be sent to the server - * @return the server response code - */ - public synchronized int sendCommand(String cmd) throws IOException{ - logger.finest(">> "+cmd); - out.write(cmd + NEWLINE); - out.flush(); - String reply = readCommand(); - return parseReturnCode(reply); - } - - /** - * Reads on line from the command channel + /** + * Sends the given line to the server and return the last line of the response * - * @throws IOException if the server returns a error code - */ - public synchronized String readCommand() throws IOException{ - String tmp = in.readLine(); - logger.finest(">> "+tmp); - if(parseReturnCode(tmp) >= 400 ) - throw new IOException(tmp); + * @param cmd a String command that will be sent to the server + * @return the server response code + */ + public synchronized int sendCommand(String cmd) throws IOException{ + logger.finest(">> "+cmd); + out.write(cmd + NEWLINE); + out.flush(); + String reply = readCommand(); + return parseReturnCode(reply); + } - return tmp; - } + /** + * Reads on line from the command channel + * + * @throws IOException if the server returns a error code + */ + public synchronized String readCommand() throws IOException{ + String tmp = in.readLine(); + logger.finest(">> "+tmp); + if(parseReturnCode(tmp) >= 400 ) + throw new IOException(tmp); + + return tmp; + } private static int parseReturnCode(String msg){ return Integer.parseInt(msg.substring(0, 3)); @@ -166,7 +166,7 @@ public class SmtpClient { sendCommand(CMD_RESET); } - public synchronized void close() throws IOException{ + public synchronized void close() throws IOException{ if (in != null) { sendCommand(CMD_QUIT); socket.close(); @@ -174,5 +174,5 @@ public class SmtpClient { in = null; out = null; } - } + } } diff --git a/src/zutil/net/ssdp/SSDPClient.java b/src/zutil/net/ssdp/SSDPClient.java index b4c410f..d0a82a2 100755 --- a/src/zutil/net/ssdp/SSDPClient.java +++ b/src/zutil/net/ssdp/SSDPClient.java @@ -50,152 +50,152 @@ import static zutil.net.ssdp.SSDPServer.SSDP_PORT; * @author Ziver */ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetworkThread{ - private static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); public static final String USER_AGENT = "Zutil SSDP Client"; - /** Mapping of search targets and list of associated services **/ - private HashMap> services_st; + /** Mapping of search targets and list of associated services **/ + private HashMap> services_st; /** Map of all unique services received **/ - private HashMap services_usn; + private HashMap services_usn; - private SSDPServiceListener listener; + private SSDPServiceListener listener; - - /** - * Creates new instance of this class. An UDP - * listening socket at the SSDP port. - * - * @throws IOException - */ - public SSDPClient() throws IOException{ + + /** + * 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 ); - super.setThread(this); - - services_st = new HashMap<>(); - services_usn = new HashMap<>(); - } + super.setThread(this); - /** - * Sends an request for an service - * - * @param searchTarget is the SearchTarget of the service - * - * ***** REQUEST: - * M-SEARCH * HTTP/1.1 - * Host: 239.255.255.250:reservedSSDPport - * Man: "ssdp:discover" - * ST: ge:fridge - * MX: 3 - * - */ - public void requestService(String searchTarget){ - requestService(searchTarget, null); - } - public void requestService(String searchTarget, HashMap headers){ - try { - // Generate an SSDP discover message - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - HttpPrintStream http = new HttpPrintStream( buffer, HttpPrintStream.HttpMessageType.REQUEST ); - http.setRequestType("M-SEARCH"); - http.setRequestURL("*"); - http.setHeader("Host", SSDP_MULTICAST_ADDR +":"+ SSDP_PORT ); - http.setHeader("ST", searchTarget ); - http.setHeader("Man", "\"ssdp:discover\"" ); - http.setHeader("MX", "3" ); - http.setHeader("USER-AGENT", USER_AGENT ); - if(headers != null) { - for (String key : headers.keySet()) { - http.setHeader(key, headers.get(key)); - } - } - logger.log(Level.FINEST, "Sending Multicast: "+ http); - http.flush(); + services_st = new HashMap<>(); + services_usn = new HashMap<>(); + } - byte[] data = buffer.toByteArray(); + /** + * Sends an request for an service + * + * @param searchTarget is the SearchTarget of the service + * + * ***** REQUEST: + * M-SEARCH * HTTP/1.1 + * Host: 239.255.255.250:reservedSSDPport + * Man: "ssdp:discover" + * ST: ge:fridge + * MX: 3 + * + */ + public void requestService(String searchTarget){ + requestService(searchTarget, null); + } + public void requestService(String searchTarget, HashMap headers){ + try { + // Generate an SSDP discover message + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + HttpPrintStream http = new HttpPrintStream( buffer, HttpPrintStream.HttpMessageType.REQUEST ); + http.setRequestType("M-SEARCH"); + http.setRequestURL("*"); + http.setHeader("Host", SSDP_MULTICAST_ADDR +":"+ SSDP_PORT ); + http.setHeader("ST", searchTarget ); + http.setHeader("Man", "\"ssdp:discover\"" ); + http.setHeader("MX", "3" ); + http.setHeader("USER-AGENT", USER_AGENT ); + if(headers != null) { + for (String key : headers.keySet()) { + http.setHeader(key, headers.get(key)); + } + } + logger.log(Level.FINEST, "Sending Multicast: "+ http); + http.flush(); + + byte[] data = buffer.toByteArray(); //System.out.println(new String(data)+"****************"); - DatagramPacket packet = new DatagramPacket( - data, data.length, - InetAddress.getByName( SSDP_MULTICAST_ADDR ), - SSDP_PORT ); - super.send( packet ); - http.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } + DatagramPacket packet = new DatagramPacket( + data, data.length, + InetAddress.getByName( SSDP_MULTICAST_ADDR ), + SSDP_PORT ); + super.send( packet ); + http.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } - /** - * Set a listener that will be notified when new services are detected - */ - public void setListener(SSDPServiceListener listener){ - this.listener = listener; - } + /** + * Set a listener that will be notified when new services are detected + */ + public void setListener(SSDPServiceListener listener){ + this.listener = listener; + } - /** - * Returns a list of received services by - * the given search target. - * - * @param searchTarget is the search target - * @return a list of received services - */ - public LinkedList getServices(String searchTarget){ + /** + * Returns a list of received services by + * the given search target. + * + * @param searchTarget is the search target + * @return a list of received services + */ + public LinkedList getServices(String searchTarget){ if(services_st.get(searchTarget) == null) return new LinkedList<>(); - return services_st.get(searchTarget); - } - - /** - * Returns the amount of services in the search target - * - * @param searchTarget is the search target - * @return the amount of services cached - */ - public int getServicesCount(String searchTarget){ - if(services_st.containsKey(searchTarget)){ - return services_st.get(searchTarget).size(); - } - return 0; - } - - /** - * Returns a service with the given USN. - * - * @param usn is the unique identifier for a service - * @return an service, null if there is no such service - */ - public StandardSSDPInfo getService(String usn){ - return services_usn.get( usn ); - } - - /** - * Clears all the received information of the services - */ - public void clearServices(){ - services_usn.clear(); - services_st.clear(); - } - /** - * Clears all services matching the search target - */ - public void clearServices(String st){ + return services_st.get(searchTarget); + } + + /** + * Returns the amount of services in the search target + * + * @param searchTarget is the search target + * @return the amount of services cached + */ + public int getServicesCount(String searchTarget){ + if(services_st.containsKey(searchTarget)){ + return services_st.get(searchTarget).size(); + } + return 0; + } + + /** + * Returns a service with the given USN. + * + * @param usn is the unique identifier for a service + * @return an service, null if there is no such service + */ + public StandardSSDPInfo getService(String usn){ + return services_usn.get( usn ); + } + + /** + * Clears all the received information of the services + */ + public void clearServices(){ + services_usn.clear(); + services_st.clear(); + } + /** + * Clears all services matching the search target + */ + public void clearServices(String st){ if(services_st.get(st) != null) { for (StandardSSDPInfo service : services_st.get(st)) { services_usn.remove(service.getUSN()); } } - } - - /** - * Waits for responses - * - * ***** RESPONSE; - * HTTP/1.1 200 OK - * Ext: - * Cache-Control: no-cache="Ext", max-age = 5000 - * ST: ge:fridge - * USN: uuid:abcdefgh-7dec-11d0-a765-00a0c91e6bf6 - * Location: http://localhost:80 - */ - public void receivedPacket(DatagramPacket packet, ThreadedUDPNetwork network) { + } + + /** + * Waits for responses + * + * ***** RESPONSE; + * HTTP/1.1 200 OK + * Ext: + * Cache-Control: no-cache="Ext", max-age = 5000 + * ST: ge:fridge + * USN: uuid:abcdefgh-7dec-11d0-a765-00a0c91e6bf6 + * Location: http://localhost:80 + */ + public void receivedPacket(DatagramPacket packet, ThreadedUDPNetwork network) { try { String msg = new String(packet.getData(), packet.getOffset(), packet.getLength()); HttpHeaderParser headerParser = new HttpHeaderParser(msg); @@ -221,7 +221,7 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork } } // Existing or new service update - else if (header.isResponse() || "NOTIFY".equals(header.getRequestType())) { + else if (header.isResponse() || "NOTIFY".equals(header.getRequestType())) { logger.log(Level.FINER, "Received service update (from: " + packet.getAddress() + "): " + header); boolean newService = false; @@ -254,22 +254,22 @@ public class SSDPClient extends ThreadedUDPNetwork implements ThreadedUDPNetwork } catch (IOException e){ logger.log(Level.SEVERE, null, e); } - } - - private long getCacheTime(String cache_control){ - long ret = 0; - HashMap tmpMap = new HashMap<>(); - HttpHeaderParser.parseHeaderValues(tmpMap, cache_control, ","); + } + + private long getCacheTime(String cache_control){ + long ret = 0; + HashMap tmpMap = new HashMap<>(); + HttpHeaderParser.parseHeaderValues(tmpMap, cache_control, ","); if(tmpMap.containsKey("max-age")) ret = Long.parseLong( tmpMap.get("max-age") ); - return ret; - } + return ret; + } - public interface SSDPServiceListener{ + public interface SSDPServiceListener{ /** * Is called when a new service is discovered. Will only be called once per service. */ - void serviceDiscovered(StandardSSDPInfo service); + void serviceDiscovered(StandardSSDPInfo service); /** * Is called when a service goes down and is not available anymore. diff --git a/src/zutil/net/ssdp/SSDPServer.java b/src/zutil/net/ssdp/SSDPServer.java index baece43..9cb0a26 100755 --- a/src/zutil/net/ssdp/SSDPServer.java +++ b/src/zutil/net/ssdp/SSDPServer.java @@ -67,268 +67,268 @@ import java.util.logging.Logger; * NTS: same as Man but for Notify messages */ public class SSDPServer extends ThreadedUDPNetwork implements ThreadedUDPNetworkThread{ - private static final Logger logger = LogUtil.getLogger(); - public static final String SERVER_INFO = "Zutil SSDP Server"; - public static final int DEFAULT_CACHE_TIME = 60*30; // 30 min - public static final String SSDP_MULTICAST_ADDR = "239.255.255.250"; - public static final int SSDP_PORT = 1900; + private static final Logger logger = LogUtil.getLogger(); + public static final String SERVER_INFO = "Zutil SSDP Server"; + public static final int DEFAULT_CACHE_TIME = 60*30; // 30 min + public static final String SSDP_MULTICAST_ADDR = "239.255.255.250"; + public static final int SSDP_PORT = 1900; - // instance specific values - private int cache_time; - private NotifyTimer notifyTimer = null; - /** HashMap that contains services as < SearchTargetName, SSDPServiceInfo > */ - private HashMap services; + // instance specific values + private int cache_time; + private NotifyTimer notifyTimer = null; + /** HashMap that contains services as < SearchTargetName, SSDPServiceInfo > */ + private HashMap services; - public SSDPServer() throws IOException{ - super( SSDP_MULTICAST_ADDR, SSDP_PORT ); - super.setThread( this ); + public SSDPServer() throws IOException{ + super( SSDP_MULTICAST_ADDR, SSDP_PORT ); + super.setThread( this ); - services = new HashMap(); + services = new HashMap(); - setCacheTime( DEFAULT_CACHE_TIME ); - enableNotify( true ); - } + setCacheTime( DEFAULT_CACHE_TIME ); + enableNotify( true ); + } - /** - * Adds an service that will be announced. - * - * @param service add a new service to be announced - */ - public void addService(SSDPServiceInfo service){ - services.put( service.getSearchTarget(), service ); - } - /** - * Remove a service from being announced. This function will - * send out an byebye message to the clients that the service is down. - * - * @param searchTarget is the ST value in SSDP - */ - public void removeService(String searchTarget){ - sendByeBye( searchTarget ); - services.remove( searchTarget ); - } + /** + * Adds an service that will be announced. + * + * @param service add a new service to be announced + */ + public void addService(SSDPServiceInfo service){ + services.put( service.getSearchTarget(), service ); + } + /** + * Remove a service from being announced. This function will + * send out an byebye message to the clients that the service is down. + * + * @param searchTarget is the ST value in SSDP + */ + public void removeService(String searchTarget){ + sendByeBye( searchTarget ); + services.remove( searchTarget ); + } - /** - * Sets the cache time that will be sent to - * the clients. If notification is enabled then an - * notification message will be sent every cache_time/2 seconds - * - * @param time is the time in seconds - */ - public void setCacheTime(int time){ - cache_time = time; - if( isNotifyEnabled() ){ - enableNotify(false); - enableNotify(true); - } - } + /** + * Sets the cache time that will be sent to + * the clients. If notification is enabled then an + * notification message will be sent every cache_time/2 seconds + * + * @param time is the time in seconds + */ + public void setCacheTime(int time){ + cache_time = time; + if( isNotifyEnabled() ){ + enableNotify(false); + enableNotify(true); + } + } - /** - * Enable or disable notification messages to clients - * every cache_time/2 seconds - */ - public void enableNotify(boolean enable){ - if( enable && notifyTimer==null ){ - notifyTimer = new NotifyTimer(); - Timer timer = new Timer(); - timer.schedule(new NotifyTimer(), 0, cache_time*1000/2); - }else if( !enable && notifyTimer!=null ){ - notifyTimer.cancel(); - notifyTimer = null; - } - } - /** - * @return if notification messages is enabled - */ - public boolean isNotifyEnabled(){ - return notifyTimer != null; - } + /** + * Enable or disable notification messages to clients + * every cache_time/2 seconds + */ + public void enableNotify(boolean enable){ + if( enable && notifyTimer==null ){ + notifyTimer = new NotifyTimer(); + Timer timer = new Timer(); + timer.schedule(new NotifyTimer(), 0, cache_time*1000/2); + }else if( !enable && notifyTimer!=null ){ + notifyTimer.cancel(); + notifyTimer = null; + } + } + /** + * @return if notification messages is enabled + */ + public boolean isNotifyEnabled(){ + return notifyTimer != null; + } - /** - * Handles the incoming packets like this: - * - * ***** REQUEST: - * M-SEARCH * HTTP/1.1 - * Host: 239.255.255.250:reservedSSDPport - * Man: "ssdp:discover" - * ST: ge:fridge - * MX: 3 - * - * ***** RESPONSE; - * HTTP/1.1 200 OK - * Ext: - * Cache-Control: no-cache="Ext", max-age = 5000 - * ST: ge:fridge - * USN: uuid:abcdefgh-7dec-11d0-a765-00a0c91e6bf6 - * Location: http://localhost:80 - * - */ - public void receivedPacket(DatagramPacket packet, ThreadedUDPNetwork network) { - try { - String msg = new String( packet.getData(), packet.getOffset(), packet.getLength() ); - HttpHeaderParser headerParser = new HttpHeaderParser( msg ); - HttpHeader header = headerParser.read(); + /** + * Handles the incoming packets like this: + * + * ***** REQUEST: + * M-SEARCH * HTTP/1.1 + * Host: 239.255.255.250:reservedSSDPport + * Man: "ssdp:discover" + * ST: ge:fridge + * MX: 3 + * + * ***** RESPONSE; + * HTTP/1.1 200 OK + * Ext: + * Cache-Control: no-cache="Ext", max-age = 5000 + * ST: ge:fridge + * USN: uuid:abcdefgh-7dec-11d0-a765-00a0c91e6bf6 + * Location: http://localhost:80 + * + */ + public void receivedPacket(DatagramPacket packet, ThreadedUDPNetwork network) { + try { + String msg = new String( packet.getData(), packet.getOffset(), packet.getLength() ); + HttpHeaderParser headerParser = new HttpHeaderParser( msg ); + HttpHeader header = headerParser.read(); - // ******* Respond - // Check that the message is an ssdp discovery message - if( header.getRequestType() != null && header.getRequestType().equalsIgnoreCase("M-SEARCH") ){ - String man = header.getHeader("Man"); - if(man != null) - man = StringUtil.trim(man, '\"'); - String st = header.getHeader("ST"); - // Check that its the correct URL and that its an ssdp:discover message - if( header.getRequestURL().equals("*") && "ssdp:discover".equalsIgnoreCase(man) ){ - // Check if the requested service exists - if( services.containsKey( st ) ){ - logger.log(Level.FINEST, "Received Multicast(from: "+packet.getAddress()+"): "+ header); + // ******* Respond + // Check that the message is an ssdp discovery message + if( header.getRequestType() != null && header.getRequestType().equalsIgnoreCase("M-SEARCH") ){ + String man = header.getHeader("Man"); + if(man != null) + man = StringUtil.trim(man, '\"'); + String st = header.getHeader("ST"); + // Check that its the correct URL and that its an ssdp:discover message + if( header.getRequestURL().equals("*") && "ssdp:discover".equalsIgnoreCase(man) ){ + // Check if the requested service exists + if( services.containsKey( st ) ){ + logger.log(Level.FINEST, "Received Multicast(from: "+packet.getAddress()+"): "+ header); - // Generate the SSDP response - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - HttpPrintStream http = new HttpPrintStream( buffer ); - http.setStatusCode(200); - http.setHeader("Location", services.get(st).getLocation() ); - http.setHeader("USN", services.get(st).getUSN() ); - http.setHeader("Server", SERVER_INFO ); - http.setHeader("ST", st ); - http.setHeader("EXT", "" ); - http.setHeader("Cache-Control", "max-age = "+ cache_time ); - if(services.get(st) instanceof SSDPCustomInfo) - ((SSDPCustomInfo)services.get(st)).writeHeaders(http); + // Generate the SSDP response + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + HttpPrintStream http = new HttpPrintStream( buffer ); + http.setStatusCode(200); + http.setHeader("Location", services.get(st).getLocation() ); + http.setHeader("USN", services.get(st).getUSN() ); + http.setHeader("Server", SERVER_INFO ); + http.setHeader("ST", st ); + http.setHeader("EXT", "" ); + http.setHeader("Cache-Control", "max-age = "+ cache_time ); + if(services.get(st) instanceof SSDPCustomInfo) + ((SSDPCustomInfo)services.get(st)).writeHeaders(http); logger.log(Level.FINEST, "Sending Response: "+ http); http.flush(); - byte[] data = buffer.toByteArray(); - packet = new DatagramPacket( - data, data.length, - packet.getAddress(), - packet.getPort()); - network.send( packet ); + byte[] data = buffer.toByteArray(); + packet = new DatagramPacket( + data, data.length, + packet.getAddress(), + packet.getPort()); + network.send( packet ); http.close(); - } - } - } - } catch (IOException e) { - logger.log(Level.SEVERE, null, e); - } - } + } + } + } + } catch (IOException e) { + logger.log(Level.SEVERE, null, e); + } + } - /** - * This thread is a timer task that sends an - * notification message to the network every - * cache_time/2 seconds. - * - * @author Ziver - */ - private class NotifyTimer extends TimerTask { - public void run(){ - sendNotify(); - } - } - /** - * Sends keep-alive messages to update the cache of the clients - */ - public void sendNotify(){ - for(String st : services.keySet()){ - sendNotify( st ); - } - } - /** - * Sends an keepalive message to update the cache of the clients - * - * @param searchTarget is the ST value of the service - * - * ********** Message ex: - * NOTIFY * HTTP/1.1 - * Host: 239.255.255.250:reservedSSDPport - * NT: blenderassociation:blender - * NTS: ssdp:alive - * USN: someunique:idscheme3 - * Location: http://localhost:80 - * Cache-Control: max-age = 7393 - */ - public void sendNotify(String searchTarget){ - try { + /** + * This thread is a timer task that sends an + * notification message to the network every + * cache_time/2 seconds. + * + * @author Ziver + */ + private class NotifyTimer extends TimerTask { + public void run(){ + sendNotify(); + } + } + /** + * Sends keep-alive messages to update the cache of the clients + */ + public void sendNotify(){ + for(String st : services.keySet()){ + sendNotify( st ); + } + } + /** + * Sends an keepalive message to update the cache of the clients + * + * @param searchTarget is the ST value of the service + * + * ********** Message ex: + * NOTIFY * HTTP/1.1 + * Host: 239.255.255.250:reservedSSDPport + * NT: blenderassociation:blender + * NTS: ssdp:alive + * USN: someunique:idscheme3 + * Location: http://localhost:80 + * Cache-Control: max-age = 7393 + */ + public void sendNotify(String searchTarget){ + try { SSDPServiceInfo service = services.get(searchTarget); - // Generate the SSDP response - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - HttpPrintStream http = new HttpPrintStream( buffer, HttpPrintStream.HttpMessageType.REQUEST ); - http.setRequestType("NOTIFY"); - http.setRequestURL("*"); - http.setHeader("Server", SERVER_INFO ); - http.setHeader("Host", SSDP_MULTICAST_ADDR+":"+SSDP_PORT ); - http.setHeader("NT", searchTarget ); - http.setHeader("NTS", "ssdp:alive" ); - http.setHeader("Location", service.getLocation() ); - http.setHeader("Cache-Control", "max-age = "+cache_time ); - http.setHeader("USN", service.getUSN() ); - if(service instanceof SSDPCustomInfo) + // Generate the SSDP response + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + HttpPrintStream http = new HttpPrintStream( buffer, HttpPrintStream.HttpMessageType.REQUEST ); + http.setRequestType("NOTIFY"); + http.setRequestURL("*"); + http.setHeader("Server", SERVER_INFO ); + http.setHeader("Host", SSDP_MULTICAST_ADDR+":"+SSDP_PORT ); + http.setHeader("NT", searchTarget ); + http.setHeader("NTS", "ssdp:alive" ); + http.setHeader("Location", service.getLocation() ); + http.setHeader("Cache-Control", "max-age = "+cache_time ); + http.setHeader("USN", service.getUSN() ); + if(service instanceof SSDPCustomInfo) ((SSDPCustomInfo) service).writeHeaders(http); logger.log(Level.FINEST, "Sending Notification: " + http); http.flush(); - byte[] data = buffer.toByteArray(); - DatagramPacket packet = new DatagramPacket( - data, data.length, - InetAddress.getByName( SSDP_MULTICAST_ADDR ), - SSDP_PORT ); - super.send( packet ); + byte[] data = buffer.toByteArray(); + DatagramPacket packet = new DatagramPacket( + data, data.length, + InetAddress.getByName( SSDP_MULTICAST_ADDR ), + SSDP_PORT ); + super.send( packet ); http.close(); - } catch (Exception e) { - logger.log(Level.SEVERE, null, e); - } - } + } catch (Exception e) { + logger.log(Level.SEVERE, null, e); + } + } - /** - * Shutdown message is sent to the clients that all - * the service is shutting down. - */ - public void sendByeBye(){ - for(String st : services.keySet()){ - sendByeBye( st ); - } - } - /** - * Shutdown message is sent to the clients that the service is shutting down - * - * @param searchTarget is the ST value of the service - * - * ********** Message ex: - * NOTIFY * HTTP/1.1 - * Host: 239.255.255.250:reservedSSDPport - * NT: someunique:idscheme3 - * NTS: ssdp:byebye - * USN: someunique:idscheme3 - */ - public void sendByeBye(String searchTarget){ - try { - // Generate the SSDP response - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - HttpPrintStream http = new HttpPrintStream( buffer, HttpPrintStream.HttpMessageType.REQUEST ); - http.setRequestType("NOTIFY"); - http.setRequestURL("*"); - http.setHeader("Server", SERVER_INFO ); - http.setHeader("Host", SSDP_MULTICAST_ADDR+":"+SSDP_PORT ); - http.setHeader("NT", searchTarget ); - http.setHeader("NTS", "ssdp:byebye" ); - http.setHeader("USN", services.get(searchTarget).getUSN() ); + /** + * Shutdown message is sent to the clients that all + * the service is shutting down. + */ + public void sendByeBye(){ + for(String st : services.keySet()){ + sendByeBye( st ); + } + } + /** + * Shutdown message is sent to the clients that the service is shutting down + * + * @param searchTarget is the ST value of the service + * + * ********** Message ex: + * NOTIFY * HTTP/1.1 + * Host: 239.255.255.250:reservedSSDPport + * NT: someunique:idscheme3 + * NTS: ssdp:byebye + * USN: someunique:idscheme3 + */ + public void sendByeBye(String searchTarget){ + try { + // Generate the SSDP response + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + HttpPrintStream http = new HttpPrintStream( buffer, HttpPrintStream.HttpMessageType.REQUEST ); + http.setRequestType("NOTIFY"); + http.setRequestURL("*"); + http.setHeader("Server", SERVER_INFO ); + http.setHeader("Host", SSDP_MULTICAST_ADDR+":"+SSDP_PORT ); + http.setHeader("NT", searchTarget ); + http.setHeader("NTS", "ssdp:byebye" ); + http.setHeader("USN", services.get(searchTarget).getUSN() ); logger.log(Level.FINEST, "Sending ByeBye: " + http); http.flush(); - byte[] data = buffer.toByteArray(); - DatagramPacket packet = new DatagramPacket( - data, data.length, - InetAddress.getByName( SSDP_MULTICAST_ADDR ), - SSDP_PORT ); - super.send( packet ); + byte[] data = buffer.toByteArray(); + DatagramPacket packet = new DatagramPacket( + data, data.length, + InetAddress.getByName( SSDP_MULTICAST_ADDR ), + SSDP_PORT ); + super.send( packet ); http.close(); - } catch (Exception e) { - logger.log(Level.SEVERE, null, e); - } - } + } catch (Exception e) { + logger.log(Level.SEVERE, null, e); + } + } } diff --git a/src/zutil/net/ssdp/SSDPServiceInfo.java b/src/zutil/net/ssdp/SSDPServiceInfo.java index 4131957..238f5a8 100755 --- a/src/zutil/net/ssdp/SSDPServiceInfo.java +++ b/src/zutil/net/ssdp/SSDPServiceInfo.java @@ -31,29 +31,29 @@ package zutil.net.ssdp; * @author Ziver */ public interface SSDPServiceInfo { - - /** - * @return the URL to the Service, e.g. "http://192.168.0.1:80/index.html" - */ - public String getLocation(); - /** - * @return the Search Target, e.g. "upnp:rootdevice" - */ - public String getSearchTarget(); - - /** - * @return the expiration time for the values in this object - */ - public long getExpirationTime(); - - /** - * @return the USN value, e.g. "uuid:abcdefgh-7dec-11d0-a765-00a0c91e6bf6 " - */ - public String getUSN(); - - /** - * @return only the USN UUID String - */ - public String getUUID(); + /** + * @return the URL to the Service, e.g. "http://192.168.0.1:80/index.html" + */ + public String getLocation(); + + /** + * @return the Search Target, e.g. "upnp:rootdevice" + */ + public String getSearchTarget(); + + /** + * @return the expiration time for the values in this object + */ + public long getExpirationTime(); + + /** + * @return the USN value, e.g. "uuid:abcdefgh-7dec-11d0-a765-00a0c91e6bf6 " + */ + public String getUSN(); + + /** + * @return only the USN UUID String + */ + public String getUUID(); } diff --git a/src/zutil/net/ssdp/StandardSSDPInfo.java b/src/zutil/net/ssdp/StandardSSDPInfo.java index 644a85d..1aa7274 100755 --- a/src/zutil/net/ssdp/StandardSSDPInfo.java +++ b/src/zutil/net/ssdp/StandardSSDPInfo.java @@ -41,124 +41,124 @@ import java.util.UUID; * @author Ziver */ public class StandardSSDPInfo implements SSDPServiceInfo, SSDPCustomInfo{ - private String location; - private String st; - private String usn; - private long expiration_time; - // All header parameters - private HashMap headers = new HashMap<>(); - private InetAddress inetAddress; + private String location; + private String st; + private String usn; + private long expiration_time; + // All header parameters + private HashMap headers = new HashMap<>(); + private InetAddress inetAddress; - /** - * @param l is the value to set the Location variable - */ - public void setLocation(String l) { - location = l; - } - - /** - * @param st is the value to set the SearchTarget variable - */ - public void setST(String st) { - this.st = st; - } + /** + * @param l is the value to set the Location variable + */ + public void setLocation(String l) { + location = l; + } - /** - * @param usn is the value to set the USN variable - */ - protected void setUSN(String usn) { - this.usn = usn; - } - - /** - * @param time sets the expiration time of values in this object - */ - protected void setExpirationTime(long time) { - expiration_time = time; - } - - /** - * @return The URL to the Service, e.g. "http://192.168.0.1:80/index.html" - */ - public String getLocation(){ - return location; - } - - /** - * @return the Search Target, e.g. "upnp:rootdevice" - */ - public String getSearchTarget(){ - return st; - } - - /** - * @return the expiration time for the values in this object - */ - public long getExpirationTime(){ - return expiration_time; - } - - /** - * @return the USN value, e.g. "uuid:abcdefgh-7dec-11d0-a765-00a0c91e6bf6 " - */ - public String getUSN(){ - if( usn==null ) - usn = genUSN(); - return usn+"::"+st; - } - - /** - * @return only the USN UUID String - */ - public String getUUID(){ - if( usn==null ) - usn = genUSN(); - return usn; - } + /** + * @param st is the value to set the SearchTarget variable + */ + public void setST(String st) { + this.st = st; + } - /** - * Generates an unique USN for the service - * - * @return an unique string that corresponds to the service - */ - private String genUSN(){ - return "uuid:" + UUID.nameUUIDFromBytes( (st+location+Math.random()).getBytes() ); - } - - public String toString(){ - return "USN: "+usn+"\nLocation: "+location+"\nST: "+st+"\nExpiration-Time: "+new Date(expiration_time); - } + /** + * @param usn is the value to set the USN variable + */ + protected void setUSN(String usn) { + this.usn = usn; + } + + /** + * @param time sets the expiration time of values in this object + */ + protected void setExpirationTime(long time) { + expiration_time = time; + } + + /** + * @return The URL to the Service, e.g. "http://192.168.0.1:80/index.html" + */ + public String getLocation(){ + return location; + } + + /** + * @return the Search Target, e.g. "upnp:rootdevice" + */ + public String getSearchTarget(){ + return st; + } + + /** + * @return the expiration time for the values in this object + */ + public long getExpirationTime(){ + return expiration_time; + } + + /** + * @return the USN value, e.g. "uuid:abcdefgh-7dec-11d0-a765-00a0c91e6bf6 " + */ + public String getUSN(){ + if( usn==null ) + usn = genUSN(); + return usn+"::"+st; + } + + /** + * @return only the USN UUID String + */ + public String getUUID(){ + if( usn==null ) + usn = genUSN(); + return usn; + } + + /** + * Generates an unique USN for the service + * + * @return an unique string that corresponds to the service + */ + private String genUSN(){ + return "uuid:" + UUID.nameUUIDFromBytes( (st+location+Math.random()).getBytes() ); + } + + public String toString(){ + return "USN: "+usn+"\nLocation: "+location+"\nST: "+st+"\nExpiration-Time: "+new Date(expiration_time); + } public void setHeader(String key, String value) { headers.put(key, value); } - public String getHeader(String header){ - return headers.get(header); - } - @Override - public void writeHeaders(HttpPrintStream http) { - try { + public String getHeader(String header){ + return headers.get(header); + } + @Override + public void writeHeaders(HttpPrintStream http) { + try { for (String key : headers.keySet()) http.setHeader(key, headers.get(key)); - }catch(IOException e){ + }catch(IOException e){ e.printStackTrace(); - } - } + } + } @Override public void readHeaders(HttpHeader header) { Iterator it = header.getHeaderKeys(); while (it.hasNext()) { - String key = it.next(); - headers.put(key, header.getHeader(key)); - } + String key = it.next(); + headers.put(key, header.getHeader(key)); + } } - public InetAddress getInetAddress(){ - return inetAddress; - } + public InetAddress getInetAddress(){ + return inetAddress; + } - protected void setInetAddress(InetAddress inetAddress) { - this.inetAddress = inetAddress; - } + protected void setInetAddress(InetAddress inetAddress) { + this.inetAddress = inetAddress; + } } diff --git a/src/zutil/net/threaded/ThreadedTCPNetworkServer.java b/src/zutil/net/threaded/ThreadedTCPNetworkServer.java index e2839fd..c071c37 100755 --- a/src/zutil/net/threaded/ThreadedTCPNetworkServer.java +++ b/src/zutil/net/threaded/ThreadedTCPNetworkServer.java @@ -47,108 +47,108 @@ import java.util.logging.Logger; * @author Ziver */ public abstract class ThreadedTCPNetworkServer extends Thread{ - private static final Logger logger = LogUtil.getLogger(); - - private final int port; - private Executor executor; - private File keyStore; - private String keyStorePass; + private static final Logger logger = LogUtil.getLogger(); - /** - * Creates a new instance of the sever - * - * @param port The port that the server should listen to - */ - public ThreadedTCPNetworkServer(int port){ - this(port, null, null); - } - /** - * Creates a new instance of the sever - * - * @param port The port that the server should listen to - * @param keyStore If this is not null then the server will use SSL connection with this keyStore file path - * @param keyStorePass If this is not null then the server will use a SSL connection with the given certificate - */ - public ThreadedTCPNetworkServer(int port, File keyStore, String keyStorePass){ - this.port = port; + private final int port; + private Executor executor; + private File keyStore; + private String keyStorePass; + + /** + * Creates a new instance of the sever + * + * @param port The port that the server should listen to + */ + public ThreadedTCPNetworkServer(int port){ + this(port, null, null); + } + /** + * Creates a new instance of the sever + * + * @param port The port that the server should listen to + * @param keyStore If this is not null then the server will use SSL connection with this keyStore file path + * @param keyStorePass If this is not null then the server will use a SSL connection with the given certificate + */ + public ThreadedTCPNetworkServer(int port, File keyStore, String keyStorePass){ + this.port = port; executor = Executors.newCachedThreadPool(); - this.keyStorePass = keyStorePass; - this.keyStore = keyStore; - } + this.keyStorePass = keyStorePass; + this.keyStore = keyStore; + } - public void run(){ - ServerSocket serverSocket = null; - try{ - if(keyStorePass != null && keyStore != null){ - registerCertificate(keyStore, keyStorePass); - serverSocket = initSSL( port ); - } - else{ - serverSocket = new ServerSocket( port ); - } - logger.info("Listening for TCP Connections on port: "+port); + public void run(){ + ServerSocket serverSocket = null; + try{ + if(keyStorePass != null && keyStore != null){ + registerCertificate(keyStore, keyStorePass); + serverSocket = initSSL( port ); + } + else{ + serverSocket = new ServerSocket( port ); + } + logger.info("Listening for TCP Connections on port: "+port); - while(true){ - Socket connectionSocket = serverSocket.accept(); - ThreadedTCPNetworkServerThread thread = getThreadInstance( connectionSocket ); - if( thread!=null ) { + while(true){ + Socket connectionSocket = serverSocket.accept(); + ThreadedTCPNetworkServerThread thread = getThreadInstance( connectionSocket ); + if( thread!=null ) { executor.execute(thread); - } - else{ - logger.severe("Unable to instantiate ThreadedTCPNetworkServerThread, closing connection!"); - connectionSocket.close(); - } - } - } catch(Exception e) { - logger.log(Level.SEVERE, null, e); - } finally { - if( serverSocket!=null ){ - try{ - serverSocket.close(); - }catch(IOException e){ logger.log(Level.SEVERE, null, e); } - } - } - } + } + else{ + logger.severe("Unable to instantiate ThreadedTCPNetworkServerThread, closing connection!"); + connectionSocket.close(); + } + } + } catch(Exception e) { + logger.log(Level.SEVERE, null, e); + } finally { + if( serverSocket!=null ){ + try{ + serverSocket.close(); + }catch(IOException e){ logger.log(Level.SEVERE, null, e); } + } + } + } - /** - * This method returns an new instance of the ThreadedTCPNetworkServerThread - * that will handle the newly made connection, if an null value is returned - * then the ThreadedTCPNetworkServer will close the new connection. - * - * @param s is an new connection to an host - * @return a new instance of an thread or null - */ - protected abstract ThreadedTCPNetworkServerThread getThreadInstance( Socket s ) throws IOException; + /** + * This method returns an new instance of the ThreadedTCPNetworkServerThread + * that will handle the newly made connection, if an null value is returned + * then the ThreadedTCPNetworkServer will close the new connection. + * + * @param s is an new connection to an host + * @return a new instance of an thread or null + */ + protected abstract ThreadedTCPNetworkServerThread getThreadInstance( Socket s ) throws IOException; - /** - * Initiates a SSLServerSocket - * - * @param port The port to listen to - * @return The SSLServerSocket - */ - private ServerSocket initSSL(int port) throws IOException{ - SSLServerSocketFactory sslserversocketfactory = - (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - return sslserversocketfactory.createServerSocket(port); + /** + * Initiates a SSLServerSocket + * + * @param port The port to listen to + * @return The SSLServerSocket + */ + private ServerSocket initSSL(int port) throws IOException{ + SSLServerSocketFactory sslserversocketfactory = + (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); + return sslserversocketfactory.createServerSocket(port); - } + } - /** - * Registers the given cert file to the KeyStore - * - * @param keyStore The cert file - */ - protected void registerCertificate(File keyStore, String keyStorePass) throws CertificateException, IOException, KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException{ - System.setProperty("javax.net.ssl.keyStore", keyStore.getAbsolutePath()); - System.setProperty("javax.net.ssl.keyStorePassword", keyStorePass); - } - - /** - * Stops the server and interrupts its internal thread. - * This is a permanent action that will not be able to recover from - */ - public void close(){ - this.interrupt(); - } + /** + * Registers the given cert file to the KeyStore + * + * @param keyStore The cert file + */ + protected void registerCertificate(File keyStore, String keyStorePass) throws CertificateException, IOException, KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException{ + System.setProperty("javax.net.ssl.keyStore", keyStore.getAbsolutePath()); + System.setProperty("javax.net.ssl.keyStorePassword", keyStorePass); + } + + /** + * Stops the server and interrupts its internal thread. + * This is a permanent action that will not be able to recover from + */ + public void close(){ + this.interrupt(); + } } diff --git a/src/zutil/net/threaded/ThreadedUDPNetwork.java b/src/zutil/net/threaded/ThreadedUDPNetwork.java index 2850056..ad4f43b 100755 --- a/src/zutil/net/threaded/ThreadedUDPNetwork.java +++ b/src/zutil/net/threaded/ThreadedUDPNetwork.java @@ -35,102 +35,102 @@ import java.net.*; * @author Ziver */ public class ThreadedUDPNetwork extends Thread{ - public static final int BUFFER_SIZE = 512; - - // Type of UDP socket - enum UDPType{ - MULTICAST, - UNICAST - } - protected final UDPType type; - protected final int port; - protected DatagramSocket socket; - protected ThreadedUDPNetworkThread thread = null; + public static final int BUFFER_SIZE = 512; - /** - * Creates a new unicast Client instance of the class - * - * @throws SocketException - */ - public ThreadedUDPNetwork() throws SocketException{ - this.type = UDPType.UNICAST; - this.port = -1; - - socket = new DatagramSocket(); - } + // Type of UDP socket + enum UDPType{ + MULTICAST, + UNICAST + } + protected final UDPType type; + protected final int port; + protected DatagramSocket socket; + protected ThreadedUDPNetworkThread thread = null; - /** - * 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; - this.port = port; - - socket = new DatagramSocket( port ); - } - - /** - * Creates a new multicast Server instance of the class - * - * @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; - this.port = port; - - // init udp socket - MulticastSocket msocket = new MulticastSocket( port ); - InetAddress group = InetAddress.getByName( multicastAddr ); - msocket.joinGroup( group ); + /** + * Creates a new unicast Client instance of the class + * + * @throws SocketException + */ + public ThreadedUDPNetwork() throws SocketException{ + this.type = UDPType.UNICAST; + this.port = -1; - socket = msocket; - } + socket = new DatagramSocket(); + } + + /** + * 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; + this.port = port; + + socket = new DatagramSocket( port ); + } + + /** + * Creates a new multicast Server instance of the class + * + * @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; + this.port = port; + + // init udp socket + MulticastSocket msocket = new MulticastSocket( port ); + InetAddress group = InetAddress.getByName( multicastAddr ); + msocket.joinGroup( group ); + + socket = msocket; + } - public void run(){ - try{ - while(true){ - byte[] buf = new byte[BUFFER_SIZE]; - DatagramPacket packet = new DatagramPacket(buf, buf.length); - socket.receive( packet ); - if( thread!=null ) - thread.receivedPacket( packet, this ); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Sends the given packet - * - * @param packet is the packet to send - * @throws IOException - */ - public synchronized void send( DatagramPacket packet ) throws IOException{ - socket.send(packet); - } - - /** - * Sets the thread that will handle the incoming packets - * - * @param thread is the thread - */ - public void setThread(ThreadedUDPNetworkThread thread){ - this.thread = thread; - } - - /** - * Stops the server and interrupts its internal thread. - * This is a permanent action that will not be able to recover from - */ - public void close(){ - this.interrupt(); - socket.close(); - } + public void run(){ + try{ + while(true){ + byte[] buf = new byte[BUFFER_SIZE]; + DatagramPacket packet = new DatagramPacket(buf, buf.length); + socket.receive( packet ); + if( thread!=null ) + thread.receivedPacket( packet, this ); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Sends the given packet + * + * @param packet is the packet to send + * @throws IOException + */ + public synchronized void send( DatagramPacket packet ) throws IOException{ + socket.send(packet); + } + + /** + * Sets the thread that will handle the incoming packets + * + * @param thread is the thread + */ + public void setThread(ThreadedUDPNetworkThread thread){ + this.thread = thread; + } + + /** + * Stops the server and interrupts its internal thread. + * This is a permanent action that will not be able to recover from + */ + public void close(){ + this.interrupt(); + socket.close(); + } } diff --git a/src/zutil/net/threaded/ThreadedUDPNetworkThread.java b/src/zutil/net/threaded/ThreadedUDPNetworkThread.java index 52bd3c8..f119053 100644 --- a/src/zutil/net/threaded/ThreadedUDPNetworkThread.java +++ b/src/zutil/net/threaded/ThreadedUDPNetworkThread.java @@ -34,12 +34,12 @@ import java.net.DatagramPacket; * */ public interface ThreadedUDPNetworkThread extends Runnable{ - - /** - * Packet will be processed in this method - * - * @param packet is the received packet - * @param network is the network class that received the packet - */ - public void receivedPacket(DatagramPacket packet, ThreadedUDPNetwork network); + + /** + * Packet will be processed in this method + * + * @param packet is the received packet + * @param network is the network class that received the packet + */ + void receivedPacket(DatagramPacket packet, ThreadedUDPNetwork network); } diff --git a/src/zutil/net/torrent/TorrentFile.java b/src/zutil/net/torrent/TorrentFile.java index 4e205b1..2ffcfc3 100755 --- a/src/zutil/net/torrent/TorrentFile.java +++ b/src/zutil/net/torrent/TorrentFile.java @@ -30,19 +30,19 @@ package zutil.net.torrent; * @author Ziver */ public class TorrentFile{ - private String filename; - private long size; - - public TorrentFile(String filename, long size){ - this.filename = filename; - this.size = size; - } - + private String filename; + private long size; - public String getFilename() { - return filename; - } - public long getSize() { - return size; - } + public TorrentFile(String filename, long size){ + this.filename = filename; + this.size = size; + } + + + public String getFilename() { + return filename; + } + public long getSize() { + return size; + } } diff --git a/src/zutil/net/torrent/TorrentMetainfo.java b/src/zutil/net/torrent/TorrentMetainfo.java index 793f069..3d46960 100755 --- a/src/zutil/net/torrent/TorrentMetainfo.java +++ b/src/zutil/net/torrent/TorrentMetainfo.java @@ -39,144 +39,144 @@ import java.util.Iterator; public class TorrentMetainfo { /** Name **/ private String name; - /** Comment (optional) **/ - private String comment; - /** Signature of the software which created the torrent (optional) **/ - private String created_by; - /** Creation date as Unix timestamp (optional) **/ - private long creation_date; - /** The main Tracker (the tracker the torrent has been received from) **/ - private String announce; - /** List of known trackers for the torrent (optional) **/ - private ArrayList announce_list; - /** The encoding of the Strings (optional) **/ - private String encoding; + /** Comment (optional) **/ + private String comment; + /** Signature of the software which created the torrent (optional) **/ + private String created_by; + /** Creation date as Unix timestamp (optional) **/ + private long creation_date; + /** The main Tracker (the tracker the torrent has been received from) **/ + private String announce; + /** List of known trackers for the torrent (optional) **/ + private ArrayList announce_list; + /** The encoding of the Strings (optional) **/ + private String encoding; - /** Size of of the full torrent (after download) **/ - private long size; - /** Number of bytes in each piece **/ - private long piece_length; - /** String consisting of the concatenation of all 20-byte SHA1 hash values, one per piece **/ - private ArrayList piece_hashes; - /** Torrent is private. No other trackers allowed other then those listed. (optional) **/ - private boolean is_private; + /** Size of of the full torrent (after download) **/ + private long size; + /** Number of bytes in each piece **/ + private long piece_length; + /** String consisting of the concatenation of all 20-byte SHA1 hash values, one per piece **/ + private ArrayList piece_hashes; + /** Torrent is private. No other trackers allowed other then those listed. (optional) **/ + private boolean is_private; - // Files in the torrent - private ArrayList file_list; + // Files in the torrent + private ArrayList file_list; - public TorrentMetainfo(File torrent) throws IOException, ParseException { - this(FileUtil.getContent(torrent)); - } + public TorrentMetainfo(File torrent) throws IOException, ParseException { + this(FileUtil.getContent(torrent)); + } - public TorrentMetainfo(String data) throws ParseException { - decode(data); - } + public TorrentMetainfo(String data) throws ParseException { + decode(data); + } - private void decode(String data) throws ParseException { - DataNode metainfo = BEncodedParser.read(data); - - // Main values - announce = metainfo.getString("announce"); - created_by = metainfo.getString("created by"); - comment = metainfo.getString("comment"); - encoding = metainfo.getString("encoding"); - if( metainfo.get("creation date") != null ) - creation_date = metainfo.getLong("creation date"); - if( metainfo.get("announce-list") != null ){ - DataNode tmp = metainfo.get("announce-list"); - announce_list = new ArrayList(); - for( DataNode tracker : tmp ) - announce_list.add( tracker.getString() ); - } + private void decode(String data) throws ParseException { + DataNode metainfo = BEncodedParser.read(data); - // info data - DataNode info = metainfo.get("info"); - name = info.getString("name"); - piece_length = info.getLong("piece length"); - if( info.get("private") != null ) - is_private = (info.getInt("private") != 0); - // Split the hashes - String hashes = info.getString("pieces"); - piece_hashes = new ArrayList(); - for(int i=0; i(); + for( DataNode tracker : tmp ) + announce_list.add( tracker.getString() ); + } - // File data - file_list = new ArrayList(); - // Single-file torrent - if( info.get("files") == null ){ - Long fileSize = size = info.getLong("length"); - file_list.add( new TorrentFile(name, fileSize) ); - } - // Multi-file torrent - else{ - DataNode files = info.get("files"); - for( DataNode file : files ){ - StringBuilder filename = new StringBuilder(); - DataNode tmp = file.get("path"); - // File in subdir - if( tmp.isList() ){ - Iterator it = tmp.iterator(); - while( it.hasNext() ){ - filename.append(it.next().getString()); - if(it.hasNext()) - filename.append(File.separator); - } - } - // File in root dir - else - filename.append(tmp.getString()); - Long fileSize = file.getLong("length"); + // info data + DataNode info = metainfo.get("info"); + name = info.getString("name"); + piece_length = info.getLong("piece length"); + if( info.get("private") != null ) + is_private = (info.getInt("private") != 0); + // Split the hashes + String hashes = info.getString("pieces"); + piece_hashes = new ArrayList(); + for(int i=0; i(); + // Single-file torrent + if( info.get("files") == null ){ + Long fileSize = size = info.getLong("length"); + file_list.add( new TorrentFile(name, fileSize) ); + } + // Multi-file torrent + else{ + DataNode files = info.get("files"); + for( DataNode file : files ){ + StringBuilder filename = new StringBuilder(); + DataNode tmp = file.get("path"); + // File in subdir + if( tmp.isList() ){ + Iterator it = tmp.iterator(); + while( it.hasNext() ){ + filename.append(it.next().getString()); + if(it.hasNext()) + filename.append(File.separator); + } + } + // File in root dir + else + filename.append(tmp.getString()); + Long fileSize = file.getLong("length"); size += fileSize; - file_list.add( new TorrentFile(filename.toString(), fileSize) ); - } - } - } + file_list.add( new TorrentFile(filename.toString(), fileSize) ); + } + } + } - public String getName() { - return name; - } - public String getComment() { - return comment; - } - public String getCreatedBy() { - return created_by; - } - public long getCreationDate() { - return creation_date; - } - public String getAnnounce() { - return announce; - } - public ArrayList getAnnounceList() { - return announce_list; - } - public String getEncoding() { - return encoding; - } - public long getSize() { - return size; - } - public long getPieceLength() { - return piece_length; - } - public ArrayList getPieceHashes() { - return piece_hashes; - } - public boolean isPrivate() { - return is_private; - } - public ArrayList getFileList() { - return file_list; - } + public String getName() { + return name; + } + public String getComment() { + return comment; + } + public String getCreatedBy() { + return created_by; + } + public long getCreationDate() { + return creation_date; + } + public String getAnnounce() { + return announce; + } + public ArrayList getAnnounceList() { + return announce_list; + } + public String getEncoding() { + return encoding; + } + public long getSize() { + return size; + } + public long getPieceLength() { + return piece_length; + } + public ArrayList getPieceHashes() { + return piece_hashes; + } + public boolean isPrivate() { + return is_private; + } + public ArrayList getFileList() { + return file_list; + } } diff --git a/src/zutil/net/torrent/TorrentTracker.java b/src/zutil/net/torrent/TorrentTracker.java index ae4740a..0959df6 100755 --- a/src/zutil/net/torrent/TorrentTracker.java +++ b/src/zutil/net/torrent/TorrentTracker.java @@ -37,14 +37,14 @@ import java.net.URL; * @author Ziver */ public class TorrentTracker { - /** The address to the tracker **/ - private URL trackerURL; - - - // TODO: incomplete - public void update() throws IOException { - HttpClient request = new HttpClient(HttpClient.HttpRequestType.GET); - request.setURL( trackerURL ); - HttpHeaderParser response = request.send(); - } + /** The address to the tracker **/ + private URL trackerURL; + + + // TODO: incomplete + public void update() throws IOException { + HttpClient request = new HttpClient(HttpClient.HttpRequestType.GET); + request.setURL( trackerURL ); + HttpHeaderParser response = request.send(); + } } diff --git a/src/zutil/net/update/FileInfo.java b/src/zutil/net/update/FileInfo.java index 35603a0..2706cd1 100644 --- a/src/zutil/net/update/FileInfo.java +++ b/src/zutil/net/update/FileInfo.java @@ -38,44 +38,44 @@ import java.io.Serializable; * @author Ziver */ public class FileInfo implements Serializable{ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private transient File file; - private String path; - private String hash; - private long size; + private transient File file; + private String path; + private String hash; + private long size; - public FileInfo(String root, File file) throws IOException{ - path = FileUtil.relativePath(file, root); - hash = Hasher.MD5(file); - size = file.length(); - this.file = file; - } + public FileInfo(String root, File file) throws IOException{ + path = FileUtil.relativePath(file, root); + hash = Hasher.MD5(file); + size = file.length(); + this.file = file; + } - public String getPath() { - return path; - } - public String getHash() { - return hash; - } - public long getSize() { - return size; - } - public File getFile(){ - return file; - } + public String getPath() { + return path; + } + public String getHash() { + return hash; + } + public long getSize() { + return size; + } + public File getFile(){ + return file; + } - public boolean equals(Object comp){ - if(comp instanceof FileInfo){ - FileInfo tmp = (FileInfo)comp; - return path.equals(tmp.path) && hash.equals(tmp.hash); - } - return false; - } + public boolean equals(Object comp){ + if(comp instanceof FileInfo){ + FileInfo tmp = (FileInfo)comp; + return path.equals(tmp.path) && hash.equals(tmp.hash); + } + return false; + } - public String toString(){ - return path; - } + public String toString(){ + return path; + } } diff --git a/src/zutil/net/update/FileListMessage.java b/src/zutil/net/update/FileListMessage.java index 61884e9..6dfeeb7 100644 --- a/src/zutil/net/update/FileListMessage.java +++ b/src/zutil/net/update/FileListMessage.java @@ -39,68 +39,68 @@ import java.util.List; * @author Ziver */ class FileListMessage implements Serializable{ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private ArrayList fileList; - private long totalSize; + private ArrayList fileList; + private long totalSize; - private FileListMessage(){} - - /** - * Returns a ArrayList of FileInfo object for all the files in the specified folder - * - * @param path is the path to scan - **/ - public FileListMessage(String path) throws IOException{ - fileList = new ArrayList(); + private FileListMessage(){} - List files = FileUtil.search(FileUtil.find(path)); - long totalSize = 0; - for(File file : files){ - FileInfo fileInfo = new FileInfo(path, file); - fileList.add( fileInfo ); - totalSize += fileInfo.getSize(); - } - this.totalSize = totalSize; - } + /** + * Returns a ArrayList of FileInfo object for all the files in the specified folder + * + * @param path is the path to scan + **/ + public FileListMessage(String path) throws IOException{ + fileList = new ArrayList(); + + List files = FileUtil.search(FileUtil.find(path)); + long totalSize = 0; + for(File file : files){ + FileInfo fileInfo = new FileInfo(path, file); + fileList.add( fileInfo ); + totalSize += fileInfo.getSize(); + } + this.totalSize = totalSize; + } - public long getTotalSize() { - return totalSize; - } - - public ArrayList getFileList(){ - return fileList; - } - - /** - * Compares the files and returns the files that differ from this file list - * - * @param comp is the file list to compare with - * @return - */ - public FileListMessage getDiff( FileListMessage comp){ - FileListMessage diff = new FileListMessage(); + public long getTotalSize() { + return totalSize; + } - long diffSize = 0; - diff.fileList = new ArrayList(); - for(FileInfo file : this.fileList){ - if( !comp.fileList.contains( file)){ - diff.fileList.add( file ); - diffSize += file.getSize(); - } - } - diff.totalSize = diffSize; - - return diff; - } + public ArrayList getFileList(){ + return fileList; + } + + /** + * Compares the files and returns the files that differ from this file list + * + * @param comp is the file list to compare with + * @return + */ + public FileListMessage getDiff( FileListMessage comp){ + FileListMessage diff = new FileListMessage(); + + long diffSize = 0; + diff.fileList = new ArrayList(); + for(FileInfo file : this.fileList){ + if( !comp.fileList.contains( file)){ + diff.fileList.add( file ); + diffSize += file.getSize(); + } + } + diff.totalSize = diffSize; + + return diff; + } - public boolean equals(Object comp){ - if(comp instanceof FileListMessage){ - FileListMessage tmp = (FileListMessage)comp; - return fileList.equals(tmp.fileList) && totalSize == tmp.totalSize; - } - return false; - } + 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 25f9fe4..f610e58 100644 --- a/src/zutil/net/update/UpdateClient.java +++ b/src/zutil/net/update/UpdateClient.java @@ -41,134 +41,134 @@ import java.util.logging.Logger; * */ public class UpdateClient{ - private static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); - private String path; - private Socket socket; - private FileListMessage fileList; + private String path; + private Socket socket; + private FileListMessage fileList; - private long speed; - private long totalReceived; - private long expectedSize; - private ProgressListener progress; + private long speed; + private long totalReceived; + private long expectedSize; + private ProgressListener progress; - /** - * Creates a 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); - socket = new Socket(address, port); - this.path = path; - } + /** + * Creates a 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); + socket = new Socket(address, port); + this.path = path; + } - public void setProgressListener(ProgressListener p){ - progress = p; - } + public void setProgressListener(ProgressListener p){ + progress = p; + } - /** - * Updates the files - */ - public void update() throws IOException{ - try{ - ObjectOutputStream out = new ObjectOutputStream( socket.getOutputStream()); - ObjectInputStream in = new ObjectInputStream ( socket.getInputStream() ); + /** + * Updates the files + */ + public void update() throws IOException{ + try{ + ObjectOutputStream out = new ObjectOutputStream( socket.getOutputStream()); + ObjectInputStream in = new ObjectInputStream ( socket.getInputStream() ); - // send client file list - out.writeObject( fileList ); - out.flush(); - // get update list - FileListMessage updateList = (FileListMessage) in.readObject(); - expectedSize = updateList.getTotalSize(); + // send client file list + out.writeObject( fileList ); + out.flush(); + // get update list + FileListMessage updateList = (FileListMessage) in.readObject(); + expectedSize = updateList.getTotalSize(); - // receive file updates - File tmpPath = FileUtil.find(path); - totalReceived = 0; - for(FileInfo info : updateList.getFileList() ){ - // reading new file data - File file = new File( tmpPath, info.getPath() ); - logger.fine("Updating file: "+file); - if( !file.getParentFile().exists() && !file.getParentFile().mkdirs() ){ - throw new IOException("Unable to create folder: "+file.getParentFile()); - } - File tmpFile = File.createTempFile(file.getName(), ".tmp", tmpPath); - tmpFile.deleteOnExit(); + // receive file updates + File tmpPath = FileUtil.find(path); + totalReceived = 0; + for(FileInfo info : updateList.getFileList() ){ + // reading new file data + File file = new File( tmpPath, info.getPath() ); + logger.fine("Updating file: "+file); + if( !file.getParentFile().exists() && !file.getParentFile().mkdirs() ){ + throw new IOException("Unable to create folder: "+file.getParentFile()); + } + File tmpFile = File.createTempFile(file.getName(), ".tmp", tmpPath); + tmpFile.deleteOnExit(); - FileOutputStream fileOut = new FileOutputStream(tmpFile); - byte[] buffer = new byte[socket.getReceiveBufferSize()]; + FileOutputStream fileOut = new FileOutputStream(tmpFile); + byte[] buffer = new byte[socket.getReceiveBufferSize()]; - long bytesReceived = 0; - int byteRead = 0; - long time = System.currentTimeMillis(); - long timeTotalRecived = 0; + long bytesReceived = 0; + int byteRead = 0; + long time = System.currentTimeMillis(); + long timeTotalRecived = 0; - while( bytesReceived < info.getSize() ) { - byteRead = in.read(buffer); - fileOut.write(buffer, 0, byteRead); - bytesReceived += byteRead; + while( bytesReceived < info.getSize() ) { + byteRead = in.read(buffer); + fileOut.write(buffer, 0, byteRead); + bytesReceived += byteRead; - if(time+1000 < System.currentTimeMillis()){ - time = System.currentTimeMillis(); - speed = (int)(totalReceived - timeTotalRecived); - timeTotalRecived = totalReceived; - } + if(time+1000 < System.currentTimeMillis()){ + time = System.currentTimeMillis(); + speed = (int)(totalReceived - timeTotalRecived); + timeTotalRecived = totalReceived; + } - totalReceived += byteRead; - if(progress != null) progress.progressUpdate(this, info, ((double)totalReceived/updateList.getTotalSize())*100); - } - fileOut.close(); - speed = 0; + totalReceived += byteRead; + if(progress != null) progress.progressUpdate(this, info, ((double)totalReceived/updateList.getTotalSize())*100); + } + fileOut.close(); + speed = 0; - // delete old file and replace whit new - file.delete(); - if( !tmpFile.renameTo(file) ){ - throw new IOException("Can not move downloaded file: "+tmpFile.getAbsolutePath()+" to: "+file); - } - } - }catch(ClassNotFoundException e){ - logger.log(Level.SEVERE, null, e); - } + // delete old file and replace whit new + file.delete(); + if( !tmpFile.renameTo(file) ){ + throw new IOException("Can not move downloaded file: "+tmpFile.getAbsolutePath()+" to: "+file); + } + } + }catch(ClassNotFoundException e){ + logger.log(Level.SEVERE, null, e); + } - logger.info("Update done."); - } + logger.info("Update done."); + } - /** - * Returns the speed of the transfer - * - * @return The speed in bytes/s - */ - public long getSpeed(){ - return speed; - } + /** + * Returns the speed of the transfer + * + * @return The speed in bytes/s + */ + public long getSpeed(){ + return speed; + } - /** - * Returns the total amount of data received - * - * @return a long that represents bytes - */ - public long getTotalReceived(){ - return totalReceived; - } - - /** - * Returns the expected total amount of data that will be received - * - * @return a long that represents bytes - */ - public long getTotalSize(){ - return expectedSize; - } + /** + * Returns the total amount of data received + * + * @return a long that represents bytes + */ + public long getTotalReceived(){ + return totalReceived; + } - /** - * Closes the connection - * - * @throws IOException - */ - public void close() throws IOException{ - socket.close(); - } + /** + * Returns the expected total amount of data that will be received + * + * @return a long that represents bytes + */ + public long getTotalSize(){ + return expectedSize; + } + + /** + * Closes the connection + * + * @throws IOException + */ + public void close() throws IOException{ + socket.close(); + } } diff --git a/src/zutil/net/update/UpdateConfigMessage.java b/src/zutil/net/update/UpdateConfigMessage.java index 86737b5..1194475 100644 --- a/src/zutil/net/update/UpdateConfigMessage.java +++ b/src/zutil/net/update/UpdateConfigMessage.java @@ -32,8 +32,8 @@ import java.io.Serializable; * @author Ziver */ class UpdateConfigMessage implements Serializable{ - private static final long serialVersionUID = 1L; - - protected String hashAlgorithm; - protected boolean compression; + private static final long serialVersionUID = 1L; + + protected String hashAlgorithm; + protected boolean compression; } diff --git a/src/zutil/net/update/UpdateServer.java b/src/zutil/net/update/UpdateServer.java index 95f5388..3580e40 100755 --- a/src/zutil/net/update/UpdateServer.java +++ b/src/zutil/net/update/UpdateServer.java @@ -38,88 +38,88 @@ import java.util.logging.Level; import java.util.logging.Logger; public class UpdateServer extends ThreadedTCPNetworkServer{ - private static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); - private FileListMessage fileList; + private FileListMessage fileList; - /** - * Creates a UpdateServer Thread - * - * @param path The path to sync the clients with - */ - public UpdateServer(int port, String path) throws Exception{ - super(port); - fileList = new FileListMessage(path); - MultiPrintStream.out.dump(fileList); - - this.start(); - logger.info("Update Server Ready."); - } + /** + * Creates a UpdateServer Thread + * + * @param path The path to sync the clients with + */ + public UpdateServer(int port, String path) throws Exception{ + super(port); + fileList = new FileListMessage(path); + MultiPrintStream.out.dump(fileList); - @Override - protected ThreadedTCPNetworkServerThread getThreadInstance(Socket s) { - return new UpdateServerThread(s); - } + this.start(); + logger.info("Update Server Ready."); + } - /** - * Handles all the connecting clients - * - * @author Ziver - */ - class UpdateServerThread implements ThreadedTCPNetworkServerThread{ - private ObjectOutputStream out; - private ObjectInputStream in; - private Socket socket; + @Override + protected ThreadedTCPNetworkServerThread getThreadInstance(Socket s) { + return new UpdateServerThread(s); + } - /** - * Creates a UpdateServerThread - * - * @param c is the socket to the client - */ - public UpdateServerThread(Socket c){ - socket = c; - try { - out = new ObjectOutputStream( socket.getOutputStream()); - in = new ObjectInputStream ( socket.getInputStream() ); - } catch (IOException e) { - logger.log(Level.SEVERE, null, e); - } + /** + * Handles all the connecting clients + * + * @author Ziver + */ + class UpdateServerThread implements ThreadedTCPNetworkServerThread{ + private ObjectOutputStream out; + private ObjectInputStream in; + private Socket socket; - } + /** + * Creates a UpdateServerThread + * + * @param c is the socket to the client + */ + public UpdateServerThread(Socket c){ + socket = c; + try { + out = new ObjectOutputStream( socket.getOutputStream()); + in = new ObjectInputStream ( socket.getInputStream() ); + } catch (IOException e) { + logger.log(Level.SEVERE, null, e); + } - public void run(){ - try { - logger.info("Client["+socket.getInetAddress()+"] connectiong..."); - // receive the clients file list - FileListMessage clientFileList = (FileListMessage)in.readObject(); - MultiPrintStream.out.dump(clientFileList); - FileListMessage diff = fileList.getDiff( clientFileList ); - MultiPrintStream.out.dump(diff); - out.writeObject( diff ); + } - logger.info("Updating client["+socket.getInetAddress()+"]..."); - for(FileInfo info : diff.getFileList()){ - // send file data - FileInputStream input = new FileInputStream( info.getFile() ); - byte[] nextBytes = new byte[ socket.getSendBufferSize() ]; - int bytesRead = 0; - while((bytesRead = input.read(nextBytes)) > 0){ - out.write(nextBytes,0,bytesRead); - } - out.flush(); - input.close(); - } - - out.flush(); - socket.close(); - logger.info("Client["+socket.getInetAddress()+"] update done."); - } catch (Exception e) { - logger.log(Level.SEVERE, "Update error Client["+socket.getInetAddress()+"].", e); - } finally { - logger.info("Client["+socket.getInetAddress()+"] disconnected."); - } - } - } + public void run(){ + try { + logger.info("Client["+socket.getInetAddress()+"] connectiong..."); + // receive the clients file list + FileListMessage clientFileList = (FileListMessage)in.readObject(); + MultiPrintStream.out.dump(clientFileList); + FileListMessage diff = fileList.getDiff( clientFileList ); + MultiPrintStream.out.dump(diff); + out.writeObject( diff ); + + logger.info("Updating client["+socket.getInetAddress()+"]..."); + for(FileInfo info : diff.getFileList()){ + // send file data + FileInputStream input = new FileInputStream( info.getFile() ); + byte[] nextBytes = new byte[ socket.getSendBufferSize() ]; + int bytesRead = 0; + while((bytesRead = input.read(nextBytes)) > 0){ + out.write(nextBytes,0,bytesRead); + } + out.flush(); + input.close(); + } + + out.flush(); + socket.close(); + logger.info("Client["+socket.getInetAddress()+"] update done."); + } catch (Exception e) { + logger.log(Level.SEVERE, "Update error Client["+socket.getInetAddress()+"].", e); + } finally { + logger.info("Client["+socket.getInetAddress()+"] disconnected."); + } + } + } } diff --git a/src/zutil/net/update/Zupdater.java b/src/zutil/net/update/Zupdater.java index 574dc6f..043e257 100644 --- a/src/zutil/net/update/Zupdater.java +++ b/src/zutil/net/update/Zupdater.java @@ -38,110 +38,110 @@ import java.awt.event.ActionListener; public class Zupdater extends JFrame implements ProgressListener{ - private static final long serialVersionUID = 1L; - - private JPanel contentPane; - private JLabel lblSpeed; - private JLabel lblFile; - private JProgressBar progressBar; + private static final long serialVersionUID = 1L; - /** - * Launch the application. - */ - public static void main(String[] args) { - EventQueue.invokeLater(new Runnable() { - public void run() { - try { - Zupdater frame = new Zupdater(); - frame.setVisible(true); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } + private JPanel contentPane; + private JLabel lblSpeed; + private JLabel lblFile; + private JProgressBar progressBar; - - public void progressUpdate(UpdateClient source, FileInfo info, double percent) { - lblFile.setText( info.getPath() ); - progressBar.setValue( (int)percent ); - progressBar.setString( StringUtil.formatByteSizeToString(source.getTotalReceived()) + - " / "+StringUtil.formatByteSizeToString(source.getTotalSize())); - - lblSpeed.setText( StringUtil.formatByteSizeToString(((UpdateClient) source).getSpeed())+"/s" ); - } - - - /** - * Create the frame. - */ - public Zupdater() { - setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - setAlwaysOnTop(true); - setResizable(false); - setTitle("Updating..."); - setBounds(100, 100, 537, 124); - contentPane = new JPanel(); - contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); - setContentPane(contentPane); - - progressBar = new JProgressBar(); - progressBar.setString("2.5 MB / 5 MB"); - progressBar.setValue(50); - progressBar.setStringPainted(true); - progressBar.setToolTipText(""); - - lblFile = new JLabel("apa.zip"); - - lblSpeed = new JLabel("200 kb/s"); - lblSpeed.setHorizontalAlignment(SwingConstants.RIGHT); - - JSeparator separator = new JSeparator(); - - JButton btnCancel = new JButton("Cancel"); - btnCancel.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - System.exit(0); - } - }); - - JLabel lblFile_1 = new JLabel("File:"); - GroupLayout gl_contentPane = new GroupLayout(contentPane); - gl_contentPane.setHorizontalGroup( - gl_contentPane.createParallelGroup(Alignment.TRAILING) - .addGroup(gl_contentPane.createSequentialGroup() - .addGap(10) - .addComponent(progressBar, GroupLayout.DEFAULT_SIZE, 501, Short.MAX_VALUE) - .addGap(10)) - .addComponent(separator, GroupLayout.DEFAULT_SIZE, 521, Short.MAX_VALUE) - .addGroup(gl_contentPane.createSequentialGroup() - .addContainerGap() - .addComponent(lblFile_1) - .addPreferredGap(ComponentPlacement.RELATED) - .addComponent(lblFile, GroupLayout.PREFERRED_SIZE, 331, GroupLayout.PREFERRED_SIZE) - .addGap(60) - .addComponent(lblSpeed, GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE) - .addContainerGap()) - .addGroup(gl_contentPane.createSequentialGroup() - .addContainerGap() - .addComponent(btnCancel)) - ); - gl_contentPane.setVerticalGroup( - gl_contentPane.createParallelGroup(Alignment.LEADING) - .addGroup(gl_contentPane.createSequentialGroup() - .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) - .addComponent(lblSpeed) - .addComponent(lblFile) - .addComponent(lblFile_1)) - .addPreferredGap(ComponentPlacement.RELATED) - .addComponent(progressBar, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE) - .addPreferredGap(ComponentPlacement.RELATED) - .addComponent(separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) - .addPreferredGap(ComponentPlacement.RELATED) - .addComponent(btnCancel) - .addContainerGap(14, Short.MAX_VALUE)) - ); - contentPane.setLayout(gl_contentPane); - } + /** + * Launch the application. + */ + public static void main(String[] args) { + EventQueue.invokeLater(new Runnable() { + public void run() { + try { + Zupdater frame = new Zupdater(); + frame.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + + + public void progressUpdate(UpdateClient source, FileInfo info, double percent) { + lblFile.setText( info.getPath() ); + progressBar.setValue( (int)percent ); + progressBar.setString( StringUtil.formatByteSizeToString(source.getTotalReceived()) + + " / "+StringUtil.formatByteSizeToString(source.getTotalSize())); + + lblSpeed.setText( StringUtil.formatByteSizeToString(((UpdateClient) source).getSpeed())+"/s" ); + } + + + /** + * Create the frame. + */ + public Zupdater() { + setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setAlwaysOnTop(true); + setResizable(false); + setTitle("Updating..."); + setBounds(100, 100, 537, 124); + contentPane = new JPanel(); + contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); + setContentPane(contentPane); + + progressBar = new JProgressBar(); + progressBar.setString("2.5 MB / 5 MB"); + progressBar.setValue(50); + progressBar.setStringPainted(true); + progressBar.setToolTipText(""); + + lblFile = new JLabel("apa.zip"); + + lblSpeed = new JLabel("200 kb/s"); + lblSpeed.setHorizontalAlignment(SwingConstants.RIGHT); + + JSeparator separator = new JSeparator(); + + JButton btnCancel = new JButton("Cancel"); + btnCancel.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + System.exit(0); + } + }); + + JLabel lblFile_1 = new JLabel("File:"); + GroupLayout gl_contentPane = new GroupLayout(contentPane); + gl_contentPane.setHorizontalGroup( + gl_contentPane.createParallelGroup(Alignment.TRAILING) + .addGroup(gl_contentPane.createSequentialGroup() + .addGap(10) + .addComponent(progressBar, GroupLayout.DEFAULT_SIZE, 501, Short.MAX_VALUE) + .addGap(10)) + .addComponent(separator, GroupLayout.DEFAULT_SIZE, 521, Short.MAX_VALUE) + .addGroup(gl_contentPane.createSequentialGroup() + .addContainerGap() + .addComponent(lblFile_1) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(lblFile, GroupLayout.PREFERRED_SIZE, 331, GroupLayout.PREFERRED_SIZE) + .addGap(60) + .addComponent(lblSpeed, GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE) + .addContainerGap()) + .addGroup(gl_contentPane.createSequentialGroup() + .addContainerGap() + .addComponent(btnCancel)) + ); + gl_contentPane.setVerticalGroup( + gl_contentPane.createParallelGroup(Alignment.LEADING) + .addGroup(gl_contentPane.createSequentialGroup() + .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) + .addComponent(lblSpeed) + .addComponent(lblFile) + .addComponent(lblFile_1)) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(progressBar, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) + .addPreferredGap(ComponentPlacement.RELATED) + .addComponent(btnCancel) + .addContainerGap(14, Short.MAX_VALUE)) + ); + contentPane.setLayout(gl_contentPane); + } } diff --git a/src/zutil/net/upnp/UPnPMediaServer.java b/src/zutil/net/upnp/UPnPMediaServer.java index 02be448..a79b0e6 100755 --- a/src/zutil/net/upnp/UPnPMediaServer.java +++ b/src/zutil/net/upnp/UPnPMediaServer.java @@ -38,80 +38,80 @@ import java.util.UUID; * @author Ziver */ public class UPnPMediaServer extends UPnPRootDevice{ - public static final String RELATIVE_URL = "upnp/rootdev"; - - private String url; - private String uuid; - - public UPnPMediaServer(String location){ - url = location; - } + public static final String RELATIVE_URL = "upnp/rootdev"; - public void respond(HttpPrintStream out, + private String url; + private String uuid; + + public UPnPMediaServer(String location){ + url = location; + } + + public void respond(HttpPrintStream out, HttpHeader headers, Map session, Map cookie, Map request) throws IOException { - out.enableBuffering(true); - out.setHeader("Content-Type", "text/xml"); - - out.println(""); - out.println(""); - out.println(" "); - out.println(" 1"); - out.println(" 0"); - out.println(" "); - out.println(" "+url+"");//"+ssdp.getLocation()+" - out.println(" "); - out.println(" urn:schemas-upnp-org:device:MediaServer:1"); - out.println(" ZupNP AV Media Server"); - out.println(" Ziver Koc"); - out.println(" http://ziver.koc.se"); - out.println(""); - out.println(" ZupNP Server"); - out.println(" UPnP AV Media Server"); - out.println(" 0.1"); - out.println(" "+getUUID()+""); - out.println(" "); - out.println(" "); - out.println(" urn:schemas-upnp-org:service:ConnectionManager:1"); - out.println(" urn:upnp-org:serviceId:CMGR_1-0"); - out.println(" CMGR_Control/GetServDesc"); - out.println(" CMGR_Control"); - out.println(" CMGR_Event"); - out.println(" "); - out.println(" "); - out.println(" urn:schemas-upnp-org:service:ContentDirectory:1"); - out.println(" urn:upnp-org:serviceId:CDS_1-0"); - out.println(" SCP/ContentDir"); - out.println(" Action/ContentDir"); - out.println(" Event/ContentDir"); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(""); - out.flush(); - } + out.enableBuffering(true); + out.setHeader("Content-Type", "text/xml"); - - public long getExpirationTime() { - return 60*30; // 30min - } - public String getLocation() { - return url+"RootDesc"; - } - public String getSearchTarget() { - return "upnp:rootdevice"; - } - public String getUSN() { - return getUUID()+"::upnp:rootdevice"; - } - public String getUUID() { - if(uuid==null){ - uuid = "uuid:"+UUID.nameUUIDFromBytes( this.getClass().toString().getBytes() ); //(url+Math.random()).getBytes() - } - return uuid; - } + out.println(""); + out.println(""); + out.println(" "); + out.println(" 1"); + out.println(" 0"); + out.println(" "); + out.println(" "+url+"");//"+ssdp.getLocation()+" + out.println(" "); + out.println(" urn:schemas-upnp-org:device:MediaServer:1"); + out.println(" ZupNP AV Media Server"); + out.println(" Ziver Koc"); + out.println(" http://ziver.koc.se"); + out.println(""); + out.println(" ZupNP Server"); + out.println(" UPnP AV Media Server"); + out.println(" 0.1"); + out.println(" "+getUUID()+""); + out.println(" "); + out.println(" "); + out.println(" urn:schemas-upnp-org:service:ConnectionManager:1"); + out.println(" urn:upnp-org:serviceId:CMGR_1-0"); + out.println(" CMGR_Control/GetServDesc"); + out.println(" CMGR_Control"); + out.println(" CMGR_Event"); + out.println(" "); + out.println(" "); + out.println(" urn:schemas-upnp-org:service:ContentDirectory:1"); + out.println(" urn:upnp-org:serviceId:CDS_1-0"); + out.println(" SCP/ContentDir"); + out.println(" Action/ContentDir"); + out.println(" Event/ContentDir"); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(""); + out.flush(); + } + + + public long getExpirationTime() { + return 60*30; // 30min + } + public String getLocation() { + return url+"RootDesc"; + } + public String getSearchTarget() { + return "upnp:rootdevice"; + } + public String getUSN() { + return getUUID()+"::upnp:rootdevice"; + } + public String getUUID() { + if(uuid==null){ + uuid = "uuid:"+UUID.nameUUIDFromBytes( this.getClass().toString().getBytes() ); //(url+Math.random()).getBytes() + } + return uuid; + } } diff --git a/src/zutil/net/upnp/service/BrowseRetObj.java b/src/zutil/net/upnp/service/BrowseRetObj.java index e87a022..e2124e1 100755 --- a/src/zutil/net/upnp/service/BrowseRetObj.java +++ b/src/zutil/net/upnp/service/BrowseRetObj.java @@ -28,12 +28,12 @@ import zutil.net.ws.WSReturnObject; public class BrowseRetObj extends WSReturnObject{ - @WSValueName("Result") - public String Result; - @WSValueName("NumberReturned") - public int NumberReturned; - @WSValueName("TotalMatches") - public int TotalMatches; - @WSValueName("UpdateID") - public int UpdateID; - } + @WSValueName("Result") + public String Result; + @WSValueName("NumberReturned") + public int NumberReturned; + @WSValueName("TotalMatches") + public int TotalMatches; + @WSValueName("UpdateID") + public int UpdateID; +} diff --git a/src/zutil/net/upnp/service/UPnPContentDirectory.java b/src/zutil/net/upnp/service/UPnPContentDirectory.java index 8b9f506..113f215 100755 --- a/src/zutil/net/upnp/service/UPnPContentDirectory.java +++ b/src/zutil/net/upnp/service/UPnPContentDirectory.java @@ -41,576 +41,576 @@ import java.util.Map; /** * Information about a UPNP Service - * + * * @author Ziver */ public class UPnPContentDirectory implements UPnPService, HttpPage, WSInterface { - public static final int VERSION = 1; + public static final int VERSION = 1; - private static List file_list; + private static List file_list; - public UPnPContentDirectory(){} - - public UPnPContentDirectory(File dir){ - file_list = FileUtil.search(dir, new LinkedList(), true, Integer.MAX_VALUE); - } + public UPnPContentDirectory(){} - /** - * This action returns the searching capabilities - * that are supported by the device. - * - */ - @WSReturnName("SortCaps") - public String GetSearchCapabilities(){ - // "dc:title,res@size" - return ""; - } + public UPnPContentDirectory(File dir){ + file_list = FileUtil.search(dir, new LinkedList(), true, Integer.MAX_VALUE); + } - /** - * Returns the CSV list of meta-data tags that can - * be used in sortCriteria - * - */ - @WSReturnName("SortCaps") - public String GetSortCapabilities(){ - return "dc:title"; - } + /** + * This action returns the searching capabilities + * that are supported by the device. + * + */ + @WSReturnName("SortCaps") + public String GetSearchCapabilities(){ + // "dc:title,res@size" + return ""; + } - /** - * This action returns the current value of state variable - * SystemUpdateID. It can be used by clients that want to - * 'poll' for any changes in the Content Directory - * (as opposed to subscribing to events). - * - */ - @WSReturnName("Id") - public int GetSystemUpdateID(){ - return 0; - } + /** + * Returns the CSV list of meta-data tags that can + * be used in sortCriteria + * + */ + @WSReturnName("SortCaps") + public String GetSortCapabilities(){ + return "dc:title"; + } - /** - * This action allows the caller to incrementally browse - * the native hierarchy of the Content Directory objects - * 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") - public BrowseRetObj Browse( - @WSParamName("ObjectID") String ObjectID, - @WSParamName("BrowseFlag") String BrowseFlag, - @WSParamName("Filter") String Filter, - @WSParamName("StartingIndex") int StartingIndex, - @WSParamName("RequestedCount") int RequestedCount, - @WSParamName("SortCriteria") String SortCriteria) throws DocumentException{ + /** + * This action returns the current value of state variable + * SystemUpdateID. It can be used by clients that want to + * 'poll' for any changes in the Content Directory + * (as opposed to subscribing to events). + * + */ + @WSReturnName("Id") + public int GetSystemUpdateID(){ + return 0; + } - BrowseRetObj ret = new BrowseRetObj(); - if( BrowseFlag.equals("BrowseMetadata") ){ + /** + * This action allows the caller to incrementally browse + * the native hierarchy of the Content Directory objects + * 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") + public BrowseRetObj Browse( + @WSParamName("ObjectID") String ObjectID, + @WSParamName("BrowseFlag") String BrowseFlag, + @WSParamName("Filter") String Filter, + @WSParamName("StartingIndex") int StartingIndex, + @WSParamName("RequestedCount") int RequestedCount, + @WSParamName("SortCriteria") String SortCriteria) throws DocumentException{ - } - else if( BrowseFlag.equals("BrowseDirectChildren") ){ - StringBuffer xml = new StringBuffer(); - xml.append( "" ); - List tmp = FileUtil.search( file_list.get(Integer.parseInt(ObjectID)), new LinkedList(), false ); - for(File file : tmp){ - xml.append(" "); - - xml.append(" "+file.getName()+" "); - if( file.isDirectory() ) - xml.append(" object.container.storageFolder "); - else - xml.append(" object.container "); - xml.append(" "+(int)(file.length()/1000)+" "); - xml.append(" "); - - ret.NumberReturned++; - ret.TotalMatches++; - } - xml.append( "" ); - - ret.Result = xml.toString(); - //Document document = DocumentHelper.parseText( xml.toString() ); - //ret.Result = document.getRootElement(); - } - return ret; - } - public class BrowseRetObj extends WSReturnObject{ - @WSValueName("Result") - public String Result; - @WSValueName("NumberReturned") - public int NumberReturned; - @WSValueName("TotalMatches") - public int TotalMatches; - @WSValueName("UpdateID") - public int UpdateID; - } - + BrowseRetObj ret = new BrowseRetObj(); + if( BrowseFlag.equals("BrowseMetadata") ){ - @WSIgnore - public void respond(HttpPrintStream out, HttpHeader headers, + } + else if( BrowseFlag.equals("BrowseDirectChildren") ){ + StringBuffer xml = new StringBuffer(); + xml.append( "" ); + List tmp = FileUtil.search( file_list.get(Integer.parseInt(ObjectID)), new LinkedList(), false ); + for(File file : tmp){ + xml.append(" "); + + xml.append(" "+file.getName()+" "); + if( file.isDirectory() ) + xml.append(" object.container.storageFolder "); + else + xml.append(" object.container "); + xml.append(" "+(int)(file.length()/1000)+" "); + xml.append(" "); + + ret.NumberReturned++; + ret.TotalMatches++; + } + xml.append( "" ); + + ret.Result = xml.toString(); + //Document document = DocumentHelper.parseText( xml.toString() ); + //ret.Result = document.getRootElement(); + } + return ret; + } + public class BrowseRetObj extends WSReturnObject{ + @WSValueName("Result") + public String Result; + @WSValueName("NumberReturned") + public int NumberReturned; + @WSValueName("TotalMatches") + public int TotalMatches; + @WSValueName("UpdateID") + public int UpdateID; + } + + + @WSIgnore + public void respond(HttpPrintStream out, HttpHeader headers, Map session, Map cookie, Map request) throws IOException { - out.enableBuffering(true); - out.setHeader("Content-Type", "text/xml"); + out.enableBuffering(true); + out.setHeader("Content-Type", "text/xml"); - out.println(""); - out.println(""); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" TransferIDs"); - out.println(" yes"); - out.println(" string"); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_ObjectID"); - out.println(" no"); - out.println(" string"); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_Result"); - out.println(" no"); - out.println(" string"); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_SearchCriteria"); - out.println(" no"); - out.println(" string"); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_BrowseFlag"); - out.println(" no"); - out.println(" string"); - out.println(" "); - out.println(" BrowseMetadata"); - out.println(" BrowseDirectChildren"); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_Filter"); - out.println(" no"); - out.println(" string"); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_SortCriteria"); - out.println(" no"); - out.println(" string"); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_Index"); - out.println(" no"); - out.println(" ui4"); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_Count"); - out.println(" no"); - out.println(" ui4"); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_UpdateID"); - out.println(" no"); - out.println(" ui4"); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_TransferID"); - out.println(" no"); - out.println(" ui4"); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_TransferStatus"); - out.println(" no"); - out.println(" string"); - out.println(" "); - out.println(" COMPLETED"); - out.println(" ERROR"); - out.println(" IN_PROGRESS"); - out.println(" STOPPED"); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_TransferLength"); - out.println(" no"); - out.println(" string"); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_TransferTotal"); - out.println(" no"); - out.println(" string"); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_TagValueList"); - out.println(" no"); - out.println(" string"); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" A_ARG_TYPE_URI"); - out.println(" no"); - out.println(" uri"); - out.println(" "); - out.println(" "); - out.println(" SearchCapabilities"); - out.println(" no"); - out.println(" string"); - out.println(" "); - out.println(" "); - out.println(" SortCapabilities"); - out.println(" no"); - out.println(" string"); - out.println(" "); - out.println(" "); - out.println(" SystemUpdateID"); - out.println(" yes"); - out.println(" ui4"); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" ContainerUpdateIDs"); - out.println(" yes"); - out.println(" string"); - out.println(" "); - out.println(" "); + out.println(""); + out.println(""); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" TransferIDs"); + out.println(" yes"); + out.println(" string"); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_ObjectID"); + out.println(" no"); + out.println(" string"); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_Result"); + out.println(" no"); + out.println(" string"); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_SearchCriteria"); + out.println(" no"); + out.println(" string"); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_BrowseFlag"); + out.println(" no"); + out.println(" string"); + out.println(" "); + out.println(" BrowseMetadata"); + out.println(" BrowseDirectChildren"); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_Filter"); + out.println(" no"); + out.println(" string"); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_SortCriteria"); + out.println(" no"); + out.println(" string"); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_Index"); + out.println(" no"); + out.println(" ui4"); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_Count"); + out.println(" no"); + out.println(" ui4"); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_UpdateID"); + out.println(" no"); + out.println(" ui4"); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_TransferID"); + out.println(" no"); + out.println(" ui4"); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_TransferStatus"); + out.println(" no"); + out.println(" string"); + out.println(" "); + out.println(" COMPLETED"); + out.println(" ERROR"); + out.println(" IN_PROGRESS"); + out.println(" STOPPED"); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_TransferLength"); + out.println(" no"); + out.println(" string"); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_TransferTotal"); + out.println(" no"); + out.println(" string"); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_TagValueList"); + out.println(" no"); + out.println(" string"); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" A_ARG_TYPE_URI"); + out.println(" no"); + out.println(" uri"); + out.println(" "); + out.println(" "); + out.println(" SearchCapabilities"); + out.println(" no"); + out.println(" string"); + out.println(" "); + out.println(" "); + out.println(" SortCapabilities"); + out.println(" no"); + out.println(" string"); + out.println(" "); + out.println(" "); + out.println(" SystemUpdateID"); + out.println(" yes"); + out.println(" ui4"); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" ContainerUpdateIDs"); + out.println(" yes"); + out.println(" string"); + out.println(" "); + out.println(" "); - out.println(" "); - out.println(" "); - out.println(" GetSearchCapabilities"); - out.println(" "); - out.println(" "); - out.println(" SearchCaps"); - out.println(" out"); - out.println(" SearchCapabilities"); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" GetSortCapabilities"); - out.println(" "); - out.println(" "); - out.println(" SortCaps"); - out.println(" out"); - out.println(" SortCapabilities"); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" "); - out.println(" GetSystemUpdateID"); - out.println(" "); - out.println(" "); - out.println(" Id"); - out.println(" out"); - out.println(" SystemUpdateID"); - out.println(" "); - out.println(" "); - out.println(" "); + out.println(" "); + out.println(" "); + out.println(" GetSearchCapabilities"); + out.println(" "); + out.println(" "); + out.println(" SearchCaps"); + out.println(" out"); + out.println(" SearchCapabilities"); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" GetSortCapabilities"); + out.println(" "); + out.println(" "); + out.println(" SortCaps"); + out.println(" out"); + out.println(" SortCapabilities"); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" GetSystemUpdateID"); + out.println(" "); + out.println(" "); + out.println(" Id"); + out.println(" out"); + out.println(" SystemUpdateID"); + out.println(" "); + out.println(" "); + out.println(" "); - out.println(" "); - out.println(" Browse"); - out.println(" "); - out.println(" "); - out.println(" ObjectID"); - out.println(" in"); - out.println(" A_ARG_TYPE_ObjectID"); - out.println(" "); - out.println(" "); - out.println(" BrowseFlag"); - out.println(" in"); - out.println(" A_ARG_TYPE_BrowseFlag"); - out.println(" "); - out.println(" "); - out.println(" Filter"); - out.println(" in"); - out.println(" A_ARG_TYPE_Filter"); - out.println(" "); - out.println(" "); - out.println(" StartingIndex"); - out.println(" in"); - out.println(" A_ARG_TYPE_Index"); - out.println(" "); - out.println(" "); - out.println(" RequestedCount"); - out.println(" in"); - out.println(" A_ARG_TYPE_Count"); - out.println(" "); - out.println(" "); - out.println(" SortCriteria"); - out.println(" in"); - out.println(" A_ARG_TYPE_SortCriteria"); - out.println(" "); - out.println(" "); - out.println(" Result"); - out.println(" out"); - out.println(" A_ARG_TYPE_Result"); - out.println(" "); - out.println(" "); - out.println(" NumberReturned"); - out.println(" out"); - out.println(" A_ARG_TYPE_Count"); - out.println(" "); - out.println(" "); - out.println(" TotalMatches"); - out.println(" out"); - out.println(" A_ARG_TYPE_Count"); - out.println(" "); - out.println(" "); - out.println(" UpdateID"); - out.println(" out"); - out.println(" A_ARG_TYPE_UpdateID"); - out.println(" "); - out.println(" "); - out.println(" "); + out.println(" "); + out.println(" Browse"); + out.println(" "); + out.println(" "); + out.println(" ObjectID"); + out.println(" in"); + out.println(" A_ARG_TYPE_ObjectID"); + out.println(" "); + out.println(" "); + out.println(" BrowseFlag"); + out.println(" in"); + out.println(" A_ARG_TYPE_BrowseFlag"); + out.println(" "); + out.println(" "); + out.println(" Filter"); + out.println(" in"); + out.println(" A_ARG_TYPE_Filter"); + out.println(" "); + out.println(" "); + out.println(" StartingIndex"); + out.println(" in"); + out.println(" A_ARG_TYPE_Index"); + out.println(" "); + out.println(" "); + out.println(" RequestedCount"); + out.println(" in"); + out.println(" A_ARG_TYPE_Count"); + out.println(" "); + out.println(" "); + out.println(" SortCriteria"); + out.println(" in"); + out.println(" A_ARG_TYPE_SortCriteria"); + out.println(" "); + out.println(" "); + out.println(" Result"); + out.println(" out"); + out.println(" A_ARG_TYPE_Result"); + out.println(" "); + out.println(" "); + out.println(" NumberReturned"); + out.println(" out"); + out.println(" A_ARG_TYPE_Count"); + out.println(" "); + out.println(" "); + out.println(" TotalMatches"); + out.println(" out"); + out.println(" A_ARG_TYPE_Count"); + out.println(" "); + out.println(" "); + out.println(" UpdateID"); + out.println(" out"); + out.println(" A_ARG_TYPE_UpdateID"); + out.println(" "); + out.println(" "); + out.println(" "); - /*out.println(" "); - out.println(" "); - out.println(" Search"); - out.println(" "); - out.println(" "); - out.println(" ContainerID"); - out.println(" in"); - out.println(" A_ARG_TYPE_ObjectID"); - out.println(" "); - out.println(" "); - out.println(" SearchCriteria"); - out.println(" in"); - out.println(" A_ARG_TYPE_SearchCriteria "); - out.println(" "); - out.println(" "); - out.println(" Filter"); - out.println(" in"); - out.println(" A_ARG_TYPE_Filter"); - out.println(" "); - out.println(" "); - out.println(" StartingIndex"); - out.println(" in"); - out.println(" A_ARG_TYPE_Index"); - out.println(" "); - out.println(" "); - out.println(" RequestedCount"); - out.println(" in"); - out.println(" A_ARG_TYPE_Count"); - out.println(" "); - out.println(" "); - out.println(" SortCriteria"); - out.println(" in"); - out.println(" A_ARG_TYPE_SortCriteria"); - out.println(" "); - out.println(" "); - out.println(" Result"); - out.println(" out"); - out.println(" A_ARG_TYPE_Result"); - out.println(" "); - out.println(" "); - out.println(" NumberReturned"); - out.println(" out"); - out.println(" A_ARG_TYPE_Count"); - out.println(" "); - out.println(" "); - out.println(" TotalMatches"); - out.println(" out"); - out.println(" A_ARG_TYPE_Count"); - out.println(" "); - out.println(" "); - out.println(" UpdateID"); - out.println(" out"); - out.println(" A_ARG_TYPE_UpdateID"); - out.println(" "); - out.println(" "); - out.println(" ");*/ + /*out.println(" "); + out.println(" "); + out.println(" Search"); + out.println(" "); + out.println(" "); + out.println(" ContainerID"); + out.println(" in"); + out.println(" A_ARG_TYPE_ObjectID"); + out.println(" "); + out.println(" "); + out.println(" SearchCriteria"); + out.println(" in"); + out.println(" A_ARG_TYPE_SearchCriteria "); + out.println(" "); + out.println(" "); + out.println(" Filter"); + out.println(" in"); + out.println(" A_ARG_TYPE_Filter"); + out.println(" "); + out.println(" "); + out.println(" StartingIndex"); + out.println(" in"); + out.println(" A_ARG_TYPE_Index"); + out.println(" "); + out.println(" "); + out.println(" RequestedCount"); + out.println(" in"); + out.println(" A_ARG_TYPE_Count"); + out.println(" "); + out.println(" "); + out.println(" SortCriteria"); + out.println(" in"); + out.println(" A_ARG_TYPE_SortCriteria"); + out.println(" "); + out.println(" "); + out.println(" Result"); + out.println(" out"); + out.println(" A_ARG_TYPE_Result"); + out.println(" "); + out.println(" "); + out.println(" NumberReturned"); + out.println(" out"); + out.println(" A_ARG_TYPE_Count"); + out.println(" "); + out.println(" "); + out.println(" TotalMatches"); + out.println(" out"); + out.println(" A_ARG_TYPE_Count"); + out.println(" "); + out.println(" "); + out.println(" UpdateID"); + out.println(" out"); + out.println(" A_ARG_TYPE_UpdateID"); + out.println(" "); + out.println(" "); + out.println(" ");*/ - /*out.println(" "); - out.println(" "); - out.println(" CreateObject"); - out.println(" "); - out.println(" "); - out.println(" ContainerID"); - out.println(" in"); - out.println(" A_ARG_TYPE_ObjectID"); - out.println(" "); - out.println(" "); - out.println(" Elements"); - out.println(" in"); - out.println(" A_ARG_TYPE_Result"); - out.println(" "); - out.println(" "); - out.println(" ObjectID"); - out.println(" out"); - out.println(" A_ARG_TYPE_ObjectID"); - out.println(" "); - out.println(" "); - out.println(" Result"); - out.println(" out"); - out.println(" A_ARG_TYPE_Result"); - out.println(" "); - out.println(" "); - out.println(" ");*/ + /*out.println(" "); + out.println(" "); + out.println(" CreateObject"); + out.println(" "); + out.println(" "); + out.println(" ContainerID"); + out.println(" in"); + out.println(" A_ARG_TYPE_ObjectID"); + out.println(" "); + out.println(" "); + out.println(" Elements"); + out.println(" in"); + out.println(" A_ARG_TYPE_Result"); + out.println(" "); + out.println(" "); + out.println(" ObjectID"); + out.println(" out"); + out.println(" A_ARG_TYPE_ObjectID"); + out.println(" "); + out.println(" "); + out.println(" Result"); + out.println(" out"); + out.println(" A_ARG_TYPE_Result"); + out.println(" "); + out.println(" "); + out.println(" ");*/ - /*out.println(" "); - out.println(" "); - out.println(" DestroyObject"); - out.println(" "); - out.println(" "); - out.println(" ObjectID"); - out.println(" in"); - out.println(" A_ARG_TYPE_ObjectID"); - out.println(" "); - out.println(" "); - out.println(" ");*/ + /*out.println(" "); + out.println(" "); + out.println(" DestroyObject"); + out.println(" "); + out.println(" "); + out.println(" ObjectID"); + out.println(" in"); + out.println(" A_ARG_TYPE_ObjectID"); + out.println(" "); + out.println(" "); + out.println(" ");*/ - /*out.println(" "); - out.println(" "); - out.println(" UpdateObject"); - out.println(" "); - out.println(" "); - out.println(" ObjectID"); - out.println(" in"); - out.println(" A_ARG_TYPE_ObjectID"); - out.println(" "); - out.println(" "); - out.println(" CurrentTagValue"); - out.println(" in"); - out.println(" A_ARG_TYPE_TagValueList "); - out.println(" "); - out.println(" "); - out.println(" NewTagValue"); - out.println(" in"); - out.println(" A_ARG_TYPE_TagValueList "); - out.println(" "); - out.println(" "); - out.println(" ");*/ + /*out.println(" "); + out.println(" "); + out.println(" UpdateObject"); + out.println(" "); + out.println(" "); + out.println(" ObjectID"); + out.println(" in"); + out.println(" A_ARG_TYPE_ObjectID"); + out.println(" "); + out.println(" "); + out.println(" CurrentTagValue"); + out.println(" in"); + out.println(" A_ARG_TYPE_TagValueList "); + out.println(" "); + out.println(" "); + out.println(" NewTagValue"); + out.println(" in"); + out.println(" A_ARG_TYPE_TagValueList "); + out.println(" "); + out.println(" "); + out.println(" ");*/ - /*out.println(" "); - out.println(" "); - out.println(" ImportResource"); - out.println(" "); - out.println(" "); - out.println(" SourceURI"); - out.println(" in"); - out.println(" A_ARG_TYPE_URI"); - out.println(" "); - out.println(" "); - out.println(" DestinationURI"); - out.println(" in"); - out.println(" A_ARG_TYPE_URI"); - out.println(" "); - out.println(" "); - out.println(" TransferID"); - out.println(" out"); - out.println(" A_ARG_TYPE_TransferID "); - out.println(" "); - out.println(" "); - out.println(" ");*/ + /*out.println(" "); + out.println(" "); + out.println(" ImportResource"); + out.println(" "); + out.println(" "); + out.println(" SourceURI"); + out.println(" in"); + out.println(" A_ARG_TYPE_URI"); + out.println(" "); + out.println(" "); + out.println(" DestinationURI"); + out.println(" in"); + out.println(" A_ARG_TYPE_URI"); + out.println(" "); + out.println(" "); + out.println(" TransferID"); + out.println(" out"); + out.println(" A_ARG_TYPE_TransferID "); + out.println(" "); + out.println(" "); + out.println(" ");*/ - /*out.println(" "); - out.println(" "); - out.println(" ExportResource"); - out.println(" "); - out.println(" "); - out.println(" SourceURI"); - out.println(" in"); - out.println(" A_ARG_TYPE_URI"); - out.println(" "); - out.println(" "); - out.println(" DestinationURI"); - out.println(" in"); - out.println(" A_ARG_TYPE_URI"); - out.println(" "); - out.println(" "); - out.println(" TransferID"); - out.println(" out"); - out.println(" A_ARG_TYPE_TransferID "); - out.println(" "); - out.println(" "); - out.println(" ");*/ + /*out.println(" "); + out.println(" "); + out.println(" ExportResource"); + out.println(" "); + out.println(" "); + out.println(" SourceURI"); + out.println(" in"); + out.println(" A_ARG_TYPE_URI"); + out.println(" "); + out.println(" "); + out.println(" DestinationURI"); + out.println(" in"); + out.println(" A_ARG_TYPE_URI"); + out.println(" "); + out.println(" "); + out.println(" TransferID"); + out.println(" out"); + out.println(" A_ARG_TYPE_TransferID "); + out.println(" "); + out.println(" "); + out.println(" ");*/ - /*out.println(" "); - out.println(" "); - out.println(" StopTransferResource"); - out.println(" "); - out.println(" "); - out.println(" TransferID"); - out.println(" in"); - out.println(" A_ARG_TYPE_TransferID "); - out.println(" "); - out.println(" "); - out.println(" ");*/ + /*out.println(" "); + out.println(" "); + out.println(" StopTransferResource"); + out.println(" "); + out.println(" "); + out.println(" TransferID"); + out.println(" in"); + out.println(" A_ARG_TYPE_TransferID "); + out.println(" "); + out.println(" "); + out.println(" ");*/ - /*out.println(" "); - out.println(" "); - out.println(" GetTransferProgress"); - out.println(" "); - out.println(" "); - out.println(" TransferID"); - out.println(" in"); - out.println(" A_ARG_TYPE_TransferID "); - out.println(" "); - out.println(" "); - out.println(" TransferStatus"); - out.println(" out"); - out.println(" A_ARG_TYPE_TransferStatus "); - out.println(" "); - out.println(" "); - out.println(" TransferLength"); - out.println(" out"); - out.println(" A_ARG_TYPE_TransferLength "); - out.println(" "); - out.println(" "); - out.println(" TransferTotal"); - out.println(" out"); - out.println(" A_ARG_TYPE_TransferTotal"); - out.println(" "); - out.println(" "); - out.println(" ");*/ + /*out.println(" "); + out.println(" "); + out.println(" GetTransferProgress"); + out.println(" "); + out.println(" "); + out.println(" TransferID"); + out.println(" in"); + out.println(" A_ARG_TYPE_TransferID "); + out.println(" "); + out.println(" "); + out.println(" TransferStatus"); + out.println(" out"); + out.println(" A_ARG_TYPE_TransferStatus "); + out.println(" "); + out.println(" "); + out.println(" TransferLength"); + out.println(" out"); + out.println(" A_ARG_TYPE_TransferLength "); + out.println(" "); + out.println(" "); + out.println(" TransferTotal"); + out.println(" out"); + out.println(" A_ARG_TYPE_TransferTotal"); + out.println(" "); + out.println(" "); + out.println(" ");*/ - /*out.println(" "); - out.println(" "); - out.println(" DeleteResource"); - out.println(" "); - out.println(" "); - out.println(" ResourceURI"); - out.println(" in"); - out.println(" A_ARG_TYPE_URI"); - out.println(" "); - out.println(" "); - out.println(" ");*/ + /*out.println(" "); + out.println(" "); + out.println(" DeleteResource"); + out.println(" "); + out.println(" "); + out.println(" ResourceURI"); + out.println(" in"); + out.println(" A_ARG_TYPE_URI"); + out.println(" "); + out.println(" "); + out.println(" ");*/ - /*out.println(" "); - out.println(" "); - out.println(" CreateReference"); - out.println(" "); - out.println(" "); - out.println(" ContainerID"); - out.println(" in"); - out.println(" A_ARG_TYPE_ObjectID"); - out.println(" "); - out.println(" "); - out.println(" ObjectID"); - out.println(" in"); - out.println(" A_ARG_TYPE_ObjectID"); - out.println(" "); - out.println(" "); - out.println(" NewID"); - out.println(" out"); - out.println(" A_ARG_TYPE_ObjectID"); - out.println(" "); - out.println(" "); - out.println(" ");*/ + /*out.println(" "); + out.println(" "); + out.println(" CreateReference"); + out.println(" "); + out.println(" "); + out.println(" ContainerID"); + out.println(" in"); + out.println(" A_ARG_TYPE_ObjectID"); + out.println(" "); + out.println(" "); + out.println(" ObjectID"); + out.println(" in"); + out.println(" A_ARG_TYPE_ObjectID"); + out.println(" "); + out.println(" "); + out.println(" NewID"); + out.println(" out"); + out.println(" A_ARG_TYPE_ObjectID"); + out.println(" "); + out.println(" "); + out.println(" ");*/ - out.println(" "); - out.println(""); - } -} + out.println(" "); + out.println(""); + } +} diff --git a/src/zutil/net/ws/WSMethodDef.java b/src/zutil/net/ws/WSMethodDef.java index af22ee1..996b5d3 100755 --- a/src/zutil/net/ws/WSMethodDef.java +++ b/src/zutil/net/ws/WSMethodDef.java @@ -41,222 +41,222 @@ import java.util.List; */ // TODO: Header parameters public class WSMethodDef { - /** The parent web service definition **/ - private WebServiceDef wsDef; - /** A list of input parameters **/ - private ArrayList inputs; - /** A List of return parameters of the method **/ - private ArrayList outputs; - /** A List of exceptions that this method throws **/ - private ArrayList> exceptions; - /** The real method that this class represent, can be null if its a remote method **/ - private Method method; - /** Documentation of the method **/ - private String doc; - /** This is the namespace of the method **/ - private String namespace; - /** The published name of the method **/ - private String name; - + /** The parent web service definition **/ + private WebServiceDef wsDef; + /** A list of input parameters **/ + private ArrayList inputs; + /** A List of return parameters of the method **/ + private ArrayList outputs; + /** A List of exceptions that this method throws **/ + private ArrayList> exceptions; + /** The real method that this class represent, can be null if its a remote method **/ + private Method method; + /** Documentation of the method **/ + private String doc; + /** This is the namespace of the method **/ + private String namespace; + /** The published name of the method **/ + private String name; - /** - * - * @param me is a method in a class that implements WSInterface - */ - protected WSMethodDef( WebServiceDef wsDef, Method me) { - if( !WSInterface.class.isAssignableFrom(me.getDeclaringClass()) ) - throw new ClassCastException("Declaring class does not implement WSInterface!"); - this.wsDef = wsDef; - method = me; - inputs = new ArrayList(); - outputs = new ArrayList(); - exceptions = new ArrayList>(); - name = method.getName(); - //***** Documentation & Namespace - WSDocumentation tmpDoc = method.getAnnotation( WSDocumentation.class ); - if(tmpDoc != null){ - doc = tmpDoc.value(); - } - WSNamespace tmpSpace = method.getAnnotation( WSNamespace.class ); - if( tmpSpace != null ) - namespace = tmpSpace.value(); - else - namespace = wsDef.getNamespace()+"?#"+name; - - //***** Exceptions - for( Class exc : method.getExceptionTypes() ){ - exceptions.add( exc ); - } - - //********* Get the input parameter names ********** - Annotation[][] paramAnnotation = method.getParameterAnnotations(); - Class[] inputTypes = method.getParameterTypes(); - - for(int i=0; i(); + outputs = new ArrayList(); + exceptions = new ArrayList>(); + name = method.getName(); - inputs.add( param ); - } + //***** Documentation & Namespace + WSDocumentation tmpDoc = method.getAnnotation( WSDocumentation.class ); + if(tmpDoc != null){ + doc = tmpDoc.value(); + } + WSNamespace tmpSpace = method.getAnnotation( WSNamespace.class ); + if( tmpSpace != null ) + namespace = tmpSpace.value(); + else + namespace = wsDef.getNamespace()+"?#"+name; - //******** The return parameter name ************ - WSInterface.WSReturnName returnName = method.getAnnotation(WSInterface.WSReturnName.class); - if( WSReturnObject.class.isAssignableFrom( method.getReturnType() ) ){ - Class retClass = method.getReturnType(); - Field[] fields = retClass.getFields(); - - for(int i=0; i> getExceptions(){ - return exceptions; - } - - /** - * @return the number of parameters for this method - */ - public int getInputCount(){ - return inputs.size(); - } - - /** - * @return a list of input parameters - */ - public List getInputs(){ - return inputs; - } - - /** - * @param index is a index - * @return a {@link WSParameterDef} object in the given index - */ - public WSParameterDef getInput( int index ){ - return inputs.get( index ); - } - - /** - * @return the number of parameters for this method - */ - public int getOutputCount(){ - return outputs.size(); - } - - /** - * @return a list of input parameters - */ - public List getOutputs(){ - return outputs; - } - - /** - * @param index is a index - * @return a {@link WSParameterDef} object in the given index - */ - public WSParameterDef getOutput( int index ){ - return outputs.get( index ); - } - - /** - * @return Documentation of the method if one exists or else null - */ - public String getDocumentation(){ - return doc; - } - - /** - * @return the namespace of the method - */ - public String getNamespace(){ - return namespace; - } - - public WebServiceDef getWebService(){ - return wsDef; - } - - /** - * Invokes a specified method - * - * @param obj the object the method will called on - * @param params a vector with arguments - */ - public Object invoke(Object obj, Object[] params) throws Exception { - return this.method.invoke(obj, params ); - } - - - public String toString(){ - StringBuilder tmp = new StringBuilder(); - boolean first = true; - tmp.append(name).append("("); - for(WSParameterDef param : inputs){ - if(first) - first = false; - else - tmp.append(" ,"); - tmp.append(param.getParamClass().getSimpleName()); - tmp.append(" "); - tmp.append(param.getName()); - } - tmp.append(") => "); - first = true; - for(WSParameterDef param : outputs){ - if(first) - first = false; - else - tmp.append(" ,"); - tmp.append(param.getParamClass().getSimpleName()); - tmp.append(" "); - tmp.append(param.getName()); - } - return tmp.toString(); - } + //***** Exceptions + for( Class exc : method.getExceptionTypes() ){ + exceptions.add( exc ); + } + + //********* Get the input parameter names ********** + Annotation[][] paramAnnotation = method.getParameterAnnotations(); + Class[] inputTypes = method.getParameterTypes(); + + for(int i=0; i retClass = method.getReturnType(); + Field[] fields = retClass.getFields(); + + for(int i=0; i> getExceptions(){ + return exceptions; + } + + /** + * @return the number of parameters for this method + */ + public int getInputCount(){ + return inputs.size(); + } + + /** + * @return a list of input parameters + */ + public List getInputs(){ + return inputs; + } + + /** + * @param index is a index + * @return a {@link WSParameterDef} object in the given index + */ + public WSParameterDef getInput( int index ){ + return inputs.get( index ); + } + + /** + * @return the number of parameters for this method + */ + public int getOutputCount(){ + return outputs.size(); + } + + /** + * @return a list of input parameters + */ + public List getOutputs(){ + return outputs; + } + + /** + * @param index is a index + * @return a {@link WSParameterDef} object in the given index + */ + public WSParameterDef getOutput( int index ){ + return outputs.get( index ); + } + + /** + * @return Documentation of the method if one exists or else null + */ + public String getDocumentation(){ + return doc; + } + + /** + * @return the namespace of the method + */ + public String getNamespace(){ + return namespace; + } + + public WebServiceDef getWebService(){ + return wsDef; + } + + /** + * Invokes a specified method + * + * @param obj the object the method will called on + * @param params a vector with arguments + */ + public Object invoke(Object obj, Object[] params) throws Exception { + return this.method.invoke(obj, params ); + } + + + public String toString(){ + StringBuilder tmp = new StringBuilder(); + boolean first = true; + tmp.append(name).append("("); + for(WSParameterDef param : inputs){ + if(first) + first = false; + else + tmp.append(" ,"); + tmp.append(param.getParamClass().getSimpleName()); + tmp.append(" "); + tmp.append(param.getName()); + } + tmp.append(") => "); + first = true; + for(WSParameterDef param : outputs){ + if(first) + first = false; + else + tmp.append(" ,"); + tmp.append(param.getParamClass().getSimpleName()); + tmp.append(" "); + tmp.append(param.getName()); + } + return tmp.toString(); + } } diff --git a/src/zutil/net/ws/WSParameterDef.java b/src/zutil/net/ws/WSParameterDef.java index 6557b84..0ec38cc 100644 --- a/src/zutil/net/ws/WSParameterDef.java +++ b/src/zutil/net/ws/WSParameterDef.java @@ -30,54 +30,54 @@ package zutil.net.ws; * @author Ziver */ public class WSParameterDef{ - /** The parent method **/ - private WSMethodDef mDef; - /** The class type of the parameter **/ - private Class paramClass; - /** The web service name of the parameter **/ - private String name; - /** Developer documentation **/ - private String doc; - /** If this parameter is optional **/ - private boolean optional; - /** Is it an header parameter **/ - //boolean header; - - protected WSParameterDef( WSMethodDef mDef ){ - this.mDef = mDef; - this.optional = false; - } - - - public Class getParamClass() { - return paramClass; - } - protected void setParamClass(Class paramClass) { - this.paramClass = paramClass; - } - - public String getName() { - return name; - } - protected void setName(String name) { - this.name = name; - } - - public String getDoc() { - return doc; - } - protected void setDoc(String doc) { - this.doc = doc; - } - - public boolean isOptional() { - return optional; - } - protected void setOptional(boolean optional) { - this.optional = optional; - } - - public WSMethodDef getMethod(){ - return mDef; - } + /** The parent method **/ + private WSMethodDef mDef; + /** The class type of the parameter **/ + private Class paramClass; + /** The web service name of the parameter **/ + private String name; + /** Developer documentation **/ + private String doc; + /** If this parameter is optional **/ + private boolean optional; + /** Is it an header parameter **/ + //boolean header; + + protected WSParameterDef( WSMethodDef mDef ){ + this.mDef = mDef; + this.optional = false; + } + + + public Class getParamClass() { + return paramClass; + } + protected void setParamClass(Class paramClass) { + this.paramClass = paramClass; + } + + public String getName() { + return name; + } + protected void setName(String name) { + this.name = name; + } + + public String getDoc() { + return doc; + } + protected void setDoc(String doc) { + this.doc = doc; + } + + public boolean isOptional() { + return optional; + } + protected void setOptional(boolean optional) { + this.optional = optional; + } + + public WSMethodDef getMethod(){ + return mDef; + } } diff --git a/src/zutil/net/ws/WSReturnObject.java b/src/zutil/net/ws/WSReturnObject.java index eb4d7e1..c053a60 100644 --- a/src/zutil/net/ws/WSReturnObject.java +++ b/src/zutil/net/ws/WSReturnObject.java @@ -54,32 +54,32 @@ import java.lang.reflect.Field; * */ public class WSReturnObject{ - /** - * Method comments for the WSDL. - * These comments are put in the operation part of the WSDL - * - * @author Ziver - */ - @Retention(RetentionPolicy.RUNTIME) - public @interface WSDLDocumentation{ - String value(); - } - - /** - * Annotation that assigns a name to the return value - * to the field. - * - * @author Ziver - */ - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.FIELD) - public @interface WSValueName { - String value(); - boolean optional() default false; - } - - - public Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException{ - return field.get(this); - } + /** + * Method comments for the WSDL. + * These comments are put in the operation part of the WSDL + * + * @author Ziver + */ + @Retention(RetentionPolicy.RUNTIME) + public @interface WSDLDocumentation{ + String value(); + } + + /** + * Annotation that assigns a name to the return value + * to the field. + * + * @author Ziver + */ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.FIELD) + public @interface WSValueName { + String value(); + boolean optional() default false; + } + + + public Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException{ + return field.get(this); + } } diff --git a/src/zutil/net/ws/WebServiceDef.java b/src/zutil/net/ws/WebServiceDef.java index 46cb20d..3bb3d12 100755 --- a/src/zutil/net/ws/WebServiceDef.java +++ b/src/zutil/net/ws/WebServiceDef.java @@ -36,86 +36,86 @@ import java.util.Set; * @author Ziver */ public class WebServiceDef { - /** A map of methods in this Service **/ - private HashMap methods; - /** Namespace of the service **/ - private String namespace; - /** Name of the web service **/ - private String name; - /** This is the WSInterface class **/ - private Class intf; - - - public WebServiceDef(Class intf){ - this.intf = intf; - methods = new HashMap(); - name = intf.getSimpleName(); + /** A map of methods in this Service **/ + private HashMap methods; + /** Namespace of the service **/ + private String namespace; + /** Name of the web service **/ + private String name; + /** This is the WSInterface class **/ + private Class intf; - if( intf.getAnnotation( WSInterface.WSNamespace.class ) != null ) - this.namespace = intf.getAnnotation( WSInterface.WSNamespace.class ).value(); - - for(Method m : intf.getDeclaredMethods()){ - // check for public methods - if((m.getModifiers() & Modifier.PUBLIC) > 0 && - !m.isAnnotationPresent(WSInterface.WSIgnore.class)){ - WSMethodDef method = new WSMethodDef(this, m); - methods.put(method.getName(), method); - } - } - } - - /** - * @return the class that defines this web service - */ - public Class getWSClass(){ - return intf; - } - - /** - * @return the name of the Service (usually the class name of the WSInterface) - */ - public String getName(){ - return name; - } - - /** - * @param name is the name of the method - * @return if there is a method by the given name - */ - public boolean hasMethod( String name ){ - return methods.containsKey( name ); - } - - /** - * @param name is the name of the method - * @return the method or null if there is no such method - */ - public WSMethodDef getMethod( String name ){ - return methods.get( name ); - } - - /** - * @return a Set of all the method names - */ - public Set getMethodNames(){ - return methods.keySet(); - } - - /** - * @return all the methods - */ - public Collection getMethods(){ - return methods.values(); - } - - /** - * @return the namespace of this web service ( usually the URL of the service ) - */ - public String getNamespace(){ - return namespace; - } - public WSInterface newInstance() throws InstantiationException, IllegalAccessException { - return intf.newInstance(); - } + public WebServiceDef(Class intf){ + this.intf = intf; + methods = new HashMap(); + name = intf.getSimpleName(); + + if( intf.getAnnotation( WSInterface.WSNamespace.class ) != null ) + this.namespace = intf.getAnnotation( WSInterface.WSNamespace.class ).value(); + + for(Method m : intf.getDeclaredMethods()){ + // check for public methods + if((m.getModifiers() & Modifier.PUBLIC) > 0 && + !m.isAnnotationPresent(WSInterface.WSIgnore.class)){ + WSMethodDef method = new WSMethodDef(this, m); + methods.put(method.getName(), method); + } + } + } + + /** + * @return the class that defines this web service + */ + public Class getWSClass(){ + return intf; + } + + /** + * @return the name of the Service (usually the class name of the WSInterface) + */ + public String getName(){ + return name; + } + + /** + * @param name is the name of the method + * @return if there is a method by the given name + */ + public boolean hasMethod( String name ){ + return methods.containsKey( name ); + } + + /** + * @param name is the name of the method + * @return the method or null if there is no such method + */ + public WSMethodDef getMethod( String name ){ + return methods.get( name ); + } + + /** + * @return a Set of all the method names + */ + public Set getMethodNames(){ + return methods.keySet(); + } + + /** + * @return all the methods + */ + public Collection getMethods(){ + return methods.values(); + } + + /** + * @return the namespace of this web service ( usually the URL of the service ) + */ + public String getNamespace(){ + return namespace; + } + + public WSInterface newInstance() throws InstantiationException, IllegalAccessException { + return intf.newInstance(); + } } diff --git a/src/zutil/net/ws/soap/SOAPClientInvocationHandler.java b/src/zutil/net/ws/soap/SOAPClientInvocationHandler.java index 85d7417..85b205a 100755 --- a/src/zutil/net/ws/soap/SOAPClientInvocationHandler.java +++ b/src/zutil/net/ws/soap/SOAPClientInvocationHandler.java @@ -53,21 +53,21 @@ public class SOAPClientInvocationHandler implements InvocationHandler { private static Logger logger = LogUtil.getLogger(); private WebServiceDef wsDef; - /** Web address of the web service */ - protected URL url; + /** Web address of the web service */ + protected URL url; - public SOAPClientInvocationHandler(URL url, WebServiceDef wsDef){ - this.url = url; + public SOAPClientInvocationHandler(URL url, WebServiceDef wsDef){ + this.url = url; this.wsDef = wsDef; - } + } - /** - * Makes a request to the target web service - */ - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + /** + * Makes a request to the target web service + */ + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Generate XML Document document = genSOAPRequest((WSInterface)proxy, method.getName(), args); String reqXml = document.asXML(); @@ -89,21 +89,21 @@ public class SOAPClientInvocationHandler implements InvocationHandler { System.out.println(rspXml); } - return parseSOAPResponse(rspXml); - } + return parseSOAPResponse(rspXml); + } - private Document genSOAPRequest(WSInterface obj, String targetMethod, Object[] args){ - logger.fine("Sending request for "+targetMethod); - Document document = DocumentHelper.createDocument(); - Element envelope = document.addElement("soap:Envelope"); + private Document genSOAPRequest(WSInterface obj, String targetMethod, Object[] args){ + logger.fine("Sending request for "+targetMethod); + Document document = DocumentHelper.createDocument(); + Element envelope = document.addElement("soap:Envelope"); WSMethodDef methodDef = wsDef.getMethod( targetMethod ); - try { - envelope.addNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); - envelope.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); - envelope.addNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); + try { + envelope.addNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); + envelope.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); + envelope.addNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); - Element body = envelope.addElement( "soap:Body" ); + Element body = envelope.addElement( "soap:Body" ); Element method = body.addElement(""); method.addNamespace("m", methodDef.getNamespace() ); method.setName("m:"+methodDef.getName()+"Request"); @@ -112,12 +112,12 @@ public class SOAPClientInvocationHandler implements InvocationHandler { SOAPHttpPage.generateSOAPXMLForObj(method, args[i] , param.getName()); } - } catch (Exception e) { - logger.log(Level.SEVERE, "Exception in SOAP generation", e); - } + } catch (Exception e) { + logger.log(Level.SEVERE, "Exception in SOAP generation", e); + } - return document; - } + return document; + } private Object parseSOAPResponse(String xml){ try { diff --git a/src/zutil/net/ws/soap/SOAPException.java b/src/zutil/net/ws/soap/SOAPException.java index b0ab02f..554d75e 100644 --- a/src/zutil/net/ws/soap/SOAPException.java +++ b/src/zutil/net/ws/soap/SOAPException.java @@ -31,9 +31,9 @@ package zutil.net.ws.soap; * @author Ziver */ public class SOAPException extends Exception{ - private static final long serialVersionUID = 1L; - - public SOAPException(String string) { - super(string); - } + private static final long serialVersionUID = 1L; + + public SOAPException(String string) { + super(string); + } } diff --git a/src/zutil/net/ws/soap/SOAPHttpPage.java b/src/zutil/net/ws/soap/SOAPHttpPage.java index 78b377e..73be0f4 100755 --- a/src/zutil/net/ws/soap/SOAPHttpPage.java +++ b/src/zutil/net/ws/soap/SOAPHttpPage.java @@ -81,66 +81,66 @@ import java.util.logging.Logger; * @author Ziver */ public class SOAPHttpPage implements HttpPage{ - private static final Logger logger = LogUtil.getLogger(); - - /** The object that the functions will be invoked from **/ - private WebServiceDef wsDef; - /** This instance of the web service class is used if session is disabled **/ - private WSInterface ws; - /** Session enabled **/ - private boolean session_enabled; + private static final Logger logger = LogUtil.getLogger(); - public SOAPHttpPage( WebServiceDef wsDef ){ - this.wsDef = wsDef; - this.session_enabled = false; - } - - /** - * Enables session support, if enabled then a new instance - * of the SOAPInterface will be created, if disabled then - * only the given object will be used as an static interface. - * Default is false. - * - * @param enabled is if session should be enabled - */ - public void enableSession(boolean enabled){ - this.session_enabled = enabled; - } + /** The object that the functions will be invoked from **/ + private WebServiceDef wsDef; + /** This instance of the web service class is used if session is disabled **/ + private WSInterface ws; + /** Session enabled **/ + private boolean session_enabled; - /** - * Sets the web service object to the specified one. - * Only used when session is disabled - */ - public void setObject(WSInterface obj) { - this.ws = obj; - } - + public SOAPHttpPage( WebServiceDef wsDef ){ + this.wsDef = wsDef; + this.session_enabled = false; + } - public void respond(HttpPrintStream out, - HttpHeader headers, - Map session, - Map cookie, - Map request) { + /** + * Enables session support, if enabled then a new instance + * of the SOAPInterface will be created, if disabled then + * only the given object will be used as an static interface. + * Default is false. + * + * @param enabled is if session should be enabled + */ + public void enableSession(boolean enabled){ + this.session_enabled = enabled; + } - try { - // Read http body + /** + * Sets the web service object to the specified one. + * Only used when session is disabled + */ + public void setObject(WSInterface obj) { + this.ws = obj; + } + + + public void respond(HttpPrintStream out, + HttpHeader headers, + Map session, + Map cookie, + Map request) { + + try { + // Read http body StringBuilder data = null; - String contentType = headers.getHeader("Content-Type"); - if (contentType != null && + String contentType = headers.getHeader("Content-Type"); + if (contentType != null && (contentType.contains("application/soap+xml") || - contentType.contains("text/xml") || - contentType.contains("text/plain"))) { - int post_data_length = Integer.parseInt(headers.getHeader("Content-Length")); + contentType.contains("text/xml") || + contentType.contains("text/plain"))) { + int post_data_length = Integer.parseInt(headers.getHeader("Content-Length")); BufferedReader in = new BufferedReader(new InputStreamReader(headers.getInputStream())); - data = new StringBuilder(post_data_length); - for (int i = 0; i < post_data_length; i++) { - data.append((char) in.read()); - } - } + data = new StringBuilder(post_data_length); + for (int i = 0; i < post_data_length; i++) { + data.append((char) in.read()); + } + } - // Response - out.setHeader("Content-Type", "text/xml"); - out.flush(); + // Response + out.setHeader("Content-Type", "text/xml"); + out.flush(); WSInterface obj = null; if(session_enabled){ @@ -159,7 +159,7 @@ public class SOAPHttpPage implements HttpPage{ Document document = genSOAPResponse( (data!=null ? data.toString() : ""), obj); - OutputFormat format = OutputFormat.createPrettyPrint(); + OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter( out, format ); writer.write( document ); @@ -172,221 +172,221 @@ public class SOAPHttpPage implements HttpPage{ writer = new XMLWriter( System.out, format ); writer.write( document ); } - } catch (Exception e) { - logger.log(Level.WARNING, "Unhandled request", e); - } - } - - /** - * Generates a soap response for the given XML - * - * @param xml is the XML request - * @return a Document with the response - */ - public Document genSOAPResponse(String xml){ - try { - WSInterface obj = null; - if( ws == null ) - ws = wsDef.newInstance(); - obj = ws; - - return genSOAPResponse(xml, obj ); - } catch (Exception e) { - logger.log(Level.WARNING, "Exception in SOAP generation", e); - } - return null; - } + } catch (Exception e) { + logger.log(Level.WARNING, "Unhandled request", e); + } + } - protected Document genSOAPResponse(String xml, WSInterface obj){ - Document document = DocumentHelper.createDocument(); - Element envelope = document.addElement("soap:Envelope"); - try { - envelope.addNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); - envelope.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); - envelope.addNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); - - Element body = envelope.addElement( "soap:Body" ); - try{ - Element request = getXMLRoot(xml); - if(request == null) return document; - // Header - if( request.element("Header") != null){ - Element header = envelope.addElement( "soap:Header" ); - prepareInvoke( obj, request.element("Header"), header ); - } + /** + * Generates a soap response for the given XML + * + * @param xml is the XML request + * @return a Document with the response + */ + public Document genSOAPResponse(String xml){ + try { + WSInterface obj = null; + if( ws == null ) + ws = wsDef.newInstance(); + obj = ws; - // Body - if( request.element("Body") != null){ - prepareInvoke( obj, request.element("Body"), body ); - } - }catch(Throwable e){ - body.clearContent(); - Element fault = body.addElement("soap:Fault"); - // The fault source - if(e instanceof SOAPException || e instanceof SAXException || e instanceof DocumentException) - fault.addElement("faultcode").setText( "soap:Client" ); - else - fault.addElement("faultcode").setText( "soap:Server" ); - // The fault message - if( e.getMessage() == null || e.getMessage().isEmpty()) - fault.addElement("faultstring").setText( ""+e.getClass().getSimpleName() ); - else - fault.addElement("faultstring").setText( ""+e.getMessage() ); - logger.log(Level.WARNING, "Caught exception from SOAP Class", e); - } - } catch (Exception e) { - logger.log(Level.WARNING, "Exception in SOAP generation", e); - } + return genSOAPResponse(xml, obj ); + } catch (Exception e) { + logger.log(Level.WARNING, "Exception in SOAP generation", e); + } + return null; + } - return document; - } - - /** - * Converts an String XML to an Element - * - * @param xml is the string XML - * @return the XML root Element - */ - protected static Element getXMLRoot(String xml) throws DocumentException { - if(xml != null && !xml.isEmpty()){ - Document document = DocumentHelper.parseText(xml); - return document.getRootElement(); - } - return null; - } + protected Document genSOAPResponse(String xml, WSInterface obj){ + Document document = DocumentHelper.createDocument(); + Element envelope = document.addElement("soap:Envelope"); + try { + envelope.addNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); + envelope.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); + envelope.addNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); - /** - * Takes an XML Element and invokes all the it's child elements as methods. - * - * @param obj is the object that the methods will be called from - * @param requestRoot is the Element where the children lies - * @param responseRoot is the root element of the response - */ - @SuppressWarnings("unchecked") - private void prepareInvoke(WSInterface obj, Element requestRoot, Element responseRoot) throws Throwable{ - Iterator it = requestRoot.elementIterator(); - while( it.hasNext() ){ - Element e = it.next(); - if( wsDef.hasMethod( e.getQName().getName()) ){ - WSMethodDef m = wsDef.getMethod( e.getQName().getName() ); - Object[] params = new Object[ m.getInputCount() ]; + Element body = envelope.addElement( "soap:Body" ); + try{ + Element request = getXMLRoot(xml); + if(request == null) return document; + // Header + if( request.element("Header") != null){ + Element header = envelope.addElement( "soap:Header" ); + prepareInvoke( obj, request.element("Header"), header ); + } - // Get the parameter values - for(int i=0; i it = requestRoot.elementIterator(); + while( it.hasNext() ){ + Element e = it.next(); + if( wsDef.hasMethod( e.getQName().getName()) ){ + WSMethodDef m = wsDef.getMethod( e.getQName().getName() ); + Object[] params = new Object[ m.getInputCount() ]; + + // Get the parameter values + for(int i=0; i0 ){ - Element response = responseRoot.addElement(""); - response.addNamespace("m", m.getNamespace() ); - response.setName("m:"+m.getName()+"Response"); - - if( ret instanceof WSReturnObject ){ - Field[] f = ret.getClass().getFields(); - for(int i=0; i0 ){ + Element response = responseRoot.addElement(""); + response.addNamespace("m", m.getNamespace() ); + response.setName("m:"+m.getName()+"Response"); + + if( ret instanceof WSReturnObject ){ + Field[] f = ret.getClass().getFields(); + for(int i=0; i c){ - Class cTmp = getClass(c); - if(byte[].class.isAssignableFrom(c)){ - return "base64Binary"; - } - else if( WSReturnObject.class.isAssignableFrom(cTmp) ){ - return c.getSimpleName(); - } - else{ - String ret = c.getSimpleName().toLowerCase(); - - if(cTmp == Integer.class) ret = ret.replaceAll("integer", "int"); - else if(cTmp == Character.class)ret = ret.replaceAll("character", "char"); - - return ret; - } - } - protected static Class getClass(Class c){ - if(c!=null && c.isArray()){ - return getClass(c.getComponentType()); - } - return c; - } + protected static String getSOAPClassName(Class c){ + Class cTmp = getClass(c); + if(byte[].class.isAssignableFrom(c)){ + return "base64Binary"; + } + else if( WSReturnObject.class.isAssignableFrom(cTmp) ){ + return c.getSimpleName(); + } + else{ + String ret = c.getSimpleName().toLowerCase(); + + if(cTmp == Integer.class) ret = ret.replaceAll("integer", "int"); + else if(cTmp == Character.class)ret = ret.replaceAll("character", "char"); + + return ret; + } + } + + protected static Class getClass(Class c){ + if(c!=null && c.isArray()){ + return getClass(c.getComponentType()); + } + return c; + } } diff --git a/src/zutil/parser/BBCodeParser.java b/src/zutil/parser/BBCodeParser.java index 42b6a4e..32a0b7e 100755 --- a/src/zutil/parser/BBCodeParser.java +++ b/src/zutil/parser/BBCodeParser.java @@ -30,158 +30,158 @@ import java.util.HashMap; /** * Parses BBCode and replaces them with the corresponding HTML. - * + * * @author Ziver */ public class BBCodeParser { - /** Contains all the BBCodes and the corresponding HTML **/ - private HashMap bbcodes; - - - /** - * Initiates a instance of the parser with the most used BBCodes. - */ - public BBCodeParser(){ - bbcodes = new HashMap(); - addBBCode("b", "%2"); - addBBCode("i", "%2"); - addBBCode("u", "%2"); - addBBCode("url", "%2"); - addBBCode("img", ""); - addBBCode("quote", "
%2
"); - addBBCode("code", "
%2
"); - addBBCode("size", "%2"); - addBBCode("color", "%2"); - addBBCode("ul", "
    %2
"); - addBBCode("li", "
  • %2
  • "); - } - - /** - * Registers a new BBCode to the parser. Only one type of BBCode allowed. - * - * @param bbcode is the BBCode e.g. "b" or "url" - * @param html is the corresponding HTML e.g. "%2" - * where the %x corresponds to BBCode like this: [url=%1]%2[/url] - */ - public void addBBCode(String bbcode, String html){ - bbcodes.put(bbcode, html); - } - - /** - * Removes a BBCode definition from the parser - * - * @param bbcode is the bbcode to remove - */ - public void removeBBCode(String bbcode){ - bbcodes.remove(bbcode); - } - - /** - * Parses the text with BBCode and converts it to HTML - * - * @param text is a String with BBCode - * @return a String where all BBCode has been replaced by HTML - */ - public String read(String text){ - StringBuilder out = new StringBuilder(); - StringBuilder t = new StringBuilder(text); - - read(new MutableInt(), t, out, ""); - - return out.toString(); - } - - private void read(MutableInt index, StringBuilder text, StringBuilder out, String rootBBC){ - StringBuilder bbcode = null; - boolean closeTag = false; - while(index.i < text.length()){ - char c = text.charAt(index.i); - if(c == '['){ - bbcode = new StringBuilder(); - } - else if(bbcode!=null && c == '/'){ - closeTag = true; - } - else if(bbcode!=null){ - String param = ""; - switch(c){ - case '=': - param = parseParam(index, text); - case ']': - String bbcode_cache = bbcode.toString(); - if(closeTag){ - if(!rootBBC.equals(bbcode_cache)){ - out.append("[/").append(bbcode).append("]"); - } - return; - } - String value = parseValue(index, text, bbcode_cache); - if(bbcodes.containsKey( bbcode_cache )){ - String html = bbcodes.get( bbcode_cache ); - html = html.replaceAll("%1", param); - html = html.replaceAll("%2", value); - out.append(html); - } - else{ - out.append('[').append(bbcode); - if(!param.isEmpty()) - out.append('=').append(param); - out.append(']').append(value); - out.append("[/").append(bbcode).append("]"); - } - bbcode = null; - break; - default: - bbcode.append(c); - break; - } - } - else - out.append(c); - - index.i++; - } - if(bbcode!=null) - if(closeTag)out.append("[/").append(bbcode); - else out.append('[').append(bbcode); - } - - /** - * Parses a parameter from a BBCode block: [url=param] - * - * @param text is the text to parse from - * @return only the parameter string - */ - private String parseParam(MutableInt index, StringBuilder text){ - StringBuilder param = new StringBuilder(); - while(index.i < text.length()){ - char c = text.charAt(index.i); - if(c == ']') - break; - else if(c != '=') - param.append(c); - index.i++; - } - return param.toString(); - } - - /** - * Parses the value in the BBCodes e.g. [url]value[/url] - * - * @param text is the text to parse the value from - */ - private String parseValue(MutableInt index, StringBuilder text, String bbcode){ - StringBuilder value = new StringBuilder(); - while(index.i < text.length()){ - char c = text.charAt(index.i); - if(c == '['){ - read(index, text, value, bbcode); - break; - } - else if(c != ']') - value.append(c); - index.i++; - } - return value.toString(); - } + /** Contains all the BBCodes and the corresponding HTML **/ + private HashMap bbcodes; + + + /** + * Initiates a instance of the parser with the most used BBCodes. + */ + public BBCodeParser(){ + bbcodes = new HashMap(); + addBBCode("b", "%2"); + addBBCode("i", "%2"); + addBBCode("u", "%2"); + addBBCode("url", "%2"); + addBBCode("img", ""); + addBBCode("quote", "
    %2
    "); + addBBCode("code", "
    %2
    "); + addBBCode("size", "%2"); + addBBCode("color", "%2"); + addBBCode("ul", "
      %2
    "); + addBBCode("li", "
  • %2
  • "); + } + + /** + * Registers a new BBCode to the parser. Only one type of BBCode allowed. + * + * @param bbcode is the BBCode e.g. "b" or "url" + * @param html is the corresponding HTML e.g. "%2" + * where the %x corresponds to BBCode like this: [url=%1]%2[/url] + */ + public void addBBCode(String bbcode, String html){ + bbcodes.put(bbcode, html); + } + + /** + * Removes a BBCode definition from the parser + * + * @param bbcode is the bbcode to remove + */ + public void removeBBCode(String bbcode){ + bbcodes.remove(bbcode); + } + + /** + * Parses the text with BBCode and converts it to HTML + * + * @param text is a String with BBCode + * @return a String where all BBCode has been replaced by HTML + */ + public String read(String text){ + StringBuilder out = new StringBuilder(); + StringBuilder t = new StringBuilder(text); + + read(new MutableInt(), t, out, ""); + + return out.toString(); + } + + private void read(MutableInt index, StringBuilder text, StringBuilder out, String rootBBC){ + StringBuilder bbcode = null; + boolean closeTag = false; + while(index.i < text.length()){ + char c = text.charAt(index.i); + if(c == '['){ + bbcode = new StringBuilder(); + } + else if(bbcode!=null && c == '/'){ + closeTag = true; + } + else if(bbcode!=null){ + String param = ""; + switch(c){ + case '=': + param = parseParam(index, text); + case ']': + String bbcode_cache = bbcode.toString(); + if(closeTag){ + if(!rootBBC.equals(bbcode_cache)){ + out.append("[/").append(bbcode).append("]"); + } + return; + } + String value = parseValue(index, text, bbcode_cache); + if(bbcodes.containsKey( bbcode_cache )){ + String html = bbcodes.get( bbcode_cache ); + html = html.replaceAll("%1", param); + html = html.replaceAll("%2", value); + out.append(html); + } + else{ + out.append('[').append(bbcode); + if(!param.isEmpty()) + out.append('=').append(param); + out.append(']').append(value); + out.append("[/").append(bbcode).append("]"); + } + bbcode = null; + break; + default: + bbcode.append(c); + break; + } + } + else + out.append(c); + + index.i++; + } + if(bbcode!=null) + if(closeTag)out.append("[/").append(bbcode); + else out.append('[').append(bbcode); + } + + /** + * Parses a parameter from a BBCode block: [url=param] + * + * @param text is the text to parse from + * @return only the parameter string + */ + private String parseParam(MutableInt index, StringBuilder text){ + StringBuilder param = new StringBuilder(); + while(index.i < text.length()){ + char c = text.charAt(index.i); + if(c == ']') + break; + else if(c != '=') + param.append(c); + index.i++; + } + return param.toString(); + } + + /** + * Parses the value in the BBCodes e.g. [url]value[/url] + * + * @param text is the text to parse the value from + */ + private String parseValue(MutableInt index, StringBuilder text, String bbcode){ + StringBuilder value = new StringBuilder(); + while(index.i < text.length()){ + char c = text.charAt(index.i); + if(c == '['){ + read(index, text, value, bbcode); + break; + } + else if(c != ']') + value.append(c); + index.i++; + } + return value.toString(); + } } diff --git a/src/zutil/parser/BEncodedParser.java b/src/zutil/parser/BEncodedParser.java index eddbdfc..0c46c46 100755 --- a/src/zutil/parser/BEncodedParser.java +++ b/src/zutil/parser/BEncodedParser.java @@ -37,93 +37,93 @@ import java.text.ParseException; */ public class BEncodedParser { - /** - * Returns the representation of the data in the BEncoded string - * - * @param data is the data to be decoded - */ - public static DataNode read(String data) throws ParseException { - return decode_BEncoded(new MutableInt(), new StringBuilder(data)); - } + /** + * Returns the representation of the data in the BEncoded string + * + * @param data is the data to be decoded + */ + public static DataNode read(String data) throws ParseException { + return decode_BEncoded(new MutableInt(), new StringBuilder(data)); + } - /** - * Returns the representation of the data in the BEncoded string - * - * @param data is the data to be decoded - * @param index is the index in data to start from - * @return - */ - private static DataNode decode_BEncoded(MutableInt index, StringBuilder data) throws ParseException { - String tmp; - char c = ' '; + /** + * Returns the representation of the data in the BEncoded string + * + * @param data is the data to be decoded + * @param index is the index in data to start from + * @return + */ + private static DataNode decode_BEncoded(MutableInt index, StringBuilder data) throws ParseException { + String tmp; + 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. - */ - case 'i': - index.i++; - end = data.indexOf("e", index.i); - if (end < 0) - throw new ParseException("Corrupt bEncoding", index.i); - 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 - * l7:Monduna3:Bit8:Torrentse. The list [1, "Monduna", 3, ["Sub", "List"]] - * would bEncode to li1e7:Mondunai3el3:Sub4:Listee - */ - case 'l': - index.i++; - DataNode list = new DataNode( DataType.List ); - c = data.charAt(index.i); - while(c != 'e'){ - list.add( decode_BEncoded(index, data) ); - c = data.charAt(index.i); - } - 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} - * would bEncode to d3:key5:value7:Monduna3:com3:bit:8:Torrents6:numberi7ee - */ - case 'd': - index.i++; - DataNode map = new DataNode( DataType.Map ); - c = data.charAt(index.i); - while(c != 'e'){ - DataNode tmp2 = decode_BEncoded(index, data); - map.set(tmp2.getString(), decode_BEncoded(index, data)); - if (index.i >= data.length()) - throw new ParseException("Incorrect bEncoding ending of element", index.i); - c = data.charAt(index.i); - } - 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. - */ - default: - end = data.indexOf(":", index.i); - if (end < 0) - throw new ParseException("Corrupt bEncoding", index.i); - tmp = data.substring(index.i, end); - int length = Integer.parseInt(tmp); - index.i += tmp.length() + 1; - String ret = data.substring(index.i, index.i+length); - index.i += length; - return new DataNode( ret ); - } - } + 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. + */ + case 'i': + index.i++; + end = data.indexOf("e", index.i); + if (end < 0) + throw new ParseException("Corrupt bEncoding", index.i); + 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 + * l7:Monduna3:Bit8:Torrentse. The list [1, "Monduna", 3, ["Sub", "List"]] + * would bEncode to li1e7:Mondunai3el3:Sub4:Listee + */ + case 'l': + index.i++; + DataNode list = new DataNode( DataType.List ); + c = data.charAt(index.i); + while(c != 'e'){ + list.add( decode_BEncoded(index, data) ); + c = data.charAt(index.i); + } + 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} + * would bEncode to d3:key5:value7:Monduna3:com3:bit:8:Torrents6:numberi7ee + */ + case 'd': + index.i++; + DataNode map = new DataNode( DataType.Map ); + c = data.charAt(index.i); + while(c != 'e'){ + DataNode tmp2 = decode_BEncoded(index, data); + map.set(tmp2.getString(), decode_BEncoded(index, data)); + if (index.i >= data.length()) + throw new ParseException("Incorrect bEncoding ending of element", index.i); + c = data.charAt(index.i); + } + 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. + */ + default: + end = data.indexOf(":", index.i); + if (end < 0) + throw new ParseException("Corrupt bEncoding", index.i); + tmp = data.substring(index.i, end); + int length = Integer.parseInt(tmp); + index.i += tmp.length() + 1; + String ret = data.substring(index.i, index.i+length); + index.i += length; + return new DataNode( ret ); + } + } } diff --git a/src/zutil/parser/Base64Decoder.java b/src/zutil/parser/Base64Decoder.java index 1455a94..69547a6 100755 --- a/src/zutil/parser/Base64Decoder.java +++ b/src/zutil/parser/Base64Decoder.java @@ -28,33 +28,33 @@ import zutil.converter.Converter; import zutil.io.DynamicByteArrayStream; public class Base64Decoder { - public static final char[] B64_ENCODE_TABLE = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', - 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', - 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', - 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', - 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - - '0', '1', '2', '3', '4', '5', '6', '7', '8', - '9', '+', '/' - }; - - private DynamicByteArrayStream output; - private byte rest_data; - private int rest = 0; - - public Base64Decoder(){ - output = new DynamicByteArrayStream(); - } + public static final char[] B64_ENCODE_TABLE = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', + 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', + 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - - public static String decode( String data ){ - Base64Decoder base64 = new Base64Decoder(); - base64.read( data ); - return base64.toString(); - } + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', + 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', + 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + + '0', '1', '2', '3', '4', '5', '6', '7', '8', + '9', '+', '/' + }; + + private DynamicByteArrayStream output; + private byte rest_data; + private int rest = 0; + + public Base64Decoder(){ + output = new DynamicByteArrayStream(); + } + + + public static String decode( String data ){ + Base64Decoder base64 = new Base64Decoder(); + base64.read( data ); + return base64.toString(); + } public static String decodeToHex( String data ){ Base64Decoder base64 = new Base64Decoder(); @@ -67,130 +67,130 @@ public class Base64Decoder { base64.read( data ); return base64.getByte(); } - - public void read( String data ){ - byte[] buffer = new byte[ (data.length()*6/8) + 1 ]; - int buffi = 0; - if( rest != 0 ) - buffer[0] = rest_data; - - for( int i=0; i> 2) & 0b0011_1111); - break; - case 2: - b = (byte) ((data[i-1] << 4) & 0b0011_0000); - b |= (byte) ((data[i] >> 4) & 0b0000_1111); - break; - case 4: - b = (byte) ((data[i-1] << 2) & 0b0011_1100); - b |= (byte) ((data[i] >> 6) & 0b0000_0011); - break; - case 6: - --i; // Go back one element - b = (byte) (data[i] & 0b0011_1111); - break; - } + switch(rest){ + case 0: + b = (byte)((data[i] >> 2) & 0b0011_1111); + break; + case 2: + b = (byte) ((data[i-1] << 4) & 0b0011_0000); + b |= (byte) ((data[i] >> 4) & 0b0000_1111); + break; + case 4: + b = (byte) ((data[i-1] << 2) & 0b0011_1100); + b |= (byte) ((data[i] >> 6) & 0b0000_0011); + break; + case 6: + --i; // Go back one element + b = (byte) (data[i] & 0b0011_1111); + break; + } - rest = (rest + 2) % 8; + rest = (rest + 2) % 8; buffer[buffIndex++] = getChar(b); - } + } // Any rest left? if(rest == 2) buffer[buffIndex++] = getChar((byte) ((data[data.length-1] << 4) & 0b0011_0000)); @@ -77,7 +77,7 @@ public class Base64Encoder { buffer[buffIndex] = '='; return new String(buffer); - } + } private static int getBufferLength(int length) { int buffLength = (int) Math.ceil(length*8/6.0); @@ -89,74 +89,74 @@ public class Base64Encoder { private static char getChar( byte b ){ - switch(b){ - case (byte)( 0 & 0xff): return 'A'; - case (byte)( 1 & 0xff): return 'B'; - case (byte)( 2 & 0xff): return 'C'; - case (byte)( 3 & 0xff): return 'D'; - case (byte)( 4 & 0xff): return 'E'; - case (byte)( 5 & 0xff): return 'F'; - case (byte)( 6 & 0xff): return 'G'; - case (byte)( 7 & 0xff): return 'H'; - case (byte)( 8 & 0xff): return 'I'; - case (byte)( 9 & 0xff): return 'J'; - case (byte)(10 & 0xff): return 'K'; - case (byte)(11 & 0xff): return 'L'; - case (byte)(12 & 0xff): return 'M'; - case (byte)(13 & 0xff): return 'N'; - case (byte)(14 & 0xff): return 'O'; - case (byte)(15 & 0xff): return 'P'; - case (byte)(16 & 0xff): return 'Q'; - case (byte)(17 & 0xff): return 'R'; - case (byte)(18 & 0xff): return 'S'; - case (byte)(19 & 0xff): return 'T'; - case (byte)(20 & 0xff): return 'U'; - case (byte)(21 & 0xff): return 'V'; - case (byte)(22 & 0xff): return 'W'; - case (byte)(23 & 0xff): return 'X'; - case (byte)(24 & 0xff): return 'Y'; - case (byte)(25 & 0xff): return 'Z'; - - case (byte)(26 & 0xff): return 'a'; - case (byte)(27 & 0xff): return 'b'; - case (byte)(28 & 0xff): return 'c'; - case (byte)(29 & 0xff): return 'd'; - case (byte)(30 & 0xff): return 'e'; - case (byte)(31 & 0xff): return 'f'; - case (byte)(32 & 0xff): return 'g'; - case (byte)(33 & 0xff): return 'h'; - case (byte)(34 & 0xff): return 'i'; - case (byte)(35 & 0xff): return 'j'; - case (byte)(36 & 0xff): return 'k'; - case (byte)(37 & 0xff): return 'l'; - case (byte)(38 & 0xff): return 'm'; - case (byte)(39 & 0xff): return 'n'; - case (byte)(40 & 0xff): return 'o'; - case (byte)(41 & 0xff): return 'p'; - case (byte)(42 & 0xff): return 'q'; - case (byte)(43 & 0xff): return 'r'; - case (byte)(44 & 0xff): return 's'; - case (byte)(45 & 0xff): return 't'; - case (byte)(46 & 0xff): return 'u'; - case (byte)(47 & 0xff): return 'v'; - case (byte)(48 & 0xff): return 'w'; - case (byte)(49 & 0xff): return 'x'; - case (byte)(50 & 0xff): return 'y'; - case (byte)(51 & 0xff): return 'z'; - - case (byte)(52 & 0xff): return '0'; - case (byte)(53 & 0xff): return '1'; - case (byte)(54 & 0xff): return '2'; - case (byte)(55 & 0xff): return '3'; - case (byte)(56 & 0xff): return '4'; - case (byte)(57 & 0xff): return '5'; - case (byte)(58 & 0xff): return '6'; - case (byte)(59 & 0xff): return '7'; - case (byte)(60 & 0xff): return '8'; - case (byte)(61 & 0xff): return '9'; - case (byte)(62 & 0xff): return '+'; - case (byte)(63 & 0xff): return '/'; - } + switch(b){ + case (byte)( 0 & 0xff): return 'A'; + case (byte)( 1 & 0xff): return 'B'; + case (byte)( 2 & 0xff): return 'C'; + case (byte)( 3 & 0xff): return 'D'; + case (byte)( 4 & 0xff): return 'E'; + case (byte)( 5 & 0xff): return 'F'; + case (byte)( 6 & 0xff): return 'G'; + case (byte)( 7 & 0xff): return 'H'; + case (byte)( 8 & 0xff): return 'I'; + case (byte)( 9 & 0xff): return 'J'; + case (byte)(10 & 0xff): return 'K'; + case (byte)(11 & 0xff): return 'L'; + case (byte)(12 & 0xff): return 'M'; + case (byte)(13 & 0xff): return 'N'; + case (byte)(14 & 0xff): return 'O'; + case (byte)(15 & 0xff): return 'P'; + case (byte)(16 & 0xff): return 'Q'; + case (byte)(17 & 0xff): return 'R'; + case (byte)(18 & 0xff): return 'S'; + case (byte)(19 & 0xff): return 'T'; + case (byte)(20 & 0xff): return 'U'; + case (byte)(21 & 0xff): return 'V'; + case (byte)(22 & 0xff): return 'W'; + case (byte)(23 & 0xff): return 'X'; + case (byte)(24 & 0xff): return 'Y'; + case (byte)(25 & 0xff): return 'Z'; + + case (byte)(26 & 0xff): return 'a'; + case (byte)(27 & 0xff): return 'b'; + case (byte)(28 & 0xff): return 'c'; + case (byte)(29 & 0xff): return 'd'; + case (byte)(30 & 0xff): return 'e'; + case (byte)(31 & 0xff): return 'f'; + case (byte)(32 & 0xff): return 'g'; + case (byte)(33 & 0xff): return 'h'; + case (byte)(34 & 0xff): return 'i'; + case (byte)(35 & 0xff): return 'j'; + case (byte)(36 & 0xff): return 'k'; + case (byte)(37 & 0xff): return 'l'; + case (byte)(38 & 0xff): return 'm'; + case (byte)(39 & 0xff): return 'n'; + case (byte)(40 & 0xff): return 'o'; + case (byte)(41 & 0xff): return 'p'; + case (byte)(42 & 0xff): return 'q'; + case (byte)(43 & 0xff): return 'r'; + case (byte)(44 & 0xff): return 's'; + case (byte)(45 & 0xff): return 't'; + case (byte)(46 & 0xff): return 'u'; + case (byte)(47 & 0xff): return 'v'; + case (byte)(48 & 0xff): return 'w'; + case (byte)(49 & 0xff): return 'x'; + case (byte)(50 & 0xff): return 'y'; + case (byte)(51 & 0xff): return 'z'; + + case (byte)(52 & 0xff): return '0'; + case (byte)(53 & 0xff): return '1'; + case (byte)(54 & 0xff): return '2'; + case (byte)(55 & 0xff): return '3'; + case (byte)(56 & 0xff): return '4'; + case (byte)(57 & 0xff): return '5'; + case (byte)(58 & 0xff): return '6'; + case (byte)(59 & 0xff): return '7'; + case (byte)(60 & 0xff): return '8'; + case (byte)(61 & 0xff): return '9'; + case (byte)(62 & 0xff): return '+'; + case (byte)(63 & 0xff): return '/'; + } return 0; - } + } } diff --git a/src/zutil/parser/DataNode.java b/src/zutil/parser/DataNode.java index 34a8bd8..b9e1d21 100644 --- a/src/zutil/parser/DataNode.java +++ b/src/zutil/parser/DataNode.java @@ -33,310 +33,310 @@ import java.util.*; * @author Ziver */ public class DataNode implements Iterable{ - public enum DataType{ - Map, List, String, Number, Boolean - } - private Map map = null; - private List list = null; - private String value = null; - private DataType type; + public enum DataType{ + Map, List, String, Number, Boolean + } + private Map map = null; + private List list = null; + private String value = null; + private DataType type; - /** - * Creates an instance with an Boolean value - */ - public DataNode(boolean value){ - this.type = DataType.Boolean; - this.value = ""+value; - } - /** - * Creates an instance with an int value - */ - public DataNode(int value){ - this.type = DataType.Number; - this.value = ""+value; - } - /** - * Creates an instance with an double value - */ - public DataNode(double value){ - this.type = DataType.Number; - this.value = ""+value; - } - /** - * Creates an instance with an long value - */ - public DataNode(long value){ - this.type = DataType.Number; - this.value = ""+value; - } - /** - * Creates an instance with an String value - */ - public DataNode(String value){ - this.type = DataType.String; - this.value = value; - } - /** - * Creates an instance with a specific type - */ - public DataNode(DataType type){ - this.type = type; - switch(type){ - case Map: - map = new HashMap(); break; - case List: - list = new LinkedList(); break; - default: - break; - } - } + /** + * Creates an instance with an Boolean value + */ + public DataNode(boolean value){ + this.type = DataType.Boolean; + this.value = ""+value; + } + /** + * Creates an instance with an int value + */ + public DataNode(int value){ + this.type = DataType.Number; + this.value = ""+value; + } + /** + * Creates an instance with an double value + */ + public DataNode(double value){ + this.type = DataType.Number; + this.value = ""+value; + } + /** + * Creates an instance with an long value + */ + public DataNode(long value){ + this.type = DataType.Number; + this.value = ""+value; + } + /** + * Creates an instance with an String value + */ + public DataNode(String value){ + this.type = DataType.String; + this.value = value; + } + /** + * Creates an instance with a specific type + */ + public DataNode(DataType type){ + this.type = type; + switch(type){ + case Map: + map = new HashMap(); break; + case List: + list = new LinkedList(); break; + default: + break; + } + } - /** - * @param index is the index of the List or Map - * @return an JSONNode that contains the next level of the List or Map - */ - public DataNode get(int index){ + /** + * @param index is the index of the List or Map + * @return an JSONNode that contains the next level of the List or Map + */ + public DataNode get(int index){ if(map != null) return map.get(""+index); else if(list != null) return list.get(index); return null; - } - /** - * @param index is the key in the Map - * @return an JSONNode that contains the next level of the Map - */ - public DataNode get(String index){ - if(map != null) - return map.get(index); - return null; - } + } + /** + * @param index is the key in the Map + * @return an JSONNode that contains the next level of the Map + */ + public DataNode get(String index){ + if(map != null) + return map.get(index); + return null; + } - /** - * @return a iterator for the Map or List or null if the node contains a value - */ - public Iterator iterator(){ - if(map != null) - return map.values().iterator(); - else if(list != null) - return list.iterator(); - return null; - } - /** - * @return a iterator for the keys in the Map or null if the node contains a value or List - */ - public Iterator keyIterator(){ - if(map != null) - return map.keySet().iterator(); - return null; - } - /** - * @return the size of the Map or List or -1 if it is a value - */ - public int size(){ - if(map != null) - return map.size(); - else if(list != null) - return list.size(); - return -1; - } + /** + * @return a iterator for the Map or List or null if the node contains a value + */ + public Iterator iterator(){ + if(map != null) + return map.values().iterator(); + else if(list != null) + return list.iterator(); + return null; + } + /** + * @return a iterator for the keys in the Map or null if the node contains a value or List + */ + public Iterator keyIterator(){ + if(map != null) + return map.keySet().iterator(); + return null; + } + /** + * @return the size of the Map or List or -1 if it is a value + */ + public int size(){ + if(map != null) + return map.size(); + else if(list != null) + return list.size(); + return -1; + } - /** - * Adds a node to the List - */ - public void add(DataNode node){ - list.add(node); - } - public void add(boolean value){ - list.add(new DataNode( value )); - } - public void add(int value){ - list.add(new DataNode( value )); - } - public void add(double value){ - list.add(new DataNode( value )); - } - public void add(long value){ - list.add(new DataNode( value )); - } - public void add(String value){ - list.add(new DataNode( value )); - } - /** - * Adds a node to the Map - */ - public void set(String key, DataNode node){ - map.put(key, node); - } - public void set(String key, boolean value){ - map.put(key, new DataNode(value)); - } - public void set(String key, int value){ - map.put(key, new DataNode(value)); - } - public void set(String key, double value){ - map.put(key, new DataNode(value)); - } - public void set(String key, long value){ - map.put(key, new DataNode(value)); - } - public void set(String key, String value){ - map.put(key, new DataNode(value)); - } - /** - * Sets the value of the node - * @exception NullPointerException if the node is setup as anything other than a DataType.Number - */ - public void set(int value){ - if( this.type != DataType.Number ) - throw new NullPointerException("The node is not setup as a DataType.Number"); - this.value = ""+value; - } - /** - * Sets the value of the node - * @exception NullPointerException if the node is setup as anything other than a DataType.Number - */ - public void set(double value){ - if( this.type != DataType.Number ) - throw new NullPointerException("The node is not setup as a DataType.Number"); - this.value = ""+value; - } - /** - * Sets the value of the node - * @exception NullPointerException if the node is setup as anything other than a DataType.Boolean - */ - public void set(boolean value){ - if( this.type != DataType.Boolean ) - throw new NullPointerException("The node is not setup as a DataType.Boolean"); - this.value = ""+value; - } - /** - * Sets the value of the node, but only - * @exception NullPointerException if the node is setup as anything other than a DataType.Number - */ - public void set(long value){ - if( this.type != DataType.Number ) - throw new NullPointerException("The node is not setup as a DataType.Number"); - this.value = ""+value; - } - /** - * Sets the value of the node - * @exception NullPointerException if the method DataType.isValue() returns false - */ - public void set(String value){ - if( !this.isValue() ) throw new NullPointerException("The node is not setup as a value node"); - this.value = value; - } + /** + * Adds a node to the List + */ + public void add(DataNode node){ + list.add(node); + } + public void add(boolean value){ + list.add(new DataNode( value )); + } + public void add(int value){ + list.add(new DataNode( value )); + } + public void add(double value){ + list.add(new DataNode( value )); + } + public void add(long value){ + list.add(new DataNode( value )); + } + public void add(String value){ + list.add(new DataNode( value )); + } + /** + * Adds a node to the Map + */ + public void set(String key, DataNode node){ + map.put(key, node); + } + public void set(String key, boolean value){ + map.put(key, new DataNode(value)); + } + public void set(String key, int value){ + map.put(key, new DataNode(value)); + } + public void set(String key, double value){ + map.put(key, new DataNode(value)); + } + public void set(String key, long value){ + map.put(key, new DataNode(value)); + } + public void set(String key, String value){ + map.put(key, new DataNode(value)); + } + /** + * Sets the value of the node + * @exception NullPointerException if the node is setup as anything other than a DataType.Number + */ + public void set(int value){ + if( this.type != DataType.Number ) + throw new NullPointerException("The node is not setup as a DataType.Number"); + this.value = ""+value; + } + /** + * Sets the value of the node + * @exception NullPointerException if the node is setup as anything other than a DataType.Number + */ + public void set(double value){ + if( this.type != DataType.Number ) + throw new NullPointerException("The node is not setup as a DataType.Number"); + this.value = ""+value; + } + /** + * Sets the value of the node + * @exception NullPointerException if the node is setup as anything other than a DataType.Boolean + */ + public void set(boolean value){ + if( this.type != DataType.Boolean ) + throw new NullPointerException("The node is not setup as a DataType.Boolean"); + this.value = ""+value; + } + /** + * Sets the value of the node, but only + * @exception NullPointerException if the node is setup as anything other than a DataType.Number + */ + public void set(long value){ + if( this.type != DataType.Number ) + throw new NullPointerException("The node is not setup as a DataType.Number"); + this.value = ""+value; + } + /** + * Sets the value of the node + * @exception NullPointerException if the method DataType.isValue() returns false + */ + public void set(String value){ + if( !this.isValue() ) throw new NullPointerException("The node is not setup as a value node"); + this.value = value; + } - /** - * @return if this node contains an Map - */ - public boolean isMap(){ - return type == DataType.Map; - } - /** - * @return if this node contains an List - */ - public boolean isList(){ - return type == DataType.List; - } - /** - * @return if this node contains an value - */ - public boolean isValue(){ - return type != DataType.Map && type != DataType.List; - } - /** - * @return the type of the node - */ - public DataType getType(){ - return type; - } - - - /** - * @return the String value in this map - */ - public String getString(String key){ - if( !this.isMap() ) throw new NullPointerException("The node is not setup as a map"); - if( !this.map.containsKey(key) ) - return null; - return this.get(key).getString(); - } - /** - * @return the boolean value in this map - */ - public boolean getBoolean(String key){ - if( !this.isMap() ) throw new NullPointerException("The node is not setup as a map"); - if( !this.map.containsKey(key) ) throw new NullPointerException("No such key in map"); - return this.get(key).getBoolean(); - } - /** - * @return the integer value in this map - */ - public int getInt(String key){ - if( !this.isMap() ) throw new NullPointerException("The node is not setup as a map"); - if( !this.map.containsKey(key) ) throw new NullPointerException("No such key in map"); - return this.get(key).getInt(); - } - /** - * @return the double value in this map - */ - public double getDouble(String key){ - if( !this.isMap() ) throw new NullPointerException("The node is not setup as a map"); - if( !this.map.containsKey(key) ) throw new NullPointerException("No such key in map"); - return this.get(key).getDouble(); - } - /** - * @return the long value in this map - */ - public long getLong(String key){ - if( !this.isMap() ) throw new NullPointerException("The node is not setup as a map"); - if( !this.map.containsKey(key) ) throw new NullPointerException("No such key in map"); - return this.get(key).getLong(); - } - - - /** - * @return the String value in this node, null if its a Map or List - */ - public String getString(){ - return value; - } - /** - * @return the boolean value in this node - */ - public boolean getBoolean(){ - return Boolean.parseBoolean(value); - } - /** - * @return the integer value in this node - */ - public int getInt(){ - return Integer.parseInt(value); - } - /** - * @return the double value in this node - */ - public double getDouble(){ - return Double.parseDouble(value); - } - /** - * @return the long value in this node - */ - public long getLong(){ - return Long.parseLong(value); - } + /** + * @return if this node contains an Map + */ + public boolean isMap(){ + return type == DataType.Map; + } + /** + * @return if this node contains an List + */ + public boolean isList(){ + return type == DataType.List; + } + /** + * @return if this node contains an value + */ + public boolean isValue(){ + return type != DataType.Map && type != DataType.List; + } + /** + * @return the type of the node + */ + public DataType getType(){ + return type; + } - public String toString(){ - if( this.isMap() ) - return map.toString(); - else if( this.isList() ) - return list.toString(); - return value; - } + /** + * @return the String value in this map + */ + public String getString(String key){ + if( !this.isMap() ) throw new NullPointerException("The node is not setup as a map"); + if( !this.map.containsKey(key) ) + return null; + return this.get(key).getString(); + } + /** + * @return the boolean value in this map + */ + public boolean getBoolean(String key){ + if( !this.isMap() ) throw new NullPointerException("The node is not setup as a map"); + if( !this.map.containsKey(key) ) throw new NullPointerException("No such key in map"); + return this.get(key).getBoolean(); + } + /** + * @return the integer value in this map + */ + public int getInt(String key){ + if( !this.isMap() ) throw new NullPointerException("The node is not setup as a map"); + if( !this.map.containsKey(key) ) throw new NullPointerException("No such key in map"); + return this.get(key).getInt(); + } + /** + * @return the double value in this map + */ + public double getDouble(String key){ + if( !this.isMap() ) throw new NullPointerException("The node is not setup as a map"); + if( !this.map.containsKey(key) ) throw new NullPointerException("No such key in map"); + return this.get(key).getDouble(); + } + /** + * @return the long value in this map + */ + public long getLong(String key){ + if( !this.isMap() ) throw new NullPointerException("The node is not setup as a map"); + if( !this.map.containsKey(key) ) throw new NullPointerException("No such key in map"); + return this.get(key).getLong(); + } + + + /** + * @return the String value in this node, null if its a Map or List + */ + public String getString(){ + return value; + } + /** + * @return the boolean value in this node + */ + public boolean getBoolean(){ + return Boolean.parseBoolean(value); + } + /** + * @return the integer value in this node + */ + public int getInt(){ + return Integer.parseInt(value); + } + /** + * @return the double value in this node + */ + public double getDouble(){ + return Double.parseDouble(value); + } + /** + * @return the long value in this node + */ + public long getLong(){ + return Long.parseLong(value); + } + + + public String toString(){ + if( this.isMap() ) + return map.toString(); + else if( this.isList() ) + return list.toString(); + return value; + } } diff --git a/src/zutil/parser/MathParser.java b/src/zutil/parser/MathParser.java index f90b47b..a4bfac4 100644 --- a/src/zutil/parser/MathParser.java +++ b/src/zutil/parser/MathParser.java @@ -36,222 +36,222 @@ import java.io.InputStreamReader; */ public class MathParser { - public static MathNode parse(String functionString){ - StringBuffer functionStringBuffer = new StringBuffer(functionString+(char)0); - MathNode node = new MathNode(); + public static MathNode parse(String functionString){ + StringBuffer functionStringBuffer = new StringBuffer(functionString+(char)0); + MathNode node = new MathNode(); - parse(functionStringBuffer, new StringBuffer(), null, node); + parse(functionStringBuffer, new StringBuffer(), null, node); - System.out.println("----------------------------------------------------------------------"); - System.out.println(node+" = "+node.exec()); - System.out.println("----------------------------------------------------------------------"); - return 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){ - return; - } - char c = functionString.charAt(0); - functionString.deleteCharAt(0); - System.out.println("char: "+c); - MathOperation current = null; + private static void parse(StringBuffer functionString, StringBuffer temp, MathOperation previus, 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)){ - temp.append(c); - } - else{ - Math container = new MathNumber(); - if(temp.length() > 0){ - System.out.println("("+Double.parseDouble(temp.toString())+")"); - ((MathNumber)container).num = Double.parseDouble(temp.toString()); - temp.delete(0, temp.length()); - } + if(!Character.isWhitespace(c)){ + if(isNumber(c)){ + temp.append(c); + } + else{ + Math container = new MathNumber(); + if(temp.length() > 0){ + System.out.println("("+Double.parseDouble(temp.toString())+")"); + ((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){ + 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; - // get the next operation - c = functionString.charAt(0); - functionString.deleteCharAt(0); - System.out.println("char: "+c); - } + // 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; + current = getOperation(c); + System.out.println("operation: "+current.getClass().getName()); + current.math1 = container; + previus.math2 = current; - if(c == ')'){ - return; - } - } - } - } + 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, previus, rootNode); + return; + } - private static boolean isNumber(char c){ - if(Character.isDigit(c)){ - return true; - } - return false; - } + private static boolean isNumber(char c){ + if(Character.isDigit(c)){ + return true; + } + return false; + } - 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; - } - } + 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; + } + } - public static void main(String[] args){ - try { - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - while(true){ - System.out.print(">>Math: "); - parse(in.readLine()); - } - } catch (IOException e) { - e.printStackTrace(); - } - } + public static void main(String[] args){ + try { + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + while(true){ + System.out.print(">>Math: "); + parse(in.readLine()); + } + } catch (IOException e) { + e.printStackTrace(); + } + } - static abstract class Math{ - public abstract double exec(); + static abstract class Math{ + public abstract double exec(); - public abstract String toString(); - } + public abstract String toString(); + } - static class MathNode extends Math{ - Math math; + static class MathNode extends Math{ + Math math; - public double exec() { - return math.exec(); - } + public double exec() { + return math.exec(); + } - public String toString() { - return "( "+math.toString()+" )"; - } - } + public String toString() { + return "( "+math.toString()+" )"; + } + } - static class MathNumber extends Math{ - double num; + static class MathNumber extends Math{ + double num; - public double exec() { - return num; - } + public double exec() { + return num; + } - public String toString() { - return ""+num; - } - } + public String toString() { + return ""+num; + } + } - static abstract class MathOperation extends Math{ - Math math1; - Math math2; + static abstract class MathOperation extends Math{ + Math math1; + Math math2; - public abstract double exec(); - } + public abstract double exec(); + } - static class MathAddition extends MathOperation{ - public double exec() { - return math1.exec() + math2.exec(); - } + static class MathAddition extends MathOperation{ + public double exec() { + return math1.exec() + math2.exec(); + } - public String toString() { - return math1.toString()+" + "+math2.toString(); - } - } + public String toString() { + return math1.toString()+" + "+math2.toString(); + } + } - static class MathSubtraction extends MathOperation{ - public double exec() { - return math1.exec() - math2.exec(); - } + static class MathSubtraction extends MathOperation{ + public double exec() { + return math1.exec() - math2.exec(); + } - public String toString() { - return math1.toString()+" - "+math2.toString(); - } - } + public String toString() { + return math1.toString()+" - "+math2.toString(); + } + } - static class MathMultiplication extends MathOperation{ - public double exec() { - return math1.exec() * math2.exec(); - } + static class MathMultiplication extends MathOperation{ + public double exec() { + return math1.exec() * math2.exec(); + } - public String toString() { - return math1.toString()+" * "+math2.toString(); - } - } + public String toString() { + return math1.toString()+" * "+math2.toString(); + } + } - static class MathDivision extends MathOperation{ - public double exec() { - return math1.exec() / math2.exec(); - } + static class MathDivision extends MathOperation{ + public double exec() { + return math1.exec() / math2.exec(); + } - public String toString() { - return math1.toString()+" / "+math2.toString(); - } - } + public String toString() { + return math1.toString()+" / "+math2.toString(); + } + } - static class MathModulus extends MathOperation{ - public double exec() { - return math1.exec() % math2.exec(); - } + static class MathModulus extends MathOperation{ + public double exec() { + return math1.exec() % math2.exec(); + } - public String toString() { - return math1.toString()+" % "+math2.toString(); - } - } + public String toString() { + return math1.toString()+" % "+math2.toString(); + } + } - static class MathPow extends MathOperation{ - public double exec() { - double ret = 1; - double tmp1 = math1.exec(); - double tmp2 = math2.exec(); - for(int i=0; i type, Object value) throws UnsupportedDataTypeException, IllegalArgumentException, IllegalAccessException { - DataNode node = null; + DataNode node = null; if (type == int.class || - type == Integer.class || - type == long.class || - type == Long.class || - type == double.class || - type == Double.class) - node = new DataNode(DataType.Number); + type == Integer.class || + type == long.class || + type == Long.class || + type == double.class || + type == Double.class) + node = new DataNode(DataType.Number); else if(type == boolean.class || - type == Boolean.class) - node = new DataNode(DataType.Boolean); + type == Boolean.class) + node = new DataNode(DataType.Boolean); else if(type == String.class || - type == char.class || - type == Character.class) - node = new DataNode(DataType.String); + type == char.class || + type == Character.class) + node = new DataNode(DataType.String); else - throw new UnsupportedDataTypeException("Unsupported primitive data type: "+type.getName()); + throw new UnsupportedDataTypeException("Unsupported primitive data type: "+type.getName()); if(value != null) - node.set(value.toString()); - return node; - } + node.set(value.toString()); + return node; + } /** * Enable or disables the use of meta data in the JSON diff --git a/src/zutil/parser/json/JSONParser.java b/src/zutil/parser/json/JSONParser.java index 9e51780..d22ebb6 100755 --- a/src/zutil/parser/json/JSONParser.java +++ b/src/zutil/parser/json/JSONParser.java @@ -43,10 +43,10 @@ public class JSONParser extends Parser { private static final int END_WITH_NULL = 1; private static final int END_WITH_VALUE = 2; // Regex for parsing primitives - private static final Pattern NUMBER_PATTERN = Pattern.compile("^[0-9.]++$"); - private static final Pattern BOOLEAN_PATTERN = Pattern.compile("^(true|false)$", Pattern.CASE_INSENSITIVE); + private static final Pattern NUMBER_PATTERN = Pattern.compile("^[0-9.]++$"); + private static final Pattern BOOLEAN_PATTERN = Pattern.compile("^(true|false)$", Pattern.CASE_INSENSITIVE); private static final Pattern NULL_PATTERN = Pattern.compile("^null$", Pattern.CASE_INSENSITIVE); - + private Reader in; @@ -68,20 +68,20 @@ public class JSONParser extends Parser { return parse(in, new MutableInt()); } - /** - * Starts parsing from a string - * - * @param json is the JSON String to parse - * @return a DataNode object representing the JSON in the input String - */ - public static DataNode read(String json){ + /** + * Starts parsing from a string + * + * @param json is the JSON String to parse + * @return a DataNode object representing the JSON in the input String + */ + public static DataNode read(String json){ try{ - return parse(new StringReader(json), new MutableInt()); + return parse(new StringReader(json), new MutableInt()); }catch (IOException e){ e.printStackTrace(); }catch (NullPointerException e){} return null; - } + } /** * This is the real recursive parsing method @@ -152,9 +152,9 @@ public class JSONParser extends Parser { if( NULL_PATTERN.matcher(data).matches() ) root = null; else if( BOOLEAN_PATTERN.matcher(data).matches() ) - root = new DataNode(DataType.Boolean); + root = new DataNode(DataType.Boolean); else if( NUMBER_PATTERN.matcher(data).matches() ) - root = new DataNode(DataType.Number); + root = new DataNode(DataType.Number); else { root = new DataNode(DataType.String); data = unEscapeString(data); diff --git a/src/zutil/parser/wsdl/WSDLWriter.java b/src/zutil/parser/wsdl/WSDLWriter.java index 52102c3..da15e93 100644 --- a/src/zutil/parser/wsdl/WSDLWriter.java +++ b/src/zutil/parser/wsdl/WSDLWriter.java @@ -48,10 +48,10 @@ public class WSDLWriter{ /** A list of services **/ private ArrayList services; - public WSDLWriter( WebServiceDef ws ){ + public WSDLWriter( WebServiceDef ws ){ this.services = new ArrayList(); - this.ws = ws; - } + this.ws = ws; + } /** * Add a service to be published with the WSDL @@ -62,177 +62,177 @@ public class WSDLWriter{ } - public void write( Writer out ) throws IOException { - out.write(generate()); - } - public void write( PrintStream out ) { - out.print(generate()); - } - public void write( OutputStream out ) throws IOException { - out.write(generate().getBytes() ); - } + public void write( Writer out ) throws IOException { + out.write(generate()); + } + public void write( PrintStream out ) { + out.print(generate()); + } + public void write( OutputStream out ) throws IOException { + out.write(generate().getBytes() ); + } - private String generate(){ - if(cache == null){ - try { - OutputFormat outformat = OutputFormat.createPrettyPrint(); - StringOutputStream out = new StringOutputStream(); - XMLWriter writer = new XMLWriter(out, outformat); + private String generate(){ + if(cache == null){ + try { + OutputFormat outformat = OutputFormat.createPrettyPrint(); + StringOutputStream out = new StringOutputStream(); + XMLWriter writer = new XMLWriter(out, outformat); - Document docroot = generateDefinition(); - writer.write(docroot); + Document docroot = generateDefinition(); + writer.write(docroot); - writer.flush(); - this.cache = out.toString(); - out.close(); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - return cache; - } + writer.flush(); + this.cache = out.toString(); + out.close(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return cache; + } - private Document generateDefinition(){ - Document wsdl = DocumentHelper.createDocument(); - Element definitions = wsdl.addElement("wsdl:definitions"); - definitions.addNamespace("wsdl", "http://schemas.xmlsoap.org/wsdl/"); - definitions.addNamespace("soap", "http://schemas.xmlsoap.org/wsdl/soap/"); - definitions.addNamespace("http", "http://schemas.xmlsoap.org/wsdl/http/"); - definitions.addNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); - definitions.addNamespace("soap-enc", "http://schemas.xmlsoap.org/soap/encoding/"); - definitions.addNamespace("tns", ws.getNamespace()+"?type"); - definitions.addAttribute("targetNamespace", ws.getNamespace()); + private Document generateDefinition(){ + Document wsdl = DocumentHelper.createDocument(); + Element definitions = wsdl.addElement("wsdl:definitions"); + definitions.addNamespace("wsdl", "http://schemas.xmlsoap.org/wsdl/"); + definitions.addNamespace("soap", "http://schemas.xmlsoap.org/wsdl/soap/"); + definitions.addNamespace("http", "http://schemas.xmlsoap.org/wsdl/http/"); + definitions.addNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); + definitions.addNamespace("soap-enc", "http://schemas.xmlsoap.org/soap/encoding/"); + definitions.addNamespace("tns", ws.getNamespace()+"?type"); + definitions.addAttribute("targetNamespace", ws.getNamespace()); - generateType(definitions); - generateMessages(definitions); - generatePortType(definitions); - generateBinding(definitions); - generateService(definitions); + generateType(definitions); + generateMessages(definitions); + generatePortType(definitions); + generateBinding(definitions); + generateService(definitions); - return wsdl; - } + return wsdl; + } - private void generateMessages(Element definitions){ - for( WSMethodDef method : ws.getMethods() ){ - generateMessage(definitions, method); - } + private void generateMessages(Element definitions){ + for( WSMethodDef method : ws.getMethods() ){ + generateMessage(definitions, method); + } - // Default message used for functions without input parameters - // definitions -> message: empty - Element empty = definitions.addElement("wsdl:message"); - empty.addAttribute("name", "empty"); - // definitions -> message: empty -> part - Element empty_part = empty.addElement("wsdl:part"); - empty_part.addAttribute("name", "empty"); - empty_part.addAttribute("type", "td:empty"); + // Default message used for functions without input parameters + // definitions -> message: empty + Element empty = definitions.addElement("wsdl:message"); + empty.addAttribute("name", "empty"); + // definitions -> message: empty -> part + Element empty_part = empty.addElement("wsdl:part"); + empty_part.addAttribute("name", "empty"); + empty_part.addAttribute("type", "td:empty"); - // Exception message - // definitions -> message: exception - Element exception = definitions.addElement("wsdl:message"); - exception.addAttribute("name", "exception"); - // definitions -> message: exception -> part - Element exc_part = exception.addElement("wsdl:part"); - exc_part.addAttribute("name", "exception"); - exc_part.addAttribute("type", "td:string"); - } + // Exception message + // definitions -> message: exception + Element exception = definitions.addElement("wsdl:message"); + exception.addAttribute("name", "exception"); + // definitions -> message: exception -> part + Element exc_part = exception.addElement("wsdl:part"); + exc_part.addAttribute("name", "exception"); + exc_part.addAttribute("type", "td:string"); + } - private void generateMessage(Element parent, WSMethodDef method){ - //*************************** Input - if( method.getInputCount() > 0 ){ - // definitions -> message - Element input = parent.addElement("wsdl:message"); - input.addAttribute("name", method.getName()+"Request"); + private void generateMessage(Element parent, WSMethodDef method){ + //*************************** Input + if( method.getInputCount() > 0 ){ + // definitions -> message + Element input = parent.addElement("wsdl:message"); + input.addAttribute("name", method.getName()+"Request"); - // Parameters - for( WSParameterDef param : method.getInputs() ){ - // definitions -> message -> part - Element part = input.addElement("wsdl:part"); - part.addAttribute("name", param.getName()); - part.addAttribute("type", "xsd:"+getClassName( param.getParamClass())); + // Parameters + for( WSParameterDef param : method.getInputs() ){ + // definitions -> message -> part + Element part = input.addElement("wsdl:part"); + part.addAttribute("name", param.getName()); + part.addAttribute("type", "xsd:"+getClassName( param.getParamClass())); - if( param.isOptional() ) - part.addAttribute("minOccurs", "0"); - } - } - //*************************** Output - if( method.getOutputCount() > 0 ){ - // definitions -> message - Element output = parent.addElement("wsdl:message"); - output.addAttribute("name", method.getName()+"Response"); + if( param.isOptional() ) + part.addAttribute("minOccurs", "0"); + } + } + //*************************** Output + if( method.getOutputCount() > 0 ){ + // definitions -> message + Element output = parent.addElement("wsdl:message"); + output.addAttribute("name", method.getName()+"Response"); - // Parameters - for( WSParameterDef param : method.getOutputs() ){ - // definitions -> message -> part - Element part = output.addElement("wsdl:part"); - part.addAttribute("name", param.getName()); + // Parameters + for( WSParameterDef param : method.getOutputs() ){ + // definitions -> message -> part + Element part = output.addElement("wsdl:part"); + part.addAttribute("name", param.getName()); - Class paramClass = param.getParamClass(); - Class valueClass = getClass( paramClass ); - // is an binary array - if(byte[].class.isAssignableFrom( paramClass )){ - part.addAttribute("type", "xsd:base64Binary"); - } - // is an array? - else if( paramClass.isArray()){ - part.addAttribute("type", "td:" +getArrayClassName(paramClass)); - } - else if( WSReturnObject.class.isAssignableFrom(valueClass) ){ - // its an SOAPObject - part.addAttribute("type", "td:"+getClassName( paramClass )); - } - else{// its an Object - part.addAttribute("type", "xsd:"+getClassName( paramClass )); - } - } - } - } + Class paramClass = param.getParamClass(); + Class valueClass = getClass( paramClass ); + // is an binary array + if(byte[].class.isAssignableFrom( paramClass )){ + part.addAttribute("type", "xsd:base64Binary"); + } + // is an array? + else if( paramClass.isArray()){ + part.addAttribute("type", "td:" +getArrayClassName(paramClass)); + } + else if( WSReturnObject.class.isAssignableFrom(valueClass) ){ + // its an SOAPObject + part.addAttribute("type", "td:"+getClassName( paramClass )); + } + else{// its an Object + part.addAttribute("type", "xsd:"+getClassName( paramClass )); + } + } + } + } - private void generatePortType(Element definitions){ - // definitions -> portType - Element portType = definitions.addElement("wsdl:portType"); - portType.addAttribute("name", ws.getName()+"PortType"); + private void generatePortType(Element definitions){ + // definitions -> portType + Element portType = definitions.addElement("wsdl:portType"); + portType.addAttribute("name", ws.getName()+"PortType"); - for( WSMethodDef method : ws.getMethods() ){ - // definitions -> portType -> operation - Element operation = portType.addElement("wsdl:operation"); - operation.addAttribute("name", method.getName()); + for( WSMethodDef method : ws.getMethods() ){ + // definitions -> portType -> operation + Element operation = portType.addElement("wsdl:operation"); + operation.addAttribute("name", method.getName()); - // Documentation - if(method.getDocumentation() != null){ - Element doc = operation.addElement("wsdl:documentation"); - doc.setText(method.getDocumentation()); - } + // Documentation + if(method.getDocumentation() != null){ + Element doc = operation.addElement("wsdl:documentation"); + doc.setText(method.getDocumentation()); + } - //*************************** Input - if( method.getInputCount() > 0 ){ - // definitions -> message - Element input = operation.addElement("wsdl:input"); - input.addAttribute("message", "tns:"+method.getName()+"Request"); - } - //*************************** Output - if( method.getOutputCount() > 0 ){ - // definitions -> message - Element output = operation.addElement("wsdl:output"); - output.addAttribute("message", "tns:"+method.getName()+"Response"); - } - //*************************** Fault - if( method.getOutputCount() > 0 ){ - // definitions -> message - Element fault = operation.addElement("wsdl:fault"); - fault.addAttribute("message", "tns:exception"); - } - } - } + //*************************** Input + if( method.getInputCount() > 0 ){ + // definitions -> message + Element input = operation.addElement("wsdl:input"); + input.addAttribute("message", "tns:"+method.getName()+"Request"); + } + //*************************** Output + if( method.getOutputCount() > 0 ){ + // definitions -> message + Element output = operation.addElement("wsdl:output"); + output.addAttribute("message", "tns:"+method.getName()+"Response"); + } + //*************************** Fault + if( method.getOutputCount() > 0 ){ + // definitions -> message + Element fault = operation.addElement("wsdl:fault"); + fault.addAttribute("message", "tns:exception"); + } + } + } - private void generateBinding(Element definitions){ - // definitions -> binding - Element binding = definitions.addElement("wsdl:binding"); - binding.addAttribute("name", ws.getName()+"Binding"); - binding.addAttribute("type", "tns:"+ws.getName()+"PortType"); + private void generateBinding(Element definitions){ + // definitions -> binding + Element binding = definitions.addElement("wsdl:binding"); + binding.addAttribute("name", ws.getName()+"Binding"); + binding.addAttribute("type", "tns:"+ws.getName()+"PortType"); for(WSDLService serv : services){ serv.generateBinding(binding); @@ -241,154 +241,154 @@ public class WSDLWriter{ serv.generateOperation(binding, method); } } - } + } - private void generateService(Element parent){ - // definitions -> service - Element root = parent.addElement("wsdl:service"); - root.addAttribute("name", ws.getName()+"Service"); + private void generateService(Element parent){ + // definitions -> service + Element root = parent.addElement("wsdl:service"); + root.addAttribute("name", ws.getName()+"Service"); - // definitions -> service -> port - Element port = root.addElement("wsdl:port"); - port.addAttribute("name", ws.getName()+"Port"); - port.addAttribute("binding", "tns:"+ws.getName()+"Binding"); + // definitions -> service -> port + Element port = root.addElement("wsdl:port"); + port.addAttribute("name", ws.getName()+"Port"); + port.addAttribute("binding", "tns:"+ws.getName()+"Binding"); for(WSDLService serv : services){ // definitions -> service-> port -> address Element address = port.addElement(serv.getServiceType()+":address"); address.addAttribute("location", serv.getServiceAddress()); } - } + } - /** - * This function generates the Type section of the WSDL. - *
    -	 * -wsdl:definitions
    -	 *     -wsdl:type
    -	 *  
    - */ - private void generateType(Element definitions){ - ArrayList> types = new ArrayList>(); - // Find types - for( WSMethodDef method : ws.getMethods() ){ - if( method.getOutputCount() > 0 ){ - for( WSParameterDef param : method.getOutputs() ){ - Class paramClass = param.getParamClass(); - Class valueClass = getClass(paramClass); - // is an array? or special class - if( paramClass.isArray() || WSReturnObject.class.isAssignableFrom(valueClass)){ - // add to type generation list - if(!types.contains( paramClass )) - types.add( paramClass ); - } - } - } - } + /** + * This function generates the Type section of the WSDL. + *
    +     * -wsdl:definitions
    +     *     -wsdl:type
    +     *  
    + */ + private void generateType(Element definitions){ + ArrayList> types = new ArrayList>(); + // Find types + for( WSMethodDef method : ws.getMethods() ){ + if( method.getOutputCount() > 0 ){ + for( WSParameterDef param : method.getOutputs() ){ + Class paramClass = param.getParamClass(); + Class valueClass = getClass(paramClass); + // is an array? or special class + if( paramClass.isArray() || WSReturnObject.class.isAssignableFrom(valueClass)){ + // add to type generation list + if(!types.contains( paramClass )) + types.add( paramClass ); + } + } + } + } - // definitions -> types - Element typeE = definitions.addElement("wsdl:types"); - Element schema = typeE.addElement("xsd:schema"); - schema.addAttribute("targetNamespace", ws.getNamespace()+"?type"); + // definitions -> types + Element typeE = definitions.addElement("wsdl:types"); + Element schema = typeE.addElement("xsd:schema"); + schema.addAttribute("targetNamespace", ws.getNamespace()+"?type"); - // empty type - Element empty = schema.addElement("xsd:complexType"); - empty.addAttribute("name", "empty"); - empty.addElement("xsd:sequence"); + // empty type + Element empty = schema.addElement("xsd:complexType"); + empty.addAttribute("name", "empty"); + empty.addElement("xsd:sequence"); - for(int n=0; n c = types.get(n); - // Generate Array type - if(c.isArray()){ - Class ctmp = getClass(c); + for(int n=0; n c = types.get(n); + // Generate Array type + if(c.isArray()){ + Class ctmp = getClass(c); - Element type = schema.addElement("xsd:complexType"); - type.addAttribute("name", getArrayClassName(c)); + Element type = schema.addElement("xsd:complexType"); + type.addAttribute("name", getArrayClassName(c)); - Element sequence = type.addElement("xsd:sequence"); + Element sequence = type.addElement("xsd:sequence"); - Element element = sequence.addElement("xsd:element"); - element.addAttribute("minOccurs", "0"); - element.addAttribute("maxOccurs", "unbounded"); - element.addAttribute("name", "element"); - element.addAttribute("nillable", "true"); - if( WSReturnObject.class.isAssignableFrom(ctmp) ) - element.addAttribute("type", "tns:"+getClassName(c).replace("[]", "")); - else - element.addAttribute("type", "xsd:"+getClassName(c).replace("[]", "")); + Element element = sequence.addElement("xsd:element"); + element.addAttribute("minOccurs", "0"); + element.addAttribute("maxOccurs", "unbounded"); + element.addAttribute("name", "element"); + element.addAttribute("nillable", "true"); + if( WSReturnObject.class.isAssignableFrom(ctmp) ) + element.addAttribute("type", "tns:"+getClassName(c).replace("[]", "")); + else + element.addAttribute("type", "xsd:"+getClassName(c).replace("[]", "")); - if(!types.contains(ctmp)) - types.add(ctmp); - } - // Generate SOAPObject type - else if(WSReturnObject.class.isAssignableFrom(c)){ - Element type = schema.addElement("xsd:complexType"); - type.addAttribute("name", getClassName(c)); + if(!types.contains(ctmp)) + types.add(ctmp); + } + // Generate SOAPObject type + else if(WSReturnObject.class.isAssignableFrom(c)){ + Element type = schema.addElement("xsd:complexType"); + type.addAttribute("name", getClassName(c)); - Element sequence = type.addElement("xsd:sequence"); + Element sequence = type.addElement("xsd:sequence"); - Field[] fields = c.getFields(); - for(int i=0; i cTmp = getClass(fields[i].getType()); - if( WSReturnObject.class.isAssignableFrom(cTmp) ){ - element.addAttribute("type", "tns:"+getClassName(cTmp)); - if(!types.contains(cTmp)) - types.add(cTmp); - } - else{ - element.addAttribute("type", "xsd:"+getClassName(fields[i].getType())); - } - // Is the Field optional - if(tmp != null && tmp.optional()) - element.addAttribute("minOccurs", "0"); - } - } - } - } + // Check if the object is an SOAPObject + Class cTmp = getClass(fields[i].getType()); + if( WSReturnObject.class.isAssignableFrom(cTmp) ){ + element.addAttribute("type", "tns:"+getClassName(cTmp)); + if(!types.contains(cTmp)) + types.add(cTmp); + } + else{ + element.addAttribute("type", "xsd:"+getClassName(fields[i].getType())); + } + // Is the Field optional + if(tmp != null && tmp.optional()) + element.addAttribute("minOccurs", "0"); + } + } + } + } - /////////////////////////////////////////////////////////////////////////////////////////////// - // TODO: FIX THESE ARE DUPLICATES FROM SOAPHttpPage - /////////////////////////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////////////////////////// + // TODO: FIX THESE ARE DUPLICATES FROM SOAPHttpPage + /////////////////////////////////////////////////////////////////////////////////////////////// - private Class getClass(Class c){ - if(c!=null && c.isArray()){ - return getClass(c.getComponentType()); - } - return c; - } + private Class getClass(Class c){ + if(c!=null && c.isArray()){ + return getClass(c.getComponentType()); + } + return c; + } - private String getArrayClassName(Class c){ - return "ArrayOf"+getClassName(c).replaceAll("[\\[\\]]", ""); - } + private String getArrayClassName(Class c){ + return "ArrayOf"+getClassName(c).replaceAll("[\\[\\]]", ""); + } - private String getClassName(Class c){ - Class cTmp = getClass(c); - if( byte[].class.isAssignableFrom(c) ){ - return "base64Binary"; - } - else if( WSReturnObject.class.isAssignableFrom(cTmp) ){ - return c.getSimpleName(); - } - else{ - String ret = c.getSimpleName().toLowerCase(); + private String getClassName(Class c){ + Class cTmp = getClass(c); + if( byte[].class.isAssignableFrom(c) ){ + return "base64Binary"; + } + else if( WSReturnObject.class.isAssignableFrom(cTmp) ){ + return c.getSimpleName(); + } + else{ + String ret = c.getSimpleName().toLowerCase(); - if( cTmp == Integer.class ) ret = ret.replaceAll("integer", "int"); - else if( cTmp == Character.class ) ret = ret.replaceAll("character", "char"); + if( cTmp == Integer.class ) ret = ret.replaceAll("integer", "int"); + else if( cTmp == Character.class ) ret = ret.replaceAll("character", "char"); - return ret; - } - } + return ret; + } + } - public void close() {} + public void close() {} } diff --git a/src/zutil/plugin/PluginData.java b/src/zutil/plugin/PluginData.java index 663babf..a6bd12e 100755 --- a/src/zutil/plugin/PluginData.java +++ b/src/zutil/plugin/PluginData.java @@ -39,138 +39,138 @@ import java.util.logging.Logger; * @author Ziver */ public class PluginData { - private static Logger log = LogUtil.getLogger(); + private static Logger log = LogUtil.getLogger(); - private double pluginVersion; - private String pluginName; - private HashMap, List>> classMap; - private HashMap objectMap; - - - protected PluginData(DataNode data) throws ClassNotFoundException, MalformedURLException { - classMap = new HashMap<>(); - objectMap = new HashMap(); - - pluginVersion = data.getDouble("version"); - pluginName = data.getString("name"); - log.fine("Plugin: " + this); - - DataNode node = data.get("interfaces"); - if(node.isMap()) - addInterfaces(node); - else if(node.isList()) { - Iterator intfs_it = node.iterator(); - while (intfs_it.hasNext()) { - addInterfaces(intfs_it.next()); - } - } - } - private void addInterfaces(DataNode node){ - Iterator intf_it = node.keyIterator(); - while (intf_it.hasNext()) { - String pluginIntf = intf_it.next(); - String className = node.get(pluginIntf).getString(); - - Class intfClass = getClassByName(pluginIntf); - Class pluginClass = getClassByName(className); - if (intfClass == null || pluginClass == null) - log.warning("Plugin interface: " + - (intfClass==null ? "(Not Available) " : "") + pluginIntf + " --> " + - (pluginClass==null ? "(Not Available) " : "") + className); - else - log.finer("Plugin interface: "+ pluginIntf +" --> "+ className); - - if (intfClass == null || pluginClass == null) - continue; - - if (!classMap.containsKey(intfClass)) - classMap.put(intfClass, new ArrayList>()); - classMap.get(intfClass).add(pluginClass); - } - } - private static Class getClassByName(String name) { - try { - return Class.forName(name); - }catch (Exception e){ - //log.log(Level.WARNING, null, e); // No need to log, we are handling it - } - return null; - } + private double pluginVersion; + private String pluginName; + private HashMap, List>> classMap; + private HashMap objectMap; - public double getVersion(){ - return pluginVersion; - } - public String getName(){ - return pluginName; - } + protected PluginData(DataNode data) throws ClassNotFoundException, MalformedURLException { + classMap = new HashMap<>(); + objectMap = new HashMap(); + + pluginVersion = data.getDouble("version"); + pluginName = data.getString("name"); + log.fine("Plugin: " + this); + + DataNode node = data.get("interfaces"); + if(node.isMap()) + addInterfaces(node); + else if(node.isList()) { + Iterator intfs_it = node.iterator(); + while (intfs_it.hasNext()) { + addInterfaces(intfs_it.next()); + } + } + } + private void addInterfaces(DataNode node){ + Iterator intf_it = node.keyIterator(); + while (intf_it.hasNext()) { + String pluginIntf = intf_it.next(); + String className = node.get(pluginIntf).getString(); + + Class intfClass = getClassByName(pluginIntf); + Class pluginClass = getClassByName(className); + if (intfClass == null || pluginClass == null) + log.warning("Plugin interface: " + + (intfClass==null ? "(Not Available) " : "") + pluginIntf + " --> " + + (pluginClass==null ? "(Not Available) " : "") + className); + else + log.finer("Plugin interface: "+ pluginIntf +" --> "+ className); + + if (intfClass == null || pluginClass == null) + continue; + + if (!classMap.containsKey(intfClass)) + classMap.put(intfClass, new ArrayList>()); + classMap.get(intfClass).add(pluginClass); + } + } + private static Class getClassByName(String name) { + try { + return Class.forName(name); + }catch (Exception e){ + //log.log(Level.WARNING, null, e); // No need to log, we are handling it + } + return null; + } - public Iterator getObjectIterator(Class intf){ - if(!classMap.containsKey(intf)) - return Collections.emptyIterator(); - return new PluginObjectIterator(classMap.get(intf).iterator()); - } - public Iterator> getClassIterator(Class intf){ - if(!classMap.containsKey(intf)) - return Collections.emptyIterator(); - return classMap.get(intf).iterator(); - } - - private T getObject(Class objClass) { - try { - if (!objectMap.containsKey(objClass)) - objectMap.put(objClass, objClass.newInstance()); - return (T) objectMap.get(objClass); - } catch (Exception e) { - log.log(Level.WARNING, null, e); - } - return null; - } + public double getVersion(){ + return pluginVersion; + } + public String getName(){ + return pluginName; + } - public boolean contains(Class intf){ - return classMap.containsKey(intf); - } + public Iterator getObjectIterator(Class intf){ + if(!classMap.containsKey(intf)) + return Collections.emptyIterator(); + return new PluginObjectIterator(classMap.get(intf).iterator()); + } + public Iterator> getClassIterator(Class intf){ + if(!classMap.containsKey(intf)) + return Collections.emptyIterator(); + return classMap.get(intf).iterator(); + } - public String toString(){ - return getName()+"(ver: "+getVersion()+")"; - } + private T getObject(Class objClass) { + try { + if (!objectMap.containsKey(objClass)) + objectMap.put(objClass, objClass.newInstance()); + return (T) objectMap.get(objClass); + } catch (Exception e) { + log.log(Level.WARNING, null, e); + } + return null; + } + + + public boolean contains(Class intf){ + return classMap.containsKey(intf); + } + + public String toString(){ + return getName()+"(ver: "+getVersion()+")"; + } - private class PluginObjectIterator implements Iterator{ - private Iterator> classIt; - private T currentObj; + private class PluginObjectIterator implements Iterator{ + private Iterator> classIt; + private T currentObj; - public PluginObjectIterator(Iterator> it) { - classIt = it; - } + public PluginObjectIterator(Iterator> it) { + classIt = it; + } - @Override - public boolean hasNext() { - if(currentObj != null) - return true; - while (classIt.hasNext()){ - currentObj = (T)getObject(classIt.next()); - if(currentObj != null) - return true; - } - return false; - } + @Override + public boolean hasNext() { + if(currentObj != null) + return true; + while (classIt.hasNext()){ + currentObj = (T)getObject(classIt.next()); + if(currentObj != null) + return true; + } + return false; + } - @Override - public T next() { - if(!hasNext()) - throw new NoSuchElementException(); - T tmp = currentObj; - currentObj = null; - return tmp; - } + @Override + public T next() { + if(!hasNext()) + throw new NoSuchElementException(); + T tmp = currentObj; + currentObj = null; + return tmp; + } - @Override - public void remove() { - throw new RuntimeException("Iterator is ReadOnly"); - } - } + @Override + public void remove() { + throw new RuntimeException("Iterator is ReadOnly"); + } + } } diff --git a/src/zutil/plugin/PluginManager.java b/src/zutil/plugin/PluginManager.java index efea874..67cc695 100755 --- a/src/zutil/plugin/PluginManager.java +++ b/src/zutil/plugin/PluginManager.java @@ -46,70 +46,70 @@ import java.util.logging.Logger; * @author Ziver */ public class PluginManager implements Iterable{ - private static Logger log = LogUtil.getLogger(); + private static Logger log = LogUtil.getLogger(); - private HashMap plugins; + private HashMap plugins; - public static PluginManager load(String path){ - return new PluginManager(path); - } + public static PluginManager load(String path){ + return new PluginManager(path); + } - public PluginManager(){ - this("./"); - } - public PluginManager(String path){ - plugins = new HashMap(); + public PluginManager(){ + this("./"); + } + public PluginManager(String path){ + plugins = new HashMap(); - FileSearcher search = new FileSearcher(new File(path)); - search.setRecursive(true); - search.searchFolders(false); - search.searchCompressedFiles(true); - search.setFileName("plugin.json"); + FileSearcher search = new FileSearcher(new File(path)); + search.setRecursive(true); + search.searchFolders(false); + search.searchCompressedFiles(true); + search.setFileName("plugin.json"); - log.fine("Searching for plugins..."); - for(FileSearcher.FileSearchItem file : search){ - try { - DataNode node = JSONParser.read(IOUtil.readContentAsString(file.getInputStream(), true)); - log.fine("Found plugin: "+file.getPath()); - PluginData plugin = new PluginData(node); + log.fine("Searching for plugins..."); + for(FileSearcher.FileSearchItem file : search){ + try { + DataNode node = JSONParser.read(IOUtil.readContentAsString(file.getInputStream(), true)); + log.fine("Found plugin: "+file.getPath()); + PluginData plugin = new PluginData(node); - if (!plugins.containsKey(plugin.getName())){ - plugins.put(plugin.getName(), plugin); - } - else { - double version = plugins.get(plugin.getName()).getVersion(); - if(version < plugin.getVersion()) - plugins.put(plugin.getName(), plugin); - else if(version == plugin.getVersion()) - log.fine("Ignoring duplicate plugin: " + plugin); - else - log.fine("Ignoring outdated plugin: "+plugin); + if (!plugins.containsKey(plugin.getName())){ + plugins.put(plugin.getName(), plugin); + } + else { + double version = plugins.get(plugin.getName()).getVersion(); + if(version < plugin.getVersion()) + plugins.put(plugin.getName(), plugin); + else if(version == plugin.getVersion()) + log.fine("Ignoring duplicate plugin: " + plugin); + else + log.fine("Ignoring outdated plugin: "+plugin); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - @Override - public Iterator iterator() { - return plugins.values().iterator(); - } - public Iterator getObjectIterator(Class intf) { - return new PluginObjectIterator(plugins.values().iterator(), intf); - } - public Iterator> getClassIterator(Class intf) { - return new PluginClassIterator(plugins.values().iterator(), intf); - } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } - public ArrayList toArray() { - return toGenericArray(iterator()); - } - public ArrayList toArray(Class intf) { + @Override + public Iterator iterator() { + return plugins.values().iterator(); + } + public Iterator getObjectIterator(Class intf) { + return new PluginObjectIterator(plugins.values().iterator(), intf); + } + public Iterator> getClassIterator(Class intf) { + return new PluginClassIterator(plugins.values().iterator(), intf); + } + + public ArrayList toArray() { + return toGenericArray(iterator()); + } + public ArrayList toArray(Class intf) { return toGenericArray(getObjectIterator(intf)); - } + } private ArrayList toGenericArray(Iterator it) { ArrayList list = new ArrayList<>(); while(it.hasNext()) @@ -118,82 +118,82 @@ public class PluginManager implements Iterable{ } - public static class PluginClassIterator implements Iterator> { - private Class intf; - private Iterator pluginIt; - private Iterator> classIt; + public static class PluginClassIterator implements Iterator> { + private Class intf; + private Iterator pluginIt; + private Iterator> classIt; - PluginClassIterator(Iterator it, Class intf){ - this.intf = intf; - this.pluginIt = it; - } + PluginClassIterator(Iterator it, Class intf){ + this.intf = intf; + this.pluginIt = it; + } - @Override - public boolean hasNext() { - if(pluginIt == null) - return false; - if(classIt != null && classIt.hasNext()) - return true; + @Override + public boolean hasNext() { + if(pluginIt == null) + return false; + if(classIt != null && classIt.hasNext()) + return true; - while(pluginIt.hasNext()) { - classIt = pluginIt.next().getClassIterator(intf); - if(classIt.hasNext()) - return true; - } - classIt = null; - return false; - } + while(pluginIt.hasNext()) { + classIt = pluginIt.next().getClassIterator(intf); + if(classIt.hasNext()) + return true; + } + classIt = null; + return false; + } - @Override - public Class next() { - if(!hasNext()) - throw new NoSuchElementException(); - return (Class) classIt.next(); - } + @Override + public Class next() { + if(!hasNext()) + throw new NoSuchElementException(); + return (Class) classIt.next(); + } - @Override - public void remove() { - throw new RuntimeException("Iterator is ReadOnly"); - } - } + @Override + public void remove() { + throw new RuntimeException("Iterator is ReadOnly"); + } + } - public static class PluginObjectIterator implements Iterator { - private Class intf; - private Iterator pluginIt; - private Iterator objectIt; + public static class PluginObjectIterator implements Iterator { + private Class intf; + private Iterator pluginIt; + private Iterator objectIt; - PluginObjectIterator(Iterator it, Class intf){ - this.intf = intf; - this.pluginIt = it; - } + PluginObjectIterator(Iterator it, Class intf){ + this.intf = intf; + this.pluginIt = it; + } - @Override - public boolean hasNext() { - if(pluginIt == null) - return false; - if(objectIt != null && objectIt.hasNext()) - return true; + @Override + public boolean hasNext() { + if(pluginIt == null) + return false; + if(objectIt != null && objectIt.hasNext()) + return true; - while(pluginIt.hasNext()) { - objectIt = pluginIt.next().getObjectIterator(intf); - if(objectIt.hasNext()) - return true; - } - objectIt = null; - return false; - } + while(pluginIt.hasNext()) { + objectIt = pluginIt.next().getObjectIterator(intf); + if(objectIt.hasNext()) + return true; + } + objectIt = null; + return false; + } - @Override - public T next() { - if(!hasNext()) - throw new NoSuchElementException(); - return objectIt.next(); - } + @Override + public T next() { + if(!hasNext()) + throw new NoSuchElementException(); + return objectIt.next(); + } - @Override - public void remove() { - throw new RuntimeException("Iterator is ReadOnly"); - } - } + @Override + public void remove() { + throw new RuntimeException("Iterator is ReadOnly"); + } + } } \ No newline at end of file diff --git a/src/zutil/plugin/plugin.json.example b/src/zutil/plugin/plugin.json.example index 5af4f95..e783b42 100644 --- a/src/zutil/plugin/plugin.json.example +++ b/src/zutil/plugin/plugin.json.example @@ -1,8 +1,8 @@ { - "version": 1.0, - "name": "Nice name of Plugin", - "interfaces": [ - {"plugin.interface.class": "plugin.implementation.class"}, - {"wa.server.plugin.WAFrontend": "wa.server.plugin.apache.ApacheFrontend"} - ] + "version": 1.0, + "name": "Nice name of Plugin", + "interfaces": [ + {"plugin.interface.class": "plugin.implementation.class"}, + {"wa.server.plugin.WAFrontend": "wa.server.plugin.apache.ApacheFrontend"} + ] } \ No newline at end of file diff --git a/src/zutil/struct/HistoryList.java b/src/zutil/struct/HistoryList.java index 8a25e42..c7cb7ae 100644 --- a/src/zutil/struct/HistoryList.java +++ b/src/zutil/struct/HistoryList.java @@ -29,101 +29,101 @@ import java.util.LinkedList; public class HistoryList implements Iterable{ - public int history_length; - private LinkedList history; - private int historyIndex = 0; - - /** - * Creates an HistoryList object - */ - public HistoryList(){ - this( Integer.MAX_VALUE ); - } - - /** - * Creates an HistoryList object with an max size - * - * @param histlength the maximum size of the list - */ - public HistoryList(int histlength){ - history_length = histlength; - history = new LinkedList(); - } - - /** - * Returns the item in the given index - * - * @param i is the index - * @return item in that index - */ - public T get(int i){ - return history.get( i ); - } - - /** - * Adds an item to the list and removes the last if - * the list is bigger than the max length. - * - * @param item is the item to add - */ - public void add(T item){ - while(historyIndex < history.size()-1){ - history.removeLast(); - } - history.addLast(item); - if(history_length < history.size()){ - history.removeFirst(); - } - - historyIndex = history.size()-1; - } - - /** - * @return the previous item in the list - */ - public T getPrevious(){ - if(historyIndex > 0){ - historyIndex -= 1; - } - else{ - historyIndex = 0; - } - return history.get(historyIndex); - } - - /** - * @return the next item in the list - */ - public T getNext(){ - if(next()){ - historyIndex += 1; - } - else{ - historyIndex = history.size()-1; - } - return history.get(historyIndex); - } - - public T getCurrent(){ - return history.get(historyIndex); - } - - /** - * @return if there are items newer than the current - */ - public boolean next(){ - if(historyIndex < history.size()-1){ - return true; - } - else{ - return false; - } - } - - /** - * @return an iterator of the list - */ - public Iterator iterator(){ - return history.iterator(); - } + public int history_length; + private LinkedList history; + private int historyIndex = 0; + + /** + * Creates an HistoryList object + */ + public HistoryList(){ + this( Integer.MAX_VALUE ); + } + + /** + * Creates an HistoryList object with an max size + * + * @param histlength the maximum size of the list + */ + public HistoryList(int histlength){ + history_length = histlength; + history = new LinkedList(); + } + + /** + * Returns the item in the given index + * + * @param i is the index + * @return item in that index + */ + public T get(int i){ + return history.get( i ); + } + + /** + * Adds an item to the list and removes the last if + * the list is bigger than the max length. + * + * @param item is the item to add + */ + public void add(T item){ + while(historyIndex < history.size()-1){ + history.removeLast(); + } + history.addLast(item); + if(history_length < history.size()){ + history.removeFirst(); + } + + historyIndex = history.size()-1; + } + + /** + * @return the previous item in the list + */ + public T getPrevious(){ + if(historyIndex > 0){ + historyIndex -= 1; + } + else{ + historyIndex = 0; + } + return history.get(historyIndex); + } + + /** + * @return the next item in the list + */ + public T getNext(){ + if(next()){ + historyIndex += 1; + } + else{ + historyIndex = history.size()-1; + } + return history.get(historyIndex); + } + + public T getCurrent(){ + return history.get(historyIndex); + } + + /** + * @return if there are items newer than the current + */ + public boolean next(){ + if(historyIndex < history.size()-1){ + return true; + } + else{ + return false; + } + } + + /** + * @return an iterator of the list + */ + public Iterator iterator(){ + return history.iterator(); + } } diff --git a/src/zutil/struct/MutableInt.java b/src/zutil/struct/MutableInt.java index d293b1d..9fe7e7c 100644 --- a/src/zutil/struct/MutableInt.java +++ b/src/zutil/struct/MutableInt.java @@ -31,11 +31,11 @@ package zutil.struct; * @author Ziver */ public class MutableInt { - public int i = 0; - - public MutableInt(){} - - public MutableInt(int i){ - this.i = i; - } + public int i = 0; + + public MutableInt(){} + + public MutableInt(int i){ + this.i = i; + } } diff --git a/src/zutil/ui/Console.java b/src/zutil/ui/Console.java index e41f54b..a3caecd 100644 --- a/src/zutil/ui/Console.java +++ b/src/zutil/ui/Console.java @@ -45,271 +45,271 @@ import java.io.PrintStream; * */ public class Console{ - public static String DEFAULT_ICON = "zutil/data/JavaConsole.png"; - // UI things - private JFrame frame; - private JTextPane console; - private Document doc; - private TrayIcon trayIcon; - private int bufferSize; + public static String DEFAULT_ICON = "zutil/data/JavaConsole.png"; + // UI things + private JFrame frame; + private JTextPane console; + private Document doc; + private TrayIcon trayIcon; + private int bufferSize; - public Console(String title){ - this(title, 680, 340, 50000, false); - } + public Console(String title){ + this(title, 680, 340, 50000, false); + } - public Console(String title, boolean tray){ - this(title, 680, 340, 50000, tray); - } + public Console(String title, boolean tray){ + this(title, 680, 340, 50000, tray); + } - public Console(String title, int width, int height, int buffer, boolean tray){ - ConsoleInputStream in = new ConsoleInputStream(); - DEFAULT_ICON = FileUtil.find(DEFAULT_ICON).getAbsolutePath(); - initUI(title, in); + public Console(String title, int width, int height, int buffer, boolean tray){ + ConsoleInputStream in = new ConsoleInputStream(); + DEFAULT_ICON = FileUtil.find(DEFAULT_ICON).getAbsolutePath(); + initUI(title, in); - bufferSize = buffer; - System.setOut(new ConsolePrintStream(System.out, Color.white)); - System.setErr(new ConsolePrintStream(System.out, Color.red, TrayIcon.MessageType.ERROR)); - System.setIn(in); + bufferSize = buffer; + System.setOut(new ConsolePrintStream(System.out, Color.white)); + System.setErr(new ConsolePrintStream(System.out, Color.red, TrayIcon.MessageType.ERROR)); + System.setIn(in); - enableTray(tray); - setFrameIcon(Toolkit.getDefaultToolkit().getImage(DEFAULT_ICON)); - frame.setSize(width, height); - frame.setVisible(true); - } + enableTray(tray); + setFrameIcon(Toolkit.getDefaultToolkit().getImage(DEFAULT_ICON)); + frame.setSize(width, height); + frame.setVisible(true); + } - /** - * initiates the ui - */ - private void initUI(String title, KeyListener listener){ - frame = new JFrame(title); + /** + * initiates the ui + */ + private void initUI(String title, KeyListener listener){ + frame = new JFrame(title); - console = new JTextPane(); - console.setBackground(Color.black); - console.setForeground(Color.white); - console.setFont(new Font("Lucida Console", Font.BOLD, 11)); - console.setEditable(false); - console.addKeyListener(listener); - doc = new DefaultStyledDocument(); - console.setDocument(doc); + console = new JTextPane(); + console.setBackground(Color.black); + console.setForeground(Color.white); + console.setFont(new Font("Lucida Console", Font.BOLD, 11)); + console.setEditable(false); + console.addKeyListener(listener); + doc = new DefaultStyledDocument(); + console.setDocument(doc); - JScrollPane scroll = new JScrollPane(console, - JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + JScrollPane scroll = new JScrollPane(console, + JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, + JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - frame.add(scroll, BorderLayout.CENTER); - } + frame.add(scroll, BorderLayout.CENTER); + } - public void setIcon(){ + public void setIcon(){ - } + } - public void appendConsole(String s, Style style){ - try { - doc.insertString(doc.getLength(), s, style); - if(doc.getLength() > bufferSize){ - doc.remove(0, doc.getLength() - bufferSize); - } - } catch (BadLocationException e) { - e.printStackTrace(); - } - } + public void appendConsole(String s, Style style){ + try { + doc.insertString(doc.getLength(), s, style); + if(doc.getLength() > bufferSize){ + doc.remove(0, doc.getLength() - bufferSize); + } + } catch (BadLocationException e) { + e.printStackTrace(); + } + } - /** - * Enables the tray icon and sets the icon - * @param img The image to use as the icon - */ - public void setTrayIcon(Image img){ - enableTray(true); - trayIcon.setImage(img); - } + /** + * Enables the tray icon and sets the icon + * @param img The image to use as the icon + */ + public void setTrayIcon(Image img){ + enableTray(true); + trayIcon.setImage(img); + } - /** - * Sets the icon for the Frame - * - * @param img The image to use as a icon - */ - public void setFrameIcon(Image img){ - frame.setIconImage(img); - } + /** + * Sets the icon for the Frame + * + * @param img The image to use as a icon + */ + public void setFrameIcon(Image img){ + frame.setIconImage(img); + } - /** - * Enables the go down to tray functionality - * - * @param enable if tray icon is enabled - */ - public void enableTray(boolean enable){ - if(enable && SystemTray.isSupported()){ - frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); - SystemTray tray = SystemTray.getSystemTray(); + /** + * Enables the go down to tray functionality + * + * @param enable if tray icon is enabled + */ + public void enableTray(boolean enable){ + if(enable && SystemTray.isSupported()){ + frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); + SystemTray tray = SystemTray.getSystemTray(); - if(trayIcon == null){ - // Menu - PopupMenu menu = new PopupMenu(); - MenuItem item = new MenuItem("Open"); - item.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - frame.setVisible(true); - } - }); - menu.add(item); - menu.addSeparator(); - item = new MenuItem("Exit"); - item.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - System.exit(0); - } - }); - menu.add(item); + if(trayIcon == null){ + // Menu + PopupMenu menu = new PopupMenu(); + MenuItem item = new MenuItem("Open"); + item.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + frame.setVisible(true); + } + }); + menu.add(item); + menu.addSeparator(); + item = new MenuItem("Exit"); + item.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + System.exit(0); + } + }); + menu.add(item); - // Icon - trayIcon = new TrayIcon( - Toolkit.getDefaultToolkit().getImage(DEFAULT_ICON), - "Console", menu); - trayIcon.setImageAutoSize(true); - trayIcon.addMouseListener(new MouseListener(){ - public void mouseClicked(MouseEvent e) { - if(e.getClickCount() == 2) - frame.setVisible(true); - } - public void mouseEntered(MouseEvent e) {} - public void mouseExited(MouseEvent e) {} - public void mousePressed(MouseEvent e) {} - public void mouseReleased(MouseEvent e) {} - }); - } + // Icon + trayIcon = new TrayIcon( + Toolkit.getDefaultToolkit().getImage(DEFAULT_ICON), + "Console", menu); + trayIcon.setImageAutoSize(true); + trayIcon.addMouseListener(new MouseListener(){ + public void mouseClicked(MouseEvent e) { + if(e.getClickCount() == 2) + frame.setVisible(true); + } + public void mouseEntered(MouseEvent e) {} + public void mouseExited(MouseEvent e) {} + public void mousePressed(MouseEvent e) {} + public void mouseReleased(MouseEvent e) {} + }); + } - try { - tray.add(trayIcon); - } catch (AWTException e) { - System.err.println("TrayIcon could not be added."); - } - } - else{ - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - SystemTray.getSystemTray().remove(trayIcon); - } - } + try { + tray.add(trayIcon); + } catch (AWTException e) { + System.err.println("TrayIcon could not be added."); + } + } + else{ + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + SystemTray.getSystemTray().remove(trayIcon); + } + } - /** - * The Stream to replace System.out - * - * @author Ziver - * - * TrayIcon.MessageType.ERROR An error message - * TrayIcon.MessageType.INFO An information message - * TrayIcon.MessageType.NONE A simple message - * TrayIcon.MessageType.WARNING A warning message - */ - private class ConsolePrintStream extends PrintStream{ - private Style style; - private MessageType trayMessageType; + /** + * The Stream to replace System.out + * + * @author Ziver + * + * TrayIcon.MessageType.ERROR An error message + * TrayIcon.MessageType.INFO An information message + * TrayIcon.MessageType.NONE A simple message + * TrayIcon.MessageType.WARNING A warning message + */ + private class ConsolePrintStream extends PrintStream{ + private Style style; + private MessageType trayMessageType; - public ConsolePrintStream(OutputStream out, Color c) { - this(out, c, null); - } - - public ConsolePrintStream(OutputStream out, Color c, MessageType type) { - super(out); - style = console.addStyle("PrintStream", null); - StyleConstants.setForeground(style, c); - trayMessageType = type; - } + public ConsolePrintStream(OutputStream out, Color c) { + this(out, c, null); + } - public void print(String s){ - appendConsole(s, style); - console.setCaretPosition(console.getDocument().getLength()); - if(trayMessageType != null && trayIcon != null){ - trayIcon.displayMessage( - s.substring(0, (s.length() > 25 ? 25 : s.length()))+"...", - s, trayMessageType); + public ConsolePrintStream(OutputStream out, Color c, MessageType type) { + super(out); + style = console.addStyle("PrintStream", null); + StyleConstants.setForeground(style, c); + trayMessageType = type; + } - } - } + public void print(String s){ + appendConsole(s, style); + console.setCaretPosition(console.getDocument().getLength()); + if(trayMessageType != null && trayIcon != null){ + trayIcon.displayMessage( + s.substring(0, (s.length() > 25 ? 25 : s.length()))+"...", + s, trayMessageType); - public void println(String s){ - print(s+"\n"); - } + } + } - public void println(){ println("");} - public void println(boolean x){ println(""+x);} - public void println(char x){ println(""+x);} - public void println(char[] x){ println(new String(x));} - public void println(double x){ println(""+x);} - public void println(float x){ println(""+x);} - public void println(int x){ println(""+x);} - public void println(long x){ println(""+x);} - public void println(Object x){ println(""+x);} + public void println(String s){ + print(s+"\n"); + } - public void print(boolean x){ print(""+x);} - public void print(char x){ print(""+x);} - public void print(char[] x){ print(new String(x));} - public void print(double x){ print(""+x);} - public void print(float x){ print(""+x);} - public void print(int x){ print(""+x);} - public void print(long x){ print(""+x);} - public void print(Object x){ print(""+x);} - } + public void println(){ println("");} + public void println(boolean x){ println(""+x);} + public void println(char x){ println(""+x);} + public void println(char[] x){ println(new String(x));} + public void println(double x){ println(""+x);} + public void println(float x){ println(""+x);} + public void println(int x){ println(""+x);} + public void println(long x){ println(""+x);} + public void println(Object x){ println(""+x);} - private class ConsoleInputStream extends InputStream implements KeyListener{ - private boolean read = false; - private int input; + public void print(boolean x){ print(""+x);} + public void print(char x){ print(""+x);} + public void print(char[] x){ print(new String(x));} + public void print(double x){ print(""+x);} + public void print(float x){ print(""+x);} + public void print(int x){ print(""+x);} + public void print(long x){ print(""+x);} + public void print(Object x){ print(""+x);} + } - @Override - public int read() throws IOException { - if(input < 0) { - input = 0; - return -1; - } - - read = true; - input = 0; - while(input == 0){ - try {Thread.sleep(10);} catch (InterruptedException e) {} - } - read = false; - - System.out.print((char)input); - if(input == KeyEvent.VK_ENTER){ - input = -1; - return '\n'; - } - return input; - } - /* - @Override - public int read(byte[] b) throws IOException { - return read(b, 0, b.length); - } + private class ConsoleInputStream extends InputStream implements KeyListener{ + private boolean read = false; + private int input; - @Override - public int read(byte[] b, int off, int len) throws IOException { - System.out.println(off+"-"+len); - int i; - for(i=-1; i pages; - /** HashMap containing all the selected values */ - private HashMap values; - /** The general component listener */ - private WizardActionHandler handler; - /** This is the user listener that handles all the values after the wizard */ - private WizardListener listener; - - /** This is the old validation fail, this is needed for reseting purposes */ - private ValidationFail oldFail; - + /** Some defoult backgrounds for the sidebar */ + public static final String BACKGROUND_1 = "zutil/data/wizard1.jpg"; + public static final String BACKGROUND_2 = "zutil/data/wizard2.jpg"; + public static final String BACKGROUND_3 = "zutil/data/wizard3.png"; - private Wizard(WizardListener listener){ - this(listener, null); - } + /** An list with all the previous pages and the current at the beginning */ + private HistoryList pages; + /** HashMap containing all the selected values */ + private HashMap values; + /** The general component listener */ + private WizardActionHandler handler; + /** This is the user listener that handles all the values after the wizard */ + private WizardListener listener; - /** - * Creates a new Wizard - */ - public Wizard(WizardListener listener, WizardPage start){ - this(listener, start, BACKGROUND_1); - } + /** This is the old validation fail, this is needed for reseting purposes */ + private ValidationFail oldFail; - /** - * Creates a new Wizard - * - * @param start is the first page in the wizard - * @param bg is the background image to use - */ - public Wizard(WizardListener listener, final WizardPage start, final String bg){ - try { - this.listener = listener; - pages = new HistoryList(); - values = new HashMap(); - handler = new WizardActionHandler( values ); - // GUI - frame = new JFrame(); - initComponents(); - sidebar.scale( false ); - - // add action listener to the buttons - back.addActionListener( this ); - next.addActionListener( this ); - cancel.addActionListener( this ); - finish.addActionListener( this ); - - // Set the image in the sidebar - sidebar.setImage(ImageIO.read( FileUtil.getInputStream( bg ) )); - - // add the first page - pages.add( start ); - displayWizardPage( start ); + private Wizard(WizardListener listener){ + this(listener, null); + } - } catch (Exception e) { - e.printStackTrace(MultiPrintStream.out); - } - } + /** + * Creates a new Wizard + */ + public Wizard(WizardListener listener, WizardPage start){ + this(listener, start, BACKGROUND_1); + } - /** - * Sets the title of the Wizard - */ - public void setTitle(String s){ - frame.setTitle(s); - } - - /** - * Sets the size of the Wizard frame - * - * @param w is the width - * @param h is the height - */ - public void setSize(int w, int h){ - frame.setSize(w, h); - } + /** + * Creates a new Wizard + * + * @param start is the first page in the wizard + * @param bg is the background image to use + */ + public Wizard(WizardListener listener, final WizardPage start, final String bg){ + try { + this.listener = listener; + pages = new HistoryList(); + values = new HashMap(); + handler = new WizardActionHandler( values ); - /** - * Displays the wizard - */ - public void start(){ - frame.setVisible(true); - } - - /** - * @return the JFrame used for the wizard - */ - public JFrame getFrame(){ - return frame; - } - - /** - * Set the current WizardPage - * - * @param page is the page to be displayed - */ - protected void displayWizardPage(WizardPage page){ - pageContainer.getViewport().setView(page); - pageTitle.setText( page.getPageDescription() ); - } + // GUI + frame = new JFrame(); + initComponents(); + sidebar.scale( false ); + + // add action listener to the buttons + back.addActionListener( this ); + next.addActionListener( this ); + cancel.addActionListener( this ); + finish.addActionListener( this ); + + // Set the image in the sidebar + sidebar.setImage(ImageIO.read( FileUtil.getInputStream( bg ) )); + + // add the first page + pages.add( start ); + displayWizardPage( start ); + + } catch (Exception e) { + e.printStackTrace(MultiPrintStream.out); + } + } + + /** + * Sets the title of the Wizard + */ + public void setTitle(String s){ + frame.setTitle(s); + } + + /** + * Sets the size of the Wizard frame + * + * @param w is the width + * @param h is the height + */ + public void setSize(int w, int h){ + frame.setSize(w, h); + } + + /** + * Displays the wizard + */ + public void start(){ + frame.setVisible(true); + } + + /** + * @return the JFrame used for the wizard + */ + public JFrame getFrame(){ + return frame; + } + + /** + * Set the current WizardPage + * + * @param page is the page to be displayed + */ + protected void displayWizardPage(WizardPage page){ + pageContainer.getViewport().setView(page); + pageTitle.setText( page.getPageDescription() ); + } + + public void actionPerformed(ActionEvent e) { + // Back Button + if(e.getSource() == back){ + WizardPage page = pages.getPrevious(); + displayWizardPage( page ); + if(pages.get(0) == page){ + back.setEnabled( false ); + } + } + // Next Button and Finish Button + else if(e.getSource() == next || e.getSource() == finish){ + WizardPage page = pages.getCurrent(); + page.registerValues( handler ); + if(DEBUG) MultiPrintStream.out.println(values); + + ValidationFail fail = page.validate( values ); + if(fail != null){ + // reset old fail + if(oldFail != null) oldFail.getSource().setBorder( BorderFactory.createEmptyBorder() ); + if(fail.getSource() != null) + fail.getSource().setBorder( BorderFactory.createLineBorder(Color.RED) ); + //pageStatus.setText( fail.getMessage() ); + } + else if(e.getSource() == finish){ + frame.dispose(); + listener.onFinished( values ); + } + else if(e.getSource() == next){ + WizardPage nextPage = page.getNextPage( values ); + if(nextPage == null){ + frame.dispose(); + listener.onCancel(page, values ); + return; + } + pages.add( nextPage ); + displayWizardPage( nextPage ); + back.setEnabled( true ); + if( nextPage.isFinalPage() ){ + next.setEnabled( false ); + finish.setEnabled( true ); + } + } + } + // Cancel Button + else if(e.getSource() == cancel){ + frame.dispose(); + listener.onCancel(pages.getCurrent(), values ); + } + } - public void actionPerformed(ActionEvent e) { - // Back Button - if(e.getSource() == back){ - WizardPage page = pages.getPrevious(); - displayWizardPage( page ); - if(pages.get(0) == page){ - back.setEnabled( false ); - } - } - // Next Button and Finish Button - else if(e.getSource() == next || e.getSource() == finish){ - WizardPage page = pages.getCurrent(); - page.registerValues( handler ); - if(DEBUG) MultiPrintStream.out.println(values); - - ValidationFail fail = page.validate( values ); - if(fail != null){ - // reset old fail - if(oldFail != null) oldFail.getSource().setBorder( BorderFactory.createEmptyBorder() ); - if(fail.getSource() != null) - fail.getSource().setBorder( BorderFactory.createLineBorder(Color.RED) ); - //pageStatus.setText( fail.getMessage() ); - } - else if(e.getSource() == finish){ - frame.dispose(); - listener.onFinished( values ); - } - else if(e.getSource() == next){ - WizardPage nextPage = page.getNextPage( values ); - if(nextPage == null){ - frame.dispose(); - listener.onCancel(page, values ); - return; - } - pages.add( nextPage ); - displayWizardPage( nextPage ); - back.setEnabled( true ); - if( nextPage.isFinalPage() ){ - next.setEnabled( false ); - finish.setEnabled( true ); - } - } - } - // Cancel Button - else if(e.getSource() == cancel){ - frame.dispose(); - listener.onCancel(pages.getCurrent(), values ); - } - } - private void initComponents() { cancel = new JButton(); @@ -328,31 +328,31 @@ public class Wizard implements ActionListener{ } - /** - * @param args the command line arguments - */ - public static void main(String args[]) { - final BlockingWizardListener listener = new BlockingWizardListener(); - EventQueue.invokeLater(new Runnable() { - public void run() { - Wizard wizard = new Wizard(listener); - wizard.start(); - } - }); - MultiPrintStream.out.dump( listener.getValues() ); + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + final BlockingWizardListener listener = new BlockingWizardListener(); + EventQueue.invokeLater(new Runnable() { + public void run() { + Wizard wizard = new Wizard(listener); + wizard.start(); + } + }); + MultiPrintStream.out.dump( listener.getValues() ); - } + } - // Variables declaration - do not modify - private JLabel error; - private JButton back; - private JButton cancel; - private JButton finish; - private JButton next; - private JScrollPane pageContainer; - private JLabel pageTitle; - private JImagePanel sidebar; - private JFrame frame; - // End of variables declaration + // Variables declaration - do not modify + private JLabel error; + private JButton back; + private JButton cancel; + private JButton finish; + private JButton next; + private JScrollPane pageContainer; + private JLabel pageTitle; + private JImagePanel sidebar; + private JFrame frame; + // End of variables declaration } diff --git a/src/zutil/ui/wizard/WizardListener.java b/src/zutil/ui/wizard/WizardListener.java index 4111e62..24d8a7d 100644 --- a/src/zutil/ui/wizard/WizardListener.java +++ b/src/zutil/ui/wizard/WizardListener.java @@ -28,18 +28,18 @@ import java.util.HashMap; public interface WizardListener { - /** - * Will be called when the cancel button is pressed - * - * @param page is the WizardPage where the cancel button was pressed - * @param values is the values until now - */ - public void onCancel(WizardPage page, HashMap values); - - /** - * Will be called when the wizard is finished - * - * @param values is the values until now - */ - public void onFinished(HashMap values); + /** + * Will be called when the cancel button is pressed + * + * @param page is the WizardPage where the cancel button was pressed + * @param values is the values until now + */ + void onCancel(WizardPage page, HashMap values); + + /** + * Will be called when the wizard is finished + * + * @param values is the values until now + */ + void onFinished(HashMap values); } diff --git a/src/zutil/ui/wizard/WizardPage.java b/src/zutil/ui/wizard/WizardPage.java index 7b63b78..445c81e 100644 --- a/src/zutil/ui/wizard/WizardPage.java +++ b/src/zutil/ui/wizard/WizardPage.java @@ -35,78 +35,78 @@ import java.util.LinkedList; * @author Ziver */ public abstract class WizardPage extends JPanel{ - private static final long serialVersionUID = 1L; - - /** contains the components whom values will be saved */ - private LinkedList components; - /** if this is the last page in the wizard */ - private boolean lastPage = false; - - public WizardPage(){ - components = new LinkedList(); - } + private static final long serialVersionUID = 1L; - /** - * Register a component whom the value will be saved with - * the key that is what getName returns from the component - * and passed on to the other pages. - * - * @param c is the component - */ - public void registerComponent(Component c){ - components.add( c ); - } - - /** - * Sets if this is the last page in the wizard, - * Should be called as early as possible. - */ - public void setFinalPage(boolean b){ - lastPage = b; - } - - /** - * @return is this is the last page in the wizard - */ - public boolean isFinalPage(){ - return lastPage; - } - - /** - * @return the next page in the wizard, - * is called when the next button is pressed, - * return null to end the wizard - */ - public abstract WizardPage getNextPage(HashMap values); - - /** - * @return a very short description of this page - */ - public abstract String getPageDescription(); - - - /** - * This method is called when the next button is pressed - * and the input values are going to be validated. - * - * @param values is the values until now - * @return a ValidateFail object or null if the validation passed - */ - public ValidationFail validate(HashMap values){ - return null; - } - - /** - * Will be called after the validation passes and will - * save all the states of the registered components - * - * @param listener is the object that handles the save process - */ - public void registerValues(WizardActionHandler listener){ - for(Component c : components){ - listener.registerValue( c ); - } - } + /** contains the components whom values will be saved */ + private LinkedList components; + /** if this is the last page in the wizard */ + private boolean lastPage = false; + + public WizardPage(){ + components = new LinkedList(); + } + + /** + * Register a component whom the value will be saved with + * the key that is what getName returns from the component + * and passed on to the other pages. + * + * @param c is the component + */ + public void registerComponent(Component c){ + components.add( c ); + } + + /** + * Sets if this is the last page in the wizard, + * Should be called as early as possible. + */ + public void setFinalPage(boolean b){ + lastPage = b; + } + + /** + * @return is this is the last page in the wizard + */ + public boolean isFinalPage(){ + return lastPage; + } + + /** + * @return the next page in the wizard, + * is called when the next button is pressed, + * return null to end the wizard + */ + public abstract WizardPage getNextPage(HashMap values); + + /** + * @return a very short description of this page + */ + public abstract String getPageDescription(); + + + /** + * This method is called when the next button is pressed + * and the input values are going to be validated. + * + * @param values is the values until now + * @return a ValidateFail object or null if the validation passed + */ + public ValidationFail validate(HashMap values){ + return null; + } + + /** + * Will be called after the validation passes and will + * save all the states of the registered components + * + * @param listener is the object that handles the save process + */ + public void registerValues(WizardActionHandler listener){ + for(Component c : components){ + listener.registerValue( c ); + } + } } /** @@ -115,37 +115,37 @@ public abstract class WizardPage extends JPanel{ * @author Ziver */ class ValidationFail{ - /** The component that failed the validation */ - private JComponent source; - /** An message to the user about the fault */ - private String msg; - - /** - * 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){ - this(null, msg); - } - - /** - * 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(JComponent c, String msg){ - this.source = c; - this.msg = msg; - } - - public JComponent getSource(){ - return source; - } - - public String getMessage(){ - return msg; - } + /** The component that failed the validation */ + private JComponent source; + /** An message to the user about the fault */ + private String msg; + + /** + * 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){ + this(null, msg); + } + + /** + * 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(JComponent c, String msg){ + this.source = c; + this.msg = msg; + } + + public JComponent getSource(){ + return source; + } + + public String getMessage(){ + return msg; + } } diff --git a/src/zutil/ui/wizard/listener/BlockingWizardListener.java b/src/zutil/ui/wizard/listener/BlockingWizardListener.java index 30b0e9b..0bf6501 100644 --- a/src/zutil/ui/wizard/listener/BlockingWizardListener.java +++ b/src/zutil/ui/wizard/listener/BlockingWizardListener.java @@ -32,38 +32,38 @@ import java.util.HashMap; /** * This listener class will block until the wizard is finished * and than return the values of the wizard - * + * * @author Ziver */ public class BlockingWizardListener implements WizardListener{ - private HashMap values; + private HashMap values; - /** - * Will block until the wizard is finished - * - * @return the values with a extra parameter "canceled" set - * as a boolean if the wizard was canceled and "canceledPage" - * witch is the page where the cancel button was pressed - */ - public HashMap getValues(){ - while(values == null){ - try{ - Thread.sleep(100); - }catch(Exception e){} - } - return values; - } + /** + * Will block until the wizard is finished + * + * @return the values with a extra parameter "canceled" set + * as a boolean if the wizard was canceled and "canceledPage" + * witch is the page where the cancel button was pressed + */ + public HashMap getValues(){ + while(values == null){ + try{ + Thread.sleep(100); + }catch(Exception e){} + } + return values; + } - public void onCancel(WizardPage page, HashMap values) { - values.put("canceled", Boolean.TRUE); - values.put("canceledPage", page); - this.values = values; - } + public void onCancel(WizardPage page, HashMap values) { + values.put("canceled", Boolean.TRUE); + values.put("canceledPage", page); + this.values = values; + } - public void onFinished(HashMap values) { - values.put("canceled", Boolean.FALSE); - this.values = values; - } + public void onFinished(HashMap values) { + values.put("canceled", Boolean.FALSE); + this.values = values; + } } diff --git a/src/zutil/ui/wizard/page/SummaryPage.java b/src/zutil/ui/wizard/page/SummaryPage.java index 0a73eb8..5ed2b9f 100755 --- a/src/zutil/ui/wizard/page/SummaryPage.java +++ b/src/zutil/ui/wizard/page/SummaryPage.java @@ -37,34 +37,34 @@ import java.util.HashMap; * */ public class SummaryPage extends WizardPage{ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public SummaryPage(HashMap values){ - this.setFinalPage( true ); - - JTextArea summary = new JTextArea(); - summary.setEditable(false); - summary.setEnabled(false); - this.add( summary ); - - StringBuffer tmp = new StringBuffer(); - for(String key : values.keySet()){ - tmp.append(key); - tmp.append(": "); - tmp.append(values.get( key )); - tmp.append("\n"); - } - summary.setText( tmp.toString() ); - } - - @Override - public WizardPage getNextPage(HashMap values) { - return null; - } + public SummaryPage(HashMap values){ + this.setFinalPage( true ); - @Override - public String getPageDescription() { - return "Summary"; - } + JTextArea summary = new JTextArea(); + summary.setEditable(false); + summary.setEnabled(false); + this.add( summary ); + + StringBuffer tmp = new StringBuffer(); + for(String key : values.keySet()){ + tmp.append(key); + tmp.append(": "); + tmp.append(values.get( key )); + tmp.append("\n"); + } + summary.setText( tmp.toString() ); + } + + @Override + public WizardPage getNextPage(HashMap values) { + return null; + } + + @Override + public String getPageDescription() { + return "Summary"; + } } diff --git a/src/zutil/wrapper/SerializableBufferedImage.java b/src/zutil/wrapper/SerializableBufferedImage.java index 9f2e96a..1f161ea 100644 --- a/src/zutil/wrapper/SerializableBufferedImage.java +++ b/src/zutil/wrapper/SerializableBufferedImage.java @@ -32,27 +32,27 @@ import java.io.ObjectOutputStream; import java.io.Serializable; public class SerializableBufferedImage implements Serializable{ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private BufferedImage image; + private BufferedImage image; - public SerializableBufferedImage(BufferedImage image){ - this.image = image; - } - - public BufferedImage getImage(){ - return image; - } - - public void setImage(BufferedImage image){ - this.image=image; - } + public SerializableBufferedImage(BufferedImage image){ + this.image = image; + } - private void writeObject(ObjectOutputStream out)throws IOException{ - ImageIO.write(image,"jpeg",ImageIO.createImageOutputStream(out)); - } + public BufferedImage getImage(){ + return image; + } - private void readObject(ObjectInputStream in)throws IOException, ClassNotFoundException{ - image = ImageIO.read(ImageIO.createImageInputStream(in)); - } + public void setImage(BufferedImage image){ + this.image=image; + } + + private void writeObject(ObjectOutputStream out)throws IOException{ + ImageIO.write(image,"jpeg",ImageIO.createImageOutputStream(out)); + } + + private void readObject(ObjectInputStream in)throws IOException, ClassNotFoundException{ + image = ImageIO.read(ImageIO.createImageInputStream(in)); + } } diff --git a/test/zutil/EncrypterTest.java b/test/zutil/EncrypterTest.java index 40352e0..1c091a7 100755 --- a/test/zutil/EncrypterTest.java +++ b/test/zutil/EncrypterTest.java @@ -31,24 +31,24 @@ import static org.junit.Assert.assertEquals; public class EncrypterTest { - public static final String data = "Hello there, wats yor name, my is a secret, 123456789"; + public static final String data = "Hello there, wats yor name, my is a secret, 123456789"; public static final String key = "abcdefghijklmnopqrstuvwxyz"; - @Test - public void encryptDES() throws Exception { - Encrypter.randomizeSalt(); - Encrypter encrypter = new Encrypter(key, Algorithm.DES); - Encrypter decrypter = new Encrypter(key, Algorithm.DES); + @Test + public void encryptDES() throws Exception { + Encrypter.randomizeSalt(); + Encrypter encrypter = new Encrypter(key, Algorithm.DES); + Encrypter decrypter = new Encrypter(key, Algorithm.DES); assertEquals(data, encryptDecrypt(encrypter, decrypter, data)); - } + } - @Test - public void encryptBLOWFISH() throws Exception { - Encrypter.randomizeSalt(); + @Test + public void encryptBLOWFISH() throws Exception { + Encrypter.randomizeSalt(); Encrypter encrypter = new Encrypter(Algorithm.Blowfish); - Encrypter.randomizeSalt(); + Encrypter.randomizeSalt(); Encrypter decrypter = new Encrypter(encrypter.getKey()); assertEquals(data, encryptDecrypt(encrypter, decrypter, data)); diff --git a/test/zutil/HasherTest.java b/test/zutil/HasherTest.java index 03a54d4..fbb6154 100755 --- a/test/zutil/HasherTest.java +++ b/test/zutil/HasherTest.java @@ -30,22 +30,22 @@ import static org.junit.Assert.assertEquals; public class HasherTest { - - @Test - public void MD5Test(){ - assertEquals(Hasher.MD5("AAAABBBB"), "9da4fc50e09e5eeb8ae8149ef4f23792"); - assertEquals(Hasher.MD5("qwerty12345"), "85064efb60a9601805dcea56ec5402f7"); - assertEquals(Hasher.MD5("123456789"), "25f9e794323b453885f5181f1b624d0b"); - //assertEquals(Hasher.MD5(".,<>|!#�%&/()=?"), "20d5cda029514fa49a8bbe854a539847"); - assertEquals(Hasher.MD5("Test45"), "fee43a4c9d88769e14ec6a1d8b80f2e7"); - } - - @Test - public void SHA1Test(){ - assertEquals(Hasher.SHA1("AAAABBBB"), "7cd188ef3a9ea7fa0ee9c62c168709695460f5c0"); - assertEquals(Hasher.SHA1("qwerty12345"), "4e17a448e043206801b95de317e07c839770c8b8"); - assertEquals(Hasher.SHA1("123456789"), "f7c3bc1d808e04732adf679965ccc34ca7ae3441"); - //assertEquals(Hasher.SHA1(".,<>|!#�%&/()=?"), "6b3de029cdb367bb365d5154a197294ee590a77a"); - assertEquals(Hasher.SHA1("Test45"), "9194c6e64a6801e24e63a924d5843a46428d2b3a"); - } + + @Test + public void MD5Test(){ + assertEquals(Hasher.MD5("AAAABBBB"), "9da4fc50e09e5eeb8ae8149ef4f23792"); + assertEquals(Hasher.MD5("qwerty12345"), "85064efb60a9601805dcea56ec5402f7"); + assertEquals(Hasher.MD5("123456789"), "25f9e794323b453885f5181f1b624d0b"); + //assertEquals(Hasher.MD5(".,<>|!#�%&/()=?"), "20d5cda029514fa49a8bbe854a539847"); + assertEquals(Hasher.MD5("Test45"), "fee43a4c9d88769e14ec6a1d8b80f2e7"); + } + + @Test + public void SHA1Test(){ + assertEquals(Hasher.SHA1("AAAABBBB"), "7cd188ef3a9ea7fa0ee9c62c168709695460f5c0"); + assertEquals(Hasher.SHA1("qwerty12345"), "4e17a448e043206801b95de317e07c839770c8b8"); + assertEquals(Hasher.SHA1("123456789"), "f7c3bc1d808e04732adf679965ccc34ca7ae3441"); + //assertEquals(Hasher.SHA1(".,<>|!#�%&/()=?"), "6b3de029cdb367bb365d5154a197294ee590a77a"); + assertEquals(Hasher.SHA1("Test45"), "9194c6e64a6801e24e63a924d5843a46428d2b3a"); + } } diff --git a/test/zutil/StringUtilTest.java b/test/zutil/StringUtilTest.java index b8300bf..1b8a1c5 100755 --- a/test/zutil/StringUtilTest.java +++ b/test/zutil/StringUtilTest.java @@ -33,50 +33,50 @@ import static org.junit.Assert.assertEquals; public class StringUtilTest { - @Test - public void formatByteSizeToStringTest() { - assertEquals( "100.0 B", StringUtil.formatByteSizeToString(100) ); - assertEquals( "9.7 kB", StringUtil.formatByteSizeToString(10000) ); - } + @Test + public void formatByteSizeToStringTest() { + assertEquals( "100.0 B", StringUtil.formatByteSizeToString(100) ); + assertEquals( "9.7 kB", StringUtil.formatByteSizeToString(10000) ); + } - @Test - 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 ) ); - assertEquals( "2 months 2 days 2 hours 2 min 2 sec 2 milisec ", - StringUtil.formatTimeToString( (2629743830l+86400000+3600000+60000+1000+1)*2 ) ); - } - - @Test - public void trimTest() { - assertEquals( "", StringUtil.trim("", ' ') ); - assertEquals( "aa", StringUtil.trim(" aa ", ' ') ); - assertEquals( "aa", StringUtil.trim("aa ", ' ') ); - assertEquals( "aa", StringUtil.trim(" aa", ' ') ); - assertEquals( "", StringUtil.trim(" aa ", 'a') ); - assertEquals( "aa", StringUtil.trim("\u0010 aa ", ' ') ); - assertEquals( "aa", StringUtil.trim("\n\naa\n\t", ' ') ); - assertEquals( "aa", StringUtil.trim("\"aa\"", '\"') ); - } + @Test + 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 ) ); + assertEquals( "2 months 2 days 2 hours 2 min 2 sec 2 milisec ", + StringUtil.formatTimeToString( (2629743830l+86400000+3600000+60000+1000+1)*2 ) ); + } - @Test - public void trimQuotesTest() { - assertEquals( "", StringUtil.trimQuotes("") ); - assertEquals( "\"", StringUtil.trimQuotes("\"") ); - assertEquals( "", StringUtil.trimQuotes("\"\"") ); - assertEquals( "\"aa", StringUtil.trimQuotes("\"aa") ); - assertEquals( "aa\"", StringUtil.trimQuotes("aa\"") ); - assertEquals( "aa", StringUtil.trimQuotes("\"aa\"") ); - } + @Test + public void trimTest() { + assertEquals( "", StringUtil.trim("", ' ') ); + assertEquals( "aa", StringUtil.trim(" aa ", ' ') ); + assertEquals( "aa", StringUtil.trim("aa ", ' ') ); + assertEquals( "aa", StringUtil.trim(" aa", ' ') ); + assertEquals( "", StringUtil.trim(" aa ", 'a') ); + assertEquals( "aa", StringUtil.trim("\u0010 aa ", ' ') ); + assertEquals( "aa", StringUtil.trim("\n\naa\n\t", ' ') ); + assertEquals( "aa", StringUtil.trim("\"aa\"", '\"') ); + } - @Test - public void joinTest(){ - assertEquals("", StringUtil.join(",", Arrays.asList())); - 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))); + @Test + public void trimQuotesTest() { + assertEquals( "", StringUtil.trimQuotes("") ); + assertEquals( "\"", StringUtil.trimQuotes("\"") ); + assertEquals( "", StringUtil.trimQuotes("\"\"") ); + assertEquals( "\"aa", StringUtil.trimQuotes("\"aa") ); + assertEquals( "aa\"", StringUtil.trimQuotes("aa\"") ); + assertEquals( "aa", StringUtil.trimQuotes("\"aa\"") ); + } + + @Test + public void joinTest(){ + assertEquals("", StringUtil.join(",", Arrays.asList())); + 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")); assertEquals("animal,monkey,dog", StringUtil.join(",", Arrays.asList("animal", "monkey", "dog"))); assertEquals("12345", StringUtil.join("", 1,2,3,4,5)); - } + } } diff --git a/test/zutil/algo/search/QuickSelectTest.java b/test/zutil/algo/search/QuickSelectTest.java index b591006..085e0c0 100755 --- a/test/zutil/algo/search/QuickSelectTest.java +++ b/test/zutil/algo/search/QuickSelectTest.java @@ -33,21 +33,21 @@ import java.util.Arrays; * TODO: Convert to JUnit */ public class QuickSelectTest { - public static void main(String[] args){ - int[] array = {1,3,4,6,3,2,98,5,7,8,543,2,4,5,8,9,5,2,3,5,7,5,3,2,6,8,5,324,8,6}; - //int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,17,18,19,20}; - - long time = System.currentTimeMillis(); - int median = (Integer)QuickSelect.find(new SortableIntArray(array), array.length/2); - System.out.println("QuickSelection("+(System.currentTimeMillis()-time)+"ms): "+median); - - time = System.currentTimeMillis(); - Arrays.sort(array); - System.out.println("RightAnswer("+(System.currentTimeMillis()-time)+"ms): "+array[array.length/2]); - - System.out.println("Sorted Array("+array.length+"): "); - for(int i=0; i array[i]){ - error = i; - } - } - - if(error >= 0){ - System.out.println("\nArray not sorted!! ("+array[error-1]+" > "+array[error]+")"); - } - System.out.println("\nTime: "+time+" ms"); - } + public static void main(String[] args){ + int[] array = new int[SIZE]; + + for(int i=0; i array[i]){ + error = i; + } + } + + if(error >= 0){ + System.out.println("\nArray not sorted!! ("+array[error-1]+" > "+array[error]+")"); + } + System.out.println("\nTime: "+time+" ms"); + } } diff --git a/test/zutil/converter/ConverterTest.java b/test/zutil/converter/ConverterTest.java index 0b8042c..ba392a5 100755 --- a/test/zutil/converter/ConverterTest.java +++ b/test/zutil/converter/ConverterTest.java @@ -32,23 +32,23 @@ import static org.junit.Assert.assertEquals; public class ConverterTest { - @Test - public void testHexToByte() { - assertEquals( (byte)1, Converter.hexToByte('1') ); - assertEquals( (byte)5, Converter.hexToByte('5') ); - assertEquals( (byte)10, Converter.hexToByte('A') ); - assertEquals( (byte)10, Converter.hexToByte('a') ); - } - - @Test - public void testHexToByte2() { - assertEquals( 0x00, Converter.hexToByte('0','0') ); - assertEquals( 0x11, Converter.hexToByte('1','1') ); - assertEquals( 0x75, Converter.hexToByte('7','5') ); - assertEquals( 0xDA, Converter.hexToByte('D','A') & 0xFF ); - assertEquals( 0xFA, Converter.hexToByte('F','a') & 0xFF ); - assertEquals( 0xFF, Converter.hexToByte('f','f') & 0xFF ); - } + @Test + public void testHexToByte() { + assertEquals( (byte)1, Converter.hexToByte('1') ); + assertEquals( (byte)5, Converter.hexToByte('5') ); + assertEquals( (byte)10, Converter.hexToByte('A') ); + assertEquals( (byte)10, Converter.hexToByte('a') ); + } + + @Test + public void testHexToByte2() { + assertEquals( 0x00, Converter.hexToByte('0','0') ); + assertEquals( 0x11, Converter.hexToByte('1','1') ); + assertEquals( 0x75, Converter.hexToByte('7','5') ); + assertEquals( 0xDA, Converter.hexToByte('D','A') & 0xFF ); + assertEquals( 0xFA, Converter.hexToByte('F','a') & 0xFF ); + assertEquals( 0xFF, Converter.hexToByte('f','f') & 0xFF ); + } @Test public void testHexStringToByte() { @@ -61,42 +61,42 @@ public class ConverterTest { assertArrayEquals( new byte[]{(byte)0xF1,0x10}, Converter.hexToByte("F11") ); } - @Test - public void testUrlEncode() { - assertEquals( "fas8dg7%20a0d1%2313f9g8d7%200h9a%25h0", - Converter.urlEncode("fas8dg7 a0d1#13f9g8d7 0h9a%h0") ); - assertEquals( "9i34%202y9252%25%2623%20463765(%2f%26(", - Converter.urlEncode("9i34 2y9252%&23 463765(/&(") ); - - } - - @Test - public void testUrlDecode() { - assertEquals( "fas8dg7 a0d1#13f9g8d7 0h9a%h0", - Converter.urlDecode("fas8dg7%20a0d1%2313f9g8d7%200h9a%25h0") ); - assertEquals( "9i34 2y9252%&23 463765(/&(", - Converter.urlDecode("9i34%202y9252%25%2623%20463765(%2f%26(") ); - } + @Test + public void testUrlEncode() { + assertEquals( "fas8dg7%20a0d1%2313f9g8d7%200h9a%25h0", + Converter.urlEncode("fas8dg7 a0d1#13f9g8d7 0h9a%h0") ); + assertEquals( "9i34%202y9252%25%2623%20463765(%2f%26(", + Converter.urlEncode("9i34 2y9252%&23 463765(/&(") ); + + } + + @Test + public void testUrlDecode() { + assertEquals( "fas8dg7 a0d1#13f9g8d7 0h9a%h0", + Converter.urlDecode("fas8dg7%20a0d1%2313f9g8d7%200h9a%25h0") ); + assertEquals( "9i34 2y9252%&23 463765(/&(", + Converter.urlDecode("9i34%202y9252%25%2623%20463765(%2f%26(") ); + } - @Test - public void byteArrayToInt(){ - assertEquals(0, Converter.toInt(new byte[]{})); - assertEquals(1, Converter.toInt(new byte[]{0b0000_0001})); - assertEquals(1, Converter.toInt(new byte[]{0x01,0x00})); - assertEquals(256, Converter.toInt(new byte[]{0x00,0x01,0x00})); - assertEquals(-1, Converter.toInt(new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF})); - assertEquals(Integer.MAX_VALUE, Converter.toInt(new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0x7F})); - assertEquals(Integer.MAX_VALUE, Converter.toInt(new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0x7F, (byte)0xFF,(byte)0xFF})); - } + @Test + public void byteArrayToInt(){ + assertEquals(0, Converter.toInt(new byte[]{})); + assertEquals(1, Converter.toInt(new byte[]{0b0000_0001})); + assertEquals(1, Converter.toInt(new byte[]{0x01,0x00})); + assertEquals(256, Converter.toInt(new byte[]{0x00,0x01,0x00})); + assertEquals(-1, Converter.toInt(new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF})); + assertEquals(Integer.MAX_VALUE, Converter.toInt(new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0x7F})); + assertEquals(Integer.MAX_VALUE, Converter.toInt(new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0x7F, (byte)0xFF,(byte)0xFF})); + } - @Test - public void intToByteArray(){ - assertArrayEquals(new byte[]{0x00,0x00,0x00,0x00}, Converter.toBytes(0)); - assertArrayEquals(new byte[]{0x01,0x00,0x00,0x00}, Converter.toBytes(1)); - assertArrayEquals(new byte[]{0x00,0x01,0x00,0x00}, Converter.toBytes(256)); - assertArrayEquals(new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF}, Converter.toBytes(-1)); - assertArrayEquals(new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0x7F}, Converter.toBytes(Integer.MAX_VALUE)); - assertArrayEquals(new byte[]{(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x80}, Converter.toBytes(Integer.MIN_VALUE)); - } + @Test + public void intToByteArray(){ + assertArrayEquals(new byte[]{0x00,0x00,0x00,0x00}, Converter.toBytes(0)); + assertArrayEquals(new byte[]{0x01,0x00,0x00,0x00}, Converter.toBytes(1)); + assertArrayEquals(new byte[]{0x00,0x01,0x00,0x00}, Converter.toBytes(256)); + assertArrayEquals(new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF}, Converter.toBytes(-1)); + assertArrayEquals(new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0x7F}, Converter.toBytes(Integer.MAX_VALUE)); + assertArrayEquals(new byte[]{(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x80}, Converter.toBytes(Integer.MIN_VALUE)); + } } diff --git a/test/zutil/converter/NumberToWordsConverterTest.java b/test/zutil/converter/NumberToWordsConverterTest.java index 8765d60..f2929c6 100755 --- a/test/zutil/converter/NumberToWordsConverterTest.java +++ b/test/zutil/converter/NumberToWordsConverterTest.java @@ -39,57 +39,57 @@ import static org.junit.Assert.assertThat; @RunWith(Parameterized.class) public class NumberToWordsConverterTest { - - @Parameters - public static Collection parameters() { - Object[][] data = new Object[][] { - {-77, "minus seventy seven"} - , {-2, "minus two"} - , {1, "one"} - , {0, "zero"} - , {7, "seven"} - , {11, "eleven"} - , {12, "twelve"} - , {17, "seventeen"} - , {20, "twenty"} - , {21, "twenty one"} - , {23, "twenty three"} - , {25, "twenty five"} - , {30, "thirty"} - , {34, "thirty four"} - , {50, "fifty"} - , {70, "seventy"} - , {100, "one hundred"} - , {110, "one hundred ten"} - , {131, "one hundred thirty one"} - , {222, "two hundred twenty two"} - , {1000, "one thousand"} - , {10_000, "ten thousand"} - , {100_000, "one hundred thousand"} - , {1000_000, "one million"} - , {10_000_000, "ten million"} - , {Integer.MAX_VALUE, "two billion one hundred forty seven million four hundred eighty three thousand six hundred forty seven"} - , {Integer.MIN_VALUE, "minus two billion one hundred forty seven million four hundred eighty three thousand six hundred forty eight"} - }; - return Arrays.asList(data); - } - - - private int input; - private String expected; - - public NumberToWordsConverterTest(int input, String expected) { - this.input = input; - this.expected = expected; - } + @Parameters + public static Collection parameters() { + Object[][] data = new Object[][] { + {-77, "minus seventy seven"} + , {-2, "minus two"} + , {1, "one"} + , {0, "zero"} + , {7, "seven"} + , {11, "eleven"} + , {12, "twelve"} + , {17, "seventeen"} + , {20, "twenty"} + , {21, "twenty one"} + , {23, "twenty three"} + , {25, "twenty five"} + , {30, "thirty"} + , {34, "thirty four"} + , {50, "fifty"} + , {70, "seventy"} + , {100, "one hundred"} + , {110, "one hundred ten"} + , {131, "one hundred thirty one"} + , {222, "two hundred twenty two"} + , {1000, "one thousand"} + , {10_000, "ten thousand"} + , {100_000, "one hundred thousand"} + , {1000_000, "one million"} + , {10_000_000, "ten million"} + , {Integer.MAX_VALUE, "two billion one hundred forty seven million four hundred eighty three thousand six hundred forty seven"} + , {Integer.MIN_VALUE, "minus two billion one hundred forty seven million four hundred eighty three thousand six hundred forty eight"} + }; + return Arrays.asList(data); + } - @Test - public void testConvert() { - assertThat(new NumberToWordsConverter().convert(input) - , is(equalTo(expected))); - } + + private int input; + private String expected; + + + public NumberToWordsConverterTest(int input, String expected) { + this.input = input; + this.expected = expected; + } + + @Test + public void testConvert() { + assertThat(new NumberToWordsConverter().convert(input) + , is(equalTo(expected))); + } } - - + + diff --git a/test/zutil/db/DBConnectionTest.java b/test/zutil/db/DBConnectionTest.java index 147503b..4fcb43e 100755 --- a/test/zutil/db/DBConnectionTest.java +++ b/test/zutil/db/DBConnectionTest.java @@ -31,31 +31,31 @@ import java.sql.PreparedStatement; public class DBConnectionTest { - public static void main(String[] args){ - try { - DBConnection db = new DBConnection("koc.se","db","user","password"); - - // Query 1 - PreparedStatement sql = db.getPreparedStatement("SELECT ?"); - sql.setInt(1, 1); - DBConnection.exec(sql); - - // Query 2 - db.exec("UPDATE ..."); - - // Query 3 - 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()); - System.out.println( s2 ); - - db.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } + public static void main(String[] args){ + try { + DBConnection db = new DBConnection("koc.se","db","user","password"); + + // Query 1 + PreparedStatement sql = db.getPreparedStatement("SELECT ?"); + sql.setInt(1, 1); + DBConnection.exec(sql); + + // Query 2 + db.exec("UPDATE ..."); + + // Query 3 + 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()); + System.out.println( s2 ); + + db.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/test/zutil/db/SQLQueryTest.java b/test/zutil/db/SQLQueryTest.java index 7adf7b5..081796e 100755 --- a/test/zutil/db/SQLQueryTest.java +++ b/test/zutil/db/SQLQueryTest.java @@ -31,90 +31,90 @@ import static org.junit.Assert.assertEquals; public class SQLQueryTest { - @Test - public void selectTest() { - assertEquals( "SELECT * FROM test1", - ""+SQLQuery.SELECT().FROM("test1") ); - assertEquals( "SELECT * FROM test1", - ""+SQLQuery.SELECT("*").FROM("test1") ); - assertEquals( "SELECT test1,test2 FROM test1", - ""+SQLQuery.SELECT("test1","test2").FROM("test1") ); - } - @Test - public void selectJoinTest() { - assertEquals( "SELECT * FROM test1 JOIN test2", - ""+SQLQuery.SELECT("*").FROM("test1").JOIN("test2") ); - assertEquals( "SELECT * FROM test1 NATURAL JOIN test2", - ""+SQLQuery.SELECT("*").FROM("test1").NATURAL_JOIN("test2") ); - assertEquals( "SELECT * FROM test1 UNION test2", - ""+SQLQuery.SELECT("*").FROM("test1").UNION("test2") ); - assertEquals( "SELECT * FROM test1 JOIN test2 NATURAL JOIN test3 UNION test4", - ""+SQLQuery.SELECT("*").FROM("test1").JOIN("test2").NATURAL_JOIN("test3").UNION("test4") ); - - assertEquals( "SELECT * FROM test1 NATURAL JOIN test2 NATURAL JOIN test3 NATURAL JOIN test4", - ""+SQLQuery.SELECT("*").FROM().NATURAL_JOIN("test1","test2","test3","test4") ); - assertEquals( "SELECT * FROM test1 JOIN test2 JOIN test3 JOIN test4", - ""+SQLQuery.SELECT("*").FROM().JOIN("test1","test2","test3","test4") ); - assertEquals( "SELECT * FROM test1 UNION test2 UNION test3 UNION test4", - ""+SQLQuery.SELECT("*").FROM().UNION("test1","test2","test3","test4") ); - } - @Test - public void selectWhereTest() { - assertEquals( "SELECT * FROM test1 WHERE arg=value", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value") ); - } - @Test - public void selectGroupByTest() { - assertEquals( "SELECT * FROM test1 GROUP BY col1", - ""+SQLQuery.SELECT("*").FROM("test1").GROUP_BY("col1") ); - assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1") ); - assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ASC", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ASC() ); - assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 DESC", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").DESC() ); - } - @Test - public void selectOrderByTest() { - assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1") ); - assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1 ASC", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1").ASC() ); - assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1 DESC", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1").DESC() ); - assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ORDER BY col2 DESC", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ORDER_BY("col2").DESC() ); - assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ASC ORDER BY col2 DESC", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ASC().ORDER_BY("col2").DESC() ); - } - @Test - public void selectLimitTest() { - assertEquals( "SELECT * FROM test1 LIMIT 1", - ""+SQLQuery.SELECT("*").FROM("test1").LIMIT(1) ); - assertEquals( "SELECT * FROM test1 LIMIT 1 4", - ""+SQLQuery.SELECT("*").FROM("test1").LIMIT(1).TO(4) ); - assertEquals( "SELECT * FROM test1 WHERE arg=value LIMIT 1", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").LIMIT(1) ); - assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1 DESC LIMIT 1", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1").DESC().LIMIT(1) ); - assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ORDER BY col2 DESC LIMIT 1", - ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ORDER_BY("col2").DESC().LIMIT(1) ); - } - - - @Test - public void updateTest() { - - } + @Test + public void selectTest() { + assertEquals( "SELECT * FROM test1", + ""+SQLQuery.SELECT().FROM("test1") ); + assertEquals( "SELECT * FROM test1", + ""+SQLQuery.SELECT("*").FROM("test1") ); + assertEquals( "SELECT test1,test2 FROM test1", + ""+SQLQuery.SELECT("test1","test2").FROM("test1") ); + } + @Test + public void selectJoinTest() { + assertEquals( "SELECT * FROM test1 JOIN test2", + ""+SQLQuery.SELECT("*").FROM("test1").JOIN("test2") ); + assertEquals( "SELECT * FROM test1 NATURAL JOIN test2", + ""+SQLQuery.SELECT("*").FROM("test1").NATURAL_JOIN("test2") ); + assertEquals( "SELECT * FROM test1 UNION test2", + ""+SQLQuery.SELECT("*").FROM("test1").UNION("test2") ); + assertEquals( "SELECT * FROM test1 JOIN test2 NATURAL JOIN test3 UNION test4", + ""+SQLQuery.SELECT("*").FROM("test1").JOIN("test2").NATURAL_JOIN("test3").UNION("test4") ); - - @Test - public void deleteTest() { - - } - - @Test - public void createTest() { - - } + assertEquals( "SELECT * FROM test1 NATURAL JOIN test2 NATURAL JOIN test3 NATURAL JOIN test4", + ""+SQLQuery.SELECT("*").FROM().NATURAL_JOIN("test1","test2","test3","test4") ); + assertEquals( "SELECT * FROM test1 JOIN test2 JOIN test3 JOIN test4", + ""+SQLQuery.SELECT("*").FROM().JOIN("test1","test2","test3","test4") ); + assertEquals( "SELECT * FROM test1 UNION test2 UNION test3 UNION test4", + ""+SQLQuery.SELECT("*").FROM().UNION("test1","test2","test3","test4") ); + } + @Test + public void selectWhereTest() { + assertEquals( "SELECT * FROM test1 WHERE arg=value", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value") ); + } + @Test + public void selectGroupByTest() { + assertEquals( "SELECT * FROM test1 GROUP BY col1", + ""+SQLQuery.SELECT("*").FROM("test1").GROUP_BY("col1") ); + assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1") ); + assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ASC", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ASC() ); + assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 DESC", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").DESC() ); + } + @Test + public void selectOrderByTest() { + assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1") ); + assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1 ASC", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1").ASC() ); + assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1 DESC", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1").DESC() ); + assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ORDER BY col2 DESC", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ORDER_BY("col2").DESC() ); + assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ASC ORDER BY col2 DESC", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ASC().ORDER_BY("col2").DESC() ); + } + @Test + public void selectLimitTest() { + assertEquals( "SELECT * FROM test1 LIMIT 1", + ""+SQLQuery.SELECT("*").FROM("test1").LIMIT(1) ); + assertEquals( "SELECT * FROM test1 LIMIT 1 4", + ""+SQLQuery.SELECT("*").FROM("test1").LIMIT(1).TO(4) ); + assertEquals( "SELECT * FROM test1 WHERE arg=value LIMIT 1", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").LIMIT(1) ); + assertEquals( "SELECT * FROM test1 WHERE arg=value ORDER BY col1 DESC LIMIT 1", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").ORDER_BY("col1").DESC().LIMIT(1) ); + assertEquals( "SELECT * FROM test1 WHERE arg=value GROUP BY col1 ORDER BY col2 DESC LIMIT 1", + ""+SQLQuery.SELECT("*").FROM("test1").WHERE().EQ("arg","value").GROUP_BY("col1").ORDER_BY("col2").DESC().LIMIT(1) ); + } + + + @Test + public void updateTest() { + + } + + + @Test + public void deleteTest() { + + } + + @Test + public void createTest() { + + } } diff --git a/test/zutil/image/ImageProcessorTest.java b/test/zutil/image/ImageProcessorTest.java index 1b1ea84..e6a30b5 100755 --- a/test/zutil/image/ImageProcessorTest.java +++ b/test/zutil/image/ImageProcessorTest.java @@ -41,90 +41,90 @@ 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 String imgPath = "test.gif"; + //private static String imgPath = "test2.jpg"; - private JLabel processedLabel; - private JLabel orginalLabel; - private JProgressBar progress; + private JLabel processedLabel; + private JLabel orginalLabel; + private JProgressBar progress; - public static void main(String[] args){ - new ImageProcessorTest(); - } + public static void main(String[] args){ + new ImageProcessorTest(); + } - @SuppressWarnings("unchecked") - public ImageProcessorTest(){ - JFrame frame = getJFrame(); - BufferedImage img = null; + @SuppressWarnings("unchecked") + public ImageProcessorTest(){ + JFrame frame = getJFrame(); + BufferedImage img = null; - try { - // Read from an input stream - InputStream is = new BufferedInputStream(new FileInputStream(imgPath)); - img = ImageIO.read(is); - } catch (IOException e) { - e.printStackTrace(); - System.exit(1); - } + try { + // Read from an input stream + InputStream is = new BufferedInputStream(new FileInputStream(imgPath)); + img = ImageIO.read(is); + } catch (IOException e) { + e.printStackTrace(); + System.exit(1); + } - ImageIcon orginalIcon = new ImageIcon(img); - orginalLabel.setIcon(orginalIcon); - frame.setVisible(true); - frame.pack(); - - BufferedImage procImg = null; - try { - //ImageFilterProcessor processor = new SobelEdgeDetectionFilter(img); - ImageFilterProcessor processor = new GaussianBlurFilter(img); - //ImageFilterProcessor processor = new BlurFilter(img, 100); - //ImageFilterProcessor processor = new ColorIntensityFilter(img, true); - //ImageFilterProcessor processor = new ContrastBrightnessFilter(img); - //ImageFilterProcessor processor = new DitheringFilter(img); - //ImageFilterProcessor processor = new MeanBlurFilter(img); - //ImageFilterProcessor processor = new MedianFilter(img); - //ImageFilterProcessor processor = new ResizeImage(img,100,100); - //ImageFilterProcessor processor = new SpotLightFilter(img,100,100,100); - - processor.setProgressListener(this); - procImg = processor.process(); - } catch (Exception e) { - e.printStackTrace(); - } - ImageIcon processedIcon = new ImageIcon(procImg); - processedLabel.setIcon(processedIcon); + ImageIcon orginalIcon = new ImageIcon(img); + orginalLabel.setIcon(orginalIcon); + frame.setVisible(true); + frame.pack(); - - frame.pack(); - } + BufferedImage procImg = null; + try { + //ImageFilterProcessor processor = new SobelEdgeDetectionFilter(img); + ImageFilterProcessor processor = new GaussianBlurFilter(img); + //ImageFilterProcessor processor = new BlurFilter(img, 100); + //ImageFilterProcessor processor = new ColorIntensityFilter(img, true); + //ImageFilterProcessor processor = new ContrastBrightnessFilter(img); + //ImageFilterProcessor processor = new DitheringFilter(img); + //ImageFilterProcessor processor = new MeanBlurFilter(img); + //ImageFilterProcessor processor = new MedianFilter(img); + //ImageFilterProcessor processor = new ResizeImage(img,100,100); + //ImageFilterProcessor processor = new SpotLightFilter(img,100,100,100); - private JFrame getJFrame() { - processedLabel = new JLabel("Processed"); - orginalLabel = new JLabel("Orginal"); - - progress = new JProgressBar(); - progress.setMaximum(100); - progress.setValue(0); - progress.setIndeterminate(false); - progress.setStringPainted(true); - - JPanel jPanel = new JPanel(); - jPanel.setLayout(new BorderLayout()); - jPanel.add(orginalLabel, BorderLayout.NORTH); - jPanel.add(processedLabel, BorderLayout.CENTER); - jPanel.add(progress, BorderLayout.SOUTH); + processor.setProgressListener(this); + procImg = processor.process(); + } catch (Exception e) { + e.printStackTrace(); + } + ImageIcon processedIcon = new ImageIcon(procImg); + processedLabel.setIcon(processedIcon); - JFrame jFrame = new JFrame("ImageProcessorTest"); - jFrame.setSize(new Dimension(715, 361)); - jFrame.setContentPane(jPanel); - jFrame.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - return jFrame; - } + frame.pack(); + } - public void progressUpdate(Object source, Object info, double percent) { - progress.setValue((int)percent); - } + private JFrame getJFrame() { + processedLabel = new JLabel("Processed"); + orginalLabel = new JLabel("Orginal"); + + progress = new JProgressBar(); + progress.setMaximum(100); + progress.setValue(0); + progress.setIndeterminate(false); + progress.setStringPainted(true); + + JPanel jPanel = new JPanel(); + jPanel.setLayout(new BorderLayout()); + jPanel.add(orginalLabel, BorderLayout.NORTH); + jPanel.add(processedLabel, BorderLayout.CENTER); + jPanel.add(progress, BorderLayout.SOUTH); + + JFrame jFrame = new JFrame("ImageProcessorTest"); + jFrame.setSize(new Dimension(715, 361)); + jFrame.setContentPane(jPanel); + jFrame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.exit(0); + } + }); + + return jFrame; + } + + public void progressUpdate(Object source, Object info, double percent) { + progress.setValue((int)percent); + } } diff --git a/test/zutil/io/BufferedBoundaryInputStreamTest.java b/test/zutil/io/BufferedBoundaryInputStreamTest.java index 5c25cda..e33e2e5 100755 --- a/test/zutil/io/BufferedBoundaryInputStreamTest.java +++ b/test/zutil/io/BufferedBoundaryInputStreamTest.java @@ -58,18 +58,18 @@ public class BufferedBoundaryInputStreamTest { - @Test - public void read_normal() throws IOException { + @Test + public void read_normal() throws IOException { BufferedBoundaryInputStream in = getBufferedBoundaryInputStream("aaa#a##aaaaaaa#", "#"); - assertTrue(in.hasNext()); + assertTrue(in.hasNext()); assertEquals('a', in.read()); assertEquals('a', in.read()); assertEquals('a', in.read()); assertEquals(-1, in.read()); assertTrue(in.hasNext()); - in.next(); + in.next(); assertEquals('a', in.read()); assertEquals(-1, in.read()); @@ -89,33 +89,33 @@ public class BufferedBoundaryInputStreamTest { assertEquals(-1, in.read()); assertFalse(in.hasNext()); - in.next(); - assertEquals(-1, in.read()); + in.next(); + assertEquals(-1, in.read()); assertFalse(in.hasNext()); - } + } @Test - public void readArr_normal() throws IOException { + public void readArr_normal() throws IOException { BufferedBoundaryInputStream in = getBufferedBoundaryInputStream("aaa#aaaaaaaaaaaaaaaa#aaaaaaaaaaaaaaa#", "#"); - byte[] buff = new byte[100]; - int n = in.read(buff); - assertEquals(3, n); + byte[] buff = new byte[100]; + int n = in.read(buff); + assertEquals(3, n); - assertTrue(in.hasNext()); - in.next(); - n = in.read(buff); - assertEquals(16, n); + assertTrue(in.hasNext()); + in.next(); + n = in.read(buff); + assertEquals(16, n); - assertTrue(in.hasNext()); - in.next(); - n = in.read(buff); - assertEquals(15, n); + assertTrue(in.hasNext()); + in.next(); + n = in.read(buff); + assertEquals(15, n); - assertFalse(in.hasNext()); - in.next(); - n = in.read(buff); - assertEquals(-1, n); - } + assertFalse(in.hasNext()); + in.next(); + n = in.read(buff); + assertEquals(-1, n); + } @Test public void read_multiCharBoundary() throws IOException { @@ -151,57 +151,57 @@ public class BufferedBoundaryInputStreamTest { assertFalse(in.hasNext()); } - @Test - public void read_startWithBound() throws IOException { + @Test + public void read_startWithBound() throws IOException { BufferedBoundaryInputStream in = getBufferedBoundaryInputStream("#aaa", "#"); - assertEquals(-1, in.read()); - } - @Test - public void readArr_startWithBound() throws IOException { + assertEquals(-1, in.read()); + } + @Test + public void readArr_startWithBound() throws IOException { BufferedBoundaryInputStream in = getBufferedBoundaryInputStream("#aaa", "#"); assertEquals(-1, in.read(new byte[10], 0, 10)); - } + } - @Test - public void read_onlyBoundaries() throws IOException { + @Test + public void read_onlyBoundaries() throws IOException { BufferedBoundaryInputStream in = getBufferedBoundaryInputStream("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "a"); - - int n; - for(n=1; in.hasNext(); n++){ - assertEquals(-1, in.read()); - assertEquals(-1, in.read()); - in.next(); - } - assertEquals(35, n); - } - @Test - public void readArr_onlyBoundaries() throws IOException { + + int n; + for(n=1; in.hasNext(); n++){ + assertEquals(-1, in.read()); + assertEquals(-1, in.read()); + in.next(); + } + assertEquals(35, n); + } + @Test + public void readArr_onlyBoundaries() throws IOException { BufferedBoundaryInputStream in = getBufferedBoundaryInputStream("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "a"); byte[] buff = new byte[100]; - int n; - for(n=1; in.hasNext(); n++){ - assertEquals(-1, in.read(buff)); - assertEquals(-1, in.read(buff)); - in.next(); - } - assertEquals(35, n); - } - - @Test - public void read_noBounds() throws IOException { - String data = "1234567891011121314151617181920"; + int n; + for(n=1; in.hasNext(); n++){ + assertEquals(-1, in.read(buff)); + assertEquals(-1, in.read(buff)); + in.next(); + } + assertEquals(35, n); + } + + @Test + public void read_noBounds() throws IOException { + String data = "1234567891011121314151617181920"; BufferedBoundaryInputStream in = getBufferedBoundaryInputStream(data, "#"); - - int out; - StringBuilder output = new StringBuilder(); - while((out = in.read()) != -1){ - output.append((char)out); - } - assertEquals(data, output.toString()); - } + + int out; + StringBuilder output = new StringBuilder(); + while((out = in.read()) != -1){ + output.append((char)out); + } + assertEquals(data, output.toString()); + } @Test public void readArr_noBounds() throws IOException { String data = "1234567891011121314151617181920"; diff --git a/test/zutil/io/DynamicByteArrayStreamTest.java b/test/zutil/io/DynamicByteArrayStreamTest.java index 842b1a4..f928c40 100755 --- a/test/zutil/io/DynamicByteArrayStreamTest.java +++ b/test/zutil/io/DynamicByteArrayStreamTest.java @@ -52,7 +52,7 @@ public class DynamicByteArrayStreamTest { byte[] result = out.getBytes(); for(int i=0; i - - - + + + -
    - - -
    -
      -
    • -
      - - Test - -
      -
    • -
    +
    + + +
    +
      +
    • +
      + + Test + +
      +
    • +
    \ No newline at end of file diff --git a/test/zutil/log/net/NetLogServerTest.java b/test/zutil/log/net/NetLogServerTest.java index 823ab96..99f8a5e 100755 --- a/test/zutil/log/net/NetLogServerTest.java +++ b/test/zutil/log/net/NetLogServerTest.java @@ -31,23 +31,23 @@ import java.util.logging.Logger; public class NetLogServerTest { - private static final Logger logger = LogUtil.getLogger(); + private static final Logger logger = LogUtil.getLogger(); - public static void main(String[] args){ - LogUtil.setGlobalLevel(Level.FINEST); - LogUtil.addGlobalHandler(new NetLogServer(5050)); - - while(true){ - logger.log(Level.SEVERE, "Test Severe"); - logger.log(Level.WARNING, "Test Warning"); - logger.log(Level.INFO, "Test Info"); - logger.log(Level.FINE, "Test Fine"); - logger.log(Level.FINER, "Test Finer"); - logger.log(Level.FINEST, "Test Finest"); - - logger.log(Level.SEVERE, "Test Exception", new Exception("Test")); - - try{Thread.sleep(3000);}catch(Exception e){} - } - } + public static void main(String[] args){ + LogUtil.setGlobalLevel(Level.FINEST); + LogUtil.addGlobalHandler(new NetLogServer(5050)); + + while(true){ + logger.log(Level.SEVERE, "Test Severe"); + logger.log(Level.WARNING, "Test Warning"); + logger.log(Level.INFO, "Test Info"); + logger.log(Level.FINE, "Test Fine"); + logger.log(Level.FINER, "Test Finer"); + logger.log(Level.FINEST, "Test Finest"); + + logger.log(Level.SEVERE, "Test Exception", new Exception("Test")); + + try{Thread.sleep(3000);}catch(Exception e){} + } + } } diff --git a/test/zutil/net/ServerFindClientTest.java b/test/zutil/net/ServerFindClientTest.java index c0c0a24..c7b71da 100755 --- a/test/zutil/net/ServerFindClientTest.java +++ b/test/zutil/net/ServerFindClientTest.java @@ -28,12 +28,12 @@ import java.io.IOException; public class ServerFindClientTest { - public static void main(String[] args){ - try { - ServerFindClient client = new ServerFindClient(2000); - System.out.println(client.find().getHostAddress()); - } catch (IOException e) { - e.printStackTrace(); - } - } + public static void main(String[] args){ + try { + ServerFindClient client = new ServerFindClient(2000); + System.out.println(client.find().getHostAddress()); + } catch (IOException e) { + e.printStackTrace(); + } + } } diff --git a/test/zutil/net/ServerFindServerTest.java b/test/zutil/net/ServerFindServerTest.java index 19bffc5..fe75a64 100755 --- a/test/zutil/net/ServerFindServerTest.java +++ b/test/zutil/net/ServerFindServerTest.java @@ -28,11 +28,11 @@ import java.io.IOException; public class ServerFindServerTest { - public static void main(String[] args){ - try { - new ServerFind(2000); - } catch (IOException e) { - e.printStackTrace(); - } - } + public static void main(String[] args){ + try { + new ServerFind(2000); + } catch (IOException e) { + e.printStackTrace(); + } + } } diff --git a/test/zutil/net/http/HttpURLTest.java b/test/zutil/net/http/HttpURLTest.java index 6e71dc8..253db00 100755 --- a/test/zutil/net/http/HttpURLTest.java +++ b/test/zutil/net/http/HttpURLTest.java @@ -34,41 +34,41 @@ import static org.junit.Assert.assertEquals; public class HttpURLTest { - @Test - public void fullURLTest() { - HttpURL url = new HttpURL(); - url.setProtocol("http"); - assertEquals( "http://127.0.0.1/", url.getURL() ); - - url.setHost("koc.se"); - assertEquals( "http://koc.se/", url.getURL() ); - - url.setPort( 80 ); - assertEquals( "http://koc.se:80/", url.getURL() ); - - url.setPath("test/index.html"); - assertEquals( "http://koc.se:80/test/index.html", url.getURL() ); - - url.setParameter("key", "value"); - assertEquals( "http://koc.se:80/test/index.html?key=value", url.getURL() ); - - url.setAnchor( "anch" ); - assertEquals( "http://koc.se:80/test/index.html?key=value#anch", url.getURL() ); - } - - @Test - public void urlParameterTest() { - HttpURL url = new HttpURL(); - url.setParameter("key1", "value1"); - assertEquals( "key1=value1", url.getParameterString() ); - - url.setParameter("key1", "value1"); - assertEquals( "key1=value1", url.getParameterString() ); - - url.setParameter("key2", "value2"); - assertThat(url.getParameterString(), allOf(containsString("key2=value2"), containsString("key1=value1"))); + @Test + public void fullURLTest() { + HttpURL url = new HttpURL(); + url.setProtocol("http"); + assertEquals( "http://127.0.0.1/", url.getURL() ); - } + url.setHost("koc.se"); + assertEquals( "http://koc.se/", url.getURL() ); + + url.setPort( 80 ); + assertEquals( "http://koc.se:80/", url.getURL() ); + + url.setPath("test/index.html"); + assertEquals( "http://koc.se:80/test/index.html", url.getURL() ); + + url.setParameter("key", "value"); + assertEquals( "http://koc.se:80/test/index.html?key=value", url.getURL() ); + + url.setAnchor( "anch" ); + assertEquals( "http://koc.se:80/test/index.html?key=value#anch", url.getURL() ); + } + + @Test + public void urlParameterTest() { + HttpURL url = new HttpURL(); + url.setParameter("key1", "value1"); + assertEquals( "key1=value1", url.getParameterString() ); + + url.setParameter("key1", "value1"); + assertEquals( "key1=value1", url.getParameterString() ); + + url.setParameter("key2", "value2"); + assertThat(url.getParameterString(), allOf(containsString("key2=value2"), containsString("key1=value1"))); + + } } diff --git a/test/zutil/net/http/page/HttpGuessTheNumber.java b/test/zutil/net/http/page/HttpGuessTheNumber.java index bf35750..3570c23 100755 --- a/test/zutil/net/http/page/HttpGuessTheNumber.java +++ b/test/zutil/net/http/page/HttpGuessTheNumber.java @@ -40,37 +40,37 @@ import static zutil.net.http.HttpServer.SESSION_KEY_ID; public class HttpGuessTheNumber implements HttpPage { - private static final String SESSION_KEY_NUMBER = "random_number"; - private static final String REQUEST_KEY_GUESS = "guess"; - private static final String COOKIE_KEY_LOW = "low"; - private static final String COOKIE_KEY_HIGH = "high"; + private static final String SESSION_KEY_NUMBER = "random_number"; + private static final String REQUEST_KEY_GUESS = "guess"; + private static final String COOKIE_KEY_LOW = "low"; + private static final String COOKIE_KEY_HIGH = "high"; - public static void main(String[] args) throws IOException{ + public static void main(String[] args) throws IOException{ LogUtil.setGlobalLevel(Level.ALL); LogUtil.setGlobalFormatter(new CompactLogFormatter()); //HttpServer server = new HttpServer("localhost", 443, FileFinder.find("keySSL"), "rootroot");//SSL - HttpServer server = new HttpServer(8080); - server.setDefaultPage(new HttpGuessTheNumber()); - server.run(); - } + HttpServer server = new HttpServer(8080); + server.setDefaultPage(new HttpGuessTheNumber()); + server.run(); + } - public void respond(HttpPrintStream out, - HttpHeader client_info, - Map session, - Map cookie, - Map request) throws IOException { + public void respond(HttpPrintStream out, + HttpHeader client_info, + Map session, + Map cookie, + Map request) throws IOException { - out.enableBuffering(true); - out.println(""); - out.println("

    Welcome To The Number Guess Game!

    "); + out.enableBuffering(true); + out.println(""); + out.println("

    Welcome To The Number Guess Game!

    "); - String low = cookie.get(COOKIE_KEY_LOW); - String high = cookie.get(COOKIE_KEY_HIGH); + String low = cookie.get(COOKIE_KEY_LOW); + String high = cookie.get(COOKIE_KEY_HIGH); - if(session.containsKey(SESSION_KEY_NUMBER)){ - if (request.containsKey(REQUEST_KEY_GUESS)) { + if(session.containsKey(SESSION_KEY_NUMBER)){ + if (request.containsKey(REQUEST_KEY_GUESS)) { int guess = Integer.parseInt(request.get(REQUEST_KEY_GUESS)); int number = (Integer) session.get(SESSION_KEY_NUMBER); @@ -93,26 +93,26 @@ public class HttpGuessTheNumber implements HttpPage { } } } - } - else{ - session.put(SESSION_KEY_NUMBER, (int)(Math.random()*99+1)); - low = "0"; - high = "100"; + } + else{ + session.put(SESSION_KEY_NUMBER, (int)(Math.random()*99+1)); + low = "0"; + high = "100"; out.setCookie(COOKIE_KEY_LOW, low); out.setCookie(COOKIE_KEY_HIGH, high); - } + } - out.println("
    "); - out.println(low+" < X < "+high+"
    "); - out.println("Guess a number between 0 and 100:
    "); - out.println(""); - out.println(""); - out.println(""); - out.println("
    "); - out.println(""); - out.println("DEBUG: session_id="+session.get(SESSION_KEY_ID)+"
    "); - out.println("DEBUG: number="+session.get(SESSION_KEY_NUMBER)+"
    "); - out.println(""); - } + out.println("
    "); + out.println(low+" < X < "+high+"
    "); + out.println("Guess a number between 0 and 100:
    "); + out.println(""); + out.println(""); + out.println(""); + out.println("
    "); + out.println(""); + out.println("DEBUG: session_id="+session.get(SESSION_KEY_ID)+"
    "); + out.println("DEBUG: number="+session.get(SESSION_KEY_NUMBER)+"
    "); + out.println(""); + } } diff --git a/test/zutil/net/nio/NetworkClientTest.java b/test/zutil/net/nio/NetworkClientTest.java index a9e71a0..30578e7 100755 --- a/test/zutil/net/nio/NetworkClientTest.java +++ b/test/zutil/net/nio/NetworkClientTest.java @@ -38,35 +38,35 @@ import java.util.logging.Level; @SuppressWarnings("unused") public class NetworkClientTest { - public static void main(String[] args) throws NoSuchAlgorithmException, InterruptedException { - try { + public static void main(String[] args) throws NoSuchAlgorithmException, InterruptedException { + try { //LogUtil.setGlobalLevel(Level.ALL); LogUtil.setGlobalFormatter(new CompactLogFormatter()); int count = 0; - long time = System.currentTimeMillis()+1000*60; - NioClient client = new NioClient(InetAddress.getByName("localhost"), 6056); - StandardWorker worker = new StandardWorker(client); - client.setDefaultWorker(worker); + long time = System.currentTimeMillis()+1000*60; + NioClient client = new NioClient(InetAddress.getByName("localhost"), 6056); + StandardWorker worker = new StandardWorker(client); + client.setDefaultWorker(worker); Thread.sleep(1000); - while(time > System.currentTimeMillis()){ - PrintResponseHandler handler = new PrintResponseHandler(); - worker.send(client.getRemoteAddress(), + while(time > System.currentTimeMillis()){ + PrintResponseHandler handler = new PrintResponseHandler(); + worker.send(client.getRemoteAddress(), new StringResponseMessage("StringResponseMessage: "+count), handler); - handler.waitForResponse(); - //Thread.sleep(100); - //System.out.println("sending.."); - count++; - } - client.close(); - - System.out.println("Message Count 1m: "+count); - System.out.println("Message Count 1s: "+count/60); - System.exit(0); - } catch (IOException e) { - e.printStackTrace(); - } - } + handler.waitForResponse(); + //Thread.sleep(100); + //System.out.println("sending.."); + count++; + } + client.close(); + + System.out.println("Message Count 1m: "+count); + System.out.println("Message Count 1s: "+count/60); + System.exit(0); + } catch (IOException e) { + e.printStackTrace(); + } + } } diff --git a/test/zutil/net/nio/NetworkServerTest.java b/test/zutil/net/nio/NetworkServerTest.java index fd51b49..c2ad4f7 100755 --- a/test/zutil/net/nio/NetworkServerTest.java +++ b/test/zutil/net/nio/NetworkServerTest.java @@ -35,19 +35,19 @@ import java.util.logging.Level; @SuppressWarnings("unused") public class NetworkServerTest { - public static void main(String[] args) throws NoSuchAlgorithmException, InterruptedException { - try { - //LogUtil.setGlobalLevel(Level.ALL); - LogUtil.setGlobalFormatter(new CompactLogFormatter()); + public static void main(String[] args) throws NoSuchAlgorithmException, InterruptedException { + try { + //LogUtil.setGlobalLevel(Level.ALL); + LogUtil.setGlobalFormatter(new CompactLogFormatter()); - NioServer server = new NioServer(6056); - server.setDefaultWorker(new StandardWorker(server)); + NioServer server = new NioServer(6056); + server.setDefaultWorker(new StandardWorker(server)); - while(true){ - Thread.sleep(1000); + while(true){ + Thread.sleep(1000); } - } catch (IOException e) { - e.printStackTrace(); - } - } + } catch (IOException e) { + e.printStackTrace(); + } + } } diff --git a/test/zutil/net/update/UpdateClientTest.java b/test/zutil/net/update/UpdateClientTest.java index 37b5a75..bd4336b 100755 --- a/test/zutil/net/update/UpdateClientTest.java +++ b/test/zutil/net/update/UpdateClientTest.java @@ -33,41 +33,41 @@ import java.util.logging.Level; public class UpdateClientTest implements ProgressListener{ - public static void main(String[] args){ - LogUtil.setLevel("zutil", Level.FINEST); - LogUtil.setFormatter("zutil", new CompactLogFormatter()); - - UpdateClientTest client = new UpdateClientTest(); - client.start(); - } - - public void start(){ - try { - final UpdateClient client = new UpdateClient("localhost", 2000, "C:\\Users\\Ziver\\Desktop\\client"); - client.setProgressListener(new Zupdater()); - - //client.setProgressListener(this); - - EventQueue.invokeLater(new Runnable() { - public void run() { - try { - Zupdater gui = new Zupdater(); - client.setProgressListener(gui); - gui.setVisible(true); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - - client.update(); - client.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } + public static void main(String[] args){ + LogUtil.setLevel("zutil", Level.FINEST); + LogUtil.setFormatter("zutil", new CompactLogFormatter()); - public void progressUpdate(UpdateClient source, FileInfo info, double percent) { - System.out.println(info+": "+percent+"%"); - } + UpdateClientTest client = new UpdateClientTest(); + client.start(); + } + + public void start(){ + try { + final UpdateClient client = new UpdateClient("localhost", 2000, "C:\\Users\\Ziver\\Desktop\\client"); + client.setProgressListener(new Zupdater()); + + //client.setProgressListener(this); + + EventQueue.invokeLater(new Runnable() { + public void run() { + try { + Zupdater gui = new Zupdater(); + client.setProgressListener(gui); + gui.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + + client.update(); + client.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void progressUpdate(UpdateClient source, FileInfo info, double percent) { + System.out.println(info+": "+percent+"%"); + } } diff --git a/test/zutil/net/update/UpdateServerTest.java b/test/zutil/net/update/UpdateServerTest.java index 6065606..aa7bf2f 100755 --- a/test/zutil/net/update/UpdateServerTest.java +++ b/test/zutil/net/update/UpdateServerTest.java @@ -31,14 +31,14 @@ import java.util.logging.Level; public class UpdateServerTest { - public static void main(String[] args){ - try { - LogUtil.setGlobalLevel(Level.FINEST); - LogUtil.setGlobalFormatter(new CompactLogFormatter()); - - new UpdateServer(2000, "C:\\Users\\Ziver\\Desktop\\server"); - }catch (Exception e) { - e.printStackTrace(); - } - } + public static void main(String[] args){ + try { + LogUtil.setGlobalLevel(Level.FINEST); + LogUtil.setGlobalFormatter(new CompactLogFormatter()); + + new UpdateServer(2000, "C:\\Users\\Ziver\\Desktop\\server"); + }catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/test/zutil/net/upnp/UPnPServerTest.java b/test/zutil/net/upnp/UPnPServerTest.java index 94fef65..8557d9f 100755 --- a/test/zutil/net/upnp/UPnPServerTest.java +++ b/test/zutil/net/upnp/UPnPServerTest.java @@ -36,28 +36,28 @@ import java.io.IOException; public class UPnPServerTest { - - public static void main(String[] args) throws IOException{ - UPnPMediaServer upnp = new UPnPMediaServer("http://192.168.0.60:8080/"); - MultiPrintStream.out.println("UPNP Server running"); - - UPnPContentDirectory cds = new UPnPContentDirectory(new File("C:\\Users\\Ziver\\Desktop\\lan")); - WebServiceDef ws = new WebServiceDef( UPnPContentDirectory.class ); - - HttpServer http = new HttpServer(8080); - //http.setDefaultPage(upnp); - http.setPage("/RootDesc", upnp ); - http.setPage("/SCP/ContentDir", cds ); - SOAPHttpPage soap = new SOAPHttpPage(ws); - soap.setObject( cds ); - soap.enableSession( false ); - http.setPage("/Action/ContentDir", soap ); - http.start(); - MultiPrintStream.out.println("HTTP Server running"); - - SSDPServer ssdp = new SSDPServer(); - ssdp.addService( upnp ); - ssdp.start(); - MultiPrintStream.out.println("SSDP Server running"); - } + + public static void main(String[] args) throws IOException{ + UPnPMediaServer upnp = new UPnPMediaServer("http://192.168.0.60:8080/"); + MultiPrintStream.out.println("UPNP Server running"); + + UPnPContentDirectory cds = new UPnPContentDirectory(new File("C:\\Users\\Ziver\\Desktop\\lan")); + WebServiceDef ws = new WebServiceDef( UPnPContentDirectory.class ); + + HttpServer http = new HttpServer(8080); + //http.setDefaultPage(upnp); + http.setPage("/RootDesc", upnp ); + http.setPage("/SCP/ContentDir", cds ); + SOAPHttpPage soap = new SOAPHttpPage(ws); + soap.setObject( cds ); + soap.enableSession( false ); + http.setPage("/Action/ContentDir", soap ); + http.start(); + MultiPrintStream.out.println("HTTP Server running"); + + SSDPServer ssdp = new SSDPServer(); + ssdp.addService( upnp ); + ssdp.start(); + MultiPrintStream.out.println("SSDP Server running"); + } } diff --git a/test/zutil/net/ws/soap/SOAPClientTest.java b/test/zutil/net/ws/soap/SOAPClientTest.java index 28bd722..7d2facc 100755 --- a/test/zutil/net/ws/soap/SOAPClientTest.java +++ b/test/zutil/net/ws/soap/SOAPClientTest.java @@ -36,20 +36,20 @@ import java.util.logging.Level; // TODO: COnvert to JUnit public class SOAPClientTest { - public static void main(String[] args) throws InstantiationException, IllegalAccessException, MalformedURLException { - LogUtil.setGlobalLevel(Level.ALL); - LogUtil.setFormatter("", new CompactLogFormatter()); - - TestClient intf = SOAPClientFactory.createClient(new URL("http://localhost:3289"), TestClient.class); - intf.m(); - intf.c(); - } - - - public interface TestClient extends WSInterface{ - public void m(); - - public void c(); + public static void main(String[] args) throws InstantiationException, IllegalAccessException, MalformedURLException { + LogUtil.setGlobalLevel(Level.ALL); + LogUtil.setFormatter("", new CompactLogFormatter()); - } + TestClient intf = SOAPClientFactory.createClient(new URL("http://localhost:3289"), TestClient.class); + intf.m(); + intf.c(); + } + + + public interface TestClient extends WSInterface{ + public void m(); + + public void c(); + + } } diff --git a/test/zutil/net/ws/soap/SOAPTest.java b/test/zutil/net/ws/soap/SOAPTest.java index e49750c..6cfb2de 100755 --- a/test/zutil/net/ws/soap/SOAPTest.java +++ b/test/zutil/net/ws/soap/SOAPTest.java @@ -37,116 +37,116 @@ import zutil.parser.wsdl.WSDLWriter; // TODO: Convert to JUnit public class SOAPTest { /************************* TEST CASES ************************/ - public static void main(String[] args){ - WebServiceDef wsDef = new WebServiceDef( MainSOAPClass.class ); - SOAPHttpPage soap = new SOAPHttpPage( wsDef ); + public static void main(String[] args){ + WebServiceDef wsDef = new WebServiceDef( MainSOAPClass.class ); + SOAPHttpPage soap = new SOAPHttpPage( wsDef ); - System.out.println( "****************** WSDL *********************" ); - WSDLWriter wsdl = new WSDLWriter( wsDef ); - wsdl.write(System.out); - - // Response - try { - System.out.println( "\n****************** REQUEST *********************" ); - String request = "\n" + - "\n" + - " \n" + - " \n" + - " IBM\n" + - " \n" + + System.out.println( "****************** WSDL *********************" ); + WSDLWriter wsdl = new WSDLWriter( wsDef ); + wsdl.write(System.out); - " \n" + - " IBM\n" + - " \n" + - " \n" + - ""; - System.out.println(request); + // Response + try { + System.out.println( "\n****************** REQUEST *********************" ); + String request = "\n" + + "\n" + + " \n" + + " \n" + + " IBM\n" + + " \n" + + + " \n" + + " IBM\n" + + " \n" + + " \n" + + ""; + System.out.println(request); System.out.println( "\n****************** EXECUTION *********************" ); - Document document = soap.genSOAPResponse(request); - System.out.println( "\n****************** RESPONSE *********************" ); + Document document = soap.genSOAPResponse(request); + System.out.println( "\n****************** RESPONSE *********************" ); - OutputFormat format = OutputFormat.createPrettyPrint(); - XMLWriter writer = new XMLWriter( System.out, format ); - writer.write( document ); + OutputFormat format = OutputFormat.createPrettyPrint(); + XMLWriter writer = new XMLWriter( System.out, format ); + writer.write( document ); - System.out.println(); - } catch (Exception e) { - e.printStackTrace(); - } - } + System.out.println(); + } catch (Exception e) { + e.printStackTrace(); + } + } /************************* TEST CLASSES ************************/ @SuppressWarnings("unused") - public static class SpecialReturnClass extends WSReturnObject{ - @WSValueName(value="otherValue1") - public String param1 = "otherValue1"; - @WSValueName("otherName2") - public String param2 = "otherValue2"; - public byte[] b = new byte[]{0x12, 0x23}; - public InnerClass inner = new InnerClass(); - } + public static class SpecialReturnClass extends WSReturnObject{ + @WSValueName(value="otherValue1") + public String param1 = "otherValue1"; + @WSValueName("otherName2") + public String param2 = "otherValue2"; + public byte[] b = new byte[]{0x12, 0x23}; + public InnerClass inner = new InnerClass(); + } @SuppressWarnings("unused") - public static class InnerClass extends WSReturnObject{ - public String innerClassParam1 = "innerClass1"; - public String innerClassParam2 = "innerClass2"; - } + public static class InnerClass extends WSReturnObject{ + public String innerClassParam1 = "innerClass1"; + public String innerClassParam2 = "innerClass2"; + } @SuppressWarnings("unused") - public static class SimpleReturnClass extends WSReturnObject{ - @WSValueName("otherParam1") - public String param1 = "param1"; - public String param2 = "param2"; - } + public static class SimpleReturnClass extends WSReturnObject{ + @WSValueName("otherParam1") + public String param1 = "param1"; + public String param2 = "param2"; + } @SuppressWarnings("unused") - @WSNamespace("http://test.se:8080/") - public static class MainSOAPClass implements WSInterface{ - public MainSOAPClass(){} - - @WSHeader() - @WSDocumentation("Documentation of method exceptionMethod()") - public void exceptionMethod( - @WSParamName(value="otherParam1", optional=true) int param1, - @WSParamName(value="otherParam2", optional=true) int param2) throws Exception{ - System.out.println("Executing method: exceptionMethod(int param1="+param1+", int param2="+param2+",)"); - throw new Exception("This is an Exception"); - } + @WSNamespace("http://test.se:8080/") + public static class MainSOAPClass implements WSInterface{ + public MainSOAPClass(){} - @WSReturnName("stringArray") - @WSParamDocumentation("Documentation of stringArrayMethod()") - public String[][] stringArrayMethod ( - @WSParamName("StringName") String str) throws Exception{ - System.out.println("Executing method: stringArrayMethod(String str='"+str+"')"); - return new String[][]{{"test","test2"},{"test3","test4"}}; - } + @WSHeader() + @WSDocumentation("Documentation of method exceptionMethod()") + public void exceptionMethod( + @WSParamName(value="otherParam1", optional=true) int param1, + @WSParamName(value="otherParam2", optional=true) int param2) throws Exception{ + System.out.println("Executing method: exceptionMethod(int param1="+param1+", int param2="+param2+",)"); + throw new Exception("This is an Exception"); + } - @WSReturnName("specialReturnClass") - @WSParamDocumentation("Documentation of specialReturnMethod()") - public SpecialReturnClass[] specialReturnMethod ( - @WSParamName("StringName2") String str) throws Exception{ - System.out.println("Executing method: specialReturnMethod(String str='"+str+"')"); - return new SpecialReturnClass[]{new SpecialReturnClass(), new SpecialReturnClass()}; - } + @WSReturnName("stringArray") + @WSParamDocumentation("Documentation of stringArrayMethod()") + public String[][] stringArrayMethod ( + @WSParamName("StringName") String str) throws Exception{ + System.out.println("Executing method: stringArrayMethod(String str='"+str+"')"); + return new String[][]{{"test","test2"},{"test3","test4"}}; + } - @WSReturnName("SimpleReturnClass") - @WSParamDocumentation("null is the kala") - public SimpleReturnClass simpleReturnClassMethod ( - @WSParamName("byte") String lol) throws Exception{ - System.out.println("Executing method: simpleReturnClassMethod()"); - SimpleReturnClass tmp = new SimpleReturnClass(); - tmp.param1 = "newParam1"; - tmp.param2 = "newParam2"; - return tmp; - } - - @WSParamDocumentation("void method documentation") - public void voidMethod (){ } - - @WSIgnore() - public void disabledMethod(){ } - protected void protectedMethod(){ } + @WSReturnName("specialReturnClass") + @WSParamDocumentation("Documentation of specialReturnMethod()") + public SpecialReturnClass[] specialReturnMethod ( + @WSParamName("StringName2") String str) throws Exception{ + System.out.println("Executing method: specialReturnMethod(String str='"+str+"')"); + return new SpecialReturnClass[]{new SpecialReturnClass(), new SpecialReturnClass()}; + } - private void privateMethod(){ } - } + @WSReturnName("SimpleReturnClass") + @WSParamDocumentation("null is the kala") + public SimpleReturnClass simpleReturnClassMethod ( + @WSParamName("byte") String lol) throws Exception{ + System.out.println("Executing method: simpleReturnClassMethod()"); + SimpleReturnClass tmp = new SimpleReturnClass(); + tmp.param1 = "newParam1"; + tmp.param2 = "newParam2"; + return tmp; + } + + @WSParamDocumentation("void method documentation") + public void voidMethod (){ } + + @WSIgnore() + public void disabledMethod(){ } + protected void protectedMethod(){ } + + private void privateMethod(){ } + } } diff --git a/test/zutil/parser/BBCodeParserTest.java b/test/zutil/parser/BBCodeParserTest.java index 6b5d20d..8d6e20e 100755 --- a/test/zutil/parser/BBCodeParserTest.java +++ b/test/zutil/parser/BBCodeParserTest.java @@ -31,18 +31,18 @@ import static org.junit.Assert.assertEquals; public class BBCodeParserTest{ - @Test - public void BBCodeParser() { - BBCodeParser parser = new BBCodeParser(); - - assertEquals("1234", parser.read("1234")); - assertEquals("1234", parser.read("[i]1234[/i]")); - assertEquals("[apa]lol[/apa]", parser.read("[apa]lol[/apa]")); - assertEquals("jshdkj lol [apa]lol[/apa]", parser.read("jshdkj [u]lol [apa]lol[/apa]")); - //assertEquals("jshdkj [m]lol[/k] lol", parser.read("jshdkj [m]lol[/k] [i]lol[/i]")); - assertEquals("jshdkj [m", parser.read("jshdkj [m")); - assertEquals("jshdkj [/m", parser.read("jshdkj [/m")); - assertEquals("jshdkj m]", parser.read("jshdkj m]")); - assertEquals("jshdkj
    ", parser.read("jshdkj
    ")); - } + @Test + public void BBCodeParser() { + BBCodeParser parser = new BBCodeParser(); + + assertEquals("1234", parser.read("1234")); + assertEquals("1234", parser.read("[i]1234[/i]")); + assertEquals("[apa]lol[/apa]", parser.read("[apa]lol[/apa]")); + assertEquals("jshdkj lol [apa]lol[/apa]", parser.read("jshdkj [u]lol [apa]lol[/apa]")); + //assertEquals("jshdkj [m]lol[/k] lol", parser.read("jshdkj [m]lol[/k] [i]lol[/i]")); + assertEquals("jshdkj [m", parser.read("jshdkj [m")); + assertEquals("jshdkj [/m", parser.read("jshdkj [/m")); + assertEquals("jshdkj m]", parser.read("jshdkj m]")); + assertEquals("jshdkj
    ", parser.read("jshdkj
    ")); + } } diff --git a/test/zutil/parser/Base64Test.java b/test/zutil/parser/Base64Test.java index 1d2d3e9..f54ab5c 100755 --- a/test/zutil/parser/Base64Test.java +++ b/test/zutil/parser/Base64Test.java @@ -33,41 +33,41 @@ import static org.junit.Assert.assertEquals; public class Base64Test { - @Test - public void decode() { + @Test + public void decode() { assertEquals( "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.", Base64Decoder.decode("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=") - ); + ); Base64Decoder decoder = new Base64Decoder(); - decoder.clear(); - decoder.read("YW55IGNhcm5hbCBwbGVhc3VyZQ=="); - assertEquals( "any carnal pleasure", decoder.toString() ); - decoder.clear(); - decoder.read("bGVhc3VyZS4="); - assertEquals( "leasure.", decoder.toString() ); - decoder.clear(); - decoder.read("YW55IGNhcm5hbCBwbGVhc3Vy"); - assertEquals( "any carnal pleasur", decoder.toString() ); - decoder.clear(); - } + decoder.clear(); + decoder.read("YW55IGNhcm5hbCBwbGVhc3VyZQ=="); + assertEquals( "any carnal pleasure", decoder.toString() ); + decoder.clear(); + decoder.read("bGVhc3VyZS4="); + assertEquals( "leasure.", decoder.toString() ); + decoder.clear(); + decoder.read("YW55IGNhcm5hbCBwbGVhc3Vy"); + assertEquals( "any carnal pleasur", decoder.toString() ); + decoder.clear(); + } - @Test - public void encode() { - assertEquals("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=" , - Base64Encoder.encode("Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.") - ); + @Test + public void encode() { + assertEquals("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=" , + Base64Encoder.encode("Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.") + ); - assertEquals("YW55IGNhcm5hbCBwbGVhc3VyZQ==", Base64Encoder.encode("any carnal pleasure")); - assertEquals("bGVhc3VyZS4=", Base64Encoder.encode("leasure.")); - assertEquals("YW55IGNhcm5hbCBwbGVhc3Vy", Base64Encoder.encode("any carnal pleasur")); - } + assertEquals("YW55IGNhcm5hbCBwbGVhc3VyZQ==", Base64Encoder.encode("any carnal pleasure")); + assertEquals("bGVhc3VyZS4=", Base64Encoder.encode("leasure.")); + assertEquals("YW55IGNhcm5hbCBwbGVhc3Vy", Base64Encoder.encode("any carnal pleasur")); + } @Test public void encodeJavaUtil() { - assertEquals("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=" , - Base64.getEncoder().encodeToString("Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.".getBytes()) - ); + assertEquals("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=" , + Base64.getEncoder().encodeToString("Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.".getBytes()) + ); assertEquals("YW55IGNhcm5hbCBwbGVhc3VyZQ==", Base64.getEncoder().encodeToString("any carnal pleasure".getBytes())); assertEquals("bGVhc3VyZS4=", Base64.getEncoder().encodeToString("leasure.".getBytes())); diff --git a/test/zutil/parser/json/JSONParserTest.java b/test/zutil/parser/json/JSONParserTest.java index 0608f7c..dfd6181 100755 --- a/test/zutil/parser/json/JSONParserTest.java +++ b/test/zutil/parser/json/JSONParserTest.java @@ -147,36 +147,36 @@ public class JSONParserTest { } - @Test - public void complexMap() { - String json = "{" + - "\"test1\": 1234," + - "\"TEST1\": 5678," + - "\"test3\": 1234.99," + - "\"test4\": \"91011\"," + - "\"test5\": [12,13,14,15]," + - "\"test6\": [\"a\",\"b\",\"c\",\"d\"]" + - "}"; - - DataNode data = JSONParser.read(json); - assert( data.isMap() ); - assert( 1234 == data.get("test1").getInt() ); - assert( 5678 == data.get("TEST1").getInt() ); - assert( 1234.99 == data.get("test3").getDouble() ); - assertEquals( "91011", data.get("test4").getString() ); - - assert( data.get("test5").isList() ); - assertEquals( 4, data.get("test5").size() ); - assertEquals( 12, data.get("test5").get(0).getInt() ); - assertEquals( 13, data.get("test5").get(1).getInt() ); - assertEquals( 14, data.get("test5").get(2).getInt() ); - assertEquals( 15, data.get("test5").get(3).getInt() ); - - assert( data.get("test6").isList() ); - assertEquals( 4, data.get("test6").size() ); - assertEquals( "a", data.get("test6").get(0).getString() ); - assertEquals( "b", data.get("test6").get(1).getString() ); - assertEquals( "c", data.get("test6").get(2).getString() ); - assertEquals( "d", data.get("test6").get(3).getString() ); - } + @Test + public void complexMap() { + String json = "{" + + "\"test1\": 1234," + + "\"TEST1\": 5678," + + "\"test3\": 1234.99," + + "\"test4\": \"91011\"," + + "\"test5\": [12,13,14,15]," + + "\"test6\": [\"a\",\"b\",\"c\",\"d\"]" + + "}"; + + DataNode data = JSONParser.read(json); + assert( data.isMap() ); + assert( 1234 == data.get("test1").getInt() ); + assert( 5678 == data.get("TEST1").getInt() ); + assert( 1234.99 == data.get("test3").getDouble() ); + assertEquals( "91011", data.get("test4").getString() ); + + assert( data.get("test5").isList() ); + assertEquals( 4, data.get("test5").size() ); + assertEquals( 12, data.get("test5").get(0).getInt() ); + assertEquals( 13, data.get("test5").get(1).getInt() ); + assertEquals( 14, data.get("test5").get(2).getInt() ); + assertEquals( 15, data.get("test5").get(3).getInt() ); + + assert( data.get("test6").isList() ); + assertEquals( 4, data.get("test6").size() ); + assertEquals( "a", data.get("test6").get(0).getString() ); + assertEquals( "b", data.get("test6").get(1).getString() ); + assertEquals( "c", data.get("test6").get(2).getString() ); + assertEquals( "d", data.get("test6").get(3).getString() ); + } } diff --git a/test/zutil/parser/json/JSONSerializerTest.java b/test/zutil/parser/json/JSONSerializerTest.java index d75311f..4498c7d 100755 --- a/test/zutil/parser/json/JSONSerializerTest.java +++ b/test/zutil/parser/json/JSONSerializerTest.java @@ -51,19 +51,19 @@ public class JSONSerializerTest{ assertThat(data, containsString("'value': 42")); assertThat(data, containsString("'decimal': 1.1")); } - - @Test - public void testInputSerializerWithPrimitives() throws InterruptedException, IOException, ClassNotFoundException{ - TestClass sourceObj = new TestClass().init(); - - TestClass targetObj = sendReceiveObject(sourceObj); + + @Test + public void testInputSerializerWithPrimitives() throws InterruptedException, IOException, ClassNotFoundException{ + TestClass sourceObj = new TestClass().init(); + + TestClass targetObj = sendReceiveObject(sourceObj); TestClass.assertEquals(sourceObj, targetObj); - } + } @Test public void testOutputSerializerWithClones() throws InterruptedException, IOException, ClassNotFoundException{ - TestClassObjClone sourceObj = new TestClassObjClone().init(); + TestClassObjClone sourceObj = new TestClassObjClone().init(); String data = writeObjectToJson(sourceObj); data = data.replace("\"", "'"); @@ -72,15 +72,15 @@ public class JSONSerializerTest{ assertThat(data, containsString("'obj1': {'@class': 'zutil.parser.json.JSONSerializerTest$TestObj', '@object_id': 2, 'value': 42}")); assertThat(data, containsString("'obj2': {'@object_id': 2}")); } - - @Test - public void testInputSerializerWithClones() throws InterruptedException, IOException, ClassNotFoundException{ - TestClassObjClone sourceObj = new TestClassObjClone().init(); - - TestClassObjClone targetObj = sendReceiveObject(sourceObj); - - assertEquals( sourceObj, targetObj ); - } + + @Test + public void testInputSerializerWithClones() throws InterruptedException, IOException, ClassNotFoundException{ + TestClassObjClone sourceObj = new TestClassObjClone().init(); + + TestClassObjClone targetObj = sendReceiveObject(sourceObj); + + assertEquals( sourceObj, targetObj ); + } @Test public void testOutputSerializerWithArrays() throws InterruptedException, IOException, ClassNotFoundException{ @@ -110,27 +110,27 @@ public class JSONSerializerTest{ assertEquals( sourceObj, targetObj ); } - @Test - public void testSerializerWithNullFieldsHidden() throws InterruptedException, IOException, ClassNotFoundException{ - TestClass sourceObj = new TestClass(); + @Test + public void testSerializerWithNullFieldsHidden() throws InterruptedException, IOException, ClassNotFoundException{ + TestClass sourceObj = new TestClass(); - String data = writeObjectToJson(sourceObj, false); - data = data.replace("\"", "'"); - assertEquals( - "{'decimal': 0.0}", - data); + String data = writeObjectToJson(sourceObj, false); + data = data.replace("\"", "'"); + assertEquals( + "{'decimal': 0.0}", + data); TestClass targetObj = sendReceiveObject(sourceObj); - TestClass.assertEquals(sourceObj, targetObj); - } + TestClass.assertEquals(sourceObj, targetObj); + } - @Test - public void testSerializerWithMapField() throws InterruptedException, IOException, ClassNotFoundException{ + @Test + public void testSerializerWithMapField() throws InterruptedException, IOException, ClassNotFoundException{ TestClassMap sourceObj = new TestClassMap().init(); TestClassMap targetObj = sendReceiveObject(sourceObj); TestClassMap.assertEquals(sourceObj, targetObj); - } + } @Test public void testSerializerWithMapFieldWithNullEntry() throws InterruptedException, IOException, ClassNotFoundException{ @@ -173,95 +173,95 @@ public class JSONSerializerTest{ TestClass.assertEquals(sourceObj2, targetObj2); } - /******************* Utility Functions ************************************/ - - public static T sendReceiveObject(T sourceObj) throws IOException{ - return readObjectFromJson( - writeObjectToJson(sourceObj)); - } - - @SuppressWarnings("unchecked") + /******************* Utility Functions ************************************/ + + public static T sendReceiveObject(T sourceObj) throws IOException{ + return readObjectFromJson( + writeObjectToJson(sourceObj)); + } + + @SuppressWarnings("unchecked") public static T readObjectFromJson(String json) throws IOException{ - StringReader bin = new StringReader(json); - JSONObjectInputStream in = new JSONObjectInputStream(bin); - T targetObj = (T) in.readObject(); - in.close(); - - return targetObj; - } + StringReader bin = new StringReader(json); + JSONObjectInputStream in = new JSONObjectInputStream(bin); + T targetObj = (T) in.readObject(); + in.close(); - public static String writeObjectToJson(T sourceObj) throws IOException{ - return writeObjectToJson(sourceObj, true); - } + return targetObj; + } + + public static String writeObjectToJson(T sourceObj) throws IOException{ + return writeObjectToJson(sourceObj, true); + } public static String writeObjectToJson(T sourceObj, boolean metadata) throws IOException{ - StringOutputStream bout = new StringOutputStream(); - JSONObjectOutputStream out = new JSONObjectOutputStream(bout); - out.enableMetaData(metadata); + StringOutputStream bout = new StringOutputStream(); + JSONObjectOutputStream out = new JSONObjectOutputStream(bout); + out.enableMetaData(metadata); - out.writeObject(sourceObj); - out.flush(); - out.close(); - - String data = bout.toString(); + out.writeObject(sourceObj); + out.flush(); + out.close(); + + String data = bout.toString(); return data; - } - - /******************** Test Classes ************************************/ - - public static class TestClass implements Serializable{ - private static final long serialVersionUID = 1L; - String str; - double decimal; - TestObj obj1; - TestObj obj2; - - public TestClass init(){ - this.str = "abcd"; - this.decimal = 1.1; - this.obj1 = new TestObj().init(); - this.obj2 = new TestObj().init(); - return this; - } - - public static void assertEquals(TestClass obj1, TestClass obj2){ - Assert.assertEquals(obj1.str, obj2.str); - Assert.assertEquals(obj1.decimal, obj2.decimal, 0.001); - Assert.assertEquals(obj1.obj1, obj2.obj1); - Assert.assertEquals(obj1.obj2, obj2.obj2); - } - } - - public static class TestClassObjClone{ - TestObj obj1; - TestObj obj2; - - public TestClassObjClone init(){ - this.obj1 = this.obj2 = new TestObj().init(); - return this; - } - - public boolean equals(Object obj){ - return obj instanceof TestClassObjClone && - this.obj1.equals(((TestClassObjClone)obj).obj1) && - this.obj1 == this.obj2 && - ((TestClassObjClone)obj).obj1 == ((TestClassObjClone)obj).obj2; - } - } - - public static class TestObj implements Serializable{ - private static final long serialVersionUID = 1L; - int value; - - public TestObj init(){ - this.value = 42; - return this; - } - - public boolean equals(Object obj){ - return obj instanceof TestObj && + } + + /******************** Test Classes ************************************/ + + public static class TestClass implements Serializable{ + private static final long serialVersionUID = 1L; + String str; + double decimal; + TestObj obj1; + TestObj obj2; + + public TestClass init(){ + this.str = "abcd"; + this.decimal = 1.1; + this.obj1 = new TestObj().init(); + this.obj2 = new TestObj().init(); + return this; + } + + public static void assertEquals(TestClass obj1, TestClass obj2){ + Assert.assertEquals(obj1.str, obj2.str); + Assert.assertEquals(obj1.decimal, obj2.decimal, 0.001); + Assert.assertEquals(obj1.obj1, obj2.obj1); + Assert.assertEquals(obj1.obj2, obj2.obj2); + } + } + + public static class TestClassObjClone{ + TestObj obj1; + TestObj obj2; + + public TestClassObjClone init(){ + this.obj1 = this.obj2 = new TestObj().init(); + return this; + } + + public boolean equals(Object obj){ + return obj instanceof TestClassObjClone && + this.obj1.equals(((TestClassObjClone)obj).obj1) && + this.obj1 == this.obj2 && + ((TestClassObjClone)obj).obj1 == ((TestClassObjClone)obj).obj2; + } + } + + public static class TestObj implements Serializable{ + private static final long serialVersionUID = 1L; + int value; + + public TestObj init(){ + this.value = 42; + return this; + } + + public boolean equals(Object obj){ + return obj instanceof TestObj && this.value == ((TestObj)obj).value; - } - } + } + } public static class TestClassArray{ private int[] array; diff --git a/test/zutil/struct/BloomFilterTest.java b/test/zutil/struct/BloomFilterTest.java index 0f8ec82..db09cbf 100755 --- a/test/zutil/struct/BloomFilterTest.java +++ b/test/zutil/struct/BloomFilterTest.java @@ -34,54 +34,54 @@ import java.util.Random; /** * This code may be used, modified, and redistributed provided that the * author tag below remains intact. - * + * * @author Ian Clarke */ public class BloomFilterTest extends TestCase { - public void testBloomFilter() { - DecimalFormat df = new DecimalFormat("0.00000"); - 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 bf = new BloomFilter(bfSize, addCount); - HashSet added = new HashSet(); - for (int x = 0; x < addCount; x++) { - int num = r.nextInt(); - added.add(num); - } - bf.addAll(added); - assertTrue("Assert that there are no false negatives", bf - .containsAll(added)); + public void testBloomFilter() { + DecimalFormat df = new DecimalFormat("0.00000"); + 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 bf = new BloomFilter(bfSize, addCount); + HashSet added = new HashSet(); + for (int x = 0; x < addCount; x++) { + int num = r.nextInt(); + added.add(num); + } + bf.addAll(added); + assertTrue("Assert that there are no false negatives", bf + .containsAll(added)); - int falsePositives = 0; - for (int x = 0; x < addCount; x++) { - int num = r.nextInt(); + int falsePositives = 0; + for (int x = 0; x < addCount; x++) { + int num = r.nextInt(); - // Ensure that this random number hasn't been added already - if (added.contains(num)) { - continue; - } - - // If necessary, record a false positive - if (bf.contains(num)) { - falsePositives++; - } - } - double expectedFP = bf.falsePositiveProbability(); - double actualFP = (double) falsePositives / (double) addCount; - System.out.println("Got " + falsePositives - + " false positives out of " + addCount + " added items, rate = " - + df.format(actualFP) + ", expected = " - + df.format(expectedFP)); - double ratio = actualFP/expectedFP; - assertTrue( - "Assert that the actual false positive rate doesn't deviate by more than 10% from what was predicted, ratio: "+ratio, - ratio < 1.1); - } - } + // Ensure that this random number hasn't been added already + if (added.contains(num)) { + continue; + } + + // If necessary, record a false positive + if (bf.contains(num)) { + falsePositives++; + } + } + double expectedFP = bf.falsePositiveProbability(); + double actualFP = (double) falsePositives / (double) addCount; + System.out.println("Got " + falsePositives + + " false positives out of " + addCount + " added items, rate = " + + df.format(actualFP) + ", expected = " + + df.format(expectedFP)); + double ratio = actualFP/expectedFP; + assertTrue( + "Assert that the actual false positive rate doesn't deviate by more than 10% from what was predicted, ratio: "+ratio, + ratio < 1.1); + } + } } diff --git a/test/zutil/ui/ConsoleTest.java b/test/zutil/ui/ConsoleTest.java index bb78b1f..74e38c8 100755 --- a/test/zutil/ui/ConsoleTest.java +++ b/test/zutil/ui/ConsoleTest.java @@ -30,20 +30,20 @@ import java.io.InputStreamReader; public class ConsoleTest { - public static void main(String[] args) throws IOException{ - Console terminal = new Console("Console Test"); - terminal.enableTray(true); - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + public static void main(String[] args) throws IOException{ + Console terminal = new Console("Console Test"); + terminal.enableTray(true); + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - while(true){ - System.out.println("hello= "+in.readLine()); - for(int i=0; i<2 ;i++){ - System.out.println(i+"Hello World!!!sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"); - System.err.println(i+"Hello World!!!sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"); - try { - Thread.sleep(100); - } catch (InterruptedException e) {} - } - } - } + while(true){ + System.out.println("hello= "+in.readLine()); + for(int i=0; i<2 ;i++){ + System.out.println(i+"Hello World!!!sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"); + System.err.println(i+"Hello World!!!sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"); + try { + Thread.sleep(100); + } catch (InterruptedException e) {} + } + } + } }