Changed folder structure of test classes and renamed some packages

This commit is contained in:
Ziver Koc 2016-03-04 17:48:59 +01:00
parent ccd50ec104
commit 884c5d64c3
76 changed files with 5305 additions and 5375 deletions

View file

@ -22,13 +22,13 @@
* THE SOFTWARE.
*/
package zutil.test;
package zutil;
import org.junit.Test;
import zutil.ByteUtil;
import static org.junit.Assert.assertEquals;
/**
* Created by Ziver on 2016-01-31.
*/

View file

@ -1,73 +1,73 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.Encrypter;
import zutil.Encrypter.Algorithm;
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 key = "abcdefghijklmnopqrstuvwxyz";
@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();
Encrypter encrypter = new Encrypter(Algorithm.Blowfish);
Encrypter.randomizeSalt();
Encrypter decrypter = new Encrypter(encrypter.getKey());
assertEquals(data, encryptDecrypt(encrypter, decrypter, data));
}
@Test
public void encryptAES() throws Exception {
Encrypter.randomizeSalt();
Encrypter encrypter = new Encrypter(key, Algorithm.AES);
Encrypter decrypter = new Encrypter(key, Algorithm.AES);
assertEquals(data, encryptDecrypt(encrypter, decrypter, data));
}
public static String encryptDecrypt(Encrypter encrypter, Encrypter decrypter, String data){
byte[] encrypted = encrypter.encrypt(data.getBytes());
byte[] decrypted = decrypter.decrypt(encrypted);
return new String(decrypted);
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil;
import org.junit.Test;
import zutil.Encrypter.Algorithm;
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 key = "abcdefghijklmnopqrstuvwxyz";
@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();
Encrypter encrypter = new Encrypter(Algorithm.Blowfish);
Encrypter.randomizeSalt();
Encrypter decrypter = new Encrypter(encrypter.getKey());
assertEquals(data, encryptDecrypt(encrypter, decrypter, data));
}
@Test
public void encryptAES() throws Exception {
Encrypter.randomizeSalt();
Encrypter encrypter = new Encrypter(key, Algorithm.AES);
Encrypter decrypter = new Encrypter(key, Algorithm.AES);
assertEquals(data, encryptDecrypt(encrypter, decrypter, data));
}
public static String encryptDecrypt(Encrypter encrypter, Encrypter decrypter, String data){
byte[] encrypted = encrypter.encrypt(data.getBytes());
byte[] decrypted = decrypter.decrypt(encrypted);
return new String(decrypted);
}
}

View file

@ -1,52 +1,51 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.Hasher;
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(".,<>|!#<23>%&/()=?"), "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(".,<>|!#<23>%&/()=?"), "6b3de029cdb367bb365d5154a197294ee590a77a");
assertEquals(Hasher.SHA1("Test45"), "9194c6e64a6801e24e63a924d5843a46428d2b3a");
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil;
import org.junit.Test;
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(".,<>|!#<23>%&/()=?"), "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(".,<>|!#<23>%&/()=?"), "6b3de029cdb367bb365d5154a197294ee590a77a");
assertEquals(Hasher.SHA1("Test45"), "9194c6e64a6801e24e63a924d5843a46428d2b3a");
}
}

View file

@ -1,104 +1,105 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.StringUtil;
import java.util.Arrays;
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 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 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 formatBytesToStringTest(){
byte[] data = new byte[1];
assertEquals("000 00 '. '",
StringUtil.formatBytesToString(data));
data[0] = 65;
assertEquals("000 41 'A '",
StringUtil.formatBytesToString(data));
byte[] data2 = new byte[8];
data2[4] = 65;
assertEquals("000 00 00 00 00 41 00 00 00 '....A...'",
StringUtil.formatBytesToString(data2));
byte[] data3 = new byte[32];
data3[4] = 65;
assertEquals("000 00 00 00 00 41 00 00 00 '....A...'\n"+
"008 00 00 00 00 00 00 00 00 '........'\n"+
"016 00 00 00 00 00 00 00 00 '........'\n"+
"024 00 00 00 00 00 00 00 00 '........'",
StringUtil.formatBytesToString(data3));
}
@Test
public void joinTest(){
assertEquals("", StringUtil.join(Arrays.asList(), ","));
assertEquals("1,2,3,4,5", StringUtil.join(Arrays.asList(1,2,3,4,5), ","));
assertEquals("animal,monkey,dog", StringUtil.join(Arrays.asList("animal", "monkey", "dog"), ","));
assertEquals("12345", StringUtil.join(Arrays.asList(1,2,3,4,5), ""));
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil;
import org.junit.Test;
import zutil.StringUtil;
import java.util.Arrays;
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 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 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 formatBytesToStringTest(){
byte[] data = new byte[1];
assertEquals("000 00 '. '",
StringUtil.formatBytesToString(data));
data[0] = 65;
assertEquals("000 41 'A '",
StringUtil.formatBytesToString(data));
byte[] data2 = new byte[8];
data2[4] = 65;
assertEquals("000 00 00 00 00 41 00 00 00 '....A...'",
StringUtil.formatBytesToString(data2));
byte[] data3 = new byte[32];
data3[4] = 65;
assertEquals("000 00 00 00 00 41 00 00 00 '....A...'\n"+
"008 00 00 00 00 00 00 00 00 '........'\n"+
"016 00 00 00 00 00 00 00 00 '........'\n"+
"024 00 00 00 00 00 00 00 00 '........'",
StringUtil.formatBytesToString(data3));
}
@Test
public void joinTest(){
assertEquals("", StringUtil.join(Arrays.asList(), ","));
assertEquals("1,2,3,4,5", StringUtil.join(Arrays.asList(1,2,3,4,5), ","));
assertEquals("animal,monkey,dog", StringUtil.join(Arrays.asList("animal", "monkey", "dog"), ","));
assertEquals("12345", StringUtil.join(Arrays.asList(1,2,3,4,5), ""));
}
}

View file

@ -1,50 +1,53 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.algo.search.QuickSelect;
import zutil.algo.sort.sortable.SortableIntArray;
import java.util.Arrays;
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.length ;i++){
System.out.println(array[i] +",");
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.algo.search;
import zutil.algo.sort.sortable.SortableIntArray;
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.length ;i++){
System.out.println(array[i] +",");
}
}
}

View file

@ -1,44 +1,42 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.algo.sort.ExternalSort;
import java.io.File;
public class ExternalSortTest {
public static void main(String[] args){
try {
File file = new File("C:\\Users\\Ziver\\Desktop\\IndexFile.txt");
File sortedFile = new File("C:\\Users\\Ziver\\Desktop\\SortedIndexFile.txt");
ExternalSort sort = new ExternalSort(file, sortedFile);
sort.sort();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.algo.sort;
import java.io.File;
public class ExternalSortTest {
public static void main(String[] args){
try {
File file = new File("C:\\Users\\Ziver\\Desktop\\IndexFile.txt");
File sortedFile = new File("C:\\Users\\Ziver\\Desktop\\SortedIndexFile.txt");
ExternalSort sort = new ExternalSort(file, sortedFile);
sort.sort();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View file

@ -1,70 +1,71 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.algo.sort.MergeSort;
import zutil.algo.sort.sortable.SortableIntArray;
@SuppressWarnings("unused")
public class SortTestSimple {
public static final int SIZE = 10000;
public static final int MAX_INT = 10000;
public static void main(String[] args){
int[] array = new int[SIZE];
for(int i=0; i<array.length ;i++){
array[i] = (int)(Math.random()*MAX_INT);
}
for(int i=0; i<array.length ;i++){
System.out.print(array[i]+", ");
}
long time = System.currentTimeMillis();
//SimpleSort.bubbleSort( new SortableIntArray(array) );
//SimpleSort.selectionSort( new SortableIntArray(array) );
//SimpleSort.insertionSort( new SortableIntArray(array) );
//QuickSort.sort( new SortableIntArray(array) );
//MergeSort.sort( array );
MergeSort.sort( new SortableIntArray(array) );
time = System.currentTimeMillis() - time;
System.out.println("\n--------------------------------------------");
System.out.print(array[0]+", ");
int error = -1;
for(int i=1; i<array.length ;i++){
System.out.print(array[i]+", ");
if(array[i-1] > array[i]){
error = i;
}
}
if(error >= 0){
System.out.println("\nArray not sorted!! ("+array[error-1]+" > "+array[error]+")");
}
System.out.println("\nTime: "+time+" ms");
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.algo.sort;
import zutil.algo.sort.MergeSort;
import zutil.algo.sort.sortable.SortableIntArray;
// TODO: Convert to JUnit
@SuppressWarnings("unused")
public class MergeSortTest {
public static final int SIZE = 10000;
public static final int MAX_INT = 10000;
public static void main(String[] args){
int[] array = new int[SIZE];
for(int i=0; i<array.length ;i++){
array[i] = (int)(Math.random()*MAX_INT);
}
for(int i=0; i<array.length ;i++){
System.out.print(array[i]+", ");
}
long time = System.currentTimeMillis();
//SimpleSort.bubbleSort( new SortableIntArray(array) );
//SimpleSort.selectionSort( new SortableIntArray(array) );
//SimpleSort.insertionSort( new SortableIntArray(array) );
//QuickSort.sort( new SortableIntArray(array) );
//MergeSort.sort( array );
MergeSort.sort( new SortableIntArray(array) );
time = System.currentTimeMillis() - time;
System.out.println("\n--------------------------------------------");
System.out.print(array[0]+", ");
int error = -1;
for(int i=1; i<array.length ;i++){
System.out.print(array[i]+", ");
if(array[i-1] > array[i]){
error = i;
}
}
if(error >= 0){
System.out.println("\nArray not sorted!! ("+array[error-1]+" > "+array[error]+")");
}
System.out.println("\nTime: "+time+" ms");
}
}

View file

@ -1,62 +1,61 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.chart.ChartData;
import zutil.chart.LineChart;
import zutil.log.LogUtil;
import javax.swing.*;
import java.util.logging.Level;
public class ChartTest extends JFrame{
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
LogUtil.setLevel("zutil", Level.FINEST);
ChartTest frame = new ChartTest();
frame.setVisible(true);
}
public ChartTest(){
ChartData data = new ChartData();
data.addPoint(1,1);
data.addPoint(2,1);
data.addPoint(3,1);
data.addPoint(4,1);
data.addPoint(5,1);
data.addPoint(6,1);
data.addPoint(7,1);
data.addPoint(8,1);
LineChart chart = new LineChart();
chart.setChartData( data );
this.add( chart );
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setSize(600, 400);
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.chart;
import zutil.log.LogUtil;
import javax.swing.*;
import java.util.logging.Level;
public class ChartTest extends JFrame{
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
LogUtil.setLevel("zutil", Level.FINEST);
ChartTest frame = new ChartTest();
frame.setVisible(true);
}
public ChartTest(){
ChartData data = new ChartData();
data.addPoint(1,1);
data.addPoint(2,1);
data.addPoint(3,1);
data.addPoint(4,1);
data.addPoint(5,1);
data.addPoint(6,1);
data.addPoint(7,1);
data.addPoint(8,1);
LineChart chart = new LineChart();
chart.setChartData( data );
this.add( chart );
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setSize(600, 400);
}
}

View file

@ -1,61 +1,61 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.db.DBConnection;
import zutil.db.handler.SimpleSQLResult;
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<String>());
System.out.println( s );
// Query 4
PreparedStatement sql2 = db.getPreparedStatement("SELECT ?");
sql2.setString(1, "hello");
String s2 = DBConnection.exec(sql2, new SimpleSQLResult<String>());
System.out.println( s2 );
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.db;
import zutil.db.handler.SimpleSQLResult;
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<String>());
System.out.println( s );
// Query 4
PreparedStatement sql2 = db.getPreparedStatement("SELECT ?");
sql2.setString(1, "hello");
String s2 = DBConnection.exec(sql2, new SimpleSQLResult<String>());
System.out.println( s2 );
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View file

@ -1,120 +1,120 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.db.SQLQuery;
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 deleteTest() {
}
@Test
public void createTest() {
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.db;
import org.junit.Test;
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 deleteTest() {
}
@Test
public void createTest() {
}
}

View file

@ -1,130 +1,130 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.ProgressListener;
import zutil.image.ImageFilterProcessor;
import zutil.image.filters.GaussianBlurFilter;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
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 JLabel processedLabel;
private JLabel orginalLabel;
private JProgressBar progress;
public static void main(String[] args){
new ImageProcessorTest();
}
@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);
}
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);
frame.pack();
}
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);
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.image;
import zutil.ProgressListener;
import zutil.image.filter.GaussianBlurFilter;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
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 JLabel processedLabel;
private JLabel orginalLabel;
private JProgressBar progress;
public static void main(String[] args){
new ImageProcessorTest();
}
@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);
}
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);
frame.pack();
}
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);
}
}

View file

@ -1,100 +1,99 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.io.BoundaryBufferedInputStream;
import zutil.io.StringInputStream;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
@SuppressWarnings("resource")
public class BoundaryBufferedInputStreamTest {
@Test
public void testReadB1() throws IOException {
StringInputStream inin = new StringInputStream();
BoundaryBufferedInputStream in = new BoundaryBufferedInputStream(inin);
inin.add("aaa#aaaaaaaaaaaaaaaa#aaaaaaaaaaaaaaa#");
in.setBoundary("#");
int n = 0;
for(n=0; in.read() != -1; n++);
assertEquals(3, n);
in.next();
n = 0;
for(n=0; in.read() != -1; n++);
assertEquals(16, n);
in.next();
n = 0;
for(n=0; in.read() != -1; n++);
assertEquals(15, n);
in.next();
assertEquals(-1, in.read());
}
@Test
public void testOnlyBoundaries() throws IOException {
StringInputStream inin = new StringInputStream();
BoundaryBufferedInputStream in = new BoundaryBufferedInputStream(inin);
inin.add("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
in.setBoundary("a");
int n;
for(n=1; true; n++){
assertEquals(-1, in.read());
assertEquals(-1, in.read());
in.next();
if(!in.isBoundary())
break;
}
assertEquals(35, n);
}
@Test
public void testNoBounds() throws IOException {
String data = "1234567891011121314151617181920";
StringInputStream inin = new StringInputStream();
BoundaryBufferedInputStream in = new BoundaryBufferedInputStream(inin);
inin.add(data);
in.setBoundary("#");
int out;
StringBuilder output = new StringBuilder();
while((out = in.read()) != -1){
output.append((char)out);
}
assertEquals(data, output.toString());
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.io;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
@SuppressWarnings("resource")
public class BoundaryBufferedInputStreamTest {
@Test
public void testReadB1() throws IOException {
StringInputStream inin = new StringInputStream();
BoundaryBufferedInputStream in = new BoundaryBufferedInputStream(inin);
inin.add("aaa#aaaaaaaaaaaaaaaa#aaaaaaaaaaaaaaa#");
in.setBoundary("#");
int n = 0;
for(n=0; in.read() != -1; n++);
assertEquals(3, n);
in.next();
n = 0;
for(n=0; in.read() != -1; n++);
assertEquals(16, n);
in.next();
n = 0;
for(n=0; in.read() != -1; n++);
assertEquals(15, n);
in.next();
assertEquals(-1, in.read());
}
@Test
public void testOnlyBoundaries() throws IOException {
StringInputStream inin = new StringInputStream();
BoundaryBufferedInputStream in = new BoundaryBufferedInputStream(inin);
inin.add("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
in.setBoundary("a");
int n;
for(n=1; true; n++){
assertEquals(-1, in.read());
assertEquals(-1, in.read());
in.next();
if(!in.isBoundary())
break;
}
assertEquals(35, n);
}
@Test
public void testNoBounds() throws IOException {
String data = "1234567891011121314151617181920";
StringInputStream inin = new StringInputStream();
BoundaryBufferedInputStream in = new BoundaryBufferedInputStream(inin);
inin.add(data);
in.setBoundary("#");
int out;
StringBuilder output = new StringBuilder();
while((out = in.read()) != -1){
output.append((char)out);
}
assertEquals(data, output.toString());
}
}

View file

@ -1,58 +1,58 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.io.DynamicByteArrayStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* User: Ziver
*/
public class DynamicByteArrayStreamTest {
@Test
public void emptyArray(){
DynamicByteArrayStream out = new DynamicByteArrayStream();
assertEquals(0, out.available());
assertEquals(0, out.getBytes().length);
assertTrue(out.toString().isEmpty());
}
@Test
public void oneByteArray(){
byte[] b = new byte[]{0x01,0x02,0x03,0x04};
DynamicByteArrayStream out = new DynamicByteArrayStream();
out.append(b);
byte[] result = out.getBytes();
for(int i=0; i<b.length; i++){
assertEquals(b[i], result[i]);
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.io;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* User: Ziver
*/
public class DynamicByteArrayStreamTest {
@Test
public void emptyArray(){
DynamicByteArrayStream out = new DynamicByteArrayStream();
assertEquals(0, out.available());
assertEquals(0, out.getBytes().length);
assertTrue(out.toString().isEmpty());
}
@Test
public void oneByteArray(){
byte[] b = new byte[]{0x01,0x02,0x03,0x04};
DynamicByteArrayStream out = new DynamicByteArrayStream();
out.append(b);
byte[] result = out.getBytes();
for(int i=0; i<b.length; i++){
assertEquals(b[i], result[i]);
}
}
}

View file

@ -1,53 +1,50 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.io.file.FileChangeListener;
import zutil.io.file.FileUtil;
import zutil.io.file.FileWatcher;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
public class FileChangedTest implements FileChangeListener{
public static void main(String[] args) throws URISyntaxException, FileNotFoundException{
FileWatcher watcher = new FileWatcher(FileUtil.find("test.txt"));
watcher.setListener(new FileChangedTest());
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void fileChangedEvent(File file) {
System.out.println(file);
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.io.file;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
public class FileChangedTest implements FileChangeListener{
public static void main(String[] args) throws URISyntaxException, FileNotFoundException{
FileWatcher watcher = new FileWatcher(FileUtil.find("test.txt"));
watcher.setListener(new FileChangedTest());
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void fileChangedEvent(File file) {
System.out.println(file);
}
}

View file

@ -1,73 +1,73 @@
<!--
~ The MIT License (MIT)
~
~ Copyright (c) 2015 Ziver Koc
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy
~ of this software and associated documentation files (the "Software"), to deal
~ in the Software without restriction, including without limitation the rights
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
~ copies of the Software, and to permit persons to whom the Software is
~ furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in
~ all copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
~ THE SOFTWARE.
-->
<html>
<head>
<script type='text/javascript' src='js/jquery-1.4.2.min.js'></script>
<script type='text/javascript' src='upload?js'></script>
<style type='text/css'>
.progressbar{
background: transparent url(img/bar-grey.gif) repeat-x scroll 0%;
border: 1px solid black;
color: white;
height: 16px;
margin: 0pt;
padding: 0pt;
position: relative;
text-align: center;
width; 150px;
border-collapse: collapse;
}
.progressbar b{
background: transparent url(img/bar-revered.gif) repeat-x scroll 0%;
float: left;
height: 16px;
margin: 0pt;
padding: 0pt;
font-size: 11px;
}
ul{
list-style-type: none;
padding: 0px;
margin: 0px;
}
</style>
</head>
<body>
<FORM id="AjaxFileUpload">
<INPUT type="file" name="file" multiple/>
<INPUT type="submit" />
</FORM>
<UL id="UploadQueue">
<li id="1367232194">
<div class="progressbar">
<b id="progress" style="width: 70%; display: block; ">
<span id="filename">Test</span>
</b>
</div>
</li>
</UL>
</body>
<!--
~ The MIT License (MIT)
~
~ Copyright (c) 2015 Ziver Koc
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy
~ of this software and associated documentation files (the "Software"), to deal
~ in the Software without restriction, including without limitation the rights
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
~ copies of the Software, and to permit persons to whom the Software is
~ furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in
~ all copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
~ THE SOFTWARE.
-->
<html>
<head>
<script type='text/javascript' src='js/jquery-1.4.2.min.js'></script>
<script type='text/javascript' src='upload?js'></script>
<style type='text/css'>
.progressbar{
background: transparent url(img/bar-grey.gif) repeat-x scroll 0%;
border: 1px solid black;
color: white;
height: 16px;
margin: 0pt;
padding: 0pt;
position: relative;
text-align: center;
width; 150px;
border-collapse: collapse;
}
.progressbar b{
background: transparent url(img/bar-revered.gif) repeat-x scroll 0%;
float: left;
height: 16px;
margin: 0pt;
padding: 0pt;
font-size: 11px;
}
ul{
list-style-type: none;
padding: 0px;
margin: 0px;
}
</style>
</head>
<body>
<FORM id="AjaxFileUpload">
<INPUT type="file" name="file" multiple/>
<INPUT type="submit" />
</FORM>
<UL id="UploadQueue">
<li id="1367232194">
<div class="progressbar">
<b id="progress" style="width: 70%; display: block; ">
<span id="filename">Test</span>
</b>
</div>
</li>
</UL>
</body>
</html>

View file

@ -1,53 +1,53 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.log.LogUtil;
import zutil.log.net.NetLogServer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NetLogServerTest {
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){}
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.log.net;
import zutil.log.LogUtil;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NetLogServerTest {
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){}
}
}
}

View file

@ -1,40 +1,41 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.net.ServerFindClient;
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();
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net;
import zutil.net.ServerFindClient;
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();
}
}
}

View file

@ -1,39 +1,38 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.net.ServerFind;
import java.io.IOException;
public class ServerFindServerTest {
public static void main(String[] args){
try {
new ServerFind(2000);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net;
import java.io.IOException;
public class ServerFindServerTest {
public static void main(String[] args){
try {
new ServerFind(2000);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View file

@ -1,107 +1,102 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream;
import zutil.net.http.HttpServer;
import java.io.IOException;
import java.util.Map;
public class HTTPGuessTheNumber implements HttpPage{
public static void main(String[] args) throws IOException{
//HttpServer server = new HttpServer("localhost", 443, FileFinder.find("keySSL"), "rootroot");//SSL
HttpServer server = new HttpServer(8080);
server.setDefaultPage(new HTTPGuessTheNumber());
server.run();
}
public void respond(HttpPrintStream out,
HttpHeader client_info,
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request) throws IOException {
out.enableBuffering(true);
out.println("<html>");
out.println("<H2>Welcome To The Number Guess Game!</H2>");
if(session.containsKey("random_nummber") && request.containsKey("guess") && !request.get("guess").isEmpty()){
int guess = Integer.parseInt(request.get("guess"));
int nummber = (Integer)session.get("random_nummber");
try {
if(guess == nummber){
session.remove("random_nummber");
out.println("You Guessed Right! Congrats!");
out.println("</html>");
return;
}
else if(guess > nummber){
out.println("<b>To High</b><br>");
if(Integer.parseInt(cookie.get("high")) > guess){
out.setCookie("high", ""+guess);
cookie.put("high", ""+guess);
}
}
else{
out.println("<b>To Low</b><br>");
if(Integer.parseInt(cookie.get("low")) < guess){
out.setCookie("low", ""+guess);
cookie.put("low", ""+guess);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
else{
session.put("random_nummber", (int)(Math.random()*99+1));
try {
out.setCookie("low", "0");
out.setCookie("high", "100");
cookie.put("low", "0");
cookie.put("high", "100");
} catch (Exception e) {
e.printStackTrace();
}
}
out.println("<form method='post'>");
out.println(cookie.get("low")+" < X < "+cookie.get("high")+"<br>");
out.println("Guess a number between 0 and 100:<br>");
out.println("<input type='text' name='guess'>");
out.println("<input type='hidden' name='test' value='test'>");
out.println("<input type='submit' value='Guess'>");
out.println("</form>");
out.println("<script>document.all.guess.focus();</script>");
out.println("<b>DEBUG: nummber="+session.get("random_nummber")+"</b><br>");
out.println("</html>");
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.http;
import java.io.IOException;
import java.util.Map;
public class HTTPGuessTheNumber implements HttpPage{
public static void main(String[] args) throws IOException{
//HttpServer server = new HttpServer("localhost", 443, FileFinder.find("keySSL"), "rootroot");//SSL
HttpServer server = new HttpServer(8080);
server.setDefaultPage(new HTTPGuessTheNumber());
server.run();
}
public void respond(HttpPrintStream out,
HttpHeader client_info,
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request) throws IOException {
out.enableBuffering(true);
out.println("<html>");
out.println("<H2>Welcome To The Number Guess Game!</H2>");
if(session.containsKey("random_nummber") && request.containsKey("guess") && !request.get("guess").isEmpty()){
int guess = Integer.parseInt(request.get("guess"));
int nummber = (Integer)session.get("random_nummber");
try {
if(guess == nummber){
session.remove("random_nummber");
out.println("You Guessed Right! Congrats!");
out.println("</html>");
return;
}
else if(guess > nummber){
out.println("<b>To High</b><br>");
if(Integer.parseInt(cookie.get("high")) > guess){
out.setCookie("high", ""+guess);
cookie.put("high", ""+guess);
}
}
else{
out.println("<b>To Low</b><br>");
if(Integer.parseInt(cookie.get("low")) < guess){
out.setCookie("low", ""+guess);
cookie.put("low", ""+guess);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
else{
session.put("random_nummber", (int)(Math.random()*99+1));
try {
out.setCookie("low", "0");
out.setCookie("high", "100");
cookie.put("low", "0");
cookie.put("high", "100");
} catch (Exception e) {
e.printStackTrace();
}
}
out.println("<form method='post'>");
out.println(cookie.get("low")+" < X < "+cookie.get("high")+"<br>");
out.println("Guess a number between 0 and 100:<br>");
out.println("<input type='text' name='guess'>");
out.println("<input type='hidden' name='test' value='test'>");
out.println("<input type='submit' value='Guess'>");
out.println("</form>");
out.println("<script>document.all.guess.focus();</script>");
out.println("<b>DEBUG: nummber="+session.get("random_nummber")+"</b><br>");
out.println("</html>");
}
}

View file

@ -1,62 +1,57 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream;
import zutil.net.http.HttpServer;
import java.io.IOException;
import java.util.Map;
public class HTTPUploaderTest implements HttpPage{
public static void main(String[] args) throws IOException{
HttpServer server = new HttpServer(80);
server.setDefaultPage(new HTTPUploaderTest());
server.run();
}
public void respond(HttpPrintStream out,
HttpHeader client_info,
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request) throws IOException {
if(!session.containsKey("file1")){
out.println("</html>" +
" <form enctype='multipart/form-data' method='post'>" +
" <p>Please specify a file, or a set of files:<br>" +
" <input type='file' name='datafile' size='40'>" +
" </p>" +
" <input type='submit' value='Send'>" +
" </form>" +
"</html>");
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.http;
import java.io.IOException;
import java.util.Map;
public class HTTPUploaderTest implements HttpPage{
public static void main(String[] args) throws IOException{
HttpServer server = new HttpServer(80);
server.setDefaultPage(new HTTPUploaderTest());
server.run();
}
public void respond(HttpPrintStream out,
HttpHeader client_info,
Map<String, Object> session,
Map<String, String> cookie,
Map<String, String> request) throws IOException {
if(!session.containsKey("file1")){
out.println("</html>" +
" <form enctype='multipart/form-data' method='post'>" +
" <p>Please specify a file, or a set of files:<br>" +
" <input type='file' name='datafile' size='40'>" +
" </p>" +
" <input type='submit' value='Send'>" +
" </form>" +
"</html>");
}
}
}

View file

@ -1,75 +1,74 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.net.http.HttpURL;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.both;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
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")));
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.http;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
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")));
}
}

View file

@ -1,60 +1,59 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.net.nio.NioClient;
import zutil.net.nio.message.StringMessage;
import zutil.net.nio.response.PrintRsp;
import java.io.IOException;
import java.net.InetAddress;
import java.security.NoSuchAlgorithmException;
@SuppressWarnings("unused")
public class NetworkClientTest {
public static void main(String[] args) throws NoSuchAlgorithmException {
try {
int count = 0;
long time = System.currentTimeMillis()+1000*60;
NioClient client = new NioClient(InetAddress.getByName("localhost"), 6056);
//client.setEncrypter(new Encrypter("lol", Encrypter.PASSPHRASE_DES_ALGO));
while(time > System.currentTimeMillis()){
PrintRsp handler = new PrintRsp();
client.send(handler, new StringMessage("StringMessage: "+count));
handler.waitForResponse();
//try {Thread.sleep(100);} catch (InterruptedException e) {}
//System.out.println("sending..");
count++;
}
System.out.println("Message Count 1m: "+count);
System.out.println("Message Count 1s: "+count/60);
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.nio;
import zutil.net.nio.message.StringMessage;
import zutil.net.nio.response.PrintRsp;
import java.io.IOException;
import java.net.InetAddress;
import java.security.NoSuchAlgorithmException;
@SuppressWarnings("unused")
public class NetworkClientTest {
public static void main(String[] args) throws NoSuchAlgorithmException {
try {
int count = 0;
long time = System.currentTimeMillis()+1000*60;
NioClient client = new NioClient(InetAddress.getByName("localhost"), 6056);
//client.setEncrypter(new Encrypter("lol", Encrypter.PASSPHRASE_DES_ALGO));
while(time > System.currentTimeMillis()){
PrintRsp handler = new PrintRsp();
client.send(handler, new StringMessage("StringMessage: "+count));
handler.waitForResponse();
//try {Thread.sleep(100);} catch (InterruptedException e) {}
//System.out.println("sending..");
count++;
}
System.out.println("Message Count 1m: "+count);
System.out.println("Message Count 1s: "+count/60);
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View file

@ -1,43 +1,41 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.net.nio.NioServer;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
@SuppressWarnings("unused")
public class NetworkServerTest {
public static void main(String[] args) throws NoSuchAlgorithmException {
try {
NioServer server = new NioServer(6056);
//server.setEncrypter(new Encrypter("lol", Encrypter.PASSPHRASE_DES_ALGO));
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.nio;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
@SuppressWarnings("unused")
public class NetworkServerTest {
public static void main(String[] args) throws NoSuchAlgorithmException {
try {
NioServer server = new NioServer(6056);
//server.setEncrypter(new Encrypter("lol", Encrypter.PASSPHRASE_DES_ALGO));
} catch (IOException e) {
e.printStackTrace();
}
}
}

View file

@ -1,51 +1,52 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.log.LogUtil;
import zutil.net.ssdp.SSDPClient;
import java.io.IOException;
import java.util.logging.Level;
/**
* Created by Ziver on 2015-09-29.
*/
public class SSDPClientTest {
public static void main(String[] args) throws IOException {
System.out.println(LogUtil.getCallingClass());
LogUtil.setGlobalLevel(Level.FINEST);
SSDPClient ssdp = new SSDPClient();
ssdp.requestService("upnp:rootdevice");
ssdp.start();
for(int i=0; true ;++i){
while( i==ssdp.getServicesCount("upnp:rootdevice") ){ try{Thread.sleep(100);}catch(Exception e){} }
System.out.println("************************" );
System.out.println("" + ssdp.getServices("upnp:rootdevice").get(i));
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.ssdp;
import zutil.log.LogUtil;
import zutil.net.ssdp.SSDPClient;
import java.io.IOException;
import java.util.logging.Level;
/**
* Created by Ziver on 2015-09-29.
*/
public class SSDPClientTest {
public static void main(String[] args) throws IOException {
System.out.println(LogUtil.getCallingClass());
LogUtil.setGlobalLevel(Level.FINEST);
SSDPClient ssdp = new SSDPClient();
ssdp.requestService("upnp:rootdevice");
ssdp.start();
for(int i=0; true ;++i){
while( i==ssdp.getServicesCount("upnp:rootdevice") ){ try{Thread.sleep(100);}catch(Exception e){} }
System.out.println("************************" );
System.out.println("" + ssdp.getServices("upnp:rootdevice").get(i));
}
}
}

View file

@ -1,54 +1,53 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.log.LogUtil;
import zutil.net.ssdp.SSDPServer;
import zutil.net.ssdp.StandardSSDPInfo;
import java.io.IOException;
import java.util.logging.Level;
/**
* Created by Ziver on 2015-09-29.
*/
public class SSDPServerTest {
public static void main(String[] args) throws IOException {
LogUtil.setGlobalLevel(Level.FINEST);
StandardSSDPInfo service = new StandardSSDPInfo();
service.setLocation("nowhere");
service.setST("zep:discover");
service.setHeader("Alias", "Desktop");
service.setHeader("PublicKey", "SuperDesktopKey");
SSDPServer ssdp = new SSDPServer();
ssdp.addService(service);
ssdp.start();
System.out.println("SSDP Server running");
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.ssdp;
import zutil.log.LogUtil;
import java.io.IOException;
import java.util.logging.Level;
/**
* Created by Ziver on 2015-09-29.
*/
public class SSDPServerTest {
public static void main(String[] args) throws IOException {
LogUtil.setGlobalLevel(Level.FINEST);
StandardSSDPInfo service = new StandardSSDPInfo();
service.setLocation("nowhere");
service.setST("zep:discover");
service.setHeader("Alias", "Desktop");
service.setHeader("PublicKey", "SuperDesktopKey");
SSDPServer ssdp = new SSDPServer();
ssdp.addService(service);
ssdp.start();
System.out.println("SSDP Server running");
}
}

View file

@ -1,75 +1,73 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.ProgressListener;
import zutil.log.CompactLogFormatter;
import zutil.log.LogUtil;
import zutil.net.update.FileInfo;
import zutil.net.update.UpdateClient;
import zutil.net.update.Zupdater;
import java.awt.*;
import java.util.logging.Level;
public class UpdateClientTest implements ProgressListener<UpdateClient, FileInfo>{
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 void progressUpdate(UpdateClient source, FileInfo info, double percent) {
System.out.println(info+": "+percent+"%");
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.update;
import zutil.ProgressListener;
import zutil.log.CompactLogFormatter;
import zutil.log.LogUtil;
import java.awt.*;
import java.util.logging.Level;
public class UpdateClientTest implements ProgressListener<UpdateClient, FileInfo>{
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 void progressUpdate(UpdateClient source, FileInfo info, double percent) {
System.out.println(info+": "+percent+"%");
}
}

View file

@ -1,44 +1,44 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.log.CompactLogFormatter;
import zutil.log.LogUtil;
import zutil.net.update.UpdateServer;
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();
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.update;
import zutil.log.CompactLogFormatter;
import zutil.log.LogUtil;
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();
}
}
}

View file

@ -1,63 +1,63 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.io.MultiPrintStream;
import zutil.net.http.HttpServer;
import zutil.net.ssdp.SSDPServer;
import zutil.net.upnp.UPnPMediaServer;
import zutil.net.upnp.services.UPnPContentDirectory;
import zutil.net.ws.WebServiceDef;
import zutil.net.ws.soap.SOAPHttpPage;
import java.io.File;
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");
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.upnp;
import zutil.io.MultiPrintStream;
import zutil.net.http.HttpServer;
import zutil.net.ssdp.SSDPServer;
import zutil.net.upnp.service.UPnPContentDirectory;
import zutil.net.ws.WebServiceDef;
import zutil.net.ws.soap.SOAPHttpPage;
import java.io.File;
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");
}
}

View file

@ -1,54 +1,55 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.log.CompactLogFormatter;
import zutil.log.LogUtil;
import zutil.net.ws.WSInterface;
import zutil.net.ws.soap.SOAPClientFactory;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
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();
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.ws.soap;
import zutil.log.CompactLogFormatter;
import zutil.log.LogUtil;
import zutil.net.ws.WSInterface;
import java.net.MalformedURLException;
import java.net.URL;
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();
}
}

View file

@ -1,156 +1,157 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import zutil.net.ws.WSInterface;
import zutil.net.ws.WSInterface.WSNamespace;
import zutil.net.ws.WSReturnObject;
import zutil.net.ws.WebServiceDef;
import zutil.net.ws.soap.SOAPHttpPage;
import zutil.parser.wsdl.WSDLWriter;
public class SOAPTest {
/************************* TEST CASES ************************/
public static void main(String[] args){
new SOAPTest();
}
public SOAPTest(){
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 = "<?xml version=\"1.0\"?>\n" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
" <soap:Body xmlns:m=\"http://www.example.org/stock\">\n" +
" <m:stringArrayMethod>\n" +
" <m:StringName>IBM</m:StringName>\n" +
" </m:stringArrayMethod>\n" +
" <m:simpleReturnClassMethod>\n" +
" <m:byte>IBM</m:byte>\n" +
" </m:simpleReturnClassMethod>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
System.out.println(request);
System.out.println( "\n****************** EXECUTION *********************" );
Document document = soap.genSOAPResponse(request);
System.out.println( "\n****************** RESPONSE *********************" );
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter( System.out, format );
writer.write( document );
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("otherValue2")
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";
}
@SuppressWarnings("unused")
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");
}
@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("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("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 (){ }
@WSDisabled()
public void disabledMethod(){ }
protected void protectedMethod(){ }
private void privateMethod(){ }
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.net.ws.soap;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import zutil.net.ws.WSInterface;
import zutil.net.ws.WSInterface.WSNamespace;
import zutil.net.ws.WSReturnObject;
import zutil.net.ws.WebServiceDef;
import zutil.parser.wsdl.WSDLWriter;
// TODO: Convert to JUnit
public class SOAPTest {
/************************* TEST CASES ************************/
public static void main(String[] args){
new SOAPTest();
}
public SOAPTest(){
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 = "<?xml version=\"1.0\"?>\n" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
" <soap:Body xmlns:m=\"http://www.example.org/stock\">\n" +
" <m:stringArrayMethod>\n" +
" <m:StringName>IBM</m:StringName>\n" +
" </m:stringArrayMethod>\n" +
" <m:simpleReturnClassMethod>\n" +
" <m:byte>IBM</m:byte>\n" +
" </m:simpleReturnClassMethod>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
System.out.println(request);
System.out.println( "\n****************** EXECUTION *********************" );
Document document = soap.genSOAPResponse(request);
System.out.println( "\n****************** RESPONSE *********************" );
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter( System.out, format );
writer.write( document );
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("otherValue2")
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";
}
@SuppressWarnings("unused")
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");
}
@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("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("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 (){ }
@WSDisabled()
public void disabledMethod(){ }
protected void protectedMethod(){ }
private void privateMethod(){ }
}
}

View file

@ -1,49 +1,48 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.parser.BBCodeParser;
import static org.junit.Assert.assertEquals;
public class ParserTest{
@Test
public void BBCodeParser() {
BBCodeParser parser = new BBCodeParser();
assertEquals("1234", parser.read("1234"));
assertEquals("<i>1234</i>", parser.read("[i]1234[/i]"));
assertEquals("[apa]lol[/apa]", parser.read("[apa]lol[/apa]"));
assertEquals("jshdkj <u>lol [apa]lol[/apa]</u>", parser.read("jshdkj [u]lol [apa]lol[/apa]"));
//assertEquals("jshdkj [m]lol[/k] <i>lol</i>", 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 <br />", parser.read("jshdkj <br />"));
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.parser;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class BBCodeParserTest{
@Test
public void BBCodeParser() {
BBCodeParser parser = new BBCodeParser();
assertEquals("1234", parser.read("1234"));
assertEquals("<i>1234</i>", parser.read("[i]1234[/i]"));
assertEquals("[apa]lol[/apa]", parser.read("[apa]lol[/apa]"));
assertEquals("jshdkj <u>lol [apa]lol[/apa]</u>", parser.read("jshdkj [u]lol [apa]lol[/apa]"));
//assertEquals("jshdkj [m]lol[/k] <i>lol</i>", 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 <br />", parser.read("jshdkj <br />"));
}
}

View file

@ -1,77 +1,76 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.parser.Base64Decoder;
import zutil.parser.Base64Encoder;
import java.util.Base64;
import static org.junit.Assert.assertEquals;
public class Base64Test {
@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();
}
@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"));
}
@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("YW55IGNhcm5hbCBwbGVhc3VyZQ==", Base64.getEncoder().encodeToString("any carnal pleasure".getBytes()));
assertEquals("bGVhc3VyZS4=", Base64.getEncoder().encodeToString("leasure.".getBytes()));
assertEquals("YW55IGNhcm5hbCBwbGVhc3Vy", Base64.getEncoder().encodeToString("any carnal pleasur".getBytes()));
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.parser;
import org.junit.Test;
import java.util.Base64;
import static org.junit.Assert.assertEquals;
public class Base64Test {
@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();
}
@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"));
}
@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("YW55IGNhcm5hbCBwbGVhc3VyZQ==", Base64.getEncoder().encodeToString("any carnal pleasure".getBytes()));
assertEquals("bGVhc3VyZS4=", Base64.getEncoder().encodeToString("leasure.".getBytes()));
assertEquals("YW55IGNhcm5hbCBwbGVhc3Vy", Base64.getEncoder().encodeToString("any carnal pleasur".getBytes()));
}
}

View file

@ -1,110 +1,109 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.parser.CSVParser;
import zutil.parser.DataNode;
import java.io.IOException;
import java.io.StringReader;
import static org.junit.Assert.assertEquals;
/**
* Created by ezivkoc on 2015-07-30.
*/
public class CSVParserTest {
@Test
public void emptyTest(){
DataNode node = CSVParser.read("");
assertEquals(null, node);
}
@Test
public void simpleTest(){
DataNode node = CSVParser.read("hello,world,you");
assertEquals(3, node.size());
assertEquals("hello", node.get(0).getString());
assertEquals("world", node.get(1).getString());
assertEquals("you", node.get(2).getString());
}
@Test
public void simpleHeaderTest() throws IOException {
CSVParser parser = new CSVParser(new StringReader("where,what,who\nhello,world,you"), true);
DataNode node = parser.read();
assertEquals(3, node.size());
assertEquals("hello", node.get(0).getString());
assertEquals("world", node.get(1).getString());
assertEquals("you", node.get(2).getString());
node = parser.getHeaders();
assertEquals("where", node.get(0).getString());
assertEquals("what", node.get(1).getString());
assertEquals("who", node.get(2).getString());
}
@Test
public void simpleMultilineTest() throws IOException {
CSVParser parser = new CSVParser(
new StringReader("hello,world,you\nhello,world,you\nhello,world,you"));
int rows=0;
for(DataNode node = parser.read(); node != null; node=parser.read(), ++rows) {
assertEquals(3, node.size());
assertEquals("hello", node.get(0).getString());
assertEquals("world", node.get(1).getString());
assertEquals("you", node.get(2).getString());
}
assertEquals(3, rows);
}
@Test
public void quotedTest(){
DataNode node = CSVParser.read("\"hello\",\"world\",\"you\"");
assertEquals(3, node.size());
assertEquals("hello", node.get(0).getString());
assertEquals("world", node.get(1).getString());
assertEquals("you", node.get(2).getString());
}
@Test
public void quotedIncorrectlyTest(){
DataNode node = CSVParser.read("hello\",wo\"rl\"d,\"you\"");
assertEquals(3, node.size());
assertEquals("hello\"", node.get(0).getString());
assertEquals("wo\"rl\"d", node.get(1).getString());
assertEquals("you", node.get(2).getString());
}
@Test
public void quotedCommaTest(){
DataNode node = CSVParser.read("hello,\"world,you\"");
assertEquals(2, node.size());
assertEquals("hello", node.get(0).getString());
assertEquals("world,you", node.get(1).getString());
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.parser;
import org.junit.Test;
import java.io.IOException;
import java.io.StringReader;
import static org.junit.Assert.assertEquals;
/**
* Created by ezivkoc on 2015-07-30.
*/
public class CSVParserTest {
@Test
public void emptyTest(){
DataNode node = CSVParser.read("");
assertEquals(null, node);
}
@Test
public void simpleTest(){
DataNode node = CSVParser.read("hello,world,you");
assertEquals(3, node.size());
assertEquals("hello", node.get(0).getString());
assertEquals("world", node.get(1).getString());
assertEquals("you", node.get(2).getString());
}
@Test
public void simpleHeaderTest() throws IOException {
CSVParser parser = new CSVParser(new StringReader("where,what,who\nhello,world,you"), true);
DataNode node = parser.read();
assertEquals(3, node.size());
assertEquals("hello", node.get(0).getString());
assertEquals("world", node.get(1).getString());
assertEquals("you", node.get(2).getString());
node = parser.getHeaders();
assertEquals("where", node.get(0).getString());
assertEquals("what", node.get(1).getString());
assertEquals("who", node.get(2).getString());
}
@Test
public void simpleMultilineTest() throws IOException {
CSVParser parser = new CSVParser(
new StringReader("hello,world,you\nhello,world,you\nhello,world,you"));
int rows=0;
for(DataNode node = parser.read(); node != null; node=parser.read(), ++rows) {
assertEquals(3, node.size());
assertEquals("hello", node.get(0).getString());
assertEquals("world", node.get(1).getString());
assertEquals("you", node.get(2).getString());
}
assertEquals(3, rows);
}
@Test
public void quotedTest(){
DataNode node = CSVParser.read("\"hello\",\"world\",\"you\"");
assertEquals(3, node.size());
assertEquals("hello", node.get(0).getString());
assertEquals("world", node.get(1).getString());
assertEquals("you", node.get(2).getString());
}
@Test
public void quotedIncorrectlyTest(){
DataNode node = CSVParser.read("hello\",wo\"rl\"d,\"you\"");
assertEquals(3, node.size());
assertEquals("hello\"", node.get(0).getString());
assertEquals("wo\"rl\"d", node.get(1).getString());
assertEquals("you", node.get(2).getString());
}
@Test
public void quotedCommaTest(){
DataNode node = CSVParser.read("hello,\"world,you\"");
assertEquals(2, node.size());
assertEquals("hello", node.get(0).getString());
assertEquals("world,you", node.get(1).getString());
}
}

View file

@ -1,305 +1,305 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.parser.Templator;
import java.util.ArrayList;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
/**
* Created by Ziver on 2015-03-23.
*/
public class TemplatorTest {
class TestClass{
public String attr;
}
class TestSubClass extends TestClass{
public String subAttr;
}
class TestFuncClass{
public boolean isTrue(){
return true;
}
public boolean isFalse(){
return false;
}
}
@Test
public void tagIncorrectTest(){
assertEquals("<HTML>{{</HTML>",
new Templator("<HTML>{{</HTML>").compile());
assertEquals("<HTML>}}</HTML>",
new Templator("<HTML>}}</HTML>").compile());
assertEquals("<HTML></HTML>}}",
new Templator("<HTML></HTML>}}").compile());
assertEquals("<HTML></HTML>{{",
new Templator("<HTML></HTML>{{").compile());
assertEquals("<HTML>{</HTML>",
new Templator("<HTML>{</HTML>").compile());
assertEquals("<HTML>}</HTML>",
new Templator("<HTML>}</HTML>").compile());
assertEquals("<HTML>{}</HTML>",
new Templator("<HTML>{}</HTML>").compile());
assertEquals("<HTML>{test}</HTML>",
new Templator("<HTML>{test}</HTML>").compile());
}
@Test
public void attributeEmptyTest(){
Templator tmpl = new Templator("<HTML>{{test}}</HTML>");
assertEquals("<HTML>null</HTML>", tmpl.compile());
}
@Test
public void attributeSimpleTest() {
Templator tmpl = new Templator("<HTML>{{test}}</HTML>");
tmpl.set("test", "1234");
assertEquals("<HTML>1234</HTML>", tmpl.compile());
}
@Test
public void attributeObjectTest(){
Templator tmpl = new Templator("<HTML>{{test.attr}}</HTML>");
TestClass obj = new TestClass();
obj.attr = "1234";
tmpl.set("test", obj);
assertEquals("<HTML>1234</HTML>", tmpl.compile());
}
@Test
public void conditionIncompleteTest(){
assertEquals("<HTML>{{#key}}</HTML>",
new Templator("<HTML>{{#key}}</HTML>").compile());
assertEquals("<HTML>{{/key}}</HTML>",
new Templator("<HTML>{{/key}}</HTML>").compile());
assertEquals("",
new Templator("{{#key}}{{/key}}").compile());
assertEquals("<HTML></HTML>",
new Templator("<HTML>{{#key}}{{/key}}</HTML>").compile());
}
@Test
public void conditionEmptyTest(){
Templator tmpl = new Templator(
"<HTML>{{#key}}123456789{{/key}}</HTML>");
assertEquals(
"<HTML></HTML>",
tmpl.compile());
}
@Test
public void conditionSimpleTest(){
Templator tmpl = new Templator(
"<HTML>{{#key}}123456789{{/key}}</HTML>");
tmpl.set("key", "set");
assertEquals(
"<HTML>123456789</HTML>",
tmpl.compile());
}
@Test
public void conditionObjectTest(){
Templator tmpl = new Templator("<HTML>{{#test.attr}}5678{{/test.attr}}</HTML>");
TestClass obj = new TestClass();
obj.attr = "1234";
tmpl.set("test", obj);
assertEquals("<HTML>5678</HTML>", tmpl.compile());
tmpl.clear();
tmpl.set("test", new TestClass());
assertEquals("<HTML></HTML>", tmpl.compile());
}
@Test
public void conditionBooleanTest(){
Templator tmpl = new Templator(
"<HTML>{{#key}}123456789{{/key}}</HTML>");
tmpl.set("key", true);
assertEquals(
"<HTML>123456789</HTML>", tmpl.compile());
tmpl.set("key", false);
assertEquals(
"<HTML></HTML>", tmpl.compile());
}
@Test
public void conditionIteratorEmptyTest(){
Templator tmpl = new Templator("<HTML>{{#list}}1234 {{.}} {{/list}}</HTML>");
tmpl.set("list", new ArrayList());
assertEquals(
"<HTML></HTML>", tmpl.compile());
}
@Test
public void conditionIteratorTest(){
Templator tmpl = new Templator("<HTML>{{#list}}{{.}}{{/list}}</HTML>");
tmpl.set("list", Arrays.asList(1,2,3,4,5,6,7,8,9));
assertEquals(
"<HTML>123456789</HTML>", tmpl.compile());
}
@Test
public void conditionArrayTest(){
Templator tmpl = new Templator("<HTML>{{#list}}{{.}}{{/list}}</HTML>");
tmpl.set("list", new int[]{1,2,3,4,5,6,7,8,9});
assertEquals(
"<HTML>123456789</HTML>", tmpl.compile());
}
@Test
public void conditionArrayLength(){
Templator tmpl = new Templator("<HTML>{{#list.length}}run once{{/list.length}}</HTML>");
tmpl.set("list", new int[]{});
assertEquals(
"<HTML></HTML>", tmpl.compile());
tmpl.set("list", new int[]{1});
assertEquals(
"<HTML>run once</HTML>", tmpl.compile());
tmpl.set("list", new int[]{1,2,3,4,5,6,7,8,9});
assertEquals(
"<HTML>run once</HTML>", tmpl.compile());
}
@Test
public void negativeConditionEmptyTest(){
Templator tmpl = new Templator(
"<HTML>{{^key}}123456789{{/key}}</HTML>");
assertEquals(
"<HTML>123456789</HTML>", tmpl.compile());
}
@Test
public void negativeConditionSetTest(){
Templator tmpl = new Templator(
"<HTML>{{^key}}123456789{{/key}}</HTML>");
tmpl.set("key", "set");
assertEquals(
"<HTML></HTML>", tmpl.compile());
}
@Test
public void negativeConditionObjectTest(){
Templator tmpl = new Templator("<HTML>{{^test.attr}}5678{{/test.attr}}</HTML>");
TestClass obj = new TestClass();
obj.attr = "1234";
tmpl.set("test", obj);
assertEquals("<HTML></HTML>", tmpl.compile());
tmpl.clear();
tmpl.set("test", new TestClass());
assertEquals("<HTML>5678</HTML>", tmpl.compile());
}
@Test
public void negativeConditionIteratorTest(){
Templator tmpl = new Templator(
"<HTML>{{^key}}123456789{{/key}}</HTML>");
tmpl.set("key", Arrays.asList(1,2,3,4,5,6,7,8,9));
assertEquals(
"<HTML></HTML>", tmpl.compile());
}
@Test
public void negativeConditionIteratorEmptyTest(){
Templator tmpl = new Templator(
"<HTML>{{^key}}123456789{{/key}}</HTML>");
tmpl.set("key", new ArrayList());
assertEquals(
"<HTML>123456789</HTML>", tmpl.compile());
}
@Test
public void negativeConditionBooleanTest(){
Templator tmpl = new Templator(
"<HTML>{{^key}}123456789{{/key}}</HTML>");
tmpl.set("key", true);
assertEquals(
"<HTML></HTML>", tmpl.compile());
tmpl.set("key", false);
assertEquals(
"<HTML>123456789</HTML>", tmpl.compile());
}
@Test
public void commentTest(){
Templator tmpl = new Templator(
"<HTML>{{! This is a comment}}</HTML>");
assertEquals(
"<HTML></HTML>", tmpl.compile());
}
@Test
public void functionCallTest(){
Templator tmpl = new Templator(
"<HTML>{{#obj.isTrue()}}it is true{{/obj.isTrue()}}</HTML>");
tmpl.set("obj", new TestFuncClass());
assertEquals(
"<HTML>it is true</HTML>", tmpl.compile());
tmpl = new Templator(
"<HTML>{{#obj.isFalse()}}it is true{{/obj.isFalse()}}</HTML>");
tmpl.set("obj", new TestFuncClass());
assertEquals(
"<HTML></HTML>", tmpl.compile());
}
@Test
public void functionInArrayTest(){
Templator tmpl = new Templator(
"<HTML>{{#list}}{{#.isTrue()}}1{{/.isTrue()}}{{/list}}</HTML>");
tmpl.set("list", new TestFuncClass[]{
new TestFuncClass(),new TestFuncClass(),new TestFuncClass()
});
assertEquals(
"<HTML>111</HTML>", tmpl.compile());
}
@Test
public void recursiveTemplateorTest(){
Templator tmpl2 = new Templator(
"{{value1}},{{value2}}");
tmpl2.set("value1", "sub1");
tmpl2.set("value2", "sub2");
Templator tmpl = new Templator(
"<HTML>{{parent}}:{{child}}</HTML>");
tmpl.set("parent", "super");
tmpl.set("child", tmpl2);
assertEquals(
"<HTML>super:sub1,sub2</HTML>", tmpl.compile());
}
@Test
public void subClassTest(){
Templator tmpl = new Templator("<HTML>{{test.attr}}:{{test.subAttr}}</HTML>");
TestSubClass obj = new TestSubClass();
obj.attr = "1234";
obj.subAttr = "5678";
tmpl.set("test", obj);
assertEquals("<HTML>1234:5678</HTML>", tmpl.compile());
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.parser;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
/**
* Created by Ziver on 2015-03-23.
*/
public class TemplatorTest {
class TestClass{
public String attr;
}
class TestSubClass extends TestClass{
public String subAttr;
}
class TestFuncClass{
public boolean isTrue(){
return true;
}
public boolean isFalse(){
return false;
}
}
@Test
public void tagIncorrectTest(){
assertEquals("<HTML>{{</HTML>",
new Templator("<HTML>{{</HTML>").compile());
assertEquals("<HTML>}}</HTML>",
new Templator("<HTML>}}</HTML>").compile());
assertEquals("<HTML></HTML>}}",
new Templator("<HTML></HTML>}}").compile());
assertEquals("<HTML></HTML>{{",
new Templator("<HTML></HTML>{{").compile());
assertEquals("<HTML>{</HTML>",
new Templator("<HTML>{</HTML>").compile());
assertEquals("<HTML>}</HTML>",
new Templator("<HTML>}</HTML>").compile());
assertEquals("<HTML>{}</HTML>",
new Templator("<HTML>{}</HTML>").compile());
assertEquals("<HTML>{test}</HTML>",
new Templator("<HTML>{test}</HTML>").compile());
}
@Test
public void attributeEmptyTest(){
Templator tmpl = new Templator("<HTML>{{test}}</HTML>");
assertEquals("<HTML>null</HTML>", tmpl.compile());
}
@Test
public void attributeSimpleTest() {
Templator tmpl = new Templator("<HTML>{{test}}</HTML>");
tmpl.set("test", "1234");
assertEquals("<HTML>1234</HTML>", tmpl.compile());
}
@Test
public void attributeObjectTest(){
Templator tmpl = new Templator("<HTML>{{test.attr}}</HTML>");
TestClass obj = new TestClass();
obj.attr = "1234";
tmpl.set("test", obj);
assertEquals("<HTML>1234</HTML>", tmpl.compile());
}
@Test
public void conditionIncompleteTest(){
assertEquals("<HTML>{{#key}}</HTML>",
new Templator("<HTML>{{#key}}</HTML>").compile());
assertEquals("<HTML>{{/key}}</HTML>",
new Templator("<HTML>{{/key}}</HTML>").compile());
assertEquals("",
new Templator("{{#key}}{{/key}}").compile());
assertEquals("<HTML></HTML>",
new Templator("<HTML>{{#key}}{{/key}}</HTML>").compile());
}
@Test
public void conditionEmptyTest(){
Templator tmpl = new Templator(
"<HTML>{{#key}}123456789{{/key}}</HTML>");
assertEquals(
"<HTML></HTML>",
tmpl.compile());
}
@Test
public void conditionSimpleTest(){
Templator tmpl = new Templator(
"<HTML>{{#key}}123456789{{/key}}</HTML>");
tmpl.set("key", "set");
assertEquals(
"<HTML>123456789</HTML>",
tmpl.compile());
}
@Test
public void conditionObjectTest(){
Templator tmpl = new Templator("<HTML>{{#test.attr}}5678{{/test.attr}}</HTML>");
TestClass obj = new TestClass();
obj.attr = "1234";
tmpl.set("test", obj);
assertEquals("<HTML>5678</HTML>", tmpl.compile());
tmpl.clear();
tmpl.set("test", new TestClass());
assertEquals("<HTML></HTML>", tmpl.compile());
}
@Test
public void conditionBooleanTest(){
Templator tmpl = new Templator(
"<HTML>{{#key}}123456789{{/key}}</HTML>");
tmpl.set("key", true);
assertEquals(
"<HTML>123456789</HTML>", tmpl.compile());
tmpl.set("key", false);
assertEquals(
"<HTML></HTML>", tmpl.compile());
}
@Test
public void conditionIteratorEmptyTest(){
Templator tmpl = new Templator("<HTML>{{#list}}1234 {{.}} {{/list}}</HTML>");
tmpl.set("list", new ArrayList());
assertEquals(
"<HTML></HTML>", tmpl.compile());
}
@Test
public void conditionIteratorTest(){
Templator tmpl = new Templator("<HTML>{{#list}}{{.}}{{/list}}</HTML>");
tmpl.set("list", Arrays.asList(1,2,3,4,5,6,7,8,9));
assertEquals(
"<HTML>123456789</HTML>", tmpl.compile());
}
@Test
public void conditionArrayTest(){
Templator tmpl = new Templator("<HTML>{{#list}}{{.}}{{/list}}</HTML>");
tmpl.set("list", new int[]{1,2,3,4,5,6,7,8,9});
assertEquals(
"<HTML>123456789</HTML>", tmpl.compile());
}
@Test
public void conditionArrayLength(){
Templator tmpl = new Templator("<HTML>{{#list.length}}run once{{/list.length}}</HTML>");
tmpl.set("list", new int[]{});
assertEquals(
"<HTML></HTML>", tmpl.compile());
tmpl.set("list", new int[]{1});
assertEquals(
"<HTML>run once</HTML>", tmpl.compile());
tmpl.set("list", new int[]{1,2,3,4,5,6,7,8,9});
assertEquals(
"<HTML>run once</HTML>", tmpl.compile());
}
@Test
public void negativeConditionEmptyTest(){
Templator tmpl = new Templator(
"<HTML>{{^key}}123456789{{/key}}</HTML>");
assertEquals(
"<HTML>123456789</HTML>", tmpl.compile());
}
@Test
public void negativeConditionSetTest(){
Templator tmpl = new Templator(
"<HTML>{{^key}}123456789{{/key}}</HTML>");
tmpl.set("key", "set");
assertEquals(
"<HTML></HTML>", tmpl.compile());
}
@Test
public void negativeConditionObjectTest(){
Templator tmpl = new Templator("<HTML>{{^test.attr}}5678{{/test.attr}}</HTML>");
TestClass obj = new TestClass();
obj.attr = "1234";
tmpl.set("test", obj);
assertEquals("<HTML></HTML>", tmpl.compile());
tmpl.clear();
tmpl.set("test", new TestClass());
assertEquals("<HTML>5678</HTML>", tmpl.compile());
}
@Test
public void negativeConditionIteratorTest(){
Templator tmpl = new Templator(
"<HTML>{{^key}}123456789{{/key}}</HTML>");
tmpl.set("key", Arrays.asList(1,2,3,4,5,6,7,8,9));
assertEquals(
"<HTML></HTML>", tmpl.compile());
}
@Test
public void negativeConditionIteratorEmptyTest(){
Templator tmpl = new Templator(
"<HTML>{{^key}}123456789{{/key}}</HTML>");
tmpl.set("key", new ArrayList());
assertEquals(
"<HTML>123456789</HTML>", tmpl.compile());
}
@Test
public void negativeConditionBooleanTest(){
Templator tmpl = new Templator(
"<HTML>{{^key}}123456789{{/key}}</HTML>");
tmpl.set("key", true);
assertEquals(
"<HTML></HTML>", tmpl.compile());
tmpl.set("key", false);
assertEquals(
"<HTML>123456789</HTML>", tmpl.compile());
}
@Test
public void commentTest(){
Templator tmpl = new Templator(
"<HTML>{{! This is a comment}}</HTML>");
assertEquals(
"<HTML></HTML>", tmpl.compile());
}
@Test
public void functionCallTest(){
Templator tmpl = new Templator(
"<HTML>{{#obj.isTrue()}}it is true{{/obj.isTrue()}}</HTML>");
tmpl.set("obj", new TestFuncClass());
assertEquals(
"<HTML>it is true</HTML>", tmpl.compile());
tmpl = new Templator(
"<HTML>{{#obj.isFalse()}}it is true{{/obj.isFalse()}}</HTML>");
tmpl.set("obj", new TestFuncClass());
assertEquals(
"<HTML></HTML>", tmpl.compile());
}
@Test
public void functionInArrayTest(){
Templator tmpl = new Templator(
"<HTML>{{#list}}{{#.isTrue()}}1{{/.isTrue()}}{{/list}}</HTML>");
tmpl.set("list", new TestFuncClass[]{
new TestFuncClass(),new TestFuncClass(),new TestFuncClass()
});
assertEquals(
"<HTML>111</HTML>", tmpl.compile());
}
@Test
public void recursiveTemplateorTest(){
Templator tmpl2 = new Templator(
"{{value1}},{{value2}}");
tmpl2.set("value1", "sub1");
tmpl2.set("value2", "sub2");
Templator tmpl = new Templator(
"<HTML>{{parent}}:{{child}}</HTML>");
tmpl.set("parent", "super");
tmpl.set("child", tmpl2);
assertEquals(
"<HTML>super:sub1,sub2</HTML>", tmpl.compile());
}
@Test
public void subClassTest(){
Templator tmpl = new Templator("<HTML>{{test.attr}}:{{test.subAttr}}</HTML>");
TestSubClass obj = new TestSubClass();
obj.attr = "1234";
obj.subAttr = "5678";
tmpl.set("test", obj);
assertEquals("<HTML>1234:5678</HTML>", tmpl.compile());
}
}

View file

@ -22,7 +22,7 @@
* THE SOFTWARE.
*/
package zutil.test;
package zutil.parser;
import org.junit.Test;
import zutil.parser.URLDecoder;

View file

@ -22,15 +22,14 @@
* THE SOFTWARE.
*/
package zutil.test;
package zutil.parser.binary;
import org.junit.Test;
import zutil.parser.binary.BinaryStruct;
import zutil.parser.binary.BinaryStructParser;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertFalse;
/**
* Created by Ziver on 2016-01-28.
*/

View file

@ -1,183 +1,183 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.parser.DataNode;
import zutil.parser.DataNode.DataType;
import zutil.parser.json.JSONParser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class JSONParserTest {
@Test
public void nullString(){
DataNode data = JSONParser.read(null);
assertNull(data);
}
@Test
public void emptyString(){
DataNode data = JSONParser.read("");
assertNull(data);
}
@Test
public void emptyMap(){
DataNode data = JSONParser.read("{}");
assertEquals(DataType.Map, data.getType());
assertEquals( 0, data.size());
}
@Test
public void emptyList(){
DataNode data = JSONParser.read("[]");
assertEquals(DataType.List, data.getType());
assertEquals( 0, data.size());
}
@Test
public void valueInt(){
DataNode data = JSONParser.read("1234");
assert(data.isValue());
assertEquals( DataType.Number, data.getType());
assertEquals( 1234, data.getInt());
}
@Test
public void valueDouble(){
DataNode data = JSONParser.read("12.34");
assert(data.isValue());
assertEquals( DataType.Number, data.getType());
assertEquals( 12.34, data.getDouble(), 0);
}
@Test
public void valueBoolean(){
DataNode data = JSONParser.read("false");
assert(data.isValue());
assertEquals( DataType.Boolean, data.getType());
assertEquals( false, data.getBoolean());
}
@Test
public void valueBooleanUpperCase(){
DataNode data = JSONParser.read("TRUE");
assert(data.isValue());
assertEquals( DataType.Boolean, data.getType());
assertEquals( true, data.getBoolean());
}
@Test
public void valueStringNoQuotes(){
DataNode data = JSONParser.read("teststring");
assert(data.isValue());
assertEquals( DataType.String, data.getType());
assertEquals( "teststring", data.getString());
}
@Test
public void toManyCommasInList(){
DataNode data = JSONParser.read("[1,2,3,]");
assertEquals(DataType.List, data.getType());
assertEquals( 1, data.get(0).getInt());
assertEquals( 2, data.get(1).getInt());
assertEquals( 3, data.get(2).getInt());
}
@Test
public void toManyCommasInMap(){
DataNode data = JSONParser.read("{1:1,2:2,3:3,}");
assertEquals(DataType.Map, data.getType());
assertEquals( 1, data.get("1").getInt());
assertEquals( 2, data.get("2").getInt());
assertEquals( 3, data.get("3").getInt());
}
@Test
public void nullValueInList(){
DataNode data = JSONParser.read("[1,null,3,]");
assertEquals(DataType.List, data.getType());
assertEquals(3, data.size());
assertEquals( "1", data.get(0).getString());
assertNull(data.get(1));
assertEquals( "3", data.get(2).getString());
}
@Test
public void nullValueInMap(){
DataNode data = JSONParser.read("{1:1,2:null,3:3,}");
assertEquals(DataType.Map, data.getType());
assertEquals(3, data.size());
assertEquals( "1", data.getString("1"));
assertNull(data.get("2"));
assertEquals( "3", data.getString("3"));
}
@Test
public void emptyStringInMap(){
DataNode data = JSONParser.read("{1:{2:\"\"}}");
assertEquals(DataType.Map, data.getType());
assertEquals(1, data.size());
assertEquals( "", data.get("1").getString("2"));
}
@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() );
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.parser.json;
import org.junit.Test;
import zutil.parser.DataNode;
import zutil.parser.DataNode.DataType;
import zutil.parser.json.JSONParser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class JSONParserTest {
@Test
public void nullString(){
DataNode data = JSONParser.read(null);
assertNull(data);
}
@Test
public void emptyString(){
DataNode data = JSONParser.read("");
assertNull(data);
}
@Test
public void emptyMap(){
DataNode data = JSONParser.read("{}");
assertEquals(DataType.Map, data.getType());
assertEquals( 0, data.size());
}
@Test
public void emptyList(){
DataNode data = JSONParser.read("[]");
assertEquals(DataType.List, data.getType());
assertEquals( 0, data.size());
}
@Test
public void valueInt(){
DataNode data = JSONParser.read("1234");
assert(data.isValue());
assertEquals( DataType.Number, data.getType());
assertEquals( 1234, data.getInt());
}
@Test
public void valueDouble(){
DataNode data = JSONParser.read("12.34");
assert(data.isValue());
assertEquals( DataType.Number, data.getType());
assertEquals( 12.34, data.getDouble(), 0);
}
@Test
public void valueBoolean(){
DataNode data = JSONParser.read("false");
assert(data.isValue());
assertEquals( DataType.Boolean, data.getType());
assertEquals( false, data.getBoolean());
}
@Test
public void valueBooleanUpperCase(){
DataNode data = JSONParser.read("TRUE");
assert(data.isValue());
assertEquals( DataType.Boolean, data.getType());
assertEquals( true, data.getBoolean());
}
@Test
public void valueStringNoQuotes(){
DataNode data = JSONParser.read("teststring");
assert(data.isValue());
assertEquals( DataType.String, data.getType());
assertEquals( "teststring", data.getString());
}
@Test
public void toManyCommasInList(){
DataNode data = JSONParser.read("[1,2,3,]");
assertEquals(DataType.List, data.getType());
assertEquals( 1, data.get(0).getInt());
assertEquals( 2, data.get(1).getInt());
assertEquals( 3, data.get(2).getInt());
}
@Test
public void toManyCommasInMap(){
DataNode data = JSONParser.read("{1:1,2:2,3:3,}");
assertEquals(DataType.Map, data.getType());
assertEquals( 1, data.get("1").getInt());
assertEquals( 2, data.get("2").getInt());
assertEquals( 3, data.get("3").getInt());
}
@Test
public void nullValueInList(){
DataNode data = JSONParser.read("[1,null,3,]");
assertEquals(DataType.List, data.getType());
assertEquals(3, data.size());
assertEquals( "1", data.get(0).getString());
assertNull(data.get(1));
assertEquals( "3", data.get(2).getString());
}
@Test
public void nullValueInMap(){
DataNode data = JSONParser.read("{1:1,2:null,3:3,}");
assertEquals(DataType.Map, data.getType());
assertEquals(3, data.size());
assertEquals( "1", data.getString("1"));
assertNull(data.get("2"));
assertEquals( "3", data.getString("3"));
}
@Test
public void emptyStringInMap(){
DataNode data = JSONParser.read("{1:{2:\"\"}}");
assertEquals(DataType.Map, data.getType());
assertEquals(1, data.size());
assertEquals( "", data.get("1").getString("2"));
}
@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() );
}
}

View file

@ -1,125 +1,126 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import com.carrotsearch.junitbenchmarks.BenchmarkRule;
import org.junit.Rule;
import org.junit.Test;
import zutil.test.JSONSerializerTest.TestClass;
import java.io.*;
import static org.junit.Assert.assertEquals;
public class JSONSerializerBenchmark {
private static final int TEST_EXECUTIONS = 2000;
@Rule
public BenchmarkRule benchmarkRun = new BenchmarkRule();
@Test
public void testJavaLegacySerialize() throws InterruptedException, IOException, ClassNotFoundException{
for(int i=0; i<TEST_EXECUTIONS; i++){
TestClass sourceObj = new TestClass().init();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(sourceObj);
out.flush();
out.close();
byte[] data = bout.toByteArray();
ByteArrayInputStream bin = new ByteArrayInputStream(data);
ObjectInputStream in = new ObjectInputStream(bin);
TestClass targetObj = (TestClass) in.readObject();
in.close();
assertEquals( sourceObj, targetObj );
}
}
@Test
public void testJavaJSONSerialize() throws InterruptedException, IOException, ClassNotFoundException{
for(int i=0; i<TEST_EXECUTIONS; i++){
TestClass sourceObj = new TestClass().init();
TestClass targetObj = JSONSerializerTest.sendReceiveObject(sourceObj);
assertEquals( sourceObj, targetObj );
}
}
@Test
public void testOutputJavaLegacySerialize() throws InterruptedException, IOException, ClassNotFoundException{
for(int i=0; i<TEST_EXECUTIONS; i++){
TestClass sourceObj = new TestClass().init();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(sourceObj);
out.flush();
out.close();
byte[] data = bout.toByteArray();
}
}
@Test
public void testOutputJavaJSONSerialize() throws InterruptedException, IOException, ClassNotFoundException{
for(int i=0; i<TEST_EXECUTIONS; i++){
TestClass sourceObj = new TestClass().init();
String targetObj = JSONSerializerTest.writeObjectToJson(sourceObj);
}
}
@Test
public void testInputJavaLegacySerialize() throws InterruptedException, IOException, ClassNotFoundException{
TestClass sourceObj = new TestClass().init();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(sourceObj);
out.flush();
out.close();
byte[] data = bout.toByteArray();
for(int i=0; i<TEST_EXECUTIONS; i++){
ByteArrayInputStream bin = new ByteArrayInputStream(data);
ObjectInputStream in = new ObjectInputStream(bin);
TestClass targetObj = (TestClass) in.readObject();
in.close();
}
}
@Test
public void testInputJavaJSONSerialize() throws InterruptedException, IOException, ClassNotFoundException{
TestClass sourceObj = new TestClass().init();
String sourceStr = JSONSerializerTest.writeObjectToJson(sourceObj);
for(int i=0; i<TEST_EXECUTIONS; i++){
TestClass targetObj = JSONSerializerTest.readObjectFromJson(sourceStr);
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.parser.json;
import com.carrotsearch.junitbenchmarks.BenchmarkRule;
import org.junit.Rule;
import org.junit.Test;
import zutil.parser.json.JSONSerializerTest.TestClass;
import java.io.*;
import static org.junit.Assert.assertEquals;
public class JSONSerializerBenchmark {
private static final int TEST_EXECUTIONS = 2000;
@Rule
public BenchmarkRule benchmarkRun = new BenchmarkRule();
@Test
public void testJavaLegacySerialize() throws InterruptedException, IOException, ClassNotFoundException{
for(int i=0; i<TEST_EXECUTIONS; i++){
TestClass sourceObj = new TestClass().init();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(sourceObj);
out.flush();
out.close();
byte[] data = bout.toByteArray();
ByteArrayInputStream bin = new ByteArrayInputStream(data);
ObjectInputStream in = new ObjectInputStream(bin);
TestClass targetObj = (TestClass) in.readObject();
in.close();
assertEquals( sourceObj, targetObj );
}
}
@Test
public void testJavaJSONSerialize() throws InterruptedException, IOException, ClassNotFoundException{
for(int i=0; i<TEST_EXECUTIONS; i++){
TestClass sourceObj = new TestClass().init();
TestClass targetObj = JSONSerializerTest.sendReceiveObject(sourceObj);
assertEquals( sourceObj, targetObj );
}
}
@Test
public void testOutputJavaLegacySerialize() throws InterruptedException, IOException, ClassNotFoundException{
for(int i=0; i<TEST_EXECUTIONS; i++){
TestClass sourceObj = new TestClass().init();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(sourceObj);
out.flush();
out.close();
byte[] data = bout.toByteArray();
}
}
@Test
public void testOutputJavaJSONSerialize() throws InterruptedException, IOException, ClassNotFoundException{
for(int i=0; i<TEST_EXECUTIONS; i++){
TestClass sourceObj = new TestClass().init();
String targetObj = JSONSerializerTest.writeObjectToJson(sourceObj);
}
}
@Test
public void testInputJavaLegacySerialize() throws InterruptedException, IOException, ClassNotFoundException{
TestClass sourceObj = new TestClass().init();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(sourceObj);
out.flush();
out.close();
byte[] data = bout.toByteArray();
for(int i=0; i<TEST_EXECUTIONS; i++){
ByteArrayInputStream bin = new ByteArrayInputStream(data);
ObjectInputStream in = new ObjectInputStream(bin);
TestClass targetObj = (TestClass) in.readObject();
in.close();
}
}
@Test
public void testInputJavaJSONSerialize() throws InterruptedException, IOException, ClassNotFoundException{
TestClass sourceObj = new TestClass().init();
String sourceStr = JSONSerializerTest.writeObjectToJson(sourceObj);
for(int i=0; i<TEST_EXECUTIONS; i++){
TestClass targetObj = JSONSerializerTest.readObjectFromJson(sourceStr);
}
}
}

View file

@ -1,309 +1,308 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Assert;
import org.junit.Test;
import zutil.io.StringOutputStream;
import zutil.parser.json.JSONObjectInputStream;
import zutil.parser.json.JSONObjectOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class JSONSerializerTest{
@Test
public void testOutputSerializerWithPrimitives() throws InterruptedException, IOException, ClassNotFoundException{
TestClass sourceObj = new TestClass().init();
String data = writeObjectToJson(sourceObj);
data = data.replace("\"", "'");
assertThat(data, containsString("'str': 'abcd'"));
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);
TestClass.assertEquals(sourceObj, targetObj);
}
@Test
public void testOutputSerializerWithClones() throws InterruptedException, IOException, ClassNotFoundException{
TestClassObjClone sourceObj = new TestClassObjClone().init();
String data = writeObjectToJson(sourceObj);
data = data.replace("\"", "'");
assertThat(data, containsString("'@class': 'zutil.test.JSONSerializerTest$TestClassObjClone'"));
assertThat(data, containsString("'obj1': {'@class': 'zutil.test.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 testOutputSerializerWithArrays() throws InterruptedException, IOException, ClassNotFoundException{
TestClassArray sourceObj = new TestClassArray().init();
String data = writeObjectToJson(sourceObj);
data = data.replace("\"", "'");
assertEquals(
"{'@class': 'zutil.test.JSONSerializerTest$TestClassArray', 'array': [1, 2, 3, 4], '@object_id': 1}\n",
data);
}
@Test
public void testInputSerializerWithArrays() throws InterruptedException, IOException, ClassNotFoundException{
TestClassArray sourceObj = new TestClassArray().init();
TestClassArray targetObj = sendReceiveObject(sourceObj);
assertEquals( sourceObj, targetObj );
}
@Test
public void testInputSerializerWithStringArrays() throws InterruptedException, IOException, ClassNotFoundException{
TestClassStringArray sourceObj = new TestClassStringArray().init();
TestClassStringArray targetObj = sendReceiveObject(sourceObj);
assertEquals( sourceObj, targetObj );
}
@Test
public void testSerializerWithNullFieldsHidden() throws InterruptedException, IOException, ClassNotFoundException{
TestClass sourceObj = new TestClass();
String data = writeObjectToJson(sourceObj, false);
data = data.replace("\"", "'");
assertEquals(
"{'decimal': 0.0}\n",
data);
TestClass targetObj = sendReceiveObject(sourceObj);
TestClass.assertEquals(sourceObj, targetObj);
}
@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{
TestClassMap sourceObj = new TestClassMap().init();
sourceObj.map.put("key1", null);
TestClassMap targetObj = sendReceiveObject(sourceObj);
sourceObj.map.remove("key1"); // key1 should not be set in destination
TestClassMap.assertEquals(sourceObj, targetObj);
}
@Test
public void testSerializerWithListField() throws InterruptedException, IOException, ClassNotFoundException{
TestClassList sourceObj = new TestClassList().init();
String data = writeObjectToJson(sourceObj);
data = data.replace("\"", "'");
assertThat(data, containsString("'list': ['value1', 'value2']"));
TestClassList targetObj = sendReceiveObject(sourceObj);
TestClassList.assertEquals(sourceObj, targetObj);
}
/******************* Utility Functions ************************************/
public static <T> T sendReceiveObject(T sourceObj) throws IOException{
return readObjectFromJson(
writeObjectToJson(sourceObj));
}
@SuppressWarnings("unchecked")
public static <T> 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;
}
public static <T> String writeObjectToJson(T sourceObj) throws IOException{
return writeObjectToJson(sourceObj, true);
}
public static <T> String writeObjectToJson(T sourceObj, boolean metadata) throws IOException{
StringOutputStream bout = new StringOutputStream();
JSONObjectOutputStream out = new JSONObjectOutputStream(bout);
out.enableMetaData(metadata);
out.writeObject(sourceObj);
out.flush();
out.close();
String data = bout.toString();
System.out.println(data);
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 &&
this.value == ((TestObj)obj).value;
}
}
public static class TestClassArray{
private int[] array;
public TestClassArray init(){
array = new int[]{1,2,3,4};
return this;
}
public boolean equals(Object obj){
return obj instanceof TestClassArray &&
Arrays.equals(this.array ,((TestClassArray)obj).array);
}
}
public static class TestClassStringArray{
private String[] array;
public TestClassStringArray init(){
array = new String[]{"test","string","array"};
return this;
}
public boolean equals(Object obj){
return obj instanceof TestClassStringArray &&
Arrays.equals(this.array ,((TestClassStringArray)obj).array);
}
}
public static class TestClassMap{
private HashMap<String,String> map;
public TestClassMap init(){
map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
return this;
}
public static void assertEquals(TestClassMap obj1, TestClassMap obj2){
Assert.assertEquals(obj1.map, obj2.map);
}
}
public static class TestClassList{
private ArrayList<String> list;
public TestClassList init(){
list = new ArrayList<>();
list.add("value1");
list.add("value2");
return this;
}
public static void assertEquals(TestClassList obj1, TestClassList obj2){
Assert.assertEquals(obj1.list, obj2.list);
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.parser.json;
import org.junit.Assert;
import org.junit.Test;
import zutil.io.StringOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class JSONSerializerTest{
@Test
public void testOutputSerializerWithPrimitives() throws InterruptedException, IOException, ClassNotFoundException{
TestClass sourceObj = new TestClass().init();
String data = writeObjectToJson(sourceObj);
data = data.replace("\"", "'");
assertThat(data, containsString("'str': 'abcd'"));
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);
TestClass.assertEquals(sourceObj, targetObj);
}
@Test
public void testOutputSerializerWithClones() throws InterruptedException, IOException, ClassNotFoundException{
TestClassObjClone sourceObj = new TestClassObjClone().init();
String data = writeObjectToJson(sourceObj);
data = data.replace("\"", "'");
assertThat(data, containsString("'@class': 'zutil.test.JSONSerializerTest$TestClassObjClone'"));
assertThat(data, containsString("'obj1': {'@class': 'zutil.test.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 testOutputSerializerWithArrays() throws InterruptedException, IOException, ClassNotFoundException{
TestClassArray sourceObj = new TestClassArray().init();
String data = writeObjectToJson(sourceObj);
data = data.replace("\"", "'");
assertEquals(
"{'@class': 'zutil.test.JSONSerializerTest$TestClassArray', 'array': [1, 2, 3, 4], '@object_id': 1}\n",
data);
}
@Test
public void testInputSerializerWithArrays() throws InterruptedException, IOException, ClassNotFoundException{
TestClassArray sourceObj = new TestClassArray().init();
TestClassArray targetObj = sendReceiveObject(sourceObj);
assertEquals( sourceObj, targetObj );
}
@Test
public void testInputSerializerWithStringArrays() throws InterruptedException, IOException, ClassNotFoundException{
TestClassStringArray sourceObj = new TestClassStringArray().init();
TestClassStringArray targetObj = sendReceiveObject(sourceObj);
assertEquals( sourceObj, targetObj );
}
@Test
public void testSerializerWithNullFieldsHidden() throws InterruptedException, IOException, ClassNotFoundException{
TestClass sourceObj = new TestClass();
String data = writeObjectToJson(sourceObj, false);
data = data.replace("\"", "'");
assertEquals(
"{'decimal': 0.0}\n",
data);
TestClass targetObj = sendReceiveObject(sourceObj);
TestClass.assertEquals(sourceObj, targetObj);
}
@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{
TestClassMap sourceObj = new TestClassMap().init();
sourceObj.map.put("key1", null);
TestClassMap targetObj = sendReceiveObject(sourceObj);
sourceObj.map.remove("key1"); // key1 should not be set in destination
TestClassMap.assertEquals(sourceObj, targetObj);
}
@Test
public void testSerializerWithListField() throws InterruptedException, IOException, ClassNotFoundException{
TestClassList sourceObj = new TestClassList().init();
String data = writeObjectToJson(sourceObj);
data = data.replace("\"", "'");
assertThat(data, containsString("'list': ['value1', 'value2']"));
TestClassList targetObj = sendReceiveObject(sourceObj);
TestClassList.assertEquals(sourceObj, targetObj);
}
/******************* Utility Functions ************************************/
public static <T> T sendReceiveObject(T sourceObj) throws IOException{
return readObjectFromJson(
writeObjectToJson(sourceObj));
}
@SuppressWarnings("unchecked")
public static <T> 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;
}
public static <T> String writeObjectToJson(T sourceObj) throws IOException{
return writeObjectToJson(sourceObj, true);
}
public static <T> String writeObjectToJson(T sourceObj, boolean metadata) throws IOException{
StringOutputStream bout = new StringOutputStream();
JSONObjectOutputStream out = new JSONObjectOutputStream(bout);
out.enableMetaData(metadata);
out.writeObject(sourceObj);
out.flush();
out.close();
String data = bout.toString();
System.out.println(data);
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 &&
this.value == ((TestObj)obj).value;
}
}
public static class TestClassArray{
private int[] array;
public TestClassArray init(){
array = new int[]{1,2,3,4};
return this;
}
public boolean equals(Object obj){
return obj instanceof TestClassArray &&
Arrays.equals(this.array ,((TestClassArray)obj).array);
}
}
public static class TestClassStringArray{
private String[] array;
public TestClassStringArray init(){
array = new String[]{"test","string","array"};
return this;
}
public boolean equals(Object obj){
return obj instanceof TestClassStringArray &&
Arrays.equals(this.array ,((TestClassStringArray)obj).array);
}
}
public static class TestClassMap{
private HashMap<String,String> map;
public TestClassMap init(){
map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
return this;
}
public static void assertEquals(TestClassMap obj1, TestClassMap obj2){
Assert.assertEquals(obj1.map, obj2.map);
}
}
public static class TestClassList{
private ArrayList<String> list;
public TestClassList init(){
list = new ArrayList<>();
list.add("value1");
list.add("value2");
return this;
}
public static void assertEquals(TestClassList obj1, TestClassList obj2){
Assert.assertEquals(obj1.list, obj2.list);
}
}
}

View file

@ -1,87 +1,87 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import junit.framework.TestCase;
import zutil.struct.BloomFilter;
import java.text.DecimalFormat;
import java.util.HashSet;
import java.util.Random;
/**
* This code may be used, modified, and redistributed provided that the
* author tag below remains intact.
*
* @author Ian Clarke <ian@uprizer.com>
*/
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<Integer> bf = new BloomFilter<Integer>(bfSize, addCount);
HashSet<Integer> added = new HashSet<Integer>();
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();
// 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.falsePosetiveProbability();
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);
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.struct;
import junit.framework.TestCase;
import java.text.DecimalFormat;
import java.util.HashSet;
import java.util.Random;
/**
* This code may be used, modified, and redistributed provided that the
* author tag below remains intact.
*
* @author Ian Clarke <ian@uprizer.com>
*/
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<Integer> bf = new BloomFilter<Integer>(bfSize, addCount);
HashSet<Integer> added = new HashSet<Integer>();
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();
// 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.falsePosetiveProbability();
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);
}
}
}

View file

@ -1,119 +1,119 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.struct.CircularBuffer;
import java.util.Iterator;
import java.util.NoSuchElementException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* Created by Ziver on 2015-09-22.
*/
public class CircularBufferTest {
@Test
public void addToEmpty() {
CircularBuffer<Integer> buff = new CircularBuffer<Integer>(0);
try {
buff.add(10);
fail("IndexOutOfBoundsException was not thrown");
} catch (IndexOutOfBoundsException e) {}
}
@Test
public void addOneElement() {
CircularBuffer<Integer> buff = new CircularBuffer<Integer>(1);
assertEquals(0, buff.size());
buff.add(10);
assertEquals(1, buff.size());
assertEquals((Integer) 10, buff.get(0));
}
@Test
public void addThreeElements() {
CircularBuffer<Integer> buff = new CircularBuffer<Integer>(10);
buff.add(10);
buff.add(11);
buff.add(12);
assertEquals(3, buff.size());
assertEquals((Integer) 12, buff.get(0));
assertEquals((Integer) 11, buff.get(1));
assertEquals((Integer) 10, buff.get(2));
}
@Test
public void addOutOfRange() {
CircularBuffer<Integer> buff = new CircularBuffer<Integer>(2);
buff.add(10);
buff.add(11);
buff.add(12);
assertEquals(2, buff.size());
assertEquals((Integer) 12, buff.get(0));
assertEquals((Integer) 11, buff.get(1));
try {
buff.get(2);
fail("IndexOutOfBoundsException was not thrown");
} catch (IndexOutOfBoundsException e) {}
}
@Test
public void iteratorEmpty() {
CircularBuffer<Integer> buff = new CircularBuffer<Integer>(10);
Iterator<Integer> it = buff.iterator();
assert (!it.hasNext());
try {
it.next();
fail("NoSuchElementException was not thrown");
} catch (NoSuchElementException e) {}
}
@Test
public void iteratorThreeElements() {
CircularBuffer<Integer> buff = new CircularBuffer<Integer>(10);
buff.add(10);
buff.add(11);
buff.add(12);
Iterator<Integer> it = buff.iterator();
assert (it.hasNext());
assertEquals((Integer) 12, it.next());
assert (it.hasNext());
assertEquals((Integer) 11, it.next());
assert (it.hasNext());
assertEquals((Integer) 10, it.next());
assert (!it.hasNext());
try {
it.next();
fail("NoSuchElementException was not thrown");
} catch (NoSuchElementException e) {}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.struct;
import org.junit.Test;
import java.util.Iterator;
import java.util.NoSuchElementException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* Created by Ziver on 2015-09-22.
*/
public class CircularBufferTest {
@Test
public void addToEmpty() {
CircularBuffer<Integer> buff = new CircularBuffer<Integer>(0);
try {
buff.add(10);
fail("IndexOutOfBoundsException was not thrown");
} catch (IndexOutOfBoundsException e) {}
}
@Test
public void addOneElement() {
CircularBuffer<Integer> buff = new CircularBuffer<Integer>(1);
assertEquals(0, buff.size());
buff.add(10);
assertEquals(1, buff.size());
assertEquals((Integer) 10, buff.get(0));
}
@Test
public void addThreeElements() {
CircularBuffer<Integer> buff = new CircularBuffer<Integer>(10);
buff.add(10);
buff.add(11);
buff.add(12);
assertEquals(3, buff.size());
assertEquals((Integer) 12, buff.get(0));
assertEquals((Integer) 11, buff.get(1));
assertEquals((Integer) 10, buff.get(2));
}
@Test
public void addOutOfRange() {
CircularBuffer<Integer> buff = new CircularBuffer<Integer>(2);
buff.add(10);
buff.add(11);
buff.add(12);
assertEquals(2, buff.size());
assertEquals((Integer) 12, buff.get(0));
assertEquals((Integer) 11, buff.get(1));
try {
buff.get(2);
fail("IndexOutOfBoundsException was not thrown");
} catch (IndexOutOfBoundsException e) {}
}
@Test
public void iteratorEmpty() {
CircularBuffer<Integer> buff = new CircularBuffer<Integer>(10);
Iterator<Integer> it = buff.iterator();
assert (!it.hasNext());
try {
it.next();
fail("NoSuchElementException was not thrown");
} catch (NoSuchElementException e) {}
}
@Test
public void iteratorThreeElements() {
CircularBuffer<Integer> buff = new CircularBuffer<Integer>(10);
buff.add(10);
buff.add(11);
buff.add(12);
Iterator<Integer> it = buff.iterator();
assert (it.hasNext());
assertEquals((Integer) 12, it.next());
assert (it.hasNext());
assertEquals((Integer) 11, it.next());
assert (it.hasNext());
assertEquals((Integer) 10, it.next());
assert (!it.hasNext());
try {
it.next();
fail("NoSuchElementException was not thrown");
} catch (NoSuchElementException e) {}
}
}

View file

@ -22,13 +22,13 @@
* THE SOFTWARE.
*/
package zutil.test;
package zutil.struct;
import org.junit.Test;
import zutil.struct.TimedHashSet;
import static org.junit.Assert.assertFalse;
/**
* Created by Ziver on 2015-11-20.
*/

View file

@ -1,92 +0,0 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import zutil.converters.Converter;
import static org.junit.Assert.assertArrayEquals;
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 testHexStringToByte() {
assertArrayEquals( null, Converter.hexToByte(null) );
assertArrayEquals( new byte[]{}, Converter.hexToByte("") );
assertArrayEquals( new byte[]{0x00}, Converter.hexToByte("0x00") );
assertArrayEquals( new byte[]{0x00}, Converter.hexToByte("00") );
assertArrayEquals(new byte[]{0x07,0x06,0x05,0x04,0x03,0x02,0x01},
Converter.hexToByte("01020304050607") );
assertArrayEquals( new byte[]{0x11,0x0F}, 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 byteArrayToInt(){
assertEquals(0, Converter.toInt(new byte[]{}));
assertEquals(1, Converter.toInt(new byte[]{0b0000_0001}));
assertEquals(1, Converter.toInt(new byte[]{0x00,0x01}));
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)0x7F,(byte)0xFF,(byte)0xFF,(byte)0xFF}));
assertEquals(Integer.MAX_VALUE, Converter.toInt(new byte[]{(byte)0x7F,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF}));
}
}

View file

@ -1,50 +0,0 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.Hasher;
import zutil.io.file.FileUtil;
import java.io.File;
import java.net.URISyntaxException;
import java.util.List;
public class FileFinderHasherTest {
public static void main(String[] args) throws URISyntaxException{
String relativePath = "zutil/test";
File path = FileUtil.find(relativePath);
List<File> files = FileUtil.search(path);
for(int i=0; i<files.size(); i++){
try {
System.out.println(
FileUtil.relativePath(files.get(i), relativePath)+
": "+Hasher.hash(files.get(i),"MD5"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

View file

@ -1,96 +0,0 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import zutil.converters.NumberToWordsConverter;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(Parameterized.class)
public class NumberToWordsConverterTest {
@Parameters
public static Collection<Object[]> 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;
}
@Test
public void testConvert() {
assertThat(new NumberToWordsConverter().convert(input)
, is(equalTo(expected)));
}
}

View file

@ -1,50 +1,49 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.test;
import zutil.ui.Console;
import java.io.BufferedReader;
import java.io.IOException;
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));
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) {}
}
}
}
}
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.ui;
import java.io.BufferedReader;
import java.io.IOException;
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));
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) {}
}
}
}
}