answer
stringlengths
17
10.2M
package repackaged.net.sourceforge.isbnhyphenappender; public enum Group { /** * Group: 978-0 - English language. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 227 * 2280 - 2289 * 229 - 638 * 6390 - 6398 * 6399000 - 6399999 * 640 - 647 * 6480000 - 6489999 * 649 - 654 * 6550 - 6559 * 656 - 699 * 7000 - 8499 * 85000 - 89999 * 900000 - 949999 * 9500000 - 9999999</pre> * <p> * Maximum length: 7 */ _9780(9780, new String[][]{ {"00", "19"}, {"200", "227"}, {"2280", "2289"}, {"229", "638"}, {"6390", "6398"}, {"6399000", "6399999"}, {"640", "647"}, {"6480000", "6489999"}, {"649", "654"}, {"6550", "6559"}, {"656", "699"}, {"7000", "8499"}, {"85000", "89999"}, {"900000", "949999"}, {"9500000", "9999999"},}, 7), /** * Group: 978-1 - English language. * <p> * Valid publisher ranges: * <pre> * 00 - 09 * 100 - 399 * 4000 - 5499 * 55000 - 73199 * 7320000 - 7399999 * 74000 - 77499 * 7750000 - 7753999 * 77540 - 86979 * 869800 - 972999 * 9730 - 9877 * 987800 - 998999 * 9990000 - 9999999</pre> * <p> * Maximum length: 7 */ _9781(9781, new String[][]{ {"00", "09"}, {"100", "399"}, {"4000", "5499"}, {"55000", "73199"}, {"7320000", "7399999"}, {"74000", "77499"}, {"7750000", "7753999"}, {"77540", "86979"}, {"869800", "972999"}, {"9730", "9877"}, {"987800", "998999"}, {"9990000", "9999999"},}, 7), /** * Group: 978-2 - French language. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 349 * 35000 - 39999 * 400 - 489 * 490000 - 494999 * 495 - 699 * 7000 - 8399 * 84000 - 89999 * 900000 - 919799 * 91980 - 91980 * 919810 - 919942 * 9199430 - 9199689 * 919969 - 949999 * 9500000 - 9999999</pre> * <p> * Maximum length: 7 */ _9782(9782, new String[][]{ {"00", "19"}, {"200", "349"}, {"35000", "39999"}, {"400", "489"}, {"490000", "494999"}, {"495", "699"}, {"7000", "8399"}, {"84000", "89999"}, {"900000", "919799"}, {"91980", "91980"}, {"919810", "919942"}, {"9199430", "9199689"}, {"919969", "949999"}, {"9500000", "9999999"},}, 7), /** * Group: 978-3 - German language. * <p> * Valid publisher ranges: * <pre> * 00 - 02 * 030 - 033 * 0340 - 0369 * 03700 - 03999 * 04 - 19 * 200 - 699 * 7000 - 8499 * 85000 - 89999 * 900000 - 949999 * 9500000 - 9539999 * 95400 - 96999 * 9700000 - 9899999 * 99000 - 99499 * 99500 - 99999</pre> * <p> * Maximum length: 7 */ _9783(9783, new String[][]{ {"00", "02"}, {"030", "033"}, {"0340", "0369"}, {"03700", "03999"}, {"04", "19"}, {"200", "699"}, {"7000", "8499"}, {"85000", "89999"}, {"900000", "949999"}, {"9500000", "9539999"}, {"95400", "96999"}, {"9700000", "9899999"}, {"99000", "99499"}, {"99500", "99999"},}, 7), /** * Group: 978-4 - Japan. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 699 * 7000 - 8499 * 85000 - 89999 * 900000 - 949999 * 9500000 - 9999999</pre> * <p> * Maximum length: 7 */ _9784(9784, new String[][]{ {"00", "19"}, {"200", "699"}, {"7000", "8499"}, {"85000", "89999"}, {"900000", "949999"}, {"9500000", "9999999"},}, 7), /** * Group: 978-5 - former U.S.S.R. * <p> * Valid publisher ranges: * <pre> * 00000 - 00499 * 0050 - 0099 * 01 - 19 * 200 - 420 * 4210 - 4299 * 430 - 430 * 4310 - 4399 * 440 - 440 * 4410 - 4499 * 450 - 603 * 6040000 - 6049999 * 605 - 699 * 7000 - 8499 * 85000 - 89999 * 900000 - 909999 * 91000 - 91999 * 9200 - 9299 * 93000 - 94999 * 9500000 - 9500999 * 9501 - 9799 * 98000 - 98999 * 9900000 - 9909999 * 9910 - 9999</pre> * <p> * Maximum length: 7 */ _9785(9785, new String[][]{ {"00000", "00499"}, {"0050", "0099"}, {"01", "19"}, {"200", "420"}, {"4210", "4299"}, {"430", "430"}, {"4310", "4399"}, {"440", "440"}, {"4410", "4499"}, {"450", "603"}, {"6040000", "6049999"}, {"605", "699"}, {"7000", "8499"}, {"85000", "89999"}, {"900000", "909999"}, {"91000", "91999"}, {"9200", "9299"}, {"93000", "94999"}, {"9500000", "9500999"}, {"9501", "9799"}, {"98000", "98999"}, {"9900000", "9909999"}, {"9910", "9999"},}, 7), /** * Group: 978-600 - Iran. * <p> * Valid publisher ranges: * <pre> * 00 - 09 * 100 - 499 * 5000 - 8999 * 90000 - 99999</pre> * <p> * Maximum length: 5 */ _978600(978600, new String[][]{ {"00", "09"}, {"100", "499"}, {"5000", "8999"}, {"90000", "99999"},}, 5), /** * Group: 978-601 - Kazakhstan. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 699 * 7000 - 7999 * 80000 - 84999 * 85 - 99</pre> * <p> * Maximum length: 5 */ _978601(978601, new String[][]{ {"00", "19"}, {"200", "699"}, {"7000", "7999"}, {"80000", "84999"}, {"85", "99"},}, 5), /** * Group: 978-602 - Indonesia. * <p> * Valid publisher ranges: * <pre> * 00 - 07 * 0800 - 0899 * 0900 - 1099 * 1100 - 1199 * 1200 - 1399 * 14000 - 14999 * 1500 - 1699 * 17000 - 17999 * 18000 - 18999 * 19000 - 19999 * 200 - 499 * 50000 - 53999 * 5400 - 5999 * 60000 - 61999 * 6200 - 6749 * 6750 - 6999 * 70000 - 74999 * 7500 - 7999 * 8000 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978602(978602, new String[][]{ {"00", "07"}, {"0800", "0899"}, {"0900", "1099"}, {"1100", "1199"}, {"1200", "1399"}, {"14000", "14999"}, {"1500", "1699"}, {"17000", "17999"}, {"18000", "18999"}, {"19000", "19999"}, {"200", "499"}, {"50000", "53999"}, {"5400", "5999"}, {"60000", "61999"}, {"6200", "6749"}, {"6750", "6999"}, {"70000", "74999"}, {"7500", "7999"}, {"8000", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-603 - Saudi Arabia. * <p> * Valid publisher ranges: * <pre> * 00 - 04 * 05 - 49 * 500 - 799 * 8000 - 8999 * 90000 - 99999</pre> * <p> * Maximum length: 5 */ _978603(978603, new String[][]{ {"00", "04"}, {"05", "49"}, {"500", "799"}, {"8000", "8999"}, {"90000", "99999"},}, 5), /** * Group: 978-604 - Vietnam. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 89 * 900 - 979 * 9800 - 9999</pre> * <p> * Maximum length: 4 */ _978604(978604, new String[][]{ {"0", "4"}, {"50", "89"}, {"900", "979"}, {"9800", "9999"},}, 4), /** * Group: 978-605 - Turkey. * <p> * Valid publisher ranges: * <pre> * 0000000 - 0099999 * 01 - 02 * 030 - 039 * 04 - 09 * 100 - 199 * 2000 - 2399 * 240 - 399 * 4000 - 5999 * 60000 - 89999 * 9000 - 9999</pre> * <p> * Maximum length: 5 */ _978605(978605, new String[][]{ {"0000000", "0099999"}, {"01", "02"}, {"030", "039"}, {"04", "09"}, {"100", "199"}, {"2000", "2399"}, {"240", "399"}, {"4000", "5999"}, {"60000", "89999"}, {"9000", "9999"},}, 5), /** * Group: 978-606 - Romania. * <p> * Valid publisher ranges: * <pre> * 000 - 099 * 10 - 49 * 500 - 799 * 8000 - 9099 * 910 - 919 * 92000 - 97499 * 975 - 999</pre> * <p> * Maximum length: 5 */ _978606(978606, new String[][]{ {"000", "099"}, {"10", "49"}, {"500", "799"}, {"8000", "9099"}, {"910", "919"}, {"92000", "97499"}, {"975", "999"},}, 5), /** * Group: 978-607 - Mexico. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 749 * 7500 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978607(978607, new String[][]{ {"00", "39"}, {"400", "749"}, {"7500", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-608 - Macedonia. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 19 * 200 - 449 * 4500 - 6499 * 65000 - 69999 * 7 - 9</pre> * <p> * Maximum length: 5 */ _978608(978608, new String[][]{ {"0", "0"}, {"10", "19"}, {"200", "449"}, {"4500", "6499"}, {"65000", "69999"}, {"7", "9"},}, 5), /** * Group: 978-609 - Lithuania. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 799 * 8000 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978609(978609, new String[][]{ {"00", "39"}, {"400", "799"}, {"8000", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-611 - Thailand. * <p> * Valid publisher ranges: * <pre> * 0000000 - 9999999</pre> * <p> * Maximum length: 0 */ _978611(978611, new String[][]{ {"0000000", "9999999"},}, 0), /** * Group: 978-612 - Peru. * <p> * Valid publisher ranges: * <pre> * 00 - 29 * 300 - 399 * 4000 - 4499 * 45000 - 49999 * 50 - 99</pre> * <p> * Maximum length: 5 */ _978612(978612, new String[][]{ {"00", "29"}, {"300", "399"}, {"4000", "4499"}, {"45000", "49999"}, {"50", "99"},}, 5), /** * Group: 978-613 - Mauritius. * <p> * Valid publisher ranges: * <pre> * 0 - 9</pre> * <p> * Maximum length: 1 */ _978613(978613, new String[][]{ {"0", "9"},}, 1), /** * Group: 978-614 - Lebanon. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 799 * 8000 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978614(978614, new String[][]{ {"00", "39"}, {"400", "799"}, {"8000", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-615 - Hungary. * <p> * Valid publisher ranges: * <pre> * 00 - 09 * 100 - 499 * 5000 - 7999 * 80000 - 89999 * 9000000 - 9999999</pre> * <p> * Maximum length: 5 */ _978615(978615, new String[][]{ {"00", "09"}, {"100", "499"}, {"5000", "7999"}, {"80000", "89999"}, {"9000000", "9999999"},}, 5), /** * Group: 978-616 - Thailand. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 699 * 7000 - 8999 * 90000 - 99999</pre> * <p> * Maximum length: 5 */ _978616(978616, new String[][]{ {"00", "19"}, {"200", "699"}, {"7000", "8999"}, {"90000", "99999"},}, 5), /** * Group: 978-617 - Ukraine. * <p> * Valid publisher ranges: * <pre> * 00 - 49 * 500 - 699 * 7000 - 8999 * 90000 - 99999</pre> * <p> * Maximum length: 5 */ _978617(978617, new String[][]{ {"00", "49"}, {"500", "699"}, {"7000", "8999"}, {"90000", "99999"},}, 5), /** * Group: 978-618 - Greece. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 499 * 5000 - 7999 * 80000 - 99999</pre> * <p> * Maximum length: 5 */ _978618(978618, new String[][]{ {"00", "19"}, {"200", "499"}, {"5000", "7999"}, {"80000", "99999"},}, 5), /** * Group: 978-619 - Bulgaria. * <p> * Valid publisher ranges: * <pre> * 00 - 14 * 150 - 699 * 7000 - 8999 * 90000 - 99999</pre> * <p> * Maximum length: 5 */ _978619(978619, new String[][]{ {"00", "14"}, {"150", "699"}, {"7000", "8999"}, {"90000", "99999"},}, 5), /** * Group: 978-620 - Mauritius. * <p> * Valid publisher ranges: * <pre> * 0 - 9</pre> * <p> * Maximum length: 1 */ _978620(978620, new String[][]{ {"0", "9"},}, 1), /** * Group: 978-621 - Philippines. * <p> * Valid publisher ranges: * <pre> * 00 - 29 * 3000000 - 3999999 * 400 - 599 * 6000000 - 7999999 * 8000 - 8999 * 9000000 - 9499999 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978621(978621, new String[][]{ {"00", "29"}, {"3000000", "3999999"}, {"400", "599"}, {"6000000", "7999999"}, {"8000", "8999"}, {"9000000", "9499999"}, {"95000", "99999"},}, 5), /** * Group: 978-7 - China, People's Republic. * <p> * Valid publisher ranges: * <pre> * 00 - 09 * 100 - 499 * 5000 - 7999 * 80000 - 89999 * 900000 - 999999</pre> * <p> * Maximum length: 6 */ _9787(9787, new String[][]{ {"00", "09"}, {"100", "499"}, {"5000", "7999"}, {"80000", "89999"}, {"900000", "999999"},}, 6), /** * Group: 978-80 - former Czechoslovakia. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 699 * 7000 - 8499 * 85000 - 89999 * 900000 - 999999</pre> * <p> * Maximum length: 6 */ _97880(97880, new String[][]{ {"00", "19"}, {"200", "699"}, {"7000", "8499"}, {"85000", "89999"}, {"900000", "999999"},}, 6), /** * Group: 978-81 - India. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 699 * 7000 - 8499 * 85000 - 89999 * 900000 - 999999</pre> * <p> * Maximum length: 6 */ _97881(97881, new String[][]{ {"00", "19"}, {"200", "699"}, {"7000", "8499"}, {"85000", "89999"}, {"900000", "999999"},}, 6), /** * Group: 978-82 - Norway. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 689 * 690000 - 699999 * 7000 - 8999 * 90000 - 98999 * 990000 - 999999</pre> * <p> * Maximum length: 6 */ _97882(97882, new String[][]{ {"00", "19"}, {"200", "689"}, {"690000", "699999"}, {"7000", "8999"}, {"90000", "98999"}, {"990000", "999999"},}, 6), /** * Group: 978-83 - Poland. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 599 * 60000 - 69999 * 7000 - 8499 * 85000 - 89999 * 900000 - 999999</pre> * <p> * Maximum length: 6 */ _97883(97883, new String[][]{ {"00", "19"}, {"200", "599"}, {"60000", "69999"}, {"7000", "8499"}, {"85000", "89999"}, {"900000", "999999"},}, 6), /** * Group: 978-84 - Spain. * <p> * Valid publisher ranges: * <pre> * 00 - 12 * 1300 - 1399 * 140 - 149 * 15000 - 19999 * 200 - 699 * 7000 - 8499 * 85000 - 89999 * 9000 - 9199 * 920000 - 923999 * 92400 - 92999 * 930000 - 949999 * 95000 - 96999 * 9700 - 9999</pre> * <p> * Maximum length: 6 */ _97884(97884, new String[][]{ {"00", "12"}, {"1300", "1399"}, {"140", "149"}, {"15000", "19999"}, {"200", "699"}, {"7000", "8499"}, {"85000", "89999"}, {"9000", "9199"}, {"920000", "923999"}, {"92400", "92999"}, {"930000", "949999"}, {"95000", "96999"}, {"9700", "9999"},}, 6), /** * Group: 978-85 - Brazil. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 543 * 5440 - 5479 * 54800 - 54999 * 5500 - 5999 * 60000 - 69999 * 7000 - 8499 * 85000 - 89999 * 900000 - 924999 * 92500 - 94499 * 9450 - 9599 * 96 - 97 * 98000 - 99999</pre> * <p> * Maximum length: 6 */ _97885(97885, new String[][]{ {"00", "19"}, {"200", "543"}, {"5440", "5479"}, {"54800", "54999"}, {"5500", "5999"}, {"60000", "69999"}, {"7000", "8499"}, {"85000", "89999"}, {"900000", "924999"}, {"92500", "94499"}, {"9450", "9599"}, {"96", "97"}, {"98000", "99999"},}, 6), /** * Group: 978-86 - former Yugoslavia. * <p> * Valid publisher ranges: * <pre> * 00 - 29 * 300 - 599 * 6000 - 7999 * 80000 - 89999 * 900000 - 999999</pre> * <p> * Maximum length: 6 */ _97886(97886, new String[][]{ {"00", "29"}, {"300", "599"}, {"6000", "7999"}, {"80000", "89999"}, {"900000", "999999"},}, 6), /** * Group: 978-87 - Denmark. * <p> * Valid publisher ranges: * <pre> * 00 - 29 * 3000000 - 3999999 * 400 - 649 * 6500000 - 6999999 * 7000 - 7999 * 8000000 - 8499999 * 85000 - 94999 * 9500000 - 9699999 * 970000 - 999999</pre> * <p> * Maximum length: 6 */ _97887(97887, new String[][]{ {"00", "29"}, {"3000000", "3999999"}, {"400", "649"}, {"6500000", "6999999"}, {"7000", "7999"}, {"8000000", "8499999"}, {"85000", "94999"}, {"9500000", "9699999"}, {"970000", "999999"},}, 6), /** * Group: 978-88 - Italy. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 326 * 3270 - 3389 * 339 - 599 * 6000 - 8499 * 85000 - 89999 * 900000 - 909999 * 910 - 929 * 9300 - 9399 * 940000 - 947999 * 94800 - 94999 * 95000 - 99999</pre> * <p> * Maximum length: 6 */ _97888(97888, new String[][]{ {"00", "19"}, {"200", "326"}, {"3270", "3389"}, {"339", "599"}, {"6000", "8499"}, {"85000", "89999"}, {"900000", "909999"}, {"910", "929"}, {"9300", "9399"}, {"940000", "947999"}, {"94800", "94999"}, {"95000", "99999"},}, 6), /** * Group: 978-89 - Korea, Republic. * <p> * Valid publisher ranges: * <pre> * 00 - 24 * 250 - 549 * 5500 - 8499 * 85000 - 94999 * 950000 - 969999 * 97000 - 98999 * 990 - 999</pre> * <p> * Maximum length: 6 */ _97889(97889, new String[][]{ {"00", "24"}, {"250", "549"}, {"5500", "8499"}, {"85000", "94999"}, {"950000", "969999"}, {"97000", "98999"}, {"990", "999"},}, 6), /** * Group: 978-90 - Netherlands. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 499 * 5000 - 6999 * 70000 - 79999 * 800000 - 849999 * 8500 - 8999 * 90 - 90 * 9100000 - 9399999 * 94 - 94 * 9500000 - 9999999</pre> * <p> * Maximum length: 6 */ _97890(97890, new String[][]{ {"00", "19"}, {"200", "499"}, {"5000", "6999"}, {"70000", "79999"}, {"800000", "849999"}, {"8500", "8999"}, {"90", "90"}, {"9100000", "9399999"}, {"94", "94"}, {"9500000", "9999999"},}, 6), /** * Group: 978-91 - Sweden. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 49 * 500 - 649 * 6500000 - 6999999 * 7000 - 7999 * 8000000 - 8499999 * 85000 - 94999 * 9500000 - 9699999 * 970000 - 999999</pre> * <p> * Maximum length: 6 */ _97891(97891, new String[][]{ {"0", "1"}, {"20", "49"}, {"500", "649"}, {"6500000", "6999999"}, {"7000", "7999"}, {"8000000", "8499999"}, {"85000", "94999"}, {"9500000", "9699999"}, {"970000", "999999"},}, 6), /** * Group: 978-92 - International NGO Publishers and EU Organizations. * <p> * Valid publisher ranges: * <pre> * 0 - 5 * 60 - 79 * 800 - 899 * 9000 - 9499 * 95000 - 98999 * 990000 - 999999</pre> * <p> * Maximum length: 6 */ _97892(97892, new String[][]{ {"0", "5"}, {"60", "79"}, {"800", "899"}, {"9000", "9499"}, {"95000", "98999"}, {"990000", "999999"},}, 6), /** * Group: 978-93 - India. * <p> * Valid publisher ranges: * <pre> * 00 - 09 * 100 - 499 * 5000 - 7999 * 80000 - 94999 * 950000 - 999999</pre> * <p> * Maximum length: 6 */ _97893(97893, new String[][]{ {"00", "09"}, {"100", "499"}, {"5000", "7999"}, {"80000", "94999"}, {"950000", "999999"},}, 6), /** * Group: 978-94 - Netherlands. * <p> * Valid publisher ranges: * <pre> * 000 - 599 * 6000 - 8999 * 90000 - 99999</pre> * <p> * Maximum length: 5 */ _97894(97894, new String[][]{ {"000", "599"}, {"6000", "8999"}, {"90000", "99999"},}, 5), /** * Group: 978-950 - Argentina. * <p> * Valid publisher ranges: * <pre> * 00 - 49 * 500 - 899 * 9000 - 9899 * 99000 - 99999</pre> * <p> * Maximum length: 5 */ _978950(978950, new String[][]{ {"00", "49"}, {"500", "899"}, {"9000", "9899"}, {"99000", "99999"},}, 5), /** * Group: 978-951 - Finland. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 54 * 550 - 889 * 8900 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978951(978951, new String[][]{ {"0", "1"}, {"20", "54"}, {"550", "889"}, {"8900", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-952 - Finland. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 499 * 5000 - 5999 * 60 - 65 * 6600 - 6699 * 67000 - 69999 * 7000 - 7999 * 80 - 94 * 9500 - 9899 * 99000 - 99999</pre> * <p> * Maximum length: 5 */ _978952(978952, new String[][]{ {"00", "19"}, {"200", "499"}, {"5000", "5999"}, {"60", "65"}, {"6600", "6699"}, {"67000", "69999"}, {"7000", "7999"}, {"80", "94"}, {"9500", "9899"}, {"99000", "99999"},}, 5), /** * Group: 978-953 - Croatia. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 14 * 150 - 509 * 51 - 54 * 55000 - 59999 * 6000 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978953(978953, new String[][]{ {"0", "0"}, {"10", "14"}, {"150", "509"}, {"51", "54"}, {"55000", "59999"}, {"6000", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-954 - Bulgaria. * <p> * Valid publisher ranges: * <pre> * 00 - 28 * 2900 - 2999 * 300 - 799 * 8000 - 8999 * 90000 - 92999 * 9300 - 9999</pre> * <p> * Maximum length: 5 */ _978954(978954, new String[][]{ {"00", "28"}, {"2900", "2999"}, {"300", "799"}, {"8000", "8999"}, {"90000", "92999"}, {"9300", "9999"},}, 5), /** * Group: 978-955 - Sri Lanka. * <p> * Valid publisher ranges: * <pre> * 0000 - 1999 * 20 - 35 * 3600 - 3799 * 38000 - 38999 * 3900 - 4099 * 41000 - 44999 * 4500 - 4999 * 50000 - 54999 * 550 - 719 * 7200 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978955(978955, new String[][]{ {"0000", "1999"}, {"20", "35"}, {"3600", "3799"}, {"38000", "38999"}, {"3900", "4099"}, {"41000", "44999"}, {"4500", "4999"}, {"50000", "54999"}, {"550", "719"}, {"7200", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-956 - Chile. * <p> * Valid publisher ranges: * <pre> * 00 - 08 * 09000 - 09999 * 10 - 19 * 200 - 599 * 6000 - 6999 * 7000 - 9999</pre> * <p> * Maximum length: 5 */ _978956(978956, new String[][]{ {"00", "08"}, {"09000", "09999"}, {"10", "19"}, {"200", "599"}, {"6000", "6999"}, {"7000", "9999"},}, 5), /** * Group: 978-957 - Taiwan. * <p> * Valid publisher ranges: * <pre> * 00 - 02 * 0300 - 0499 * 05 - 19 * 2000 - 2099 * 21 - 27 * 28000 - 30999 * 31 - 43 * 440 - 819 * 8200 - 9699 * 97000 - 99999</pre> * <p> * Maximum length: 5 */ _978957(978957, new String[][]{ {"00", "02"}, {"0300", "0499"}, {"05", "19"}, {"2000", "2099"}, {"21", "27"}, {"28000", "30999"}, {"31", "43"}, {"440", "819"}, {"8200", "9699"}, {"97000", "99999"},}, 5), /** * Group: 978-958 - Colombia. * <p> * Valid publisher ranges: * <pre> * 00 - 53 * 5400 - 5599 * 56000 - 56999 * 57000 - 59999 * 600 - 799 * 8000 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978958(978958, new String[][]{ {"00", "53"}, {"5400", "5599"}, {"56000", "56999"}, {"57000", "59999"}, {"600", "799"}, {"8000", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-959 - Cuba. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 699 * 7000 - 8499 * 85000 - 99999</pre> * <p> * Maximum length: 5 */ _978959(978959, new String[][]{ {"00", "19"}, {"200", "699"}, {"7000", "8499"}, {"85000", "99999"},}, 5), /** * Group: 978-960 - Greece. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 659 * 6600 - 6899 * 690 - 699 * 7000 - 8499 * 85000 - 92999 * 93 - 93 * 9400 - 9799 * 98000 - 99999</pre> * <p> * Maximum length: 5 */ _978960(978960, new String[][]{ {"00", "19"}, {"200", "659"}, {"6600", "6899"}, {"690", "699"}, {"7000", "8499"}, {"85000", "92999"}, {"93", "93"}, {"9400", "9799"}, {"98000", "99999"},}, 5), /** * Group: 978-961 - Slovenia. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 599 * 6000 - 8999 * 90000 - 94999 * 9500000 - 9999999</pre> * <p> * Maximum length: 5 */ _978961(978961, new String[][]{ {"00", "19"}, {"200", "599"}, {"6000", "8999"}, {"90000", "94999"}, {"9500000", "9999999"},}, 5), /** * Group: 978-962 - Hong Kong, China. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 699 * 7000 - 8499 * 85000 - 86999 * 8700 - 8999 * 900 - 999</pre> * <p> * Maximum length: 5 */ _978962(978962, new String[][]{ {"00", "19"}, {"200", "699"}, {"7000", "8499"}, {"85000", "86999"}, {"8700", "8999"}, {"900", "999"},}, 5), /** * Group: 978-963 - Hungary. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 699 * 7000 - 8499 * 85000 - 89999 * 9000 - 9999</pre> * <p> * Maximum length: 5 */ _978963(978963, new String[][]{ {"00", "19"}, {"200", "699"}, {"7000", "8499"}, {"85000", "89999"}, {"9000", "9999"},}, 5), /** * Group: 978-964 - Iran. * <p> * Valid publisher ranges: * <pre> * 00 - 14 * 150 - 249 * 2500 - 2999 * 300 - 549 * 5500 - 8999 * 90000 - 96999 * 970 - 989 * 9900 - 9999</pre> * <p> * Maximum length: 5 */ _978964(978964, new String[][]{ {"00", "14"}, {"150", "249"}, {"2500", "2999"}, {"300", "549"}, {"5500", "8999"}, {"90000", "96999"}, {"970", "989"}, {"9900", "9999"},}, 5), /** * Group: 978-965 - Israel. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 599 * 6000000 - 6999999 * 7000 - 7999 * 8000000 - 8999999 * 90000 - 99999</pre> * <p> * Maximum length: 5 */ _978965(978965, new String[][]{ {"00", "19"}, {"200", "599"}, {"6000000", "6999999"}, {"7000", "7999"}, {"8000000", "8999999"}, {"90000", "99999"},}, 5), /** * Group: 978-966 - Ukraine. * <p> * Valid publisher ranges: * <pre> * 00 - 12 * 130 - 139 * 14 - 14 * 1500 - 1699 * 170 - 199 * 2000 - 2789 * 279 - 289 * 2900 - 2999 * 300 - 699 * 7000 - 8999 * 90000 - 90999 * 910 - 949 * 95000 - 97999 * 980 - 999</pre> * <p> * Maximum length: 5 */ _978966(978966, new String[][]{ {"00", "12"}, {"130", "139"}, {"14", "14"}, {"1500", "1699"}, {"170", "199"}, {"2000", "2789"}, {"279", "289"}, {"2900", "2999"}, {"300", "699"}, {"7000", "8999"}, {"90000", "90999"}, {"910", "949"}, {"95000", "97999"}, {"980", "999"},}, 5), /** * Group: 978-967 - Malaysia. * <p> * Valid publisher ranges: * <pre> * 00 - 00 * 0100 - 0999 * 10000 - 19999 * 2000 - 2499 * 2500000 - 2999999 * 300 - 499 * 5000 - 5999 * 60 - 89 * 900 - 989 * 9900 - 9989 * 99900 - 99999</pre> * <p> * Maximum length: 5 */ _978967(978967, new String[][]{ {"00", "00"}, {"0100", "0999"}, {"10000", "19999"}, {"2000", "2499"}, {"2500000", "2999999"}, {"300", "499"}, {"5000", "5999"}, {"60", "89"}, {"900", "989"}, {"9900", "9989"}, {"99900", "99999"},}, 5), /** * Group: 978-968 - Mexico. * <p> * Valid publisher ranges: * <pre> * 01 - 39 * 400 - 499 * 5000 - 7999 * 800 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _978968(978968, new String[][]{ {"01", "39"}, {"400", "499"}, {"5000", "7999"}, {"800", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-969 - Pakistan. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 22 * 23000 - 23999 * 24 - 39 * 400 - 749 * 7500 - 9999</pre> * <p> * Maximum length: 5 */ _978969(978969, new String[][]{ {"0", "1"}, {"20", "22"}, {"23000", "23999"}, {"24", "39"}, {"400", "749"}, {"7500", "9999"},}, 5), /** * Group: 978-970 - Mexico. * <p> * Valid publisher ranges: * <pre> * 01 - 59 * 600 - 899 * 9000 - 9099 * 91000 - 96999 * 9700 - 9999</pre> * <p> * Maximum length: 5 */ _978970(978970, new String[][]{ {"01", "59"}, {"600", "899"}, {"9000", "9099"}, {"91000", "96999"}, {"9700", "9999"},}, 5), /** * Group: 978-971 - Philippines. * <p> * Valid publisher ranges: * <pre> * 000 - 015 * 0160 - 0199 * 02 - 02 * 0300 - 0599 * 06 - 49 * 500 - 849 * 8500 - 9099 * 91000 - 95999 * 9600 - 9699 * 97 - 98 * 9900 - 9999</pre> * <p> * Maximum length: 5 */ _978971(978971, new String[][]{ {"000", "015"}, {"0160", "0199"}, {"02", "02"}, {"0300", "0599"}, {"06", "49"}, {"500", "849"}, {"8500", "9099"}, {"91000", "95999"}, {"9600", "9699"}, {"97", "98"}, {"9900", "9999"},}, 5), /** * Group: 978-972 - Portugal. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 54 * 550 - 799 * 8000 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978972(978972, new String[][]{ {"0", "1"}, {"20", "54"}, {"550", "799"}, {"8000", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-973 - Romania. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 100 - 169 * 1700 - 1999 * 20 - 54 * 550 - 759 * 7600 - 8499 * 85000 - 88999 * 8900 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978973(978973, new String[][]{ {"0", "0"}, {"100", "169"}, {"1700", "1999"}, {"20", "54"}, {"550", "759"}, {"7600", "8499"}, {"85000", "88999"}, {"8900", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-974 - Thailand. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 699 * 7000 - 8499 * 85000 - 89999 * 90000 - 94999 * 9500 - 9999</pre> * <p> * Maximum length: 5 */ _978974(978974, new String[][]{ {"00", "19"}, {"200", "699"}, {"7000", "8499"}, {"85000", "89999"}, {"90000", "94999"}, {"9500", "9999"},}, 5), /** * Group: 978-975 - Turkey. * <p> * Valid publisher ranges: * <pre> * 00000 - 01999 * 02 - 23 * 2400 - 2499 * 250 - 599 * 6000 - 9199 * 92000 - 98999 * 990 - 999</pre> * <p> * Maximum length: 5 */ _978975(978975, new String[][]{ {"00000", "01999"}, {"02", "23"}, {"2400", "2499"}, {"250", "599"}, {"6000", "9199"}, {"92000", "98999"}, {"990", "999"},}, 5), /** * Group: 978-976 - Caribbean Community. * <p> * Valid publisher ranges: * <pre> * 0 - 3 * 40 - 59 * 600 - 799 * 8000 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978976(978976, new String[][]{ {"0", "3"}, {"40", "59"}, {"600", "799"}, {"8000", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-977 - Egypt. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 499 * 5000 - 6999 * 700 - 849 * 85000 - 89999 * 90 - 99</pre> * <p> * Maximum length: 5 */ _978977(978977, new String[][]{ {"00", "19"}, {"200", "499"}, {"5000", "6999"}, {"700", "849"}, {"85000", "89999"}, {"90", "99"},}, 5), /** * Group: 978-978 - Nigeria. * <p> * Valid publisher ranges: * <pre> * 000 - 199 * 2000 - 2999 * 30000 - 79999 * 8000 - 8999 * 900 - 999</pre> * <p> * Maximum length: 5 */ _978978(978978, new String[][]{ {"000", "199"}, {"2000", "2999"}, {"30000", "79999"}, {"8000", "8999"}, {"900", "999"},}, 5), /** * Group: 978-979 - Indonesia. * <p> * Valid publisher ranges: * <pre> * 000 - 099 * 1000 - 1499 * 15000 - 19999 * 20 - 29 * 3000 - 3999 * 400 - 799 * 8000 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978979(978979, new String[][]{ {"000", "099"}, {"1000", "1499"}, {"15000", "19999"}, {"20", "29"}, {"3000", "3999"}, {"400", "799"}, {"8000", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-980 - Venezuela. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 599 * 6000 - 9999</pre> * <p> * Maximum length: 4 */ _978980(978980, new String[][]{ {"00", "19"}, {"200", "599"}, {"6000", "9999"},}, 4), /** * Group: 978-981 - Singapore. * <p> * Valid publisher ranges: * <pre> * 00 - 16 * 17000 - 19999 * 200 - 299 * 3000 - 3099 * 310 - 399 * 4000 - 9999</pre> * <p> * Maximum length: 5 */ _978981(978981, new String[][]{ {"00", "16"}, {"17000", "19999"}, {"200", "299"}, {"3000", "3099"}, {"310", "399"}, {"4000", "9999"},}, 5), /** * Group: 978-982 - South Pacific. * <p> * Valid publisher ranges: * <pre> * 00 - 09 * 100 - 699 * 70 - 89 * 9000 - 9799 * 98000 - 99999</pre> * <p> * Maximum length: 5 */ _978982(978982, new String[][]{ {"00", "09"}, {"100", "699"}, {"70", "89"}, {"9000", "9799"}, {"98000", "99999"},}, 5), /** * Group: 978-983 - Malaysia. * <p> * Valid publisher ranges: * <pre> * 00 - 01 * 020 - 199 * 2000 - 3999 * 40000 - 44999 * 45 - 49 * 50 - 79 * 800 - 899 * 9000 - 9899 * 99000 - 99999</pre> * <p> * Maximum length: 5 */ _978983(978983, new String[][]{ {"00", "01"}, {"020", "199"}, {"2000", "3999"}, {"40000", "44999"}, {"45", "49"}, {"50", "79"}, {"800", "899"}, {"9000", "9899"}, {"99000", "99999"},}, 5), /** * Group: 978-984 - Bangladesh. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 799 * 8000 - 8999 * 90000 - 99999</pre> * <p> * Maximum length: 5 */ _978984(978984, new String[][]{ {"00", "39"}, {"400", "799"}, {"8000", "8999"}, {"90000", "99999"},}, 5), /** * Group: 978-985 - Belarus. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 599 * 6000 - 8999 * 90000 - 99999</pre> * <p> * Maximum length: 5 */ _978985(978985, new String[][]{ {"00", "39"}, {"400", "599"}, {"6000", "8999"}, {"90000", "99999"},}, 5), /** * Group: 978-986 - Taiwan. * <p> * Valid publisher ranges: * <pre> * 00 - 11 * 120 - 559 * 5600 - 7999 * 80000 - 99999</pre> * <p> * Maximum length: 5 */ _978986(978986, new String[][]{ {"00", "11"}, {"120", "559"}, {"5600", "7999"}, {"80000", "99999"},}, 5), /** * Group: 978-987 - Argentina. * <p> * Valid publisher ranges: * <pre> * 00 - 09 * 1000 - 1999 * 20000 - 29999 * 30 - 35 * 3600 - 3999 * 4000 - 4199 * 42 - 43 * 4400 - 4499 * 45000 - 48999 * 4900 - 4999 * 500 - 899 * 9000 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978987(978987, new String[][]{ {"00", "09"}, {"1000", "1999"}, {"20000", "29999"}, {"30", "35"}, {"3600", "3999"}, {"4000", "4199"}, {"42", "43"}, {"4400", "4499"}, {"45000", "48999"}, {"4900", "4999"}, {"500", "899"}, {"9000", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-988 - Hong Kong, China. * <p> * Valid publisher ranges: * <pre> * 00 - 11 * 12000 - 14999 * 15000 - 16999 * 17000 - 19999 * 200 - 769 * 77000 - 79999 * 8000 - 9699 * 97000 - 99999</pre> * <p> * Maximum length: 5 */ _978988(978988, new String[][]{ {"00", "11"}, {"12000", "14999"}, {"15000", "16999"}, {"17000", "19999"}, {"200", "769"}, {"77000", "79999"}, {"8000", "9699"}, {"97000", "99999"},}, 5), /** * Group: 978-989 - Portugal. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 53 * 54000 - 54999 * 550 - 799 * 8000 - 9499 * 95000 - 99999</pre> * <p> * Maximum length: 5 */ _978989(978989, new String[][]{ {"0", "1"}, {"20", "53"}, {"54000", "54999"}, {"550", "799"}, {"8000", "9499"}, {"95000", "99999"},}, 5), /** * Group: 978-9922 - Iraq. * <p> * Valid publisher ranges: * <pre> * 0000000 - 1999999 * 20 - 29 * 3000000 - 5999999 * 600 - 799 * 8000000 - 8999999 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789922(9789922, new String[][]{ {"0000000", "1999999"}, {"20", "29"}, {"3000000", "5999999"}, {"600", "799"}, {"8000000", "8999999"}, {"9000", "9999"},}, 4), /** * Group: 978-9923 - Jordan. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 49 * 5000000 - 6999999 * 700 - 899 * 9000000 - 9699999 * 9700 - 9999</pre> * <p> * Maximum length: 4 */ _9789923(9789923, new String[][]{ {"0", "0"}, {"10", "49"}, {"5000000", "6999999"}, {"700", "899"}, {"9000000", "9699999"}, {"9700", "9999"},}, 4), /** * Group: 978-9924 - Cambodia. * <p> * Valid publisher ranges: * <pre> * 0000000 - 2999999 * 30 - 39 * 4000000 - 4999999 * 500 - 649 * 6500000 - 8999999 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789924(9789924, new String[][]{ {"0000000", "2999999"}, {"30", "39"}, {"4000000", "4999999"}, {"500", "649"}, {"6500000", "8999999"}, {"9000", "9999"},}, 4), /** * Group: 978-9925 - Cyprus. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 54 * 550 - 734 * 7350 - 9999</pre> * <p> * Maximum length: 4 */ _9789925(9789925, new String[][]{ {"0", "2"}, {"30", "54"}, {"550", "734"}, {"7350", "9999"},}, 4), /** * Group: 978-9926 - Bosnia and Herzegovina. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 39 * 400 - 799 * 8000 - 9999</pre> * <p> * Maximum length: 4 */ _9789926(9789926, new String[][]{ {"0", "1"}, {"20", "39"}, {"400", "799"}, {"8000", "9999"},}, 4), /** * Group: 978-9927 - Qatar. * <p> * Valid publisher ranges: * <pre> * 00 - 09 * 100 - 399 * 4000 - 4999 * 5000000 - 9999999</pre> * <p> * Maximum length: 4 */ _9789927(9789927, new String[][]{ {"00", "09"}, {"100", "399"}, {"4000", "4999"}, {"5000000", "9999999"},}, 4), /** * Group: 978-9928 - Albania. * <p> * Valid publisher ranges: * <pre> * 00 - 09 * 100 - 399 * 4000 - 4999 * 5000000 - 9999999</pre> * <p> * Maximum length: 4 */ _9789928(9789928, new String[][]{ {"00", "09"}, {"100", "399"}, {"4000", "4999"}, {"5000000", "9999999"},}, 4), /** * Group: 978-9929 - Guatemala. * <p> * Valid publisher ranges: * <pre> * 0 - 3 * 40 - 54 * 550 - 799 * 8000 - 9999</pre> * <p> * Maximum length: 4 */ _9789929(9789929, new String[][]{ {"0", "3"}, {"40", "54"}, {"550", "799"}, {"8000", "9999"},}, 4), /** * Group: 978-9930 - Costa Rica. * <p> * Valid publisher ranges: * <pre> * 00 - 49 * 500 - 939 * 9400 - 9999</pre> * <p> * Maximum length: 4 */ _9789930(9789930, new String[][]{ {"00", "49"}, {"500", "939"}, {"9400", "9999"},}, 4), /** * Group: 978-9931 - Algeria. * <p> * Valid publisher ranges: * <pre> * 00 - 29 * 300 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789931(9789931, new String[][]{ {"00", "29"}, {"300", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9932 - Lao People's Democratic Republic. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 849 * 8500 - 9999</pre> * <p> * Maximum length: 4 */ _9789932(9789932, new String[][]{ {"00", "39"}, {"400", "849"}, {"8500", "9999"},}, 4), /** * Group: 978-9933 - Syria. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 39 * 400 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789933(9789933, new String[][]{ {"0", "0"}, {"10", "39"}, {"400", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9934 - Latvia. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 49 * 500 - 799 * 8000 - 9999</pre> * <p> * Maximum length: 4 */ _9789934(9789934, new String[][]{ {"0", "0"}, {"10", "49"}, {"500", "799"}, {"8000", "9999"},}, 4), /** * Group: 978-9935 - Iceland. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 39 * 400 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789935(9789935, new String[][]{ {"0", "0"}, {"10", "39"}, {"400", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9936 - Afghanistan. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 39 * 400 - 799 * 8000 - 9999</pre> * <p> * Maximum length: 4 */ _9789936(9789936, new String[][]{ {"0", "1"}, {"20", "39"}, {"400", "799"}, {"8000", "9999"},}, 4), /** * Group: 978-9937 - Nepal. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 49 * 500 - 799 * 8000 - 9999</pre> * <p> * Maximum length: 4 */ _9789937(9789937, new String[][]{ {"0", "2"}, {"30", "49"}, {"500", "799"}, {"8000", "9999"},}, 4), /** * Group: 978-9938 - Tunisia. * <p> * Valid publisher ranges: * <pre> * 00 - 79 * 800 - 949 * 9500 - 9999</pre> * <p> * Maximum length: 4 */ _9789938(9789938, new String[][]{ {"00", "79"}, {"800", "949"}, {"9500", "9999"},}, 4), /** * Group: 978-9939 - Armenia. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789939(9789939, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9940 - Montenegro. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 49 * 500 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789940(9789940, new String[][]{ {"0", "1"}, {"20", "49"}, {"500", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9941 - Georgia. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 39 * 400 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789941(9789941, new String[][]{ {"0", "0"}, {"10", "39"}, {"400", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9942 - Ecuador. * <p> * Valid publisher ranges: * <pre> * 00 - 74 * 750 - 849 * 8500 - 8999 * 900 - 984 * 9850 - 9999</pre> * <p> * Maximum length: 4 */ _9789942(9789942, new String[][]{ {"00", "74"}, {"750", "849"}, {"8500", "8999"}, {"900", "984"}, {"9850", "9999"},}, 4), /** * Group: 978-9943 - Uzbekistan. * <p> * Valid publisher ranges: * <pre> * 00 - 29 * 300 - 399 * 4000 - 9749 * 975 - 999</pre> * <p> * Maximum length: 4 */ _9789943(9789943, new String[][]{ {"00", "29"}, {"300", "399"}, {"4000", "9749"}, {"975", "999"},}, 4), /** * Group: 978-9944 - Turkey. * <p> * Valid publisher ranges: * <pre> * 0000 - 0999 * 100 - 499 * 5000 - 5999 * 60 - 69 * 700 - 799 * 80 - 89 * 900 - 999</pre> * <p> * Maximum length: 4 */ _9789944(9789944, new String[][]{ {"0000", "0999"}, {"100", "499"}, {"5000", "5999"}, {"60", "69"}, {"700", "799"}, {"80", "89"}, {"900", "999"},}, 4), /** * Group: 978-9945 - Dominican Republic. * <p> * Valid publisher ranges: * <pre> * 00 - 00 * 010 - 079 * 08 - 39 * 400 - 569 * 57 - 57 * 580 - 849 * 8500 - 9999</pre> * <p> * Maximum length: 4 */ _9789945(9789945, new String[][]{ {"00", "00"}, {"010", "079"}, {"08", "39"}, {"400", "569"}, {"57", "57"}, {"580", "849"}, {"8500", "9999"},}, 4), /** * Group: 978-9946 - Korea, P.D.R.. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 39 * 400 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789946(9789946, new String[][]{ {"0", "1"}, {"20", "39"}, {"400", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9947 - Algeria. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _9789947(9789947, new String[][]{ {"0", "1"}, {"20", "79"}, {"800", "999"},}, 3), /** * Group: 978-9948 - United Arab Emirates. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 849 * 8500 - 9999</pre> * <p> * Maximum length: 4 */ _9789948(9789948, new String[][]{ {"00", "39"}, {"400", "849"}, {"8500", "9999"},}, 4), /** * Group: 978-9949 - Estonia. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 39 * 400 - 699 * 70 - 71 * 7200 - 7499 * 75 - 89 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789949(9789949, new String[][]{ {"0", "0"}, {"10", "39"}, {"400", "699"}, {"70", "71"}, {"7200", "7499"}, {"75", "89"}, {"9000", "9999"},}, 4), /** * Group: 978-9950 - Palestine. * <p> * Valid publisher ranges: * <pre> * 00 - 29 * 300 - 849 * 8500 - 9999</pre> * <p> * Maximum length: 4 */ _9789950(9789950, new String[][]{ {"00", "29"}, {"300", "849"}, {"8500", "9999"},}, 4), /** * Group: 978-9951 - Kosova. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 849 * 8500 - 9999</pre> * <p> * Maximum length: 4 */ _9789951(9789951, new String[][]{ {"00", "39"}, {"400", "849"}, {"8500", "9999"},}, 4), /** * Group: 978-9952 - Azerbaijan. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 39 * 400 - 799 * 8000 - 9999</pre> * <p> * Maximum length: 4 */ _9789952(9789952, new String[][]{ {"0", "1"}, {"20", "39"}, {"400", "799"}, {"8000", "9999"},}, 4), /** * Group: 978-9953 - Lebanon. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 39 * 400 - 599 * 60 - 89 * 9000 - 9299 * 93 - 96 * 970 - 999</pre> * <p> * Maximum length: 4 */ _9789953(9789953, new String[][]{ {"0", "0"}, {"10", "39"}, {"400", "599"}, {"60", "89"}, {"9000", "9299"}, {"93", "96"}, {"970", "999"},}, 4), /** * Group: 978-9954 - Morocco. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 39 * 400 - 799 * 8000 - 9899 * 99 - 99</pre> * <p> * Maximum length: 4 */ _9789954(9789954, new String[][]{ {"0", "1"}, {"20", "39"}, {"400", "799"}, {"8000", "9899"}, {"99", "99"},}, 4), /** * Group: 978-9955 - Lithuania. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 929 * 9300 - 9999</pre> * <p> * Maximum length: 4 */ _9789955(9789955, new String[][]{ {"00", "39"}, {"400", "929"}, {"9300", "9999"},}, 4), /** * Group: 978-9956 - Cameroon. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 39 * 400 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789956(9789956, new String[][]{ {"0", "0"}, {"10", "39"}, {"400", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9957 - Jordan. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 649 * 65 - 67 * 680 - 699 * 70 - 84 * 8500 - 8799 * 88 - 99</pre> * <p> * Maximum length: 4 */ _9789957(9789957, new String[][]{ {"00", "39"}, {"400", "649"}, {"65", "67"}, {"680", "699"}, {"70", "84"}, {"8500", "8799"}, {"88", "99"},}, 4), /** * Group: 978-9958 - Bosnia and Herzegovina. * <p> * Valid publisher ranges: * <pre> * 00 - 01 * 020 - 029 * 0300 - 0399 * 040 - 089 * 0900 - 0999 * 10 - 18 * 1900 - 1999 * 20 - 49 * 500 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789958(9789958, new String[][]{ {"00", "01"}, {"020", "029"}, {"0300", "0399"}, {"040", "089"}, {"0900", "0999"}, {"10", "18"}, {"1900", "1999"}, {"20", "49"}, {"500", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9959 - Libya. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 79 * 800 - 949 * 9500 - 9699 * 970 - 979 * 98 - 99</pre> * <p> * Maximum length: 4 */ _9789959(9789959, new String[][]{ {"0", "1"}, {"20", "79"}, {"800", "949"}, {"9500", "9699"}, {"970", "979"}, {"98", "99"},}, 4), /** * Group: 978-9960 - Saudi Arabia. * <p> * Valid publisher ranges: * <pre> * 00 - 59 * 600 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789960(9789960, new String[][]{ {"00", "59"}, {"600", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9961 - Algeria. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 69 * 700 - 949 * 9500 - 9999</pre> * <p> * Maximum length: 4 */ _9789961(9789961, new String[][]{ {"0", "2"}, {"30", "69"}, {"700", "949"}, {"9500", "9999"},}, 4), /** * Group: 978-9962 - Panama. * <p> * Valid publisher ranges: * <pre> * 00 - 54 * 5500 - 5599 * 56 - 59 * 600 - 849 * 8500 - 9999</pre> * <p> * Maximum length: 4 */ _9789962(9789962, new String[][]{ {"00", "54"}, {"5500", "5599"}, {"56", "59"}, {"600", "849"}, {"8500", "9999"},}, 4), /** * Group: 978-9963 - Cyprus. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 2000 - 2499 * 250 - 279 * 2800 - 2999 * 30 - 54 * 550 - 734 * 7350 - 7499 * 7500 - 9999</pre> * <p> * Maximum length: 4 */ _9789963(9789963, new String[][]{ {"0", "1"}, {"2000", "2499"}, {"250", "279"}, {"2800", "2999"}, {"30", "54"}, {"550", "734"}, {"7350", "7499"}, {"7500", "9999"},}, 4), /** * Group: 978-9964 - Ghana. * <p> * Valid publisher ranges: * <pre> * 0 - 6 * 70 - 94 * 950 - 999</pre> * <p> * Maximum length: 3 */ _9789964(9789964, new String[][]{ {"0", "6"}, {"70", "94"}, {"950", "999"},}, 3), /** * Group: 978-9965 - Kazakhstan. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789965(9789965, new String[][]{ {"00", "39"}, {"400", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9966 - Kenya. * <p> * Valid publisher ranges: * <pre> * 000 - 149 * 1500 - 1999 * 20 - 69 * 7000 - 7499 * 750 - 959 * 9600 - 9999</pre> * <p> * Maximum length: 4 */ _9789966(9789966, new String[][]{ {"000", "149"}, {"1500", "1999"}, {"20", "69"}, {"7000", "7499"}, {"750", "959"}, {"9600", "9999"},}, 4), /** * Group: 978-9967 - Kyrgyz Republic. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789967(9789967, new String[][]{ {"00", "39"}, {"400", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9968 - Costa Rica. * <p> * Valid publisher ranges: * <pre> * 00 - 49 * 500 - 939 * 9400 - 9999</pre> * <p> * Maximum length: 4 */ _9789968(9789968, new String[][]{ {"00", "49"}, {"500", "939"}, {"9400", "9999"},}, 4), /** * Group: 978-9970 - Uganda. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789970(9789970, new String[][]{ {"00", "39"}, {"400", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9971 - Singapore. * <p> * Valid publisher ranges: * <pre> * 0 - 5 * 60 - 89 * 900 - 989 * 9900 - 9999</pre> * <p> * Maximum length: 4 */ _9789971(9789971, new String[][]{ {"0", "5"}, {"60", "89"}, {"900", "989"}, {"9900", "9999"},}, 4), /** * Group: 978-9972 - Peru. * <p> * Valid publisher ranges: * <pre> * 00 - 09 * 1 - 1 * 200 - 249 * 2500 - 2999 * 30 - 59 * 600 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789972(9789972, new String[][]{ {"00", "09"}, {"1", "1"}, {"200", "249"}, {"2500", "2999"}, {"30", "59"}, {"600", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9973 - Tunisia. * <p> * Valid publisher ranges: * <pre> * 00 - 05 * 060 - 089 * 0900 - 0999 * 10 - 69 * 700 - 969 * 9700 - 9999</pre> * <p> * Maximum length: 4 */ _9789973(9789973, new String[][]{ {"00", "05"}, {"060", "089"}, {"0900", "0999"}, {"10", "69"}, {"700", "969"}, {"9700", "9999"},}, 4), /** * Group: 978-9974 - Uruguay. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 54 * 550 - 749 * 7500 - 8799 * 880 - 909 * 91 - 94 * 95 - 99</pre> * <p> * Maximum length: 4 */ _9789974(9789974, new String[][]{ {"0", "2"}, {"30", "54"}, {"550", "749"}, {"7500", "8799"}, {"880", "909"}, {"91", "94"}, {"95", "99"},}, 4), /** * Group: 978-9975 - Moldova. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 100 - 299 * 3000 - 3999 * 4000 - 4499 * 45 - 89 * 900 - 949 * 9500 - 9999</pre> * <p> * Maximum length: 4 */ _9789975(9789975, new String[][]{ {"0", "0"}, {"100", "299"}, {"3000", "3999"}, {"4000", "4499"}, {"45", "89"}, {"900", "949"}, {"9500", "9999"},}, 4), /** * Group: 978-9976 - Tanzania. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 5000 - 5999 * 60 - 89 * 900 - 989 * 9900 - 9999</pre> * <p> * Maximum length: 4 */ _9789976(9789976, new String[][]{ {"0", "4"}, {"5000", "5999"}, {"60", "89"}, {"900", "989"}, {"9900", "9999"},}, 4), /** * Group: 978-9977 - Costa Rica. * <p> * Valid publisher ranges: * <pre> * 00 - 89 * 900 - 989 * 9900 - 9999</pre> * <p> * Maximum length: 4 */ _9789977(9789977, new String[][]{ {"00", "89"}, {"900", "989"}, {"9900", "9999"},}, 4), /** * Group: 978-9978 - Ecuador. * <p> * Valid publisher ranges: * <pre> * 00 - 29 * 300 - 399 * 40 - 94 * 950 - 989 * 9900 - 9999</pre> * <p> * Maximum length: 4 */ _9789978(9789978, new String[][]{ {"00", "29"}, {"300", "399"}, {"40", "94"}, {"950", "989"}, {"9900", "9999"},}, 4), /** * Group: 978-9979 - Iceland. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 64 * 650 - 659 * 66 - 75 * 760 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789979(9789979, new String[][]{ {"0", "4"}, {"50", "64"}, {"650", "659"}, {"66", "75"}, {"760", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9980 - Papua New Guinea. * <p> * Valid publisher ranges: * <pre> * 0 - 3 * 40 - 89 * 900 - 989 * 9900 - 9999</pre> * <p> * Maximum length: 4 */ _9789980(9789980, new String[][]{ {"0", "3"}, {"40", "89"}, {"900", "989"}, {"9900", "9999"},}, 4), /** * Group: 978-9981 - Morocco. * <p> * Valid publisher ranges: * <pre> * 00 - 09 * 100 - 159 * 1600 - 1999 * 20 - 79 * 800 - 949 * 9500 - 9999</pre> * <p> * Maximum length: 4 */ _9789981(9789981, new String[][]{ {"00", "09"}, {"100", "159"}, {"1600", "1999"}, {"20", "79"}, {"800", "949"}, {"9500", "9999"},}, 4), /** * Group: 978-9982 - Zambia. * <p> * Valid publisher ranges: * <pre> * 00 - 79 * 800 - 989 * 9900 - 9999</pre> * <p> * Maximum length: 4 */ _9789982(9789982, new String[][]{ {"00", "79"}, {"800", "989"}, {"9900", "9999"},}, 4), /** * Group: 978-9983 - Gambia. * <p> * Valid publisher ranges: * <pre> * 0000000 - 7999999 * 80 - 94 * 950 - 989 * 9900 - 9999</pre> * <p> * Maximum length: 4 */ _9789983(9789983, new String[][]{ {"0000000", "7999999"}, {"80", "94"}, {"950", "989"}, {"9900", "9999"},}, 4), /** * Group: 978-9984 - Latvia. * <p> * Valid publisher ranges: * <pre> * 00 - 49 * 500 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789984(9789984, new String[][]{ {"00", "49"}, {"500", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9985 - Estonia. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 899 * 9000 - 9999</pre> * <p> * Maximum length: 4 */ _9789985(9789985, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "899"}, {"9000", "9999"},}, 4), /** * Group: 978-9986 - Lithuania. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 899 * 9000 - 9399 * 940 - 969 * 97 - 99</pre> * <p> * Maximum length: 4 */ _9789986(9789986, new String[][]{ {"00", "39"}, {"400", "899"}, {"9000", "9399"}, {"940", "969"}, {"97", "99"},}, 4), /** * Group: 978-9987 - Tanzania. * <p> * Valid publisher ranges: * <pre> * 00 - 39 * 400 - 879 * 8800 - 9999</pre> * <p> * Maximum length: 4 */ _9789987(9789987, new String[][]{ {"00", "39"}, {"400", "879"}, {"8800", "9999"},}, 4), /** * Group: 978-9988 - Ghana. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 54 * 550 - 749 * 7500 - 9999</pre> * <p> * Maximum length: 4 */ _9789988(9789988, new String[][]{ {"0", "2"}, {"30", "54"}, {"550", "749"}, {"7500", "9999"},}, 4), /** * Group: 978-9989 - Macedonia. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 100 - 199 * 2000 - 2999 * 30 - 59 * 600 - 949 * 9500 - 9999</pre> * <p> * Maximum length: 4 */ _9789989(9789989, new String[][]{ {"0", "0"}, {"100", "199"}, {"2000", "2999"}, {"30", "59"}, {"600", "949"}, {"9500", "9999"},}, 4), /** * Group: 978-99901 - Bahrain. * <p> * Valid publisher ranges: * <pre> * 00 - 49 * 500 - 799 * 80 - 99</pre> * <p> * Maximum length: 3 */ _97899901(97899901, new String[][]{ {"00", "49"}, {"500", "799"}, {"80", "99"},}, 3), /** * Group: 978-99902 - Reserved Agency. * <p> * Valid publisher ranges: * <pre> * 0000000 - 9999999</pre> * <p> * Maximum length: 0 */ _97899902(97899902, new String[][]{ {"0000000", "9999999"},}, 0), /** * Group: 978-99903 - Mauritius. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899903(97899903, new String[][]{ {"0", "1"}, {"20", "89"}, {"900", "999"},}, 3), _97899904(97899904, new String[][]{ {"0", "5"}, {"60", "89"}, {"900", "999"},}, 3), /** * Group: 978-99905 - Bolivia. * <p> * Valid publisher ranges: * <pre> * 0 - 3 * 40 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899905(97899905, new String[][]{ {"0", "3"}, {"40", "79"}, {"800", "999"},}, 3), /** * Group: 978-99906 - Kuwait. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 59 * 600 - 699 * 70 - 89 * 90 - 94 * 950 - 999</pre> * <p> * Maximum length: 3 */ _97899906(97899906, new String[][]{ {"0", "2"}, {"30", "59"}, {"600", "699"}, {"70", "89"}, {"90", "94"}, {"950", "999"},}, 3), /** * Group: 978-99908 - Malawi. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899908(97899908, new String[][]{ {"0", "0"}, {"10", "89"}, {"900", "999"},}, 3), /** * Group: 978-99909 - Malta. * <p> * Valid publisher ranges: * <pre> * 0 - 3 * 40 - 94 * 950 - 999</pre> * <p> * Maximum length: 3 */ _97899909(97899909, new String[][]{ {"0", "3"}, {"40", "94"}, {"950", "999"},}, 3), /** * Group: 978-99910 - Sierra Leone. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899910(97899910, new String[][]{ {"0", "2"}, {"30", "89"}, {"900", "999"},}, 3), /** * Group: 978-99911 - Lesotho. * <p> * Valid publisher ranges: * <pre> * 00 - 59 * 600 - 999</pre> * <p> * Maximum length: 3 */ _97899911(97899911, new String[][]{ {"00", "59"}, {"600", "999"},}, 3), /** * Group: 978-99912 - Botswana. * <p> * Valid publisher ranges: * <pre> * 0 - 3 * 400 - 599 * 60 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899912(97899912, new String[][]{ {"0", "3"}, {"400", "599"}, {"60", "89"}, {"900", "999"},}, 3), /** * Group: 978-99913 - Andorra. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 35 * 3600000 - 5999999 * 600 - 604 * 6050000 - 9999999</pre> * <p> * Maximum length: 3 */ _97899913(97899913, new String[][]{ {"0", "2"}, {"30", "35"}, {"3600000", "5999999"}, {"600", "604"}, {"6050000", "9999999"},}, 3), /** * Group: 978-99914 - International NGO Publishers. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 69 * 7 - 7 * 80 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899914(97899914, new String[][]{ {"0", "4"}, {"50", "69"}, {"7", "7"}, {"80", "89"}, {"900", "999"},}, 3), /** * Group: 978-99915 - Maldives. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899915(97899915, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "999"},}, 3), /** * Group: 978-99916 - Namibia. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 69 * 700 - 999</pre> * <p> * Maximum length: 3 */ _97899916(97899916, new String[][]{ {"0", "2"}, {"30", "69"}, {"700", "999"},}, 3), /** * Group: 978-99917 - Brunei Darussalam. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899917(97899917, new String[][]{ {"0", "2"}, {"30", "89"}, {"900", "999"},}, 3), /** * Group: 978-99918 - Faroe Islands. * <p> * Valid publisher ranges: * <pre> * 0 - 3 * 40 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899918(97899918, new String[][]{ {"0", "3"}, {"40", "79"}, {"800", "999"},}, 3), /** * Group: 978-99919 - Benin. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 300 - 399 * 40 - 69 * 70 - 79 * 800 - 849 * 850 - 899 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899919(97899919, new String[][]{ {"0", "2"}, {"300", "399"}, {"40", "69"}, {"70", "79"}, {"800", "849"}, {"850", "899"}, {"900", "999"},}, 3), /** * Group: 978-99920 - Andorra. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899920(97899920, new String[][]{ {"0", "4"}, {"50", "89"}, {"900", "999"},}, 3), /** * Group: 978-99921 - Qatar. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 69 * 700 - 799 * 8 - 8 * 90 - 99</pre> * <p> * Maximum length: 3 */ _97899921(97899921, new String[][]{ {"0", "1"}, {"20", "69"}, {"700", "799"}, {"8", "8"}, {"90", "99"},}, 3), /** * Group: 978-99922 - Guatemala. * <p> * Valid publisher ranges: * <pre> * 0 - 3 * 40 - 69 * 700 - 999</pre> * <p> * Maximum length: 3 */ _97899922(97899922, new String[][]{ {"0", "3"}, {"40", "69"}, {"700", "999"},}, 3), /** * Group: 978-99923 - El Salvador. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899923(97899923, new String[][]{ {"0", "1"}, {"20", "79"}, {"800", "999"},}, 3), /** * Group: 978-99924 - Nicaragua. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899924(97899924, new String[][]{ {"0", "1"}, {"20", "79"}, {"800", "999"},}, 3), /** * Group: 978-99925 - Paraguay. * <p> * Valid publisher ranges: * <pre> * 0 - 3 * 40 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899925(97899925, new String[][]{ {"0", "3"}, {"40", "79"}, {"800", "999"},}, 3), /** * Group: 978-99926 - Honduras. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 59 * 600 - 869 * 87 - 89 * 90 - 99</pre> * <p> * Maximum length: 3 */ _97899926(97899926, new String[][]{ {"0", "0"}, {"10", "59"}, {"600", "869"}, {"87", "89"}, {"90", "99"},}, 3), /** * Group: 978-99927 - Albania. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 59 * 600 - 999</pre> * <p> * Maximum length: 3 */ _97899927(97899927, new String[][]{ {"0", "2"}, {"30", "59"}, {"600", "999"},}, 3), /** * Group: 978-99928 - Georgia. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899928(97899928, new String[][]{ {"0", "0"}, {"10", "79"}, {"800", "999"},}, 3), /** * Group: 978-99929 - Mongolia. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899929(97899929, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "999"},}, 3), /** * Group: 978-99930 - Armenia. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899930(97899930, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "999"},}, 3), /** * Group: 978-99931 - Seychelles. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899931(97899931, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "999"},}, 3), /** * Group: 978-99932 - Malta. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 59 * 600 - 699 * 7 - 7 * 80 - 99</pre> * <p> * Maximum length: 3 */ _97899932(97899932, new String[][]{ {"0", "0"}, {"10", "59"}, {"600", "699"}, {"7", "7"}, {"80", "99"},}, 3), /** * Group: 978-99933 - Nepal. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 59 * 600 - 999</pre> * <p> * Maximum length: 3 */ _97899933(97899933, new String[][]{ {"0", "2"}, {"30", "59"}, {"600", "999"},}, 3), /** * Group: 978-99934 - Dominican Republic. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899934(97899934, new String[][]{ {"0", "1"}, {"20", "79"}, {"800", "999"},}, 3), /** * Group: 978-99935 - Haiti. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 59 * 600 - 699 * 7 - 8 * 90 - 99</pre> * <p> * Maximum length: 3 */ _97899935(97899935, new String[][]{ {"0", "2"}, {"30", "59"}, {"600", "699"}, {"7", "8"}, {"90", "99"},}, 3), /** * Group: 978-99936 - Bhutan. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 59 * 600 - 999</pre> * <p> * Maximum length: 3 */ _97899936(97899936, new String[][]{ {"0", "0"}, {"10", "59"}, {"600", "999"},}, 3), /** * Group: 978-99937 - Macau. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 59 * 600 - 999</pre> * <p> * Maximum length: 3 */ _97899937(97899937, new String[][]{ {"0", "1"}, {"20", "59"}, {"600", "999"},}, 3), /** * Group: 978-99938 - Srpska, Republic of. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 59 * 600 - 899 * 90 - 99</pre> * <p> * Maximum length: 3 */ _97899938(97899938, new String[][]{ {"0", "1"}, {"20", "59"}, {"600", "899"}, {"90", "99"},}, 3), /** * Group: 978-99939 - Guatemala. * <p> * Valid publisher ranges: * <pre> * 0 - 5 * 60 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899939(97899939, new String[][]{ {"0", "5"}, {"60", "89"}, {"900", "999"},}, 3), /** * Group: 978-99940 - Georgia. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 69 * 700 - 999</pre> * <p> * Maximum length: 3 */ _97899940(97899940, new String[][]{ {"0", "0"}, {"10", "69"}, {"700", "999"},}, 3), /** * Group: 978-99941 - Armenia. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899941(97899941, new String[][]{ {"0", "2"}, {"30", "79"}, {"800", "999"},}, 3), /** * Group: 978-99942 - Sudan. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899942(97899942, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "999"},}, 3), /** * Group: 978-99943 - Albania. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 59 * 600 - 999</pre> * <p> * Maximum length: 3 */ _97899943(97899943, new String[][]{ {"0", "2"}, {"30", "59"}, {"600", "999"},}, 3), /** * Group: 978-99944 - Ethiopia. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899944(97899944, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "999"},}, 3), /** * Group: 978-99945 - Namibia. * <p> * Valid publisher ranges: * <pre> * 0 - 5 * 60 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899945(97899945, new String[][]{ {"0", "5"}, {"60", "89"}, {"900", "999"},}, 3), /** * Group: 978-99946 - Nepal. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 59 * 600 - 999</pre> * <p> * Maximum length: 3 */ _97899946(97899946, new String[][]{ {"0", "2"}, {"30", "59"}, {"600", "999"},}, 3), /** * Group: 978-99947 - Tajikistan. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 69 * 700 - 999</pre> * <p> * Maximum length: 3 */ _97899947(97899947, new String[][]{ {"0", "2"}, {"30", "69"}, {"700", "999"},}, 3), /** * Group: 978-99948 - Eritrea. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899948(97899948, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "999"},}, 3), /** * Group: 978-99949 - Mauritius. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899949(97899949, new String[][]{ {"0", "1"}, {"20", "89"}, {"900", "999"},}, 3), /** * Group: 978-99950 - Cambodia. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899950(97899950, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "999"},}, 3), /** * Group: 978-99951 - Reserved Agency. * <p> * Valid publisher ranges: * <pre> * 0000000 - 9999999</pre> * <p> * Maximum length: 0 */ _97899951(97899951, new String[][]{ {"0000000", "9999999"},}, 0), /** * Group: 978-99952 - Mali. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899952(97899952, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "999"},}, 3), /** * Group: 978-99953 - Paraguay. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 79 * 800 - 939 * 94 - 99</pre> * <p> * Maximum length: 3 */ _97899953(97899953, new String[][]{ {"0", "2"}, {"30", "79"}, {"800", "939"}, {"94", "99"},}, 3), /** * Group: 978-99954 - Bolivia. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 69 * 700 - 879 * 88 - 99</pre> * <p> * Maximum length: 3 */ _97899954(97899954, new String[][]{ {"0", "2"}, {"30", "69"}, {"700", "879"}, {"88", "99"},}, 3), /** * Group: 978-99955 - Srpska, Republic of. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 59 * 600 - 799 * 80 - 99</pre> * <p> * Maximum length: 3 */ _97899955(97899955, new String[][]{ {"0", "1"}, {"20", "59"}, {"600", "799"}, {"80", "99"},}, 3), /** * Group: 978-99956 - Albania. * <p> * Valid publisher ranges: * <pre> * 00 - 59 * 600 - 859 * 86 - 99</pre> * <p> * Maximum length: 3 */ _97899956(97899956, new String[][]{ {"00", "59"}, {"600", "859"}, {"86", "99"},}, 3), /** * Group: 978-99957 - Malta. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899957(97899957, new String[][]{ {"0", "1"}, {"20", "79"}, {"800", "999"},}, 3), /** * Group: 978-99958 - Bahrain. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 93 * 940 - 949 * 950 - 999</pre> * <p> * Maximum length: 3 */ _97899958(97899958, new String[][]{ {"0", "4"}, {"50", "93"}, {"940", "949"}, {"950", "999"},}, 3), /** * Group: 978-99959 - Luxembourg. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 59 * 600 - 999</pre> * <p> * Maximum length: 3 */ _97899959(97899959, new String[][]{ {"0", "2"}, {"30", "59"}, {"600", "999"},}, 3), /** * Group: 978-99960 - Malawi. * <p> * Valid publisher ranges: * <pre> * 0 - 0 * 10 - 94 * 950 - 999</pre> * <p> * Maximum length: 3 */ _97899960(97899960, new String[][]{ {"0", "0"}, {"10", "94"}, {"950", "999"},}, 3), /** * Group: 978-99961 - El Salvador. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 300 - 399 * 40 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899961(97899961, new String[][]{ {"0", "2"}, {"300", "399"}, {"40", "89"}, {"900", "999"},}, 3), /** * Group: 978-99962 - Mongolia. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899962(97899962, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "999"},}, 3), /** * Group: 978-99963 - Cambodia. * <p> * Valid publisher ranges: * <pre> * 00 - 49 * 500 - 919 * 92 - 99</pre> * <p> * Maximum length: 3 */ _97899963(97899963, new String[][]{ {"00", "49"}, {"500", "919"}, {"92", "99"},}, 3), /** * Group: 978-99964 - Nicaragua. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899964(97899964, new String[][]{ {"0", "1"}, {"20", "79"}, {"800", "999"},}, 3), /** * Group: 978-99965 - Macau. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 300 - 379 * 38 - 62 * 630 - 999</pre> * <p> * Maximum length: 3 */ _97899965(97899965, new String[][]{ {"0", "2"}, {"300", "379"}, {"38", "62"}, {"630", "999"},}, 3), /** * Group: 978-99966 - Kuwait. * <p> * Valid publisher ranges: * <pre> * 0 - 2 * 30 - 69 * 700 - 799 * 80 - 96 * 970 - 999</pre> * <p> * Maximum length: 3 */ _97899966(97899966, new String[][]{ {"0", "2"}, {"30", "69"}, {"700", "799"}, {"80", "96"}, {"970", "999"},}, 3), /** * Group: 978-99967 - Paraguay. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 59 * 600 - 899 * 9000000 - 9999999</pre> * <p> * Maximum length: 3 */ _97899967(97899967, new String[][]{ {"0", "1"}, {"20", "59"}, {"600", "899"}, {"9000000", "9999999"},}, 3), /** * Group: 978-99968 - Botswana. * <p> * Valid publisher ranges: * <pre> * 0 - 3 * 400 - 599 * 60 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899968(97899968, new String[][]{ {"0", "3"}, {"400", "599"}, {"60", "89"}, {"900", "999"},}, 3), /** * Group: 978-99969 - Oman. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899969(97899969, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "999"},}, 3), /** * Group: 978-99970 - Haiti. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899970(97899970, new String[][]{ {"0", "4"}, {"50", "89"}, {"900", "999"},}, 3), /** * Group: 978-99971 - Myanmar. * <p> * Valid publisher ranges: * <pre> * 0 - 5 * 60 - 84 * 850 - 999</pre> * <p> * Maximum length: 3 */ _97899971(97899971, new String[][]{ {"0", "5"}, {"60", "84"}, {"850", "999"},}, 3), /** * Group: 978-99972 - Faroe Islands. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 89 * 900 - 999</pre> * <p> * Maximum length: 3 */ _97899972(97899972, new String[][]{ {"0", "4"}, {"50", "89"}, {"900", "999"},}, 3), /** * Group: 978-99973 - Mongolia. * <p> * Valid publisher ranges: * <pre> * 0 - 3 * 40 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899973(97899973, new String[][]{ {"0", "3"}, {"40", "79"}, {"800", "999"},}, 3), /** * Group: 978-99974 - Bolivia. * <p> * Valid publisher ranges: * <pre> * 0000000 - 3999999 * 40 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899974(97899974, new String[][]{ {"0000000", "3999999"}, {"40", "79"}, {"800", "999"},}, 3), /** * Group: 978-99975 - Tajikistan. * <p> * Valid publisher ranges: * <pre> * 0 - 3 * 40 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899975(97899975, new String[][]{ {"0", "3"}, {"40", "79"}, {"800", "999"},}, 3), /** * Group: 978-99976 - Srpska, Republic of. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 20 - 59 * 600 - 799 * 8000000 - 9999999</pre> * <p> * Maximum length: 3 */ _97899976(97899976, new String[][]{ {"0", "1"}, {"20", "59"}, {"600", "799"}, {"8000000", "9999999"},}, 3), /** * Group: 978-99977 - Rwanda. * <p> * Valid publisher ranges: * <pre> * 0 - 1 * 2000000 - 3999999 * 40 - 69 * 700 - 799 * 8000000 - 9999999</pre> * <p> * Maximum length: 3 */ _97899977(97899977, new String[][]{ {"0", "1"}, {"2000000", "3999999"}, {"40", "69"}, {"700", "799"}, {"8000000", "9999999"},}, 3), /** * Group: 978-99978 - Mongolia. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899978(97899978, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "999"},}, 3), /** * Group: 978-99979 - Honduras. * <p> * Valid publisher ranges: * <pre> * 0 - 4 * 50 - 79 * 800 - 999</pre> * <p> * Maximum length: 3 */ _97899979(97899979, new String[][]{ {"0", "4"}, {"50", "79"}, {"800", "999"},}, 3), /** * Group: 979-10 - France. * <p> * Valid publisher ranges: * <pre> * 00 - 19 * 200 - 699 * 7000 - 8999 * 90000 - 97599 * 976000 - 999999</pre> * <p> * Maximum length: 6 */ _97910(97910, new String[][]{ {"00", "19"}, {"200", "699"}, {"7000", "8999"}, {"90000", "97599"}, {"976000", "999999"},}, 6), /** * Group: 979-11 - Korea, Republic. * <p> * Valid publisher ranges: * <pre> * 00 - 24 * 250 - 549 * 5500 - 8499 * 85000 - 94999 * 950000 - 999999</pre> * <p> * Maximum length: 6 */ _97911(97911, new String[][]{ {"00", "24"}, {"250", "549"}, {"5500", "8499"}, {"85000", "94999"}, {"950000", "999999"},}, 6), /** * Group: 979-12 - Italy. * <p> * Valid publisher ranges: * <pre> * 0000000 - 1999999 * 200 - 200 * 2010000 - 9999999</pre> * <p> * Maximum length: 3 */ _97912(97912, new String[][]{ {"0000000", "1999999"}, {"200", "200"}, {"2010000", "9999999"},}, 3),; /** * Number of the group. */ private final int number; /** * Ranges of valid publisher numbers for the group. */ private final String[][] validPublisherNumbers; /** * Maximum length of a valid publisher number of the group. */ private final int maximumPublisherNumberLength; /** * Initializes the group attributes. * * @param number number of the group * @param validPublisherNumbers valid publisher numbers for the group * @param maximumPublisherNumberLength maximum publisher number length */ private Group(int number, String[][] validPublisherNumbers, int maximumPublisherNumberLength) { this.number = number; this.validPublisherNumbers = validPublisherNumbers; this.maximumPublisherNumberLength = maximumPublisherNumberLength; } /** * Returns the group of the specified ISBN. * * @param ISBN ISBN for the group wants to get. * @return the group of the specified ISBN or {@code null} if the ISBN is * not from any group. */ public static Group getGroup(String ISBN) { Group result = null; int length = ISBN.length(); int i = 1; while (result == null && i < length) { try { result = Group.valueOf('_' + ISBN.substring(0, i)); } catch (IllegalArgumentException ex) { } i++; } return result; } /** * Returns the number of the group. * * @return the number of the group */ public int getNumber() { return number; } /** * Returns the valid publisher numbers for the group. * * @return the valid publisher numbers for the group */ public String[][] getValidPublisherNumbers() { return validPublisherNumbers; } /** * Returns the maximum publisher number length. * * @return the maximum publisher number length */ public int getMaximumPublisherNumberLength() { return maximumPublisherNumberLength; } }
package jsettlers.integration.ai; import static org.junit.Assert.fail; import java.util.Arrays; import org.junit.Test; import jsettlers.ai.highlevel.AiStatistics; import jsettlers.common.CommonConstants; import jsettlers.common.ai.EPlayerType; import jsettlers.common.buildings.EBuildingType; import jsettlers.common.logging.StatisticsStopWatch; import jsettlers.common.map.MapLoadException; import jsettlers.common.menu.IStartedGame; import jsettlers.common.player.ECivilisation; import jsettlers.input.PlayerState; import jsettlers.logic.constants.MatchConstants; import jsettlers.logic.map.loading.MapLoader; import jsettlers.logic.player.PlayerSetting; import jsettlers.main.JSettlersGame; import jsettlers.main.replay.ReplayUtils; import jsettlers.network.client.OfflineNetworkConnector; import jsettlers.testutils.TestUtils; import jsettlers.testutils.map.MapUtils; /** * @author codingberlin */ public class AiDifficultiesIT { public static final int MINUTES = 1000 * 60; public static final int JUMP_FORWARD = 2 * MINUTES; static { CommonConstants.ENABLE_CONSOLE_LOGGING = true; TestUtils.setupTempResourceManager(); } @Test public void easyShouldConquerVeryEasy() throws MapLoadException { holdBattleBetween(EPlayerType.AI_EASY, EPlayerType.AI_VERY_EASY, 100 * MINUTES); } @Test public void hardShouldConquerEasy() throws MapLoadException { holdBattleBetween(EPlayerType.AI_HARD, EPlayerType.AI_EASY, 100 * MINUTES); } @Test public void veryHardShouldConquerHard() throws MapLoadException { holdBattleBetween(EPlayerType.AI_VERY_HARD, EPlayerType.AI_HARD, 100 * MINUTES); } @Test public void veryHardShouldProduceCertainAmountOfSoldiersWithin85Minutes() throws MapLoadException { PlayerSetting[] playerSettings = getDefaultPlayerSettings(12); playerSettings[0] = new PlayerSetting(EPlayerType.AI_VERY_HARD, ECivilisation.ROMAN, (byte) 0); JSettlersGame.GameRunner startingGame = createStartingGame(playerSettings); IStartedGame startedGame = ReplayUtils.waitForGameStartup(startingGame); MatchConstants.clock().fastForwardTo(85 * MINUTES); ReplayUtils.awaitShutdown(startedGame); short expectedMinimalProducedSoldiers = 1000; short producedSoldiers = startingGame.getMainGrid().getPartitionsGrid().getPlayer(0).getEndgameStatistic().getAmountOfProducedSoldiers(); if (producedSoldiers < expectedMinimalProducedSoldiers) { fail("AI_VERY_HARD was not able to produce " + expectedMinimalProducedSoldiers + " within 90 minutes.\nOnly " + producedSoldiers + " " + "soldiers were produced. Some code changes make the AI weaker."); } ensureRuntimePerformance("to apply rules", startingGame.getAiExecutor().getApplyRulesStopWatch(), 50, 2500); ensureRuntimePerformance("tp update statistics", startingGame.getAiExecutor().getUpdateStatisticsStopWatch(), 50, 2500); } private void holdBattleBetween(EPlayerType expectedWinner, EPlayerType expectedLooser, int maximumTimeToWin) throws MapLoadException { PlayerSetting[] playerSettings = getDefaultPlayerSettings(12); playerSettings[2] = new PlayerSetting(expectedWinner, ECivilisation.ROMAN, (byte) 0); playerSettings[8] = new PlayerSetting(expectedLooser, ECivilisation.ROMAN, (byte) 1); JSettlersGame.GameRunner startingGame = createStartingGame(playerSettings); IStartedGame startedGame = ReplayUtils.waitForGameStartup(startingGame); AiStatistics aiStatistics = new AiStatistics(startingGame.getMainGrid()); int targetGameTime = 0; do { targetGameTime += JUMP_FORWARD; MatchConstants.clock().fastForwardTo(targetGameTime); aiStatistics.updateStatistics(); if (aiStatistics.getNumberOfBuildingTypeForPlayer(EBuildingType.TOWER, (byte) 2) == 0) { stopAndFail(expectedWinner + " was defeated by " + expectedLooser, startedGame); } if (MatchConstants.clock().getTime() > maximumTimeToWin) { MapLoader savegame = MapUtils.saveMainGrid( startingGame.getMainGrid(), new PlayerState[] { new PlayerState((byte) 2, null), new PlayerState((byte) 8, null) }); System.out.println("Saved game at: " + savegame.getListedMap().getFile()); stopAndFail(expectedWinner + " was not able to defeat " + expectedLooser + " within " + (maximumTimeToWin / 60000) + " minutes.\nIf the AI code was changed in a way which makes the " + expectedLooser + " stronger with the sideeffect that " + "the " + expectedWinner + " needs more time to win you could make the " + expectedWinner + " stronger, too, or increase " + "the maximumTimeToWin.", startedGame); } } while (aiStatistics.getNumberOfBuildingTypeForPlayer(EBuildingType.TOWER, (byte) 8) > 0); System.out.println("The battle between " + expectedWinner + " and " + expectedLooser + " took " + (MatchConstants.clock().getTime() / 60000) + " minutes."); ReplayUtils.awaitShutdown(startedGame); ensureRuntimePerformance("to apply rules", startingGame.getAiExecutor().getApplyRulesStopWatch(), 50, 3000); ensureRuntimePerformance("to update statistics", startingGame.getAiExecutor().getUpdateStatisticsStopWatch(), 50, 2500); } private void ensureRuntimePerformance(String description, StatisticsStopWatch stopWatch, long median, int max) { System.out.println(description + ": " + stopWatch); if (stopWatch.getMedian() > median) { fail(description + "'s median is higher than " + median + ". It was " + stopWatch.getMedian() + ".\nSomething in the code changed which " + "caused the AI to have a worse runtime performance."); } if (stopWatch.getMax() > max) { fail(description + "'s max is higher than " + max + ". It was " + stopWatch.getMax() + ".\nSomething in the code changed which " + "caused the AI to have a worse runtime performance."); } } private JSettlersGame.GameRunner createStartingGame(PlayerSetting[] playerSettings) throws MapLoadException { byte playerId = 0; for (byte i = 0; i < playerSettings.length; i++) { if (playerSettings[i].isAvailable()) { playerId = i; break; } } MapLoader mapCreator = MapUtils.getSpezialSumpf(); JSettlersGame game = new JSettlersGame(mapCreator, 2L, new OfflineNetworkConnector(), playerId, playerSettings); return (JSettlersGame.GameRunner) game.start(); } private void stopAndFail(String reason, IStartedGame startedGame) { ReplayUtils.awaitShutdown(startedGame); fail(reason); } private PlayerSetting[] getDefaultPlayerSettings(int numberOfPlayers) { PlayerSetting[] playerSettings = new PlayerSetting[numberOfPlayers]; Arrays.fill(playerSettings, 0, numberOfPlayers, new PlayerSetting()); return playerSettings; } }
package com.fsck.k9.mail.store.imap; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import com.fsck.k9.mail.Body; import com.fsck.k9.mail.FetchProfile; import com.fsck.k9.mail.FetchProfile.Item; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Folder.FolderType; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessageRetrievalListener; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Part; import com.fsck.k9.mail.internet.BinaryTempFileBody; import com.fsck.k9.mail.internet.MimeHeader; import com.fsck.k9.mail.store.StoreConfig; import org.apache.james.mime4j.util.MimeUtil; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import static com.fsck.k9.mail.Folder.OPEN_MODE_RO; import static com.fsck.k9.mail.Folder.OPEN_MODE_RW; import static com.fsck.k9.mail.store.imap.ImapResponseHelper.createImapResponse; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.mockito.internal.util.collections.Sets.newSet; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE, sdk = 21) public class ImapFolderTest { private ImapStore imapStore; private ImapConnection imapConnection; private StoreConfig storeConfig; @Before public void setUp() throws Exception { BinaryTempFileBody.setTempDirectory(RuntimeEnvironment.application.getCacheDir()); imapStore = mock(ImapStore.class); storeConfig = mock(StoreConfig.class); when(storeConfig.getInboxFolderName()).thenReturn("INBOX"); when(imapStore.getCombinedPrefix()).thenReturn(""); when(imapStore.getStoreConfig()).thenReturn(storeConfig); imapConnection = mock(ImapConnection.class); } @Test public void open_readWrite_shouldOpenFolder() throws Exception { ImapFolder imapFolder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); imapFolder.open(OPEN_MODE_RW); assertTrue(imapFolder.isOpen()); } @Test public void open_readOnly_shouldOpenFolder() throws Exception { ImapFolder imapFolder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); imapFolder.open(OPEN_MODE_RO); assertTrue(imapFolder.isOpen()); } @Test public void open_shouldFetchMessageCount() throws Exception { ImapFolder imapFolder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); imapFolder.open(OPEN_MODE_RW); assertEquals(23, imapFolder.getMessageCount()); } @Test public void open_readWrite_shouldMakeGetModeReturnReadWrite() throws Exception { ImapFolder imapFolder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); imapFolder.open(OPEN_MODE_RW); assertEquals(OPEN_MODE_RW, imapFolder.getMode()); } @Test public void open_readOnly_shouldMakeGetModeReturnReadOnly() throws Exception { ImapFolder imapFolder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); imapFolder.open(OPEN_MODE_RO); assertEquals(OPEN_MODE_RO, imapFolder.getMode()); } @Test public void open_shouldMakeExistReturnTrueWithoutExecutingAdditionalCommands() throws Exception { ImapFolder imapFolder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); imapFolder.open(OPEN_MODE_RW); assertTrue(imapFolder.exists()); verify(imapConnection, times(1)).executeSimpleCommand(anyString()); } @Test public void open_calledTwice_shouldReuseSameImapConnection() throws Exception { ImapFolder imapFolder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); imapFolder.open(OPEN_MODE_RW); imapFolder.open(OPEN_MODE_RW); verify(imapStore, times(1)).getConnection(); } @Test public void open_withConnectionThrowingOnReUse_shouldCreateNewImapConnection() throws Exception { ImapFolder imapFolder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); imapFolder.open(OPEN_MODE_RW); doThrow(IOException.class).when(imapConnection).executeSimpleCommand(Commands.NOOP); imapFolder.open(OPEN_MODE_RW); verify(imapStore, times(2)).getConnection(); } @Test public void open_withIoException_shouldThrowMessagingException() throws Exception { ImapFolder imapFolder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); doThrow(IOException.class).when(imapConnection).executeSimpleCommand("SELECT \"Folder\""); try { imapFolder.open(OPEN_MODE_RW); fail("Expected exception"); } catch (MessagingException e) { assertNotNull(e.getCause()); assertEquals(IOException.class, e.getCause().getClass()); } } @Test public void open_withMessagingException_shouldThrowMessagingException() throws Exception { ImapFolder imapFolder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); doThrow(MessagingException.class).when(imapConnection).executeSimpleCommand("SELECT \"Folder\""); try { imapFolder.open(OPEN_MODE_RW); fail("Expected exception"); } catch (MessagingException ignored) { } } @Test public void open_withoutExistsResponse_shouldThrowMessagingException() throws Exception { ImapFolder imapFolder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); List<ImapResponse> selectResponses = asList( createImapResponse("* OK [UIDNEXT 57576] Predicted next UID"), createImapResponse("2 OK [READ-WRITE] Select completed.") ); when(imapConnection.executeSimpleCommand("SELECT \"Folder\"")).thenReturn(selectResponses); try { imapFolder.open(OPEN_MODE_RW); fail("Expected exception"); } catch (MessagingException e) { assertEquals("Did not find message count during open", e.getMessage()); } } @Test public void close_shouldCloseImapFolder() throws Exception { ImapFolder imapFolder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); imapFolder.open(OPEN_MODE_RW); imapFolder.close(); assertFalse(imapFolder.isOpen()); } @Test public void exists_withClosedFolder_shouldOpenConnectionAndIssueStatusCommand() throws Exception { ImapFolder imapFolder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); imapFolder.exists(); verify(imapConnection).executeSimpleCommand("STATUS \"Folder\" (UIDVALIDITY)"); } @Test public void exists_withoutNegativeImapResponse_shouldReturnTrue() throws Exception { ImapFolder imapFolder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); boolean result = imapFolder.exists(); assertTrue(result); } @Test public void exists_withNegativeImapResponse_shouldReturnFalse() throws Exception { ImapFolder imapFolder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); doThrow(NegativeImapResponseException.class).when(imapConnection) .executeSimpleCommand("STATUS \"Folder\" (UIDVALIDITY)"); boolean result = imapFolder.exists(); assertFalse(result); } @Test public void create_withClosedFolder_shouldOpenConnectionAndIssueCreateCommand() throws Exception { ImapFolder imapFolder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); imapFolder.create(FolderType.HOLDS_MESSAGES); verify(imapConnection).executeSimpleCommand("CREATE \"Folder\""); } @Test public void create_withoutNegativeImapResponse_shouldReturnTrue() throws Exception { ImapFolder imapFolder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); boolean result = imapFolder.create(FolderType.HOLDS_MESSAGES); assertTrue(result); } @Test public void create_withNegativeImapResponse_shouldReturnFalse() throws Exception { ImapFolder imapFolder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); doThrow(NegativeImapResponseException.class).when(imapConnection).executeSimpleCommand("CREATE \"Folder\""); boolean result = imapFolder.create(FolderType.HOLDS_MESSAGES); assertFalse(result); } @Test public void copyMessages_withoutDestinationFolderOfWrongType_shouldThrow() throws Exception { ImapFolder sourceFolder = createFolder("Source"); Folder destinationFolder = mock(Folder.class); List<ImapMessage> messages = singletonList(mock(ImapMessage.class)); try { sourceFolder.copyMessages(messages, destinationFolder); fail("Expected exception"); } catch (MessagingException e) { assertEquals("ImapFolder.copyMessages passed non-ImapFolder", e.getMessage()); } } @Test public void copyMessages_withEmptyMessageList_shouldReturnNull() throws Exception { ImapFolder sourceFolder = createFolder("Source"); ImapFolder destinationFolder = createFolder("Destination"); List<ImapMessage> messages = Collections.emptyList(); Map<String, String> result = sourceFolder.copyMessages(messages, destinationFolder); assertNull(result); } @Test public void copyMessages_withClosedFolder_shouldThrow() throws Exception { ImapFolder sourceFolder = createFolder("Source"); ImapFolder destinationFolder = createFolder("Destination"); when(imapStore.getConnection()).thenReturn(imapConnection); when(imapStore.getCombinedPrefix()).thenReturn(""); List<ImapMessage> messages = singletonList(mock(ImapMessage.class)); try { sourceFolder.copyMessages(messages, destinationFolder); fail("Expected exception"); } catch (MessagingException e) { assertEquals("Folder Source is not open.", e.getMessage()); } } @Test public void copyMessages() throws Exception { ImapFolder sourceFolder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); ImapFolder destinationFolder = createFolder("Destination"); List<ImapMessage> messages = singletonList(createImapMessage("1")); List<ImapResponse> copyResponses = singletonList( createImapResponse("x OK [COPYUID 23 1 101] Success") ); when(imapConnection.executeSimpleCommand("UID COPY 1 \"Destination\"")).thenReturn(copyResponses); sourceFolder.open(OPEN_MODE_RW); Map<String, String> result = sourceFolder.copyMessages(messages, destinationFolder); assertNotNull(result); assertEquals("101", result.get("1")); } @Test public void moveMessages_shouldCopyMessages() throws Exception { ImapFolder sourceFolder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); ImapFolder destinationFolder = createFolder("Destination"); List<ImapMessage> messages = singletonList(createImapMessage("1")); List<ImapResponse> copyResponses = singletonList( createImapResponse("x OK [COPYUID 23 1 101] Success") ); when(imapConnection.executeSimpleCommand("UID COPY 1 \"Destination\"")).thenReturn(copyResponses); sourceFolder.open(OPEN_MODE_RW); Map<String, String> result = sourceFolder.moveMessages(messages, destinationFolder); assertNotNull(result); assertEquals("101", result.get("1")); } @Test public void moveMessages_shouldDeleteMessagesFromSourceFolder() throws Exception { ImapFolder sourceFolder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); ImapFolder destinationFolder = createFolder("Destination"); List<ImapMessage> messages = singletonList(createImapMessage("1")); List<ImapResponse> copyResponses = singletonList( createImapResponse("x OK [COPYUID 23 1 101] Success") ); when(imapConnection.executeSimpleCommand("UID COPY 1 \"Destination\"")).thenReturn(copyResponses); sourceFolder.open(OPEN_MODE_RW); sourceFolder.moveMessages(messages, destinationFolder); verify(imapConnection).executeSimpleCommand("UID STORE 1 +FLAGS.SILENT (\\Deleted)"); } @Test public void moveMessages_withEmptyMessageList_shouldReturnNull() throws Exception { ImapFolder sourceFolder = createFolder("Source"); ImapFolder destinationFolder = createFolder("Destination"); List<ImapMessage> messages = Collections.emptyList(); Map<String, String> result = sourceFolder.moveMessages(messages, destinationFolder); assertNull(result); } @Test public void delete_withEmptyMessageList_shouldNotInteractWithImapConnection() throws Exception { ImapFolder folder = createFolder("Source"); List<ImapMessage> messages = Collections.emptyList(); folder.delete(messages, "Trash"); verifyNoMoreInteractions(imapConnection); } @Test public void delete_fromTrashFolder_shouldIssueUidStoreFlagsCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapMessage> messages = singletonList(createImapMessage("23")); folder.open(OPEN_MODE_RW); folder.delete(messages, "Folder"); verify(imapConnection).executeSimpleCommand("UID STORE 23 +FLAGS.SILENT (\\Deleted)"); } @Test public void delete_shouldMoveMessagesToTrashFolder() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); ImapFolder trashFolder = createFolder("Trash"); when(imapStore.getFolder("Trash")).thenReturn(trashFolder); List<ImapMessage> messages = singletonList(createImapMessage("2")); List<ImapResponse> copyResponses = singletonList( createImapResponse("x OK [COPYUID 23 2 102] Success") ); when(imapConnection.executeSimpleCommand("UID COPY 2 \"Trash\"")).thenReturn(copyResponses); folder.open(OPEN_MODE_RW); folder.delete(messages, "Trash"); verify(imapConnection).executeSimpleCommand("UID STORE 2 +FLAGS.SILENT (\\Deleted)"); } @Test public void delete_withoutTrashFolderExisting_shouldCreateTrashFolder() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); ImapFolder trashFolder = createFolder("Trash"); when(imapStore.getFolder("Trash")).thenReturn(trashFolder); List<ImapMessage> messages = singletonList(createImapMessage("2")); List<ImapResponse> copyResponses = singletonList( createImapResponse("x OK [COPYUID 23 2 102] Success") ); when(imapConnection.executeSimpleCommand("UID COPY 2 \"Trash\"")).thenReturn(copyResponses); folder.open(OPEN_MODE_RW); doThrow(NegativeImapResponseException.class).doReturn(Collections.emptyList()) .when(imapConnection).executeSimpleCommand("STATUS \"Trash\" (RECENT)"); folder.delete(messages, "Trash"); verify(imapConnection).executeSimpleCommand("CREATE \"Trash\""); } @Test public void getUnreadMessageCount_withClosedFolder_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); try { folder.getUnreadMessageCount(); fail("Expected exception"); } catch (MessagingException e) { assertCheckOpenErrorMessage("Folder", e); } } @Test public void getUnreadMessageCount_connectionThrowsIOException_shouldThrowMessagingException() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); when(imapConnection.executeSimpleCommand("SEARCH 1:* UNSEEN NOT DELETED")).thenThrow(new IOException()); folder.open(OPEN_MODE_RW); try { folder.getUnreadMessageCount(); fail("Expected exception"); } catch (MessagingException e) { assertEquals("IO Error", e.getMessage()); } } @Test public void getUnreadMessageCount() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapResponse> imapResponses = singletonList(createImapResponse("* SEARCH 1 2 3")); when(imapConnection.executeSimpleCommand("SEARCH 1:* UNSEEN NOT DELETED")).thenReturn(imapResponses); folder.open(OPEN_MODE_RW); int result = folder.getUnreadMessageCount(); assertEquals(3, result); } @Test public void getFlaggedMessageCount_withClosedFolder_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); try { folder.getFlaggedMessageCount(); fail("Expected exception"); } catch (MessagingException e) { assertCheckOpenErrorMessage("Folder", e); } } @Test public void getFlaggedMessageCount() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapResponse> imapResponses = asList( createImapResponse("* SEARCH 1 2"), createImapResponse("* SEARCH 23 42") ); when(imapConnection.executeSimpleCommand("SEARCH 1:* FLAGGED NOT DELETED")).thenReturn(imapResponses); folder.open(OPEN_MODE_RW); int result = folder.getFlaggedMessageCount(); assertEquals(4, result); } @Test public void getHighestUid() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapResponse> imapResponses = singletonList(createImapResponse("* SEARCH 42")); when(imapConnection.executeSimpleCommand("UID SEARCH *:*")).thenReturn(imapResponses); folder.open(OPEN_MODE_RW); long result = folder.getHighestUid(); assertEquals(42L, result); } @Test public void getHighestUid_imapConnectionThrowsNegativesResponse_shouldReturnMinus1() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); when(imapConnection.executeSimpleCommand("UID SEARCH *:*")) .thenThrow(NegativeImapResponseException.class); folder.open(OPEN_MODE_RW); long highestUid = folder.getHighestUid(); assertEquals(-1L, highestUid); } @Test public void getHighestUid_imapConnectionThrowsIOException_shouldThrowMessagingException() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); when(imapConnection.executeSimpleCommand("UID SEARCH *:*")) .thenThrow(IOException.class); folder.open(OPEN_MODE_RW); try { folder.getHighestUid(); fail("Expected MessagingException"); } catch (MessagingException e) { assertEquals("IO Error", e.getMessage()); } } @Test public void getMessages_withoutDateConstraint() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapResponse> imapResponses = asList( createImapResponse("* SEARCH 3"), createImapResponse("* SEARCH 5"), createImapResponse("* SEARCH 6") ); when(imapConnection.executeSimpleCommand("UID SEARCH 1:10 NOT DELETED")).thenReturn(imapResponses); folder.open(OPEN_MODE_RW); List<ImapMessage> messages = folder.getMessages(1, 10, null, null); assertNotNull(messages); assertEquals(newSet("3", "5", "6"), extractMessageUids(messages)); } @Test public void getMessages_withDateConstraint() throws Exception { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapResponse> imapResponses = asList( createImapResponse("* SEARCH 47"), createImapResponse("* SEARCH 18") ); when(imapConnection.executeSimpleCommand("UID SEARCH 1:10 SINCE 06-Feb-2016 NOT DELETED")) .thenReturn(imapResponses); folder.open(OPEN_MODE_RW); List<ImapMessage> messages = folder.getMessages(1, 10, new Date(1454719826000L), null); assertNotNull(messages); assertEquals(newSet("18", "47"), extractMessageUids(messages)); } @Test public void getMessages_withListener_shouldCallListener() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapResponse> imapResponses = singletonList(createImapResponse("* SEARCH 99")); when(imapConnection.executeSimpleCommand("UID SEARCH 1:10 NOT DELETED")).thenReturn(imapResponses); folder.open(OPEN_MODE_RW); MessageRetrievalListener<ImapMessage> listener = createMessageRetrievalListener(); List<ImapMessage> result = folder.getMessages(1, 10, null, listener); ImapMessage message = result.get(0); verify(listener).messageStarted("99", 0, 1); verify(listener).messageFinished(message, 0, 1); verifyNoMoreInteractions(listener); } @Test public void getMessages_withInvalidStartArgument_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); try { folder.getMessages(0, 10, null, null); fail("Expected exception"); } catch (MessagingException e) { assertEquals("Invalid message set 0 10", e.getMessage()); } } @Test public void getMessages_withInvalidEndArgument_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); try { folder.getMessages(10, 0, null, null); fail("Expected exception"); } catch (MessagingException e) { assertEquals("Invalid message set 10 0", e.getMessage()); } } @Test public void getMessages_withEndArgumentSmallerThanStartArgument_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); try { folder.getMessages(10, 5, null, null); fail("Expected exception"); } catch (MessagingException e) { assertEquals("Invalid message set 10 5", e.getMessage()); } } @Test public void getMessages_withClosedFolder_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); try { folder.getMessages(1, 5, null, null); fail("Expected exception"); } catch (MessagingException e) { assertCheckOpenErrorMessage("Folder", e); } } @Test public void getMessages_sequenceNumbers_withClosedFolder_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); try { folder.getMessages(asList(1L, 2L, 5L), false, null); fail("Expected exception"); } catch (MessagingException e) { assertCheckOpenErrorMessage("Folder", e); } } @Test public void getMessages_sequenceNumbers() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapResponse> imapResponses = asList( createImapResponse("* SEARCH 17"), createImapResponse("* SEARCH 18"), createImapResponse("* SEARCH 49") ); when(imapConnection.executeSimpleCommand("UID SEARCH 1,2,5 NOT DELETED")).thenReturn(imapResponses); folder.open(OPEN_MODE_RW); List<ImapMessage> messages = folder.getMessages(asList(1L, 2L, 5L), false, null); assertNotNull(messages); assertEquals(newSet("17", "18", "49"), extractMessageUids(messages)); } @Test public void getMessages_sequenceNumbers_withListener_shouldCallListener() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapResponse> imapResponses = singletonList(createImapResponse("* SEARCH 99")); when(imapConnection.executeSimpleCommand("UID SEARCH 1")).thenReturn(imapResponses); folder.open(OPEN_MODE_RW); MessageRetrievalListener<ImapMessage> listener = createMessageRetrievalListener(); List<ImapMessage> result = folder.getMessages(singletonList(1L), true, listener); ImapMessage message = result.get(0); verify(listener).messageStarted("99", 0, 1); verify(listener).messageFinished(message, 0, 1); verifyNoMoreInteractions(listener); } @Test public void getMessagesFromUids_withClosedFolder_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); try { folder.getMessagesFromUids(asList("11", "22", "25")); fail("Expected exception"); } catch (MessagingException e) { assertCheckOpenErrorMessage("Folder", e); } } @Test public void getMessagesFromUids() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapResponse> imapResponses = asList( createImapResponse("* SEARCH 11"), createImapResponse("* SEARCH 22"), createImapResponse("* SEARCH 25") ); when(imapConnection.executeSimpleCommand("UID SEARCH UID 11,22,25")).thenReturn(imapResponses); folder.open(OPEN_MODE_RW); List<ImapMessage> messages = folder.getMessagesFromUids(asList("11", "22", "25")); assertNotNull(messages); assertEquals(newSet("11", "22", "25"), extractMessageUids(messages)); } @Test public void areMoreMessagesAvailable_withClosedFolder_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); when(imapStore.getConnection()).thenReturn(imapConnection); try { folder.areMoreMessagesAvailable(10, new Date()); fail("Expected exception"); } catch (MessagingException e) { assertCheckOpenErrorMessage("Folder", e); } } @Test public void areMoreMessagesAvailable_withAdditionalMessages_shouldReturnTrue() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); List<ImapResponse> imapResponses = singletonList(createImapResponse("* SEARCH 42")); when(imapConnection.executeSimpleCommand("SEARCH 1:9 NOT DELETED")).thenReturn(imapResponses); folder.open(OPEN_MODE_RW); boolean result = folder.areMoreMessagesAvailable(10, null); assertTrue(result); } @Test public void areMoreMessagesAvailable_withoutAdditionalMessages_shouldReturnFalse() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); folder.open(OPEN_MODE_RW); boolean result = folder.areMoreMessagesAvailable(600, null); assertFalse(result); } @Test public void areMoreMessagesAvailable_withIndexOf1_shouldReturnFalseWithoutPerformingSearch() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); folder.open(OPEN_MODE_RW); boolean areMoreMessagesAvailable = folder.areMoreMessagesAvailable(1, null); assertFalse(areMoreMessagesAvailable); //SELECT during OPEN and no more verify(imapConnection, times(1)).executeSimpleCommand(anyString()); } @Test public void areMoreMessagesAvailable_withoutAdditionalMessages_shouldIssueSearchCommandsUntilAllMessagesSearched() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); folder.open(OPEN_MODE_RW); folder.areMoreMessagesAvailable(600, null); verify(imapConnection).executeSimpleCommand("SEARCH 100:599 NOT DELETED"); verify(imapConnection).executeSimpleCommand("SEARCH 1:99 NOT DELETED"); } @Test public void fetch_withNullMessageListArgument_shouldDoNothing() throws Exception { ImapFolder folder = createFolder("Folder"); FetchProfile fetchProfile = createFetchProfile(); folder.fetch(null, fetchProfile, null); verifyNoMoreInteractions(imapStore); } @Test public void fetch_withEmptyMessageListArgument_shouldDoNothing() throws Exception { ImapFolder folder = createFolder("Folder"); FetchProfile fetchProfile = createFetchProfile(); folder.fetch(Collections.<ImapMessage>emptyList(), fetchProfile, null); verifyNoMoreInteractions(imapStore); } @Test public void fetch_withFlagsFetchProfile_shouldIssueRespectiveCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); folder.open(OPEN_MODE_RO); when(imapConnection.readResponse(any(ImapResponseCallback.class))).thenReturn(createImapResponse("x OK")); List<ImapMessage> messages = createImapMessages("1"); FetchProfile fetchProfile = createFetchProfile(Item.FLAGS); folder.fetch(messages, fetchProfile, null); verify(imapConnection).sendCommand("UID FETCH 1 (UID FLAGS)", false); } @Test public void fetch_withEnvelopeFetchProfile_shouldIssueRespectiveCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); folder.open(OPEN_MODE_RO); when(imapConnection.readResponse(any(ImapResponseCallback.class))).thenReturn(createImapResponse("x OK")); List<ImapMessage> messages = createImapMessages("1"); FetchProfile fetchProfile = createFetchProfile(Item.ENVELOPE); folder.fetch(messages, fetchProfile, null); verify(imapConnection).sendCommand("UID FETCH 1 (UID INTERNALDATE RFC822.SIZE BODY.PEEK[HEADER.FIELDS " + "(date subject from content-type to cc reply-to message-id references in-reply-to X-K9mail-Identity)]" + ")", false); } @Test public void fetch_withStructureFetchProfile_shouldIssueRespectiveCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); folder.open(OPEN_MODE_RO); when(imapConnection.readResponse(any(ImapResponseCallback.class))).thenReturn(createImapResponse("x OK")); List<ImapMessage> messages = createImapMessages("1"); FetchProfile fetchProfile = createFetchProfile(Item.STRUCTURE); folder.fetch(messages, fetchProfile, null); verify(imapConnection).sendCommand("UID FETCH 1 (UID BODYSTRUCTURE)", false); } @Test public void fetch_withBodySaneFetchProfile_shouldIssueRespectiveCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); folder.open(OPEN_MODE_RO); when(imapConnection.readResponse(any(ImapResponseCallback.class))).thenReturn(createImapResponse("x OK")); List<ImapMessage> messages = createImapMessages("1"); FetchProfile fetchProfile = createFetchProfile(Item.BODY_SANE); when(storeConfig.getMaximumAutoDownloadMessageSize()).thenReturn(4096); folder.fetch(messages, fetchProfile, null); verify(imapConnection).sendCommand("UID FETCH 1 (UID BODY.PEEK[]<0.4096>)", false); } @Test public void fetch_withBodySaneFetchProfileAndNoMaximumDownloadSize_shouldIssueRespectiveCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); folder.open(OPEN_MODE_RO); when(imapConnection.readResponse(any(ImapResponseCallback.class))).thenReturn(createImapResponse("x OK")); List<ImapMessage> messages = createImapMessages("1"); FetchProfile fetchProfile = createFetchProfile(Item.BODY_SANE); when(storeConfig.getMaximumAutoDownloadMessageSize()).thenReturn(0); folder.fetch(messages, fetchProfile, null); verify(imapConnection).sendCommand("UID FETCH 1 (UID BODY.PEEK[])", false); } @Test public void fetch_withBodyFetchProfileAndNoMaximumDownloadSize_shouldIssueRespectiveCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); folder.open(OPEN_MODE_RO); when(imapConnection.readResponse(any(ImapResponseCallback.class))).thenReturn(createImapResponse("x OK")); List<ImapMessage> messages = createImapMessages("1"); FetchProfile fetchProfile = createFetchProfile(Item.BODY); folder.fetch(messages, fetchProfile, null); verify(imapConnection).sendCommand("UID FETCH 1 (UID BODY.PEEK[])", false); } @Test public void fetch_withFlagsFetchProfile_shouldSetFlags() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); folder.open(OPEN_MODE_RO); List<ImapMessage> messages = createImapMessages("1"); FetchProfile fetchProfile = createFetchProfile(Item.FLAGS); when(imapConnection.readResponse(any(ImapResponseCallback.class))) .thenReturn(createImapResponse("* 1 FETCH (FLAGS (\\Seen) UID 1)")) .thenReturn(createImapResponse("x OK")); folder.fetch(messages, fetchProfile, null); ImapMessage imapMessage = messages.get(0); verify(imapMessage).setFlagInternal(Flag.SEEN, true); } @Test public void fetchPart_withTextSection_shouldIssueRespectiveCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); when(storeConfig.getMaximumAutoDownloadMessageSize()).thenReturn(4096); folder.open(OPEN_MODE_RO); ImapMessage message = createImapMessage("1"); Part part = createPart("TEXT"); when(imapConnection.readResponse(any(ImapResponseCallback.class))).thenReturn(createImapResponse("x OK")); folder.fetchPart(message, part, null); verify(imapConnection).sendCommand("UID FETCH 1 (UID BODY.PEEK[TEXT]<0.4096>)", false); } @Test public void fetchPart_withNonTextSection_shouldIssueRespectiveCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); folder.open(OPEN_MODE_RO); ImapMessage message = createImapMessage("1"); Part part = createPart("1.1"); when(imapConnection.readResponse(any(ImapResponseCallback.class))).thenReturn(createImapResponse("x OK")); folder.fetchPart(message, part, null); verify(imapConnection).sendCommand("UID FETCH 1 (UID BODY.PEEK[1.1])", false); } @Test public void fetchPart_withTextSection_shouldProcessImapResponses() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); folder.open(OPEN_MODE_RO); ImapMessage message = createImapMessage("1"); Part part = createPlainTextPart("1.1"); setupSingleFetchResponseToCallback(); folder.fetchPart(message, part, null); ArgumentCaptor<Body> bodyArgumentCaptor = ArgumentCaptor.forClass(Body.class); verify(part).setBody(bodyArgumentCaptor.capture()); Body body = bodyArgumentCaptor.getValue(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); body.writeTo(byteArrayOutputStream); assertEquals("text", new String(byteArrayOutputStream.toByteArray())); } @Test public void appendMessages_shouldIssueRespectiveCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); folder.open(OPEN_MODE_RW); List<ImapMessage> messages = createImapMessages("1"); when(imapConnection.readResponse()).thenReturn(createImapResponse("x OK [APPENDUID 1 23]")); folder.appendMessages(messages); verify(imapConnection).sendCommand("APPEND \"Folder\" () {0}", false); } @Test public void getUidFromMessageId_withoutMessageIdHeader_shouldReturnNull() throws Exception { ImapFolder folder = createFolder("Folder"); ImapMessage message = createImapMessage("2"); when(message.getHeader("Message-ID")).thenReturn(new String[0]); String result = folder.getUidFromMessageId(message); assertNull(result); } @Test public void getUidFromMessageId_withMessageIdHeader_shouldIssueUidSearchCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); folder.open(OPEN_MODE_RW); ImapMessage message = createImapMessage("2"); when(message.getHeader("Message-ID")).thenReturn(new String[] { "<00000000.0000000@example.org>" }); folder.getUidFromMessageId(message); verify(imapConnection).executeSimpleCommand("UID SEARCH HEADER MESSAGE-ID \"<00000000.0000000@example.org>\""); } @Test public void getUidFromMessageId() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); folder.open(OPEN_MODE_RW); ImapMessage message = createImapMessage("2"); when(message.getHeader("Message-ID")).thenReturn(new String[] { "<00000000.0000000@example.org>" }); when(imapConnection.executeSimpleCommand("UID SEARCH HEADER MESSAGE-ID \"<00000000.0000000@example.org>\"")) .thenReturn(singletonList(createImapResponse("* SEARCH 23"))); String result = folder.getUidFromMessageId(message); assertEquals("23", result); } @Test public void expunge_shouldIssueExpungeCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); folder.expunge(); verify(imapConnection).executeSimpleCommand("EXPUNGE"); } @Test public void setFlags_shouldIssueUidStoreCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); folder.setFlags(newSet(Flag.SEEN), true); verify(imapConnection).executeSimpleCommand("UID STORE 1:* +FLAGS.SILENT (\\Seen)"); } @Test public void getNewPushState_withNewerUid_shouldReturnNewPushState() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); ImapMessage message = createImapMessage("2"); String result = folder.getNewPushState("uidNext=2", message); assertEquals("uidNext=3", result); } @Test public void getNewPushState_withoutNewerUid_shouldReturnNull() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); ImapMessage message = createImapMessage("1"); String result = folder.getNewPushState("uidNext=2", message); assertNull(result); } @Test public void search_withFullTextSearchEnabled_shouldIssueRespectiveCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); when(storeConfig.allowRemoteSearch()).thenReturn(true); when(storeConfig.isRemoteSearchFullText()).thenReturn(true); folder.search("query", newSet(Flag.SEEN), Collections.<Flag>emptySet()); verify(imapConnection).executeSimpleCommand("UID SEARCH SEEN TEXT \"query\""); } @Test public void search_withFullTextSearchDisabled_shouldIssueRespectiveCommand() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RO); when(storeConfig.allowRemoteSearch()).thenReturn(true); when(storeConfig.isRemoteSearchFullText()).thenReturn(false); folder.search("query", Collections.<Flag>emptySet(), Collections.<Flag>emptySet()); verify(imapConnection).executeSimpleCommand("UID SEARCH OR SUBJECT \"query\" FROM \"query\""); } @Test public void search_withRemoteSearchDisabled_shouldThrow() throws Exception { ImapFolder folder = createFolder("Folder"); when(storeConfig.allowRemoteSearch()).thenReturn(false); try { folder.search("query", Collections.<Flag>emptySet(), Collections.<Flag>emptySet()); fail("Expected exception"); } catch (MessagingException e) { assertEquals("Your settings do not allow remote searching of this account", e.getMessage()); } } @Test(expected = Error.class) public void delete_notImplemented() throws Exception { ImapFolder folder = createFolder("Folder"); folder.delete(false); } @Test public void getMessageByUid_returnsNewImapMessageWithUidInFolder() throws Exception { ImapFolder folder = createFolder("Folder"); ImapMessage message = folder.getMessage("uid"); assertEquals("uid", message.getUid()); assertEquals(folder, message.getFolder()); } private Part createPlainTextPart(String serverExtra) { Part part = createPart(serverExtra); when(part.getHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING)).thenReturn( new String[] { MimeUtil.ENC_7BIT } ); when(part.getHeader(MimeHeader.HEADER_CONTENT_TYPE)).thenReturn( new String[] { "text/plain" } ); return part; } private void setupSingleFetchResponseToCallback() throws IOException { when(imapConnection.readResponse(any(ImapResponseCallback.class))) .thenAnswer(new Answer<ImapResponse>() { @Override public ImapResponse answer(InvocationOnMock invocation) throws Throwable { ImapResponseCallback callback = (ImapResponseCallback) invocation.getArguments()[0]; return buildImapFetchResponse(callback); } }) .thenAnswer(new Answer<ImapResponse>() { @Override public ImapResponse answer(InvocationOnMock invocation) throws Throwable { ImapResponseCallback callback = (ImapResponseCallback) invocation.getArguments()[0]; return ImapResponse.newTaggedResponse(callback, "TAG"); } }); } private ImapResponse buildImapFetchResponse(ImapResponseCallback callback) { ImapResponse response = ImapResponse.newContinuationRequest(callback); response.add("1"); response.add("FETCH"); ImapList fetchList = new ImapList(); fetchList.add("UID"); fetchList.add("1"); fetchList.add("BODY"); fetchList.add("1.1"); fetchList.add("text"); response.add(fetchList); return response; } private Set<String> extractMessageUids(List<ImapMessage> messages) { Set<String> result = new HashSet<>(); for (Message message : messages) { result.add(message.getUid()); } return result; } private ImapFolder createFolder(String folderName) { return new ImapFolder(imapStore, folderName, FolderNameCodec.newInstance()); } private ImapMessage createImapMessage(String uid) { ImapMessage message = mock(ImapMessage.class); when(message.getUid()).thenReturn(uid); return message; } private List<ImapMessage> createImapMessages(String... uids) { List<ImapMessage> imapMessages = new ArrayList<>(uids.length); for (String uid : uids) { ImapMessage imapMessage = createImapMessage(uid); imapMessages.add(imapMessage); } return imapMessages; } private Part createPart(String serverExtra) { Part part = mock(Part.class); when(part.getServerExtra()).thenReturn(serverExtra); return part; } private FetchProfile createFetchProfile(Item... items) { FetchProfile fetchProfile = new FetchProfile(); Collections.addAll(fetchProfile, items); return fetchProfile; } @SuppressWarnings("unchecked") private MessageRetrievalListener<ImapMessage> createMessageRetrievalListener() { return mock(MessageRetrievalListener.class); } private void prepareImapFolderForOpen(int openMode) throws MessagingException, IOException { when(imapStore.getConnection()).thenReturn(imapConnection); List<ImapResponse> imapResponses = asList( createImapResponse("* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft NonJunk $MDNSent)"), createImapResponse("* OK [PERMANENTFLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft NonJunk " + "$MDNSent \\*)] Flags permitted."), createImapResponse("* 23 EXISTS"), createImapResponse("* 0 RECENT"), createImapResponse("* OK [UIDVALIDITY 1125022061] UIDs valid"), createImapResponse("* OK [UIDNEXT 57576] Predicted next UID"), (openMode == OPEN_MODE_RW) ? createImapResponse("2 OK [READ-WRITE] Select completed.") : createImapResponse("2 OK [READ-ONLY] Examine completed.") ); if (openMode == OPEN_MODE_RW) { when(imapConnection.executeSimpleCommand("SELECT \"Folder\"")).thenReturn(imapResponses); } else { when(imapConnection.executeSimpleCommand("EXAMINE \"Folder\"")).thenReturn(imapResponses); } } private void assertCheckOpenErrorMessage(String folderName, MessagingException e) { assertEquals("Folder " + folderName + " is not open.", e.getMessage()); } }
package model; import java.lang.ref.WeakReference; import java.util.List; import javafx.beans.property.BooleanProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.eclipse.egit.github.core.Issue; import org.eclipse.egit.github.core.Label; import org.eclipse.egit.github.core.PullRequest; import util.UserConfigurations; public class TurboIssue implements Listable { private static final String STATE_CLOSED = "closed"; private static final String STATE_OPEN = "open"; private static final String REGEX_REPLACE_DESC = "^[^<>]*<hr>"; private static final String REGEX_SPLIT_PARENT = "(,\\s+)? private static final String REGEX_SPLIT_LINES = "(\\r?\\n)+"; private static final String METADATA_HEADER_PARENT = "* Parent: "; private static final String METADATA_PARENT = "#%1d \n"; private static final String METADATA_SEPERATOR = "<hr>"; /* * Attributes, Getters & Setters */ private WeakReference<Model> model; private WeakReference<Model> getModel(){ return model; } private int numOfComments; public int getNumOfComments(){ return numOfComments; } public void setNumOfComments(int num){ this.numOfComments = num; } private PullRequest pullRequest; public PullRequest getPullRequest(){ return pullRequest; } public void setPullRequest(PullRequest pr){ this.pullRequest = pr; } private IntegerProperty id = new SimpleIntegerProperty(); public final int getId() { return id.get(); } public final void setId(int value) { id.set(value); } public IntegerProperty idProperty() { return id; } private StringProperty title = new SimpleStringProperty(); public final String getTitle() { return title.get(); } public final void setTitle(String value) { title.set(value); } public StringProperty titleProperty() { return title; } private StringProperty description = new SimpleStringProperty(); public final String getDescription() { return description.get(); } public final void setDescription(String value) { description.set(value); } public StringProperty descriptionProperty() { return description; } private IntegerProperty parentIssue = new SimpleIntegerProperty(); public int getParentIssue(){ return parentIssue.get(); } public final IntegerProperty parentIssueProperty(){ return parentIssue; } public final void setParentIssue(int parent){ parentIssue.set(parent); } private BooleanProperty state = new SimpleBooleanProperty(); public final Boolean getOpen() { return state.get(); } public final void setOpen(Boolean value) { state.set(value); } public BooleanProperty openProperty() { return state; } private TurboUser assignee; public TurboUser getAssignee() { return assignee; } public void setAssignee(TurboUser assignee) { this.assignee = getCollaboratorReference(assignee); } private TurboMilestone milestone; public TurboMilestone getMilestone() { return milestone; } public void setMilestone(TurboMilestone milestone) { this.milestone = getMilestoneReference(milestone); } private String htmlUrl; public String getHtmlUrl() { return htmlUrl; } private void setHtmlUrl(String htmlUrl) { this.htmlUrl = htmlUrl; } private ObservableList<TurboLabel> labels = FXCollections.observableArrayList(); public ObservableList<TurboLabel> getLabels() { return FXCollections.observableArrayList(labels); } public ObservableList<TurboLabel> getLabelsReference() { return labels; } private TurboLabel getLabelReference(TurboLabel label){ List<TurboLabel> allLabels = model.get().getLabels(); int index = allLabels.indexOf(label); assert index != -1; return allLabels.get(index); } private TurboMilestone getMilestoneReference(TurboMilestone milestone){ List<TurboMilestone> allMilestones = model.get().getMilestones(); int index = allMilestones.indexOf(milestone); if(index != -1){ return allMilestones.get(index); }else{ return milestone; } } private TurboUser getCollaboratorReference(TurboUser user){ List<TurboUser> allCollaborators = model.get().getCollaborators(); int index = allCollaborators.indexOf(user); if(index != -1){ return allCollaborators.get(index); }else{ return user; } } public boolean hasLabel(TurboLabel label){ return labels.contains(label); } public void addLabel(TurboLabel label){ if(labels.contains(label)){ return; } if (UserConfigurations.isClosedStatusLabel(label.toGhName())) { this.setOpen(false); }else if(UserConfigurations.isOpenStatusLabel(label.toGhName())){ this.setOpen(true); } addToLabels(label); } public void addLabels(List<TurboLabel> labList){ for(TurboLabel label : labList){ addLabel(label); } } public void removeLabel(TurboLabel label){ if(!labels.remove(label)){ return; } if (UserConfigurations.isClosedStatusLabel(label.toGhName())) { //Default status of the issue is open this.setOpen(true); } } public void removeLabels(List<TurboLabel> labList){ for(TurboLabel label : labList){ removeLabel(label); } } private void addToLabels(TurboLabel label){ labels.add(getLabelReference(label)); } public void setLabels(List<TurboLabel> labels) { if(this.labels != labels){ clearAllLabels(); for(TurboLabel label : labels){ addLabel(label); } } } public void clearAllLabels(){ this.labels.clear(); this.setOpen(true); } /* * Constructors & Public Methods */ public TurboIssue(String title, String desc, Model model) { assert title != null; assert desc != null; assert model != null; this.model = new WeakReference<Model>(model); setTitle(title); setDescription(desc); setOpen(true); } // Copy constructor public TurboIssue(TurboIssue other) { assert other != null; copyValues(other); } public TurboIssue(Issue issue, Model model) { assert issue != null; assert model != null; this.model = new WeakReference<Model>(model); setHtmlUrl(issue.getHtmlUrl()); setTitle(issue.getTitle()); setOpen(new Boolean(issue.getState().equals(STATE_OPEN))); setId(issue.getNumber()); setDescription(extractDescription(issue.getBody())); setAssignee(issue.getAssignee() == null ? null : new TurboUser(issue.getAssignee())); setMilestone(issue.getMilestone() == null ? null : new TurboMilestone(issue.getMilestone())); setLabels(translateLabels(issue.getLabels())); setParentIssue(extractIssueParent(issue.getBody())); setPullRequest(issue.getPullRequest()); setNumOfComments(issue.getComments()); } public Issue toGhResource() { Issue ghIssue = new Issue(); ghIssue.setHtmlUrl(getHtmlUrl()); ghIssue.setNumber(getId()); ghIssue.setTitle(getTitle()); ghIssue.setState(getOpen() ? STATE_OPEN : STATE_CLOSED); if (assignee != null) ghIssue.setAssignee(assignee.toGhResource()); if (milestone != null) ghIssue.setMilestone(milestone.toGhResource()); ghIssue.setLabels(TurboLabel.toGhLabels(labels)); ghIssue.setBody(buildGithubBody()); return ghIssue; } public void copyValues(Object other) { assert other != null; if(other.getClass() == TurboIssue.class){ TurboIssue obj = (TurboIssue)other; model = obj.getModel(); setHtmlUrl(obj.getHtmlUrl()); setTitle(obj.getTitle()); setOpen(obj.getOpen()); setId(obj.getId()); setDescription(obj.getDescription()); setAssignee(obj.getAssignee()); setMilestone(obj.getMilestone()); setLabels(obj.getLabels()); setParentIssue(obj.getParentIssue()); setPullRequest(obj.getPullRequest()); setNumOfComments(obj.getNumOfComments()); } } /* * Private Methods */ private String extractDescription(String issueBody) { if (issueBody == null) return ""; String description = issueBody.replaceAll(REGEX_REPLACE_DESC, "").trim(); return description; } private Integer extractIssueParent(String issueBody) { if (issueBody == null){ return -1; } String[] lines = issueBody.split(REGEX_SPLIT_LINES); int seperatorLineIndex = getSeperatorIndex(lines); for (int i = 0; i < seperatorLineIndex; i++) { String line = lines[i]; if(id.get() == 29){ System.out.println(line); } if (line.startsWith(METADATA_HEADER_PARENT)) { System.out.println(line); String value = line.replace(METADATA_HEADER_PARENT, ""); String[] valueTokens = value.split(REGEX_SPLIT_PARENT); for (int j = 0; j < valueTokens.length; j++) { System.out.println(valueTokens); if (!valueTokens[j].trim().isEmpty()){ return Integer.parseInt(valueTokens[j].trim()); } } } } return -1; } private ObservableList<TurboLabel> translateLabels(List<Label> labels) { ObservableList<TurboLabel> turboLabels = FXCollections.observableArrayList(); if (labels == null) return turboLabels; for (Label label : labels) { turboLabels.add(new TurboLabel(label)); } return turboLabels; } private int getSeperatorIndex(String[] lines) { for (int i = 0; i < lines.length; i++) { if (lines[i].equals(METADATA_SEPERATOR)) { return i; } } return -1; } public String buildGithubBody() { StringBuilder body = new StringBuilder(); int parent = this.getParentIssue(); if(parent > 0){ String parentData = METADATA_HEADER_PARENT + METADATA_PARENT; body.append(String.format(parentData, this.getParentIssue())); body.append(METADATA_SEPERATOR + "\n"); } body.append(getDescription()); return body.toString(); } /* * Overridden Methods */ @Override public String toString() { return "Issue " + getTitle(); } @Override public String getListName() { return "#" + getId() + " " + getTitle(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TurboIssue other = (TurboIssue) obj; if (id == null) { if (other.id != null) return false; } else if (getId() != other.getId()) return false; return true; } /** * Deprecated methods * */ // private ObservableList<Integer> parents = FXCollections.observableArrayList(); // public ObservableList<Integer> getParents() { // return FXCollections.observableArrayList(parents); // public ObservableList<Integer> getParentsReference(){ // return parents; // public void setParents(ObservableList<Integer> parentNumbers) { // if (this.parents == null) { // this.parents = parentNumbers; // } else if (parentNumbers != this.parents) { // this.parents.clear(); // if(!parentNumbers.isEmpty()){ // this.parents.add(parentNumbers.get(0)); // public void addParent(Integer parentId){ // //Only single parent for now. This might be extended in future to allow multiple parents // this.parents.clear(); // this.parents.add(parentId); // private ObservableList<Integer> extractParentNumbers(String issueBody) { // ObservableList<Integer> parents = FXCollections.observableArrayList(); // if (issueBody == null) return parents; // String[] lines = issueBody.split(REGEX_SPLIT_LINES); // int seperatorLineIndex = getSeperatorIndex(lines); // for (int i = 0; i < seperatorLineIndex; i++) { // String line = lines[i]; // if (line.startsWith(METADATA_HEADER_PARENT)) { // String value = line.replace(METADATA_HEADER_PARENT, ""); // String[] valueTokens = value.split(REGEX_SPLIT_PARENT); // for (int j = 0; j < valueTokens.length; j++) { // if (valueTokens[j].trim().isEmpty()) continue; // parents.add(Integer.parseInt(valueTokens[j].trim())); // return parents; // public String buildGithubBody() { // StringBuilder body = new StringBuilder(); // if (!parents.isEmpty()) { // String parentsMd = METADATA_HEADER_PARENT; // Iterator<Integer> parentsItr = parents.iterator(); // while (parentsItr.hasNext()) { // parentsMd = parentsMd + "#" + parentsItr.next(); // if (parentsItr.hasNext()) { // parentsMd = parentsMd + ", "; // body.append(parentsMd + "\n"); // body.append(METADATA_SEPERATOR + "\n"); // body.append(getDescription()); // return body.toString(); }
package test.integration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Test; import usi.gui.functionality.GUIFunctionality_search; import usi.gui.functionality.mapping.Instance_GUI_pattern; import usi.gui.functionality.mapping.Instance_window; import usi.gui.pattern.Boolean_regexp; import usi.gui.pattern.Cardinality; import usi.gui.pattern.GUI_Pattern; import usi.gui.pattern.Pattern_action_widget; import usi.gui.pattern.Pattern_input_widget; import usi.gui.pattern.Pattern_window; import usi.gui.structure.Action_widget; import usi.gui.structure.GUI; import usi.gui.structure.Input_widget; import usi.gui.structure.Window; import usi.guisemantic.FunctionalitySemantics; import usi.guisemantic.SpecificSemantics; import usi.guisemantic.alloy.AlloyUtil; import usi.guisemantic.alloy.Alloy_Model; import usi.guisemantic.testcase.AlloyTestCaseGenerator; import usi.guisemantic.testcase.GUITestCase; import edu.mit.csail.sdg.alloy4compiler.translator.A4Solution; public class AlloyTestCaseGenerationTest { public class Action_widget_test extends Action_widget { public Action_widget_test(final String id, final String label) throws Exception { super(id, label, "class", 1, 1); } } public class Input_widget_test extends Input_widget { public Input_widget_test(final String id, final String label, final String value) throws Exception { super(id, label, "class", 1, 1, value); } } public class Window_test extends Window { public Window_test(final String id, final String label) throws Exception { super(id, label, "class", 1, 1, false); } public Window_test(final String id, final boolean b, final String label) throws Exception { super(id, label, "class", 1, 1, b); } public Window_test(final String id, final boolean b, final String label, final boolean root) throws Exception { super(id, label, "class", 1, 1, b); super.setRoot(root); } } @Test public void test1() { try { String gui_s = ""; String s; BufferedReader br = new BufferedReader(new FileReader("./files/alloy/GUI_general.als")); while ((s = br.readLine()) != null) { gui_s += s + System.getProperty("line.separator"); } br.close(); br = new BufferedReader(new FileReader("./files/alloy/ADD.als")); String func_s = ""; while ((s = br.readLine()) != null) { func_s += s + System.getProperty("line.separator"); } br.close(); br = new BufferedReader(new FileReader("./files/for_test/alloy/specific.als")); String spec = ""; while ((s = br.readLine()) != null) { spec += s + System.getProperty("line.separator"); } br.close(); final String model = gui_s + func_s; final String spec_model = model + spec; final Alloy_Model func = AlloyUtil.loadAlloyModelFromString(model); final FunctionalitySemantics func_sem = FunctionalitySemantics.instantiate(func); final Alloy_Model func_spec = AlloyUtil.loadAlloyModelFromString(spec_model); final SpecificSemantics spec_sem = SpecificSemantics.instantiate(func_spec); final Instance_GUI_pattern inst = new Instance_GUI_pattern(new GUI(), new GUI_Pattern(), new ArrayList<Instance_window>()) { @Override public void generateSpecificSemantics() throws Exception { this.semantics = spec_sem; } }; inst.generateSpecificSemantics(); class For_test extends AlloyTestCaseGenerator { public For_test(final Instance_GUI_pattern instance) { super(instance); // TODO Auto-generated constructor stub } @Override protected GUITestCase analyzeTuples(final A4Solution solution) throws Exception { return null; } } final For_test generator = new For_test(inst); final List<GUITestCase> tests = generator.generateTestCases(1, 30000); assertEquals(3, tests.size()); } catch ( final Exception e) { e.printStackTrace(); fail(); } } @Test public void test2() throws Exception { final GUI gui = new GUI(); final Window w1 = new Window_test("w1", "init"); final Action_widget aw1 = new Action_widget_test("aw1", "add"); final Action_widget aw2 = new Action_widget_test("aw2", "test"); w1.addWidget(aw1); w1.addWidget(aw2); gui.addWindow(w1); final Window w2 = new Window_test("w2", "form"); final Action_widget aw3 = new Action_widget_test("aw3", "next"); final Action_widget aw4 = new Action_widget_test("aw4", "back"); final Input_widget iw1 = new Input_widget_test("iw1", "field1", ""); final Input_widget iw2 = new Input_widget_test("iw2", "field2", ""); w2.addWidget(aw3); w2.addWidget(aw4); w2.addWidget(iw1); w2.addWidget(iw2); gui.addWindow(w2); final Window w3 = new Window_test("w3", "other"); final Action_widget aw5 = new Action_widget_test("aw5", "add"); final Input_widget iw3 = new Input_widget_test("iw3", "field3", ""); w3.addWidget(aw5); w3.addWidget(iw3); gui.addWindow(w3); // edges gui.addStaticEdge(aw1, w2); gui.addStaticEdge(aw2, w3); gui.addStaticEdge(aw4, w1); final GUI_Pattern pattern = new GUI_Pattern(); // pw1 final Pattern_window pw1 = new Pattern_window("pw1", ".*", Cardinality.SOME, "Initial", Boolean_regexp.ANY, Boolean_regexp.ANY); final Pattern_action_widget paw1 = new Pattern_action_widget("paw1", ".*add.*", Cardinality.SOME, "Trigger"); pw1.addWidget(paw1); pattern.addWindow(pw1); // pw2 final Pattern_window pw2 = new Pattern_window("pw2", ".*", Cardinality.ONE, "Form", Boolean_regexp.ANY, Boolean_regexp.ANY); final Pattern_action_widget paw2 = new Pattern_action_widget("paw2", ".*next.*", Cardinality.ONE, "Ok"); final Pattern_action_widget paw3 = new Pattern_action_widget("paw3", ".*back.*", Cardinality.ONE, "Cancel"); final Pattern_input_widget piw1 = new Pattern_input_widget("piw1", ".*", Cardinality.SOME, "Input_widget", null); pw2.addWidget(paw2); pw2.addWidget(paw3); pw2.addWidget(piw1); pattern.addWindow(pw2); // pw3 final Pattern_window pw3 = new Pattern_window("pw3", ".*", Cardinality.LONE, "Confirm", Boolean_regexp.TRUE, Boolean_regexp.ANY); final Pattern_action_widget paw4 = new Pattern_action_widget("paw4", ".*ok.*", Cardinality.ONE, "Ok"); final Pattern_action_widget paw5 = new Pattern_action_widget("paw5", ".*back.*", Cardinality.ONE, "Cancel"); pw3.addWidget(paw4); pw3.addWidget(paw5); pattern.addWindow(pw3); // edges pattern.addEdge(paw1, pw2); pattern.addEdge(paw3, pw1); pattern.addEdge(paw2, pw3); pattern.addEdge(paw5, pw2); pattern.loadSemantics("ADD.als"); // final Alloy_Model model = AlloyUtil.loadAlloyModelFromFile(new // File("./files/alloy/ADD.als")); // pattern.setSemantics(FunctionalitySemantics.instantiate(model)); final GUIFunctionality_search gfs = new GUIFunctionality_search(gui); final List<Instance_GUI_pattern> res = gfs.match(pattern); assertEquals(1, res.size()); assertEquals(2, res.get(0).getWindows().size()); Instance_window ww1 = null; Instance_window ww2 = null; for (final Instance_window ww : res.get(0).getWindows()) { switch (ww.getInstance().getId()) { case "w1": ww1 = ww; break; case "w2": ww2 = ww; break; } } assertTrue(ww1 != null); assertTrue(ww2 != null); final Instance_GUI_pattern in = res.get(0); in.generateSpecificSemantics(); final AlloyTestCaseGenerator generator = new AlloyTestCaseGenerator(in); final List<GUITestCase> tests = generator.generateTestCases(1, 30000); assertEquals(4, tests.size()); } /** * Scenario taken from test 2 * * @throws Exception */ @Test public void test3_RefineSemanticSpecification() throws Exception { // Concrete GUI, 3 forms final GUI gui = new GUI(); final Window w1 = new Window_test("w1", "init"); final Action_widget aw1 = new Action_widget_test("aw1", "add"); final Action_widget aw2 = new Action_widget_test("aw2", "test"); w1.addWidget(aw1); w1.addWidget(aw2); gui.addWindow(w1); final Window w2 = new Window_test("w2", "form"); final Action_widget aw3 = new Action_widget_test("aw3", "next"); final Action_widget aw4 = new Action_widget_test("aw4", "back"); final Input_widget iw1 = new Input_widget_test("iw1", "field1", ""); final Input_widget iw2 = new Input_widget_test("iw2", "field2", ""); w2.addWidget(aw3); w2.addWidget(aw4); w2.addWidget(iw1); w2.addWidget(iw2); gui.addWindow(w2); final Window w3 = new Window_test("w3", "other"); final Action_widget aw5 = new Action_widget_test("aw5", "add"); final Input_widget iw3 = new Input_widget_test("iw3", "field3", ""); w3.addWidget(aw5); w3.addWidget(iw3); gui.addWindow(w3); // edges gui.addStaticEdge(aw1, w2); gui.addStaticEdge(aw2, w3); gui.addStaticEdge(aw4, w1); final GUI_Pattern pattern = new GUI_Pattern(); // pw1 final Pattern_window pw1 = new Pattern_window("pw1", ".*", Cardinality.SOME, "Initial", Boolean_regexp.ANY, Boolean_regexp.ANY); final Pattern_action_widget paw1 = new Pattern_action_widget("paw1", ".*add.*", Cardinality.SOME, "Trigger"); pw1.addWidget(paw1); pattern.addWindow(pw1); // pw2 final Pattern_window pw2 = new Pattern_window("pw2", ".*", Cardinality.ONE, "Form", Boolean_regexp.ANY, Boolean_regexp.ANY); final Pattern_action_widget paw2 = new Pattern_action_widget("paw2", ".*next.*", Cardinality.ONE, "Ok"); final Pattern_action_widget paw3 = new Pattern_action_widget("paw3", ".*back.*", Cardinality.ONE, "Cancel"); final Pattern_input_widget piw1 = new Pattern_input_widget("piw1", ".*", Cardinality.SOME, "Input_widget", null); pw2.addWidget(paw2); pw2.addWidget(paw3); pw2.addWidget(piw1); pattern.addWindow(pw2); // pw3 final Pattern_window pw3 = new Pattern_window("pw3", ".*", Cardinality.LONE, "Confirm", Boolean_regexp.TRUE, Boolean_regexp.ANY); final Pattern_action_widget paw4 = new Pattern_action_widget("paw4", ".*ok.*", Cardinality.ONE, "Ok"); final Pattern_action_widget paw5 = new Pattern_action_widget("paw5", ".*back.*", Cardinality.ONE, "Cancel"); pw3.addWidget(paw4); pw3.addWidget(paw5); pattern.addWindow(pw3); // edges pattern.addEdge(paw1, pw2); pattern.addEdge(paw3, pw1); pattern.addEdge(paw2, pw3); pattern.addEdge(paw5, pw2); // Pattern 3 Windows pattern.loadSemantics("ADD.als"); final GUIFunctionality_search gfs = new GUIFunctionality_search(gui); final List<Instance_GUI_pattern> res = gfs.match(pattern); assertEquals(1, res.size()); assertEquals(2, res.get(0).getWindows().size()); Instance_window ww1 = null; Instance_window ww2 = null; for (final Instance_window ww : res.get(0).getWindows()) { switch (ww.getInstance().getId()) { case "w1": ww1 = ww; break; case "w2": ww2 = ww; break; } } assertTrue(ww1 != null); assertTrue(ww2 != null); final Instance_GUI_pattern in = res.get(0); in.generateSpecificSemantics(); final SpecificSemantics spec = in.getSemantics(); System.out.println("Sign " + spec.getSignatures().size()); System.out.println("Facts " + spec.getFacts().size()); final Map<Window, Pattern_window> winMap = in.getWindows_mapping(); // pw3 (Confirmation window) was not associated to a windows because it // was not discovered // let's assert this: for (final Window win : winMap.keySet()) { final String pwi = winMap.get(win).getId(); assertNotSame(pw3, pwi); } final SpecificSemantics semantic4discoveringPw3 = AlloyTestCaseGenerator .semantic4DiscoverWindow(in, w2, // sourceWindow, // pw3, // pattern_TargetWindow,// paw2// patternActionWidget ); assertNotNull(semantic4discoveringPw3); assertTrue(semantic4discoveringPw3.getFacts().size() > in.getSemantics().getFacts().size()); assertTrue(semantic4discoveringPw3.getSignatures().size() > in.getSemantics() .getSignatures().size()); // final AlloyTestCaseGenerator generator = new // AlloyTestCaseGenerator(in); // final List<GUITestCase> tests = generator.generateTestCases(1, // 30000); // assertEquals(4, tests.size()); } }
package org.joml; import java.io.IOException; import java.lang.reflect.Field; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * Helper class to do efficient memory operations on all JOML objects, NIO buffers and primitive arrays. * This class is used internally throughout JOML, is undocumented and is subject to change. * Use with extreme caution! * * @author The LWJGL authors * @author Kai Burjack */ abstract class MemUtil { public static final MemUtil INSTANCE = createInstance(); private static final MemUtil createInstance() { MemUtil accessor; try { if (Options.NO_UNSAFE) accessor = new MemUtilNIO(); else accessor = new MemUtilUnsafe(); } catch (Throwable e) { accessor = new MemUtilNIO(); } return accessor; } public abstract MemUtilUnsafe UNSAFE(); public abstract void put(Matrix4f m, int offset, FloatBuffer dest); public abstract void put(Matrix4f m, int offset, ByteBuffer dest); public abstract void put(Matrix4x3f m, int offset, FloatBuffer dest); public abstract void put(Matrix4x3f m, int offset, ByteBuffer dest); public abstract void put4x4(Matrix4x3f m, int offset, FloatBuffer dest); public abstract void put4x4(Matrix4x3f m, int offset, ByteBuffer dest); public abstract void put4x4(Matrix4x3d m, int offset, DoubleBuffer dest); public abstract void put4x4(Matrix4x3d m, int offset, ByteBuffer dest); public abstract void putTransposed(Matrix4f m, int offset, FloatBuffer dest); public abstract void putTransposed(Matrix4f m, int offset, ByteBuffer dest); public abstract void put4x3Transposed(Matrix4f m, int offset, FloatBuffer dest); public abstract void put4x3Transposed(Matrix4f m, int offset, ByteBuffer dest); public abstract void putTransposed(Matrix4x3f m, int offset, FloatBuffer dest); public abstract void putTransposed(Matrix4x3f m, int offset, ByteBuffer dest); public abstract void putTransposed(Matrix3f m, int offset, FloatBuffer dest); public abstract void putTransposed(Matrix3f m, int offset, ByteBuffer dest); public abstract void put(Matrix4d m, int offset, DoubleBuffer dest); public abstract void put(Matrix4d m, int offset, ByteBuffer dest); public abstract void put(Matrix4x3d m, int offset, DoubleBuffer dest); public abstract void put(Matrix4x3d m, int offset, ByteBuffer dest); public abstract void putf(Matrix4d m, int offset, FloatBuffer dest); public abstract void putf(Matrix4d m, int offset, ByteBuffer dest); public abstract void putf(Matrix4x3d m, int offset, FloatBuffer dest); public abstract void putf(Matrix4x3d m, int offset, ByteBuffer dest); public abstract void putTransposed(Matrix4d m, int offset, DoubleBuffer dest); public abstract void putTransposed(Matrix4d m, int offset, ByteBuffer dest); public abstract void put4x3Transposed(Matrix4d m, int offset, DoubleBuffer dest); public abstract void put4x3Transposed(Matrix4d m, int offset, ByteBuffer dest); public abstract void putTransposed(Matrix4x3d m, int offset, DoubleBuffer dest); public abstract void putTransposed(Matrix4x3d m, int offset, ByteBuffer dest); public abstract void putfTransposed(Matrix4d m, int offset, FloatBuffer dest); public abstract void putfTransposed(Matrix4d m, int offset, ByteBuffer dest); public abstract void putfTransposed(Matrix4x3d m, int offset, FloatBuffer dest); public abstract void putfTransposed(Matrix4x3d m, int offset, ByteBuffer dest); public abstract void put(Matrix3f m, int offset, FloatBuffer dest); public abstract void put(Matrix3f m, int offset, ByteBuffer dest); public abstract void put(Matrix3d m, int offset, DoubleBuffer dest); public abstract void put(Matrix3d m, int offset, ByteBuffer dest); public abstract void putf(Matrix3d m, int offset, FloatBuffer dest); public abstract void putf(Matrix3d m, int offset, ByteBuffer dest); public abstract void put(Vector4d src, int offset, DoubleBuffer dest); public abstract void put(Vector4d src, int offset, ByteBuffer dest); public abstract void put(Vector4f src, int offset, FloatBuffer dest); public abstract void put(Vector4f src, int offset, ByteBuffer dest); public abstract void put(Vector4i src, int offset, IntBuffer dest); public abstract void put(Vector4i src, int offset, ByteBuffer dest); public abstract void put(Vector3f src, int offset, FloatBuffer dest); public abstract void put(Vector3f src, int offset, ByteBuffer dest); public abstract void put(Vector3d src, int offset, DoubleBuffer dest); public abstract void put(Vector3d src, int offset, ByteBuffer dest); public abstract void put(Vector3i src, int offset, IntBuffer dest); public abstract void put(Vector3i src, int offset, ByteBuffer dest); public abstract void put(Vector2f src, int offset, FloatBuffer dest); public abstract void put(Vector2f src, int offset, ByteBuffer dest); public abstract void put(Vector2d src, int offset, DoubleBuffer dest); public abstract void put(Vector2d src, int offset, ByteBuffer dest); public abstract void put(Vector2i src, int offset, IntBuffer dest); public abstract void put(Vector2i src, int offset, ByteBuffer dest); public abstract void get(Matrix4f m, int offset, FloatBuffer src); public abstract void get(Matrix4f m, int offset, ByteBuffer src); public abstract void get(Matrix4x3f m, int offset, FloatBuffer src); public abstract void get(Matrix4x3f m, int offset, ByteBuffer src); public abstract void get(Matrix4d m, int offset, DoubleBuffer src); public abstract void get(Matrix4d m, int offset, ByteBuffer src); public abstract void get(Matrix4x3d m, int offset, DoubleBuffer src); public abstract void get(Matrix4x3d m, int offset, ByteBuffer src); public abstract void getf(Matrix4d m, int offset, FloatBuffer src); public abstract void getf(Matrix4d m, int offset, ByteBuffer src); public abstract void getf(Matrix4x3d m, int offset, FloatBuffer src); public abstract void getf(Matrix4x3d m, int offset, ByteBuffer src); public abstract void get(Matrix3f m, int offset, FloatBuffer src); public abstract void get(Matrix3f m, int offset, ByteBuffer src); public abstract void get(Matrix3d m, int offset, DoubleBuffer src); public abstract void get(Matrix3d m, int offset, ByteBuffer src); public abstract void getf(Matrix3d m, int offset, FloatBuffer src); public abstract void getf(Matrix3d m, int offset, ByteBuffer src); public abstract void get(Vector4d dst, int offset, DoubleBuffer src); public abstract void get(Vector4d dst, int offset, ByteBuffer src); public abstract void get(Vector4f dst, int offset, FloatBuffer src); public abstract void get(Vector4f dst, int offset, ByteBuffer src); public abstract void get(Vector4i dst, int offset, IntBuffer src); public abstract void get(Vector4i dst, int offset, ByteBuffer src); public abstract void get(Vector3f dst, int offset, FloatBuffer src); public abstract void get(Vector3f dst, int offset, ByteBuffer src); public abstract void get(Vector3d dst, int offset, DoubleBuffer src); public abstract void get(Vector3d dst, int offset, ByteBuffer src); public abstract void get(Vector3i dst, int offset, IntBuffer src); public abstract void get(Vector3i dst, int offset, ByteBuffer src); public abstract void get(Vector2f dst, int offset, FloatBuffer src); public abstract void get(Vector2f dst, int offset, ByteBuffer src); public abstract void get(Vector2d dst, int offset, DoubleBuffer src); public abstract void get(Vector2d dst, int offset, ByteBuffer src); public abstract void get(Vector2i dst, int offset, IntBuffer src); public abstract void get(Vector2i dst, int offset, ByteBuffer src); public abstract void copy(Matrix4f src, Matrix4f dest); public abstract void copy(Matrix4x3f src, Matrix4x3f dest); public abstract void copy(Matrix4f src, Matrix4x3f dest); public abstract void copy(Matrix4x3f src, Matrix4f dest); public abstract void copy(Matrix3f src, Matrix3f dest); public abstract void copy(Matrix3f src, Matrix4f dest); public abstract void copy(Matrix4f src, Matrix3f dest); public abstract void copy(Matrix3f src, Matrix4x3f dest); public abstract void copy3x3(Matrix4f src, Matrix4f dest); public abstract void copy3x3(Matrix4x3f src, Matrix4x3f dest); public abstract void copy3x3(Matrix3f src, Matrix4x3f dest); public abstract void copy3x3(Matrix3f src, Matrix4f dest); public abstract void copy4x3(Matrix4f src, Matrix4f dest); public abstract void copy4x3(Matrix4x3f src, Matrix4f dest); public abstract void copy(Vector4f src, Vector4f dst); public abstract void copy(Vector4i src, Vector4i dst); public abstract void copy(Quaternionf src, Quaternionf dst); public abstract void copy(float[] arr, int off, Matrix4f dest); public abstract void copy(float[] arr, int off, Matrix3f dest); public abstract void copy(float[] arr, int off, Matrix4x3f dest); public abstract void copy(Matrix4f src, float[] dest, int off); public abstract void copy(Matrix3f src, float[] dest, int off); public abstract void copy(Matrix4x3f src, float[] dest, int off); public abstract void identity(Matrix4f dest); public abstract void identity(Matrix4x3f dest); public abstract void identity(Matrix3f dest); public abstract void identity(Quaternionf dest); public abstract void swap(Matrix4f m1, Matrix4f m2); public abstract void swap(Matrix4x3f m1, Matrix4x3f m2); public abstract void swap(Matrix3f m1, Matrix3f m2); public abstract void zero(Matrix4f dest); public abstract void zero(Matrix4x3f dest); public abstract void zero(Matrix3f dest); public abstract void zero(Vector4f dest); public abstract void zero(Vector4i dest); public abstract void putMatrix3f(Quaternionf q, int position, ByteBuffer dest); public abstract void putMatrix3f(Quaternionf q, int position, FloatBuffer dest); public abstract void putMatrix4f(Quaternionf q, int position, ByteBuffer dest); public abstract void putMatrix4f(Quaternionf q, int position, FloatBuffer dest); public abstract void putMatrix4x3f(Quaternionf q, int position, ByteBuffer dest); public abstract void putMatrix4x3f(Quaternionf q, int position, FloatBuffer dest); public abstract void set(Matrix4f dest, Vector4f col0, Vector4f col1, Vector4f col2, Vector4f col3); public abstract void set(Matrix4x3f dest, Vector3f col0, Vector3f col1, Vector3f col2, Vector3f col3); public abstract void set(Matrix3f dest, Vector3f col0, Vector3f col1, Vector3f col2); public abstract void putColumn0(Matrix4f src, Vector4f dest); public abstract void putColumn1(Matrix4f src, Vector4f dest); public abstract void putColumn2(Matrix4f src, Vector4f dest); public abstract void putColumn3(Matrix4f src, Vector4f dest); public abstract void getColumn0(Matrix4f dest, Vector4f src); public abstract void getColumn1(Matrix4f dest, Vector4f src); public abstract void getColumn2(Matrix4f dest, Vector4f src); public abstract void getColumn3(Matrix4f dest, Vector4f src); public abstract void broadcast(float c, Vector4f dest); public abstract void broadcast(int c, Vector4i dest); public static final class MemUtilNIO extends MemUtil { public MemUtilUnsafe UNSAFE() { return null; } private void put0(Matrix4f m, FloatBuffer dest) { dest.put(0, m.m00); dest.put(1, m.m01); dest.put(2, m.m02); dest.put(3, m.m03); dest.put(4, m.m10); dest.put(5, m.m11); dest.put(6, m.m12); dest.put(7, m.m13); dest.put(8, m.m20); dest.put(9, m.m21); dest.put(10, m.m22); dest.put(11, m.m23); dest.put(12, m.m30); dest.put(13, m.m31); dest.put(14, m.m32); dest.put(15, m.m33); } private void putN(Matrix4f m, int offset, FloatBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m01); dest.put(offset+2, m.m02); dest.put(offset+3, m.m03); dest.put(offset+4, m.m10); dest.put(offset+5, m.m11); dest.put(offset+6, m.m12); dest.put(offset+7, m.m13); dest.put(offset+8, m.m20); dest.put(offset+9, m.m21); dest.put(offset+10, m.m22); dest.put(offset+11, m.m23); dest.put(offset+12, m.m30); dest.put(offset+13, m.m31); dest.put(offset+14, m.m32); dest.put(offset+15, m.m33); } public void put(Matrix4f m, int offset, FloatBuffer dest) { if (offset == 0) put0(m, dest); else putN(m, offset, dest); } private void put0(Matrix4f m, ByteBuffer dest) { dest.putFloat(0, m.m00); dest.putFloat(4, m.m01); dest.putFloat(8, m.m02); dest.putFloat(12, m.m03); dest.putFloat(16, m.m10); dest.putFloat(20, m.m11); dest.putFloat(24, m.m12); dest.putFloat(28, m.m13); dest.putFloat(32, m.m20); dest.putFloat(36, m.m21); dest.putFloat(40, m.m22); dest.putFloat(44, m.m23); dest.putFloat(48, m.m30); dest.putFloat(52, m.m31); dest.putFloat(56, m.m32); dest.putFloat(60, m.m33); } private final void putN(Matrix4f m, int offset, ByteBuffer dest) { dest.putFloat(offset, m.m00); dest.putFloat(offset+4, m.m01); dest.putFloat(offset+8, m.m02); dest.putFloat(offset+12, m.m03); dest.putFloat(offset+16, m.m10); dest.putFloat(offset+20, m.m11); dest.putFloat(offset+24, m.m12); dest.putFloat(offset+28, m.m13); dest.putFloat(offset+32, m.m20); dest.putFloat(offset+36, m.m21); dest.putFloat(offset+40, m.m22); dest.putFloat(offset+44, m.m23); dest.putFloat(offset+48, m.m30); dest.putFloat(offset+52, m.m31); dest.putFloat(offset+56, m.m32); dest.putFloat(offset+60, m.m33); } public void put(Matrix4f m, int offset, ByteBuffer dest) { if (offset == 0) put0(m, dest); else putN(m, offset, dest); } private void put0(Matrix4x3f m, FloatBuffer dest) { dest.put(0, m.m00); dest.put(1, m.m01); dest.put(2, m.m02); dest.put(3, m.m10); dest.put(4, m.m11); dest.put(5, m.m12); dest.put(6, m.m20); dest.put(7, m.m21); dest.put(8, m.m22); dest.put(9, m.m30); dest.put(10, m.m31); dest.put(11, m.m32); } private void putN(Matrix4x3f m, int offset, FloatBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m01); dest.put(offset+2, m.m02); dest.put(offset+3, m.m10); dest.put(offset+4, m.m11); dest.put(offset+5, m.m12); dest.put(offset+6, m.m20); dest.put(offset+7, m.m21); dest.put(offset+8, m.m22); dest.put(offset+9, m.m30); dest.put(offset+10, m.m31); dest.put(offset+11, m.m32); } public void put(Matrix4x3f m, int offset, FloatBuffer dest) { if (offset == 0) put0(m, dest); else putN(m, offset, dest); } private void put0(Matrix4x3f m, ByteBuffer dest) { dest.putFloat(0, m.m00); dest.putFloat(4, m.m01); dest.putFloat(8, m.m02); dest.putFloat(12, m.m10); dest.putFloat(16, m.m11); dest.putFloat(20, m.m12); dest.putFloat(24, m.m20); dest.putFloat(28, m.m21); dest.putFloat(32, m.m22); dest.putFloat(36, m.m30); dest.putFloat(40, m.m31); dest.putFloat(44, m.m32); } private void putN(Matrix4x3f m, int offset, ByteBuffer dest) { dest.putFloat(offset, m.m00); dest.putFloat(offset+4, m.m01); dest.putFloat(offset+8, m.m02); dest.putFloat(offset+12, m.m10); dest.putFloat(offset+16, m.m11); dest.putFloat(offset+20, m.m12); dest.putFloat(offset+24, m.m20); dest.putFloat(offset+28, m.m21); dest.putFloat(offset+32, m.m22); dest.putFloat(offset+36, m.m30); dest.putFloat(offset+40, m.m31); dest.putFloat(offset+44, m.m32); } public void put(Matrix4x3f m, int offset, ByteBuffer dest) { if (offset == 0) put0(m, dest); else putN(m, offset, dest); } public final void put4x4(Matrix4x3f m, int offset, FloatBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m01); dest.put(offset+2, m.m02); dest.put(offset+3, 0.0f); dest.put(offset+4, m.m10); dest.put(offset+5, m.m11); dest.put(offset+6, m.m12); dest.put(offset+7, 0.0f); dest.put(offset+8, m.m20); dest.put(offset+9, m.m21); dest.put(offset+10, m.m22); dest.put(offset+11, 0.0f); dest.put(offset+12, m.m30); dest.put(offset+13, m.m31); dest.put(offset+14, m.m32); dest.put(offset+15, 1.0f); } public final void put4x4(Matrix4x3f m, int offset, ByteBuffer dest) { dest.putFloat(offset, m.m00); dest.putFloat(offset+4, m.m01); dest.putFloat(offset+8, m.m02); dest.putFloat(offset+12, 0.0f); dest.putFloat(offset+16, m.m10); dest.putFloat(offset+20, m.m11); dest.putFloat(offset+24, m.m12); dest.putFloat(offset+28, 0.0f); dest.putFloat(offset+32, m.m20); dest.putFloat(offset+36, m.m21); dest.putFloat(offset+40, m.m22); dest.putFloat(offset+44, 0.0f); dest.putFloat(offset+48, m.m30); dest.putFloat(offset+52, m.m31); dest.putFloat(offset+56, m.m32); dest.putFloat(offset+60, 1.0f); } public final void put4x4(Matrix4x3d m, int offset, DoubleBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m01); dest.put(offset+2, m.m02); dest.put(offset+3, 0.0); dest.put(offset+4, m.m10); dest.put(offset+5, m.m11); dest.put(offset+6, m.m12); dest.put(offset+7, 0.0); dest.put(offset+8, m.m20); dest.put(offset+9, m.m21); dest.put(offset+10, m.m22); dest.put(offset+11, 0.0); dest.put(offset+12, m.m30); dest.put(offset+13, m.m31); dest.put(offset+14, m.m32); dest.put(offset+15, 1.0); } public final void put4x4(Matrix4x3d m, int offset, ByteBuffer dest) { dest.putDouble(offset, m.m00); dest.putDouble(offset+4, m.m01); dest.putDouble(offset+8, m.m02); dest.putDouble(offset+12, 0.0); dest.putDouble(offset+16, m.m10); dest.putDouble(offset+20, m.m11); dest.putDouble(offset+24, m.m12); dest.putDouble(offset+28, 0.0); dest.putDouble(offset+32, m.m20); dest.putDouble(offset+36, m.m21); dest.putDouble(offset+40, m.m22); dest.putDouble(offset+44, 0.0); dest.putDouble(offset+48, m.m30); dest.putDouble(offset+52, m.m31); dest.putDouble(offset+56, m.m32); dest.putDouble(offset+60, 1.0); } public final void putTransposed(Matrix4f m, int offset, FloatBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m10); dest.put(offset+2, m.m20); dest.put(offset+3, m.m30); dest.put(offset+4, m.m01); dest.put(offset+5, m.m11); dest.put(offset+6, m.m21); dest.put(offset+7, m.m31); dest.put(offset+8, m.m02); dest.put(offset+9, m.m12); dest.put(offset+10, m.m22); dest.put(offset+11, m.m32); dest.put(offset+12, m.m03); dest.put(offset+13, m.m13); dest.put(offset+14, m.m23); dest.put(offset+15, m.m33); } public final void putTransposed(Matrix4f m, int offset, ByteBuffer dest) { dest.putFloat(offset, m.m00); dest.putFloat(offset+4, m.m10); dest.putFloat(offset+8, m.m20); dest.putFloat(offset+12, m.m30); dest.putFloat(offset+16, m.m01); dest.putFloat(offset+20, m.m11); dest.putFloat(offset+24, m.m21); dest.putFloat(offset+28, m.m31); dest.putFloat(offset+32, m.m02); dest.putFloat(offset+36, m.m12); dest.putFloat(offset+40, m.m22); dest.putFloat(offset+44, m.m32); dest.putFloat(offset+48, m.m03); dest.putFloat(offset+52, m.m13); dest.putFloat(offset+56, m.m23); dest.putFloat(offset+60, m.m33); } public final void put4x3Transposed(Matrix4f m, int offset, FloatBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m10); dest.put(offset+2, m.m20); dest.put(offset+3, m.m30); dest.put(offset+4, m.m01); dest.put(offset+5, m.m11); dest.put(offset+6, m.m21); dest.put(offset+7, m.m31); dest.put(offset+8, m.m02); dest.put(offset+9, m.m12); dest.put(offset+10, m.m22); dest.put(offset+11, m.m32); } public final void put4x3Transposed(Matrix4f m, int offset, ByteBuffer dest) { dest.putFloat(offset, m.m00); dest.putFloat(offset+4, m.m10); dest.putFloat(offset+8, m.m20); dest.putFloat(offset+12, m.m30); dest.putFloat(offset+16, m.m01); dest.putFloat(offset+20, m.m11); dest.putFloat(offset+24, m.m21); dest.putFloat(offset+28, m.m31); dest.putFloat(offset+32, m.m02); dest.putFloat(offset+36, m.m12); dest.putFloat(offset+40, m.m22); dest.putFloat(offset+44, m.m32); } public final void putTransposed(Matrix4x3f m, int offset, FloatBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m10); dest.put(offset+2, m.m20); dest.put(offset+3, m.m30); dest.put(offset+4, m.m01); dest.put(offset+5, m.m11); dest.put(offset+6, m.m21); dest.put(offset+7, m.m31); dest.put(offset+8, m.m02); dest.put(offset+9, m.m12); dest.put(offset+10, m.m22); dest.put(offset+11, m.m32); } public final void putTransposed(Matrix4x3f m, int offset, ByteBuffer dest) { dest.putFloat(offset, m.m00); dest.putFloat(offset+4, m.m10); dest.putFloat(offset+8, m.m20); dest.putFloat(offset+12, m.m30); dest.putFloat(offset+16, m.m01); dest.putFloat(offset+20, m.m11); dest.putFloat(offset+24, m.m21); dest.putFloat(offset+28, m.m31); dest.putFloat(offset+32, m.m02); dest.putFloat(offset+36, m.m12); dest.putFloat(offset+40, m.m22); dest.putFloat(offset+44, m.m32); } public final void putTransposed(Matrix3f m, int offset, FloatBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m10); dest.put(offset+2, m.m20); dest.put(offset+3, m.m01); dest.put(offset+4, m.m11); dest.put(offset+5, m.m21); dest.put(offset+6, m.m02); dest.put(offset+7, m.m12); dest.put(offset+8, m.m22); } public final void putTransposed(Matrix3f m, int offset, ByteBuffer dest) { dest.putFloat(offset, m.m00); dest.putFloat(offset+4, m.m10); dest.putFloat(offset+8, m.m20); dest.putFloat(offset+12, m.m01); dest.putFloat(offset+16, m.m11); dest.putFloat(offset+20, m.m21); dest.putFloat(offset+24, m.m02); dest.putFloat(offset+28, m.m12); dest.putFloat(offset+32, m.m22); } public final void put(Matrix4d m, int offset, DoubleBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m01); dest.put(offset+2, m.m02); dest.put(offset+3, m.m03); dest.put(offset+4, m.m10); dest.put(offset+5, m.m11); dest.put(offset+6, m.m12); dest.put(offset+7, m.m13); dest.put(offset+8, m.m20); dest.put(offset+9, m.m21); dest.put(offset+10, m.m22); dest.put(offset+11, m.m23); dest.put(offset+12, m.m30); dest.put(offset+13, m.m31); dest.put(offset+14, m.m32); dest.put(offset+15, m.m33); } public final void put(Matrix4d m, int offset, ByteBuffer dest) { dest.putDouble(offset, m.m00); dest.putDouble(offset+4, m.m01); dest.putDouble(offset+8, m.m02); dest.putDouble(offset+12, m.m03); dest.putDouble(offset+16, m.m10); dest.putDouble(offset+20, m.m11); dest.putDouble(offset+24, m.m12); dest.putDouble(offset+28, m.m13); dest.putDouble(offset+32, m.m20); dest.putDouble(offset+36, m.m21); dest.putDouble(offset+40, m.m22); dest.putDouble(offset+44, m.m23); dest.putDouble(offset+48, m.m30); dest.putDouble(offset+52, m.m31); dest.putDouble(offset+56, m.m32); dest.putDouble(offset+60, m.m33); } public final void put(Matrix4x3d m, int offset, DoubleBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m01); dest.put(offset+2, m.m02); dest.put(offset+3, m.m10); dest.put(offset+4, m.m11); dest.put(offset+5, m.m12); dest.put(offset+6, m.m20); dest.put(offset+7, m.m21); dest.put(offset+8, m.m22); dest.put(offset+9, m.m30); dest.put(offset+10, m.m31); dest.put(offset+11, m.m32); } public final void put(Matrix4x3d m, int offset, ByteBuffer dest) { dest.putDouble(offset, m.m00); dest.putDouble(offset+4, m.m01); dest.putDouble(offset+8, m.m02); dest.putDouble(offset+12, m.m10); dest.putDouble(offset+16, m.m11); dest.putDouble(offset+20, m.m12); dest.putDouble(offset+24, m.m20); dest.putDouble(offset+28, m.m21); dest.putDouble(offset+32, m.m22); dest.putDouble(offset+36, m.m30); dest.putDouble(offset+40, m.m31); dest.putDouble(offset+44, m.m32); } public final void putf(Matrix4d m, int offset, FloatBuffer dest) { dest.put(offset, (float)m.m00); dest.put(offset+1, (float)m.m01); dest.put(offset+2, (float)m.m02); dest.put(offset+3, (float)m.m03); dest.put(offset+4, (float)m.m10); dest.put(offset+5, (float)m.m11); dest.put(offset+6, (float)m.m12); dest.put(offset+7, (float)m.m13); dest.put(offset+8, (float)m.m20); dest.put(offset+9, (float)m.m21); dest.put(offset+10, (float)m.m22); dest.put(offset+11, (float)m.m23); dest.put(offset+12, (float)m.m30); dest.put(offset+13, (float)m.m31); dest.put(offset+14, (float)m.m32); dest.put(offset+15, (float)m.m33); } public final void putf(Matrix4d m, int offset, ByteBuffer dest) { dest.putFloat(offset, (float)m.m00); dest.putFloat(offset+4, (float)m.m01); dest.putFloat(offset+8, (float)m.m02); dest.putFloat(offset+12, (float)m.m03); dest.putFloat(offset+16, (float)m.m10); dest.putFloat(offset+20, (float)m.m11); dest.putFloat(offset+24, (float)m.m12); dest.putFloat(offset+28, (float)m.m13); dest.putFloat(offset+32, (float)m.m20); dest.putFloat(offset+36, (float)m.m21); dest.putFloat(offset+40, (float)m.m22); dest.putFloat(offset+44, (float)m.m23); dest.putFloat(offset+48, (float)m.m30); dest.putFloat(offset+52, (float)m.m31); dest.putFloat(offset+56, (float)m.m32); dest.putFloat(offset+60, (float)m.m33); } public final void putf(Matrix4x3d m, int offset, FloatBuffer dest) { dest.put(offset, (float)m.m00); dest.put(offset+1, (float)m.m01); dest.put(offset+2, (float)m.m02); dest.put(offset+3, (float)m.m10); dest.put(offset+4, (float)m.m11); dest.put(offset+5, (float)m.m12); dest.put(offset+6, (float)m.m20); dest.put(offset+7, (float)m.m21); dest.put(offset+8, (float)m.m22); dest.put(offset+9, (float)m.m30); dest.put(offset+10, (float)m.m31); dest.put(offset+11, (float)m.m32); } public final void putf(Matrix4x3d m, int offset, ByteBuffer dest) { dest.putFloat(offset, (float)m.m00); dest.putFloat(offset+4, (float)m.m01); dest.putFloat(offset+8, (float)m.m02); dest.putFloat(offset+12, (float)m.m10); dest.putFloat(offset+16, (float)m.m11); dest.putFloat(offset+20, (float)m.m12); dest.putFloat(offset+24, (float)m.m20); dest.putFloat(offset+28, (float)m.m21); dest.putFloat(offset+32, (float)m.m22); dest.putFloat(offset+36, (float)m.m30); dest.putFloat(offset+40, (float)m.m31); dest.putFloat(offset+44, (float)m.m32); } public final void putTransposed(Matrix4d m, int offset, DoubleBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m10); dest.put(offset+2, m.m20); dest.put(offset+3, m.m30); dest.put(offset+4, m.m01); dest.put(offset+5, m.m11); dest.put(offset+6, m.m21); dest.put(offset+7, m.m31); dest.put(offset+8, m.m02); dest.put(offset+9, m.m12); dest.put(offset+10, m.m22); dest.put(offset+11, m.m32); dest.put(offset+12, m.m03); dest.put(offset+13, m.m13); dest.put(offset+14, m.m23); dest.put(offset+15, m.m33); } public final void putTransposed(Matrix4d m, int offset, ByteBuffer dest) { dest.putDouble(offset, m.m00); dest.putDouble(offset+8, m.m10); dest.putDouble(offset+16, m.m20); dest.putDouble(offset+24, m.m30); dest.putDouble(offset+32, m.m01); dest.putDouble(offset+40, m.m11); dest.putDouble(offset+48, m.m21); dest.putDouble(offset+56, m.m31); dest.putDouble(offset+64, m.m02); dest.putDouble(offset+72, m.m12); dest.putDouble(offset+80, m.m22); dest.putDouble(offset+88, m.m32); dest.putDouble(offset+96, m.m03); dest.putDouble(offset+104, m.m13); dest.putDouble(offset+112, m.m23); dest.putDouble(offset+120, m.m33); } public final void put4x3Transposed(Matrix4d m, int offset, DoubleBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m10); dest.put(offset+2, m.m20); dest.put(offset+3, m.m30); dest.put(offset+4, m.m01); dest.put(offset+5, m.m11); dest.put(offset+6, m.m21); dest.put(offset+7, m.m31); dest.put(offset+8, m.m02); dest.put(offset+9, m.m12); dest.put(offset+10, m.m22); dest.put(offset+11, m.m32); } public final void put4x3Transposed(Matrix4d m, int offset, ByteBuffer dest) { dest.putDouble(offset, m.m00); dest.putDouble(offset+8, m.m10); dest.putDouble(offset+16, m.m20); dest.putDouble(offset+24, m.m30); dest.putDouble(offset+32, m.m01); dest.putDouble(offset+40, m.m11); dest.putDouble(offset+48, m.m21); dest.putDouble(offset+56, m.m31); dest.putDouble(offset+64, m.m02); dest.putDouble(offset+72, m.m12); dest.putDouble(offset+80, m.m22); dest.putDouble(offset+88, m.m32); } public final void putTransposed(Matrix4x3d m, int offset, DoubleBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m10); dest.put(offset+2, m.m20); dest.put(offset+3, m.m30); dest.put(offset+4, m.m01); dest.put(offset+5, m.m11); dest.put(offset+6, m.m21); dest.put(offset+7, m.m31); dest.put(offset+8, m.m02); dest.put(offset+9, m.m12); dest.put(offset+10, m.m22); dest.put(offset+11, m.m32); } public final void putTransposed(Matrix4x3d m, int offset, ByteBuffer dest) { dest.putDouble(offset, m.m00); dest.putDouble(offset+4, m.m10); dest.putDouble(offset+8, m.m20); dest.putDouble(offset+12, m.m30); dest.putDouble(offset+16, m.m01); dest.putDouble(offset+20, m.m11); dest.putDouble(offset+24, m.m21); dest.putDouble(offset+28, m.m31); dest.putDouble(offset+32, m.m02); dest.putDouble(offset+36, m.m12); dest.putDouble(offset+40, m.m22); dest.putDouble(offset+44, m.m32); } public final void putfTransposed(Matrix4x3d m, int offset, FloatBuffer dest) { dest.put(offset, (float)m.m00); dest.put(offset+1, (float)m.m10); dest.put(offset+2, (float)m.m20); dest.put(offset+3, (float)m.m30); dest.put(offset+4, (float)m.m01); dest.put(offset+5, (float)m.m11); dest.put(offset+6, (float)m.m21); dest.put(offset+7, (float)m.m31); dest.put(offset+8, (float)m.m02); dest.put(offset+9, (float)m.m12); dest.put(offset+10, (float)m.m22); dest.put(offset+11, (float)m.m32); } public final void putfTransposed(Matrix4x3d m, int offset, ByteBuffer dest) { dest.putFloat(offset, (float)m.m00); dest.putFloat(offset+4, (float)m.m10); dest.putFloat(offset+8, (float)m.m20); dest.putFloat(offset+12, (float)m.m30); dest.putFloat(offset+16, (float)m.m01); dest.putFloat(offset+20, (float)m.m11); dest.putFloat(offset+24, (float)m.m21); dest.putFloat(offset+28, (float)m.m31); dest.putFloat(offset+32, (float)m.m02); dest.putFloat(offset+36, (float)m.m12); dest.putFloat(offset+40, (float)m.m22); dest.putFloat(offset+44, (float)m.m32); } public final void putfTransposed(Matrix4d m, int offset, FloatBuffer dest) { dest.put(offset, (float)m.m00); dest.put(offset+1, (float)m.m10); dest.put(offset+2, (float)m.m20); dest.put(offset+3, (float)m.m30); dest.put(offset+4, (float)m.m01); dest.put(offset+5, (float)m.m11); dest.put(offset+6, (float)m.m21); dest.put(offset+7, (float)m.m31); dest.put(offset+8, (float)m.m02); dest.put(offset+9, (float)m.m12); dest.put(offset+10, (float)m.m22); dest.put(offset+11, (float)m.m32); dest.put(offset+12, (float)m.m03); dest.put(offset+13, (float)m.m13); dest.put(offset+14, (float)m.m23); dest.put(offset+15, (float)m.m33); } public final void putfTransposed(Matrix4d m, int offset, ByteBuffer dest) { dest.putFloat(offset, (float)m.m00); dest.putFloat(offset+4, (float)m.m10); dest.putFloat(offset+8, (float)m.m20); dest.putFloat(offset+12, (float)m.m30); dest.putFloat(offset+16, (float)m.m01); dest.putFloat(offset+20, (float)m.m11); dest.putFloat(offset+24, (float)m.m21); dest.putFloat(offset+28, (float)m.m31); dest.putFloat(offset+32, (float)m.m02); dest.putFloat(offset+36, (float)m.m12); dest.putFloat(offset+40, (float)m.m22); dest.putFloat(offset+44, (float)m.m32); dest.putFloat(offset+48, (float)m.m03); dest.putFloat(offset+52, (float)m.m13); dest.putFloat(offset+56, (float)m.m23); dest.putFloat(offset+60, (float)m.m33); } public final void put(Matrix3f m, int offset, FloatBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m01); dest.put(offset+2, m.m02); dest.put(offset+3, m.m10); dest.put(offset+4, m.m11); dest.put(offset+5, m.m12); dest.put(offset+6, m.m20); dest.put(offset+7, m.m21); dest.put(offset+8, m.m22); } public final void put(Matrix3f m, int offset, ByteBuffer dest) { dest.putFloat(offset, m.m00); dest.putFloat(offset+4, m.m01); dest.putFloat(offset+8, m.m02); dest.putFloat(offset+12, m.m10); dest.putFloat(offset+16, m.m11); dest.putFloat(offset+20, m.m12); dest.putFloat(offset+24, m.m20); dest.putFloat(offset+28, m.m21); dest.putFloat(offset+32, m.m22); } public final void put(Matrix3d m, int offset, DoubleBuffer dest) { dest.put(offset, m.m00); dest.put(offset+1, m.m01); dest.put(offset+2, m.m02); dest.put(offset+3, m.m10); dest.put(offset+4, m.m11); dest.put(offset+5, m.m12); dest.put(offset+6, m.m20); dest.put(offset+7, m.m21); dest.put(offset+8, m.m22); } public final void put(Matrix3d m, int offset, ByteBuffer dest) { dest.putDouble(offset, m.m00); dest.putDouble(offset+8, m.m01); dest.putDouble(offset+16, m.m02); dest.putDouble(offset+24, m.m10); dest.putDouble(offset+32, m.m11); dest.putDouble(offset+40, m.m12); dest.putDouble(offset+48, m.m20); dest.putDouble(offset+56, m.m21); dest.putDouble(offset+64, m.m22); } public final void putf(Matrix3d m, int offset, FloatBuffer dest) { dest.put(offset, (float)m.m00); dest.put(offset+1, (float)m.m01); dest.put(offset+2, (float)m.m02); dest.put(offset+3, (float)m.m10); dest.put(offset+4, (float)m.m11); dest.put(offset+5, (float)m.m12); dest.put(offset+6, (float)m.m20); dest.put(offset+7, (float)m.m21); dest.put(offset+8, (float)m.m22); } public final void putf(Matrix3d m, int offset, ByteBuffer dest) { dest.putFloat(offset, (float)m.m00); dest.putFloat(offset+4, (float)m.m01); dest.putFloat(offset+8, (float)m.m02); dest.putFloat(offset+12, (float)m.m10); dest.putFloat(offset+16, (float)m.m11); dest.putFloat(offset+20, (float)m.m12); dest.putFloat(offset+24, (float)m.m20); dest.putFloat(offset+28, (float)m.m21); dest.putFloat(offset+32, (float)m.m22); } public final void put(Vector4d src, int offset, DoubleBuffer dest) { dest.put(offset, src.x); dest.put(offset+1, src.y); dest.put(offset+2, src.z); dest.put(offset+3, src.w); } public final void put(Vector4d src, int offset, ByteBuffer dest) { dest.putDouble(offset, src.x); dest.putDouble(offset+8, src.y); dest.putDouble(offset+16, src.z); dest.putDouble(offset+24, src.w); } public final void put(Vector4f src, int offset, FloatBuffer dest) { dest.put(offset, src.x); dest.put(offset+1, src.y); dest.put(offset+2, src.z); dest.put(offset+3, src.w); } public final void put(Vector4f src, int offset, ByteBuffer dest) { dest.putFloat(offset, src.x); dest.putFloat(offset+4, src.y); dest.putFloat(offset+8, src.z); dest.putFloat(offset+12, src.w); } public final void put(Vector4i src, int offset, IntBuffer dest) { dest.put(offset, src.x); dest.put(offset+1, src.y); dest.put(offset+2, src.z); dest.put(offset+3, src.w); } public final void put(Vector4i src, int offset, ByteBuffer dest) { dest.putInt(offset, src.x); dest.putInt(offset+4, src.y); dest.putInt(offset+8, src.z); dest.putInt(offset+12, src.w); } public final void put(Vector3f src, int offset, FloatBuffer dest) { dest.put(offset, src.x); dest.put(offset+1, src.y); dest.put(offset+2, src.z); } public final void put(Vector3f src, int offset, ByteBuffer dest) { dest.putFloat(offset, src.x); dest.putFloat(offset+4, src.y); dest.putFloat(offset+8, src.z); } public final void put(Vector3d src, int offset, DoubleBuffer dest) { dest.put(offset, src.x); dest.put(offset+1, src.y); dest.put(offset+2, src.z); } public final void put(Vector3d src, int offset, ByteBuffer dest) { dest.putDouble(offset, src.x); dest.putDouble(offset+8, src.y); dest.putDouble(offset+16, src.z); } public final void put(Vector3i src, int offset, IntBuffer dest) { dest.put(offset, src.x); dest.put(offset+1, src.y); dest.put(offset+2, src.z); } public final void put(Vector3i src, int offset, ByteBuffer dest) { dest.putInt(offset, src.x); dest.putInt(offset+4, src.y); dest.putInt(offset+8, src.z); } public final void put(Vector2f src, int offset, FloatBuffer dest) { dest.put(offset, src.x); dest.put(offset+1, src.y); } public final void put(Vector2f src, int offset, ByteBuffer dest) { dest.putFloat(offset, src.x); dest.putFloat(offset+4, src.y); } public final void put(Vector2d src, int offset, DoubleBuffer dest) { dest.put(offset, src.x); dest.put(offset+1, src.y); } public final void put(Vector2d src, int offset, ByteBuffer dest) { dest.putDouble(offset, src.x); dest.putDouble(offset+8, src.y); } public final void put(Vector2i src, int offset, IntBuffer dest) { dest.put(offset, src.x); dest.put(offset+1, src.y); } public final void put(Vector2i src, int offset, ByteBuffer dest) { dest.putInt(offset, src.x); dest.putInt(offset+4, src.y); } public final void get(Matrix4f m, int offset, FloatBuffer src) { m.m00 = src.get(offset); m.m01 = src.get(offset+1); m.m02 = src.get(offset+2); m.m03 = src.get(offset+3); m.m10 = src.get(offset+4); m.m11 = src.get(offset+5); m.m12 = src.get(offset+6); m.m13 = src.get(offset+7); m.m20 = src.get(offset+8); m.m21 = src.get(offset+9); m.m22 = src.get(offset+10); m.m23 = src.get(offset+11); m.m30 = src.get(offset+12); m.m31 = src.get(offset+13); m.m32 = src.get(offset+14); m.m33 = src.get(offset+15); } public final void get(Matrix4f m, int offset, ByteBuffer src) { m.m00 = src.getFloat(offset); m.m01 = src.getFloat(offset+4); m.m02 = src.getFloat(offset+8); m.m03 = src.getFloat(offset+12); m.m10 = src.getFloat(offset+16); m.m11 = src.getFloat(offset+20); m.m12 = src.getFloat(offset+24); m.m13 = src.getFloat(offset+28); m.m20 = src.getFloat(offset+32); m.m21 = src.getFloat(offset+36); m.m22 = src.getFloat(offset+40); m.m23 = src.getFloat(offset+44); m.m30 = src.getFloat(offset+48); m.m31 = src.getFloat(offset+52); m.m32 = src.getFloat(offset+56); m.m33 = src.getFloat(offset+60); } public final void get(Matrix4x3f m, int offset, FloatBuffer src) { m.m00 = src.get(offset); m.m01 = src.get(offset+1); m.m02 = src.get(offset+2); m.m10 = src.get(offset+3); m.m11 = src.get(offset+4); m.m12 = src.get(offset+5); m.m20 = src.get(offset+6); m.m21 = src.get(offset+7); m.m22 = src.get(offset+8); m.m30 = src.get(offset+9); m.m31 = src.get(offset+10); m.m32 = src.get(offset+11); } public final void get(Matrix4x3f m, int offset, ByteBuffer src) { m.m00 = src.getFloat(offset); m.m01 = src.getFloat(offset+4); m.m02 = src.getFloat(offset+8); m.m10 = src.getFloat(offset+12); m.m11 = src.getFloat(offset+16); m.m12 = src.getFloat(offset+20); m.m20 = src.getFloat(offset+24); m.m21 = src.getFloat(offset+28); m.m22 = src.getFloat(offset+32); m.m30 = src.getFloat(offset+36); m.m31 = src.getFloat(offset+40); m.m32 = src.getFloat(offset+44); } public final void get(Matrix4d m, int offset, DoubleBuffer src) { m.m00 = src.get(offset); m.m01 = src.get(offset+1); m.m02 = src.get(offset+2); m.m03 = src.get(offset+3); m.m10 = src.get(offset+4); m.m11 = src.get(offset+5); m.m12 = src.get(offset+6); m.m13 = src.get(offset+7); m.m20 = src.get(offset+8); m.m21 = src.get(offset+9); m.m22 = src.get(offset+10); m.m23 = src.get(offset+11); m.m30 = src.get(offset+12); m.m31 = src.get(offset+13); m.m32 = src.get(offset+14); m.m33 = src.get(offset+15); } public final void get(Matrix4d m, int offset, ByteBuffer src) { m.m00 = src.getDouble(offset); m.m01 = src.getDouble(offset+8); m.m02 = src.getDouble(offset+16); m.m03 = src.getDouble(offset+24); m.m10 = src.getDouble(offset+32); m.m11 = src.getDouble(offset+40); m.m12 = src.getDouble(offset+48); m.m13 = src.getDouble(offset+56); m.m20 = src.getDouble(offset+64); m.m21 = src.getDouble(offset+72); m.m22 = src.getDouble(offset+80); m.m23 = src.getDouble(offset+88); m.m30 = src.getDouble(offset+96); m.m31 = src.getDouble(offset+104); m.m32 = src.getDouble(offset+112); m.m33 = src.getDouble(offset+120); } public final void get(Matrix4x3d m, int offset, DoubleBuffer src) { m.m00 = src.get(offset); m.m01 = src.get(offset+1); m.m02 = src.get(offset+2); m.m10 = src.get(offset+3); m.m11 = src.get(offset+4); m.m12 = src.get(offset+5); m.m20 = src.get(offset+6); m.m21 = src.get(offset+7); m.m22 = src.get(offset+8); m.m30 = src.get(offset+9); m.m31 = src.get(offset+10); m.m32 = src.get(offset+11); } public final void get(Matrix4x3d m, int offset, ByteBuffer src) { m.m00 = src.getDouble(offset); m.m01 = src.getDouble(offset+8); m.m02 = src.getDouble(offset+16); m.m10 = src.getDouble(offset+24); m.m11 = src.getDouble(offset+32); m.m12 = src.getDouble(offset+40); m.m20 = src.getDouble(offset+48); m.m21 = src.getDouble(offset+56); m.m22 = src.getDouble(offset+64); m.m30 = src.getDouble(offset+72); m.m31 = src.getDouble(offset+80); m.m32 = src.getDouble(offset+88); } public final void getf(Matrix4d m, int offset, FloatBuffer src) { m.m00 = src.get(offset); m.m01 = src.get(offset+1); m.m02 = src.get(offset+2); m.m03 = src.get(offset+3); m.m10 = src.get(offset+4); m.m11 = src.get(offset+5); m.m12 = src.get(offset+6); m.m13 = src.get(offset+7); m.m20 = src.get(offset+8); m.m21 = src.get(offset+9); m.m22 = src.get(offset+10); m.m23 = src.get(offset+11); m.m30 = src.get(offset+12); m.m31 = src.get(offset+13); m.m32 = src.get(offset+14); m.m33 = src.get(offset+15); } public final void getf(Matrix4d m, int offset, ByteBuffer src) { m.m00 = src.getFloat(offset); m.m01 = src.getFloat(offset+4); m.m02 = src.getFloat(offset+8); m.m03 = src.getFloat(offset+12); m.m10 = src.getFloat(offset+16); m.m11 = src.getFloat(offset+20); m.m12 = src.getFloat(offset+24); m.m13 = src.getFloat(offset+28); m.m20 = src.getFloat(offset+32); m.m21 = src.getFloat(offset+36); m.m22 = src.getFloat(offset+40); m.m23 = src.getFloat(offset+44); m.m30 = src.getFloat(offset+48); m.m31 = src.getFloat(offset+52); m.m32 = src.getFloat(offset+56); m.m33 = src.getFloat(offset+60); } public final void getf(Matrix4x3d m, int offset, FloatBuffer src) { m.m00 = src.get(offset); m.m01 = src.get(offset+1); m.m02 = src.get(offset+2); m.m10 = src.get(offset+3); m.m11 = src.get(offset+4); m.m12 = src.get(offset+5); m.m20 = src.get(offset+6); m.m21 = src.get(offset+7); m.m22 = src.get(offset+8); m.m30 = src.get(offset+9); m.m31 = src.get(offset+10); m.m32 = src.get(offset+11); } public final void getf(Matrix4x3d m, int offset, ByteBuffer src) { m.m00 = src.getFloat(offset); m.m01 = src.getFloat(offset+4); m.m02 = src.getFloat(offset+8); m.m10 = src.getFloat(offset+12); m.m11 = src.getFloat(offset+16); m.m12 = src.getFloat(offset+20); m.m20 = src.getFloat(offset+24); m.m21 = src.getFloat(offset+28); m.m22 = src.getFloat(offset+32); m.m30 = src.getFloat(offset+36); m.m31 = src.getFloat(offset+40); m.m32 = src.getFloat(offset+44); } public final void get(Matrix3f m, int offset, FloatBuffer src) { m.m00 = src.get(offset); m.m01 = src.get(offset+1); m.m02 = src.get(offset+2); m.m10 = src.get(offset+3); m.m11 = src.get(offset+4); m.m12 = src.get(offset+5); m.m20 = src.get(offset+6); m.m21 = src.get(offset+7); m.m22 = src.get(offset+8); } public final void get(Matrix3f m, int offset, ByteBuffer src) { m.m00 = src.getFloat(offset); m.m01 = src.getFloat(offset+4); m.m02 = src.getFloat(offset+8); m.m10 = src.getFloat(offset+12); m.m11 = src.getFloat(offset+16); m.m12 = src.getFloat(offset+20); m.m20 = src.getFloat(offset+24); m.m21 = src.getFloat(offset+28); m.m22 = src.getFloat(offset+32); } public final void get(Matrix3d m, int offset, DoubleBuffer src) { m.m00 = src.get(offset); m.m01 = src.get(offset+1); m.m02 = src.get(offset+2); m.m10 = src.get(offset+3); m.m11 = src.get(offset+4); m.m12 = src.get(offset+5); m.m20 = src.get(offset+6); m.m21 = src.get(offset+7); m.m22 = src.get(offset+8); } public final void get(Matrix3d m, int offset, ByteBuffer src) { m.m00 = src.getDouble(offset); m.m01 = src.getDouble(offset+8); m.m02 = src.getDouble(offset+16); m.m10 = src.getDouble(offset+24); m.m11 = src.getDouble(offset+32); m.m12 = src.getDouble(offset+40); m.m20 = src.getDouble(offset+48); m.m21 = src.getDouble(offset+56); m.m22 = src.getDouble(offset+64); } public final void getf(Matrix3d m, int offset, FloatBuffer src) { m.m00 = src.get(offset); m.m01 = src.get(offset+1); m.m02 = src.get(offset+2); m.m10 = src.get(offset+3); m.m11 = src.get(offset+4); m.m12 = src.get(offset+5); m.m20 = src.get(offset+6); m.m21 = src.get(offset+7); m.m22 = src.get(offset+8); } public final void getf(Matrix3d m, int offset, ByteBuffer src) { m.m00 = src.getFloat(offset); m.m01 = src.getFloat(offset+4); m.m02 = src.getFloat(offset+8); m.m10 = src.getFloat(offset+12); m.m11 = src.getFloat(offset+16); m.m12 = src.getFloat(offset+20); m.m20 = src.getFloat(offset+24); m.m21 = src.getFloat(offset+28); m.m22 = src.getFloat(offset+32); } public final void get(Vector4d dst, int offset, DoubleBuffer src) { dst.x = src.get(offset); dst.y = src.get(offset+1); dst.z = src.get(offset+2); dst.w = src.get(offset+3); } public final void get(Vector4d dst, int offset, ByteBuffer src) { dst.x = src.getDouble(offset); dst.y = src.getDouble(offset+8); dst.z = src.getDouble(offset+16); dst.w = src.getDouble(offset+24); } public final void get(Vector4f dst, int offset, FloatBuffer src) { dst.x = src.get(offset); dst.y = src.get(offset+1); dst.z = src.get(offset+2); dst.w = src.get(offset+3); } public final void get(Vector4f dst, int offset, ByteBuffer src) { dst.x = src.getFloat(offset); dst.y = src.getFloat(offset+4); dst.z = src.getFloat(offset+8); dst.w = src.getFloat(offset+12); } public final void get(Vector4i dst, int offset, IntBuffer src) { dst.x = src.get(offset); dst.y = src.get(offset+1); dst.z = src.get(offset+2); dst.w = src.get(offset+3); } public final void get(Vector4i dst, int offset, ByteBuffer src) { dst.x = src.getInt(offset); dst.y = src.getInt(offset+4); dst.z = src.getInt(offset+8); dst.w = src.getInt(offset+12); } public final void get(Vector3f dst, int offset, FloatBuffer src) { dst.x = src.get(offset); dst.y = src.get(offset+1); dst.z = src.get(offset+2); } public final void get(Vector3f dst, int offset, ByteBuffer src) { dst.x = src.getFloat(offset); dst.y = src.getFloat(offset+4); dst.z = src.getFloat(offset+8); } public final void get(Vector3d dst, int offset, DoubleBuffer src) { dst.x = src.get(offset); dst.y = src.get(offset+1); dst.z = src.get(offset+2); } public final void get(Vector3d dst, int offset, ByteBuffer src) { dst.x = src.getDouble(offset); dst.y = src.getDouble(offset+8); dst.z = src.getDouble(offset+16); } public final void get(Vector3i dst, int offset, IntBuffer src) { dst.x = src.get(offset); dst.y = src.get(offset+1); dst.z = src.get(offset+2); } public final void get(Vector3i dst, int offset, ByteBuffer src) { dst.x = src.getInt(offset); dst.y = src.getInt(offset+4); dst.z = src.getInt(offset+8); } public final void get(Vector2f dst, int offset, FloatBuffer src) { dst.x = src.get(offset); dst.y = src.get(offset+1); } public final void get(Vector2f dst, int offset, ByteBuffer src) { dst.x = src.getFloat(offset); dst.y = src.getFloat(offset+4); } public final void get(Vector2d dst, int offset, DoubleBuffer src) { dst.x = src.get(offset); dst.y = src.get(offset+1); } public final void get(Vector2d dst, int offset, ByteBuffer src) { dst.x = src.getDouble(offset); dst.y = src.getDouble(offset+8); } public final void get(Vector2i dst, int offset, IntBuffer src) { dst.x = src.get(offset); dst.y = src.get(offset+1); } public final void get(Vector2i dst, int offset, ByteBuffer src) { dst.x = src.getInt(offset); dst.y = src.getInt(offset+4); } public final void copy(Matrix4f src, Matrix4f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m03 = src.m03; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m13 = src.m13; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; dest.m23 = src.m23; dest.m30 = src.m30; dest.m31 = src.m31; dest.m32 = src.m32; dest.m33 = src.m33; } public final void copy(Matrix3f src, Matrix4f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m03 = 0.0f; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m13 = 0.0f; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; dest.m23 = 0.0f; dest.m30 = 0.0f; dest.m31 = 0.0f; dest.m32 = 0.0f; dest.m33 = 1.0f; } public final void copy(Matrix4f src, Matrix3f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; } public final void copy(Matrix3f src, Matrix4x3f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; dest.m30 = 0.0f; dest.m31 = 0.0f; dest.m32 = 0.0f; } public final void copy3x3(Matrix4f src, Matrix4f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; } public final void copy3x3(Matrix4x3f src, Matrix4x3f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; } public final void copy3x3(Matrix3f src, Matrix4x3f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; } public final void copy3x3(Matrix3f src, Matrix4f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; } public final void copy4x3(Matrix4x3f src, Matrix4f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; dest.m30 = src.m30; dest.m31 = src.m31; dest.m32 = src.m32; } public final void copy(Vector4f src, Vector4f dst) { dst.x = src.x; dst.y = src.y; dst.z = src.z; dst.w = src.w; } public final void copy(Vector4i src, Vector4i dst) { dst.x = src.x; dst.y = src.y; dst.z = src.z; dst.w = src.w; } public final void copy(Quaternionf src, Quaternionf dst) { dst.x = src.x; dst.y = src.y; dst.z = src.z; dst.w = src.w; } public final void copy4x3(Matrix4f src, Matrix4f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; dest.m30 = src.m30; dest.m31 = src.m31; dest.m32 = src.m32; } public final void copy(Matrix4f src, Matrix4x3f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; dest.m30 = src.m30; dest.m31 = src.m31; dest.m32 = src.m32; } public final void copy(Matrix4x3f src, Matrix4f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m03 = 0.0f; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m13 = 0.0f; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; dest.m23 = 0.0f; dest.m30 = src.m30; dest.m31 = src.m31; dest.m32 = src.m32; dest.m33 = 1.0f; } public final void copy(Matrix4x3f src, Matrix4x3f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; dest.m30 = src.m30; dest.m31 = src.m31; dest.m32 = src.m32; } public final void copy(Matrix3f src, Matrix3f dest) { dest.m00 = src.m00; dest.m01 = src.m01; dest.m02 = src.m02; dest.m10 = src.m10; dest.m11 = src.m11; dest.m12 = src.m12; dest.m20 = src.m20; dest.m21 = src.m21; dest.m22 = src.m22; } public final void copy(float[] arr, int off, Matrix4f dest) { dest.m00 = arr[off+0]; dest.m01 = arr[off+1]; dest.m02 = arr[off+2]; dest.m03 = arr[off+3]; dest.m10 = arr[off+4]; dest.m11 = arr[off+5]; dest.m12 = arr[off+6]; dest.m13 = arr[off+7]; dest.m20 = arr[off+8]; dest.m21 = arr[off+9]; dest.m22 = arr[off+10]; dest.m23 = arr[off+11]; dest.m30 = arr[off+12]; dest.m31 = arr[off+13]; dest.m32 = arr[off+14]; dest.m33 = arr[off+15]; } public final void copy(float[] arr, int off, Matrix3f dest) { dest.m00 = arr[off+0]; dest.m01 = arr[off+1]; dest.m02 = arr[off+2]; dest.m10 = arr[off+3]; dest.m11 = arr[off+4]; dest.m12 = arr[off+5]; dest.m20 = arr[off+6]; dest.m21 = arr[off+7]; dest.m22 = arr[off+8]; } public final void copy(float[] arr, int off, Matrix4x3f dest) { dest.m00 = arr[off+0]; dest.m01 = arr[off+1]; dest.m02 = arr[off+2]; dest.m10 = arr[off+3]; dest.m11 = arr[off+4]; dest.m12 = arr[off+5]; dest.m20 = arr[off+6]; dest.m21 = arr[off+7]; dest.m22 = arr[off+8]; dest.m30 = arr[off+9]; dest.m31 = arr[off+10]; dest.m32 = arr[off+11]; } public final void copy(Matrix4f src, float[] dest, int off) { dest[off+0] = src.m00; dest[off+1] = src.m01; dest[off+2] = src.m02; dest[off+3] = src.m03; dest[off+4] = src.m10; dest[off+5] = src.m11; dest[off+6] = src.m12; dest[off+7] = src.m13; dest[off+8] = src.m20; dest[off+9] = src.m21; dest[off+10] = src.m22; dest[off+11] = src.m23; dest[off+12] = src.m30; dest[off+13] = src.m31; dest[off+14] = src.m32; dest[off+15] = src.m33; } public final void copy(Matrix3f src, float[] dest, int off) { dest[off+0] = src.m00; dest[off+1] = src.m01; dest[off+2] = src.m02; dest[off+3] = src.m10; dest[off+4] = src.m11; dest[off+5] = src.m12; dest[off+6] = src.m20; dest[off+7] = src.m21; dest[off+8] = src.m22; } public final void copy(Matrix4x3f src, float[] dest, int off) { dest[off+0] = src.m00; dest[off+1] = src.m01; dest[off+2] = src.m02; dest[off+3] = src.m10; dest[off+4] = src.m11; dest[off+5] = src.m12; dest[off+6] = src.m20; dest[off+7] = src.m21; dest[off+8] = src.m22; dest[off+9] = src.m30; dest[off+10] = src.m31; dest[off+11] = src.m32; } public final void identity(Matrix4f dest) { dest.m00 = 1.0f; dest.m01 = 0.0f; dest.m02 = 0.0f; dest.m03 = 0.0f; dest.m10 = 0.0f; dest.m11 = 1.0f; dest.m12 = 0.0f; dest.m13 = 0.0f; dest.m20 = 0.0f; dest.m21 = 0.0f; dest.m22 = 1.0f; dest.m23 = 0.0f; dest.m30 = 0.0f; dest.m31 = 0.0f; dest.m32 = 0.0f; dest.m33 = 1.0f; } public final void identity(Matrix4x3f dest) { dest.m00 = 1.0f; dest.m01 = 0.0f; dest.m02 = 0.0f; dest.m10 = 0.0f; dest.m11 = 1.0f; dest.m12 = 0.0f; dest.m20 = 0.0f; dest.m21 = 0.0f; dest.m22 = 1.0f; dest.m30 = 0.0f; dest.m31 = 0.0f; dest.m32 = 0.0f; } public final void identity(Matrix3f dest) { dest.m00 = 1.0f; dest.m01 = 0.0f; dest.m02 = 0.0f; dest.m10 = 0.0f; dest.m11 = 1.0f; dest.m12 = 0.0f; dest.m20 = 0.0f; dest.m21 = 0.0f; dest.m22 = 1.0f; } public final void identity(Quaternionf dest) { dest.x = 0.0f; dest.y = 0.0f; dest.z = 0.0f; dest.w = 1.0f; } public final void swap(Matrix4f m1, Matrix4f m2) { float tmp; tmp = m1.m00; m1.m00 = m2.m00; m2.m00 = tmp; tmp = m1.m01; m1.m01 = m2.m01; m2.m01 = tmp; tmp = m1.m02; m1.m02 = m2.m02; m2.m02 = tmp; tmp = m1.m03; m1.m03 = m2.m03; m2.m03 = tmp; tmp = m1.m10; m1.m10 = m2.m10; m2.m10 = tmp; tmp = m1.m11; m1.m11 = m2.m11; m2.m11 = tmp; tmp = m1.m12; m1.m12 = m2.m12; m2.m12 = tmp; tmp = m1.m13; m1.m13 = m2.m13; m2.m13 = tmp; tmp = m1.m20; m1.m20 = m2.m20; m2.m20 = tmp; tmp = m1.m21; m1.m21 = m2.m21; m2.m21 = tmp; tmp = m1.m22; m1.m22 = m2.m22; m2.m22 = tmp; tmp = m1.m23; m1.m23 = m2.m23; m2.m23 = tmp; tmp = m1.m30; m1.m30 = m2.m30; m2.m30 = tmp; tmp = m1.m31; m1.m31 = m2.m31; m2.m31 = tmp; tmp = m1.m32; m1.m32 = m2.m32; m2.m32 = tmp; tmp = m1.m33; m1.m33 = m2.m33; m2.m33 = tmp; } public final void swap(Matrix4x3f m1, Matrix4x3f m2) { float tmp; tmp = m1.m00; m1.m00 = m2.m00; m2.m00 = tmp; tmp = m1.m01; m1.m01 = m2.m01; m2.m01 = tmp; tmp = m1.m02; m1.m02 = m2.m02; m2.m02 = tmp; tmp = m1.m10; m1.m10 = m2.m10; m2.m10 = tmp; tmp = m1.m11; m1.m11 = m2.m11; m2.m11 = tmp; tmp = m1.m12; m1.m12 = m2.m12; m2.m12 = tmp; tmp = m1.m20; m1.m20 = m2.m20; m2.m20 = tmp; tmp = m1.m21; m1.m21 = m2.m21; m2.m21 = tmp; tmp = m1.m22; m1.m22 = m2.m22; m2.m22 = tmp; tmp = m1.m30; m1.m30 = m2.m30; m2.m30 = tmp; tmp = m1.m31; m1.m31 = m2.m31; m2.m31 = tmp; tmp = m1.m32; m1.m32 = m2.m32; m2.m32 = tmp; } public final void swap(Matrix3f m1, Matrix3f m2) { float tmp; tmp = m1.m00; m1.m00 = m2.m00; m2.m00 = tmp; tmp = m1.m01; m1.m01 = m2.m01; m2.m01 = tmp; tmp = m1.m02; m1.m02 = m2.m02; m2.m02 = tmp; tmp = m1.m10; m1.m10 = m2.m10; m2.m10 = tmp; tmp = m1.m11; m1.m11 = m2.m11; m2.m11 = tmp; tmp = m1.m12; m1.m12 = m2.m12; m2.m12 = tmp; tmp = m1.m20; m1.m20 = m2.m20; m2.m20 = tmp; tmp = m1.m21; m1.m21 = m2.m21; m2.m21 = tmp; tmp = m1.m22; m1.m22 = m2.m22; m2.m22 = tmp; } public final void zero(Matrix4f dest) { dest.m00 = 0.0f; dest.m01 = 0.0f; dest.m02 = 0.0f; dest.m03 = 0.0f; dest.m10 = 0.0f; dest.m11 = 0.0f; dest.m12 = 0.0f; dest.m13 = 0.0f; dest.m20 = 0.0f; dest.m21 = 0.0f; dest.m22 = 0.0f; dest.m23 = 0.0f; dest.m30 = 0.0f; dest.m31 = 0.0f; dest.m32 = 0.0f; dest.m33 = 0.0f; } public final void zero(Matrix4x3f dest) { dest.m00 = 0.0f; dest.m01 = 0.0f; dest.m02 = 0.0f; dest.m10 = 0.0f; dest.m11 = 0.0f; dest.m12 = 0.0f; dest.m20 = 0.0f; dest.m21 = 0.0f; dest.m22 = 0.0f; dest.m30 = 0.0f; dest.m31 = 0.0f; dest.m32 = 0.0f; } public final void zero(Matrix3f dest) { dest.m00 = 0.0f; dest.m01 = 0.0f; dest.m02 = 0.0f; dest.m10 = 0.0f; dest.m11 = 0.0f; dest.m12 = 0.0f; dest.m20 = 0.0f; dest.m21 = 0.0f; dest.m22 = 0.0f; } public final void zero(Vector4f dest) { dest.x = 0.0f; dest.y = 0.0f; dest.z = 0.0f; dest.w = 0.0f; } public final void zero(Vector4i dest) { dest.x = 0; dest.y = 0; dest.z = 0; dest.w = 0; } public final void putMatrix3f(Quaternionf q, int position, ByteBuffer dest) { float w2 = q.w * q.w; float x2 = q.x * q.x; float y2 = q.y * q.y; float z2 = q.z * q.z; float zw = q.z * q.w; float xy = q.x * q.y; float xz = q.x * q.z; float yw = q.y * q.w; float yz = q.y * q.z; float xw = q.x * q.w; dest.putFloat(position, w2 + x2 - z2 - y2); dest.putFloat(position + 4, xy + zw + zw + xy); dest.putFloat(position + 8, xz - yw + xz - yw); dest.putFloat(position + 12, -zw + xy - zw + xy); dest.putFloat(position + 16, y2 - z2 + w2 - x2); dest.putFloat(position + 20, yz + yz + xw + xw); dest.putFloat(position + 24, yw + xz + xz + yw); dest.putFloat(position + 28, yz + yz - xw - xw); dest.putFloat(position + 32, z2 - y2 - x2 + w2); } public final void putMatrix3f(Quaternionf q, int position, FloatBuffer dest) { float w2 = q.w * q.w; float x2 = q.x * q.x; float y2 = q.y * q.y; float z2 = q.z * q.z; float zw = q.z * q.w; float xy = q.x * q.y; float xz = q.x * q.z; float yw = q.y * q.w; float yz = q.y * q.z; float xw = q.x * q.w; dest.put(position, w2 + x2 - z2 - y2); dest.put(position + 1, xy + zw + zw + xy); dest.put(position + 2, xz - yw + xz - yw); dest.put(position + 3, -zw + xy - zw + xy); dest.put(position + 4, y2 - z2 + w2 - x2); dest.put(position + 5, yz + yz + xw + xw); dest.put(position + 6, yw + xz + xz + yw); dest.put(position + 7, yz + yz - xw - xw); dest.put(position + 8, z2 - y2 - x2 + w2); } public final void putMatrix4f(Quaternionf q, int position, ByteBuffer dest) { float w2 = q.w * q.w; float x2 = q.x * q.x; float y2 = q.y * q.y; float z2 = q.z * q.z; float zw = q.z * q.w; float xy = q.x * q.y; float xz = q.x * q.z; float yw = q.y * q.w; float yz = q.y * q.z; float xw = q.x * q.w; dest.putFloat(position, w2 + x2 - z2 - y2); dest.putFloat(position + 4, xy + zw + zw + xy); dest.putFloat(position + 8, xz - yw + xz - yw); dest.putFloat(position + 12, 0.0f); dest.putFloat(position + 16, -zw + xy - zw + xy); dest.putFloat(position + 20, y2 - z2 + w2 - x2); dest.putFloat(position + 24, yz + yz + xw + xw); dest.putFloat(position + 28, 0.0f); dest.putFloat(position + 32, yw + xz + xz + yw); dest.putFloat(position + 36, yz + yz - xw - xw); dest.putFloat(position + 40, z2 - y2 - x2 + w2); dest.putFloat(position + 44, 0.0f); dest.putLong(position + 48, 0L); dest.putLong(position + 56, 0x3F80000000000000L); } public final void putMatrix4f(Quaternionf q, int position, FloatBuffer dest) { float w2 = q.w * q.w; float x2 = q.x * q.x; float y2 = q.y * q.y; float z2 = q.z * q.z; float zw = q.z * q.w; float xy = q.x * q.y; float xz = q.x * q.z; float yw = q.y * q.w; float yz = q.y * q.z; float xw = q.x * q.w; dest.put(position, w2 + x2 - z2 - y2); dest.put(position + 1, xy + zw + zw + xy); dest.put(position + 2, xz - yw + xz - yw); dest.put(position + 3, 0.0f); dest.put(position + 4, -zw + xy - zw + xy); dest.put(position + 5, y2 - z2 + w2 - x2); dest.put(position + 6, yz + yz + xw + xw); dest.put(position + 7, 0.0f); dest.put(position + 8, yw + xz + xz + yw); dest.put(position + 9, yz + yz - xw - xw); dest.put(position + 10, z2 - y2 - x2 + w2); dest.put(position + 11, 0.0f); dest.put(position + 12, 0.0f); dest.put(position + 13, 0.0f); dest.put(position + 14, 0.0f); dest.put(position + 15, 1.0f); } public final void putMatrix4x3f(Quaternionf q, int position, ByteBuffer dest) { float w2 = q.w * q.w; float x2 = q.x * q.x; float y2 = q.y * q.y; float z2 = q.z * q.z; float zw = q.z * q.w; float xy = q.x * q.y; float xz = q.x * q.z; float yw = q.y * q.w; float yz = q.y * q.z; float xw = q.x * q.w; dest.putFloat(position, w2 + x2 - z2 - y2); dest.putFloat(position + 4, xy + zw + zw + xy); dest.putFloat(position + 8, xz - yw + xz - yw); dest.putFloat(position + 12, -zw + xy - zw + xy); dest.putFloat(position + 16, y2 - z2 + w2 - x2); dest.putFloat(position + 20, yz + yz + xw + xw); dest.putFloat(position + 24, yw + xz + xz + yw); dest.putFloat(position + 28, yz + yz - xw - xw); dest.putFloat(position + 32, z2 - y2 - x2 + w2); dest.putLong(position + 36, 0L); dest.putFloat(position + 44, 0.0f); } public final void putMatrix4x3f(Quaternionf q, int position, FloatBuffer dest) { float w2 = q.w * q.w; float x2 = q.x * q.x; float y2 = q.y * q.y; float z2 = q.z * q.z; float zw = q.z * q.w; float xy = q.x * q.y; float xz = q.x * q.z; float yw = q.y * q.w; float yz = q.y * q.z; float xw = q.x * q.w; dest.put(position, w2 + x2 - z2 - y2); dest.put(position + 1, xy + zw + zw + xy); dest.put(position + 2, xz - yw + xz - yw); dest.put(position + 3, -zw + xy - zw + xy); dest.put(position + 4, y2 - z2 + w2 - x2); dest.put(position + 5, yz + yz + xw + xw); dest.put(position + 6, yw + xz + xz + yw); dest.put(position + 7, yz + yz - xw - xw); dest.put(position + 8, z2 - y2 - x2 + w2); dest.put(position + 9, 0.0f); dest.put(position + 10, 0.0f); dest.put(position + 11, 0.0f); } public final void set(Matrix4f m, Vector4f col0, Vector4f col1, Vector4f col2, Vector4f col3) { m.m00 = col0.x; m.m01 = col0.y; m.m02 = col0.z; m.m03 = col0.w; m.m10 = col1.x; m.m11 = col1.y; m.m12 = col1.z; m.m13 = col1.w; m.m20 = col2.x; m.m21 = col2.y; m.m22 = col2.z; m.m23 = col2.w; m.m30 = col3.x; m.m31 = col3.y; m.m32 = col3.z; m.m33 = col3.w; } public final void set(Matrix4x3f m, Vector3f col0, Vector3f col1, Vector3f col2, Vector3f col3) { m.m00 = col0.x; m.m01 = col0.y; m.m02 = col0.z; m.m10 = col1.x; m.m11 = col1.y; m.m12 = col1.z; m.m20 = col2.x; m.m21 = col2.y; m.m22 = col2.z; m.m30 = col3.x; m.m31 = col3.y; m.m32 = col3.z; } public final void set(Matrix3f m, Vector3f col0, Vector3f col1, Vector3f col2) { m.m00 = col0.x; m.m01 = col0.y; m.m02 = col0.z; m.m10 = col1.x; m.m11 = col1.y; m.m12 = col1.z; m.m20 = col2.x; m.m21 = col2.y; m.m22 = col2.z; } public final void putColumn0(Matrix4f src, Vector4f dest) { dest.x = src.m00; dest.y = src.m01; dest.z = src.m02; dest.w = src.m03; } public final void putColumn1(Matrix4f src, Vector4f dest) { dest.x = src.m10; dest.y = src.m11; dest.z = src.m12; dest.w = src.m13; } public final void putColumn2(Matrix4f src, Vector4f dest) { dest.x = src.m20; dest.y = src.m21; dest.z = src.m22; dest.w = src.m23; } public final void putColumn3(Matrix4f src, Vector4f dest) { dest.x = src.m30; dest.y = src.m31; dest.z = src.m32; dest.w = src.m33; } public final void getColumn0(Matrix4f dest, Vector4f src) { dest.m00 = src.x; dest.m01 = src.y; dest.m02 = src.z; dest.m03 = src.w; } public final void getColumn1(Matrix4f dest, Vector4f src) { dest.m10 = src.x; dest.m11 = src.y; dest.m12 = src.z; dest.m13 = src.w; } public final void getColumn2(Matrix4f dest, Vector4f src) { dest.m20 = src.x; dest.m21 = src.y; dest.m22 = src.z; dest.m23 = src.w; } public final void getColumn3(Matrix4f dest, Vector4f src) { dest.m30 = src.x; dest.m31 = src.y; dest.m32 = src.z; dest.m33 = src.w; } public final void broadcast(float c, Vector4f dest) { dest.x = c; dest.y = c; dest.z = c; dest.w = c; } public final void broadcast(int c, Vector4i dest) { dest.x = c; dest.y = c; dest.z = c; dest.w = c; } } public static final class MemUtilUnsafe extends MemUtil { private static final sun.misc.Unsafe UNSAFE; private static final long ADDRESS; private static final long Matrix3f_m00; private static final long Matrix4f_m00; private static final long Matrix4x3f_m00; private static final long Vector4f_x; private static final long Vector4d_x; private static final long Vector4i_x; private static final long Vector3f_x; private static final long Vector3d_x; private static final long Vector3i_x; private static final long Vector2f_x; private static final long Vector2d_x; private static final long Vector2i_x; private static final long Quaternionf_x; private static final long floatArrayOffset; /** * Used to create a direct ByteBuffer for a known address. */ private static final native ByteBuffer newTestBuffer(); /** * Return the pointer size (4 = 32-bit, 8 = 64-bit). */ private static native int getPointerSize(); static { UNSAFE = getUnsafeInstance(); try { ADDRESS = findBufferAddress(); Matrix4f_m00 = checkMatrix4f(); Matrix4x3f_m00 = checkMatrix4x3f(); Matrix3f_m00 = checkMatrix3f(); Vector4f_x = checkVector4f(); Vector4d_x = checkVector4d(); Vector4i_x = checkVector4i(); Vector3f_x = checkVector3f(); Vector3d_x = checkVector3d(); Vector3i_x = checkVector3i(); Vector2f_x = checkVector2f(); Vector2d_x = checkVector2d(); Vector2i_x = checkVector2i(); Quaternionf_x = checkQuaternionf(); floatArrayOffset = UNSAFE.arrayBaseOffset(float[].class); // Check if we can use object field offset/address put/get methods sun.misc.Unsafe.class.getDeclaredMethod("getLong", new Class[] {Object.class, long.class}); sun.misc.Unsafe.class.getDeclaredMethod("putOrderedLong", new Class[] {Object.class, long.class, long.class}); } catch (NoSuchFieldException e) { throw new UnsupportedOperationException(e); } catch (NoSuchMethodException e) { throw new UnsupportedOperationException(e); } } private static long findBufferAddress() { try { return UNSAFE.objectFieldOffset(getDeclaredField(Buffer.class, "address")); //$NON-NLS-1$ } catch (Exception e) { /* Maybe because of JDK9 AwkwardStrongEncapsulation. */ /* Try detecting the address from a known value. */ try { SharedLibraryLoader.load(); } catch (IOException e1) { throw new UnsupportedOperationException("Failed to load joml shared library", e1); } ByteBuffer bb = newTestBuffer(); long magicAddress = 0xFEEDBABEDEADBEEFL; if (getPointerSize() == 4) magicAddress &= 0xFFFFFFFFL; long offset = 8L; while (offset <= 32L) { // <- don't expect offset to be too large if (UNSAFE.getLong(bb, offset) == magicAddress) return offset; offset += 8L; } throw new UnsupportedOperationException("Could not detect ByteBuffer.address offset", e); } } public MemUtilUnsafe UNSAFE() { return this; } private static long checkMatrix4f() throws NoSuchFieldException, SecurityException { Field f = Matrix4f.class.getDeclaredField("m00"); long Matrix4f_m00 = UNSAFE.objectFieldOffset(f); // Validate expected field offsets for (int i = 1; i < 16; i++) { int c = i >>> 2; int r = i & 3; f = Matrix4f.class.getDeclaredField("m" + c + r); long offset = UNSAFE.objectFieldOffset(f); if (offset != Matrix4f_m00 + (i << 2)) throw new UnsupportedOperationException(); } return Matrix4f_m00; } private static long checkMatrix4x3f() throws NoSuchFieldException, SecurityException { Field f = Matrix4x3f.class.getDeclaredField("m00"); long Matrix4x3f_m00 = UNSAFE.objectFieldOffset(f); // Validate expected field offsets for (int i = 1; i < 12; i++) { int c = i / 3; int r = i % 3; f = Matrix4x3f.class.getDeclaredField("m" + c + r); long offset = UNSAFE.objectFieldOffset(f); if (offset != Matrix4x3f_m00 + (i << 2)) throw new UnsupportedOperationException(); } return Matrix4x3f_m00; } private static long checkMatrix3f() throws NoSuchFieldException, SecurityException { Field f = Matrix3f.class.getDeclaredField("m00"); long Matrix3f_m00 = UNSAFE.objectFieldOffset(f); // Validate expected field offsets for (int i = 1; i < 9; i++) { int c = i / 3; int r = i % 3; f = Matrix3f.class.getDeclaredField("m" + c + r); long offset = UNSAFE.objectFieldOffset(f); if (offset != Matrix3f_m00 + (i << 2)) throw new UnsupportedOperationException(); } return Matrix3f_m00; } private static long checkVector4f() throws NoSuchFieldException, SecurityException { Field f = Vector4f.class.getDeclaredField("x"); long Vector4f_x = UNSAFE.objectFieldOffset(f); // Validate expected field offsets String[] names = {"y", "z", "w"}; for (int i = 1; i < 4; i++) { f = Vector4f.class.getDeclaredField(names[i-1]); long offset = UNSAFE.objectFieldOffset(f); if (offset != Vector4f_x + (i << 2)) throw new UnsupportedOperationException(); } return Vector4f_x; } private static long checkVector4d() throws NoSuchFieldException, SecurityException { Field f = Vector4d.class.getDeclaredField("x"); long Vector4d_x = UNSAFE.objectFieldOffset(f); // Validate expected field offsets String[] names = {"y", "z", "w"}; for (int i = 1; i < 4; i++) { f = Vector4d.class.getDeclaredField(names[i-1]); long offset = UNSAFE.objectFieldOffset(f); if (offset != Vector4d_x + (i << 3)) throw new UnsupportedOperationException(); } return Vector4d_x; } private static long checkVector4i() throws NoSuchFieldException, SecurityException { Field f = Vector4i.class.getDeclaredField("x"); long Vector4i_x = UNSAFE.objectFieldOffset(f); // Validate expected field offsets String[] names = {"y", "z", "w"}; for (int i = 1; i < 4; i++) { f = Vector4i.class.getDeclaredField(names[i-1]); long offset = UNSAFE.objectFieldOffset(f); if (offset != Vector4i_x + (i << 2)) throw new UnsupportedOperationException(); } return Vector4i_x; } private static long checkVector3f() throws NoSuchFieldException, SecurityException { Field f = Vector3f.class.getDeclaredField("x"); long Vector3f_x = UNSAFE.objectFieldOffset(f); // Validate expected field offsets String[] names = {"y", "z"}; for (int i = 1; i < 3; i++) { f = Vector3f.class.getDeclaredField(names[i-1]); long offset = UNSAFE.objectFieldOffset(f); if (offset != Vector3f_x + (i << 2)) throw new UnsupportedOperationException(); } return Vector3f_x; } private static long checkVector3d() throws NoSuchFieldException, SecurityException { Field f = Vector3d.class.getDeclaredField("x"); long Vector3d_x = UNSAFE.objectFieldOffset(f); // Validate expected field offsets String[] names = {"y", "z"}; for (int i = 1; i < 3; i++) { f = Vector3d.class.getDeclaredField(names[i-1]); long offset = UNSAFE.objectFieldOffset(f); if (offset != Vector3d_x + (i << 3)) throw new UnsupportedOperationException(); } return Vector3d_x; } private static long checkVector3i() throws NoSuchFieldException, SecurityException { Field f = Vector3i.class.getDeclaredField("x"); long Vector3i_x = UNSAFE.objectFieldOffset(f); // Validate expected field offsets String[] names = {"y", "z"}; for (int i = 1; i < 3; i++) { f = Vector3i.class.getDeclaredField(names[i-1]); long offset = UNSAFE.objectFieldOffset(f); if (offset != Vector3i_x + (i << 2)) throw new UnsupportedOperationException(); } return Vector3i_x; } private static long checkVector2f() throws NoSuchFieldException, SecurityException { Field f = Vector2f.class.getDeclaredField("x"); long Vector2f_x = UNSAFE.objectFieldOffset(f); // Validate expected field offsets f = Vector2f.class.getDeclaredField("y"); long offset = UNSAFE.objectFieldOffset(f); if (offset != Vector2f_x + (1 << 2)) throw new UnsupportedOperationException(); return Vector2f_x; } private static long checkVector2d() throws NoSuchFieldException, SecurityException { Field f = Vector2d.class.getDeclaredField("x"); long Vector2d_x = UNSAFE.objectFieldOffset(f); // Validate expected field offsets f = Vector2d.class.getDeclaredField("y"); long offset = UNSAFE.objectFieldOffset(f); if (offset != Vector2d_x + (1 << 3)) throw new UnsupportedOperationException(); return Vector2d_x; } private static long checkVector2i() throws NoSuchFieldException, SecurityException { Field f = Vector2i.class.getDeclaredField("x"); long Vector2i_x = UNSAFE.objectFieldOffset(f); // Validate expected field offsets f = Vector2i.class.getDeclaredField("y"); long offset = UNSAFE.objectFieldOffset(f); if (offset != Vector2i_x + (1 << 2)) throw new UnsupportedOperationException(); return Vector2i_x; } private static long checkQuaternionf() throws NoSuchFieldException, SecurityException { Field f = Quaternionf.class.getDeclaredField("x"); long Quaternionf_x = UNSAFE.objectFieldOffset(f); // Validate expected field offsets String[] names = {"y", "z", "w"}; for (int i = 1; i < 4; i++) { f = Quaternionf.class.getDeclaredField(names[i-1]); long offset = UNSAFE.objectFieldOffset(f); if (offset != Quaternionf_x + (i << 2)) throw new UnsupportedOperationException(); } return Quaternionf_x; } private static final java.lang.reflect.Field getDeclaredField(Class root, String fieldName) throws NoSuchFieldException { Class type = root; do { try { java.lang.reflect.Field field = type.getDeclaredField(fieldName); field.setAccessible(true); return field; } catch (NoSuchFieldException e) { type = type.getSuperclass(); } catch (SecurityException e) { type = type.getSuperclass(); } } while (type != null); throw new NoSuchFieldException(fieldName + " does not exist in " + root.getName() + " or any of its superclasses."); //$NON-NLS-1$ //$NON-NLS-2$ } private static final sun.misc.Unsafe getUnsafeInstance() throws SecurityException { java.lang.reflect.Field[] fields = sun.misc.Unsafe.class.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { java.lang.reflect.Field field = fields[i]; if (!field.getType().equals(sun.misc.Unsafe.class)) continue; int modifiers = field.getModifiers(); if (!(java.lang.reflect.Modifier.isStatic(modifiers) && java.lang.reflect.Modifier.isFinal(modifiers))) continue; field.setAccessible(true); try { return (sun.misc.Unsafe) field.get(null); } catch (IllegalAccessException e) { /* Ignore */ } break; } throw new UnsupportedOperationException(); } public final long addressOf(Buffer buffer) { return UNSAFE.getLong(buffer, ADDRESS); } public final void put(Matrix4f m, long destAddr) { for (int i = 0; i < 8; i++) { UNSAFE.putOrderedLong(null, destAddr + (i << 3), UNSAFE.getLong(m, Matrix4f_m00 + (i << 3))); } } public final void put(Matrix4x3f m, long destAddr) { for (int i = 0; i < 6; i++) { UNSAFE.putOrderedLong(null, destAddr + (i << 3), UNSAFE.getLong(m, Matrix4x3f_m00 + (i << 3))); } } public final void put4x4(Matrix4x3f m, long destAddr) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(null, destAddr + (i << 4), UNSAFE.getLong(m, Matrix4x3f_m00 + 12 * i)); long lng = UNSAFE.getInt(m, Matrix4x3f_m00 + 8 + 12 * i) & 0xFFFFFFFFL; UNSAFE.putOrderedLong(null, destAddr + 8 + (i << 4), lng); } UNSAFE.putFloat(null, destAddr + 60, 1.0f); } public final void put4x4(Matrix4x3d m, long destAddr) { UNSAFE.putDouble(null, destAddr, m.m00); UNSAFE.putDouble(null, destAddr + 8, m.m01); UNSAFE.putDouble(null, destAddr + 16, m.m02); UNSAFE.putDouble(null, destAddr + 24, 0.0); UNSAFE.putDouble(null, destAddr + 32, m.m10); UNSAFE.putDouble(null, destAddr + 40, m.m11); UNSAFE.putDouble(null, destAddr + 48, m.m12); UNSAFE.putDouble(null, destAddr + 56, 0.0); UNSAFE.putDouble(null, destAddr + 64, m.m20); UNSAFE.putDouble(null, destAddr + 72, m.m21); UNSAFE.putDouble(null, destAddr + 80, m.m22); UNSAFE.putDouble(null, destAddr + 88, 0.0); UNSAFE.putDouble(null, destAddr + 96, m.m30); UNSAFE.putDouble(null, destAddr + 104, m.m31); UNSAFE.putDouble(null, destAddr + 112, m.m32); UNSAFE.putDouble(null, destAddr + 120, 1.0); } public final void putTransposed(Matrix4f m, long destAddr) { UNSAFE.putFloat(null, destAddr, m.m00); UNSAFE.putFloat(null, destAddr + 4, m.m10); UNSAFE.putFloat(null, destAddr + 8, m.m20); UNSAFE.putFloat(null, destAddr + 12, m.m30); UNSAFE.putFloat(null, destAddr + 16, m.m01); UNSAFE.putFloat(null, destAddr + 20, m.m11); UNSAFE.putFloat(null, destAddr + 24, m.m21); UNSAFE.putFloat(null, destAddr + 28, m.m31); UNSAFE.putFloat(null, destAddr + 32, m.m02); UNSAFE.putFloat(null, destAddr + 36, m.m12); UNSAFE.putFloat(null, destAddr + 40, m.m22); UNSAFE.putFloat(null, destAddr + 44, m.m32); UNSAFE.putFloat(null, destAddr + 48, m.m03); UNSAFE.putFloat(null, destAddr + 52, m.m13); UNSAFE.putFloat(null, destAddr + 56, m.m23); UNSAFE.putFloat(null, destAddr + 60, m.m33); } public final void put4x3Transposed(Matrix4f m, long destAddr) { UNSAFE.putFloat(null, destAddr, m.m00); UNSAFE.putFloat(null, destAddr + 4, m.m10); UNSAFE.putFloat(null, destAddr + 8, m.m20); UNSAFE.putFloat(null, destAddr + 12, m.m30); UNSAFE.putFloat(null, destAddr + 16, m.m01); UNSAFE.putFloat(null, destAddr + 20, m.m11); UNSAFE.putFloat(null, destAddr + 24, m.m21); UNSAFE.putFloat(null, destAddr + 28, m.m31); UNSAFE.putFloat(null, destAddr + 32, m.m02); UNSAFE.putFloat(null, destAddr + 36, m.m12); UNSAFE.putFloat(null, destAddr + 40, m.m22); UNSAFE.putFloat(null, destAddr + 44, m.m32); } public final void putTransposed(Matrix4x3f m, long destAddr) { UNSAFE.putFloat(null, destAddr, m.m00); UNSAFE.putFloat(null, destAddr + 4, m.m10); UNSAFE.putFloat(null, destAddr + 8, m.m20); UNSAFE.putFloat(null, destAddr + 12, m.m30); UNSAFE.putFloat(null, destAddr + 16, m.m01); UNSAFE.putFloat(null, destAddr + 20, m.m11); UNSAFE.putFloat(null, destAddr + 24, m.m21); UNSAFE.putFloat(null, destAddr + 28, m.m31); UNSAFE.putFloat(null, destAddr + 32, m.m02); UNSAFE.putFloat(null, destAddr + 36, m.m12); UNSAFE.putFloat(null, destAddr + 40, m.m22); UNSAFE.putFloat(null, destAddr + 44, m.m32); } public final void putTransposed(Matrix3f m, long destAddr) { UNSAFE.putFloat(null, destAddr, m.m00); UNSAFE.putFloat(null, destAddr + 4, m.m10); UNSAFE.putFloat(null, destAddr + 8, m.m20); UNSAFE.putFloat(null, destAddr + 12, m.m01); UNSAFE.putFloat(null, destAddr + 16, m.m11); UNSAFE.putFloat(null, destAddr + 20, m.m21); UNSAFE.putFloat(null, destAddr + 24, m.m02); UNSAFE.putFloat(null, destAddr + 28, m.m12); UNSAFE.putFloat(null, destAddr + 32, m.m22); } public final void put(Matrix4d m, long destAddr) { UNSAFE.putDouble(null, destAddr, m.m00); UNSAFE.putDouble(null, destAddr + 8, m.m01); UNSAFE.putDouble(null, destAddr + 16, m.m02); UNSAFE.putDouble(null, destAddr + 24, m.m03); UNSAFE.putDouble(null, destAddr + 32, m.m10); UNSAFE.putDouble(null, destAddr + 40, m.m11); UNSAFE.putDouble(null, destAddr + 48, m.m12); UNSAFE.putDouble(null, destAddr + 56, m.m13); UNSAFE.putDouble(null, destAddr + 64, m.m20); UNSAFE.putDouble(null, destAddr + 72, m.m21); UNSAFE.putDouble(null, destAddr + 80, m.m22); UNSAFE.putDouble(null, destAddr + 88, m.m23); UNSAFE.putDouble(null, destAddr + 96, m.m30); UNSAFE.putDouble(null, destAddr + 104, m.m31); UNSAFE.putDouble(null, destAddr + 112, m.m32); UNSAFE.putDouble(null, destAddr + 120, m.m33); } public final void put(Matrix4x3d m, long destAddr) { UNSAFE.putDouble(null, destAddr, m.m00); UNSAFE.putDouble(null, destAddr + 8, m.m01); UNSAFE.putDouble(null, destAddr + 16, m.m02); UNSAFE.putDouble(null, destAddr + 24, m.m10); UNSAFE.putDouble(null, destAddr + 32, m.m11); UNSAFE.putDouble(null, destAddr + 40, m.m12); UNSAFE.putDouble(null, destAddr + 48, m.m20); UNSAFE.putDouble(null, destAddr + 56, m.m21); UNSAFE.putDouble(null, destAddr + 64, m.m22); UNSAFE.putDouble(null, destAddr + 72, m.m30); UNSAFE.putDouble(null, destAddr + 80, m.m31); UNSAFE.putDouble(null, destAddr + 88, m.m32); } public final void putTransposed(Matrix4d m, long destAddr) { UNSAFE.putDouble(null, destAddr, m.m00); UNSAFE.putDouble(null, destAddr + 8, m.m10); UNSAFE.putDouble(null, destAddr + 16, m.m20); UNSAFE.putDouble(null, destAddr + 24, m.m30); UNSAFE.putDouble(null, destAddr + 32, m.m01); UNSAFE.putDouble(null, destAddr + 40, m.m11); UNSAFE.putDouble(null, destAddr + 48, m.m21); UNSAFE.putDouble(null, destAddr + 56, m.m31); UNSAFE.putDouble(null, destAddr + 64, m.m02); UNSAFE.putDouble(null, destAddr + 72, m.m12); UNSAFE.putDouble(null, destAddr + 80, m.m22); UNSAFE.putDouble(null, destAddr + 88, m.m32); UNSAFE.putDouble(null, destAddr + 96, m.m03); UNSAFE.putDouble(null, destAddr + 104, m.m13); UNSAFE.putDouble(null, destAddr + 112, m.m23); UNSAFE.putDouble(null, destAddr + 120, m.m33); } public final void putfTransposed(Matrix4d m, long destAddr) { UNSAFE.putFloat(null, destAddr, (float)m.m00); UNSAFE.putFloat(null, destAddr + 4, (float)m.m10); UNSAFE.putFloat(null, destAddr + 8, (float)m.m20); UNSAFE.putFloat(null, destAddr + 12, (float)m.m30); UNSAFE.putFloat(null, destAddr + 16, (float)m.m01); UNSAFE.putFloat(null, destAddr + 20, (float)m.m11); UNSAFE.putFloat(null, destAddr + 24, (float)m.m21); UNSAFE.putFloat(null, destAddr + 28, (float)m.m31); UNSAFE.putFloat(null, destAddr + 32, (float)m.m02); UNSAFE.putFloat(null, destAddr + 36, (float)m.m12); UNSAFE.putFloat(null, destAddr + 40, (float)m.m22); UNSAFE.putFloat(null, destAddr + 44, (float)m.m32); UNSAFE.putFloat(null, destAddr + 48, (float)m.m03); UNSAFE.putFloat(null, destAddr + 52, (float)m.m13); UNSAFE.putFloat(null, destAddr + 56, (float)m.m23); UNSAFE.putFloat(null, destAddr + 60, (float)m.m33); } public final void put4x3Transposed(Matrix4d m, long destAddr) { UNSAFE.putDouble(null, destAddr, m.m00); UNSAFE.putDouble(null, destAddr + 8, m.m10); UNSAFE.putDouble(null, destAddr + 16, m.m20); UNSAFE.putDouble(null, destAddr + 24, m.m30); UNSAFE.putDouble(null, destAddr + 32, m.m01); UNSAFE.putDouble(null, destAddr + 40, m.m11); UNSAFE.putDouble(null, destAddr + 48, m.m21); UNSAFE.putDouble(null, destAddr + 56, m.m31); UNSAFE.putDouble(null, destAddr + 64, m.m02); UNSAFE.putDouble(null, destAddr + 72, m.m12); UNSAFE.putDouble(null, destAddr + 80, m.m22); UNSAFE.putDouble(null, destAddr + 88, m.m32); } public final void putTransposed(Matrix4x3d m, long destAddr) { UNSAFE.putDouble(null, destAddr, m.m00); UNSAFE.putDouble(null, destAddr + 8, m.m10); UNSAFE.putDouble(null, destAddr + 16, m.m20); UNSAFE.putDouble(null, destAddr + 24, m.m30); UNSAFE.putDouble(null, destAddr + 32, m.m01); UNSAFE.putDouble(null, destAddr + 40, m.m11); UNSAFE.putDouble(null, destAddr + 48, m.m21); UNSAFE.putDouble(null, destAddr + 56, m.m31); UNSAFE.putDouble(null, destAddr + 64, m.m02); UNSAFE.putDouble(null, destAddr + 72, m.m12); UNSAFE.putDouble(null, destAddr + 80, m.m22); UNSAFE.putDouble(null, destAddr + 88, m.m32); } public final void putfTransposed(Matrix4x3d m, long destAddr) { UNSAFE.putFloat(null, destAddr, (float)m.m00); UNSAFE.putFloat(null, destAddr + 4, (float)m.m10); UNSAFE.putFloat(null, destAddr + 8, (float)m.m20); UNSAFE.putFloat(null, destAddr + 12, (float)m.m30); UNSAFE.putFloat(null, destAddr + 16, (float)m.m01); UNSAFE.putFloat(null, destAddr + 20, (float)m.m11); UNSAFE.putFloat(null, destAddr + 24, (float)m.m21); UNSAFE.putFloat(null, destAddr + 28, (float)m.m31); UNSAFE.putFloat(null, destAddr + 32, (float)m.m02); UNSAFE.putFloat(null, destAddr + 36, (float)m.m12); UNSAFE.putFloat(null, destAddr + 40, (float)m.m22); UNSAFE.putFloat(null, destAddr + 44, (float)m.m32); } public final void putf(Matrix4d m, long destAddr) { UNSAFE.putFloat(null, destAddr, (float)m.m00); UNSAFE.putFloat(null, destAddr + 4, (float)m.m01); UNSAFE.putFloat(null, destAddr + 8, (float)m.m02); UNSAFE.putFloat(null, destAddr + 12, (float)m.m03); UNSAFE.putFloat(null, destAddr + 16, (float)m.m10); UNSAFE.putFloat(null, destAddr + 20, (float)m.m11); UNSAFE.putFloat(null, destAddr + 24, (float)m.m12); UNSAFE.putFloat(null, destAddr + 28, (float)m.m13); UNSAFE.putFloat(null, destAddr + 32, (float)m.m20); UNSAFE.putFloat(null, destAddr + 36, (float)m.m21); UNSAFE.putFloat(null, destAddr + 40, (float)m.m22); UNSAFE.putFloat(null, destAddr + 44, (float)m.m23); UNSAFE.putFloat(null, destAddr + 48, (float)m.m30); UNSAFE.putFloat(null, destAddr + 52, (float)m.m31); UNSAFE.putFloat(null, destAddr + 56, (float)m.m32); UNSAFE.putFloat(null, destAddr + 60, (float)m.m33); } public final void putf(Matrix4x3d m, long destAddr) { UNSAFE.putFloat(null, destAddr, (float)m.m00); UNSAFE.putFloat(null, destAddr + 4, (float)m.m01); UNSAFE.putFloat(null, destAddr + 8, (float)m.m02); UNSAFE.putFloat(null, destAddr + 12, (float)m.m10); UNSAFE.putFloat(null, destAddr + 16, (float)m.m11); UNSAFE.putFloat(null, destAddr + 20, (float)m.m12); UNSAFE.putFloat(null, destAddr + 24, (float)m.m20); UNSAFE.putFloat(null, destAddr + 28, (float)m.m21); UNSAFE.putFloat(null, destAddr + 32, (float)m.m22); UNSAFE.putFloat(null, destAddr + 36, (float)m.m30); UNSAFE.putFloat(null, destAddr + 40, (float)m.m31); UNSAFE.putFloat(null, destAddr + 44, (float)m.m32); } public final void put(Matrix3f m, long destAddr) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(null, destAddr + (i << 3), UNSAFE.getLong(m, Matrix3f_m00 + (i << 3))); } UNSAFE.putFloat(null, destAddr + 32, m.m22); } public final void put(Matrix3d m, long destAddr) { UNSAFE.putDouble(null, destAddr, m.m00); UNSAFE.putDouble(null, destAddr + 8, m.m01); UNSAFE.putDouble(null, destAddr + 16, m.m02); UNSAFE.putDouble(null, destAddr + 24, m.m10); UNSAFE.putDouble(null, destAddr + 32, m.m11); UNSAFE.putDouble(null, destAddr + 40, m.m12); UNSAFE.putDouble(null, destAddr + 48, m.m20); UNSAFE.putDouble(null, destAddr + 56, m.m21); UNSAFE.putDouble(null, destAddr + 64, m.m22); } public final void putf(Matrix3d m, long destAddr) { UNSAFE.putFloat(null, destAddr, (float)m.m00); UNSAFE.putFloat(null, destAddr + 4, (float)m.m01); UNSAFE.putFloat(null, destAddr + 8, (float)m.m02); UNSAFE.putFloat(null, destAddr + 12, (float)m.m10); UNSAFE.putFloat(null, destAddr + 16, (float)m.m11); UNSAFE.putFloat(null, destAddr + 20, (float)m.m12); UNSAFE.putFloat(null, destAddr + 24, (float)m.m20); UNSAFE.putFloat(null, destAddr + 28, (float)m.m21); UNSAFE.putFloat(null, destAddr + 32, (float)m.m22); } public final void put(Vector4d src, long destAddr) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(null, destAddr + (i << 3), UNSAFE.getLong(src, Vector4d_x + (i << 3))); } } public final void put(Vector4f src, long destAddr) { UNSAFE.putOrderedLong(null, destAddr, UNSAFE.getLong(src, Vector4f_x)); UNSAFE.putOrderedLong(null, destAddr+8, UNSAFE.getLong(src, Vector4f_x+8)); } public final void put(Vector4i src, long destAddr) { UNSAFE.putOrderedLong(null, destAddr, UNSAFE.getLong(src, Vector4i_x)); UNSAFE.putOrderedLong(null, destAddr+8, UNSAFE.getLong(src, Vector4i_x+8)); } public final void put(Vector3f src, long destAddr) { UNSAFE.putOrderedLong(null, destAddr, UNSAFE.getLong(src, Vector3f_x)); UNSAFE.putFloat(null, destAddr+8, UNSAFE.getFloat(src, Vector3f_x+8)); } public final void put(Vector3d src, long destAddr) { UNSAFE.putDouble(null, destAddr, UNSAFE.getDouble(src, Vector3d_x)); UNSAFE.putDouble(null, destAddr+8, UNSAFE.getDouble(src, Vector3d_x+8)); UNSAFE.putDouble(null, destAddr+16, UNSAFE.getDouble(src, Vector3d_x+16)); } public final void put(Vector3i src, long destAddr) { UNSAFE.putOrderedLong(null, destAddr, UNSAFE.getLong(src, Vector3i_x)); UNSAFE.putInt(null, destAddr+8, UNSAFE.getInt(src, Vector3i_x+8)); } public final void put(Vector2f src, long destAddr) { UNSAFE.putOrderedLong(null, destAddr, UNSAFE.getLong(src, Vector2f_x)); } public final void put(Vector2d src, long destAddr) { UNSAFE.putDouble(null, destAddr, UNSAFE.getDouble(src, Vector2d_x)); UNSAFE.putDouble(null, destAddr+8, UNSAFE.getDouble(src, Vector2d_x+8)); } public final void put(Vector2i src, long destAddr) { UNSAFE.putOrderedLong(null, destAddr, UNSAFE.getLong(src, Vector2i_x)); } public final void get(Matrix4f m, long srcAddr) { for (int i = 0; i < 8; i++) { UNSAFE.putOrderedLong(m, Matrix4f_m00 + (i << 3), UNSAFE.getLong(srcAddr + (i << 3))); } } public final void get(Matrix4x3f m, long srcAddr) { for (int i = 0; i < 6; i++) { UNSAFE.putOrderedLong(m, Matrix4x3f_m00 + (i << 3), UNSAFE.getLong(srcAddr + (i << 3))); } } public final void get(Matrix4d m, long srcAddr) { m.m00 = UNSAFE.getDouble(null, srcAddr); m.m01 = UNSAFE.getDouble(null, srcAddr+8); m.m02 = UNSAFE.getDouble(null, srcAddr+16); m.m03 = UNSAFE.getDouble(null, srcAddr+24); m.m10 = UNSAFE.getDouble(null, srcAddr+32); m.m11 = UNSAFE.getDouble(null, srcAddr+40); m.m12 = UNSAFE.getDouble(null, srcAddr+48); m.m13 = UNSAFE.getDouble(null, srcAddr+56); m.m20 = UNSAFE.getDouble(null, srcAddr+64); m.m21 = UNSAFE.getDouble(null, srcAddr+72); m.m22 = UNSAFE.getDouble(null, srcAddr+80); m.m23 = UNSAFE.getDouble(null, srcAddr+88); m.m30 = UNSAFE.getDouble(null, srcAddr+96); m.m31 = UNSAFE.getDouble(null, srcAddr+104); m.m32 = UNSAFE.getDouble(null, srcAddr+112); m.m33 = UNSAFE.getDouble(null, srcAddr+120); } public final void get(Matrix4x3d m, long srcAddr) { m.m00 = UNSAFE.getDouble(null, srcAddr); m.m01 = UNSAFE.getDouble(null, srcAddr+8); m.m02 = UNSAFE.getDouble(null, srcAddr+16); m.m10 = UNSAFE.getDouble(null, srcAddr+24); m.m11 = UNSAFE.getDouble(null, srcAddr+32); m.m12 = UNSAFE.getDouble(null, srcAddr+40); m.m20 = UNSAFE.getDouble(null, srcAddr+48); m.m21 = UNSAFE.getDouble(null, srcAddr+56); m.m22 = UNSAFE.getDouble(null, srcAddr+64); m.m30 = UNSAFE.getDouble(null, srcAddr+72); m.m31 = UNSAFE.getDouble(null, srcAddr+80); m.m32 = UNSAFE.getDouble(null, srcAddr+88); } public final void getf(Matrix4d m, long srcAddr) { m.m00 = UNSAFE.getFloat(null, srcAddr); m.m01 = UNSAFE.getFloat(null, srcAddr+4); m.m02 = UNSAFE.getFloat(null, srcAddr+8); m.m03 = UNSAFE.getFloat(null, srcAddr+12); m.m10 = UNSAFE.getFloat(null, srcAddr+16); m.m11 = UNSAFE.getFloat(null, srcAddr+20); m.m12 = UNSAFE.getFloat(null, srcAddr+24); m.m13 = UNSAFE.getFloat(null, srcAddr+28); m.m20 = UNSAFE.getFloat(null, srcAddr+32); m.m21 = UNSAFE.getFloat(null, srcAddr+36); m.m22 = UNSAFE.getFloat(null, srcAddr+40); m.m23 = UNSAFE.getFloat(null, srcAddr+44); m.m30 = UNSAFE.getFloat(null, srcAddr+48); m.m31 = UNSAFE.getFloat(null, srcAddr+52); m.m32 = UNSAFE.getFloat(null, srcAddr+56); m.m33 = UNSAFE.getFloat(null, srcAddr+60); } public final void getf(Matrix4x3d m, long srcAddr) { m.m00 = UNSAFE.getFloat(null, srcAddr); m.m01 = UNSAFE.getFloat(null, srcAddr+4); m.m02 = UNSAFE.getFloat(null, srcAddr+8); m.m10 = UNSAFE.getFloat(null, srcAddr+12); m.m11 = UNSAFE.getFloat(null, srcAddr+16); m.m12 = UNSAFE.getFloat(null, srcAddr+20); m.m20 = UNSAFE.getFloat(null, srcAddr+24); m.m21 = UNSAFE.getFloat(null, srcAddr+28); m.m22 = UNSAFE.getFloat(null, srcAddr+32); m.m30 = UNSAFE.getFloat(null, srcAddr+36); m.m31 = UNSAFE.getFloat(null, srcAddr+40); m.m32 = UNSAFE.getFloat(null, srcAddr+44); } public final void get(Matrix3f m, long srcAddr) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(m, Matrix3f_m00 + (i << 3), UNSAFE.getLong(null, srcAddr + (i << 3))); } m.m22 = UNSAFE.getFloat(null, srcAddr+32); } public final void get(Matrix3d m, long srcAddr) { m.m00 = UNSAFE.getDouble(null, srcAddr); m.m01 = UNSAFE.getDouble(null, srcAddr+8); m.m02 = UNSAFE.getDouble(null, srcAddr+16); m.m10 = UNSAFE.getDouble(null, srcAddr+24); m.m11 = UNSAFE.getDouble(null, srcAddr+32); m.m12 = UNSAFE.getDouble(null, srcAddr+40); m.m20 = UNSAFE.getDouble(null, srcAddr+48); m.m21 = UNSAFE.getDouble(null, srcAddr+56); m.m22 = UNSAFE.getDouble(null, srcAddr+64); } public final void getf(Matrix3d m, long srcAddr) { m.m00 = UNSAFE.getFloat(null, srcAddr); m.m01 = UNSAFE.getFloat(null, srcAddr+4); m.m02 = UNSAFE.getFloat(null, srcAddr+8); m.m10 = UNSAFE.getFloat(null, srcAddr+12); m.m11 = UNSAFE.getFloat(null, srcAddr+16); m.m12 = UNSAFE.getFloat(null, srcAddr+20); m.m20 = UNSAFE.getFloat(null, srcAddr+24); m.m21 = UNSAFE.getFloat(null, srcAddr+28); m.m22 = UNSAFE.getFloat(null, srcAddr+32); } public final void get(Vector4d dst, long srcAddr) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(dst, Vector4d_x + (i << 3), UNSAFE.getLong(null, srcAddr + (i << 3))); } } public final void get(Vector4f dst, long srcAddr) { UNSAFE.putOrderedLong(dst, Vector4f_x, UNSAFE.getLong(null, srcAddr)); UNSAFE.putOrderedLong(dst, Vector4f_x+8, UNSAFE.getLong(null, srcAddr+8)); } public final void get(Vector4i dst, long srcAddr) { UNSAFE.putOrderedLong(dst, Vector4i_x, UNSAFE.getLong(null, srcAddr)); UNSAFE.putOrderedLong(dst, Vector4i_x+8, UNSAFE.getLong(null, srcAddr+8)); } public final void get(Vector3f dst, long srcAddr) { UNSAFE.putOrderedLong(dst, Vector3f_x, UNSAFE.getLong(null, srcAddr)); UNSAFE.putFloat(dst, Vector3f_x+8, UNSAFE.getFloat(null, srcAddr+8)); } public final void get(Vector3d dst, long srcAddr) { UNSAFE.putDouble(dst, Vector3d_x, UNSAFE.getDouble(null, srcAddr)); UNSAFE.putDouble(dst, Vector3d_x+8, UNSAFE.getDouble(null, srcAddr+8)); UNSAFE.putDouble(dst, Vector3d_x+16, UNSAFE.getDouble(null, srcAddr+16)); } public final void get(Vector3i dst, long srcAddr) { UNSAFE.putOrderedLong(dst, Vector3i_x, UNSAFE.getLong(null, srcAddr)); UNSAFE.putInt(dst, Vector3i_x+8, UNSAFE.getInt(null, srcAddr+8)); } public final void get(Vector2f dst, long srcAddr) { UNSAFE.putOrderedLong(dst, Vector2f_x, UNSAFE.getLong(null, srcAddr)); } public final void get(Vector2d dst, long srcAddr) { UNSAFE.putDouble(dst, Vector2d_x, UNSAFE.getDouble(null, srcAddr)); UNSAFE.putDouble(dst, Vector2d_x+8, UNSAFE.getDouble(null, srcAddr+8)); } public final void get(Vector2i dst, long srcAddr) { UNSAFE.putOrderedLong(dst, Vector2i_x, UNSAFE.getLong(null, srcAddr)); } public final void copy(Matrix4f src, Matrix4f dest) { for (int i = 0; i < 8; i++) { UNSAFE.putOrderedLong(dest, Matrix4f_m00 + (i << 3), UNSAFE.getLong(src, Matrix4f_m00 + (i << 3))); } } public final void copy(Matrix3f src, Matrix4f dest) { for (int i = 0; i < 3; i++) { UNSAFE.putOrderedLong(dest, Matrix4f_m00 + (i << 4), UNSAFE.getLong(src, Matrix3f_m00 + 12 * i)); long lng = UNSAFE.getInt(src, Matrix3f_m00 + 8 + 12 * i) & 0xFFFFFFFFL; UNSAFE.putOrderedLong(dest, Matrix4f_m00 + 8 + (i << 4), lng); } UNSAFE.putOrderedLong(dest, Matrix4f_m00 + 48, 0L); UNSAFE.putOrderedLong(dest, Matrix4f_m00 + 56, 0x3F80000000000000L); } public final void copy(Matrix4f src, Matrix3f dest) { for (int i = 0; i < 3; i++) { UNSAFE.putOrderedLong(dest, Matrix3f_m00 + 12 * i, UNSAFE.getLong(src, Matrix4f_m00 + (i << 4))); } dest.m02 = src.m02; dest.m12 = src.m12; dest.m22 = src.m22; } public final void copy(Matrix3f src, Matrix4x3f dest) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(dest, Matrix4x3f_m00 + (i << 3), UNSAFE.getLong(src, Matrix3f_m00 + (i << 3))); } UNSAFE.putOrderedLong(dest, Matrix4x3f_m00 + 32, UNSAFE.getInt(src, Matrix3f_m00 + 32) & 0xFFFFFFFFL); UNSAFE.putOrderedLong(dest, Matrix4x3f_m00 + 40, 0L); } public final void copy3x3(Matrix4f src, Matrix4f dest) { for (int i = 0; i < 3; i++) { UNSAFE.putOrderedLong(dest, Matrix4f_m00 + (i << 4), UNSAFE.getLong(src, Matrix4f_m00 + (i << 4))); } dest.m02 = src.m02; dest.m12 = src.m12; dest.m22 = src.m22; } public final void copy3x3(Matrix4x3f src, Matrix4x3f dest) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(dest, Matrix4x3f_m00 + (i << 3), UNSAFE.getLong(src, Matrix4x3f_m00 + (i << 3))); } dest.m22 = src.m22; } public final void copy3x3(Matrix3f src, Matrix4x3f dest) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(dest, Matrix4x3f_m00 + (i << 3), UNSAFE.getLong(src, Matrix3f_m00 + (i << 3))); } dest.m22 = src.m22; } public final void copy3x3(Matrix3f src, Matrix4f dest) { for (int i = 0; i < 3; i++) { UNSAFE.putOrderedLong(dest, Matrix4f_m00 + (i << 4), UNSAFE.getLong(src, Matrix3f_m00 + 12 * i)); } dest.m02 = src.m02; dest.m12 = src.m12; dest.m22 = src.m22; } public final void copy4x3(Matrix4x3f src, Matrix4f dest) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(dest, Matrix4f_m00 + (i << 4), UNSAFE.getLong(src, Matrix4x3f_m00 + 12 * i)); } dest.m02 = src.m02; dest.m12 = src.m12; dest.m22 = src.m22; dest.m32 = src.m32; } public final void copy4x3(Matrix4f src, Matrix4f dest) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(dest, Matrix4f_m00 + (i << 4), UNSAFE.getLong(src, Matrix4f_m00 + (i << 4))); } dest.m02 = src.m02; dest.m12 = src.m12; dest.m22 = src.m22; dest.m32 = src.m32; } public final void copy(Matrix4f src, Matrix4x3f dest) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(dest, Matrix4x3f_m00 + 12 * i, UNSAFE.getLong(src, Matrix4f_m00 + (i << 4))); } dest.m02 = src.m02; dest.m12 = src.m12; dest.m22 = src.m22; dest.m32 = src.m32; } public final void copy(Matrix4x3f src, Matrix4f dest) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(dest, Matrix4f_m00 + (i << 4), UNSAFE.getLong(src, Matrix4x3f_m00 + 12 * i)); } UNSAFE.putOrderedLong(dest, Matrix4f_m00 + 8, UNSAFE.getInt(src, Matrix4x3f_m00 + 8) & 0xFFFFFFFFL); UNSAFE.putOrderedLong(dest, Matrix4f_m00 + 24, UNSAFE.getInt(src, Matrix4x3f_m00 + 20) & 0xFFFFFFFFL); UNSAFE.putOrderedLong(dest, Matrix4f_m00 + 40, UNSAFE.getInt(src, Matrix4x3f_m00 + 32) & 0xFFFFFFFFL); UNSAFE.putOrderedLong(dest, Matrix4f_m00 + 56, 0x3F80000000000000L | (UNSAFE.getInt(src, Matrix4x3f_m00 + 44) & 0xFFFFFFFFL)); } public final void copy(Matrix4x3f src, Matrix4x3f dest) { for (int i = 0; i < 6; i++) { UNSAFE.putOrderedLong(dest, Matrix4x3f_m00 + (i << 3), UNSAFE.getLong(src, Matrix4x3f_m00 + (i << 3))); } } public final void copy(Matrix3f src, Matrix3f dest) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(dest, Matrix3f_m00 + (i << 3), UNSAFE.getLong(src, Matrix3f_m00 + (i << 3))); } dest.m22 = src.m22; } public final void copy(Vector4f src, Vector4f dest) { UNSAFE.putOrderedLong(dest, Vector4f_x, UNSAFE.getLong(src, Vector4f_x)); UNSAFE.putOrderedLong(dest, Vector4f_x+8, UNSAFE.getLong(src, Vector4f_x+8)); } public final void copy(Vector4i src, Vector4i dest) { UNSAFE.putOrderedLong(dest, Vector4i_x, UNSAFE.getLong(src, Vector4i_x)); UNSAFE.putOrderedLong(dest, Vector4i_x+8, UNSAFE.getLong(src, Vector4i_x+8)); } public final void copy(Quaternionf src, Quaternionf dest) { UNSAFE.putOrderedLong(dest, Quaternionf_x, UNSAFE.getLong(src, Quaternionf_x)); UNSAFE.putOrderedLong(dest, Quaternionf_x+8, UNSAFE.getLong(src, Quaternionf_x+8)); } public final void copy(float[] arr, int off, Matrix4f dest) { for (int i = 0; i < 8; i++) { UNSAFE.putOrderedLong(dest, Matrix4f_m00 + (i << 3), UNSAFE.getLong(arr, floatArrayOffset + (off << 2) + (i << 3))); } } public final void copy(float[] arr, int off, Matrix3f dest) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(dest, Matrix3f_m00 + (i << 3), UNSAFE.getLong(arr, floatArrayOffset + (off << 2) + (i << 3))); } UNSAFE.putFloat(dest, Matrix3f_m00 + 32, UNSAFE.getFloat(arr, floatArrayOffset + (off << 2) + 32)); } public final void copy(float[] arr, int off, Matrix4x3f dest) { for (int i = 0; i < 6; i++) { UNSAFE.putOrderedLong(dest, Matrix4x3f_m00 + (i << 3), UNSAFE.getLong(arr, floatArrayOffset + (off << 2) + (i << 3))); } } public final void copy(Matrix4f src, float[] dest, int off) { for (int i = 0; i < 8; i++) { UNSAFE.putOrderedLong(dest, floatArrayOffset + (off << 2) + (i << 3), UNSAFE.getLong(src, Matrix4f_m00 + (i << 3))); } } public final void copy(Matrix3f src, float[] dest, int off) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(dest, floatArrayOffset + (off << 2) + (i << 3), UNSAFE.getLong(src, Matrix3f_m00 + (i << 3))); } UNSAFE.putFloat(dest, floatArrayOffset + (off << 2) + 32, UNSAFE.getFloat(src, Matrix3f_m00 + 32)); } public final void copy(Matrix4x3f src, float[] dest, int off) { for (int i = 0; i < 6; i++) { UNSAFE.putOrderedLong(dest, floatArrayOffset + (off << 2) + (i << 3), UNSAFE.getLong(src, Matrix4x3f_m00 + (i << 3))); } } public final void identity(Matrix4f dest) { UNSAFE.putOrderedLong(dest, Matrix4f_m00, 0x3F800000L); UNSAFE.putOrderedLong(dest, Matrix4f_m00+8, 0L); UNSAFE.putOrderedLong(dest, Matrix4f_m00+16, 0x3F80000000000000L); UNSAFE.putOrderedLong(dest, Matrix4f_m00+24, 0L); UNSAFE.putOrderedLong(dest, Matrix4f_m00+32, 0L); UNSAFE.putOrderedLong(dest, Matrix4f_m00+40, 0x3F800000L); UNSAFE.putOrderedLong(dest, Matrix4f_m00+48, 0L); UNSAFE.putOrderedLong(dest, Matrix4f_m00+56, 0x3F80000000000000L); } public final void identity(Matrix4x3f dest) { UNSAFE.putOrderedLong(dest, Matrix4x3f_m00, 0x3F800000L); UNSAFE.putOrderedLong(dest, Matrix4x3f_m00+8, 0L); UNSAFE.putOrderedLong(dest, Matrix4x3f_m00+16, 0x3F800000L); UNSAFE.putOrderedLong(dest, Matrix4x3f_m00+24, 0L); UNSAFE.putOrderedLong(dest, Matrix4x3f_m00+32, 0x3F800000L); UNSAFE.putOrderedLong(dest, Matrix4x3f_m00+40, 0L); } public final void identity(Matrix3f dest) { UNSAFE.putOrderedLong(dest, Matrix3f_m00, 0x3F800000L); UNSAFE.putOrderedLong(dest, Matrix3f_m00+8, 0L); UNSAFE.putOrderedLong(dest, Matrix3f_m00+16, 0x3F800000L); UNSAFE.putOrderedLong(dest, Matrix3f_m00+24, 0L); dest.m22 = 1.0f; } public final void identity(Quaternionf dest) { UNSAFE.putOrderedLong(dest, Quaternionf_x, 0L); UNSAFE.putOrderedLong(dest, Quaternionf_x+8, 0x3F80000000000000L); } public final void swap(Matrix4f m1, Matrix4f m2) { for (int i = 0; i < 8; i++) { long tmp; tmp = UNSAFE.getLong(m1, Matrix4f_m00 + (i << 3)); UNSAFE.putOrderedLong(m1, Matrix4f_m00 + (i << 3), UNSAFE.getLong(m2, Matrix4f_m00 + (i << 3))); UNSAFE.putOrderedLong(m2, Matrix4f_m00 + (i << 3), tmp); } } public final void swap(Matrix4x3f m1, Matrix4x3f m2) { for (int i = 0; i < 6; i++) { long tmp; tmp = UNSAFE.getLong(m1, Matrix4x3f_m00 + (i << 3)); UNSAFE.putOrderedLong(m1, Matrix4x3f_m00 + (i << 3), UNSAFE.getLong(m2, Matrix4x3f_m00 + (i << 3))); UNSAFE.putOrderedLong(m2, Matrix4x3f_m00 + (i << 3), tmp); } } public final void swap(Matrix3f m1, Matrix3f m2) { for (int i = 0; i < 4; i++) { long tmp; tmp = UNSAFE.getLong(m1, Matrix3f_m00 + (i << 3)); UNSAFE.putOrderedLong(m1, Matrix3f_m00 + (i << 3), UNSAFE.getLong(m2, Matrix3f_m00 + (i << 3))); UNSAFE.putOrderedLong(m2, Matrix3f_m00 + (i << 3), tmp); } float tmp2 = m1.m22; m1.m22 = m2.m22; m2.m22 = tmp2; } public final void zero(Matrix4f dest) { for (int i = 0; i < 8; i++) { UNSAFE.putOrderedLong(dest, Matrix4f_m00 + (i << 3), 0L); } } public final void zero(Matrix4x3f dest) { for (int i = 0; i < 6; i++) { UNSAFE.putOrderedLong(dest, Matrix4x3f_m00 + (i << 3), 0L); } } public final void zero(Matrix3f dest) { for (int i = 0; i < 4; i++) { UNSAFE.putOrderedLong(dest, Matrix3f_m00 + (i << 3), 0L); } dest.m22 = 0.0f; } public final void zero(Vector4f dest) { UNSAFE.putOrderedLong(dest, Vector4f_x, 0L); UNSAFE.putOrderedLong(dest, Vector4f_x+8, 0L); } public final void zero(Vector4i dest) { UNSAFE.putOrderedLong(dest, Vector4i_x, 0L); UNSAFE.putOrderedLong(dest, Vector4i_x+8, 0L); } private void putMatrix3f(Quaternionf q, long addr) { float dx = q.x + q.x; float dy = q.y + q.y; float dz = q.z + q.z; float q00 = dx * q.x; float q11 = dy * q.y; float q22 = dz * q.z; float q01 = dx * q.y; float q02 = dx * q.z; float q03 = dx * q.w; float q12 = dy * q.z; float q13 = dy * q.w; float q23 = dz * q.w; UNSAFE.putFloat(null, addr, 1.0f - q11 - q22); UNSAFE.putFloat(null, addr + 4, q01 + q23); UNSAFE.putFloat(null, addr + 8, q02 - q13); UNSAFE.putFloat(null, addr + 12, q01 - q23); UNSAFE.putFloat(null, addr + 16, 1.0f - q22 - q00); UNSAFE.putFloat(null, addr + 20, q12 + q03); UNSAFE.putFloat(null, addr + 24, q02 + q13); UNSAFE.putFloat(null, addr + 28, q12 - q03); UNSAFE.putFloat(null, addr + 32, 1.0f - q11 - q00); } private void putMatrix4f(Quaternionf q, long addr) { float dx = q.x + q.x; float dy = q.y + q.y; float dz = q.z + q.z; float q00 = dx * q.x; float q11 = dy * q.y; float q22 = dz * q.z; float q01 = dx * q.y; float q02 = dx * q.z; float q03 = dx * q.w; float q12 = dy * q.z; float q13 = dy * q.w; float q23 = dz * q.w; UNSAFE.putFloat(null, addr, 1.0f - q11 - q22); UNSAFE.putFloat(null, addr + 4, q01 + q23); UNSAFE.putOrderedLong(null, addr + 8, Float.floatToRawIntBits(q02 - q13) & 0xFFFFFFFFL); UNSAFE.putFloat(null, addr + 16, q01 - q23); UNSAFE.putFloat(null, addr + 20, 1.0f - q22 - q00); UNSAFE.putOrderedLong(null, addr + 24, Float.floatToRawIntBits(q12 + q03) & 0xFFFFFFFFL); UNSAFE.putFloat(null, addr + 32, q02 + q13); UNSAFE.putFloat(null, addr + 36, q12 - q03); UNSAFE.putOrderedLong(null, addr + 40, Float.floatToRawIntBits(1.0f - q11 - q00) & 0xFFFFFFFFL); UNSAFE.putOrderedLong(null, addr + 48, 0L); UNSAFE.putOrderedLong(null, addr + 56, 0x3F80000000000000L); } private void putMatrix4x3f(Quaternionf q, long addr) { float dx = q.x + q.x; float dy = q.y + q.y; float dz = q.z + q.z; float q00 = dx * q.x; float q11 = dy * q.y; float q22 = dz * q.z; float q01 = dx * q.y; float q02 = dx * q.z; float q03 = dx * q.w; float q12 = dy * q.z; float q13 = dy * q.w; float q23 = dz * q.w; UNSAFE.putFloat(null, addr, 1.0f - q11 - q22); UNSAFE.putFloat(null, addr + 4, q01 + q23); UNSAFE.putFloat(null, addr + 8, q02 - q13); UNSAFE.putFloat(null, addr + 12, q01 - q23); UNSAFE.putFloat(null, addr + 16, 1.0f - q22 - q00); UNSAFE.putFloat(null, addr + 20, q12 + q03); UNSAFE.putFloat(null, addr + 24, q02 + q13); UNSAFE.putFloat(null, addr + 28, q12 - q03); UNSAFE.putFloat(null, addr + 32, 1.0f - q11 - q00); UNSAFE.putOrderedLong(null, addr + 36, 0L); UNSAFE.putFloat(null, addr + 44, 0.0f); } private static void throwNoDirectBufferException() { throw new IllegalArgumentException("Must use a direct buffer"); } public final void putMatrix3f(Quaternionf q, int position, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } long addr = addressOf(dest) + position; putMatrix3f(q, addr); } public final void putMatrix3f(Quaternionf q, int position, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } long addr = addressOf(dest) + (position << 2); putMatrix3f(q, addr); } public final void putMatrix4f(Quaternionf q, int position, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } long addr = addressOf(dest) + position; putMatrix4f(q, addr); } public final void putMatrix4f(Quaternionf q, int position, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } long addr = addressOf(dest) + (position << 2); putMatrix4f(q, addr); } public final void putMatrix4x3f(Quaternionf q, int position, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } long addr = addressOf(dest) + position; putMatrix4x3f(q, addr); } public final void putMatrix4x3f(Quaternionf q, int position, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } long addr = addressOf(dest) + (position << 2); putMatrix4x3f(q, addr); } public final void put(Matrix4f m, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(m, addressOf(dest) + (offset << 2)); } public final void put(Matrix4f m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(m, addressOf(dest) + offset); } public final void put(Matrix4x3f m, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(m, addressOf(dest) + (offset << 2)); } public final void put(Matrix4x3f m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(m, addressOf(dest) + offset); } public final void put4x4(Matrix4x3f m, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put4x4(m, addressOf(dest) + (offset << 2)); } public final void put4x4(Matrix4x3f m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put4x4(m, addressOf(dest) + offset); } public final void put4x4(Matrix4x3d m, int offset, DoubleBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put4x4(m, addressOf(dest) + (offset << 3)); } public final void put4x4(Matrix4x3d m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put4x4(m, addressOf(dest) + offset); } public final void putTransposed(Matrix4f m, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putTransposed(m, addressOf(dest) + (offset << 2)); } public final void putTransposed(Matrix4f m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putTransposed(m, addressOf(dest) + offset); } public final void put4x3Transposed(Matrix4f m, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put4x3Transposed(m, addressOf(dest) + (offset << 2)); } public final void put4x3Transposed(Matrix4f m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put4x3Transposed(m, addressOf(dest) + offset); } public final void putTransposed(Matrix4x3f m, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putTransposed(m, addressOf(dest) + (offset << 2)); } public final void putTransposed(Matrix4x3f m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putTransposed(m, addressOf(dest) + offset); } public final void putTransposed(Matrix3f m, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putTransposed(m, addressOf(dest) + (offset << 2)); } public final void putTransposed(Matrix3f m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putTransposed(m, addressOf(dest) + offset); } public final void put(Matrix4d m, int offset, DoubleBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(m, addressOf(dest) + (offset << 3)); } public final void put(Matrix4d m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(m, addressOf(dest) + offset); } public final void put(Matrix4x3d m, int offset, DoubleBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(m, addressOf(dest) + (offset << 3)); } public final void put(Matrix4x3d m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(m, addressOf(dest) + offset); } public final void putf(Matrix4d m, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putf(m, addressOf(dest) + (offset << 2)); } public final void putf(Matrix4d m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putf(m, addressOf(dest) + offset); } public final void putf(Matrix4x3d m, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putf(m, addressOf(dest) + (offset << 2)); } public final void putf(Matrix4x3d m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putf(m, addressOf(dest) + offset); } public final void putTransposed(Matrix4d m, int offset, DoubleBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putTransposed(m, addressOf(dest) + (offset << 3)); } public final void putTransposed(Matrix4d m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putTransposed(m, addressOf(dest) + offset); } public final void put4x3Transposed(Matrix4d m, int offset, DoubleBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put4x3Transposed(m, addressOf(dest) + (offset << 3)); } public final void put4x3Transposed(Matrix4d m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put4x3Transposed(m, addressOf(dest) + offset); } public final void putTransposed(Matrix4x3d m, int offset, DoubleBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putTransposed(m, addressOf(dest) + (offset << 3)); } public final void putTransposed(Matrix4x3d m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putTransposed(m, addressOf(dest) + offset); } public final void putfTransposed(Matrix4d m, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putfTransposed(m, addressOf(dest) + (offset << 2)); } public final void putfTransposed(Matrix4d m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putfTransposed(m, addressOf(dest) + offset); } public final void putfTransposed(Matrix4x3d m, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putfTransposed(m, addressOf(dest) + (offset << 2)); } public final void putfTransposed(Matrix4x3d m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putfTransposed(m, addressOf(dest) + offset); } public final void put(Matrix3f m, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(m, addressOf(dest) + (offset << 2)); } public final void put(Matrix3f m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(m, addressOf(dest) + offset); } public final void put(Matrix3d m, int offset, DoubleBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(m, addressOf(dest) + (offset << 3)); } public final void put(Matrix3d m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(m, addressOf(dest) + offset); } public final void putf(Matrix3d m, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putf(m, addressOf(dest) + (offset << 2)); } public final void putf(Matrix3d m, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } putf(m, addressOf(dest) + offset); } public final void put(Vector4d src, int offset, DoubleBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + (offset << 3)); } public final void put(Vector4d src, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + offset); } public final void put(Vector4f src, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + (offset << 2)); } public final void put(Vector4f src, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + offset); } public final void put(Vector4i src, int offset, IntBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + (offset << 2)); } public final void put(Vector4i src, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + offset); } public final void put(Vector3f src, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + (offset << 2)); } public final void put(Vector3f src, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + offset); } public final void put(Vector3d src, int offset, DoubleBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + (offset << 3)); } public final void put(Vector3d src, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + offset); } public final void put(Vector3i src, int offset, IntBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + (offset << 2)); } public final void put(Vector3i src, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + offset); } public final void put(Vector2f src, int offset, FloatBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + (offset << 2)); } public final void put(Vector2f src, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + offset); } public final void put(Vector2d src, int offset, DoubleBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + (offset << 3)); } public final void put(Vector2d src, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + offset); } public final void put(Vector2i src, int offset, IntBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + (offset << 2)); } public final void put(Vector2i src, int offset, ByteBuffer dest) { if (Options.DEBUG && !dest.isDirect()) { throwNoDirectBufferException(); } put(src, addressOf(dest) + offset); } public final void get(Matrix4f m, int offset, FloatBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(m, addressOf(src) + (offset << 2)); } public final void get(Matrix4f m, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(m, addressOf(src) + offset); } public final void get(Matrix4x3f m, int offset, FloatBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(m, addressOf(src) + (offset << 2)); } public final void get(Matrix4x3f m, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(m, addressOf(src) + offset); } public final void get(Matrix4d m, int offset, DoubleBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(m, addressOf(src) + (offset << 3)); } public final void get(Matrix4d m, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(m, addressOf(src) + offset); } public final void get(Matrix4x3d m, int offset, DoubleBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(m, addressOf(src) + (offset << 3)); } public final void get(Matrix4x3d m, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(m, addressOf(src) + offset); } public final void getf(Matrix4d m, int offset, FloatBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } getf(m, addressOf(src) + (offset << 2)); } public final void getf(Matrix4d m, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } getf(m, addressOf(src) + offset); } public final void getf(Matrix4x3d m, int offset, FloatBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } getf(m, addressOf(src) + (offset << 2)); } public final void getf(Matrix4x3d m, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } getf(m, addressOf(src) + offset); } public final void get(Matrix3f m, int offset, FloatBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(m, addressOf(src) + (offset << 2)); } public final void get(Matrix3f m, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(m, addressOf(src) + offset); } public final void get(Matrix3d m, int offset, DoubleBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(m, addressOf(src) + (offset << 3)); } public final void get(Matrix3d m, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(m, addressOf(src) + offset); } public final void getf(Matrix3d m, int offset, FloatBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } getf(m, addressOf(src) + (offset << 2)); } public final void getf(Matrix3d m, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } getf(m, addressOf(src) + offset); } public final void get(Vector4d dst, int offset, DoubleBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + (offset << 3)); } public final void get(Vector4d dst, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + offset); } public final void get(Vector4f dst, int offset, FloatBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + (offset << 2)); } public final void get(Vector4f dst, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + offset); } public final void get(Vector4i dst, int offset, IntBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + (offset << 2)); } public final void get(Vector4i dst, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + offset); } public final void get(Vector3f dst, int offset, FloatBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + (offset << 2)); } public final void get(Vector3f dst, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + offset); } public final void get(Vector3d dst, int offset, DoubleBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + (offset << 3)); } public final void get(Vector3d dst, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + offset); } public final void get(Vector3i dst, int offset, IntBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + (offset << 2)); } public final void get(Vector3i dst, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + offset); } public final void get(Vector2f dst, int offset, FloatBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + (offset << 2)); } public final void get(Vector2f dst, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + offset); } public final void get(Vector2d dst, int offset, DoubleBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + (offset << 3)); } public final void get(Vector2d dst, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + offset); } public final void get(Vector2i dst, int offset, IntBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + (offset << 2)); } public final void get(Vector2i dst, int offset, ByteBuffer src) { if (Options.DEBUG && !src.isDirect()) { throwNoDirectBufferException(); } get(dst, addressOf(src) + offset); } public final void set(Matrix4f m, Vector4f col0, Vector4f col1, Vector4f col2, Vector4f col3) { UNSAFE.putOrderedLong(m, Matrix4f_m00, UNSAFE.getLong(col0, Vector4f_x)); UNSAFE.putOrderedLong(m, Matrix4f_m00 + 8, UNSAFE.getLong(col0, Vector4f_x + 8)); UNSAFE.putOrderedLong(m, Matrix4f_m00 + 16, UNSAFE.getLong(col1, Vector4f_x)); UNSAFE.putOrderedLong(m, Matrix4f_m00 + 24, UNSAFE.getLong(col1, Vector4f_x + 8)); UNSAFE.putOrderedLong(m, Matrix4f_m00 + 32, UNSAFE.getLong(col2, Vector4f_x)); UNSAFE.putOrderedLong(m, Matrix4f_m00 + 40, UNSAFE.getLong(col2, Vector4f_x + 8)); UNSAFE.putOrderedLong(m, Matrix4f_m00 + 48, UNSAFE.getLong(col3, Vector4f_x)); UNSAFE.putOrderedLong(m, Matrix4f_m00 + 56, UNSAFE.getLong(col3, Vector4f_x + 8)); } public final void set(Matrix4x3f m, Vector3f col0, Vector3f col1, Vector3f col2, Vector3f col3) { UNSAFE.putOrderedLong(m, Matrix4x3f_m00, UNSAFE.getLong(col0, Vector3f_x)); UNSAFE.putOrderedLong(m, Matrix4x3f_m00 + 12, UNSAFE.getLong(col1, Vector3f_x)); UNSAFE.putOrderedLong(m, Matrix4x3f_m00 + 24, UNSAFE.getLong(col2, Vector3f_x)); UNSAFE.putOrderedLong(m, Matrix4x3f_m00 + 36, UNSAFE.getLong(col3, Vector3f_x)); m.m02 = col0.z; m.m12 = col1.z; m.m22 = col2.z; m.m32 = col3.z; } public final void set(Matrix3f m, Vector3f col0, Vector3f col1, Vector3f col2) { UNSAFE.putOrderedLong(m, Matrix3f_m00, UNSAFE.getLong(col0, Vector3f_x)); UNSAFE.putOrderedLong(m, Matrix3f_m00 + 12, UNSAFE.getLong(col1, Vector3f_x)); UNSAFE.putOrderedLong(m, Matrix3f_m00 + 24, UNSAFE.getLong(col2, Vector3f_x)); m.m02 = col0.z; m.m12 = col1.z; m.m22 = col2.z; } public final void putColumn0(Matrix4f src, Vector4f dest) { UNSAFE.putOrderedLong(dest, Vector4f_x, UNSAFE.getLong(src, Matrix4f_m00)); UNSAFE.putOrderedLong(dest, Vector4f_x+8, UNSAFE.getLong(src, Matrix4f_m00+8)); } public final void putColumn1(Matrix4f src, Vector4f dest) { UNSAFE.putOrderedLong(dest, Vector4f_x, UNSAFE.getLong(src, Matrix4f_m00+16)); UNSAFE.putOrderedLong(dest, Vector4f_x+8, UNSAFE.getLong(src, Matrix4f_m00+24)); } public final void putColumn2(Matrix4f src, Vector4f dest) { UNSAFE.putOrderedLong(dest, Vector4f_x, UNSAFE.getLong(src, Matrix4f_m00+32)); UNSAFE.putOrderedLong(dest, Vector4f_x+8, UNSAFE.getLong(src, Matrix4f_m00+40)); } public final void putColumn3(Matrix4f src, Vector4f dest) { UNSAFE.putOrderedLong(dest, Vector4f_x, UNSAFE.getLong(src, Matrix4f_m00+48)); UNSAFE.putOrderedLong(dest, Vector4f_x+8, UNSAFE.getLong(src, Matrix4f_m00+56)); } public final void getColumn0(Matrix4f dest, Vector4f src) { UNSAFE.putOrderedLong(dest, Matrix4f_m00, UNSAFE.getLong(src, Vector4f_x)); UNSAFE.putOrderedLong(dest, Matrix4f_m00+8, UNSAFE.getLong(src, Vector4f_x+8)); } public final void getColumn1(Matrix4f dest, Vector4f src) { UNSAFE.putOrderedLong(dest, Matrix4f_m00+16, UNSAFE.getLong(src, Vector4f_x)); UNSAFE.putOrderedLong(dest, Matrix4f_m00+24, UNSAFE.getLong(src, Vector4f_x+8)); } public final void getColumn2(Matrix4f dest, Vector4f src) { UNSAFE.putOrderedLong(dest, Matrix4f_m00+32, UNSAFE.getLong(src, Vector4f_x)); UNSAFE.putOrderedLong(dest, Matrix4f_m00+40, UNSAFE.getLong(src, Vector4f_x+8)); } public final void getColumn3(Matrix4f dest, Vector4f src) { UNSAFE.putOrderedLong(dest, Matrix4f_m00+48, UNSAFE.getLong(src, Vector4f_x)); UNSAFE.putOrderedLong(dest, Matrix4f_m00+56, UNSAFE.getLong(src, Vector4f_x+8)); } public final void broadcast(float c, Vector4f dest) { int i = Float.floatToRawIntBits(c); long one = i & 0xFFFFFFFFL; long two = one | (one << 32); UNSAFE.putOrderedLong(dest, Vector4f_x, two); UNSAFE.putOrderedLong(dest, Vector4f_x+8, two); } public final void broadcast(int c, Vector4i dest) { long one = c & 0xFFFFFFFFL; long two = one | (one << 32); UNSAFE.putOrderedLong(dest, Vector4i_x, two); UNSAFE.putOrderedLong(dest, Vector4i_x+8, two); } } }
import com.sun.star.awt.Rectangle; import com.sun.star.beans.PropertyValue; import com.sun.star.beans.XPropertySet; import com.sun.star.chart.XDiagram; import com.sun.star.chart.XChartDocument; import com.sun.star.container.XNameAccess; import com.sun.star.container.XIndexAccess; import com.sun.star.document.XEmbeddedObjectSupplier; import com.sun.star.frame.XComponentLoader; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.sheet.XSpreadsheets; import com.sun.star.sheet.XSpreadsheet; import com.sun.star.sheet.XSpreadsheetDocument; import com.sun.star.sheet.XCellRangeAddressable; import com.sun.star.table.XTableChart; import com.sun.star.table.XTableCharts; import com.sun.star.table.XCell; import com.sun.star.table.XCellRange; import com.sun.star.table.XTableChartsSupplier; import com.sun.star.table.CellRangeAddress; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import com.sun.star.uno.XComponentContext; /** This class loads an OpenOffice.org Calc document and changes the type of the * embedded chart. * @author Bertram Nolte */ public class ChartTypeChange { /** Table chart, which type will be changed. */ private XTableChart xtablechart = null; /** Service factory */ private XMultiComponentFactory xMCF = null; /** Component context */ private XComponentContext xCompContext = null; /** Beginning of the program. * @param args No arguments will be passed to the class. */ public static void main(String args[]) { try { ChartTypeChange charttypechange = new ChartTypeChange(); // Double array holding all values the chart should be based on. String[][] stringValues = { { "", "Jan", "Feb", "Mar", "Apr", "Mai" }, { "Profit", "12.3", "43.2", "5.1", "76", "56.8" }, { "Rival in business", "12.2", "12.6", "17.7", "20.4", "100" }, }; // Create the chart with charttypechange.getChart( stringValues ); String[] stringChartType = { "com.sun.star.chart.LineDiagram", "com.sun.star.chart.BarDiagram", "com.sun.star.chart.PieDiagram", "com.sun.star.chart.NetDiagram", "com.sun.star.chart.XYDiagram", "com.sun.star.chart.StockDiagram", "com.sun.star.chart.AreaDiagram" }; for ( int intCounter = 0; intCounter < stringChartType.length; intCounter++ ) { charttypechange.changeChartType( stringChartType[ intCounter ], false ); Thread.sleep( 3000 ); } System.exit(0); } catch( Exception exception ) { System.err.println( exception ); } } /** The constructor connects to the OpenOffice.org. * @param args Parameters for this constructor (connection string). * @throws Exception All exceptions are thrown from this method. */ public ChartTypeChange() throws Exception { /* Bootstraps a component context. Component context to be granted to a component for running. Arbitrary values can be retrieved from the context. */ xCompContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); /* Gets the service manager instance to be used (or null). This method has been added for convenience, because the service manager is a often used object. */ xMCF = xCompContext.getServiceManager(); } /** This method will change the type of a specified chart. * @param stringType The chart will be converted to this type. * @param booleanIs3D If the chart should be displayed in 3D this parameter should be set to true. * @throws Exception All exceptions are thrown from this method. */ public void changeChartType( String stringType, boolean booleanIs3D ) throws Exception { XEmbeddedObjectSupplier xEmbeddedObjSupplier = (XEmbeddedObjectSupplier) UnoRuntime.queryInterface(XEmbeddedObjectSupplier.class, xtablechart); XInterface xInterface = xEmbeddedObjSupplier.getEmbeddedObject(); XChartDocument xChartDoc = (XChartDocument)UnoRuntime.queryInterface( XChartDocument.class, xInterface); XDiagram xDiagram = (XDiagram) xChartDoc.getDiagram(); XMultiServiceFactory xMSF = (XMultiServiceFactory) UnoRuntime.queryInterface( XMultiServiceFactory.class, xChartDoc ); Object object = xMSF.createInstance( stringType ); xDiagram = (XDiagram) UnoRuntime.queryInterface(XDiagram.class, object); XPropertySet xPropSet = (XPropertySet) UnoRuntime.queryInterface( XPropertySet.class, xDiagram ); xPropSet.setPropertyValue( "Dim3D", new Boolean( booleanIs3D ) ); xChartDoc.setDiagram(xDiagram); } /** Loading an OpenOffice.org Calc document and getting a chart by name. * @param stringFileName Name of the OpenOffice.org Calc document which should * be loaded. * @param stringChartName Name of the chart which should get a new chart type. */ public void getChart( String stringFileName, String stringChartName ) { try { /* A desktop environment contains tasks with one or more frames in which components can be loaded. Desktop is the environment for components which can instanciate within frames. */ XComponentLoader xComponentloader = (XComponentLoader) UnoRuntime.queryInterface( XComponentLoader.class, xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xCompContext ) ); // Load a Writer document, which will be automaticly displayed XComponent xComponent = xComponentloader.loadComponentFromURL( "file:///" + stringFileName, "_blank", 0, new PropertyValue[0] ); // Query for the interface XSpreadsheetDocument XSpreadsheetDocument xSpreadSheetDocument = ( XSpreadsheetDocument ) UnoRuntime.queryInterface( XSpreadsheetDocument.class, xComponent ); XSpreadsheets xSpreadsheets = xSpreadSheetDocument.getSheets() ; XIndexAccess xIndexAccess = (XIndexAccess) UnoRuntime.queryInterface(XIndexAccess.class, xSpreadsheets ); XSpreadsheet xSpreadsheet = (XSpreadsheet) UnoRuntime.queryInterface( XSpreadsheet.class, xIndexAccess.getByIndex(0)); XTableChartsSupplier xTableChartsSupplier = ( XTableChartsSupplier ) UnoRuntime.queryInterface( XTableChartsSupplier.class, xSpreadsheet ); xIndexAccess = (XIndexAccess) UnoRuntime.queryInterface( XIndexAccess.class, xTableChartsSupplier.getCharts() ); this.xtablechart = (XTableChart) UnoRuntime.queryInterface( XTableChart.class, xIndexAccess.getByIndex( 0 ) ); } catch( Exception exception ) { System.err.println( exception ); } } /** Creating an empty OpenOffice.org Calc document, inserting data, and getting a * chart by name. * @param stringValues Double array with the values for the chart. */ public void getChart( String[][] stringValues ) { try { /* A desktop environment contains tasks with one or more frames in which components can be loaded. Desktop is the environment for components which can instanciate within frames. */ XComponentLoader xcomponentloader = ( XComponentLoader ) UnoRuntime.queryInterface( XComponentLoader.class, xMCF.createInstanceWithContext( "com.sun.star.frame.Desktop", xCompContext ) ); // Create an empty calc document, which will be automaticly displayed XComponent xComponent = xcomponentloader.loadComponentFromURL( "private:factory/scalc", "_blank", 0, new PropertyValue[0] ); // Query for the interface XSpreadsheetDocument XSpreadsheetDocument xspreadsheetdocument = ( XSpreadsheetDocument ) UnoRuntime.queryInterface( XSpreadsheetDocument.class, xComponent ); // Get all sheets of the spreadsheet document. XSpreadsheets xspreadsheets = xspreadsheetdocument.getSheets() ; // Get the index of the spreadsheet document. XIndexAccess xindexaccess = (XIndexAccess) UnoRuntime.queryInterface( XIndexAccess.class, xspreadsheets ); // Get the first spreadsheet. XSpreadsheet xspreadsheet = (XSpreadsheet) UnoRuntime.queryInterface( XSpreadsheet.class, xindexaccess.getByIndex(0)); // The double array will written to the spreadsheet for ( int intY = 0; intY < stringValues.length; intY++ ) { for ( int intX = 0; intX < stringValues[ intY ].length; intX++ ) { // Insert the value to the cell, specified by intY and intX. this.insertIntoCell( intY, intX, stringValues[ intY ][ intX ], xspreadsheet, "" ); } } // Create a rectangle, which holds the size of the chart. Rectangle rectangle = new Rectangle(); rectangle.X = 500; rectangle.Y = 3000; rectangle.Width = 25000; rectangle.Height = 11000; // Get the cell range of the spreadsheet. XCellRange xcellrange = ( XCellRange ) UnoRuntime.queryInterface( XCellRange.class, xspreadsheet ); // Create the Unicode of the character for the column name. char charRectangle = ( char ) ( 65 + stringValues.length - 1 ); // Get maximum length all rows in the double array. int intMaximumWidthRow = 0; for ( int intRow = 0; intRow < stringValues.length; intRow++ ) { if ( stringValues[ intRow ].length > intMaximumWidthRow ) { intMaximumWidthRow = stringValues[ intRow ].length; } } // Get the cell range of the written values. XCellRange xcellrangeChart = xcellrange.getCellRangeByName( "A1:" + charRectangle + intMaximumWidthRow ); // Get the addressable cell range. XCellRangeAddressable xcellrangeaddressable = ( XCellRangeAddressable ) UnoRuntime.queryInterface( XCellRangeAddressable.class, xcellrangeChart ); // Get the cell range address. CellRangeAddress cellrangeaddress = xcellrangeaddressable.getRangeAddress(); // Create the cell range address for the chart. CellRangeAddress[] cellrangeaddressChart = new CellRangeAddress[ 1 ]; cellrangeaddressChart[ 0 ] = cellrangeaddress; // Get the table charts supplier of the spreadsheet. XTableChartsSupplier xtablechartssupplier = ( XTableChartsSupplier ) UnoRuntime.queryInterface( XTableChartsSupplier.class, xspreadsheet ); // Get all table charts of the spreadsheet. XTableCharts xtablecharts = xtablechartssupplier.getCharts(); // Create a table chart with all written values. xtablecharts.addNewByName( "Example", rectangle, cellrangeaddressChart, true, true ); // Get the created table chart. this.xtablechart = ( XTableChart ) UnoRuntime.queryInterface( XTableChart.class, (( XNameAccess ) UnoRuntime.queryInterface( XNameAccess.class, xtablecharts ) ).getByName( "Example" )); } catch( Exception exception ) { System.err.println( exception ); } } /** Inserting a given value to a cell, that is specified by the parameters intX * and intY. * @param intX Column on the spreadsheet. * @param intY Row on the spreadsheet. * @param stringValue Value to be inserted to a cell. * @param xspreadsheet Spreadsheet of the cell, which will be changed. * @param stringFlag If the value of stringFlag is "V", the stringValue * will be converted to the * float type. Otherwise the stringValue will be written as a formula. */ public static void insertIntoCell( int intX, int intY, String stringValue, XSpreadsheet xspreadsheet, String stringFlag ) { XCell xcell = null; try { xcell = xspreadsheet.getCellByPosition( intX, intY ); } catch ( com.sun.star.lang.IndexOutOfBoundsException exception ) { System.out.println( "Could not get cell." ); } if ( stringFlag.equals( "V" ) ) { xcell.setValue( ( new Float( stringValue ) ).floatValue() ); } else { xcell.setFormula( stringValue ); } } }
package io.datakernel.ot; import com.google.common.base.Joiner; import com.google.gson.TypeAdapter; import io.datakernel.utils.GsonAdapters; import io.datakernel.utils.JsonException; import javax.sql.DataSource; import java.sql.*; import java.util.*; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutorService; import static io.datakernel.eventloop.Eventloop.getCurrentEventloop; import static io.datakernel.utils.GsonAdapters.indent; import static io.datakernel.utils.GsonAdapters.ofList; import static java.util.Collections.nCopies; import static java.util.Collections.singletonList; public class OTRemoteSql<D> implements OTRemote<Integer, D> { public static final String TABLE_REVISION = "ot_revision"; public static final String TABLE_DIFFS = "ot_diffs"; private final ExecutorService executor; private final DataSource dataSource; private final TypeAdapter<List<D>> diffsAdapter; private final String tableRevision; private final String tableDiffs; private final String scope; private final String createdBy; private OTRemoteSql(ExecutorService executor, TypeAdapter<List<D>> diffsAdapter, DataSource dataSource, String tableRevision, String tableDiffs, String scope, String createdBy) { this.executor = executor; this.dataSource = dataSource; this.diffsAdapter = diffsAdapter; this.tableRevision = tableRevision; this.tableDiffs = tableDiffs; this.scope = scope; this.createdBy = createdBy; } public static <D> OTRemoteSql<D> create(ExecutorService executor, DataSource dataSource, TypeAdapter<D> diffAdapter) { return new OTRemoteSql<>(executor, indent(ofList(diffAdapter), "\t"), dataSource, TABLE_REVISION, TABLE_DIFFS, null, null); } public OTRemoteSql<D> withScope(String scope) { return new OTRemoteSql<>(executor, diffsAdapter, dataSource, tableRevision, tableDiffs, scope, createdBy); } public OTRemoteSql<D> withCreatedBy(String createdBy) { return new OTRemoteSql<>(executor, diffsAdapter, dataSource, tableRevision, tableDiffs, scope, createdBy); } public OTRemoteSql<D> withTables(String tableRevision, String tableDiffs) { return new OTRemoteSql<>(executor, diffsAdapter, dataSource, tableRevision, tableDiffs, scope, createdBy); } private String sql(String sql) { if (scope == null) { sql = sql.replace("scope=?", "NULL IS ?"); } return sql .replace(TABLE_REVISION, tableRevision) .replace(TABLE_DIFFS, tableDiffs); } public void truncateTables() throws SQLException { try (Connection connection = dataSource.getConnection()) { Statement statement = connection.createStatement(); statement.execute(sql("TRUNCATE TABLE ot_diffs")); statement.execute(sql("TRUNCATE TABLE ot_revisions")); } } @Override public CompletionStage<Integer> createId() { return getCurrentEventloop().callConcurrently(executor, () -> { try (Connection connection = dataSource.getConnection()) { connection.setAutoCommit(true); try (PreparedStatement statement = connection.prepareStatement( sql("INSERT INTO ot_revisions(scope, type, created_by) VALUES (?, ?, ?)"), Statement.RETURN_GENERATED_KEYS)) { statement.setString(1, scope); statement.setString(2, "NEW"); statement.setString(3, createdBy); statement.executeUpdate(); ResultSet generatedKeys = statement.getGeneratedKeys(); generatedKeys.next(); return generatedKeys.getInt(1); } } }); } private String toJson(List<D> diffs) throws JsonException { return GsonAdapters.toJson(diffsAdapter, diffs); } @SuppressWarnings("unchecked") private List<D> fromJson(String json) throws JsonException { return GsonAdapters.fromJson(diffsAdapter, json); } public CompletionStage<Void> push(OTCommit<Integer, D> commit) { return push(singletonList(commit)); } @Override public CompletionStage<Void> push(List<OTCommit<Integer, D>> commits) { return getCurrentEventloop().runConcurrentlyWithException(executor, () -> { try (Connection connection = dataSource.getConnection()) { connection.setAutoCommit(false); for (int i = 0; i < commits.size(); i++) { OTCommit<Integer, D> commit = commits.get(i); try (PreparedStatement ps = connection.prepareStatement(sql("" + "INSERT INTO ot_revisions (scope, id, type, checkpoint) VALUES (?, ?, ?, ?) " + "ON DUPLICATE KEY UPDATE " + "scope = values(scope)," + "type = values(type)," + "checkpoint = values(checkpoint)"))) { ps.setString(1, scope); ps.setInt(2, commit.getId()); ps.setString(3, (i == commits.size() - 1) ? "HEAD" : "INNER"); ps.setString(4, commit.getCheckpoint() == null ? null : toJson(commit.getCheckpoint())); ps.executeUpdate(); } for (Map.Entry<Integer, List<D>> entry : commit.getParents().entrySet()) { Integer parentId = entry.getKey(); List<D> diff = entry.getValue(); try (PreparedStatement ps = connection.prepareStatement( sql("INSERT INTO ot_diffs(scope, revision_id, parent_id, diff) VALUES (?, ?, ?, ?)"))) { ps.setString(1, scope); ps.setInt(2, commit.getId()); ps.setInt(3, parentId); ps.setString(4, toJson(diff)); ps.executeUpdate(); } } } Set<Integer> parents = commits.get(0).getParents().keySet(); if (!parents.isEmpty()) { try (PreparedStatement ps = connection.prepareStatement( sql("UPDATE ot_revisions SET type='INNER' WHERE scope=?" + " AND id IN (" + Joiner.on(",").join(nCopies(parents.size(), "?")) + ")"))) { ps.setString(1, scope); int pos = 2; for (Integer parent : parents) { ps.setInt(pos++, parent); } ps.executeUpdate(); } } connection.commit(); } }); } @Override public CompletionStage<Set<Integer>> getHeads() { return getCurrentEventloop().callConcurrently(executor, () -> { try (Connection connection = dataSource.getConnection()) { try (PreparedStatement ps = connection.prepareStatement( sql("SELECT id FROM ot_revisions WHERE scope=? AND type='HEAD'"))) { ps.setString(1, scope); ResultSet resultSet = ps.executeQuery(); Set<Integer> result = new HashSet<>(); while (resultSet.next()) { int id = resultSet.getInt(1); result.add(id); } return result; } } }); } @Override public CompletionStage<Integer> getCheckpoint() { return getCurrentEventloop().callConcurrently(executor, () -> { try (Connection connection = dataSource.getConnection()) { try (PreparedStatement ps = connection.prepareStatement( sql("SELECT MAX(id) FROM ot_revisions WHERE scope=? AND checkpoint IS NOT NULL"))) { ps.setString(1, scope); ResultSet resultSet = ps.executeQuery(); if (resultSet.next()) { return resultSet.getInt(1); } throw new IllegalStateException("Could not find checkpoint"); } } }); } @Override public CompletionStage<OTCommit<Integer, D>> loadCommit(Integer revisionId) { return getCurrentEventloop().callConcurrently(executor, () -> { try (Connection connection = dataSource.getConnection()) { List<D> checkpoint = null; try (PreparedStatement ps = connection.prepareStatement( sql("SELECT checkpoint FROM ot_revisions WHERE scope=? AND id=?"))) { ps.setString(1, scope); ps.setInt(2, revisionId); ResultSet resultSet = ps.executeQuery(); if (!resultSet.next()) throw new IllegalArgumentException(); String checkpointString = resultSet.getString(1); if (checkpointString != null) checkpoint = fromJson(checkpointString); } Map<Integer, List<D>> parentDiffs = new HashMap<>(); try (PreparedStatement ps = connection.prepareStatement( sql("SELECT parent_id, diff FROM ot_diffs WHERE scope=? AND revision_id=?"))) { ps.setString(1, scope); ps.setInt(2, revisionId); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { int parentId = resultSet.getInt(1); String diffString = resultSet.getString(2); List<D> diff = fromJson(diffString); parentDiffs.put(parentId, diff); } } return OTCommit.of(revisionId, checkpoint, parentDiffs); } }); } }
package JUnitTests; import static org.junit.Assert.*; import org.junit.*; import FunktioLaskin.Laskin; public class LaskinTest { private static Laskin laskin = new Laskin(); @Before public void setUp() throws Exception { System.out.println("Laskin nollataan aina ennen testiä" + laskin.annaTulos()); laskin.nollaa(); } @After public void tearDown() throws Exception { } @Test public void nollaa() throws Exception { System.out.println("Laskintesti nollaa"); laskin.nollaa(); assertTrue(laskin.annaTulos() == 0); } @Test public void lisaa() throws Exception { System.out.println("Laskintesti lisaa"); laskin.lisaa(5); assertEquals(5, laskin.annaTulos(), 0); laskin.nollaa(); laskin.lisaa(0.5); assertEquals(0.5, laskin.annaTulos(), 0); } @Test public void vahenna() throws Exception { System.out.println("Laskintesti vahenna"); laskin.vahenna(5); assertEquals(-5, laskin.annaTulos(), 0); laskin.nollaa(); laskin.vahenna(0.5); assertEquals(-0.5, laskin.annaTulos(), 0); } @Test public void kerro() throws Exception { System.out.println("Laskintesti kerro"); laskin.kerro(5); assertEquals(0, laskin.annaTulos(), 0); laskin.nollaa(); laskin.lisaa(5); laskin.kerro(-5); assertEquals(-25, laskin.annaTulos(), 0); laskin.kerro(0.5); assertEquals(-12.5, laskin.annaTulos(), 0); } @Test public void jaa() throws Exception { System.out.println("Laskintesti jaa"); laskin.jaa(5); assertEquals(0, laskin.annaTulos(), 0); laskin.nollaa(); laskin.lisaa(5); laskin.jaa(-5); assertEquals(-1, laskin.annaTulos(), 0); laskin.jaa(0.5); assertEquals(-2, laskin.annaTulos(), 0); } @Test public void nelio() throws Exception { System.out.println("Laskintesti neliö"); laskin.nelio(5); assertEquals(25, laskin.annaTulos(), 0); laskin.nelio(-5); assertEquals(25, laskin.annaTulos(), 0); laskin.nelio(0.5); assertEquals(0.25, laskin.annaTulos(), 0); } @Test public void neliojuuri() throws Exception { System.out.println("Laskintesti neliöjuuri"); laskin.neliojuuri(5); assertEquals(2.24, laskin.annaTulos(), 0.1); laskin.neliojuuri(-5); assertEquals(0.0, laskin.annaTulos(), 0.1); laskin.neliojuuri(0.5); assertEquals(0.71, laskin.annaTulos(), 0.1); } @Test public void edellinen() throws Exception { laskin.lisaa(5); laskin.edellinen(); assertEquals(0, laskin.annaTulos(), 0); laskin.lisaa(5); laskin.lisaa(5); laskin.edellinen(); assertEquals(5, laskin.annaTulos(), 0); } @Test public void potenssi() throws Exception { System.out.println("Laskintesti potenssi"); laskin.lisaa(5); laskin.potenssi(0); assertEquals(1, laskin.annaTulos(), 0); laskin.nollaa(); laskin.lisaa(3.5); laskin.potenssi(3); assertEquals(42.875, laskin.annaTulos(), 0); laskin.nollaa(); laskin.lisaa(5); laskin.potenssi(-2); assertEquals(0.04, laskin.annaTulos(), 0); laskin.nollaa(); laskin.lisaa(-5); laskin.potenssi(3); assertEquals(-125, laskin.annaTulos(), 0); laskin.nollaa(); } @Test public void sin() throws Exception { laskin.sin(15); assertEquals(0.26, laskin.annaTulos(), 0.1); laskin.sin(-15); assertEquals(-0.26, laskin.annaTulos(), 0.1); } @Test public void cos() throws Exception { laskin.cos(15); assertEquals(0.96, laskin.annaTulos(), 0.1); laskin.cos(-15); assertEquals(0.96, laskin.annaTulos(), 0.1); } @Test public void tan() throws Exception { laskin.tan(15); assertEquals(0.27, laskin.annaTulos(), 0.1); laskin.tan(-15); assertEquals(-0.27, laskin.annaTulos(), 0.1); } /* @BeforeClass public void virtaON() throws Exception { } @AfterClass public void virtaOFF() throws Exception { } */ }
package org.xbill.DNS; import java.util.*; import org.xbill.DNS.utils.*; /** * Constants and functions relating to DNSSEC (algorithm constants). * DNSSEC provides authentication for DNS information. RRsets are * signed by an appropriate key, and a SIG record is added to the set. * A KEY record is obtained from DNS and used to validate the signature, * The KEY record must also be validated or implicitly trusted - to * validate a key requires a series of validations leading to a trusted * key. The key must also be authorized to sign the data. * @see SIGRecord * @see KEYRecord * @see RRset * * @author Brian Wellington */ public class DNSSEC { public static class Algorithm { public static final int RSAMD5 = 1; public static final int RSA = RSAMD5; public static final int DH = 2; public static final int DSA = 3; public static final int ECC = 4; public static final int RSASHA1 = 5; public static final int INDIRECT = 252; public static final int PRIVATEDNS = 253; public static final int PRIVATEOID = 254; private static Mnemonic algs = new Mnemonic("DNSSEC algorithm", Mnemonic.CASE_UPPER); static { algs.setMaximum(0xFF); algs.setNumericAllowed(true); algs.add(RSAMD5, "RSAMD5"); algs.add(DH, "DH"); algs.add(DSA, "DSA"); algs.add(ECC, "ECC"); algs.add(RSASHA1, "RSASHA1"); algs.add(INDIRECT, "INDIRECT"); algs.add(PRIVATEDNS, "PRIVATEDNS"); algs.add(PRIVATEOID, "PRIVATEOID"); } /** * Converts an algorithm into its textual representation */ public static String string(int alg) { return algs.getText(alg); } /** * Converts a textual representation of an algorithm into its numeric * code. Integers in the range 0..255 are also accepted. * @param s The textual representation of the algorithm * @return The algorithm code, or -1 on error. */ public static int value(String s) { return algs.getValue(s); } } public static final int RSAMD5 = Algorithm.RSAMD5; public static final int RSA = Algorithm.RSAMD5; public static final int DH = Algorithm.DH; public static final int DSA = Algorithm.DSA; public static final int RSASHA1 = Algorithm.RSASHA1; public static final int Failed = -1; public static final int Insecure = 0; public static final int Secure = 1; private DNSSEC() { } private static void digestSIG(DataByteOutputStream out, SIGRecord sig) { out.writeShort(sig.getTypeCovered()); out.writeByte(sig.getAlgorithm()); out.writeByte(sig.getLabels()); out.writeUnsignedInt(sig.getOrigTTL()); out.writeInt((int) (sig.getExpire().getTime() / 1000)); out.writeInt((int) (sig.getTimeSigned().getTime() / 1000)); out.writeShort(sig.getFootprint()); sig.getSigner().toWireCanonical(out); } /** * Creates an array containing fields of the SIG record and the RRsets to * be signed/verified. * @param sig The SIG record used to sign/verify the rrset. * @param rrset The data to be signed/verified. * @return The data to be cryptographically signed or verified. */ public static byte [] digestRRset(SIGRecord sig, RRset rrset) { DataByteOutputStream out = new DataByteOutputStream(); digestSIG(out, sig); int size = rrset.size(); byte [][] records = new byte[size][]; Iterator it = rrset.rrs(); Name name = rrset.getName(); Name wild = null; if (name.labels() > sig.getLabels()) wild = name.wild(name.labels() - sig.getLabels()); while (it.hasNext()) { Record rec = (Record) it.next(); if (wild != null) rec = rec.withName(wild); records[--size] = rec.toWireCanonical(); } Arrays.sort(records); for (int i = 0; i < records.length; i++) out.writeArray(records[i]); return out.toByteArray(); } /** * Creates an array containing fields of the SIG record and the message to * be signed. * @param sig The SIG record used to sign/verify the rrset. * @param msg The message to be signed/verified. * @param previous If this is a response, the signature from the query. * @return The data to be cryptographically signed or verified. */ public static byte [] digestMessage(SIGRecord sig, Message msg, byte [] previous) { DataByteOutputStream out = new DataByteOutputStream(); digestSIG(out, sig); if (previous != null) out.writeArray(previous); msg.toWire(out); return out.toByteArray(); } }
package org.xbill.DNS; import java.io.*; /** * A DNS master file parser. This incrementally parses the file, returning * one record at a time. When directives are seen, they are added to the * state and used when parsing future records. * * @author Brian Wellington */ public class Master { private Name origin; private File file; private Record last = null; private long defaultTTL; private Master included = null; private Tokenizer st; Master(File file, Name initialOrigin, long initialTTL) throws IOException { FileInputStream fis; this.file = file; st = new Tokenizer(file); origin = initialOrigin; defaultTTL = initialTTL; } /** * Initializes the master file reader and opens the specified master file. * @param filename The master file. * @param origin The initial origin to append to relative names. * @param ttl The initial default TTL. * @throws IOException The master file could not be opened. */ public Master(String filename, Name origin, long ttl) throws IOException { this(new File(filename), origin, ttl); } /** * Initializes the master file reader and opens the specified master file. * @param filename The master file. * @param origin The initial origin to append to relative names. * @throws IOException The master file could not be opened. */ public Master(String filename, Name origin) throws IOException { this(new File(filename), origin, -1); } /** * Initializes the master file reader and opens the specified master file. * @param filename The master file. * @throws IOException The master file could not be opened. */ public Master(String filename) throws IOException { this(new File(filename), null, -1); } /** * Initializes the master file reader. * @param in The input stream containing a master file. * @param origin The initial origin to append to relative names. * @param ttl The initial default TTL. */ public Master(InputStream in, Name origin, long ttl) { st = new Tokenizer(in); this.origin = origin; defaultTTL = ttl; } /** * Initializes the master file reader. * @param in The input stream containing a master file. * @param origin The initial origin to append to relative names. */ public Master(InputStream in, Name origin) { this(in, origin, -1); } /** * Initializes the master file reader. * @param in The input stream containing a master file. */ public Master(InputStream in) { this(in, null, -1); } private Name parseName(String s, Name origin) throws TextParseException { try { return Name.fromString(s, origin); } catch (TextParseException e) { throw st.exception(e.getMessage()); } } /** * Returns the next record in the master file. This will process any * directives before the next record. * @return The next record. * @throws IOException The master file could not be read, or was syntactically * invalid. */ public Record nextRecord() throws IOException { Tokenizer.Token token; String s; if (included != null) { Record rec = included.nextRecord(); if (rec != null) return rec; included = null; } while (true) { Name name; long ttl; int type, dclass; token = st.get(true, false); if (token.type == Tokenizer.WHITESPACE) { Tokenizer.Token next = st.get(); if (token.type == Tokenizer.EOL) continue; else if (token.type == Tokenizer.EOF) return null; else st.unget(); if (last == null) throw st.exception("no owner"); name = last.getName(); } else if (token.type == Tokenizer.EOL) continue; else if (token.type == Tokenizer.EOF) return null; else if (((String) token.value).charAt(0) == '$') { s = token.value; if (s.equalsIgnoreCase("$ORIGIN")) { origin = st.getName(Name.root); st.getEOL(); continue; } else if (s.equalsIgnoreCase("$TTL")) { defaultTTL = st.getTTL(); st.getEOL(); continue; } else if (s.equalsIgnoreCase("$INCLUDE")) { String filename = st.getString(); String parent = file.getParent(); File newfile = new File(file.getParent(), filename); Name incorigin = origin; token = st.get(); if (token.isString()) { incorigin = parseName(token.value, Name.root); st.getEOL(); } included = new Master(newfile, incorigin, defaultTTL); /* * If we continued, we wouldn't be looking in * the new file. Recursing works better. */ return nextRecord(); } else { throw st.exception("Invalid directive: " + s); } } else { s = token.value; name = parseName(s, origin); } s = st.getString(); try { ttl = TTL.parseTTL(s); s = st.getString(); } catch (NumberFormatException e) { if (last == null && defaultTTL < 0) throw st.exception("missing TTL"); else if (defaultTTL >= 0) ttl = (int) defaultTTL; else ttl = last.getTTL(); } if ((dclass = DClass.value(s)) > 0) s = st.getString(); else dclass = DClass.IN; if ((type = Type.value(s)) < 0) throw st.exception("Invalid type '" + s + "'"); last = Record.fromString(name, type, dclass, ttl, st, origin); return last; } } }
package org.xbill.DNS; import java.io.*; import java.lang.reflect.*; import java.util.*; import org.xbill.DNS.utils.*; /** * The base class that all records are derived from. * * @author Brian Wellington */ abstract public class Record implements Cloneable { protected Name name; protected short type, dclass; protected int ttl; protected int wireLength = -1; private static Class [] knownTypes = new Class[256]; private static Class [] fromWireList = new Class [] {Name.class, Short.TYPE, Integer.TYPE, Integer.TYPE, DataByteInputStream.class, Compression.class}; private static Class [] fromTextList = new Class [] {Name.class, Short.TYPE, Integer.TYPE, MyStringTokenizer.class, Name.class}; protected Record() {} Record(Name _name, short _type, short _dclass, int _ttl) { name = _name; type = _type; dclass = _dclass; ttl = _ttl; } private static final Class toClass(short type) throws ClassNotFoundException { /* * First, see if we've already found this type. */ if (type < 0 || type > 255) throw new ClassNotFoundException(); if (knownTypes[type] != null) return knownTypes[type]; String s = Record.class.toString(); /* * Remove "class " from the beginning, and "Record" from the end. * Then construct the new class name. */ knownTypes[type] = Class.forName(s.substring(6, s.length() - 6) + Type.string(type) + "Record"); return knownTypes[type]; } private static Record newRecord(Name name, short type, short dclass, int ttl, int length, DataByteInputStream in, Compression c) throws IOException { Record rec; try { Class rrclass; Constructor m; rrclass = toClass(type); m = rrclass.getDeclaredConstructor(fromWireList); rec = (Record) m.newInstance(new Object [] { name, new Short(dclass), new Integer(ttl), new Integer(length), in, c }); rec.wireLength = length; return rec; } catch (ClassNotFoundException e) { rec = new UNKRecord(name, type, dclass, ttl, length, in, c); rec.wireLength = length; return rec; } catch (InvocationTargetException e) { if (Options.check("verbose")) { System.err.println("new record: " + e); System.err.println(e.getTargetException()); } return null; } catch (Exception e) { if (Options.check("verbose")) System.err.println("new record: " + e); return null; } } /** * Creates a new record, with the given parameters. * @return An object of a type extending Record */ public static Record newRecord(Name name, short type, short dclass, int ttl, int length, byte [] data) { DataByteInputStream dbs; if (data != null) dbs = new DataByteInputStream(data); else dbs = null; try { return newRecord(name, type, dclass, ttl, length, dbs, null); } catch (IOException e) { return null; } } /** * Creates a new empty record, with the given parameters. * @return An object of a type extending Record */ public static Record newRecord(Name name, short type, short dclass, int ttl) { return newRecord(name, type, dclass, ttl, 0, null); } /** * Creates a new empty record, with the given parameters. This method is * designed to create records that will be added to the QUERY section * of a message. * @return An object of a type extending Record */ public static Record newRecord(Name name, short type, short dclass) { return newRecord(name, type, dclass, 0, 0, null); } static Record fromWire(DataByteInputStream in, int section, Compression c) throws IOException { short type, dclass; int ttl; short length; Name name; Record rec; int start, datastart; start = in.getPos(); name = new Name(in, c); type = in.readShort(); dclass = in.readShort(); if (section == Section.QUESTION) return newRecord(name, type, dclass); ttl = in.readInt(); length = in.readShort(); if (length == 0) return newRecord(name, type, dclass, ttl); datastart = in.getPos(); rec = newRecord(name, type, dclass, ttl, length, in, c); if (in.getPos() - datastart != length) throw new IOException("Invalid record length"); rec.wireLength = in.getPos() - start; return rec; } /** * Builds a Record from DNS uncompressed wire format. */ public static Record fromWire(byte [] b, int section) throws IOException { DataByteInputStream in = new DataByteInputStream(b); return fromWire(in, section, null); } void toWire(DataByteOutputStream out, int section, Compression c) throws IOException { int start = out.getPos(); name.toWire(out, c); out.writeShort(type); out.writeShort(dclass); if (section == Section.QUESTION) return; out.writeInt(ttl); int lengthPosition = out.getPos(); out.writeShort(0); /* until we know better */ rrToWire(out, c); out.writeShortAt(out.getPos() - lengthPosition - 2, lengthPosition); wireLength = out.getPos() - start; } /** * Converts a Record into DNS uncompressed wire format. */ public byte [] toWire(int section) throws IOException { DataByteOutputStream out = new DataByteOutputStream(); toWire(out, section, null); return out.toByteArray(); } void toWireCanonical(DataByteOutputStream out) throws IOException { name.toWireCanonical(out); out.writeShort(type); out.writeShort(dclass); out.writeInt(ttl); int lengthPosition = out.getPos(); out.writeShort(0); /* until we know better */ rrToWireCanonical(out); out.writeShortAt(out.getPos() - lengthPosition - 2, lengthPosition); } /** * Converts a Record into canonical DNS uncompressed wire format (all names are * converted to lowercase). */ public byte [] toWireCanonical() throws IOException { DataByteOutputStream out = new DataByteOutputStream(); toWireCanonical(out); return out.toByteArray(); } public abstract String rdataToString(); /** * Converts a Record into a String representation */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append(name); sb.append("\t"); if (Options.check("BINDTTL")) sb.append(TTL.format(ttl)); else sb.append((long)ttl & 0xFFFFFFFFL); sb.append(" "); if (dclass != DClass.IN || !Options.check("noPrintIN")) { sb.append(DClass.string(dclass)); sb.append(" "); } sb.append(Type.string(type)); sb.append("\t\t"); if (wireLength != 0) sb.append(rdataToString()); return sb.toString(); } /** * Builds a new Record from its textual representation */ public static Record fromString(Name name, short type, short dclass, int ttl, MyStringTokenizer st, Name origin) throws IOException { Record rec; String s = st.nextToken(); /* the string tokenizer loses the \\. */ if (s.equals(" s = st.nextToken(); short length = Short.parseShort(s); s = st.remainingTokens(); byte [] data = base16.fromString(s); if (length != data.length) throw new IOException("Invalid unknown RR encoding: length mismatch"); return newRecord(name, type, dclass, ttl, length, data); } st.putBackToken(s); try { Class rrclass; Constructor m; rrclass = toClass(type); m = rrclass.getDeclaredConstructor(fromTextList); rec = (Record) m.newInstance(new Object [] { name, new Short(dclass), new Integer(ttl), st, origin }); return rec; } catch (ClassNotFoundException e) { rec = new UNKRecord(name, type, dclass, ttl, st, origin); return rec; } catch (InvocationTargetException e) { if (Options.check("verbose")) { System.err.println("from text: " + e); System.err.println(e.getTargetException()); } return null; } catch (Exception e) { if (Options.check("verbose")) System.err.println("from text: " + e); return null; } } /** * Returns the record's name * @see Name */ public Name getName() { return name; } /** * Returns record's type * @see Type */ public short getType() { return type; } /** * Returns the type of RRset that this record would belong to. For all types * except SIGRecord, this is equivalent to getType(). * @return The type of record, if not SIGRecord. If the type is SIGRecord, * the type covered is returned. * @see Type * @see RRset * @see SIGRecord */ public short getRRsetType() { if (type == Type.SIG) { SIGRecord sig = (SIGRecord) this; return sig.getTypeCovered(); } return type; } /** * Returns the record's class */ public short getDClass() { return dclass; } /** * Returns the record's TTL */ public int getTTL() { return ttl; } /** * Returns the length of this record in wire format, based on the last time * this record was parsed from data or converted to data. The wire format * may or may not be compressed * @return The last known length, or -1 if the record has never been in wire * format */ public short getWireLength() { return (short) wireLength; } /** * Converts the type-specific RR to wire format - must be overriden */ abstract void rrToWire(DataByteOutputStream out, Compression c) throws IOException; /** * Converts the type-specific RR to canonical wire format - must be overriden * if the type-specific RR data includes a Name * @see Name */ void rrToWireCanonical(DataByteOutputStream out) throws IOException { rrToWire(out, null); } /** * Determines if two Records are identical */ public boolean equals(Object arg) { if (arg == null || !(arg instanceof Record)) return false; Record r = (Record) arg; try { byte [] array1 = toWire(Section.ANSWER); byte [] array2 = r.toWire(Section.ANSWER); if (array1.length != array2.length) return false; for (int i = 0; i < array1.length; i++) if (array1[i] != array2[i]) return false; return true; } catch (IOException e) { return false; } } /** * Generates a hash code based on the Record's data */ public int hashCode() { try { byte [] array1 = toWire(Section.ANSWER); return array1.hashCode(); } catch (IOException e) { return 0; } } /** * Creates a new record identical to the current record, but with a different * name. This is most useful for replacing the name of a wildcard record. */ public Record withName(Name name) { Record rec = null; try { rec = (Record) clone(); } catch (CloneNotSupportedException e) { } rec.name = name; return rec; } }
package com.healthfortis.map.shared.client.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.google.gwt.core.client.Callback; import com.google.gwt.core.client.JavaScriptException; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.core.client.ScriptInjector; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.DomEvent; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.dom.client.MouseUpEvent; import com.google.gwt.event.dom.client.MouseUpHandler; import com.google.gwt.json.client.JSONBoolean; import com.google.gwt.json.client.JSONNumber; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONString; import com.google.gwt.json.client.JSONValue; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.TextArea; public class HFRichTextEditor extends TextArea { public static final int TINYMCE_VERSION_3 = 3; public static final int TINYMCE_VERSION_4 = 4; public static final int DEFAULT_HEIGHT = 72; public static final int DEFAULT_WIDTH = 640; public static final int PENDING_COMMAND_UNLOAD = 0; public static final int PENDING_COMMAND_LOAD = 1; public static final int PENDING_COMMAND_SELECT_ALL = 2; public static final int PENDING_COMMAND_SET_HTML = 3; public static final int PENDING_COMMAND_SET_FOCUS = 4; public static int libraryVersion = TINYMCE_VERSION_4; // select which version of the library to load at runtime. private static boolean libraryLoaded = false; private static final String DEFAULT_ELEMENT_ID = "hfRichTextEditor"; private static HashMap<String, HFRichTextEditor> activeEditors; // stores a mapping of elementId => instances of HFRichTextEditor static { activeEditors = new HashMap<String, HFRichTextEditor>(); } private ArrayList<Integer> pendingCommands = new ArrayList<Integer>(); // handle multiple onLoad and unUnload events in succession @SuppressWarnings("rawtypes") private Set fixedOptions = new HashSet(2); // options that can not be overwritten private JSONObject options = new JSONObject(); // all other TinyMCE options private boolean initialized = false; private boolean initializing = false; private String elementId; private boolean focused; private SafeHtml pendingSetHtmlText = null; private static int numInitialized = 1; // start the count at "1" private Timer initializationTimeoutTimer = null; public HFRichTextEditor() { this(DEFAULT_ELEMENT_ID); } @SuppressWarnings({ "unchecked", "rawtypes" }) public HFRichTextEditor(String elementId, Map presetOptions) { // NOTE: Do NOT use GWT's debug id scheme. This includes UIObject.ensureDebugId and the debugId property of the UI Binder. // Doing so will prevent the ID from working and this widget from being recognized properly. this.elementId = generateUniqueName(elementId); ++numInitialized; activeEditors.put(this.elementId, this); getElement().setId(this.elementId); getElement().addClassName(this.elementId); // fixed attributes addOption("selector", "textarea." + this.elementId); fixedOptions.addAll(options.keySet()); // load preset if (presetOptions == null) { applyPreset(HFRichTextEditorPreset.getAdvancedOptions()); } else { applyPreset(presetOptions); } //Add handlers to support method isFocused() addFocusHandler(new FocusHandler() { @Override public void onFocus(FocusEvent event) { focused = true; } }); addBlurHandler(new BlurHandler() { @Override public void onBlur(BlurEvent event) { focused = false; } }); final HFRichTextEditor me = this; addMouseUpHandler(new MouseUpHandler() { @Override public void onMouseUp(MouseUpEvent event) { setBookmarkPosition(me.elementId); } }); addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { restoreBookmarkPosition(me.elementId); } }); addKeyDownHandler(new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent event) { setBookmarkPosition(me.elementId); } }); } public HFRichTextEditor(String elementId) { this(elementId, null); } /** * Returns the HFRichTextEditor instance associated with a particular elementId. Used mainly * by the handler code to make sure that we end up propagating the handler sources correctly. There's * probably a better way to do this. * * @param elementId The unique ID of the HFRichTextEditor * @return the HFRichTextEditor instance associated with the input elementId */ private static HFRichTextEditor getActiveEditor(String elementId) { if (elementId == null || elementId.trim().isEmpty() || !activeEditors.containsKey(elementId.toLowerCase().trim())) { return null; } return activeEditors.get(elementId.toLowerCase().trim()); } /* * Given a id string, it checks the activeEditors key set to make sure that * a unique name is generated. This is needed so that you don't instantiate * multiple editors with the same id (and thus not be able to address them * correctly in the javascript). */ private static String generateUniqueName(String id) { if (id == null || id.trim().isEmpty()) { return ""; } String usedNameKey = id.trim().toLowerCase(); while (true) { String testKey = usedNameKey + Integer.toString(numInitialized); testKey = testKey.trim().toLowerCase(); if (!activeEditors.keySet().contains(testKey)) { return testKey; } ++numInitialized; } } /** * Applies a set of options to the TinyMCE init method. This needs to be called prior to * init being called. * * @param optionsMap the list of options, usually generated from HFRichTextEditorPreset class. */ @SuppressWarnings("rawtypes") private void applyPreset(Map optionsMap) { for (Object optionKey : optionsMap.keySet()) { addOption((String) optionKey, optionsMap.get(optionKey)); } } /** * Add an option dynamically into the set of options that will be used by the init function * for TinyMCE. * * @param key a string value denoting the configuration parameter (see TinyMCE documentation) * @param value a value of Boolean, Integer, or String types. */ public void addOption(String key, Object value) { // do not allow overriding fixed options if (fixedOptions.contains(key)) { return; } if (value instanceof Boolean) { options.put(key, JSONBoolean.getInstance((Boolean) value)); } else if (value instanceof Integer) { options.put(key, new JSONNumber((Integer) value)); } else if (value instanceof String) { options.put(key, new JSONString((String) value)); } else { // Shouldn't ever really get to this, but just in case. options.put(key, new JSONString(value.toString())); } } private void addPendingCommand(int command) { pendingCommands.add(command); } private void addPendingLoad() { addPendingCommand(PENDING_COMMAND_LOAD); } private void addPendingUnload() { addPendingCommand(PENDING_COMMAND_UNLOAD); } private void addPendingSelectAll() { addPendingCommand(PENDING_COMMAND_SELECT_ALL); } private void addPendingSetHtml() { addPendingCommand(PENDING_COMMAND_SET_HTML); } private void addPendingSetFocus() { addPendingCommand(PENDING_COMMAND_SET_FOCUS); } @Override protected void onLoad() { super.onLoad(); // Delay the initialization of the TinyMCE editor until after the current browser loop. // This will avoid issues where there are multiple loads and unloads. addPendingLoad(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { runPendingCommand(); } }); } @Override protected void onUnload() { boolean deferUnloading = false; try { if (!uninitialize()) { addPendingUnload(); deferUnloading = true; } } catch (JavaScriptException e) { GWT.log("Unable to clean up TinyMCE editor.", e); } finally { if (!deferUnloading) { super.onUnload(); } } } private Timer getInitializationTimeoutTimer() { if (initializationTimeoutTimer == null) { initializationTimeoutTimer = new Timer() { @Override public void run() { setInitialized(false); setInitializing(false); // Clear the entry in activeEditors so that we don't hold the memory if it needs to be cleaned up. activeEditors.put(elementId, null); activeEditors.remove(elementId); // Run the pending commands to remove all the irrelevant ones runPendingCommand(); } }; } return initializationTimeoutTimer; } private boolean initialize() { try { if (!isInitialized() && !isInitializing()) { initTinyMce(elementId, options.getJavaScriptObject()); setInitializing(true); // set this after since the above call is asynchronous. We don't want it to be true and an exception to be thrown // Even though this entry was set in the constructor, it could have been unset // in the unload function. We ensure that we have a valid reference while this // editor is initialized activeEditors.put(elementId, this); getInitializationTimeoutTimer().schedule(1000); // give TinyMCE 1 second to initialize the editor return true; } } catch (JavaScriptException e) { GWT.log("Unable to initialize the TinyMCE editor.", e); } return false; } private boolean uninitialize() { if (isInitialized()) { try { unloadTinyMce(elementId); } catch (JavaScriptException e) { GWT.log("Unable to uninitialize the TinyMCE editor.", e); } finally { setInitialized(false); setInitializing(false); // Clear the entry in activeEditors so that we don't hold the memory if it needs to be cleaned up. activeEditors.put(elementId, null); activeEditors.remove(elementId); } return true; } return false; } private void runPendingCommand() { if (!libraryLoaded) { // Only perform operations specific to TinyMCE if the library was successfully loaded return; } if (isInitializing()) { return; } if (pendingCommands.isEmpty()) { return; } Integer pendingCommand = pendingCommands.get(0); while (pendingCommand != null) { try { if (pendingCommand == PENDING_COMMAND_LOAD) { if (!initialize()) { // Need to add the loading command back if it was unsuccessful. pendingCommands.add(0, PENDING_COMMAND_LOAD); } break; // we break because a load is asynchronous. We can't process any of the other commands until later. } if (!isInitialized() && !isInitializing()) { // If we're not initializing or already initialized, then all other commands (other than LOAD) are irrelevant. // We "continue" (but don't try and execute) to remove them from the pending queue. continue; } if (pendingCommand == PENDING_COMMAND_UNLOAD) { // This is a deferred onUnload call. uninitialize(); super.onUnload(); } else if (pendingCommand == PENDING_COMMAND_SELECT_ALL) { selectAll(); } else if (pendingCommand == PENDING_COMMAND_SET_HTML) { setHTML(pendingSetHtmlText); pendingSetHtmlText = null; } else if (pendingCommand == PENDING_COMMAND_SET_FOCUS) { if (focused) { setFocus(true); } } } finally { pendingCommand = null; pendingCommands.remove(0); if (!pendingCommands.isEmpty()) { pendingCommand = pendingCommands.get(0); } } } } private native void initTinyMce(String elementId, JavaScriptObject options) /*-{ $wnd.tinymce.init(options); }-*/; private native void unloadTinyMce(String elementId) public static boolean loadLibrary() { String scriptUrl = ""; if (libraryVersion == TINYMCE_VERSION_4) { scriptUrl = GWT.getModuleBaseURL() + "tinymce4/tinymce.min.js"; } else if (libraryVersion == TINYMCE_VERSION_3) { // scriptUrl = GWT.getModuleBaseURL() + "tinymce3/tiny_mce.js"; return false; // Security Audit found an issue with using eval. Removing from code base for now. 4.20.2015 } else { // No such version allowed. return false; } JavaScriptObject scriptInstance = ScriptInjector.fromUrl(scriptUrl) .setWindow(ScriptInjector.TOP_WINDOW) .setCallback(new Callback<Void, Exception>() { @Override public void onFailure(Exception reason) { Window.alert("TinyMCE failed to load."); libraryLoaded = false; } @Override public void onSuccess(Void result) { // We need to register the Javascript method that will handle all of the events. registerEventHandler(); libraryLoaded = true; } }).inject(); return (scriptInstance != null); } public static void setupCallback(String elementId) { // Add actions here to take after the setup of the editor is complete (usually when event handlers are added) } public static void initCallback(String elementId) { // Add actions here to take after the editor has been properly initialized. Usually, calls are made to the widget // such as setSize, setTabIndex - before the editor is initialized. We make those calls here to ensure that they // get set properly. final String elementIdFinal = elementId; Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { HFRichTextEditor editorInstance = getActiveEditor(elementIdFinal); if (editorInstance != null) { editorInstance.getInitializationTimeoutTimer().cancel(); // cancel the timer that will de-initialize this editor since we have initialized properly editorInstance.setControlTabIndex(elementIdFinal); // set up the tabIndex that comes from the hidden textarea (if it exists) JSONValue pxWidth = editorInstance.getOptions().get("width"); if (pxWidth == null) { pxWidth = new JSONNumber(DEFAULT_WIDTH); } JSONValue pxHeight = editorInstance.getOptions().get("height"); if (pxHeight == null) { pxHeight = new JSONNumber(DEFAULT_HEIGHT); } editorInstance.setControlSize(elementIdFinal, pxWidth, pxHeight); editorInstance.setInitialized(true); editorInstance.setInitializing(false); // Set it to visible if the parent is visible if (editorInstance.getParent() != null && editorInstance.getParent().isVisible()) { editorInstance.showEditor(editorInstance.elementId, true); } // If there were any pending unload commands, we run them here. editorInstance.runPendingCommand(); } } }); } /** * This gets called by the JSNI code for every event that we want to handle. * @param elementId the unique ID of the HFRichTextEditor. Used to locate the source of the event. * @param event the NativeEvent that we will fire into the GWT event handling loop */ public static void handleNativeEvent(String elementId, Object event) { if (event instanceof NativeEvent) { HFRichTextEditor editorInstance = getActiveEditor(elementId); if (editorInstance != null) { DomEvent.fireNativeEvent((NativeEvent) event, editorInstance); } } } /** * This is the native JavaScript code that will create the callbacks needed for integration between GWT and * TinyMCE library. It's called upon loading the library so that each time an editor is initialized, it can * call the appropriate callback functions to properly register all the handlers for that editor. */ private native static void registerEventHandler() /*-{ $wnd.hfrichtexteditorSetupCallback = $entry( function(e) { @com.healthfortis.map.shared.client.ui.HFRichTextEditor::setupCallback(Ljava/lang/String;)(e.id); e.on('mousedown', function(ev) { @com.healthfortis.map.shared.client.ui.HFRichTextEditor::handleNativeEvent(Ljava/lang/String;Ljava/lang/Object;)(e.id, ev); }); e.on('mouseup', function(ev) { @com.healthfortis.map.shared.client.ui.HFRichTextEditor::handleNativeEvent(Ljava/lang/String;Ljava/lang/Object;)(e.id, ev); }); e.on('keyup', function(ev) { @com.healthfortis.map.shared.client.ui.HFRichTextEditor::handleNativeEvent(Ljava/lang/String;Ljava/lang/Object;)(e.id, ev); }); e.on('keydown', function(ev) { @com.healthfortis.map.shared.client.ui.HFRichTextEditor::handleNativeEvent(Ljava/lang/String;Ljava/lang/Object;)(e.id, ev); // Prevent Ctrl+S from propagating to the TinyMCE editor. We don't want to save to external files. if (ev.ctrlKey || ev.metaKey) { switch (String.fromCharCode(ev.which || ev.keyCode).toLowerCase()) { case 's': ev.preventDefault(); if (ev.stopPropagation) { ev.stopPropagation(); } else { ev.cancelBubble = true; } break; } } }); e.on('keypress', function(ev) { @com.healthfortis.map.shared.client.ui.HFRichTextEditor::handleNativeEvent(Ljava/lang/String;Ljava/lang/Object;)(e.id, ev); }); e.on('blur', function(ev) { @com.healthfortis.map.shared.client.ui.HFRichTextEditor::handleNativeEvent(Ljava/lang/String;Ljava/lang/Object;)(e.id, ev); }); e.on('focus', function(ev) { @com.healthfortis.map.shared.client.ui.HFRichTextEditor::handleNativeEvent(Ljava/lang/String;Ljava/lang/Object;)(e.id, ev); }); e.on('click', function(ev) { @com.healthfortis.map.shared.client.ui.HFRichTextEditor::handleNativeEvent(Ljava/lang/String;Ljava/lang/Object;)(e.id, ev); }); } ); $wnd.hfrichtexteditorInitCallback = $entry( function(e) { @com.healthfortis.map.shared.client.ui.HFRichTextEditor::initCallback(Ljava/lang/String;)(e.id); } ); }-*/; public SafeHtml getHTML() { SafeHtml result = null; if (libraryLoaded && initialized) { try { String contentHtml = getContentHtml(elementId); // TinyMCE takes care of the sanitization. if (contentHtml == null || contentHtml.trim().isEmpty()) { return SafeHtmlUtils.fromSafeConstant(""); } // Remove the root block <p></p> that gets added automatically by TinyMCE if (contentHtml.startsWith("<p>") && contentHtml.endsWith("</p>")) { contentHtml = contentHtml.substring(3, contentHtml.length() - 4); } result = SafeHtmlUtils.fromTrustedString(contentHtml); } catch (JavaScriptException e) { GWT.log("Unable to get the content from the TinyMCE editor.", e); } } else { String text = super.getText(); if (text == null || text.trim().isEmpty()) { return SafeHtmlUtils.fromSafeConstant(""); } else { return SafeHtmlUtils.fromString(text); } } return result; } public String getText() { String result = ""; if (libraryLoaded && initialized) { try { String contentText = getContentText(elementId); if (contentText == null) { contentText = ""; } result = SafeHtmlUtils.fromString(contentText).asString(); // requested as text, so we need to escape the string } catch (JavaScriptException e) { GWT.log("Unable to get the content from the TinyMCE editor.", e); } } else { result = super.getText(); if (result == null || result.trim().isEmpty()) { result = ""; } else { result = SafeHtmlUtils.fromString(result).asString(); } } return result; } private native String getContentHtml(String elementId) /*-{ var myEditor = $wnd.tinymce.get(elementId); if (myEditor == null) { return ""; } $wnd.tinyMCE.triggerSave(); return myEditor.getContent(); }-*/; private native String getContentText(String elementId) /*-{ var myEditor = $wnd.tinymce.get(elementId); if (myEditor == null) { return ""; } $wnd.tinyMCE.triggerSave(); return myEditor.getContent({ format : "text" }); }-*/; public void setHTML(SafeHtml html) { String text = html == null ? null: html.asString(); if (libraryLoaded && (isInitialized() || isInitializing())) { if (isInitializing()) { pendingSetHtmlText = html; addPendingSetHtml(); return; } try { setContent(elementId, text); } catch (JavaScriptException e) { // Don't do anything, just allow it to return. GWT.log("Unable to set the content on the TinyMCE editor.", e); } return; } else { super.setText(text); } } /* * Will automatically escape the string and put it into the widget */ @Override public void setText(String text) { String htmlText = text == null ? "" : text; setHTML(SafeHtmlUtils.fromString(htmlText)); } private native String setContent(String elementId, String text) /*-{ var myEditor = $wnd.tinymce.get(elementId); if (myEditor != null) { myEditor.setContent(text); } }-*/; private native void setBookmarkPosition(String elementId) /*-{ var myEditor = $wnd.tinymce.get(elementId); if (myEditor == null) { return; } myEditor.updatedSelectionBookmark = myEditor.selection.getBookmark(1); }-*/; private native void restoreBookmarkPosition(String elementId) /*-{ var myEditor = $wnd.tinymce.get(elementId); if (myEditor == null) { return; } myEditor.updatedSelectionBookmark && myEditor.selection.moveToBookmark(myEditor.updatedSelectionBookmark); }-*/; @Override public void selectAll() { if (isInitializing()) { addPendingSelectAll(); } else if (!isInitialized()) { // It's not even initialized. We don't do anything. return; } // If it's properly initialized, then we do the select all. selectAllContent(elementId); } private native void selectAllContent(String elementId) /*-{ var myEditor = $wnd.tinymce.get(elementId); if (myEditor != null) { myEditor.selection.select(myEditor.getBody(), true); } }-*/; /** * Puts the text cursor at the beginning or end of the body text. * * @param atBeginning true if the cursor should be set at the beginning, false if at the end. */ public void setTextCursor(boolean atBeginning) { if (!isInitialized()) { // It's not even initialized. We don't do anything. return; } // If it's properly initialized, we first select all, then collapse the selection // to either the beginning or the end. selectAllContent(elementId); collapseSelection(elementId, atBeginning); } private native void collapseSelection(String elementId, boolean atBeginning) /*-{ var myEditor = $wnd.tinymce.get(elementId); if (myEditor != null) { myEditor.selection.collapse(atBeginning); } }-*/; @Override public String getSelectedText() { return getSelectedContent(elementId); } private native String getSelectedContent(String elementId) /*-{ var myEditor = $wnd.tinymce.get(elementId); if (myEditor != null) { return myEditor.selection.getContent(); } return ""; }-*/; private JSONValue parseSizeDimension(String dimension) { JSONValue pxDimension = new JSONNumber(0); if (dimension.endsWith("px")) { dimension = dimension.substring(0, dimension.length() - 2); pxDimension = new JSONNumber(Integer.parseInt(dimension.trim())); } else if (dimension.endsWith("em")) { dimension = dimension.substring(0, dimension.length() - 2); // 1em == 16px pxDimension = new JSONNumber((int) Float.parseFloat(dimension.trim()) * 16); } else if (dimension.endsWith("%")) { // eg. 100% pxDimension = new JSONString(dimension); } else { // A straight number is equivalent to pixels pxDimension = new JSONNumber(Integer.parseInt(dimension.trim())); } return pxDimension; } @Override public void setSize(String width, String height) { setWidth(width); setHeight(height); } private native void setControlSize(String elementId, JSONValue pxWidth, JSONValue pxHeight) /*-{ var myEditor = $wnd.tinymce.get(elementId); if (myEditor != null) { // Try multiple methods to set the size. Can't seem to get the size to stick in Chrome and Firefox myEditor.dom.setStyle(elementId + '_ifr', 'height', pxHeight + 'px'); myEditor.dom.setStyle(elementId + '_ifr', 'width', pxWidth + 'px'); myEditor.theme.resizeTo(pxWidth, pxHeight); } }-*/; @Override public void setWidth(String width) { super.setWidth(width); try { JSONValue pxWidth = parseSizeDimension(width); addOption("width", pxWidth); if (libraryLoaded && initialized) { JSONValue pxHeight = options.get("height"); if (pxHeight == null) { pxHeight = new JSONNumber(DEFAULT_HEIGHT); } setControlSize(elementId, pxWidth, pxHeight); } } catch (JavaScriptException e) { // Don't do anything, just allow it to return. GWT.log("Unable to set the width on the TinyMCE editor.", e); } } @Override public void setHeight(String height) { super.setHeight(height); try { JSONValue pxHeight = parseSizeDimension(height); addOption("height", pxHeight); if (libraryLoaded && initialized) { JSONValue pxWidth = options.get("width"); if (pxWidth == null) { pxWidth = new JSONNumber(DEFAULT_WIDTH); } setControlSize(elementId, pxWidth, pxHeight); } } catch (JavaScriptException e) { // Don't do anything, just allow it to return. GWT.log("Unable to set the height on the TinyMCE editor.", e); } } /* * Returns whether the current object is the one that has the focus. */ public boolean isFocused() { return focused; } public void setFocus(boolean focused) { if (!focused) { super.setFocus(focused); // nothing we can do to unset focus. Let GWT handle it. return; } try { // Only pass along the focus command if (libraryLoaded && (isInitialized() || isInitializing())) { if (isInitializing()) { // Setting a pending focus actually messes up the final focused element. // This is because the async call always returns last, so any calls to setFocus // for any other element essentially get ignored. // if (focused) { // addPendingSetFocus(); return; } try { setControlFocus(elementId); } catch (JavaScriptException e) { GWT.log("Unable to set the focus on the TinyMCE editor.", e); } return; } } finally { super.setFocus(focused); } } private native void setControlFocus(String elementId) /*-{ var myEditor = $wnd.tinymce.get(elementId); if (myEditor != null) { myEditor.focus(); } }-*/; public void setTabIndex(int tabIndex) { super.setTabIndex(tabIndex); // sets the tabIndex for the hidden associated textarea if (!libraryLoaded || !initialized) { // If not loaded or initialized, we're done. return; } try { // This will move the value in the textArea to the iframe setControlTabIndex(elementId); } catch (JavaScriptException e) { GWT.log("Unable to set the tab index on the TinyMCE editor iframe.", e); } } /** * This will move the tabIndex from the textArea to the iframe. * * @param elementId the elementId to uniquely identify the textarea */ private native void setControlTabIndex(String elementId) /*-{ var myEditor = $wnd.tinymce.get(elementId); if (myEditor != null) { var textAreaElement = null; if ($doc.getElementById) { textAreaElement = $doc.getElementById(elementId); // element replaced by TinyMCE } if (textAreaElement == null) { return; } var originalTabIndex = 0; // tabindex of element, or 0 if (textAreaElement.getAttribute && textAreaElement.getAttribute('tabindex')) { originalTabIndex = textAreaElement.getAttribute('tabindex'); } var iframeTextEditor = $doc.getElementById(elementId + '_ifr'); // editor iframe element if (iframeTextEditor == null || !iframeTextEditor.setAttribute) { return; } iframeTextEditor.setAttribute('tabindex', originalTabIndex); // set iframe tabindex } }-*/; private native void showEditor(String elementId, boolean visible) /*-{ var myEditor = $wnd.tinymce.get(elementId); if (myEditor != null) { if (visible) { myEditor.show(); } else { myEditor.hide(); } } }-*/; @Override public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { // Call initialize in case it wasn't previously initialized because the widget was hidden. initialize(); } showEditor(elementId, visible); } public JSONObject getOptions() { return options; } public boolean isInitialized() { return initialized; } public void setInitialized(boolean initialized) { this.initialized = initialized; } public boolean isInitializing() { return initializing; } public void setInitializing(boolean initializing) { this.initializing = initializing; } }
import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.BitSet; import java.security.SecureRandom; import java.lang.Math; import java.math.BigInteger; import gnu.getopt.Getopt; // TODO: Implement key expansion // TODO: Implement genKeys public class DES { /** * S-Box for Initial Permutation */ private static int[] IP = { 58, 50, 42, 34, 26, 18, 10, 2 , 60, 52, 44, 36, 28, 20, 12, 4 , 62, 54, 46, 38, 30, 22, 14, 6 , 64, 56, 48, 40, 32, 24, 16, 8 , 57, 49, 41, 33, 25, 17, 9, 1 , 59, 51, 43, 35, 27, 19, 11, 3 , 61, 53, 45, 37, 29, 21, 13, 5 , 63, 55, 47, 39, 31, 23, 15, 7 }; /** * S-Box for Final Permutation */ private static int[] FP = { 40, 8, 48, 16, 56, 24, 64, 32 , 39, 7, 47, 15, 55, 23, 63, 31 , 38, 6, 46, 14, 54, 22, 62, 30 , 37, 5, 45, 13, 53, 21, 61, 29 , 36, 4, 44, 12, 52, 20, 60, 28 , 35, 3, 43, 11, 51, 19, 59, 27 , 34, 2, 42, 10, 50, 18, 58, 26 , 33, 1, 41, 9, 49, 17, 57, 25 }; /** * PC1 used in key expansion */ private static int[] PC1 = { 57, 49, 41, 33, 25, 17, 9 , 1 , 58, 50, 42, 34, 26, 18, 10, 2 , 59, 51, 43, 35, 27, 19, 11, 3 , 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7 , 62, 54, 46, 38, 30, 22, 14, 6 , 61, 53, 45, 37, 29, 21, 13, 5 , 28, 20, 12, 4 }; /** * PC2 used in key expansion */ private static int[] PC2 = { 14, 17, 11, 24, 1 , 5 , 3 , 28, 15, 6 , 21, 10, 23, 19, 12, 4 , 26, 8 , 16, 7 , 27, 20, 13, 2 , 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 }; /** * rotations used in key expansion */ private static int[] rotations = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; /** * f function: Expansion Permutation */ private static int[] E = { 32, 1, 2, 3, 4, 5 , 4, 5, 6, 7, 8, 9 , 8, 9, 10, 11, 12, 13 , 12, 13, 14, 15, 16, 17 , 16, 17, 18, 19, 20, 21 , 20, 21, 22, 23, 24, 25 , 24, 25, 26, 27, 28, 29 , 28, 29, 30, 31, 32, 1 }; /** * f function: S-Box Substitution */ private static final byte[][] S = { { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 }, { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 }, { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 }, { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 }, { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 }, { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 }, { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 }, { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 } }; /** * f function: P-Box Substitution */ public static int[] P = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25}; public static void main(String[] args) { StringBuilder inputFile = new StringBuilder(); StringBuilder outputFile = new StringBuilder(); StringBuilder keyStr = new StringBuilder(); StringBuilder encrypt = new StringBuilder(); pcl(args, inputFile, outputFile, keyStr, encrypt); if(keyStr.toString() != "" && encrypt.toString().equals("e")){ encrypt(keyStr, inputFile, outputFile); } else if(keyStr.toString() != "" && encrypt.toString().equals("d")){ decrypt(keyStr, inputFile, outputFile); } } private static void decrypt(StringBuilder keyStr, StringBuilder inputFile, StringBuilder outputFile) { try { PrintWriter writer = new PrintWriter(outputFile.toString(), "UTF-8"); List<String> lines = Files.readAllLines(Paths.get(inputFile.toString()), Charset.defaultCharset()); String IVStr = lines.get(0); BitSet lastCBC = HextoBitSet(IVStr); BitSet decrypted; for (int i = 1; i < lines.size(); i ++) { String line = lines.get(i); if(line.length() != 16) { throw new IllegalArgumentException("Decrypt block size should be 64 bits."); } BitSet block = HextoBitSet(line); decrypted = DES_decrypt(block, keyStr); decrypted.xor(lastCBC); lastCBC = block; if(i == lines.size()-1) { writer.print(Delete_Padding_PKCS5(decrypted)); } else { writer.print(BitSettoAscii(decrypted)); } } writer.close(); } catch (IOException e) { e.printStackTrace(); } } /** * DES decryption * @param block One block of the cyphertext. It should be 64 bits as the requirement * @param keyStr Decryption key */ private static BitSet DES_decrypt(BitSet block, StringBuilder keyStr) { BitSet[] keys = keyExpansion(keyStr, "d"); permutation(block, DES.FP); // Initial permutation BitSet result = feistelNetwork(16, block, keys); permutation(result, DES.IP); // Final permutation return result; } private static void encrypt(StringBuilder keyStr, StringBuilder inputFile, StringBuilder outputFile) { try { PrintWriter writer = new PrintWriter(outputFile.toString(), "UTF-8"); String encryptedText; // read input as a single string String plaintext = new String(Files.readAllBytes(Paths.get(inputFile.toString()))); encryptedText = DES_encrypt(plaintext, keyStr); writer.print(encryptedText); writer.close(); } catch (IOException e) { e.printStackTrace(); } } /** * The DES encryption function * @param line The input plaintext * @return String The encrypted cyphertext */ private static String DES_encrypt(String line, StringBuilder keyStr) { int blockSize = 8; // 8 bytes = 64 bits int batch = (int)Math.ceil(line.length()*1.0 / blockSize); BitSet[] EncryptKeys = keyExpansion(keyStr, "e"); String line_padded = Padding_PKCS5(line); StringBuilder ciphertext = new StringBuilder(); BitSet lastCBC = getCBC_IV(); ciphertext.append(BitSettoHex(lastCBC)+"\n"); for(int i = 0; i < batch; i++){ BitSet block = StringtoBitSet(line_padded.substring(i*blockSize,i*blockSize+blockSize)); // Using CBC mode block.xor(lastCBC); // Encrypt permutation(block, DES.IP); // Initial permutation BitSet result = feistelNetwork(16, block, EncryptKeys); permutation(result, DES.FP); // Final permutation lastCBC = result; ciphertext.append(BitSettoHex(result)+"\n"); } return ciphertext.toString(); } static void genDESkey(){ System.out.println("New key goes here"); return; } /** * The f function used by feistel Network */ private static BitSet DESf(BitSet block, BitSet key){ // Expansion Permutation: 32 bits -> 48 bits BitSet ep = new BitSet(48); for(int i = 0; i < 48; i ++) { if(block.get(DES.E[i]-1) == true) { ep.set(i); } } // XOR with key: 48 bits ep.xor(key); // S-Box Substitution: 48 bits -> 32 bits BitSet sbs = SBoxSubstituion(ep); // P-Box Permutation: 32 bits BitSet ppp = new BitSet(32); for(int i = 0; i < 32; i ++) { if(sbs.get(DES.P[i]-1) == true) { ppp.set(i); } } return ppp; } private static BitSet SBoxSubstituion(BitSet input) { BitSet output = new BitSet(32); for(int i = 0; i < 8; i ++) { byte[] sbox = DES.S[i]; //S-Box for i-th segment int[] bits = {0, 0, 0, 0, 0, 0}; for(int bits_i = 0; bits_i < 6; bits_i ++) { bits[bits_i] = (input.get(i*6+bits_i)) ? 1:0; } int row = bits[0]*2+bits[5]; int col = bits[1]*8+bits[2]*4+bits[3]*2+bits[4]; int s_value_10 = sbox[row*16+col]; int index = 0; while (s_value_10 != 0) { if (s_value_10% 2 != 0) { output.set(i*4+index); } ++index; s_value_10 = s_value_10 >>> 1; } } return output; } //feistelnetwork: turns plain(64 bits) into cipher(64 bits), should be called with rounds=16 in DES //keys should be 56 bits BitSet private static BitSet feistelNetwork(int rounds, BitSet plainBlock, BitSet keys[]){ BitSet tmp1 = plainBlock.get(0,32); BitSet tmp2 = plainBlock.get(32,64); BitSet tmp3; int i = 0; while(i < rounds){ tmp3 = DESf(tmp2, keys[i]); tmp3.xor(tmp1); tmp1 = tmp2; tmp2 = tmp3; i++; } tmp3 = tmp1; tmp1 = tmp2; tmp2 = tmp3; BitSet cipher = new BitSet(64); for(i = 0; i < 32; i ++){ if(tmp1.get(i) == true){ cipher.set(i); } } for(i = 0; i < 32; i ++){ if(tmp2.get(i) == true){ cipher.set(i+32); } } return cipher; } /** * Generate key for each round based on encryption or decryption * @param keyStr The key string * @param type Encryption or Decryption. Values are 'e' or 'd'. * @return BitSet[] A list of keys for each round */ private static BitSet[] keyExpansion(StringBuilder keyStr, String type) { //make sure keyStr is bitset of 64 size //BitSet keyBlock64 = StringtoBitSet(keyStr.toString()); //maybe do sanity check of parity, not done yet BitSet keyBlock64 = HextoBitSet("c82cea9ed93dfb8f"); BitSet[] keyBlock56 = key_64_to_2_28(keyBlock64); BitSet[] keys = new BitSet[16]; //printBitSet(keyBlock56[1]); for(int i = 0; i < 16; i ++){ //round key generation LeftCircularShift(keyBlock56[0], rotations[i]); LeftCircularShift(keyBlock56[1], rotations[i]); //printBitSet(keyBlock56[0]); //printBitSet(keyBlock56[1]); BitSet roundKey = key_2_28_to_48(keyBlock56); //mode printBitSet(roundKey,6); if(type.equals("d")) keys[i] = roundKey; else if(type.equals("e")) keys[15 - i] = roundKey; else System.out.println("wrong mode, plz use e or d"); } return keys; } /** * left shift block for movingBits, for 28 bit block only */ private static void LeftCircularShift(BitSet block, int movingBits){ BitSet buffer = new BitSet(movingBits); buffer.clear(); //printBitSet(block); for(int i = 0; i < movingBits; i++){ if(block.get(i) == true) buffer.set(i); } for(int i = movingBits; i < 28; i++){ block.set(i-movingBits,block.get(i)); } for(int i = 28 - movingBits; i < 28; i++){ block.set(i,buffer.get(i-28+movingBits)); } //printBitSet(block); } /** * Print BitSet as 1s and 0s */ private static void printBitSet(BitSet bset){ for(int i = 0; i < bset.size(); i ++) { if(i % 8 == 0) { System.out.print(" "); } if(bset.get(i) == true) { System.out.print("1"); } else { System.out.print("0"); } } System.out.print("\n"); } /** * key extraction used in key expansion */ private static BitSet[] key_64_to_2_28(BitSet keyBlock64){ BitSet[] keyBlock56 = new BitSet[2]; keyBlock56[0] = new BitSet(28); keyBlock56[1] = new BitSet(28); for(int i = 0; i < 4; i++){ boolean parity = true; for(int j = 0; j < 7; j++){ if(keyBlock64.get(PC1[i*7 + j] - 1) == true){ //System.out.println((i*7 + j) + " " +(PC1[i*7 + j] - 1)); keyBlock56[0].set(i*7 + j); parity = !parity; } } } for(int i = 4; i < 8; i++){ boolean parity = false; for(int j = 0; j < 7; j++){ //System.out.println(i+ " " +(i*7 + j)); //System.out.println(i+ " " +PC1[i*7 + j]); if(keyBlock64.get(PC1[i*7 + j] - 1) == true){ keyBlock56[1].set(i*7 + j - 28); } } } return keyBlock56; } /** * key generation phase used in key expansion */ private static BitSet key_2_28_to_48(BitSet[] keyBlock56){ BitSet roundKey = new BitSet(56); //printBitSet(keyBlock56[0],7); //printBitSet(keyBlock56[1],7); for(int i = 0; i < 48; i++){ //System.out.println(PC2[i]); if(PC2[i] > 28) roundKey.set(i,keyBlock56[1].get(PC2[i]-29)); else roundKey.set(i,keyBlock56[0].get(PC2[i]-1)); } //printBitSet(roundKey,6); return roundKey; } /** * Initial or Final Permutation */ private static void permutation(BitSet original, int[] sbox) { if(original.size() != 64) { throw new IllegalArgumentException("Block size is not 64 bit."); } BitSet permuted = new BitSet(64); for(int i = 0; i < 64; i ++) { if(original.get(sbox[i]-1) == true) { permuted.set(i); } } original = permuted; } /** * Generate IV for CBC mode */ private static BitSet getCBC_IV() { BitSet CBC_IV = new BitSet(64); SecureRandom generator = new SecureRandom(); generator.setSeed(System.currentTimeMillis()); for(int i = 0; i < 64; i ++) { CBC_IV.set(i, generator.nextBoolean()); } return CBC_IV; } /** * Use PKCS5 padding algorithm to pad block * @param block The block to be padded * @return String Padded block */ private static String Padding_PKCS5(String block) { BitSet block_bit = StringtoBitSet(block); int padding_length = 8 - block.length()%8; char padding_char = (char)padding_length; for(int i = 0; i < padding_length; i ++) { block = block+padding_char; } return block; } private static String Delete_Padding_PKCS5(BitSet block) { byte[] b = block.toByteArray(); int padding_length = b[b.length-1]; int flag = 1; for(int i = 0; i < padding_length; i ++) { if(b[b.length-i-1] != padding_length) { flag = 0; break; } } if(flag == 0) { return new String(b); } else { byte [] subArray = Arrays.copyOfRange(b, 0, b.length-padding_length); return new String(subArray); } } /** * Transform a bitset to hex string */ private static String BitSettoHex(BitSet block){ StringBuilder hex = new StringBuilder(); for(int k = 0; k < block.toByteArray().length; k++){ String result = String.format("%02X",block.toByteArray()[k]); hex.append(result); } return hex.toString(); } /** * Transform a bitset to ascii string */ private static String BitSettoAscii(BitSet block){ byte[] b = block.toByteArray(); String str = new String(b); return str; } /** * Transform Hex string to BitSet */ private static BitSet HextoBitSet(String input){ //choose input length carefully so that it fits in 64 bits BigInteger bigint = new BigInteger(input, 16); byte[] content = bigint.toByteArray(); if(content.length > 8) { content = Arrays.copyOfRange(content, 1, content.length); } if(content.length < 8) { byte[] tmp = content; content = new byte[8]; for(int i = 0; i < tmp.length; i ++) content[8-i-1] = tmp[tmp.length-i-1]; } BitSet bits = BitSet.valueOf(content); return bits; } /** * Transforms ascii string to bitset */ private static BitSet StringtoBitSet(String input){ //choose input length carefully so that it fits in 64 bits byte[] bytes = input.getBytes(); BitSet plainBlock = new BitSet(64); plainBlock.clear(); int i = 0; for(byte b:bytes){ //System.out.println(b); int j = 0; while(j < 8){ if(b%2 == 1)plainBlock.set(i); i++;j++; b >>= 1; } } return plainBlock; } /** * Processes the Command Line Arguments. */ private static void pcl(String[] args, StringBuilder inputFile, StringBuilder outputFile, StringBuilder keyString, StringBuilder encrypt) { Getopt g = new Getopt("Chat Program", args, "hke:d:i:o:"); int c; String arg; while ((c = g.getopt()) != -1){ switch(c){ case 'o': arg = g.getOptarg(); outputFile.append(arg); break; case 'i': arg = g.getOptarg(); inputFile.append(arg); break; case 'e': arg = g.getOptarg(); keyString.append(arg); encrypt.append("e"); break; case 'd': arg = g.getOptarg(); keyString.append(arg); encrypt.append("d"); break; case 'k': genDESkey(); break; case 'h': callUseage(0); case '?': break; // getopt() already printed an error default: break; } } } private static void callUseage(int exitStatus) { String useage = " -h List all command line options\n" + " -k Generate a DES key\n" + " -e <key> Specify the key used to encrypt the file\n" + " -d <key> Specify the key used to decrypt the file\n" + " -i <path> Specify the input file\n" + " -o <path> Specify the output file\n"; System.err.println(useage); System.exit(exitStatus); } }
package org.jetel.data; import java.nio.ByteBuffer; import java.util.*; import org.jetel.metadata.DataRecordMetadata; /** * This class serves the role of DataRecords comparator.<br> * It can compare two records with different structure based on * specified fields. It is used when sorting, hashing or (in general) * comparing data.<br> * <br> * <i>Usage:</i><br> * <code> * key = new RecordKey(keyFieldNames,recordMetadata);<br> * key.init();<br> * key.compare(recordA,recordB); * </code> * * @author dpavlis * @since May 2, 2002 * @revision $Revision$ * @created January 26, 2003 */ public class RecordKey { private int keyFields[]; private DataRecordMetadata metadata; private String keyFieldNames[]; private final static char KEY_ITEMS_DELIMITER = ':'; private final static int DEFAULT_STRING_KEY_LENGTH = 32; private StringBuffer keyStr; private boolean equalNULLs = false; // specifies whether two NULLs are deemed equal /** * Constructor for the RecordKey object * * @param keyFieldNames names of individual fields composing the key * @param metadata metadata describing structure of DataRecord for which the key is built * @since May 2, 2002 */ public RecordKey(String keyFieldNames[], DataRecordMetadata metadata) { this.metadata = metadata; this.keyFieldNames = keyFieldNames; } /** * @param keyFields indices of fields composing the key * @param metadata metadata describing structure of DataRecord for which the key is built */ public RecordKey(int keyFields[], DataRecordMetadata metadata) { this.metadata = metadata; this.keyFields = keyFields; } // end init /** * Assembles string representation of the key based on current record's value. * * @param record DataRecord whose field's values will be used to create key string. * @return The KeyString value * @since May 2, 2002 */ public String getKeyString(DataRecord record) { if (keyStr == null){ keyStr = new StringBuffer(DEFAULT_STRING_KEY_LENGTH); }else{ keyStr.setLength(0); } for (int i = 0; i < keyFields.length; i++) { keyStr.append(record.getField(keyFields[i]).toString()); // not used for now keyStr.append(KEY_ITEMS_DELIMITER); } return keyStr.toString(); } /** * Performs initialization of internal data structures * * @since May 2, 2002 */ public void init() { if (keyFields == null) { Integer position; keyFields = new int[keyFieldNames.length]; Map fields = metadata.getFieldNames(); for (int i = 0; i < keyFieldNames.length; i++) { if ((position = (Integer) fields.get(keyFieldNames[i])) != null) { keyFields[i] = position.intValue(); } else { throw new RuntimeException( "Field name specified as a key doesn't exist: " + keyFieldNames[i]); } } }else if (keyFieldNames==null){ keyFieldNames=new String[keyFields.length]; for (int i=0;i<keyFields.length;i++){ keyFieldNames[i]=metadata.getField(keyFields[i]).getName(); } } } /** * Gets the keyFields attribute of the RecordKey object * * @return The keyFields value */ public int[] getKeyFields() { return keyFields; } // end getKeyString /** * Compares two records (of the same layout) based on defined key-fields and returns (-1;0;1) if (< ; = ; >) * * @param record1 Description of the Parameter * @param record2 Description of the Parameter * @return -1 ; 0 ; 1 */ public int compare(DataRecord record1, DataRecord record2) { int compResult; if (record1.getMetadata() != record2.getMetadata()) { throw new RuntimeException("Can't compare - records have different metadata associated." + " Possibly different structure"); } if (equalNULLs){ for (int i = 0; i < keyFields.length; i++) { compResult = record1.getField(keyFields[i]).compareTo(record2.getField(keyFields[i])); if (compResult != 0) { if (!(record1.getField(keyFields[i]).isNull&&record2.getField(keyFields[i]).isNull)){ return compResult; } } } }else { for (int i = 0; i < keyFields.length; i++) { compResult = record1.getField(keyFields[i]).compareTo(record2.getField(keyFields[i])); if (compResult != 0) { return compResult; } } } return 0; // seem to be the same } /** * Compares two records (can have different layout) based on defined key-fields * and returns (-1;0;1) if (< ; = ; >).<br> * The particular fields to be compared have to be of the same type ! * * @param secondKey RecordKey defined for the second record * @param record1 First record * @param record2 Second record * @return -1 ; 0 ; 1 */ public int compare(RecordKey secondKey, DataRecord record1, DataRecord record2) { int compResult; int[] record2KeyFields = secondKey.getKeyFields(); if (keyFields.length != record2KeyFields.length) { throw new RuntimeException("Can't compare. keys have different number of DataFields"); } if (equalNULLs){ for (int i = 0; i < keyFields.length; i++) { compResult = record1.getField(keyFields[i]).compareTo(record2.getField(record2KeyFields[i])); if (compResult != 0) { if (!(record1.getField(keyFields[i]).isNull&&record2.getField(keyFields[i]).isNull)){ return compResult; } } } }else{ for (int i = 0; i < keyFields.length; i++) { compResult = record1.getField(keyFields[i]).compareTo(record2.getField(record2KeyFields[i])); if (compResult != 0) { return compResult; } } } return 0; // seem to be the same } /** * Description of the Method * * @param record1 Description of the Parameter * @param record2 Description of the Parameter * @return Description of the Return Value */ public boolean equals(DataRecord record1, DataRecord record2) { if (record1.getMetadata() != record2.getMetadata()) { throw new RuntimeException("Can't compare - records have different metadata associated." + " Possibly different structure"); } if (equalNULLs){ for (int i = 0; i < keyFields.length; i++) { if (!record1.getField(keyFields[i]).equals(record2.getField(keyFields[i]))) { if (!(record1.getField(keyFields[i]).isNull&&record2.getField(keyFields[i]).isNull)){ return false; } } } }else{ for (int i = 0; i < keyFields.length; i++) { if (!record1.getField(keyFields[i]).equals(record2.getField(keyFields[i]))) { return false; } } } return true; } /** * This method serializes (saves) content of key fields (for specified record) into * buffer. * * @param buffer ByteBuffer into which serialize key fields * @param record data record from which key fields will be serialized into ByteBuffer */ public void serializeKeyFields(ByteBuffer buffer,DataRecord record) { for (int i = 0; i < keyFields.length; i++) { record.getField(keyFields[i]).serialize(buffer); } } /** * This method creates DataRecordMetadata object which represents fields composing this key. It can * be used for creating data record composed from key fields only. * @return DataRecordMetadata object */ public DataRecordMetadata generateKeyRecordMetadata(){ DataRecordMetadata metadata = new DataRecordMetadata(this.metadata.getName()+"key"); for (int i = 0; i < keyFields.length; i++) { metadata.addField(this.metadata.getField(keyFields[i])); } return metadata; } /** * toString method: creates a String representation of the object * @return the String representation */ public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("RecordKey["); if (keyFields == null) { buffer.append("keyFields = ").append("null"); } else { buffer.append("keyFields = ").append("["); for (int i = 0; i < keyFields.length; i++) { if (i != 0) { buffer.append(", "); } buffer.append(keyFields[i]); } buffer.append("]"); } buffer.append(", metadata = ").append(metadata.toString()); if (keyFieldNames == null) { buffer.append(", keyFieldNames = ").append("null"); } else { buffer.append(", keyFieldNames = ").append(Arrays.asList(keyFieldNames).toString()); } buffer.append(", KEY_ITEMS_DELIMITER = ").append(KEY_ITEMS_DELIMITER); buffer.append(", DEFAULT_KEY_LENGTH = ").append(DEFAULT_STRING_KEY_LENGTH); buffer.append(", EQUAL_NULLS = ").append(equalNULLs); buffer.append(", keyStr = ").append(keyStr); buffer.append("]"); return buffer.toString(); } /** * True if two NULL values (fields with NULL flag set) are considered equal * * @return Returns the equalNULLs. */ public boolean isEqualNULLs() { return equalNULLs; } /** * Sets whether two NULL values (fields with NULL flag set) are considered equal * * @param equalNULLs The equalNULLs to set. */ public void setEqualNULLs(boolean equalNULLs) { this.equalNULLs = equalNULLs; } } // end RecordKey
package nl.rubensten.pp2lal2pp; import nl.rubensten.pp2lal2pp.compiler.Compiler; import nl.rubensten.pp2lal2pp.lang.Program; import nl.rubensten.pp2lal2pp.parser.FileParser; import nl.rubensten.pp2lal2pp.parser.Parser; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Practicum Processor To Learn Assembly Language To Preserve Prosperity-Language compiler. * * @author Ruben Schellekens, Sten Wessel * @version 0.1 */ public class PP2LAL2PP { public static void main(String[] args) { long start = System.currentTimeMillis(); if (args.length == 0) { printHelp(); return; } List<String> argList = new ArrayList<>(Arrays.asList(args)); // Parse file name. File file = new File(args[0]); if (!file.exists()) { System.out.println("File '" + file.getName() + "' does not exist!"); return; } // Destination argument. File dest = new File(args[0].replaceAll("(\\.[a-zA-Z0-9_\\-]*)$", ".asm")); if (argList.contains("-d")) { int index = argList.indexOf("-d"); if (index + 1 >= argList.size()) { System.out.println("No destination has been specified."); return; } dest = new File(argList.get(index + 1)); } // Parse file Parser parser = new FileParser(file); Program program = parser.parse(); // Compile file Compiler compiler = new Compiler(dest, program); compiler.compile(); // Finish long delta = System.currentTimeMillis() - start; float time = (float)delta / 1000f; System.out.println("Done (" + time + "s). " + "Compiled '" + file.getName() + "' to '" + dest.getName() + "'."); } private static void printHelp() { System.out.println(""); System.out.println("-= System.out.println(" Practicum Processor 2 Learn Assembly Language 2 Preserve Prosperity"); System.out.println(" PP2LAL2PP: 'java -jar JARNAME.jar [-args] <fileName>'"); System.out.println("-= System.out.println("Arguments:"); System.out.println(" -d <destination>\tdestination file"); System.out.println(" -r \t\t\t\t\trefactor file"); System.out.println(""); } }
import com.google.common.collect.ImmutableSet; import org.wso2.carbon.uuf.DebugAppender; import org.wso2.carbon.uuf.UUFRegistry; import org.wso2.carbon.uuf.UUFService; import org.wso2.carbon.uuf.core.ClassLoaderProvider; import org.wso2.carbon.uuf.core.create.AppCreator; import org.wso2.carbon.uuf.core.create.RenderableCreator; import org.wso2.carbon.uuf.fileio.ArtifactResolver; import org.wso2.carbon.uuf.fileio.StaticResolver; import org.wso2.carbon.uuf.handlebars.HbsRenderableCreator; import org.wso2.msf4j.MicroservicesRunner; import java.nio.file.FileSystems; import java.util.Optional; public class Main { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException { ArtifactResolver appResolver = new ArtifactResolver(FileSystems.getDefault().getPath(".")); StaticResolver staticResolver = new StaticResolver(FileSystems.getDefault().getPath(".")); ClassLoaderProvider classLoaderProvider = (an, cn, cv, cr) -> Main.class.getClassLoader(); RenderableCreator hbsCreator = new HbsRenderableCreator(); AppCreator appCreator = new AppCreator(ImmutableSet.of(hbsCreator), classLoaderProvider); UUFRegistry registry = new UUFRegistry(appCreator, Optional.of(new DebugAppender()), appResolver, staticResolver); new MicroservicesRunner().deploy(new UUFService(registry)).start(); } }
package ethanjones.cubes.graphics; import ethanjones.cubes.core.logging.Log; import ethanjones.cubes.core.platform.Adapter; import ethanjones.cubes.core.platform.Compatibility; import ethanjones.cubes.core.settings.Setting; import ethanjones.cubes.core.settings.Settings; import ethanjones.cubes.core.settings.type.DropDownSetting; import ethanjones.cubes.core.system.CubesException; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.PixmapIO; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.utils.BufferUtils; import com.badlogic.gdx.utils.ScreenUtils; import java.io.IOException; import java.nio.IntBuffer; import java.util.HashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class Screenshot { private static final AtomicReference<ScreenshotMethod> takingScreenshot = new AtomicReference<ScreenshotMethod>(null); private static final String[] resolutions = new String[]{"normal", "1080p", "1440p", "4k", "8k", "16k", "max"}; private static final HashMap<String, int[]> resolutionMap = new HashMap<String, int[]>(); static { resolutionMap.put("1080p", new int[]{1920, 1080}); resolutionMap.put("1440p", new int[]{2560, 1440}); resolutionMap.put("4k", new int[]{3840, 2160}); resolutionMap.put("8k", new int[]{7680, 4320}); resolutionMap.put("16k", new int[]{15360, 8640}); } public static Setting screenshotResolutionSetting() { return new DropDownSetting(resolutions) { @Override public void onChange() { if ("normal".equals(selected) || "max".equals(selected)) return; IntBuffer intBuffer = BufferUtils.newIntBuffer(2); Gdx.gl20.glGetIntegerv(GL20.GL_MAX_VIEWPORT_DIMS, intBuffer); int maxWidth = intBuffer.get(0); int maxHeight = intBuffer.get(1); int[] resolution = resolutionMap.get(selected); if (resolution[0] > maxWidth || resolution[1] > maxHeight) selected = "normal"; } }; } public static void startScreenshot() { String setting = ((DropDownSetting) Settings.getSetting(Settings.GRAPHICS_SCREENSHOT_SIZE)).getSelected(); ScreenshotMethod method = "normal".equals(setting) ? new NormalResolutionScreenshot() : new HighResolutionScreenshot(); if (takingScreenshot.compareAndSet(null, method)) { method.frameStart(); } } public static void endScreenshot() { ScreenshotMethod method = takingScreenshot.getAndSet(null); if (method != null) method.frameEnd(); } private static void writeScreenshot(Pixmap pixmap) { FileHandle dir = Compatibility.get().getBaseFolder().child("screenshots"); dir.mkdirs(); FileHandle f = dir.child(System.currentTimeMillis() + ".png"); try { PixmapIO.PNG writer = new PixmapIO.PNG((int) (pixmap.getWidth() * pixmap.getHeight() * 1.5f)); try { writer.setFlipY(true); writer.write(f, pixmap); } finally { writer.dispose(); } } catch (IOException ex) { throw new CubesException("Error writing PNG: " + f, ex); } finally { pixmap.dispose(); } Log.info("Took screenshot '" + f.file().getAbsolutePath() + "'"); } private interface ScreenshotMethod { void frameStart(); void frameEnd(); } private static class NormalResolutionScreenshot implements ScreenshotMethod { @Override public void frameStart() { } @Override public void frameEnd() { Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(0, 0, Graphics.RENDER_WIDTH, Graphics.RENDER_HEIGHT); writeScreenshot(pixmap); } } private static class HighResolutionScreenshot implements ScreenshotMethod { AtomicInteger state = new AtomicInteger(0); int screenshotWidth = 0; int screenshotHeight = 0; int oldWidth = 0; int oldHeight = 0; FrameBuffer frameBuffer = null; @Override public void frameStart() { if (!state.compareAndSet(0, 1)) return; String setting = ((DropDownSetting) Settings.getSetting(Settings.GRAPHICS_SCREENSHOT_SIZE)).getSelected(); if ("max".equals(setting)) { IntBuffer intBuffer = BufferUtils.newIntBuffer(2); Gdx.gl20.glGetIntegerv(GL20.GL_MAX_VIEWPORT_DIMS, intBuffer); screenshotWidth = intBuffer.get(0); screenshotHeight = intBuffer.get(1); } else { screenshotWidth = Screenshot.resolutionMap.get(setting)[0]; screenshotHeight = Screenshot.resolutionMap.get(setting)[1]; } Log.debug("Attempting to take " + setting + " (" + screenshotWidth + "x" + screenshotHeight + ") resolution screenshot"); frameBuffer = new FrameBuffer(Pixmap.Format.RGB888, screenshotWidth, screenshotHeight, true, true); frameBuffer.begin(); oldWidth = Graphics.RENDER_WIDTH; oldHeight = Graphics.RENDER_HEIGHT; Graphics.RENDER_WIDTH = screenshotWidth; Graphics.RENDER_HEIGHT = screenshotHeight; Adapter.getInterface().resize(screenshotWidth, screenshotHeight); } @Override public void frameEnd() { if (!state.compareAndSet(1, 2)) return; Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(0, 0, screenshotWidth, screenshotHeight); frameBuffer.end(); Graphics.RENDER_WIDTH = oldWidth; Graphics.RENDER_HEIGHT = oldHeight; Adapter.getInterface().resize(oldWidth, oldHeight); writeScreenshot(pixmap); } } }
package hudson.model; import hudson.Launcher; import hudson.Proc.LocalProc; import hudson.Util; import org.kohsuke.stapler.export.Exported; import hudson.tasks.Fingerprinter.FingerprintAction; import hudson.tasks.test.AbstractTestResultAction; import hudson.maven.MavenBuild; import static hudson.model.Hudson.isWindows; import hudson.model.listeners.SCMListener; import hudson.model.Fingerprint.RangeSet; import hudson.model.Fingerprint.BuildPtr; import hudson.scm.CVSChangeLogParser; import hudson.scm.ChangeLogParser; import hudson.scm.ChangeLogSet; import hudson.scm.ChangeLogSet.Entry; import hudson.scm.SCM; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.xml.sax.SAXException; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Calendar; import java.util.Map; import java.util.HashMap; import java.util.Collections; import java.util.List; import java.util.ArrayList; /** * Base implementation of {@link Run}s that build software. * * For now this is primarily the common part of {@link Build} and {@link MavenBuild}. * * @author Kohsuke Kawaguchi * @see AbstractProject */ public abstract class AbstractBuild<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Run<P,R> implements Queue.Executable { /** * PluginName of the slave this project was built on. * Null or "" if built by the master. (null happens when we read old record that didn't have this information.) */ private String builtOn; /** * Version of Hudson that built this. */ private String hudsonVersion; /** * SCM used for this build. * Maybe null, for historical reason, in which case CVS is assumed. */ private ChangeLogParser scm; /** * Changes in this build. */ private volatile transient ChangeLogSet<? extends Entry> changeSet; protected AbstractBuild(P job) throws IOException { super(job); } protected AbstractBuild(P job, Calendar timestamp) { super(job, timestamp); } protected AbstractBuild(P project, File buildDir) throws IOException { super(project, buildDir); } public final P getProject() { return getParent(); } /** * Returns a {@link Slave} on which this build was done. */ public Node getBuiltOn() { if(builtOn==null) return Hudson.getInstance(); else return Hudson.getInstance().getSlave(builtOn); } /** * Returns the name of the slave it was built on, or null if it was the master. */ @Exported(name="builtOn") public String getBuiltOnStr() { return builtOn; } protected abstract class AbstractRunner implements Runner { /** * Since configuration can be changed while a build is in progress, * stick to one launcher and use it. */ protected Launcher launcher; /** * Returns the current {@link Node} on which we are buildling. */ protected final Node getCurrentNode() { return Executor.currentExecutor().getOwner().getNode(); } public Result run(BuildListener listener) throws Exception { Node node = Executor.currentExecutor().getOwner().getNode(); assert builtOn==null; builtOn = node.getNodeName(); hudsonVersion = Hudson.VERSION; launcher = node.createLauncher(listener); if(node instanceof Slave) listener.getLogger().println("Building remotely on "+node.getNodeName()); if(checkout(listener)) return Result.FAILURE; Result result = doRun(listener); if(result!=null) return result; // abort here if(getResult()==null || getResult()==Result.SUCCESS) createLastSuccessfulLink(listener); return Result.SUCCESS; } private void createLastSuccessfulLink(BuildListener listener) { if(!isWindows()) { try { // ignore a failure. new LocalProc(new String[]{"rm","-f","../lastSuccessful"},new String[0],listener.getLogger(),getProject().getBuildDir()).join(); int r = new LocalProc(new String[]{ "ln","-s","builds/"+getId()/*ugly*/,"../lastSuccessful"}, new String[0],listener.getLogger(),getProject().getBuildDir()).join(); if(r!=0) listener.getLogger().println("ln failed: "+r); } catch (IOException e) { PrintStream log = listener.getLogger(); log.println("ln failed"); Util.displayIOException(e,listener); e.printStackTrace( log ); } } } private boolean checkout(BuildListener listener) throws Exception { if(!project.checkout(AbstractBuild.this,launcher,listener,new File(getRootDir(),"changelog.xml"))) return true; SCM scm = project.getScm(); AbstractBuild.this.scm = scm.createChangeLogParser(); AbstractBuild.this.changeSet = AbstractBuild.this.calcChangeSet(); for (SCMListener l : Hudson.getInstance().getSCMListeners()) l.onChangeLogParsed(AbstractBuild.this,listener,changeSet); return false; } /** * The portion of a build that is specific to a subclass of {@link AbstractBuild} * goes here. * * @return * null to continue the build normally (that means the doRun method * itself run successfully) * Return a non-null value to abort the build right there with the specified result code. */ protected abstract Result doRun(BuildListener listener) throws Exception; } /** * Gets the changes incorporated into this build. * * @return never null. */ @Exported public ChangeLogSet<? extends Entry> getChangeSet() { if(scm==null) scm = new CVSChangeLogParser(); if(changeSet==null) // cached value changeSet = calcChangeSet(); return changeSet; } /** * Returns true if the changelog is already computed. */ public boolean hasChangeSetComputed() { File changelogFile = new File(getRootDir(), "changelog.xml"); return changelogFile.exists(); } private ChangeLogSet<? extends Entry> calcChangeSet() { File changelogFile = new File(getRootDir(), "changelog.xml"); if(!changelogFile.exists()) return ChangeLogSet.createEmpty(this); try { return scm.parse(this,changelogFile); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return ChangeLogSet.createEmpty(this); } @Override public Map<String,String> getEnvVars() { Map<String,String> env = super.getEnvVars(); env.put("WORKSPACE", getProject().getWorkspace().getRemote()); JDK jdk = project.getJDK(); if(jdk !=null) jdk.buildEnvVars(env); project.getScm().buildEnvVars(env); return env; } public Calendar due() { return timestamp; } /** * Gets {@link AbstractTestResultAction} associated with this build if any. */ public AbstractTestResultAction getTestResultAction() { return getAction(AbstractTestResultAction.class); } /** * Invoked by {@link Executor} to performs a build. */ public abstract void run(); // fingerprint related stuff @Override public String getWhyKeepLog() { // if any of the downstream project is configured with 'keep dependency component', // we need to keep this log for (Map.Entry<AbstractProject, RangeSet> e : getDownstreamBuilds().entrySet()) { AbstractProject<?,?> p = e.getKey(); if(!p.isKeepDependencies()) continue; // is there any active build that depends on us? for (AbstractBuild build : p.getBuilds()) { if(e.getValue().includes(build.getNumber())) return "kept because of "+build; } } return super.getWhyKeepLog(); } /** * Gets the dependency relationship from this build (as the source) * and that project (as the sink.) * * @return * range of build numbers that represent which downstream builds are using this build. * The range will be empty if no build of that project matches this. */ public RangeSet getDownstreamRelationship(AbstractProject that) { RangeSet rs = new RangeSet(); FingerprintAction f = getAction(FingerprintAction.class); if(f==null) return rs; // look for fingerprints that point to this build as the source, and merge them all for (Fingerprint e : f.getFingerprints().values()) { BuildPtr o = e.getOriginal(); if(o!=null && o.is(this)) rs.add(e.getRangeSet(that)); } return rs; } /** * Gets the dependency relationship from this build (as the sink) * and that project (as the source.) * * @return * Build number of the upstream build that feed into this build, * or -1 if no record is available. */ public int getUpstreamRelationship(AbstractProject that) { FingerprintAction f = getAction(FingerprintAction.class); if(f==null) return -1; int n = -1; // look for fingerprints that point to the given project as the source, and merge them all for (Fingerprint e : f.getFingerprints().values()) { BuildPtr o = e.getOriginal(); if(o!=null && o.is(that)) n = Math.max(n,o.getNumber()); } return n; } /** * Gets the downstream builds of this build, which are the builds of the * downstream projects that use artifacts of this build. * * @return * For each project with fingerprinting enabled, returns the range * of builds (which can be empty if no build uses the artifact from this build.) */ public Map<AbstractProject,RangeSet> getDownstreamBuilds() { Map<AbstractProject,RangeSet> r = new HashMap<AbstractProject,RangeSet>(); for (AbstractProject p : getParent().getDownstreamProjects()) { if(p.isFingerprintConfigured()) r.put(p,getDownstreamRelationship(p)); } return r; } /** * Gets the upstream builds of this build, which are the builds of the * upstream projects whose artifacts feed into this build. */ public Map<AbstractProject,Integer> getUpstreamBuilds() { Map<AbstractProject,Integer> r = new HashMap<AbstractProject,Integer>(); for (AbstractProject p : getParent().getUpstreamProjects()) { int n = getUpstreamRelationship(p); if(n>=0) r.put(p,n); } return r; } /** * Gets the changes in the dependency between the given build and this build. */ public Map<AbstractProject,DependencyChange> getDependencyChanges(AbstractBuild from) { if(from==null) return Collections.emptyMap(); // make it easy to call this from views FingerprintAction n = this.getAction(FingerprintAction.class); FingerprintAction o = from.getAction(FingerprintAction.class); if(n==null || o==null) return Collections.emptyMap(); Map<AbstractProject,Integer> ndep = n.getDependencies(); Map<AbstractProject,Integer> odep = o.getDependencies(); Map<AbstractProject,DependencyChange> r = new HashMap<AbstractProject,DependencyChange>(); for (Map.Entry<AbstractProject,Integer> entry : odep.entrySet()) { AbstractProject p = entry.getKey(); Integer oldNumber = entry.getValue(); Integer newNumber = ndep.get(p); if(newNumber!=null && oldNumber.compareTo(newNumber)<0) { r.put(p,new DependencyChange(p,oldNumber,newNumber)); } } return r; } /** * Represents a change in the dependency. */ public static final class DependencyChange { /** * The dependency project. */ public final AbstractProject project; /** * Version of the dependency project used in the previous build. */ public final int fromId; /** * {@link Build} object for {@link #fromId}. Can be null if the log is gone. */ public final AbstractBuild from; /** * Version of the dependency project used in this build. */ public final int toId; public final AbstractBuild to; public DependencyChange(AbstractProject<?,?> project, int fromId, int toId) { this.project = project; this.fromId = fromId; this.toId = toId; this.from = project.getBuildByNumber(fromId); this.to = project.getBuildByNumber(toId); } /** * Gets the {@link AbstractBuild} objects (fromId,toId]. * <p> * This method returns all such available builds in the ascending order * of IDs, but due to log rotations, some builds may be already unavailable. */ public List<AbstractBuild> getBuilds() { List<AbstractBuild> r = new ArrayList<AbstractBuild>(); AbstractBuild<?,?> b = (AbstractBuild)project.getNearestBuild(fromId); if(b!=null && b.getNumber()==fromId) b = b.getNextBuild(); // fromId exclusive while(b!=null && b.getNumber()<=toId) { r.add(b); b = b.getNextBuild(); } return r; } } // web methods /** * Stops this build if it's still going. * * If we use this/executor/stop URL, it causes 404 if the build is already killed, * as {@link #getExecutor()} returns null. */ public synchronized void doStop( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { Executor e = getExecutor(); if(e!=null) e.doStop(req,rsp); else // nothing is building rsp.forwardToPreviousPage(req); } }
package hudson.slaves; import hudson.ExtensionPoint; import hudson.Launcher; import hudson.DescriptorExtensionList; import hudson.model.queue.CauseOfBlockage; import hudson.scm.SCM; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.Describable; import hudson.model.Environment; import hudson.model.Hudson; import hudson.model.Node; import hudson.model.Queue.Task; import java.io.IOException; import java.util.List; /** * Extensible property of {@link Node}. * * <p> * Plugins can contribute this extension point to add additional data or UI actions to {@link Node}. * {@link NodeProperty}s show up in the configuration screen of a node, and they are persisted with the {@link Node} object. * * * <h2>Views</h2> * <dl> * <dt>config.jelly</dt> * <dd>Added to the configuration page of the node. * <dt>global.jelly</dt> * <dd>Added to the system configuration page. * <dt>summary.jelly</dt> * <dd>Added to the index page of the {@link Computer} associated with the node * <dl> * * @param <N> * {@link NodeProperty} can choose to only work with a certain subtype of {@link Node}, and this 'N' * represents that type. Also see {@link NodePropertyDescriptor#isApplicable(Class)}. * * @since 1.286 */ public abstract class NodeProperty<N extends Node> implements Describable<NodeProperty<?>>, ExtensionPoint { protected transient N node; protected void setNode(N node) { this.node = node; } public NodePropertyDescriptor getDescriptor() { return (NodePropertyDescriptor)Hudson.getInstance().getDescriptorOrDie(getClass()); } /** * Called by the {@link Node} to help determine whether or not it should * take the given task. Individual properties can return a non-null value * here if there is some reason the given task should not be run on its * associated node. By default, this method returns <code>null</code>. * * @since 1.360 */ public CauseOfBlockage canTake(Task task) { return null; } /** * Runs before the {@link SCM#checkout(AbstractBuild, Launcher, FilePath, BuildListener, File)} runs, and performs a set up. * Can contribute additional properties to the environment. * * @param build * The build in progress for which an {@link Environment} object is created. * Never null. * @param launcher * This launcher can be used to launch processes for this build. * If the build runs remotely, launcher will also run a job on that remote machine. * Never null. * @param listener * Can be used to send any message. * @return * non-null if the build can continue, null if there was an error * and the build needs to be aborted. * @throws IOException * terminates the build abnormally. Hudson will handle the exception * and reports a nice error message. */ public Environment setUp( AbstractBuild build, Launcher launcher, BuildListener listener ) throws IOException, InterruptedException { return new Environment() {}; } /** * Lists up all the registered {@link NodeDescriptor}s in the system. */ public static DescriptorExtensionList<NodeProperty<?>,NodePropertyDescriptor> all() { return (DescriptorExtensionList)Hudson.getInstance().getDescriptorList(NodeProperty.class); } /** * List up all {@link NodePropertyDescriptor}s that are applicable for the * given project. */ public static List<NodePropertyDescriptor> for_(Node node) { return NodePropertyDescriptor.for_(all(),node); } }
package hudson.tasks; import hudson.model.AbstractProject; import hudson.model.Descriptor; import jenkins.model.Jenkins; import hudson.model.AbstractProject.AbstractProjectDescriptor; import hudson.Extension; import hudson.util.DescriptorList; import java.util.ArrayList; import java.util.List; /** * List of all installed {@link BuildWrapper}. * * @author Kohsuke Kawaguchi */ public class BuildWrappers { /** * @deprecated * as of 1.281. Use {@link Extension} for registration, and use {@link BuildWrapper#all()} * for listing them. */ @Deprecated public static final List<Descriptor<BuildWrapper>> WRAPPERS = new DescriptorList<>(BuildWrapper.class); /** * List up all {@link BuildWrapperDescriptor}s that are applicable for the given project. * * @return * The signature doesn't use {@link BuildWrapperDescriptor} to maintain compatibility * with {@link BuildWrapper} implementations before 1.150. */ public static List<Descriptor<BuildWrapper>> getFor(AbstractProject<?, ?> project) { List<Descriptor<BuildWrapper>> result = new ArrayList<>(); Descriptor pd = Jenkins.getInstance().getDescriptor((Class)project.getClass()); for (Descriptor<BuildWrapper> w : BuildWrapper.all()) { if (pd instanceof AbstractProjectDescriptor && !((AbstractProjectDescriptor)pd).isApplicable(w)) continue; if (w instanceof BuildWrapperDescriptor) { BuildWrapperDescriptor bwd = (BuildWrapperDescriptor) w; if(bwd.isApplicable(project)) result.add(bwd); } else { // old BuildWrapper that doesn't implement BuildWrapperDescriptor result.add(w); } } return result; } }
package hudson.util.io; import hudson.Functions; import hudson.org.apache.tools.tar.TarOutputStream; import hudson.os.PosixException; import hudson.util.FileVisitor; import hudson.util.IOUtils; import org.apache.tools.tar.TarEntry; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import static org.apache.tools.tar.TarConstants.LF_SYMLINK; /** * {@link FileVisitor} that creates a tar archive. * * @see ArchiverFactory#TAR */ final class TarArchiver extends Archiver { private final byte[] buf = new byte[8192]; private final TarArchiveOutputStream tar; TarArchiver(OutputStream out) { tar = new TarArchiveOutputStream(new BufferedOutputStream(out) { // TarOutputStream uses TarBuffer internally, // which flushes the stream for each block. this creates unnecessary // data stream fragmentation, and flush request to a remote, which slows things down. @Override public void flush() throws IOException { // so don't do anything in flush } }); tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); } @Override public void visitSymlink(File link, String target, String relativePath) throws IOException { TarArchiveEntry e = new TarArchiveEntry(relativePath, LF_SYMLINK); try { int mode = IOUtils.mode(link); if (mode != -1) { e.setMode(mode); } } catch (PosixException x) { // ignore } e.setLinkName(target); tar.putArchiveEntry(e); tar.closeArchiveEntry(); entriesWritten++; } @Override public boolean understandsSymlink() { return true; } public void visit(File file, String relativePath) throws IOException { if(Functions.isWindows()) relativePath = relativePath.replace('\\','/'); if(file.isDirectory()) relativePath+='/'; TarArchiveEntry te = new TarArchiveEntry(relativePath); int mode = IOUtils.mode(file); if (mode!=-1) te.setMode(mode); te.setModTime(file.lastModified()); if(!file.isDirectory()) te.setSize(file.length()); tar.putArchiveEntry(te); if (!file.isDirectory()) { FileInputStream in = new FileInputStream(file); try { int len; while((len=in.read(buf))>=0) tar.write(buf,0,len); } finally { in.close(); } } tar.closeArchiveEntry(); entriesWritten++; } public void close() throws IOException { tar.close(); } }
package jlibs.core.nio; import jlibs.core.lang.Waiter; import jlibs.core.util.EmptyIterator; import jlibs.core.util.NonNullIterator; import java.io.IOException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.*; import java.util.concurrent.atomic.AtomicLong; /** * @author Santhosh Kumar T */ public class NIOSelector extends Debuggable implements Iterable<NIOChannel>{ private static AtomicLong ID_GENERATOR = new AtomicLong(); protected final long id = ID_GENERATOR.incrementAndGet(); protected final Selector selector; public NIOSelector(long selectTimeout) throws IOException{ selector = Selector.open(); setSelectTimeout(selectTimeout); } public long id(){ return id; } protected long lastClientID; public ClientChannel newClient() throws IOException{ validate(); return new ClientChannel(this, SocketChannel.open()); } private long selectTimeout; public long getSelectTimeout(){ return selectTimeout; } public void setSelectTimeout(long selectTimeout){ if(selectTimeout<=0) throw new IllegalArgumentException("selectTimeout should be >0"); this.selectTimeout = selectTimeout; } @Override public String toString(){ return "NIOSelector@"+id; } public void wakeup(){ selector.wakeup(); } private volatile boolean force; private volatile boolean initiateShutdown; private boolean shutdownInProgress; public void shutdown(boolean force){ if(isShutdownPending() || isShutdown()) return; this.force = force; initiateShutdown = true; wakeup(); if(DEBUG) println(this+".shutdownRequested"); } public boolean isShutdownPending(){ return (initiateShutdown || shutdownInProgress) && (serverCount()!=0 || connectedClients!=0 || connectionPendingClients!=0); } public boolean isShutdown(){ return shutdownInProgress && serverCount()==0 && connectedClients==0 && connectionPendingClients==0; } protected void validate() throws IOException{ if(isShutdownPending()) throw new IOException("shutdown in progress"); if(isShutdown()) throw new IOException("already shutdown"); } public void shutdownOnExit(final boolean force){ if(!isShutdown()){ Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run(){ try{ shutdownAndWait(force); }catch (InterruptedException ex){ ex.printStackTrace(); } } }); } } private final Object shutdownLock = new Object(); public void waitForShutdown() throws InterruptedException{ synchronized(shutdownLock){ if(!isShutdown()) shutdownLock.wait(); } } public void shutdownAndWait(boolean force) throws InterruptedException{ synchronized(shutdownLock){ shutdown(force); if(!isShutdown()) shutdownLock.wait(); } } protected List<ServerChannel> servers = new ArrayList<ServerChannel>(); protected long connectionPendingClients; protected long connectedClients; public long serverCount(){ return servers.size(); } public long connectionPendingClientsCount(){ return connectionPendingClients; } public long connectedClientsCount(){ return connectedClients; } @Override public Iterator<NIOChannel> iterator(){ return iterator; } private Iterator<NIOChannel> iterator = new NonNullIterator<NIOChannel>(){ private Iterator<NIOChannel> delegate = Collections.<NIOChannel>emptyList().iterator(); @Override protected NIOChannel findNext(){ try{ while(!isShutdown() && !delegate.hasNext()) delegate = select(); if(delegate.hasNext()) return delegate.next(); else{ if(DEBUG) println(NIOSelector.this+".shutdown"); selector.close(); synchronized(shutdownLock){ shutdownLock.notifyAll(); } return null; } }catch(IOException ex){ throw new RuntimeException(ex); } } }; private volatile List<Runnable> tasks = new LinkedList<Runnable>(); public synchronized void invokeLater(Runnable task){ tasks.add(task); wakeup(); } public void invokeAndWait(Runnable task) throws InterruptedException{ task = new Waiter(task); synchronized(task){ invokeLater(task); task.wait(); } } private void runTasks(){ List<Runnable> list; synchronized(this){ list = tasks; tasks = new LinkedList<Runnable>(); } for(Runnable task: list){ try{ task.run(); }catch(Exception ex){ ex.printStackTrace(); } } } protected List<NIOChannel> ready = new LinkedList<NIOChannel>(); private Iterator<NIOChannel> select() throws IOException{ if(ready.size()>0) return readyIterator.reset(); runTasks(); if(ready.size()>0) return readyIterator.reset(); if(initiateShutdown){ shutdownInProgress = true; initiateShutdown = false; if(DEBUG) println(this+".shutdownInitialized: servers="+serverCount()+" connectedClients="+connectedClientsCount()+" connectionPendingClients="+connectionPendingClientsCount()); while(servers.size()>0) servers.get(0).unregister(this); if(force){ for(SelectionKey key: selector.keys()){ try{ ((NIOChannel)key.attachment()).close(); }catch(IOException ex){ ex.printStackTrace(); } } } } if(isShutdown()) return EmptyIterator.instance(); else{ if(DEBUG) System.out.println(" if(selector.select(timeoutTracker.isTracking()?selectTimeout:0)>0) return selectedIterator.reset(); else return timeoutTracker.reset(); } } private ReadyIterator readyIterator = new ReadyIterator(); private class ReadyIterator implements Iterator<NIOChannel>{ private int count; public ReadyIterator reset(){ count = ready.size(); return this; } @Override public boolean hasNext(){ return count>0; } @Override public NIOChannel next(){ if(count==0) throw new NoSuchElementException(); NIOChannel channel = ready.remove(0); count return channel; } @Override public void remove(){ throw new UnsupportedOperationException(); } } private SelectedIterator selectedIterator = new SelectedIterator(); private class SelectedIterator extends NonNullIterator<NIOChannel>{ private Iterator<SelectionKey> keys; @Override public SelectedIterator reset(){ super.reset(); keys = selector.selectedKeys().iterator(); timeoutTracker.reset(); return this; } @Override protected NIOChannel findNext(){ while(keys.hasNext()){ SelectionKey key = keys.next(); keys.remove(); NIOChannel channel = (NIOChannel)key.attachment(); if(key.isValid()){ if(channel instanceof ClientChannel){ ClientChannel client = (ClientChannel)channel; timeoutTracker.untrack(client); } if(channel.process()) return channel; } } return timeoutTracker.hasNext() ? timeoutTracker.next() : null; } } protected final TimeoutTracker timeoutTracker = new TimeoutTracker(); protected final ClientPool pool = new ClientPool(this); public ClientPool pool(){ return pool; } }
package mockit.coverage; import java.io.*; import java.util.*; import static mockit.external.asm4.Opcodes.*; import mockit.coverage.data.*; import mockit.coverage.paths.*; import mockit.external.asm4.*; final class CoverageModifier extends ClassVisitor { private static final Map<String, CoverageModifier> INNER_CLASS_MODIFIERS = new HashMap<String, CoverageModifier>(); private static final int FIELD_MODIFIERS_TO_IGNORE = ACC_FINAL + ACC_SYNTHETIC; static byte[] recoverModifiedByteCodeIfAvailable(String innerClassName) { CoverageModifier modifier = INNER_CLASS_MODIFIERS.remove(innerClassName); return modifier == null ? null : modifier.toByteArray(); } private String internalClassName; private String simpleClassName; private String sourceFileName; private FileCoverageData fileData; private boolean cannotModify; private final boolean forInnerClass; private boolean forEnumClass; CoverageModifier(ClassReader cr) { super(new ClassWriter(cr, ClassWriter.COMPUTE_MAXS)); forInnerClass = false; } private CoverageModifier(ClassReader cr, CoverageModifier other, String simpleClassName) { super(new ClassWriter(cr, ClassWriter.COMPUTE_MAXS)); sourceFileName = other.sourceFileName; fileData = other.fileData; internalClassName = other.internalClassName; this.simpleClassName = simpleClassName; forInnerClass = true; } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { if ((access & ACC_SYNTHETIC) != 0) { throw new VisitInterruptedException(); } forEnumClass = (access & ACC_ENUM) != 0; if (!forInnerClass) { internalClassName = name; int p = name.lastIndexOf('/'); if (p < 0) { simpleClassName = name; sourceFileName = ""; } else { simpleClassName = name.substring(p + 1); sourceFileName = name.substring(0, p + 1); } cannotModify = (access & ACC_ANNOTATION) != 0 || name.startsWith("mockit/coverage/"); if (!forEnumClass && (access & ACC_SUPER) != 0 && name.indexOf('$') > 0) { INNER_CLASS_MODIFIERS.put(name.replace('/', '.'), this); } } super.visit(version, access, name, signature, superName, interfaces); } @Override public void visitSource(String file, String debug) { if (!forInnerClass) { if (cannotModify) { throw VisitInterruptedException.INSTANCE; } sourceFileName += file; fileData = CoverageData.instance().addFile(sourceFileName); } super.visitSource(file, debug); } @Override public void visitInnerClass(String internalName, String outerName, String innerName, int access) { super.visitInnerClass(internalName, outerName, innerName, access); if (forInnerClass || isSyntheticOrEnumClass(access) || !isNestedInsideClassBeingModified(outerName)) { return; } String innerClassName = internalName.replace('/', '.'); if (INNER_CLASS_MODIFIERS.containsKey(innerClassName)) { return; } try { ClassReader innerCR = new ClassReader(innerClassName); CoverageModifier innerClassModifier = new CoverageModifier(innerCR, this, innerName); innerCR.accept(innerClassModifier, 0); INNER_CLASS_MODIFIERS.put(innerClassName, innerClassModifier); } catch (IOException e) { e.printStackTrace(); } } private boolean isSyntheticOrEnumClass(int access) { return (access & ACC_SYNTHETIC) != 0 || access == ACC_STATIC + ACC_ENUM; } private boolean isNestedInsideClassBeingModified(String outerName) { if (outerName == null) { return false; } int p = outerName.indexOf('$'); String outerClassName = p < 0 ? outerName : outerName.substring(0, p); return outerClassName.equals(internalClassName); } @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (fileData != null && (access & FIELD_MODIFIERS_TO_IGNORE) == 0) { fileData.dataCoverageInfo.addField(simpleClassName, name, (access & ACC_STATIC) != 0); } return super.visitField(access, name, desc, signature, value); } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); if (fileData == null || (access & ACC_SYNTHETIC) != 0) { return mv; } if (name.charAt(0) == '<') { if (name.charAt(1) == 'c') { return forEnumClass ? mv : new StaticBlockModifier(mv); } if (Metrics.PATH_COVERAGE || Metrics.DATA_COVERAGE) { // TODO: fully separate these return new ConstructorModifier(mv); } } if (Metrics.PATH_COVERAGE || Metrics.DATA_COVERAGE) { return new MethodModifier(mv, name); } else { return new BaseMethodModifier(mv); } } private class BaseMethodModifier extends MethodVisitor { static final String DATA_RECORDING_CLASS = "mockit/coverage/TestRun"; final MethodWriter mw; int currentLine; LineCoverageData lineData; final List<Label> visitedLabels = new ArrayList<Label>(); final List<Label> jumpTargetsForCurrentLine = new ArrayList<Label>(4); private final Map<Label, Label> unconditionalJumps = new HashMap<Label, Label>(2); final Map<Integer, Boolean> pendingBranches = new HashMap<Integer, Boolean>(); boolean assertFoundInCurrentLine; boolean nextLabelAfterConditionalJump; boolean potentialAssertFalseFound; BaseMethodModifier(MethodVisitor mv) { super(mv); mw = (MethodWriter) mv; } @Override public void visitLineNumber(int line, Label start) { if (!pendingBranches.isEmpty()) { pendingBranches.clear(); } lineData = fileData.addLine(line); currentLine = line; jumpTargetsForCurrentLine.clear(); nextLabelAfterConditionalJump = false; unconditionalJumps.clear(); generateCallToRegisterLineExecution(); mw.visitLineNumber(line, start); } private void generateCallToRegisterLineExecution() { mw.visitLdcInsn(sourceFileName); pushCurrentLineOnTheStack(); mw.visitMethodInsn(INVOKESTATIC, DATA_RECORDING_CLASS, "lineExecuted", "(Ljava/lang/String;I)V"); } private void pushCurrentLineOnTheStack() { if (currentLine <= Short.MAX_VALUE) { mw.visitIntInsn(SIPUSH, currentLine); } else { mw.visitLdcInsn(currentLine); } } @Override public void visitJumpInsn(int opcode, Label label) { if (visitedLabels.contains(label)) { assertFoundInCurrentLine = false; mw.visitJumpInsn(opcode, label); return; } jumpTargetsForCurrentLine.add(label); nextLabelAfterConditionalJump = isConditionalJump(opcode); if (nextLabelAfterConditionalJump) { int branchIndex = lineData.addBranch(mw.currentBlock, label); pendingBranches.put(branchIndex, false); if (assertFoundInCurrentLine) { BranchCoverageData branchData = lineData.getBranchData(branchIndex); branchData.markAsUnreachable(); } } else { unconditionalJumps.put(label, mw.currentBlock); } mw.visitJumpInsn(opcode, label); if (nextLabelAfterConditionalJump) { generateCallToRegisterBranchTargetExecutionIfPending(); } } protected final boolean isConditionalJump(int opcode) { return opcode != GOTO && opcode != JSR; } private void generateCallToRegisterBranchTargetExecutionIfPending() { potentialAssertFalseFound = false; if (pendingBranches.isEmpty()) { return; } for (Integer branchIndex : pendingBranches.keySet()) { BranchCoverageData branchData = lineData.getBranchData(branchIndex); Boolean firstInsnAfterJump = pendingBranches.get(branchIndex); if (firstInsnAfterJump) { branchData.setHasJumpTarget(); generateCallToRegisterBranchTargetExecution("jumpTargetExecuted", branchIndex); } else { branchData.setHasNoJumpTarget(); generateCallToRegisterBranchTargetExecution("noJumpTargetExecuted", branchIndex); } } pendingBranches.clear(); } @Override public void visitLabel(Label label) { visitedLabels.add(label); mw.visitLabel(label); if (nextLabelAfterConditionalJump) { int branchIndex = jumpTargetsForCurrentLine.indexOf(label); if (branchIndex >= 0) { pendingBranches.put(branchIndex, true); assertFoundInCurrentLine = false; } nextLabelAfterConditionalJump = false; } Label unconditionalJumpSource = unconditionalJumps.get(label); if (unconditionalJumpSource != null) { int branchIndex = lineData.addBranch(unconditionalJumpSource, label); BranchCoverageData branchData = lineData.getBranchData(branchIndex); branchData.setHasJumpTarget(); generateCallToRegisterBranchTargetExecution("jumpTargetExecuted", branchIndex); } } private void generateCallToRegisterBranchTargetExecution(String methodName, int branchIndex) { mw.visitLdcInsn(sourceFileName); pushCurrentLineOnTheStack(); mw.visitIntInsn(SIPUSH, branchIndex); mw.visitMethodInsn(INVOKESTATIC, DATA_RECORDING_CLASS, methodName, "(Ljava/lang/String;II)V"); } @Override public void visitInsn(int opcode) { generateCallToRegisterBranchTargetExecutionIfPending(); mw.visitInsn(opcode); } @Override public void visitIntInsn(int opcode, int operand) { generateCallToRegisterBranchTargetExecutionIfPending(); mw.visitIntInsn(opcode, operand); } @Override public void visitVarInsn(int opcode, int var) { generateCallToRegisterBranchTargetExecutionIfPending(); mw.visitVarInsn(opcode, var); if (opcode == RET) { System.out.println("RET instruction found!"); } } @Override public void visitTypeInsn(int opcode, String desc) { generateCallToRegisterBranchTargetExecutionIfPending(); mw.visitTypeInsn(opcode, desc); } @Override public void visitFieldInsn(int opcode, String owner, String name, String desc) { generateCallToRegisterBranchTargetExecutionIfPending(); mw.visitFieldInsn(opcode, owner, name, desc); assertFoundInCurrentLine = opcode == GETSTATIC && "$assertionsDisabled".equals(name); potentialAssertFalseFound = true; } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc) { generateCallToRegisterBranchTargetExecutionIfPending(); mw.visitMethodInsn(opcode, owner, name, desc); } @Override public void visitLdcInsn(Object cst) { generateCallToRegisterBranchTargetExecutionIfPending(); mw.visitLdcInsn(cst); } @Override public void visitIincInsn(int var, int increment) { generateCallToRegisterBranchTargetExecutionIfPending(); mw.visitIincInsn(var, increment); } @Override public void visitTryCatchBlock(Label start, Label end, Label handler, String type) { generateCallToRegisterBranchTargetExecutionIfPending(); mw.visitTryCatchBlock(start, end, handler, type); } @Override public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) { generateCallToRegisterBranchTargetExecutionIfPending(); mw.visitLookupSwitchInsn(dflt, keys, labels); } @Override public void visitTableSwitchInsn(int min, int max, Label dflt, Label[] labels) { generateCallToRegisterBranchTargetExecutionIfPending(); mw.visitTableSwitchInsn(min, max, dflt, labels); } @Override public void visitMultiANewArrayInsn(String desc, int dims) { generateCallToRegisterBranchTargetExecutionIfPending(); mw.visitMultiANewArrayInsn(desc, dims); } @Override public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { mw.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs); } @Override public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) { mw.visitFrame(type, nLocal, local, nStack, stack); } } private class MethodOrConstructorModifier extends BaseMethodModifier { final MethodCoverageData methodData; final NodeBuilder nodeBuilder; private Label entryPoint; MethodOrConstructorModifier(MethodVisitor mv, String methodOrConstructorName) { super(mv); methodData = new MethodCoverageData(methodOrConstructorName); nodeBuilder = new NodeBuilder(); } @Override public final void visitLabel(Label label) { int line = label.line; if (entryPoint == null) { entryPoint = new Label(); mw.visitLabel(entryPoint); mw.visitLineNumber(line, entryPoint); nodeBuilder.handleEntry(line); generateCallToRegisterNodeReached(0); } super.visitLabel(label); int newNodeIndex = nodeBuilder.handleJumpTarget(label, line > 0 ? line : currentLine); generateCallToRegisterNodeReached(newNodeIndex); } private void generateCallToRegisterNodeReached(int nodeIndex) { if (nodeIndex >= 0) { mw.visitLdcInsn(sourceFileName); mw.visitLdcInsn(nodeBuilder.firstLine); mw.visitIntInsn(SIPUSH, nodeIndex); mw.visitMethodInsn(INVOKESTATIC, DATA_RECORDING_CLASS, "nodeReached", "(Ljava/lang/String;II)V"); } } @Override public final void visitJumpInsn(int opcode, Label label) { if (visitedLabels.contains(label)) { super.visitJumpInsn(opcode, label); return; } boolean conditional = isConditionalJump(opcode); int nodeIndex = nodeBuilder.handleJump(label, currentLine, conditional); generateCallToRegisterNodeReached(nodeIndex); super.visitJumpInsn(opcode, label); } @Override public final void visitInsn(int opcode) { if (opcode >= IRETURN && opcode <= RETURN || opcode == ATHROW) { int newNodeIndex = nodeBuilder.handleExit(currentLine); generateCallToRegisterNodeReached(newNodeIndex); } else { handleRegularInstruction(opcode); } super.visitInsn(opcode); } private void handleRegularInstruction(int opcode) { int nodeIndex = nodeBuilder.handleRegularInstruction(currentLine, opcode); generateCallToRegisterNodeReached(nodeIndex); } @Override public final void visitIntInsn(int opcode, int operand) { super.visitIntInsn(opcode, operand); handleRegularInstruction(opcode); } @Override public final void visitIincInsn(int var, int increment) { super.visitIincInsn(var, increment); handleRegularInstruction(IINC); } @Override public final void visitLdcInsn(Object cst) { super.visitLdcInsn(cst); handleRegularInstruction(LDC); } @Override public final void visitTypeInsn(int opcode, String desc) { super.visitTypeInsn(opcode, desc); handleRegularInstruction(opcode); } @Override public final void visitVarInsn(int opcode, int var) { super.visitVarInsn(opcode, var); handleRegularInstruction(opcode); } @Override public final void visitFieldInsn(int opcode, String owner, String name, String desc) { boolean getField = opcode == GETSTATIC || opcode == GETFIELD; boolean isStatic = opcode == PUTSTATIC || opcode == GETSTATIC; char fieldType = desc.charAt(0); boolean size2 = fieldType == 'J' || fieldType == 'D'; String classAndFieldNames = null; boolean fieldHasData = false; if (!owner.startsWith("java/")) { classAndFieldNames = owner.substring(owner.lastIndexOf('/') + 1) + '.' + name; fieldHasData = fileData.dataCoverageInfo.isFieldWithCoverageData(classAndFieldNames); if (fieldHasData && !isStatic) { generateCodeToSaveInstanceReferenceOnTheStack(getField, size2); } } super.visitFieldInsn(opcode, owner, name, desc); if (fieldHasData) { generateCallToRegisterFieldCoverage(getField, isStatic, size2, classAndFieldNames); } handleRegularInstruction(opcode); } private void generateCodeToSaveInstanceReferenceOnTheStack(boolean getField, boolean size2) { if (getField) { mw.visitInsn(DUP); } else if (size2) { mw.visitInsn(DUP2_X1); mw.visitInsn(POP2); mw.visitInsn(DUP_X2); mw.visitInsn(DUP_X2); mw.visitInsn(POP); } else { mw.visitInsn(DUP_X1); mw.visitInsn(POP); mw.visitInsn(DUP_X1); mw.visitInsn(DUP_X1); mw.visitInsn(POP); } } private void generateCallToRegisterFieldCoverage( boolean getField, boolean isStatic, boolean size2, String classAndFieldNames) { if (!isStatic && getField) { if (size2) { mw.visitInsn(DUP2_X1); mw.visitInsn(POP2); } else { mw.visitInsn(DUP_X1); mw.visitInsn(POP); } } mw.visitLdcInsn(sourceFileName); mw.visitLdcInsn(classAndFieldNames); String methodToCall = getField ? "fieldRead" : "fieldAssigned"; String methodDesc = isStatic ? "(Ljava/lang/String;Ljava/lang/String;)V" : "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;)V"; mw.visitMethodInsn(INVOKESTATIC, DATA_RECORDING_CLASS, methodToCall, methodDesc); } @Override public final void visitMethodInsn(int opcode, String owner, String name, String desc) { super.visitMethodInsn(opcode, owner, name, desc); handleRegularInstruction(opcode); } @Override public final void visitTryCatchBlock(Label start, Label end, Label handler, String type) { super.visitTryCatchBlock(start, end, handler, type); handleRegularInstruction(0); } @Override public final void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) { int nodeIndex = nodeBuilder.handleForwardJumpsToNewTargets(dflt, labels, currentLine); generateCallToRegisterNodeReached(nodeIndex); super.visitLookupSwitchInsn(dflt, keys, labels); } @Override public final void visitTableSwitchInsn(int min, int max, Label dflt, Label[] labels) { int nodeIndex = nodeBuilder.handleForwardJumpsToNewTargets(dflt, labels, currentLine); generateCallToRegisterNodeReached(nodeIndex); super.visitTableSwitchInsn(min, max, dflt, labels); } @Override public final void visitMultiANewArrayInsn(String desc, int dims) { super.visitMultiANewArrayInsn(desc, dims); handleRegularInstruction(MULTIANEWARRAY); } @Override public final void visitEnd() { if (currentLine > 0) { methodData.buildPaths(currentLine, nodeBuilder); fileData.addMethod(methodData); } } } private final class MethodModifier extends MethodOrConstructorModifier { MethodModifier(MethodVisitor mv, String methodName) { super(mv, methodName); } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { boolean isTestMethod = desc.startsWith("Lorg/junit/") || desc.startsWith("Lorg/testng/"); if (isTestMethod) { throw VisitInterruptedException.INSTANCE; } return mw.visitAnnotation(desc, visible); } } private final class ConstructorModifier extends MethodOrConstructorModifier { ConstructorModifier(MethodVisitor mv) { super(mv, simpleClassName); } } private final class StaticBlockModifier extends BaseMethodModifier { StaticBlockModifier(MethodVisitor mv) { super(mv); } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc) { // This is to ignore bytecode belonging to a static initialization block inserted in a regular line of code by // the Java compiler when the class contains at least one "assert" statement. Otherwise, that line of code // would always appear as partially covered when running with assertions enabled. assertFoundInCurrentLine = opcode == INVOKEVIRTUAL && "java/lang/Class".equals(owner) && "desiredAssertionStatus".equals(name); super.visitMethodInsn(opcode, owner, name, desc); } } }
import java.util.*; import java.io.*; import jing.chem.*; import jing.chemParser.*; import jing.param.*; import jing.chemUtil.*; import jing.rxn.*; import jing.rxnSys.*; import jing.mathTool.*; // MainRMG.java public class RMG { //## configuration RMG::RMG public static void main(String[] args) { long tAtInitialization = System.currentTimeMillis(); Global.tAtInitialization = tAtInitialization; //begin = getCpuTime(); //System.out.println((begin)/1e3); //System.out.println(getCpuTime()/1e9 + " " + (System.currentTimeMillis()-begin)/1e3); //Pressure pres = new Pressure(30,"bar"); //System.out.println("The size of the object pressure is "+getObjectSize(pres)); initializeSystemProperties(args[0]); ReactionModelGenerator rmg = new ReactionModelGenerator(); rmg.modelGeneration(); ReactionSystem rs = rmg.getReactionSystem(); CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rs.getReactionModel(); //Write core species to RMG_Dictionary.txt String coreSpecies =""; Iterator iter = cerm.getSpecies(); while (iter.hasNext()){ int i=1; Species spe = (Species) iter.next(); coreSpecies = coreSpecies + spe.getChemkinName()+"\n"+spe.getChemGraph().toString(i)+"\n\n"; } try{ File rmgDictionary = new File("RMG_Dictionary.txt"); FileWriter fw = new FileWriter(rmgDictionary); fw.write(coreSpecies); fw.close(); } catch (IOException e) { System.out.println("Could not write RMG_Dictionary.txt"); System.exit(0); } //Write the final model output in a separete Final_Model file String finalOutput = ""; finalOutput = finalOutput + "\n\\\\\\\\\\\\\\\\\\\\\\\\\\ Final Reaction Model Output \\\\\\\\\\\\\\\\\\\\\\\\\\"; finalOutput = finalOutput +"\n"+ cerm.returnPDepModel(rs.getPresentStatus())+"\n"; finalOutput = finalOutput + "Model Edge:"; finalOutput = finalOutput + cerm.getEdge().getSpeciesNumber()+" "; finalOutput = finalOutput + " Species; "; finalOutput = finalOutput + cerm.getEdge().getReactionNumber()+" "; finalOutput = finalOutput + " Reactions."; LinkedList speList = new LinkedList(rs.getReactionModel().getSpeciesSet()); finalOutput = finalOutput + "\\\\\\\\\\\\\\\\\\\\\\\\\\\\ Concentration Profile Output \\\\\\\\\\\\\\\\\\\\\\\\\\"; finalOutput = finalOutput +"\n"+ rs.returnConcentrationProfile(speList)+"\n"; if (rmg.getError()){//svp finalOutput = finalOutput + "\n"; finalOutput = finalOutput + "Upper Bounds:"+"\n"; finalOutput = finalOutput + rs.printUpperBoundConcentrations(speList)+"\n"; finalOutput = finalOutput + "Lower Bounds:"+"\n"; finalOutput = finalOutput + rs.printLowerBoundConcentrations(speList)+"\n"; } finalOutput = finalOutput + "\\\\\\\\\\\\\\\\\\\\\\\\\\\\ Mole Fraction Profile Output \\\\\\\\\\\\\\\\\\\\\\\\\\"; finalOutput = finalOutput +"\n"+ rs.returnMoleFractionProfile(speList)+"\n"; if (rmg.getSensitivity()){//svp LinkedList importantSpecies = rmg.getSpeciesList(); finalOutput = finalOutput + "Sensitivity Analysis:"; finalOutput = finalOutput + rs.printSensitivityCoefficients(speList, importantSpecies)+"\n"; finalOutput = finalOutput + "\n"; finalOutput = finalOutput + rs.printSensitivityToThermo(speList, importantSpecies)+"\n"; finalOutput = finalOutput + "\n"; finalOutput = finalOutput + rs.printMostUncertainReactions(speList, importantSpecies)+"\n"; } long end = System.currentTimeMillis(); double min = (end-tAtInitialization)/1E3/60; finalOutput = finalOutput +"Running Time is: " + String.valueOf(min) + " minutes."; try{ File finalmodel = new File("Final_Model.txt"); FileWriter fw = new FileWriter(finalmodel); fw.write(finalOutput); fw.close(); } catch (IOException e) { System.out.println("Could not write Final_Model.txt"); System.exit(0); } }; public static void initializeSystemProperties(String inputfile) { File f = new File("."); String dir = f.getAbsolutePath(); //File chemdis = new File("chemdis"); //chemdis.mkdir(); File therfit = new File("therfit"); therfit.mkdir(); //File fit3p = new File("fit3p"); //fit3p.mkdir(); File chemkin = new File("chemkin"); chemkin.mkdir(); writeThermoFile(); File Restart = new File("Restart"); Restart.mkdir(); File GATPFit = new File("GATPFit"); GATPFit.mkdir(); String workingDir = System.getenv("RMG"); System.setProperty("RMG.workingDirectory", workingDir); System.setProperty("jing.rxnSys.ReactionModelGenerator.conditionFile",inputfile); try {//svp String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile"); if (initialConditionFile == null) { System.out.println("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile"); System.exit(0); } // Print out RMG header System.out.println("\n"); System.out.println(" RMG"); System.out.println(" Reaction Mechanism Generator"); System.out.println(" version 0.9\n"); System.out.println( " Jing Song, Sumathy Raman, Joanna Yu, William H. Green,\n" + " Sarah Petway, Sandeep Sharma, David M. Matheu,\n" + " Paul E. Yelvington, Robert Ashcraft, C. Franklin Goldsmith,\n" + " John Wen, Andrew Wong, Hsi-Wu Wong, Kevin Van Geem,\n" + " and Gregory Beran\n"); System.out.println("\n"); System.out.println(" System.out.println(" User input:"); System.out.println(" //GJB: Added mini-reader to reprint input file in job output. FileReader tmpin = new FileReader(initialConditionFile); BufferedReader minireader = new BufferedReader(tmpin); try { String inputLine = minireader.readLine(); while ( inputLine != null ) { System.out.println(inputLine); inputLine = minireader.readLine(); } } catch ( IOException error ) { System.err.println( "Error reading condition file: " + error ); } System.out.println("\n minireader.close(); FileReader in = new FileReader(initialConditionFile); BufferedReader reader = new BufferedReader(in); String line = ChemParser.readMeaningfulLine(reader); line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("Database")){ StringTokenizer st = new StringTokenizer(line); String next = st.nextToken(); String name = st.nextToken().trim(); System.setProperty("jing.chem.ChemGraph.forbiddenStructureFile", workingDir + "/databases/"+name+"/forbiddenStructure/ForbiddenStructure.txt"); System.setProperty("jing.chem.ThermoGAGroupLibrary.pathName", workingDir + "/databases/" + name+"/thermo"); System.setProperty("jing.rxn.ReactionTemplateLibrary.pathName", workingDir + "/databases/" + name+"/kinetics/kinetics"); } line = ChemParser.readMeaningfulLine(reader); if (line.startsWith("PrimaryThermoLibrary")){ StringTokenizer st = new StringTokenizer(line); String next = st.nextToken(); String name = st.nextToken().trim(); String thermoDirectory = System.getProperty("jing.chem.ThermoGAGroupLibrary.pathName"); System.setProperty("jing.chem.PrimaryThermoLibrary.pathName", thermoDirectory+"/"+name); } } catch (IOException e) { System.err.println("Error in read in reaction system initialization file!"); } } private static void writeThermoFile() { // TODO Auto-generated method stub String thermoFile = "300.000 1000.000 5000.000 \n"; thermoFile += "! neon added by pey (20/6/04) - used thermo for Ar\n"; thermoFile += "Ne 120186Ne 1 G 0300.00 5000.00 1000.00 1\n"; thermoFile += " 0.02500000E+02 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 2\n"; thermoFile += "-0.07453750E+04 0.04366001E+02 0.02500000E+02 0.00000000E+00 0.00000000E+00 3\n"; thermoFile += " 0.00000000E+00 0.00000000E+00-0.07453750E+04 0.04366001E+02 4\n"; thermoFile += "N2 121286N 2 G 0300.00 5000.00 1000.00 1\n"; thermoFile += " 0.02926640e+02 0.01487977e-01-0.05684761e-05 0.01009704e-08-0.06753351e-13 2\n"; thermoFile += "-0.09227977e+04 0.05980528e+02 0.03298677e+02 0.01408240e-01-0.03963222e-04 3\n"; thermoFile += " 0.05641515e-07-0.02444855e-10-0.01020900e+05 0.03950372e+02 4\n"; thermoFile += "Ar 120186Ar 1 G 0300.00 5000.00 1000.00 1\n"; thermoFile += " 0.02500000e+02 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 2\n"; thermoFile += "-0.07453750e+04 0.04366001e+02 0.02500000e+02 0.00000000e+00 0.00000000e+00 3\n"; thermoFile += " 0.00000000e+00 0.00000000e+00-0.07453750e+04 0.04366001e+02 4\n"; thermoFile += "end\n"; try { FileWriter fw = new FileWriter("chemkin/therm.dat"); fw.write(thermoFile); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; }; }
package thredds.servlet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import thredds.catalog.*; import thredds.server.config.HtmlConfig; import thredds.server.config.TdsContext; import thredds.server.viewer.dataservice.ViewerService; import thredds.util.ContentType; import ucar.nc2.constants.AxisType; import ucar.nc2.dataset.CoordinateAxis; import ucar.nc2.dataset.NetcdfDataset; import ucar.nc2.dataset.VariableEnhanced; import ucar.nc2.dt.GridDataset; import ucar.nc2.dt.GridDatatype; import ucar.nc2.time.CalendarDate; import ucar.nc2.units.DateType; import ucar.unidata.util.Format; import ucar.unidata.util.StringUtil2; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import static thredds.servlet.ServletUtil.setResponseContentLength; /** * Provide methods to write HTML representations of a catalog, directory, or CDM dataset to an HTTP response. * <p/> * HtmlWriter is implemented as a singleton. Before HtmlWriter can be used it * must be initialized with init(...). The singleton instance can then be * obtained with getInstance(). * * @author edavis */ @Component public class HtmlWriter { static private org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(HtmlWriter.class); private static HtmlWriter singleton; @Autowired private TdsContext tdsContext; @Autowired private HtmlConfig htmlConfig; @Autowired private ViewerService viewerService; private HtmlWriter() { } @PostConstruct public void afterPropertiesSet() { singleton = this; } public static HtmlWriter getInstance() { return singleton; } public String getHtmlDoctypeAndOpenTag() { return "<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'\n" + " 'http: } public String getXHtmlDoctypeAndOpenTag() { return "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'\n" + " 'http: "<html xmlns='http: } // public static final String UNIDATA_CSS public String getUserCSS() { return new StringBuilder() .append("<link rel='stylesheet' href='") .append(this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getPageCssUrl())) .append("' type='text/css' >").toString(); } public String getGoogleTrackingContent() { if (this.htmlConfig.getGoogleTrackingCode().isEmpty()){ return ""; } else { return new StringBuilder() .append("<!-- Google Analytics -->\n") .append("<script>\n") .append("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n") .append("(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\n") .append("m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n") .append("})(window,document,'script','https: .append('\n') .append("ga('create', '").append(this.htmlConfig.getGoogleTrackingCode()).append("', 'auto');\n") .append("ga('send', 'pageview');\n") .append("</script>\n") .append("<!-- End Google Analytics -->\n").toString(); } } public String getTdsCatalogCssLink() { return new StringBuilder() .append("<link rel='stylesheet' href='") .append(this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getCatalogCssUrl())) .append("' type='text/css' >").toString(); } public String getTdsPageCssLink() { return new StringBuilder() .append("<link rel='stylesheet' href='") .append(this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getPageCssUrl())) .append("' type='text/css' >").toString(); } // public static final String UNIDATA_HEAD public String getUserHead() { return new StringBuilder() .append("<table width='100%'><tr><td>\n") .append(" <img src='").append(this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getHostInstLogoUrl())) .append("'\n") .append(" alt='").append(this.htmlConfig.getHostInstLogoAlt()).append("'\n") .append(" align='left' valign='top'\n") .append(" hspace='10' vspace='2'>\n") .append(" <h3><strong>").append(this.tdsContext.getWebappName()).append("</strong></h3>\n") .append("</td></tr></table>\n") .toString(); } public String getOldStyleHeader() { StringBuilder sb = new StringBuilder(); appendOldStyleHeader(sb); return sb.toString(); } public void appendOldStyleHeader(StringBuilder sb) { appendOldStyleHeader(sb, this.htmlConfig.getWebappName(), this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getWebappUrl()), this.htmlConfig.getInstallLogoAlt(), this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getInstallLogoUrl()), this.htmlConfig.getInstallName(), this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getInstallUrl()), this.htmlConfig.getHostInstName(), this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getHostInstUrl())); } public void appendOldStyleHeader(StringBuilder sb, String webappName, String webappUrl, String logoAlt, String logoUrl, String installName, String installUrl, String hostName, String hostUrl) { // Table setup. sb.append("<table width='100%'>\n") .append("<tr><td>\n"); // Logo sb.append("<img src='").append(logoUrl) .append("' alt='").append(logoAlt) .append("' align='left' valign='top'") .append(" hspace='10' vspace='2'") .append(">\n"); // Installation name. sb.append("<h3><strong>") .append("<a href='").append(installUrl).append("'>") .append(installName).append("</a>") .append("</strong>"); if (false) sb.append(" at ").append(hostName); sb.append("</h3>\n"); // Webapp Name. sb.append("<h3><strong>") .append("<a href='").append(webappUrl).append("'>") .append(webappName).append("</a>") .append("</strong></h3>\n"); sb.append("</td></tr>\n") .append("</table>\n"); } public void appendTableHeader(StringBuilder stringBuilder, boolean includeInstall, boolean includeWebapp, boolean includeLogos) { // Table setup. stringBuilder .append("<table width='100%'>\n"); if (includeInstall) { stringBuilder.append("<tr><td>\n"); appendInstallationInfo(stringBuilder, includeLogos); stringBuilder.append("</td><td>\n"); appendHostInstInfo(stringBuilder, includeLogos); stringBuilder.append("</td></tr>\n"); } if (includeWebapp) { stringBuilder .append("<tr><td>\n"); appendWebappInfo(stringBuilder, includeLogos); stringBuilder.append("</td></tr>\n"); } stringBuilder.append("</table><hr>\n"); } private void appendWebappInfo(StringBuilder stringBuilder, boolean includeLogo) { // Include webapp info String webappUrl = this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getWebappUrl()); String webappLogoUrl = this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getWebappLogoUrl()); if (includeLogo && webappLogoUrl != null) stringBuilder .append("<img src='").append(webappLogoUrl) .append("' alt='").append(this.htmlConfig.getWebappLogoAlt()) .append("'> "); stringBuilder .append("<a href='").append(webappUrl).append("'>") .append(this.tdsContext.getWebappName()) .append("</a>"); } private void appendHostInstInfo(StringBuilder stringBuilder, boolean includeLogo) { // Include host institution information if (this.htmlConfig.getHostInstName() != null) { String hostInstUrl = this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getHostInstUrl()); String hostInstLogoUrl = this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getHostInstLogoUrl()); if (includeLogo && hostInstLogoUrl != null) stringBuilder .append("<img src='").append(hostInstLogoUrl) .append("' alt='").append(this.htmlConfig.getHostInstLogoAlt()) .append("'> "); if (hostInstUrl != null) stringBuilder.append("<a href='").append(hostInstUrl).append("'>"); stringBuilder.append(this.htmlConfig.getHostInstName()); if (hostInstUrl != null) stringBuilder.append("</a>"); } else stringBuilder.append("Unknown Host Institution"); } private void appendInstallationInfo(StringBuilder stringBuilder, boolean includeLogo) { // Include information on this intsallation. if (this.htmlConfig.getInstallName() != null) { String installUrl = this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getInstallUrl()); String installLogoUrl = this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getInstallLogoUrl()); if (includeLogo && installLogoUrl != null) stringBuilder .append("<img src='").append(installLogoUrl) .append("' alt='").append(this.htmlConfig.getInstallLogoAlt()) .append("'> "); if (installUrl != null) stringBuilder.append("<a href='").append(installUrl).append("'>"); stringBuilder.append(this.htmlConfig.getInstallName()); if (installUrl != null) stringBuilder.append("</a>"); } else { // This installation is not named. stringBuilder.append("Unnamed TDS Installation"); } } public void appendSimpleFooter(StringBuilder sb) { sb.append("<h3>"); if (this.htmlConfig.getInstallName() != null) { String installUrl = this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getInstallUrl()); if (installUrl != null) sb.append("<a href='").append(installUrl).append("'>"); sb.append(this.htmlConfig.getInstallName()); if (installUrl != null) sb.append("</a>"); } if (this.htmlConfig.getHostInstName() != null) { sb.append(" at "); String hostInstUrl = this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getHostInstUrl()); if (hostInstUrl != null) sb.append("<a href='").append(hostInstUrl).append("'>"); sb.append(this.htmlConfig.getHostInstName()); if (hostInstUrl != null) sb.append("</a>"); sb.append(String.format(" see <a href='%s/serverInfo.html'> Info </a>", tdsContext.getContextPath())); sb.append("<br>\n"); } sb.append( this.tdsContext.getWebappName() ) .append( " [Version " ).append( this.tdsContext.getVersionInfo() ); sb.append( "] <a href='" ) .append( this.htmlConfig.prepareUrlStringForHtml( this.htmlConfig.getWebappDocsUrl() ) ) .append( "'> Documentation</a>" ); sb.append( "</h3>\n" ); sb.append( this.getGoogleTrackingContent() ); } private void appendWebappFooter( StringBuilder sb ) { sb.append( "<h3>" ) .append( this.tdsContext.getWebappName() ) .append( " [Version " ).append( this.tdsContext.getVersionInfo() ); sb.append( "] <a href='" ) .append( this.htmlConfig.prepareUrlStringForHtml( this.htmlConfig.getWebappDocsUrl() ) ) .append( "'> Documentation</a>" ); sb.append( "</h3>\n" ); } // private static final String TOMCAT_CSS private String getTomcatCSS() { return new StringBuilder("<STYLE type='text/css'><! .append("H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} ") .append("H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} ") .append("H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} ") .append("BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} ") .append("B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} ") .append("P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}") .append("A {color : black;}") .append("A.name {color : black;}") .append("HR {color : #525D76;}") .append("--></STYLE>\r\n") .toString(); } /** * Write a file directory. * * @param res the HttpServletResponse on which to write the file directory response. * @param dir directory * @param path the URL path reletive to the base * @return the number of characters (Unicode code units) in the response. * @throws java.io.IOException if an I/O exception occurs. */ public int writeDirectory(HttpServletResponse res, File dir, String path) throws IOException { // error checking if (dir == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return 0; } if (!dir.exists() || !dir.isDirectory()) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return 0; } // Get directory as HTML String dirHtmlString = getDirectory(path, dir); res.setContentType(ContentType.html.getContentHeader()); thredds.servlet.ServletUtil.setResponseContentLength(res, dirHtmlString); PrintWriter writer = res.getWriter(); writer.write(dirHtmlString); writer.flush(); return dirHtmlString.length(); } private String getDirectory(String path, File dir) { StringBuilder sb = new StringBuilder(); // Render the page header sb.append(getHtmlDoctypeAndOpenTag()); // "<html>\n" ); sb.append("<head>\r\n"); sb.append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>"); sb.append("<title>"); sb.append("Directory listing for ").append(path); sb.append("</title>\r\n"); sb.append(this.getTdsCatalogCssLink()).append("\n"); sb.append("</head>\r\n"); sb.append("<body>\r\n"); sb.append("<h1>"); sb.append("Directory listing for ").append(path); // Render the link to our parent (if required) String parentDirectory = path; if (parentDirectory.endsWith("/")) { parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } int slash = parentDirectory.lastIndexOf('/'); if (slash >= 0) { String parent = parentDirectory.substring(0, slash); sb.append(" - <a href='"); if (parent.equals("")) { parent = "/"; } sb.append("../"); // sb.append(encode(parent)); //if (!parent.endsWith("/")) // sb.append("/"); sb.append("'>"); sb.append("<b>"); sb.append("Up to ").append(parent); sb.append("</b>"); sb.append("</a>"); } sb.append("</h1>\r\n"); sb.append("<HR size='1' noshade='noshade'>"); sb.append("<table width='100%' cellspacing='0'" + " cellpadding='5' align='center'>\r\n"); // Render the column headings sb.append("<tr>\r\n"); sb.append("<td align='left'><font size='+1'><strong>"); sb.append("Filename"); sb.append("</strong></font></td>\r\n"); sb.append("<td align='center'><font size='+1'><strong>"); sb.append("Size"); sb.append("</strong></font></td>\r\n"); sb.append("<td align='right'><font size='+1'><strong>"); sb.append("Last Modified"); sb.append("</strong></font></td>\r\n"); sb.append("</tr>"); // Render the directory entries within this directory boolean shade = false; File[] children = dir.listFiles(); List<File> fileList = (children == null) ? new ArrayList<File>() : Arrays.asList(children); Collections.sort(fileList); for (File child : fileList) { String childname = child.getName(); if (childname.equalsIgnoreCase("WEB-INF") || childname.equalsIgnoreCase("META-INF")) { continue; } if (child.isDirectory()) childname = childname + "/"; //if (!endsWithSlash) childname = path + "/" + childname; // client removes last path if no slash sb.append("<tr"); if (shade) { sb.append(" bgcolor='#eeeeee'"); } sb.append(">\r\n"); shade = !shade; sb.append("<td align='left'>&nbsp;&nbsp;\r\n"); sb.append("<a href='"); //sb.append( encode(contextPath)); // resourceName = encode(path + resourceName); sb.append(childname); sb.append("'><tt>"); sb.append(childname); sb.append("</tt></a></td>\r\n"); sb.append("<td align='right'><tt>"); if (child.isDirectory()) { sb.append("&nbsp;"); } else { sb.append(renderSize(child.length())); } sb.append("</tt></td>\r\n"); sb.append("<td align='right'><tt>"); sb.append(CalendarDate.of(child.lastModified()).toString()); sb.append("</tt></td>\r\n"); sb.append("</tr>\r\n"); } // Render the page footer sb.append("</table>\r\n"); sb.append("<HR size='1' noshade='noshade'>"); appendSimpleFooter(sb); sb.append("</body>\r\n"); sb.append("</html>\r\n"); return sb.toString(); } private String renderSize(long size) { long leftSide = size / 1024; long rightSide = (size % 1024) / 103; // Makes 1 digit if ((leftSide == 0) && (rightSide == 0) && (size > 0)) { rightSide = 1; } return ("" + leftSide + "." + rightSide + " kb"); } /** * Write an InvCatalogImpl to the HttpServletResponse, return the size in bytes of the catalog written to the response. * * @param req the HttpServletRequest * @param res the HttpServletResponse. * @param cat the InvCatalogImpl to write to the HttpServletResponse. * @param isLocalCatalog indicates whether this catalog is local to this server. * @return the size in bytes of the catalog written to the HttpServletResponse. * @throws IOException if problems writing the response. */ public int writeCatalog(HttpServletRequest req, HttpServletResponse res, InvCatalogImpl cat, boolean isLocalCatalog) throws IOException { String catHtmlAsString = convertCatalogToHtml(cat, isLocalCatalog); // Once this header is set, we know the encoding, and thus the actual // number of *bytes*, not characters, to encode res.setContentType(ContentType.html.getContentHeader()); int len = setResponseContentLength(res, catHtmlAsString); if (!req.getMethod().equals("HEAD")) { PrintWriter writer = res.getWriter(); writer.write(catHtmlAsString); writer.flush(); } return len; } /** * Write a catalog in HTML, make it look like a file directory. * * @param cat catalog to write */ String convertCatalogToHtml(InvCatalogImpl cat, boolean isLocalCatalog) { StringBuilder sb = new StringBuilder(10000); String catname = StringUtil2.quoteHtmlContent(cat.getUriString()); // Render the page header sb.append(getHtmlDoctypeAndOpenTag()); // "<html>\n" ); sb.append("<head>\r\n"); sb.append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>"); sb.append("<title>"); if (cat.isStatic()) sb.append("TdsStaticCatalog ").append(catname); // for searching else sb.append("Catalog ").append(catname); sb.append("</title>\r\n"); sb.append(this.getTdsCatalogCssLink()).append("\n"); sb.append("</head>\r\n"); sb.append("<body>"); sb.append("<h1>"); // Logo //String logoUrl = this.htmlConfig.getInstallLogoUrl(); String logoUrl = this.htmlConfig.prepareUrlStringForHtml(this.htmlConfig.getInstallLogoUrl()); if (logoUrl != null) { sb.append("<img src='").append(logoUrl); String logoAlt = this.htmlConfig.getInstallLogoAlt(); if (logoAlt != null) sb.append("' alt='").append(logoAlt); sb.append("' align='left' valign='top'") // .append(" hspace='10' vspace='2'") .append(">\n"); } sb.append("Catalog ").append(catname); sb.append("</h1>"); sb.append("<HR size='1' noshade='noshade'>"); sb.append("<table width='100%' cellspacing='0' cellpadding='5' align='center'>\r\n"); // Render the column headings sb.append("<tr>\r\n"); sb.append("<th align='left'><font size='+1'>"); sb.append("Dataset"); sb.append("</font></th>\r\n"); sb.append("<th align='center'><font size='+1'>"); sb.append("Size"); sb.append("</font></th>\r\n"); sb.append("<th align='right'><font size='+1'>"); sb.append("Last Modified"); sb.append("</font></th>\r\n"); sb.append("</tr>"); // Recursively render the datasets doDatasets(cat, cat.getDatasets(), sb, false, 0, isLocalCatalog); // Render the page footer sb.append("</table>\r\n"); sb.append("<HR size='1' noshade='noshade'>"); appendSimpleFooter(sb); sb.append("</body>\r\n"); sb.append("</html>\r\n"); return sb.toString(); } private boolean doDatasets(InvCatalogImpl cat, List<InvDataset> datasets, StringBuilder sb, boolean shade, int level, boolean isLocalCatalog) { //URI catURI = cat.getBaseURI(); String catHtml; if (!isLocalCatalog) { // Setup HREF url to link to HTML dataset page (more below). catHtml = this.tdsContext.getContextPath() + "/remoteCatalogService?command=subset&catalog=" + cat.getUriString() + "&"; // Can't be "/catalogServices?..." because subset decides on xml or html by trailing ".html" on URL path } else { // replace xml with html URI catURI = cat.getBaseURI(); // Get the catalog name - we want a relative URL catHtml = catURI.getPath(); if (catHtml == null) catHtml = cat.getUriString(); // if URI is a file int pos = catHtml.lastIndexOf("/"); if (pos != -1) catHtml = catHtml.substring(pos + 1); // change the ending to "catalog.html?" pos = catHtml.lastIndexOf('.'); if (pos < 0) catHtml = catHtml + "catalog.html?"; else catHtml = catHtml.substring(0, pos) + ".html?"; } for (InvDataset dataset : datasets) { InvDatasetImpl ds = (InvDatasetImpl) dataset; String name = StringUtil2.quoteHtmlContent(ds.getName()); sb.append("<tr"); if (shade) { sb.append(" bgcolor='#eeeeee'"); } sb.append(">\r\n"); shade = !shade; sb.append("<td align='left'>"); for (int j = 0; j <= level; j++) { sb.append("&nbsp;&nbsp;&nbsp;&nbsp;"); } sb.append("\r\n"); if (ds instanceof InvCatalogRef) { InvCatalogRef catref = (InvCatalogRef) ds; String href = catref.getXlinkHref(); if (!isLocalCatalog) { URI hrefUri = cat.getBaseURI().resolve(href); href = hrefUri.toString(); } try { URI uri = new URI(href); if (uri.isAbsolute()) { // read default as set in threddsConfig.xml boolean defaultUseRemoteCatalogService = this.htmlConfig.getUseRemoteCatalogService(); // check to see if catalogRef contains tag that overrides default Boolean dsUseRemoteCatalogSerivce = ((InvCatalogRef) ds).useRemoteCatalogService(); // by default, use the option found in threddsConfig.xml boolean useRemoteCatalogService = defaultUseRemoteCatalogService; // if the dataset does not have the useRemoteDataset option set, opt for the default behavior if (dsUseRemoteCatalogSerivce == null) dsUseRemoteCatalogSerivce = defaultUseRemoteCatalogService; // if the default is not the same as what is defined in the catalog, go with the catalog option // as the user has explicitly overridden the default if (defaultUseRemoteCatalogService != dsUseRemoteCatalogSerivce) { useRemoteCatalogService = dsUseRemoteCatalogSerivce; } // now, do the right thing with using the remoteCatalogService, or not if (useRemoteCatalogService) { href = this.tdsContext.getContextPath() + "/remoteCatalogService?catalog=" + href; } else { int pos = href.lastIndexOf('.'); href = href.substring(0, pos) + ".html"; } } else { int pos = href.lastIndexOf('.'); href = href.substring(0, pos) + ".html"; } } catch (URISyntaxException e) { log.error(href, e); } sb.append("<img src='").append(htmlConfig.prepareUrlStringForHtml(htmlConfig.getFolderIconUrl())) .append("' alt='").append(htmlConfig.getFolderIconAlt()).append("'> &nbsp;"); sb.append("<a href='"); sb.append(StringUtil2.quoteHtmlContent(href)); sb.append("'><tt>"); sb.append(name); sb.append("/</tt></a></td>\r\n"); } else // Not an InvCatalogRef { if (ds.hasNestedDatasets()) sb.append("<img src='").append(htmlConfig.prepareUrlStringForHtml(htmlConfig.getFolderIconUrl())) .append("' alt='").append(htmlConfig.getFolderIconAlt()).append("'> &nbsp;"); // Check if dataset has single resolver service. if (ds.getAccess().size() == 1 && (ds.getAccess().get(0)).getService().getServiceType().equals(ServiceType.RESOLVER)) { InvAccess access = ds.getAccess().get(0); String accessUrlName = access.getUnresolvedUrlName(); int pos = accessUrlName.lastIndexOf(".xml"); if (accessUrlName.equalsIgnoreCase("latest.xml") && !isLocalCatalog) { String catBaseUriPath = ""; String catBaseUri = cat.getBaseURI().toString(); pos = catBaseUri.lastIndexOf("catalog.xml"); if (pos != -1) { catBaseUriPath = catBaseUri.substring(0,pos); } accessUrlName = this.tdsContext.getContextPath() + "/remoteCatalogService?catalog=" + catBaseUriPath + accessUrlName; } else if (pos != -1) { accessUrlName = accessUrlName.substring(0, pos) + ".html"; } sb.append("<a href='"); sb.append(StringUtil2.quoteHtmlContent(accessUrlName)); sb.append("'><tt>"); String tmpName = name; if (tmpName.endsWith(".xml")) { tmpName = tmpName.substring(0, tmpName.lastIndexOf('.')); } sb.append(tmpName); sb.append("</tt></a></td>\r\n"); } // Dataset with an ID. else if (ds.getID() != null) { // Write link to HTML dataset page. sb.append("<a href='"); sb.append(StringUtil2.quoteHtmlContent(catHtml)); sb.append("dataset="); sb.append(StringUtil2.replace(ds.getID(), '+', "%2B")); sb.append("'><tt>"); sb.append(name); sb.append("</tt></a></td>\r\n"); } // Dataset without an ID. else { sb.append("<tt>"); sb.append(name); sb.append("</tt></td>\r\n"); } } sb.append("<td align='right'><tt>"); double size = ds.getDataSize(); if ((size != 0.0) && !Double.isNaN(size)) { sb.append(Format.formatByteSize(size)); } else { sb.append("&nbsp;"); } sb.append("</tt></td>\r\n"); sb.append("<td align='right'><tt>"); // Get last modified time. DateType lastModDateType = ds.getLastModifiedDate(); if (lastModDateType == null) { sb.append("--");// "Unknown"); } else { sb.append(lastModDateType.toDateTimeString()); } sb.append("</tt></td>\r\n"); sb.append("</tr>\r\n"); if (!(ds instanceof InvCatalogRef)) { shade = doDatasets(cat, ds.getDatasets(), sb, shade, level + 1, isLocalCatalog); } } return shade; } private String convertDatasetToHtml(String catURL, InvDatasetImpl dataset, HttpServletRequest request, boolean isLocalCatalog) { StringBuilder sb = new StringBuilder(10000); sb.append(this.getHtmlDoctypeAndOpenTag()); sb.append("<head>\r\n"); sb.append("<title> Catalog Services</title>\r\n"); sb.append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>\r\n"); sb.append(this.getTdsPageCssLink()); sb.append("</head>\r\n"); sb.append("<body>\r\n"); this.appendOldStyleHeader(sb); //this.appendTableHeader( sb, true, true, true ); sb.append("<h2> Catalog ").append(catURL).append("</h2>\r\n"); InvDatasetImpl.writeHtmlDescription(sb, dataset, false, true, false, false, !isLocalCatalog); // optional access through Viewers if (isLocalCatalog) viewerService.showViewers(sb, dataset, request); sb.append( this.getGoogleTrackingContent() ); sb.append( "</body>\r\n" ); sb.append( "</html>\r\n" ); return sb.toString(); } public int showDataset(String catURL, InvDatasetImpl dataset, HttpServletRequest request, HttpServletResponse response, boolean isLocalCatalog) throws IOException { String datasetAsHtml = this.convertDatasetToHtml(catURL, dataset, request, isLocalCatalog); response.setStatus(HttpServletResponse.SC_OK); response.setContentType(ContentType.html.getContentHeader()); if (!request.getMethod().equals("HEAD")) { PrintWriter pw = response.getWriter(); pw.write(datasetAsHtml); pw.flush(); } return datasetAsHtml.length(); } /** * Show CDM compliance (coordinate systems, etc) of a NetcdfDataset. * * @param ds dataset to write */ public void showCDM(HttpServletResponse res, NetcdfDataset ds) throws IOException { String cdmAsString = getCDM(ds); res.setContentType(ContentType.html.getContentHeader()); thredds.servlet.ServletUtil.setResponseContentLength(res, cdmAsString); PrintWriter writer = res.getWriter(); writer.write(cdmAsString); writer.flush(); } private String getCDM(NetcdfDataset ds) throws IOException { StringBuilder sb = new StringBuilder(10000); String name = StringUtil2.quoteHtmlContent(ds.getLocation()); // Render the page header sb.append(getHtmlDoctypeAndOpenTag()); // "<html>\n" ); sb.append("<head>\r\n"); sb.append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>"); sb.append("<title>"); sb.append("Common Data Model"); sb.append("</title>\r\n"); sb.append(this.getTdsPageCssLink()).append("\n"); sb.append("</head>\r\n"); sb.append("<body>"); sb.append("<h1>"); sb.append("Dataset ").append(name); sb.append("</h1>"); sb.append("<HR size='1' noshade='noshade'>"); sb.append("<table width='100%' cellspacing='0'" + " cellpadding='5' align='center'>\r\n"); //////// Axis sb.append("<tr>\r\n"); sb.append("<td align='left'><font size='+1'><strong>"); sb.append("Axis"); sb.append("</strong></font></td>\r\n"); sb.append("<td align='left'><font size='+1'><strong>"); sb.append("Type"); sb.append("</strong></font></td>\r\n"); sb.append("<td align='left'><font size='+1'><strong>"); sb.append("Units"); sb.append("</strong></font></td>\r\n"); sb.append("</tr>"); // Show the coordinate axes boolean shade = false; for (CoordinateAxis axis : ds.getCoordinateAxes()) { showAxis(axis, sb, shade); shade = !shade; } ///////////// Grid GridDataset gds = new ucar.nc2.dt.grid.GridDataset(ds); // look for projections //List gridsets = gds.getGridsets(); sb.append("<tr>\r\n"); sb.append("<td align='left'><font size='+1'><strong>"); sb.append("GeoGrid"); sb.append("</strong></font></td>\r\n"); sb.append("<td align='left'><font size='+1'><strong>"); sb.append("Description"); sb.append("</strong></font></td>\r\n"); sb.append("<td align='left'><font size='+1'><strong>"); sb.append("Units"); sb.append("</strong></font></td>\r\n"); sb.append("</tr>"); // Show the grids shade = false; for (GridDatatype grid : gds.getGrids()) { showGrid(grid, sb, shade); shade = !shade; } // Render the page footer sb.append("</table>\r\n"); sb.append("<HR size='1' noshade='noshade'>"); appendSimpleFooter(sb); sb.append("</body>\r\n"); sb.append("</html>\r\n"); return (sb.toString()); } private void showAxis(CoordinateAxis axis, StringBuilder sb, boolean shade) { sb.append("<tr"); if (shade) { sb.append(" bgcolor='#eeeeee'"); } sb.append(">\r\n"); shade = !shade; sb.append("<td align='left'>"); sb.append("\r\n"); StringBuilder sbuff = new StringBuilder(); axis.getNameAndDimensions(sbuff); String name = StringUtil2.quoteHtmlContent(sbuff.toString()); sb.append("&nbsp;"); sb.append(name); sb.append("</tt></a></td>\r\n"); sb.append("<td align='left'><tt>"); AxisType type = axis.getAxisType(); String stype = (type == null) ? "" : StringUtil2.quoteHtmlContent(type.toString()); sb.append(stype); sb.append("</tt></td>\r\n"); sb.append("<td align='left'><tt>"); String units = axis.getUnitsString(); String sunits = (units == null) ? "" : units; sb.append(sunits); sb.append("</tt></td>\r\n"); sb.append("</tr>\r\n"); } private void showGrid(GridDatatype grid, StringBuilder sb, boolean shade) { sb.append("<tr"); if (shade) { sb.append(" bgcolor='#eeeeee'"); } sb.append(">\r\n"); shade = !shade; sb.append("<td align='left'>"); sb.append("\r\n"); VariableEnhanced ve = grid.getVariable(); StringBuilder sbuff = new StringBuilder(); ve.getNameAndDimensions(new Formatter(sbuff), false, true); String name = StringUtil2.quoteHtmlContent(sbuff.toString()); sb.append("&nbsp;"); sb.append(name); sb.append("</tt></a></td>\r\n"); sb.append("<td align='left'><tt>"); String desc = ve.getDescription(); String sdesc = (desc == null) ? "" : StringUtil2.quoteHtmlContent(desc); sb.append(sdesc); sb.append("</tt></td>\r\n"); sb.append("<td align='left'><tt>"); String units = ve.getUnitsString(); String sunits = (units == null) ? "" : units; sb.append(sunits); sb.append("</tt></td>\r\n"); sb.append("</tr>\r\n"); } }
package com.android.server; //@Singleton public class SystemServiceManager { public static SystemServiceManager getInstance(); public void registerService(String name, Object service); public Object getService(String name); }
package jolie.net.protocols; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import jolie.net.AbstractCommChannel; import jolie.net.CommChannel; import jolie.net.CommMessage; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.VariablePath; /** * A CommProtocol implements a protocol for sending and receiving data under the form of CommMessage objects. * This class should not be extended directly; see {@link ConcurrentCommProtocol ConcurrentCommProtocol} and {@link SequentialCommProtocol SequentialCommProtocol} instead. * @author Fabrizio Montesi */ public abstract class CommProtocol { private final static class LazyDummyChannelHolder { private LazyDummyChannelHolder() {} private static class DummyChannel extends AbstractCommChannel { public void closeImpl() {} public void sendImpl( CommMessage message ) {} public CommMessage recvImpl() { return CommMessage.UNDEFINED_MESSAGE; } } private final static DummyChannel dummyChannel = new DummyChannel(); } private static class Parameters { private static final String OPERATION_SPECIFIC_CONFIGURATION = "osc"; } private final VariablePath configurationPath; private CommChannel channel = null; protected VariablePath configurationPath() { return configurationPath; } public abstract String name(); public CommProtocol( VariablePath configurationPath ) { this.configurationPath = configurationPath; } public void setChannel( CommChannel channel ) { this.channel = channel; } protected CommChannel channel() { if ( this.channel == null ) { return LazyDummyChannelHolder.dummyChannel; } return this.channel; } protected ValueVector getParameterVector( String id ) { return configurationPath.getValue().getChildren( id ); } protected boolean hasParameter( String id ) { if ( configurationPath.getValue().hasChildren( id ) ) { Value v = configurationPath.getValue().getFirstChild( id ); return v.isDefined() || v.hasChildren(); } return false; } protected boolean hasParameterValue( String id ) { if ( configurationPath.getValue().hasChildren( id ) ) { Value v = configurationPath.getValue().getFirstChild( id ); return v.isDefined(); } return false; } /** * Shortcut for getParameterVector( id ).first() */ protected Value getParameterFirstValue( String id ) { return getParameterVector( id ).first(); } /** * Shortcut for checking if a parameter intValue() equals 1 * @param id the parameter identifier */ protected boolean checkBooleanParameter( String id ) { return hasParameter( id ) && getParameterFirstValue( id ).boolValue(); } /** * Shortcut for checking if a parameter intValue() equals 1 * @param id the parameter identifier */ protected boolean checkBooleanParameter( String id, boolean defaultValue ) { if ( hasParameter( id ) ) { return getParameterFirstValue( id ).boolValue(); } else { return defaultValue; } } /** * Shortcut for checking if a string parameter has a given value * @param id the parameter identifier * @param value the value for checking the parameter with * @return {@code true} if the parameter has the expected value, {@code false} otherwise */ protected boolean checkStringParameter( String id, String value ) { if ( hasParameter( id ) ) { return getParameterFirstValue( id ).strValue().equals( value ); } else { return false; } } /** * Shortcut for <code>getParameterFirstValue( id ).strValue()</code> * @param id the parameter identifier */ protected String getStringParameter( String id ) { return getStringParameter( id, "" ); } protected String getStringParameter( String id, String defaultValue ) { return ( hasParameter( id ) ? getParameterFirstValue( id ).strValue() : defaultValue ); } protected boolean hasOperationSpecificParameter( String operationName, String parameterName ) { if ( hasParameter( Parameters.OPERATION_SPECIFIC_CONFIGURATION ) ) { Value osc = getParameterFirstValue( Parameters.OPERATION_SPECIFIC_CONFIGURATION ); if ( osc.hasChildren( operationName ) ) { return osc.getFirstChild( operationName ).hasChildren( parameterName ); } } return false; } protected String getOperationSpecificStringParameter( String operationName, String parameterName ) { if ( hasParameter( Parameters.OPERATION_SPECIFIC_CONFIGURATION ) ) { Value osc = getParameterFirstValue( Parameters.OPERATION_SPECIFIC_CONFIGURATION ); if ( osc.hasChildren( operationName ) ) { Value opConfig = osc.getFirstChild( operationName ); if ( opConfig.hasChildren( parameterName ) ) { return opConfig.getFirstChild( parameterName ).strValue(); } } } return ""; } /** * Shortcut for getOperationSpecificParameterVector( id ).first() */ protected Value getOperationSpecificParameterFirstValue( String operationName, String parameterName ) { return getOperationSpecificParameterVector( operationName, parameterName ).first(); } protected ValueVector getOperationSpecificParameterVector( String operationName, String parameterName ) { Value osc = getParameterFirstValue( Parameters.OPERATION_SPECIFIC_CONFIGURATION ); return osc.getFirstChild( operationName ).getChildren( parameterName ); } /** * Shortcut for <code>getParameterFirstValue( id ).intValue()</code> * @param id the parameter identifier */ protected int getIntParameter( String id ) { return ( hasParameter( id ) ? getParameterFirstValue( id ).intValue() : 0 ); } abstract public CommMessage recv( InputStream istream, OutputStream ostream ) throws IOException; abstract public void send( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException; abstract public boolean isThreadSafe(); }
package joliex.util; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import jolie.net.CommMessage; import jolie.runtime.AndJarDeps; import jolie.runtime.FaultException; import jolie.runtime.JavaService; import jolie.runtime.Value; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @AndJarDeps({"jolie-xml.jar"}) public class XmlUtils extends JavaService { final private DocumentBuilderFactory documentBuilderFactory; public XmlUtils() { this.documentBuilderFactory = DocumentBuilderFactory.newInstance(); } public CommMessage valueToXml( CommMessage request ) throws FaultException { try { Document doc = documentBuilderFactory.newDocumentBuilder().newDocument(); String root = request.value().getFirstChild( "root" ).strValue(); jolie.xml.XmlUtils.valueToDocument( request.value().getFirstChild( root ), root, doc ); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer t = tFactory.newTransformer(); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult( writer ); t.transform( new DOMSource( doc ), result ); return CommMessage.createResponse( request, Value.create( writer.toString() ) ); } catch( ParserConfigurationException e ) { e.printStackTrace(); throw new FaultException( e ); } catch( TransformerConfigurationException e ) { e.printStackTrace(); throw new FaultException( e ); } catch( TransformerException e ) { e.printStackTrace(); throw new FaultException( e ); } } public CommMessage xmlToValue( CommMessage request ) throws FaultException { try { Value result = Value.create(); DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); InputSource src; if ( request.value().isByteArray() ) { src = new InputSource( new ByteArrayInputStream( request.value().byteArrayValue().getBytes() ) ); } else { src = new InputSource( new StringReader( request.value().strValue() ) ); } Document doc = builder.parse( src ); jolie.xml.XmlUtils.documentToValue( doc, result ); return CommMessage.createResponse( request, result ); } catch( ParserConfigurationException e ) { e.printStackTrace(); throw new FaultException( e ); } catch( SAXException e ) { e.printStackTrace(); throw new FaultException( e ); } catch( IOException e ) { e.printStackTrace(); throw new FaultException( e ); } } public CommMessage transform( CommMessage request ) throws FaultException { try { StreamSource source = new StreamSource( new StringReader( request.value().getFirstChild( "source" ).strValue() ) ); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer t = tFactory.newTransformer( new StreamSource( new StringReader( request.value().getFirstChild( "xslt" ).strValue() ) ) ); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult( writer ); t.transform( source, result ); return CommMessage.createResponse( request, Value.create( writer.toString() ) ); } catch( TransformerException e ) { e.printStackTrace(); throw new FaultException( e ); } } }
package org.jpos.q2.iso; import java.util.Iterator; import java.util.StringTokenizer; import org.jdom.Element; import org.jpos.core.ConfigurationException; import org.jpos.iso.*; import org.jpos.q2.QBeanSupport; import org.jpos.q2.QFactory; import org.jpos.space.LocalSpace; import org.jpos.space.Space; import org.jpos.space.SpaceFactory; import org.jpos.space.SpaceListener; import org.jpos.util.LogSource; import org.jpos.util.NameRegistrar; import org.jpos.util.ThreadPool; /** * ISO Server wrapper. * * @author Alwyn Schoeman * @version $Revision$ $Date$ * @jmx:mbean description="ISOServer wrapper" * extends="org.jpos.q2.QBeanSupportMBean" */ public class QServer extends QBeanSupport implements QServerMBean, SpaceListener, ISORequestListener { private int port = 0; private int maxSessions = 100; private int minSessions = 1; private String channelString, packagerString, socketFactoryString; private ISOChannel channel = null; private ISOServer server; protected LocalSpace sp; private String inQueue; private String outQueue; private String sendMethod; public QServer () { super (); } @Override public void initService() throws ConfigurationException { Element e = getPersist (); sp = grabSpace (e.getChild ("space")); } private void newChannel () throws ConfigurationException { Element persist = getPersist (); Element e = persist.getChild ("channel"); if (e == null) { throw new ConfigurationException ("channel element missing"); } ChannelAdaptor adaptor = new ChannelAdaptor (); channel = adaptor.newChannel (e, getFactory ()); } private void initServer () throws ConfigurationException { if (port == 0) { throw new ConfigurationException ("Port value not set"); } newChannel(); if (channel == null) { throw new ConfigurationException ("ISO Channel is null"); } if (!(channel instanceof ServerChannel)) { throw new ConfigurationException (channelString + "does not implement ServerChannel"); } ThreadPool pool = null; pool = new ThreadPool (minSessions ,maxSessions); pool.setLogger (log.getLogger(), getName() + ".pool"); server = new ISOServer (port, (ServerChannel) channel, pool); server.setLogger (log.getLogger(), getName() + ".server"); server.setName (getName ()); if (socketFactoryString != null) { ISOServerSocketFactory sFac = (ISOServerSocketFactory) getFactory().newInstance(socketFactoryString); if (sFac != null && sFac instanceof LogSource) { ((LogSource) sFac).setLogger(log.getLogger(),getName() + ".socket-factory"); } server.setSocketFactory(sFac); } getFactory().setConfiguration (server, getPersist()); addServerSocketFactory(); addListeners ();// ISORequestListener addISOServerConnectionListeners(); NameRegistrar.register (getName(), this); new Thread (server).start(); } private void initIn() { Element persist = getPersist(); inQueue = persist.getChildText("in"); if (inQueue != null) { /* * We have an 'in' queue to monitor for messages we will * send out through server in our (SpaceListener)notify(Object, Object) method. */ sp.addListener(inQueue, this); } } private void initOut() { Element persist = getPersist(); outQueue = persist.getChildText("out"); if (outQueue != null) { /* * We have an 'out' queue to send any messages to that are received * by the our requestListner(this). * * Note, if additional ISORequestListeners are registered with the server after * this point, then they won't see anything as our process(ISOSource, ISOMsg) * always return true. */ server.addISORequestListener(this); } } @Override public void startService () { try { initServer (); initIn(); initOut(); initWhoToSendTo(); } catch (Exception e) { getLog().warn ("error starting service", e); } } private void initWhoToSendTo() { Element persist = getPersist(); sendMethod = persist.getChildText("send-request"); if (sendMethod==null) { sendMethod="LAST"; } } @Override public void stopService () { if (server != null) { server.shutdown (); } } @Override public void destroyService () { NameRegistrar.unregister (getName()); NameRegistrar.unregister ("server." + getName()); } /** * @jmx:managed-attribute description="Server port" */ @Override public synchronized void setPort (int port) { this.port = port; setAttr (getAttrs (), "port", Integer.valueOf(port)); setModified (true); } /** * @jmx:managed-attribute description="Server port" */ @Override public int getPort () { return port; } /** * @jmx:managed-attribute description="Packager" */ @Override public synchronized void setPackager (String packager) { packagerString = packager; setAttr (getAttrs (), "packager", packagerString); setModified (true); } /** * @jmx:managed-attribute description="Packager" */ @Override public String getPackager () { return packagerString; } /** * @jmx:managed-attribute description="Channel" */ @Override public synchronized void setChannel (String channel) { channelString = channel; setAttr (getAttrs (), "channel", channelString); setModified (true); } /** * @jmx:managed-attribute description="Channel" */ @Override public String getChannel () { return channelString; } /** * @jmx:managed-attribute description="Maximum Nr. of Sessions" */ @Override public synchronized void setMaxSessions (int maxSessions) { this.maxSessions = maxSessions; setAttr (getAttrs (), "maxSessions", Integer.valueOf(maxSessions)); setModified (true); } /** * @jmx:managed-attribute description="Maximum Nr. of Sessions" */ @Override public int getMaxSessions () { return maxSessions; } /** * @jmx:managed-attribute description="Minimum Nr. of Sessions" */ @Override public synchronized void setMinSessions (int minSessions) { this.minSessions = minSessions; setAttr (getAttrs (), "minSessions", Integer.valueOf(minSessions)); setModified (true); } /** * @jmx:managed-attribute description="Minimum Nr. of Sessions" */ @Override public int getMinSessions () { return minSessions; } /** * @jmx:managed-attribute description="Socket Factory" */ @Override public synchronized void setSocketFactory (String sFactory) { socketFactoryString = sFactory; setAttr (getAttrs(),"socketFactory", socketFactoryString); setModified (true); } /** * @jmx:managed-attribute description="Socket Factory" */ @Override public String getSocketFactory() { return socketFactoryString; } @Override public String getISOChannelNames() { return server.getISOChannelNames(); } @Override public String getCountersAsString () { return server.getCountersAsString (); } @Override public String getCountersAsString (String isoChannelName) { return server.getCountersAsString (isoChannelName); } private void addServerSocketFactory () throws ConfigurationException { QFactory factory = getFactory (); Element persist = getPersist (); Element serverSocketFactoryElement = persist.getChild ("server-socket-factory"); if (serverSocketFactoryElement != null) { ISOServerSocketFactory serverSocketFactory = (ISOServerSocketFactory) factory.newInstance (serverSocketFactoryElement.getAttributeValue ("class")); factory.setLogger (serverSocketFactory, serverSocketFactoryElement); factory.setConfiguration (serverSocketFactory, serverSocketFactoryElement); server.setSocketFactory(serverSocketFactory); } } private void addListeners () throws ConfigurationException { QFactory factory = getFactory (); Iterator iter = getPersist().getChildren ( "request-listener" ).iterator(); while (iter.hasNext()) { Element l = (Element) iter.next(); ISORequestListener listener = (ISORequestListener) factory.newInstance (l.getAttributeValue ("class")); factory.setLogger (listener, l); factory.setConfiguration (listener, l); server.addISORequestListener (listener); } } private void addISOServerConnectionListeners() throws ConfigurationException { QFactory factory = getFactory (); Iterator iter = getPersist().getChildren ( "connection-listener" ).iterator(); while (iter.hasNext()) { Element l = (Element) iter.next(); ISOServerEventListener listener = (ISOServerEventListener) factory.newInstance (l.getAttributeValue ("class")); factory.setLogger (listener, l); factory.setConfiguration (listener, l); server.addServerEventListener(listener); } } private LocalSpace grabSpace (Element e) throws ConfigurationException { String uri = e != null ? e.getText() : ""; Space sp = SpaceFactory.getSpace (uri); if (sp instanceof LocalSpace) { return (LocalSpace) sp; } throw new ConfigurationException ("Invalid space " + uri); } /* * This method will be invoked through the SpaceListener interface we registered once * we noticed we had an 'in' queue. */ @Override public void notify(Object key, Object value) { Object obj = sp.inp(key); if (obj instanceof ISOMsg) { ISOMsg m = (ISOMsg) obj; if ("LAST".equals(sendMethod)) { try { ISOChannel c = server.getLastConnectedISOChannel(); if (c == null) { throw new ISOException("Server has no active connections"); } if (!c.isConnected()) { throw new ISOException("Client disconnected"); } c.send(m); } catch (Exception e) { getLog().warn("notify", e); } } else if ("ALL".equals(sendMethod)) { String channelNames = getISOChannelNames(); if (channelNames!=null) { StringTokenizer tok =new StringTokenizer(channelNames, " "); while (tok.hasMoreTokens()) { try { ISOChannel c = server.getISOChannel(tok.nextToken()); if (c == null) { throw new ISOException("Server has no active connections"); } if (!c.isConnected()) { throw new ISOException("Client disconnected"); } c.send(m); } catch (Exception e) { getLog().warn("notify", e); } } } } } } /* * This method will be invoke through the ISORequestListener interface, *if* * this QServer has an 'out' queue to handle. */ @Override public boolean process(ISOSource source, ISOMsg m) { sp.out(outQueue, m); return true; } }
package to.etc.domui.dom; import java.util.*; import to.etc.domui.component.misc.*; import to.etc.domui.dom.header.*; import to.etc.domui.dom.html.*; import to.etc.domui.server.*; import to.etc.util.*; public class HtmlFullRenderer extends NodeVisitorBase { // private BrowserVersion m_browserVersion; /** The thingy responsible for rendering the tags, */ private HtmlTagRenderer m_tagRenderer; private IBrowserOutput m_o; private IRequestContext m_ctx; private Page m_page; private boolean m_xml; private StringBuilder m_createJS = new StringBuilder(); private StringBuilder m_stateJS = new StringBuilder(); protected HtmlFullRenderer(HtmlTagRenderer tagRenderer, IBrowserOutput o) { // m_browserVersion = tagRenderer.getBrowser(); m_tagRenderer = tagRenderer; m_o = o; // 20090701 jal was ADDS which is WRONG - by definition a FULL render IS a full renderer... This caused SELECT tags to be rendered with domui_selected attributes instead of selected attributes. setRenderMode(HtmlRenderMode.FULL); } public HtmlTagRenderer getTagRenderer() { // 20090701 jal was ADDS which is WRONG - by definition a FULL render IS a full renderer... This caused SELECT tags to be rendered with domui_selected attributes instead of selected attributes. // 20091002 jal removed, make callers specify render mode... // m_tagRenderer.setRenderMode(HtmlRenderMode.FULL); // All nodes from the full renderer are NEW by definition. return m_tagRenderer; } public HtmlRenderMode getMode() { return m_tagRenderer.getMode(); } public void setRenderMode(HtmlRenderMode m) { m_tagRenderer.setRenderMode(m); } public boolean isXml() { return m_xml; } public void setXml(boolean xml) { m_xml = xml; } public IBrowserOutput o() { return m_o; } public IRequestContext ctx() { return m_ctx; } public Page page() { return m_page; } @Override public void visitNodeBase(NodeBase n) throws Exception { n.build(); n.onBeforeFullRender(); // Do pre-node stuff, n.visit(getTagRenderer()); if(n.getCreateJS() != null) m_createJS.append(n.getCreateJS()); n.renderJavascriptState(m_stateJS); // Append Javascript state to state buffer if(!(n instanceof TextNode)) { if(m_xml) getTagRenderer().renderEndTag(n); else m_o.dec(); // 20080626 img et al does not dec()... } n.internalClearDelta(); checkForFocus(n); } /** * Overridden because this is a NodeBase node which MUST be terminated with a /div, always. * @see to.etc.domui.dom.html.NodeVisitorBase#visitLiteralXhtml(to.etc.domui.component.misc.LiteralXhtml) */ @Override @Deprecated public void visitLiteralXhtml(LiteralXhtml n) throws Exception { visitNodeBase(n); // Handle most thingies we need to do, if(!m_xml) { //-- In HTML mode we MUST end this tag, and we need to inc() because the visitNodeBase() has decremented.. m_o.inc(); getTagRenderer().renderEndTag(n); // Force close the tag in HTML mode. } } /** * Overridden to fix bug 627; this prevents embedding content in textarea and renders the value as * an attribute. * * @see to.etc.domui.dom.html.NodeVisitorBase#visitTextArea(to.etc.domui.dom.html.TextArea) */ @Override public void visitTextArea(TextArea n) throws Exception { if(getMode() == HtmlRenderMode.FULL) { // In FULL mode render content inside textarea goddamnit visitNodeContainer(n); return; } visitNodeBase(n); o().setIndentEnabled(true); // jal 20091002 indent when rendering js attribute // getTagRenderer().renderEndTag(n); } @Override public void visitNodeContainer(NodeContainer n) throws Exception { n.build(); n.onBeforeFullRender(); // Do pre-node stuff, boolean indena = o().isIndentEnabled(); // jal 20090903 Save indenting request.... n.visit(getTagRenderer()); // Ask base renderer to render tag if(n.getCreateJS() != null) m_createJS.append(n.getCreateJS()); n.renderJavascriptState(m_stateJS); // Append Javascript state to state buffer visitChildren(n); getTagRenderer().renderEndTag(n); o().setIndentEnabled(indena); // And restore indenting if tag handler caused it to be cleared. n.internalClearDelta(); checkForFocus(n); } @Override public void visitChildren(NodeContainer c) throws Exception { if(c instanceof IRenderNBSPIfEmpty) { if(c.getChildCount() == 0) { //-- jal 20091223 If the TD is fully-empty add a nbsp to prevent IE from misrendering the cell. //-- vmijic 20100528 In case of null DisplayValue value render &nbsp; so that height of display value can be correct. o().text("\u00a0"); // Render a nbsp. DO NOT USE THE ENTITY - IT DOES NOT EXIST IN XML. return; } } super.visitChildren(c); } /* * Handle default input focus: if no focus is set AND this is an input control -> set focus. */ private void checkForFocus(NodeBase n) { if(m_tagRenderer.getMode() != HtmlRenderMode.FULL) return; if(n.getPage().getFocusComponent() != null) return; if(n instanceof IHasChangeListener) { // FIXME Why this 'if'? if(n instanceof IControl< ? >) { IControl< ? > in = (IControl< ? >) n; if(!in.isDisabled() && !in.isReadOnly()) n.getPage().setFocusComponent(n); } else n.getPage().setFocusComponent(n); } } protected void renderPageHeader() throws Exception { if(isXml()) { o().writeRaw("<!DOCTYPE html PUBLIC \"- + "<html xmlns=\"http: + "<head>\n" + "<meta http-equiv=\"Content-Type\" content=\"application/xhtml+xml; charset=UTF-8\"/>\n" ); } else { o().writeRaw( "<!DOCTYPE html PUBLIC \"- + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"); } } public void renderThemeCSS() throws Exception { String sheet = m_ctx.getApplication().getTheme(null).getStylesheet(); //-- Render style fragments part. o().writeRaw("<link rel=\"stylesheet\" type=\"text/css\" href=\""); o().writeRaw(ctx().getRelativePath(sheet)); if(isXml()) o().writeRaw("\"/>"); else o().writeRaw("\"></link>\n"); } /** * Get all contributor sources and create an ordered list (ordered by the indicated 'order') to render. * @throws Exception */ public void renderHeadContributors() throws Exception { List<HeaderContributorEntry> full = new ArrayList<HeaderContributorEntry>(page().getApplication().getHeaderContributorList()); page().internalAddContributors(full); Collections.sort(full, HeaderContributor.C_ENTRY); for(HeaderContributorEntry hce : full) hce.getContributor().contribute(this); page().internalContributorsRendered(); // Mark as rendered. } public void renderLoadCSS(String path) throws Exception { //-- render an app-relative url o().tag("link"); o().attr("rel", "stylesheet"); o().attr("type", "text/css"); o().attr("href", ctx().getRelativePath(path)); o().endtag(); o().closetag("link"); } public void renderLoadJavascript(String path) throws Exception { //-- render an app-relative url o().tag("script"); o().attr("language", "javascript"); o().attr("src", ctx().getRelativePath(path)); o().endtag(); o().closetag("script"); } private void genVar(String name, String val) throws Exception { o().writeRaw("var " + name + "=" + val + ";\n"); } public void render(IRequestContext ctx, Page page) throws Exception { m_ctx = ctx; m_page = page; if(page.isRenderAsXHTML()) { setXml(true); } // page.build(); jal 20100618 moved to users of full renderer; building and rendering are now separate concerns renderPageHeader(); // o().writeRaw( // "<script language=\"javascript\"><!--\n" // + "var DomUIpageTag="+page.getPageTag()+";\n" // + "var DomUIThemeURL="+StringTool.strToJavascriptString(ctx.getRelativePath( ctx.getRelativeThemePath("") ), true)+";\n" // + "--></script>\n" o().writeRaw("<script language=\"javascript\">"); if(!isXml()) o().writeRaw("<! genVar("DomUIpageTag", Integer.toString(page.getPageTag())); String pb = DomApplication.get().getThemedResourceRURL("ICON/progressbar.gif"); if(null == pb) throw new IllegalStateException("Required resource missing"); genVar("DomUIProgressURL", StringTool.strToJavascriptString(ctx.getRelativePath(pb), true)); genVar("DomUICID", StringTool.strToJavascriptString(page.getConversation().getFullId(), true)); genVar("DomUIDevel", ctx.getApplication().inDevelopmentMode() ? "true" : "false"); genVar("DomUIappURL", StringTool.strToJavascriptString(ctx.getRelativePath(""), true)); if(!isXml()) o().writeRaw("\n o().writeRaw("\n</script>\n"); // EXPERIMENTAL SVG/VML support if(m_page.isAllowVectorGraphics()) { if(ctx.getBrowserVersion().isIE()) { o().writeRaw("<style>v\\: * { behavior:url(#default#VML); display:inline-block;} </style>\n"); // Puke.... o().writeRaw("<xml:namespace ns=\"urn:schemas-microsoft-com:vml\" prefix=\"v\">\n"); } } // END EXPERIMENTAL renderThemeCSS(); renderHeadContributors(); if(page.getBody().getTitle() != null) { o().tag("title"); o().endtag(); o().text(page.getBody().getTitle()); o().closetag("title"); } o().closetag("head"); // Render rest ;-) page.getBody().visit(this); /* * Render all attached Javascript in an onReady() function. This code will run * as soon as the body load has completed. */ StringBuilder sq = page.internalGetAppendedJS(); o().tag("script"); o().attr("language", "javascript"); o().endtag(); o().text("$(document).ready(function() {"); //-- If any component has a focus request issue that, NodeBase f = page.getFocusComponent(); if(f != null) { o().text("WebUI.focus('" + f.getActualID() + "');"); page.setFocusComponent(null); } if(getCreateJS().length() > 0) { o().writeRaw(getCreateJS().toString()); // o().text(m_createJS.toString()); } if(sq != null) { o().writeRaw(sq.toString()); // o().text(sq.toString()); } //-- If asynchronous actions are pending call WebUI.startPolling(); if(page.getConversation().hasDelayedActions()) o().writeRaw("WebUI.startPolling();"); int kit = ctx().getApplication().getKeepAliveInterval(); if(kit > 0) { o().writeRaw("WebUI.startPingServer(" + kit + ");"); } o().text("});"); o().closetag("script"); o().closetag("html"); } /** * Return all of the Javascript code to create/recreate this page. * @return */ public StringBuilder getCreateJS() { if(m_stateJS.length() > 0) { // Stuff present in state buffer too? m_createJS.append(';'); // Always add after all create stuff m_createJS.append(m_stateJS); m_stateJS.setLength(0); } return m_createJS; } }
package to.etc.domui.dom; import java.util.*; import to.etc.domui.component.misc.*; import to.etc.domui.dom.header.*; import to.etc.domui.dom.html.*; import to.etc.domui.server.*; import to.etc.util.*; public class HtmlFullRenderer extends NodeVisitorBase { // private BrowserVersion m_browserVersion; /** The thingy responsible for rendering the tags, */ private HtmlTagRenderer m_tagRenderer; private IBrowserOutput m_o; private IRequestContext m_ctx; private Page m_page; private boolean m_xml; private StringBuilder m_createJS = new StringBuilder(); private StringBuilder m_stateJS = new StringBuilder(); protected HtmlFullRenderer(HtmlTagRenderer tagRenderer, IBrowserOutput o) { // m_browserVersion = tagRenderer.getBrowser(); m_tagRenderer = tagRenderer; m_o = o; // 20090701 jal was ADDS which is WRONG - by definition a FULL render IS a full renderer... This caused SELECT tags to be rendered with domui_selected attributes instead of selected attributes. setRenderMode(HtmlRenderMode.FULL); } public HtmlTagRenderer getTagRenderer() { // 20090701 jal was ADDS which is WRONG - by definition a FULL render IS a full renderer... This caused SELECT tags to be rendered with domui_selected attributes instead of selected attributes. // 20091002 jal removed, make callers specify render mode... // m_tagRenderer.setRenderMode(HtmlRenderMode.FULL); // All nodes from the full renderer are NEW by definition. return m_tagRenderer; } public HtmlRenderMode getMode() { return m_tagRenderer.getMode(); } public void setRenderMode(HtmlRenderMode m) { m_tagRenderer.setRenderMode(m); } public boolean isXml() { return m_xml; } public void setXml(boolean xml) { m_xml = xml; } public IBrowserOutput o() { return m_o; } public IRequestContext ctx() { return m_ctx; } public Page page() { return m_page; } @Override public void visitNodeBase(NodeBase n) throws Exception { n.build(); n.onBeforeFullRender(); // Do pre-node stuff, n.visit(getTagRenderer()); if(n.getCreateJS() != null) m_createJS.append(n.getCreateJS()); n.renderJavascriptState(m_stateJS); // Append Javascript state to state buffer if(!(n instanceof TextNode)) { if(m_xml) getTagRenderer().renderEndTag(n); else m_o.dec(); // 20080626 img et al does not dec()... } n.internalClearDelta(); checkForFocus(n); } /** * Overridden because this is a NodeBase node which MUST be terminated with a /div, always. * @see to.etc.domui.dom.html.NodeVisitorBase#visitLiteralXhtml(to.etc.domui.component.misc.LiteralXhtml) */ @Override @Deprecated public void visitLiteralXhtml(LiteralXhtml n) throws Exception { visitNodeBase(n); // Handle most thingies we need to do, if(!m_xml) { //-- In HTML mode we MUST end this tag, and we need to inc() because the visitNodeBase() has decremented.. m_o.inc(); getTagRenderer().renderEndTag(n); // Force close the tag in HTML mode. } } /** * Overridden to fix bug 627; this prevents embedding content in textarea and renders the value as * an attribute. * * @see to.etc.domui.dom.html.NodeVisitorBase#visitTextArea(to.etc.domui.dom.html.TextArea) */ @Override public void visitTextArea(TextArea n) throws Exception { if(getMode() == HtmlRenderMode.FULL) { // In FULL mode render content inside textarea goddamnit visitNodeContainer(n); return; } visitNodeBase(n); o().setIndentEnabled(true); // jal 20091002 indent when rendering js attribute // getTagRenderer().renderEndTag(n); } @Override public void visitNodeContainer(NodeContainer n) throws Exception { n.build(); n.onBeforeFullRender(); // Do pre-node stuff, boolean indena = o().isIndentEnabled(); // jal 20090903 Save indenting request.... n.visit(getTagRenderer()); // Ask base renderer to render tag if(n.getCreateJS() != null) m_createJS.append(n.getCreateJS()); n.renderJavascriptState(m_stateJS); // Append Javascript state to state buffer visitChildren(n); getTagRenderer().renderEndTag(n); o().setIndentEnabled(indena); // And restore indenting if tag handler caused it to be cleared. n.internalClearDelta(); checkForFocus(n); } @Override public void visitChildren(NodeContainer c) throws Exception { if(c instanceof IRenderNBSPIfEmpty) { if(c.getChildCount() == 0) { //-- jal 20091223 If the TD is fully-empty add a nbsp to prevent IE from misrendering the cell. //-- vmijic 20100528 In case of null DisplayValue value render &nbsp; so that height of display value can be correct. o().text("\u00a0"); // Render a nbsp. DO NOT USE THE ENTITY - IT DOES NOT EXIST IN XML. return; } } super.visitChildren(c); } /* * Handle default input focus: if no focus is set AND this is an input control -> set focus. */ private void checkForFocus(NodeBase n) { if(n.getPage().getFocusComponent() != null) return; if(n instanceof IHasChangeListener) { // FIXME Why this 'if'? if(n instanceof IInputNode< ? >) { IInputNode< ? > in = (IInputNode< ? >) n; if(!in.isDisabled() && !in.isReadOnly()) n.getPage().setFocusComponent(n); } else n.getPage().setFocusComponent(n); } } protected void renderPageHeader() throws Exception { if(isXml()) { o().writeRaw("<!DOCTYPE html PUBLIC \"- + "<html xmlns=\"http: + "<head>\n" + "<meta http-equiv=\"Content-Type\" content=\"application/xhtml+xml; charset=UTF-8\"/>\n" ); } else { o().writeRaw( "<!DOCTYPE html PUBLIC \"- + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"); } } /** * Render the proper themed stylesheet. This will be "style.theme.css" within the current * "theme directory", which is defined by the "currentTheme" in DomApplication. * @throws Exception */ protected void renderThemeCSS() throws Exception { String sheet = m_ctx.getApplication().getThemedResourceRURL("THEME/style.theme.css"); if(null == sheet) throw new IllegalStateException("Unexpected null??"); //-- Render style fragments part. o().writeRaw("<link rel=\"stylesheet\" type=\"text/css\" href=\""); o().writeRaw(ctx().getRelativePath(sheet)); if(isXml()) o().writeRaw("\"/>"); else o().writeRaw("\"></link>\n"); } /** * Get all contributor sources and create an ordered list (ordered by the indicated 'order') to render. * @throws Exception */ public void renderHeadContributors() throws Exception { List<HeaderContributorEntry> full = new ArrayList<HeaderContributorEntry>(page().getApplication().getHeaderContributorList()); page().internalAddContributors(full); Collections.sort(full, HeaderContributor.C_ENTRY); for(HeaderContributorEntry hce : full) hce.getContributor().contribute(this); page().internalContributorsRendered(); // Mark as rendered. } public void renderLoadCSS(String path) throws Exception { //-- render an app-relative url o().tag("link"); o().attr("rel", "stylesheet"); o().attr("type", "text/css"); o().attr("href", ctx().getThemedPath(path)); o().endtag(); o().closetag("link"); } public void renderLoadJavascript(String path) throws Exception { //-- render an app-relative url o().tag("script"); o().attr("language", "javascript"); o().attr("src", ctx().getThemedPath(path)); o().endtag(); o().closetag("script"); } private void genVar(String name, String val) throws Exception { o().writeRaw("var " + name + "=" + val + ";\n"); } public void render(IRequestContext ctx, Page page) throws Exception { m_ctx = ctx; m_page = page; if(page.isRenderAsXHTML()) { setXml(true); } // page.build(); jal 20100618 moved to users of full renderer; building and rendering are now separate concerns renderPageHeader(); // o().writeRaw( // "<script language=\"javascript\"><!--\n" // + "var DomUIpageTag="+page.getPageTag()+";\n" // + "var DomUIThemeURL="+StringTool.strToJavascriptString(ctx.getRelativePath( ctx.getRelativeThemePath("") ), true)+";\n" // + "--></script>\n" o().writeRaw("<script language=\"javascript\">"); if(!isXml()) o().writeRaw("<! genVar("DomUIpageTag", Integer.toString(page.getPageTag())); String pb = DomApplication.get().getThemedResourceRURL("THEME/progressbar.gif"); if(null == pb) throw new IllegalStateException("Required resource missing"); genVar("DomUIProgressURL", StringTool.strToJavascriptString(ctx.getRelativePath(pb), true)); genVar("DomUICID", StringTool.strToJavascriptString(page.getConversation().getFullId(), true)); genVar("DomUIDevel", ctx.getApplication().inDevelopmentMode() ? "true" : "false"); genVar("DomUIappURL", StringTool.strToJavascriptString(ctx.getRelativePath(""), true)); if(!isXml()) o().writeRaw("\n o().writeRaw("\n</script>\n"); // EXPERIMENTAL SVG/VML support if(m_page.isAllowVectorGraphics()) { if(ctx.getBrowserVersion().isIE()) { o().writeRaw("<style>v\\: * { behavior:url(#default#VML); display:inline-block;} </style>\n"); // Puke.... o().writeRaw("<xml:namespace ns=\"urn:schemas-microsoft-com:vml\" prefix=\"v\">\n"); } } // END EXPERIMENTAL renderThemeCSS(); renderHeadContributors(); if(page.getBody().getPageTitle() != null) { o().tag("title"); o().endtag(); o().text(page.getBody().getPageTitle()); o().closetag("title"); } o().closetag("head"); // Render rest ;-) page.getBody().visit(this); /* * Render all attached Javascript in an onReady() function. This code will run * as soon as the body load has completed. */ StringBuilder sq = page.internalGetAppendedJS(); o().tag("script"); o().attr("language", "javascript"); o().endtag(); o().text("$(document).ready(function() {"); //-- If any component has a focus request issue that, NodeBase f = page.getFocusComponent(); if(f != null) { o().text("WebUI.focus('" + f.getActualID() + "');"); page.setFocusComponent(null); } if(getCreateJS().length() > 0) { o().writeRaw(getCreateJS().toString()); // o().text(m_createJS.toString()); } if(sq != null) { o().writeRaw(sq.toString()); // o().text(sq.toString()); } //-- If asynchronous actions are pending call WebUI.startPolling(); if(page.getConversation().hasDelayedActions()) o().writeRaw("WebUI.startPolling();"); int kit = ctx().getApplication().getKeepAliveInterval(); if(kit > 0) { o().writeRaw("WebUI.startPingServer(" + kit + ");"); } o().text("});"); o().closetag("script"); o().closetag("html"); } /** * Return all of the Javascript code to create/recreate this page. * @return */ public StringBuilder getCreateJS() { if(m_stateJS.length() > 0) { // Stuff present in state buffer too? m_createJS.append(';'); // Always add after all create stuff m_createJS.append(m_stateJS); m_stateJS.setLength(0); } return m_createJS; } }
package com.camnter.utils.apk; import android.annotation.SuppressLint; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.ServiceInfo; import android.os.Build; import android.support.annotation.NonNull; import android.util.DisplayMetrics; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author CaMnter */ @SuppressWarnings("DanglingJavadoc") public final class ApkUtils { private static final String TAG = ApkUtils.class.getSimpleName(); /** * ActivityInfo * * @param pluginIntent Intent * @return intent ActivityInfo */ public static ActivityInfo selectPluginActivity(final Map<ComponentName, ActivityInfo> activityInfoMap, Intent pluginIntent) { for (ComponentName componentName : activityInfoMap.keySet()) { if (componentName.equals(pluginIntent.getComponent())) { return activityInfoMap.get(componentName); } } return null; } /** * ServiceInfo * * @param pluginIntent Intent * @return intent ServiceInfo */ private ServiceInfo selectPluginService(final Map<ComponentName, ServiceInfo> serviceInfoMap, Intent pluginIntent) { for (ComponentName componentName : serviceInfoMap.keySet()) { if (componentName.equals(pluginIntent.getComponent())) { return serviceInfoMap.get(componentName); } } return null; } /** * Apk <activity> * * * PackageParser generateActivityInfo * * @param apkFile apkFile * @throws Exception exception */ @SuppressLint("PrivateApi") public static Map<ComponentName, ActivityInfo> getActivityInfos(@NonNull final File apkFile, @NonNull final Context context) throws Exception { final Map<ComponentName, ActivityInfo> activityInfoMap = new HashMap<>(); /** * PackageParser # parsePackage(File packageFile, int flags) */ final Class<?> packageParserClass = Class.forName("android.content.pm.PackageParser"); final int sdkVersion = Build.VERSION.SDK_INT; if (sdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { throw new RuntimeException( "[" + TAG + "] the sdk version must >= 14 (4.0.0)"); } final Object packageParser; final Object packageObject; final Method parsePackageMethod; if (sdkVersion >= Build.VERSION_CODES.LOLLIPOP) { // >= 5.0.0 // parsePackage(File packageFile, int flags) /** * PackageParser * * PackageParser # parsePackage(File packageFile, int flags) * apk Package */ packageParser = packageParserClass.newInstance(); parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class, int.class); packageObject = parsePackageMethod.invoke( packageParser, apkFile, PackageManager.GET_ACTIVITIES ); } else { // >= 4.0.0 // parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags) /** * PackageParser PackageParser(String archiveSourcePath) * * PackageParser # parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags) * apk Package */ final String apkFileAbsolutePath = apkFile.getAbsolutePath(); packageParser = packageParserClass.getConstructor(String.class) .newInstance(apkFileAbsolutePath); parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class, String.class, DisplayMetrics.class, int.class); packageObject = parsePackageMethod.invoke( packageParser, apkFile, apkFile.getAbsolutePath(), context.getResources().getDisplayMetrics(), PackageManager.GET_ACTIVITIES ); } if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // >= 4.2.0 // generateActivityInfo(Activity a, int flags, PackageUserState state, int userId) /** * Package # ArrayList<Activity> activities * ArrayList<Activity> activities Activity ActivityInfo */ final Field activitiesField = packageObject.getClass().getDeclaredField("activities"); final List activities = (List) activitiesField.get(packageObject); /** * UserHandle # static @UserIdInt int getCallingUserId() * userId * * PackageUserState */ final Class<?> packageParser$ActivityClass = Class.forName( "android.content.pm.PackageParser$Activity"); final Class<?> packageUserStateClass = Class.forName( "android.content.pm.PackageUserState"); final Class<?> userHandler = Class.forName("android.os.UserHandle"); final Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId"); final int userId = (Integer) getCallingUserIdMethod.invoke(null); final Object defaultUserState = packageUserStateClass.newInstance(); // android.content.pm.PackageParser#generateActivityInfo(Activity a, int flags, PackageUserState state, int userId) final Method generateActivityInfo = packageParserClass.getDeclaredMethod( "generateActivityInfo", packageParser$ActivityClass, int.class, packageUserStateClass, int.class); /** * PackageParser # generateActivityInfo(Activity a, int flags, PackageUserState state, int userId) * Activity ActivityInfo * * */ for (Object activity : activities) { final ActivityInfo info = (ActivityInfo) generateActivityInfo.invoke( packageParser, activity, 0, defaultUserState, userId ); activityInfoMap.put(new ComponentName(info.packageName, info.name), info); } } else if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { // >= 4.1.0 // generateActivityInfo(Activity a, int flags, boolean stopped, int enabledState, int userId) /** * Package # ArrayList<Activity> activities * ArrayList<Activity> activities Activity ActivityInfo */ final Field activitiesField = packageObject.getClass().getDeclaredField("activities"); final List activities = (List) activitiesField.get(packageObject); // android.content.pm.PackageParser#generateActivityInfo(Activity a, int flags, boolean stopped, int enabledState, int userId) final Class<?> packageParser$ActivityClass = Class.forName( "android.content.pm.PackageParser$Activity"); final Class<?> userHandler = Class.forName("android.os.UserId"); final Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId"); final int userId = (Integer) getCallingUserIdMethod.invoke(null); final Method generateActivityInfo = packageParserClass.getDeclaredMethod( "generateActivityInfo", packageParser$ActivityClass, int.class, boolean.class, int.class, int.class); /** * PackageParser # generateActivityInfo(Activity a, int flags, boolean stopped, int enabledState, int userId) * Activity ActivityInfo * * 4.0.0 * public class PackageParser { * public final static class Package { * // User set enabled state. * public int mSetEnabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; * * // Whether the package has been stopped. * public boolean mSetStopped = false; * } * } * * */ for (Object activity : activities) { final ActivityInfo info = (ActivityInfo) generateActivityInfo.invoke( packageParser, activity, 0, false, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, userId ); activityInfoMap.put(new ComponentName(info.packageName, info.name), info); } } else if (sdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // >= 4.0.0 // generateActivityInfo(Activity a, int flags) /** * Package # ArrayList<Activity> activities * ArrayList<Activity> activities Activity ActivityInfo */ final Field activitiesField = packageObject.getClass().getDeclaredField("activities"); final List activities = (List) activitiesField.get(packageObject); // android.content.pm.PackageParser#generateActivityInfo(Activity a, int flags) final Class<?> packageParser$ActivityClass = Class.forName( "android.content.pm.PackageParser$Activity"); final Method generateActivityInfo = packageParserClass.getDeclaredMethod( "generateActivityInfo", packageParser$ActivityClass, int.class); /** * PackageParser # generateActivityInfo(Activity a, int flags) * Activity ActivityInfo * * */ for (Object activity : activities) { final ActivityInfo info = (ActivityInfo) generateActivityInfo.invoke( packageParser, activity, 0 ); activityInfoMap.put(new ComponentName(info.packageName, info.name), info); } } return activityInfoMap; } /** * Apk <service> * * * PackageParser generateServiceInfo * * @param apkFile apkFile * @throws Exception exception */ @SuppressLint("PrivateApi") public Map<ComponentName, ServiceInfo> getServiceInfos(@NonNull final File apkFile, @NonNull final Context context) throws Exception { final Map<ComponentName, ServiceInfo> serviceInfoMap = new HashMap<>(); /** * PackageParser # parsePackage(File packageFile, int flags) */ final Class<?> packageParserClass = Class.forName("android.content.pm.PackageParser"); final int sdkVersion = Build.VERSION.SDK_INT; if (sdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { throw new RuntimeException( "[" + TAG + "] the sdk version must >= 14 (4.0.0)"); } final Object packageParser; final Object packageObject; final Method parsePackageMethod; if (sdkVersion >= Build.VERSION_CODES.LOLLIPOP) { // >= 5.0.0 // parsePackage(File packageFile, int flags) /** * PackageParser * * PackageParser # parsePackage(File packageFile, int flags) * apk Package */ packageParser = packageParserClass.newInstance(); parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class, int.class); packageObject = parsePackageMethod.invoke( packageParser, apkFile, PackageManager.GET_SERVICES ); } else { // >= 4.0.0 // parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags) /** * PackageParser PackageParser(String archiveSourcePath) * * PackageParser # parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags) * apk Package */ final String apkFileAbsolutePath = apkFile.getAbsolutePath(); packageParser = packageParserClass.getConstructor(String.class) .newInstance(apkFileAbsolutePath); parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class, String.class, DisplayMetrics.class, int.class); packageObject = parsePackageMethod.invoke( packageParser, apkFile, apkFile.getAbsolutePath(), context.getResources().getDisplayMetrics(), PackageManager.GET_SERVICES ); } if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // >= 4.2.0 // generateServiceInfo(Service s, int flags, PackageUserState state, int userId) /** * Package # ArrayList<Service> services * ArrayList<Service> services Service ServiceInfo */ final Field servicesField = packageObject.getClass().getDeclaredField("services"); final List services = (List) servicesField.get(packageObject); /** * UserHandle # static @UserIdInt int getCallingUserId() * userId * * PackageUserState */ final Class<?> packageParser$ServiceClass = Class.forName( "android.content.pm.PackageParser$Service"); final Class<?> packageUserStateClass = Class.forName( "android.content.pm.PackageUserState"); final Class<?> userHandler = Class.forName("android.os.UserHandle"); final Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId"); final int userId = (Integer) getCallingUserIdMethod.invoke(null); final Object defaultUserState = packageUserStateClass.newInstance(); // android.content.pm.PackageParser#generateServiceInfo(Service s, int flags, PackageUserState state, int userId) Method generateServiceInfo = packageParserClass.getDeclaredMethod( "generateServiceInfo", packageParser$ServiceClass, int.class, packageUserStateClass, int.class); /** * PackageParser # generateServiceInfo(Service s, int flags, PackageUserState state, int userId) * Service ServiceInfo * * */ for (Object service : services) { final ServiceInfo info = (ServiceInfo) generateServiceInfo.invoke(packageParser, service, 0, defaultUserState, userId); serviceInfoMap.put(new ComponentName(info.packageName, info.name), info); } } else if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { // >= 4.1.0 // generateServiceInfo(Service s, int flags, boolean stopped, int enabledState, int userId) /** * Package # ArrayList<Service> services * ArrayList<Service> services Service ServiceInfo */ final Field servicesField = packageObject.getClass().getDeclaredField("services"); final List services = (List) servicesField.get(packageObject); // android.content.pm.PackageParser#generateServiceInfo(Service s, int flags, boolean stopped, int enabledState, int userId) final Class<?> packageParser$ServiceClass = Class.forName( "android.content.pm.PackageParser$Service"); final Class<?> userHandler = Class.forName("android.os.UserId"); final Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId"); final int userId = (Integer) getCallingUserIdMethod.invoke(null); Method generateServiceInfo = packageParserClass.getDeclaredMethod( "generateServiceInfo", packageParser$ServiceClass, int.class, boolean.class, int.class, int.class); /** * PackageParser # generateServiceInfo(Service s, int flags, boolean stopped, int enabledState, int userId) * Service ServiceInfo * * 4.0.0 * public class PackageParser { * public final static class Package { * // User set enabled state. * public int mSetEnabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; * * // Whether the package has been stopped. * public boolean mSetStopped = false; * } * } * * */ for (Object service : services) { final ServiceInfo info = (ServiceInfo) generateServiceInfo.invoke(packageParser, service, 0, false, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, userId); serviceInfoMap.put(new ComponentName(info.packageName, info.name), info); } } else if (sdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // >= 4.0.0 // generateServiceInfo(Service s, int flags) /** * Package # ArrayList<Service> services * ArrayList<Service> services Service ServiceInfo */ final Field servicesField = packageObject.getClass().getDeclaredField("services"); final List services = (List) servicesField.get(packageObject); // android.content.pm.PackageParser#generateServiceInfo(Service s, int flags) final Class<?> packageParser$ServiceClass = Class.forName( "android.content.pm.PackageParser$Service"); Method generateServiceInfo = packageParserClass.getDeclaredMethod( "generateServiceInfo", packageParser$ServiceClass, int.class); /** * PackageParser # generateServiceInfo(Activity a, int flags) * Service ServiceInfo * * */ for (Object service : services) { final ServiceInfo info = (ServiceInfo) generateServiceInfo.invoke(packageParser, service, 0); serviceInfoMap.put(new ComponentName(info.packageName, info.name), info); } } return serviceInfoMap; } /** * Apk application * * * PackageParser generateApplicationInfo * * @param apkFile apkFile * @throws Exception exception */ @SuppressLint("PrivateApi") public static ApplicationInfo getApplicationInfo(@NonNull final File apkFile, @NonNull final Context context) throws Exception { final ApplicationInfo applicationInfo; /** * PackageParser # parsePackage(File packageFile, int flags) */ final Class<?> packageParserClass = Class.forName("android.content.pm.PackageParser"); final int sdkVersion = Build.VERSION.SDK_INT; if (sdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { throw new RuntimeException( "[" + TAG + "] the sdk version must >= 14 (4.0.0)"); } final Object packageParser; final Object packageObject; final Method parsePackageMethod; if (sdkVersion >= Build.VERSION_CODES.LOLLIPOP) { // >= 5.0.0 // parsePackage(File packageFile, int flags) /** * PackageParser * * PackageParser # parsePackage(File packageFile, int flags) * apk Package */ packageParser = packageParserClass.newInstance(); parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class, int.class); packageObject = parsePackageMethod.invoke( packageParser, apkFile, PackageManager.GET_SERVICES ); } else { // >= 4.0.0 // parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags) /** * PackageParser PackageParser(String archiveSourcePath) * * PackageParser # parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags) * apk Package */ final String apkFileAbsolutePath = apkFile.getAbsolutePath(); packageParser = packageParserClass.getConstructor(String.class) .newInstance(apkFileAbsolutePath); parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class, String.class, DisplayMetrics.class, int.class); packageObject = parsePackageMethod.invoke( packageParser, apkFile, apkFile.getAbsolutePath(), context.getResources().getDisplayMetrics(), PackageManager.GET_SERVICES ); } final Class<?> packageParser$Package = Class.forName( "android.content.pm.PackageParser$Package"); if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // >= 4.2.0 // generateApplicationInfo(Package p, int flags, PackageUserState state) /** * PackageUserState */ final Class<?> packageUserStateClass = Class.forName( "android.content.pm.PackageUserState"); final Object defaultUserState = packageUserStateClass.newInstance(); // android.content.pm.PackageParser#generateApplicationInfo(Package p, int flags, PackageUserState state) final Method generateApplicationInfo = packageParserClass.getDeclaredMethod( "generateApplicationInfo", packageParser$Package, int.class, packageUserStateClass); applicationInfo = (ApplicationInfo) generateApplicationInfo.invoke( packageParser, packageObject, 0 , defaultUserState ); } else if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { // >= 4.1.0 // generateApplicationInfo(Package p, int flags, boolean stopped, int enabledState, int userId) // android.content.pm.PackageParser#generateApplicationInfo(Package p, int flags, boolean stopped, int enabledState, int userId) final Class<?> userHandler = Class.forName("android.os.UserId"); final Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId"); final int userId = (Integer) getCallingUserIdMethod.invoke(null); Method generateApplicationInfo = packageParserClass.getDeclaredMethod( "generateApplicationInfo", packageParser$Package, int.class, boolean.class, int.class); /** * PackageParser # generateApplicationInfo(Package p, int flags, boolean stopped, int enabledState, int userId) * * 4.0.0 * public class PackageParser { * public final static class Package { * // User set enabled state. * public int mSetEnabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; * * // Whether the package has been stopped. * public boolean mSetStopped = false; * } * } * * */ applicationInfo = (ApplicationInfo) generateApplicationInfo.invoke( packageParser, packageObject, 0 , false, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, userId ); } else if (sdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // >= 4.0.0 // generateApplicationInfo(Package p, int flags) // android.content.pm.PackageParser#generateApplicationInfo(Package p, int flags) Method generateApplicationInfo = packageParserClass.getDeclaredMethod( "generateApplicationInfo", packageParser$Package, int.class); /** * PackageParser # generateApplicationInfo(Package p, int flags) * * */ applicationInfo = (ApplicationInfo) generateApplicationInfo.invoke( packageParser, packageObject, 0 ); } else { applicationInfo = null; } return applicationInfo; } /** * Apk <receiver> * * * PackageParser generateActivityInfo * * @param apkFile apkFile * @throws Exception exception */ @SuppressWarnings("unchecked") @SuppressLint("PrivateApi") public static Map<ActivityInfo, List<? extends IntentFilter>> getReceiverInfos(@NonNull final File apkFile, @NonNull final Context context) throws Exception { final Map<ActivityInfo, List<? extends IntentFilter>> receiverInfoMap = new HashMap<>(); /** * PackageParser # parsePackage(File packageFile, int flags) */ final Class<?> packageParserClass = Class.forName("android.content.pm.PackageParser"); final int sdkVersion = Build.VERSION.SDK_INT; if (sdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { throw new RuntimeException( "[" + TAG + "] the sdk version must >= 14 (4.0.0)"); } final Object packageParser; final Object packageObject; final Method parsePackageMethod; if (sdkVersion >= Build.VERSION_CODES.LOLLIPOP) { // >= 5.0.0 // parsePackage(File packageFile, int flags) /** * PackageParser * * PackageParser # parsePackage(File packageFile, int flags) * apk Package */ packageParser = packageParserClass.newInstance(); parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class, int.class); packageObject = parsePackageMethod.invoke( packageParser, apkFile, PackageManager.GET_RECEIVERS ); } else { // >= 4.0.0 // parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags) /** * PackageParser PackageParser(String archiveSourcePath) * * PackageParser # parsePackage(File sourceFile, String destCodePath, DisplayMetrics metrics, int flags) * apk Package */ final String apkFileAbsolutePath = apkFile.getAbsolutePath(); packageParser = packageParserClass.getConstructor(String.class) .newInstance(apkFileAbsolutePath); parsePackageMethod = packageParserClass.getDeclaredMethod("parsePackage", File.class, String.class, DisplayMetrics.class, int.class); packageObject = parsePackageMethod.invoke( packageParser, apkFile, apkFile.getAbsolutePath(), context.getResources().getDisplayMetrics(), PackageManager.GET_RECEIVERS ); } if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // >= 4.2.0 // generateActivityInfo(Activity a, int flags, PackageUserState state, int userId) /** * Package # ArrayList<Activity> receivers * ArrayList<Activity> receivers Receiver ActivityInfo */ final Field activitiesField = packageObject.getClass().getDeclaredField("receivers"); final List receivers = (List) activitiesField.get(packageObject); /** * UserHandle # static @UserIdInt int getCallingUserId() * userId * * PackageUserState */ final Class<?> packageParser$ActivityClass = Class.forName( "android.content.pm.PackageParser$Activity"); final Class<?> packageUserStateClass = Class.forName( "android.content.pm.PackageUserState"); final Class<?> userHandler = Class.forName("android.os.UserHandle"); final Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId"); final int userId = (Integer) getCallingUserIdMethod.invoke(null); final Object defaultUserState = packageUserStateClass.newInstance(); final Class<?> componentClass = Class.forName( "android.content.pm.PackageParser$Component"); final Field intentsField = componentClass.getDeclaredField("intents"); // android.content.pm.PackageParser#generateActivityInfo(Activity a, int flags, PackageUserState state, int userId) final Method generateActivityInfo = packageParserClass.getDeclaredMethod( "generateActivityInfo", packageParser$ActivityClass, int.class, packageUserStateClass, int.class); /** * PackageParser # generateActivityInfo(Activity a, int flags, PackageUserState state, int userId) * Receiver ActivityInfo * * */ for (Object receiver : receivers) { final ActivityInfo info = (ActivityInfo) generateActivityInfo.invoke( packageParser, receiver, 0, defaultUserState, userId ); final List<? extends IntentFilter> filters = (List<? extends IntentFilter>) intentsField.get(receiver); receiverInfoMap.put(info, filters); } } else if (sdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { // >= 4.1.0 // generateActivityInfo(Activity a, int flags, boolean stopped, int enabledState, int userId) /** * Package # ArrayList<Activity> receivers * ArrayList<Activity> receivers Receiver ActivityInfo */ final Field activitiesField = packageObject.getClass().getDeclaredField("receivers"); final List receivers = (List) activitiesField.get(packageObject); // android.content.pm.PackageParser#generateActivityInfo(Activity a, int flags, boolean stopped, int enabledState, int userId) final Class<?> packageParser$ActivityClass = Class.forName( "android.content.pm.PackageParser$Activity"); final Class<?> userHandler = Class.forName("android.os.UserId"); final Method getCallingUserIdMethod = userHandler.getDeclaredMethod("getCallingUserId"); final int userId = (Integer) getCallingUserIdMethod.invoke(null); final Method generateActivityInfo = packageParserClass.getDeclaredMethod( "generateActivityInfo", packageParser$ActivityClass, int.class, boolean.class, int.class, int.class); final Class<?> componentClass = Class.forName( "android.content.pm.PackageParser$Component"); final Field intentsField = componentClass.getDeclaredField("intents"); /** * PackageParser # generateActivityInfo(Activity a, int flags, boolean stopped, int enabledState, int userId) * Receiver ActivityInfo * * 4.0.0 * public class PackageParser { * public final static class Package { * // User set enabled state. * public int mSetEnabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; * * // Whether the package has been stopped. * public boolean mSetStopped = false; * } * } * * */ for (Object receiver : receivers) { final ActivityInfo info = (ActivityInfo) generateActivityInfo.invoke( packageParser, receiver, 0, false, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, userId ); final List<? extends IntentFilter> filters = (List<? extends IntentFilter>) intentsField.get(receiver); receiverInfoMap.put(info, filters); } } else if (sdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // >= 4.0.0 // generateActivityInfo(Activity a, int flags) /** * Package # ArrayList<Activity> receivers * ArrayList<Activity> receivers Receiver ActivityInfo */ final Field activitiesField = packageObject.getClass().getDeclaredField("receivers"); final List receivers = (List) activitiesField.get(packageObject); // android.content.pm.PackageParser#generateActivityInfo(Activity a, int flags) final Class<?> packageParser$ActivityClass = Class.forName( "android.content.pm.PackageParser$Activity"); final Method generateActivityInfo = packageParserClass.getDeclaredMethod( "generateActivityInfo", packageParser$ActivityClass, int.class); final Class<?> componentClass = Class.forName( "android.content.pm.PackageParser$Component"); final Field intentsField = componentClass.getDeclaredField("intents"); /** * PackageParser # generateActivityInfo(Activity a, int flags) * Receiver ActivityInfo * * */ for (Object receiver : receivers) { final ActivityInfo info = (ActivityInfo) generateActivityInfo.invoke( packageParser, receiver, 0 ); final List<? extends IntentFilter> filters = (List<? extends IntentFilter>) intentsField.get(receiver); receiverInfoMap.put(info, filters); } } return receiverInfoMap; } }
package org.languagetool.dev; import org.apache.commons.lang.StringUtils; import org.languagetool.JLanguageTool; import org.languagetool.Language; import org.languagetool.language.Contributor; import org.languagetool.tools.StringTools; import org.languagetool.tools.Tools; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.*; /** * Command line tool to list supported languages and their number of rules. * * @author Daniel Naber */ @SuppressWarnings("StringConcatenationInsideStringBufferAppend") public final class RuleOverview { private static final List<String> LANGUAGES_WITH_NEW_MAINTAINER_NEED = Arrays.asList("en", "ja", "is", "sv", "lt", "ro", "ml"); private static final List<String> LANGUAGES_WITH_CO_MAINTAINER_NEED = Arrays.asList("da", "be", "zh", "gl"); public static void main(final String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: " + RuleOverview.class.getName() + " <webRoot>"); System.exit(1); } final RuleOverview prg = new RuleOverview(); prg.run(new File(args[0])); } private RuleOverview() { // no public constructor } private void run(File webRoot) throws IOException { System.out.println("<b>Rules in LanguageTool " + JLanguageTool.VERSION + "</b><br />"); System.out.println("Date: " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "<br /><br />\n"); System.out.println("<table class=\"tablesorter sortable\" style=\"width: auto\">"); System.out.println("<thead>"); System.out.println("<tr>"); System.out.println(" <th valign='bottom' width=\"200\">Language</th>"); System.out.println(" <th valign='bottom' align=\"left\" width=\"60\">XML<br/>rules</th>"); System.out.println(" <th></th>"); System.out.println(" <th align=\"left\" width=\"60\">Java<br/>rules</th>"); System.out.println(" <th align=\"left\" width=\"60\">False<br/>friends</th>"); //System.out.println(" <th valign='bottom' width=\"65\">Auto-<br/>detected</th>"); System.out.println(" <th valign='bottom' align=\"left\">Rule Maintainers</th>"); System.out.println("</tr>"); System.out.println("</thead>"); System.out.println("<tbody>"); final List<Language> sortedLanguages = getSortedLanguages(); //setup false friends counting final String falseFriendFile = JLanguageTool.getDataBroker().getRulesDir() + File.separator + "false-friends.xml"; final String falseFriendRules = StringTools.readStream(Tools.getStream(falseFriendFile), "utf-8") .replaceAll("(?s)", "") .replaceAll("(?s)<rules.*?>", ""); int overallJavaCount = 0; int langSpecificWebsiteCount = 0; for (final Language lang : sortedLanguages) { if (lang.isVariant()) { continue; } System.out.print("<tr>"); final String langCode = lang.getShortName(); final File langSpecificWebsite = new File(webRoot, langCode); final List<String> variants = getVariants(sortedLanguages, lang); String variantsText = ""; if (variants.size() > 0) { variantsText = "<br/><span class='langVariants'>Variants for: " + StringUtils.join(variants, ", ") + "</span>"; } if (langSpecificWebsite.isDirectory()) { System.out.print("<td valign=\"top\"><a href=\"../" + langCode + "/\">" + lang.getName() + "</a>" + variantsText + "</td>"); langSpecificWebsiteCount++; } else { System.out.print("<td valign=\"top\">" + lang.getName() + " " + variantsText + "</td>"); } int allRules = countRulesForLanguage(lang); if (allRules == 0) { System.out.println("<td valign=\"top\" align=\"right\">0</td>"); } else { final String ruleBase = "https://github.com/languagetool-org/languagetool/blob/master/languagetool-language-modules/" + langCode + "/src/main/resources/org/languagetool/rules/"; System.out.print("<td valign=\"top\" align=\"right\">" + allRules + "</td>"); System.out.print("<td valign=\"top\" align=\"right\">" + //"<a href=\"" + ruleBase + langCode + "/grammar.xml" + "\">Show</a> / " + "<a href=\"http://community.languagetool.org/rule/list?lang=" + langCode + "\">Browse</a>,&nbsp;" + "<a href=\"" + ruleBase + langCode + "/grammar.xml\">XML</a>" + "</td>"); } // count Java rules: final File dir = new File("../languagetool-language-modules/" + langCode + "/src/main/java" + JLanguageTool.getDataBroker().getRulesDir() + "/" + langCode); if (!dir.exists()) { System.out.print("<td valign=\"top\" align=\"right\">0</td>"); } else { final File[] javaRules = dir.listFiles(new JavaFilter(lang.getName())); final int javaCount = javaRules.length; if (javaCount > 0) { final String sourceCodeLink = "https://github.com/languagetool-org/languagetool/blob/master/languagetool-language-modules/" + langCode + "/src/main/java/org/languagetool/rules/" + langCode + "/"; System.out.print("<td valign=\"top\" align=\"right\"><a href=\"" + sourceCodeLink + "\">" + javaCount + "</a></td>"); } else { System.out.print("<td valign=\"top\" align=\"right\">" + javaCount + "</td>"); } overallJavaCount++; } // false friends: final int count = countFalseFriendRules(falseFriendRules, lang); System.out.print("<td valign=\"top\" align=\"right\">" + count + "</td>"); //System.out.print("<td valign=\"top\">" + (isAutoDetected(lang.getShortName()) ? "yes" : "-") + "</td>"); // maintainer information: final StringBuilder maintainerInfo = getMaintainerInfo(lang); final String maintainerText; if (langCode.equals("pt")) { maintainerText = " - <span class='maintainerNeeded'><a href='http://wiki.languagetool.org/tasks-for-language-maintainers'>Looking for a maintainer for Brazilian Portuguese</a></span>"; } else if (LANGUAGES_WITH_NEW_MAINTAINER_NEED.contains(langCode)) { maintainerText = " - <span class='maintainerNeeded'><a href='http://wiki.languagetool.org/tasks-for-language-maintainers'>Looking for new maintainer</a></span>"; } else if (LANGUAGES_WITH_CO_MAINTAINER_NEED.contains(langCode)) { maintainerText = " - <span class='maintainerNeeded'><a href='http://wiki.languagetool.org/tasks-for-language-maintainers'>Looking for co-maintainer</a></span>"; } else { maintainerText = ""; } System.out.print("<td valign=\"top\" align=\"left\">" + maintainerInfo.toString() + maintainerText + "</td>"); System.out.println("</tr>"); } if (overallJavaCount == 0) { throw new RuntimeException("No Java rules found - start this script from the languagetool-standalone directory"); } if (langSpecificWebsiteCount == 0) { throw new RuntimeException("No language specific websites found - please let the web root parameter " + "point to the 'www' directory (current value: '" + webRoot + "')"); } System.out.println("</tbody>"); System.out.println("</table>"); } private int countRulesForLanguage(Language lang) throws IOException { List<String> ruleFileNames = lang.getRuleFileNames(); int count = 0; for (String ruleFileName : ruleFileNames) { final URL url = this.getClass().getResource(ruleFileName); if (url != null) { String xmlRules = StringTools.readStream(Tools.getStream(ruleFileName), "utf-8"); xmlRules = xmlRules.replaceAll("(?s)", ""); xmlRules = xmlRules.replaceAll("(?s)<rules.*?>", ""); count += countXmlRules(xmlRules); count += countXmlRuleGroupRules(xmlRules); } } return count; } private List<String> getVariants(List<Language> allLanguages, Language lang) { List<String> variants = new ArrayList<>(); for (Language sortedLanguage : allLanguages) { if (sortedLanguage.isVariant() && lang.getShortName().equals(sortedLanguage.getShortName())) { variants.add(sortedLanguage.getName().replaceAll(".*\\((.*?)\\).*", "$1").trim()); } } return variants; } private List<Language> getSortedLanguages() { final List<Language> sortedLanguages = Arrays.asList(Language.REAL_LANGUAGES); Collections.sort(sortedLanguages, new Comparator<Language>() { @Override public int compare(Language o1, Language o2) { return o1.getName().compareTo(o2.getName()); } }); return sortedLanguages; } private int countXmlRules(String xmlRules) { int pos = 0; int count = 0; while (true) { pos = xmlRules.indexOf("<rule ", pos + 1); if (pos == -1) { break; } count++; } return count; } private int countXmlRuleGroupRules(String xmlRules) { int pos = 0; int countInRuleGroup = 0; while (true) { pos = xmlRules.indexOf("<rule>", pos + 1); if (pos == -1) { break; } countInRuleGroup++; } return countInRuleGroup; } private int countFalseFriendRules(String falseFriendRules, Language lang) { int pos = 0; int count = 0; while (true) { pos = falseFriendRules.indexOf("<pattern lang=\"" + lang.getShortName(), pos + 1); if (pos == -1) { break; } count++; } return count; } private StringBuilder getMaintainerInfo(Language lang) { final StringBuilder maintainerInfo = new StringBuilder(); if (lang.getMaintainers() != null) { for (Contributor contributor : lang.getMaintainers()) { if (!StringTools.isEmpty(maintainerInfo.toString())) { maintainerInfo.append(", "); } if (contributor.getUrl() != null) { maintainerInfo.append("<a href=\""); maintainerInfo.append(contributor.getUrl()); maintainerInfo.append("\">"); } maintainerInfo.append(contributor.getName()); if (contributor.getUrl() != null) { maintainerInfo.append("</a>"); } if (contributor.getRemark() != null) { maintainerInfo.append("&nbsp;(" + contributor.getRemark() + ")"); } } } return maintainerInfo; } /*private boolean isAutoDetected(String code) { if (LanguageIdentifier.getSupportedLanguages().contains(code)) { return true; } final Set<String> additionalCodes = new HashSet<String>(Arrays.asList(LanguageIdentifierTools.ADDITIONAL_LANGUAGES)); if (additionalCodes.contains(code)) { return true; } return false; }*/ private class JavaFilter implements FileFilter { private final String langName; public JavaFilter(String langName) { this.langName = langName; } @Override public boolean accept(final File f) { final String filename = f.getName(); final boolean isAbstractTopClass = filename.endsWith(langName + "Rule.java"); return filename.endsWith(".java") && !isAbstractTopClass; } } }
package me.teaisaweso.client; import java.util.Collection; import junit.framework.Assert; import junit.framework.TestCase; import me.teaisaweso.client.graphmanagers.GraphManager2d; import me.teaisaweso.client.graphmanagers.GraphManager2dFactory; import me.teaisaweso.shared.Graph; import me.teaisaweso.shared.Vertex; import me.teaisaweso.shared.VertexDirection; /** * NOTE: this class relies on the GraphManager2d factory working, if it isn't * you should probably assume that this test is totally broken */ public class GraphManager2dTest extends TestCase { private GraphManager2d mManager; private boolean mCalled = false; private Runnable mCheckCalled = new Runnable() { @Override public void run() { GraphManager2dTest.this.mCalled = true; } }; /** * runs test setup, creates a graphmanager instance */ public void setUp() { mManager = GraphManager2dFactory.getInstance().makeDefaultGraphManager(); mCalled = false; } public void tearDown() { mManager = null; mCalled = false; } /** * tests that adding vertices works */ public void testAddVertex_single() { mManager.addVertex(new Vertex("hi"), 0, -3, 10); Graph underlying = mManager.getUnderlyingGraph(); Assert.assertEquals(true, underlying.getVertices().contains(new Vertex("hi"))); Collection<VertexDrawable> drawables = mManager.getVertexDrawables(); Assert.assertEquals(1, drawables.size()); VertexDrawable[] vds = drawables.toArray(new VertexDrawable[] { new VertexDrawable(0, 0, 0, 0, "") }); Assert.assertEquals(0, vds[0].getCenterX()); Assert.assertEquals(-5, vds[0].getLeft()); Assert.assertEquals(-3, vds[0].getCenterY()); Assert.assertEquals(-8, vds[0].getTop()); Assert.assertEquals(10, vds[0].getWidth()); Assert.assertEquals(10, vds[0].getHeight()); Assert.assertEquals("hi", vds[0].getLabel()); } public void testAddVertex_multiple() { mManager.addVertex(new Vertex("bees"), 100, 17, 2); mManager.addVertex(new Vertex("cheese"), 0, 0, 2); Graph underlying = mManager.getUnderlyingGraph(); Assert.assertEquals(2, underlying.getVertices().size()); Assert.assertEquals(true, underlying.getVertices().contains(new Vertex("bees"))); Assert.assertEquals(true, underlying.getVertices().contains(new Vertex("cheese"))); VertexDrawable[] vds = mManager.getVertexDrawables().toArray(new VertexDrawable[] {}); Assert.assertEquals(2, vds.length); } public void testInvalidate_addEdge() { mManager.addRedrawCallback(mCheckCalled); mManager.addEdge(new Vertex("a"), new Vertex("b"), VertexDirection.fromTo); Assert.assertEquals(true, mCalled); } public void testInvalidate_addVertex() { mManager.addRedrawCallback(mCheckCalled); mManager.addVertex(new Vertex("bees"), 0, 0, 10); Assert.assertEquals(true, mCalled); } public void testInvalidate_removeVertex() { mManager.addVertex(new Vertex("faces"), 0, 0, 10); mManager.addRedrawCallback(mCheckCalled); mManager.removeVertex(new Vertex("faces")); Assert.assertEquals(true, mCalled); } public void testInvalidate_removeAllEdges() { mManager.addVertex(new Vertex("faces"), 0, 0, 10); mManager.addVertex(new Vertex("bees"), 0, 0, 10); mManager.addEdge(new Vertex("bees"), new Vertex("faces"), VertexDirection.both); mManager.addRedrawCallback(mCheckCalled); mManager.removeAllEdges(new Vertex("faces"), new Vertex("bees")); Assert.assertEquals(true, mCalled); } }
package com.kaneki.xchatmessageview.base; import android.content.Context; import android.graphics.Color; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import com.kaneki.xchatmessageview.listener.OnLoadMoreListener; import java.util.List; /** * @author yueqian * @Desctription * @date 2017/1/16 * @email yueqian@mogujie.com */ public class XChatMessageView<T> extends ViewGroup { private static final String DEFAULT_BACKGROUND_COLOR = "#f5f5f5"; private Context context; private RecyclerView recyclerView; private LinearLayoutManager linearLayoutManager; private RecyclerView.Adapter messageAdpter; private OnLoadMoreListener onLoadMoreListener; private View mEmptyView; private boolean isLoadMore = false; private int lastPosition = 0; private int lastOffset = 0; private RecyclerView.AdapterDataObserver mObserver = new RecyclerView.AdapterDataObserver() { @Override public void onChanged() { if (mEmptyView != null) { RecyclerView.Adapter adapter = getMessageAdpter(); if (adapter.getItemCount() == 0) { mEmptyView.setVisibility(VISIBLE); XChatMessageView.this.setVisibility(GONE); } else { mEmptyView.setVisibility(GONE); XChatMessageView.this.setVisibility(VISIBLE); } } } public void onItemRangeChanged(int positionStart, int itemCount) {onChanged();} public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {onChanged();} public void onItemRangeRemoved(int positionStart, int itemCount) {onChanged();} public void onItemRangeInserted(int positionStart, int itemCount) {onChanged();} public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {onChanged();} }; public XChatMessageView(Context context) { this(context, null); } public XChatMessageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public XChatMessageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; initView(); initListener(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int measureWidth = measureWidth(widthMeasureSpec); int measureHeight = measureHeight(heightMeasureSpec); // ViewGroup measureChildren(widthMeasureSpec, heightMeasureSpec); // MyViewGroup setMeasuredDimension(measureWidth, measureHeight); } private int measureWidth(int pWidthMeasureSpec) { int result = 0; int widthMode = MeasureSpec.getMode(pWidthMeasureSpec); int widthSize = MeasureSpec.getSize(pWidthMeasureSpec); switch (widthMode) { /** * modeMeasureSpec.UNSPECIFIED, MeasureSpec.EXACTLY, * MeasureSpec.AT_MOST * * * MeasureSpec.EXACTLY * layout_widthlayout_heightandorid * :layout_width="50dip"FILL_PARENT * * * MeasureSpec.AT_MOST * layout_widthlayout_heightWRAP_CONTENT * * modeAT_MOSTsize * * * MeasureSpec.UNSPECIFIEDAdapterView * measure */ case MeasureSpec.AT_MOST: case MeasureSpec.UNSPECIFIED: case MeasureSpec.EXACTLY: result = widthSize; break; } return result; } private int measureHeight(int pHeightMeasureSpec) { int result = 0; int heightMode = MeasureSpec.getMode(pHeightMeasureSpec); int heightSize = MeasureSpec.getSize(pHeightMeasureSpec); switch (heightMode) { case MeasureSpec.AT_MOST: case MeasureSpec.UNSPECIFIED: case MeasureSpec.EXACTLY: result = heightSize; break; } return result; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int mTotalHeight = 0; int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View childView = getChildAt(i); // onMeasure int measureHeight = childView.getMeasuredHeight(); int measuredWidth = childView.getMeasuredWidth(); childView.layout(l, mTotalHeight, measuredWidth, mTotalHeight + measureHeight); mTotalHeight += measureHeight; } } private void initView() { recyclerView = new RecyclerView(context); recyclerView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.MATCH_PARENT)); recyclerView.setBackgroundColor(Color.parseColor(DEFAULT_BACKGROUND_COLOR)); linearLayoutManager = new LinearLayoutManager(context); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(linearLayoutManager); addView(recyclerView); } private void initListener() { recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if (messageAdpter instanceof XMessageApaterHeaderWrapper) { if (((XMessageApaterHeaderWrapper) messageAdpter).isNeedLoadMore()) saveCurrent(); } } }); } private void saveCurrent() { int pos = linearLayoutManager.findFirstVisibleItemPosition(); if (pos == 0 && !isLoadMore) { //headerView View headerView = linearLayoutManager.getChildAt(0); //view View firstView = linearLayoutManager.getChildAt(1); if (headerView != null && firstView != null) { //view lastOffset = firstView.getTop() + headerView.getHeight(); //View lastPosition = linearLayoutManager.getPosition(headerView); isLoadMore = true; onLoadMoreListener.onLoadMore(); } } else { //headerView View currentView = linearLayoutManager.getChildAt(pos); if (currentView != null) { //view lastOffset = currentView.getTop(); //View lastPosition = linearLayoutManager.getPosition(currentView); } } } private void resumeSave(int changeSize) { linearLayoutManager.scrollToPositionWithOffset(lastPosition + changeSize, lastOffset); } public void setEmptyView(View view){ this.mEmptyView = view; ((ViewGroup)this.getRootView()).addView(mEmptyView); } /** * set message adapter, the adpter should extend XMessageAdapter. * @param messageAdapter */ public void setMessageAdapter(RecyclerView.Adapter messageAdapter) { this.messageAdpter = messageAdapter; this.messageAdpter.registerAdapterDataObserver(mObserver); recyclerView.setAdapter(messageAdapter); recyclerView.scrollToPosition(messageAdpter.getItemCount() - 1); mObserver.onChanged(); } /** * set message load more listener, it calls when the header is visibile and only * calls once when trigger. * @param onLoadMoreListener */ public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) { this.onLoadMoreListener = onLoadMoreListener; } /** * get message adpater, it may return null if setMessageAdapter method whit null set. * @return */ public RecyclerView.Adapter getMessageAdpter() { return messageAdpter; } /** * toggle the load more header, it should be call before the datas change. * @param isNeedLoadMore */ public void setIsNeedLoadMore(boolean isNeedLoadMore) { if (messageAdpter instanceof XMessageApaterHeaderWrapper) { ((XMessageApaterHeaderWrapper) messageAdpter).setNeedLoadMore(isNeedLoadMore); } } /** * return the view's position on the XChatMessageView, the view should come from the XViewHolder. * @param view * @return */ public int getMessageItemPosition(View view) { return linearLayoutManager == null ? -1 : linearLayoutManager.getPosition(view); } /** * add a new message at the last of the XChatMessageView, the message should as same as the T of the * XViewHolder or XMessageAdapter. * @param t */ @SuppressWarnings("unchecked") public void addMessageAtLast(T t) { if (messageAdpter instanceof XMessageApaterHeaderWrapper) { ((XMessageApaterHeaderWrapper) messageAdpter).addMessageAtLast(t); } else { ((XMessageAdapter) messageAdpter).addMessageAtLast(t); } recyclerView.scrollToPosition(messageAdpter.getItemCount() - 1); } /** * add messages at the last of the XChatMessageView, the message should as same as the T of the * XViewHolder or XMessageAdapter. * @param tList */ @SuppressWarnings("unchecked") public void addMoreMessageAtLast(List<T> tList) { if (messageAdpter instanceof XMessageApaterHeaderWrapper) { ((XMessageApaterHeaderWrapper) messageAdpter).addMoreMessageAtLast(tList); } else { ((XMessageAdapter) messageAdpter).addMoreMessageAtLast(tList); } recyclerView.scrollToPosition(messageAdpter.getItemCount() - 1); } /** * add messages at the first of the XChatMessageView, the message should as same as the T of the * XViewHolder or XMessageAdapter. * @param tList */ @SuppressWarnings("unchecked") public void addMoreMessageAtFirst(List<T> tList) { if (messageAdpter instanceof XMessageApaterHeaderWrapper) { ((XMessageApaterHeaderWrapper) messageAdpter).addMoreMessageAtFirst(tList); if (!((XMessageApaterHeaderWrapper) messageAdpter).isNeedLoadMore()) resumeSave(tList.size()); } else { ((XMessageAdapter) messageAdpter).addMoreMessageAtFirst(tList, false); } isLoadMore = false; } /** * remove the message on the XChatMessageView, the view should come from the XViewHolder callback. * @param view */ public void reomveMessage(View view) { int position = linearLayoutManager.getPosition(view); if (messageAdpter instanceof XMessageApaterHeaderWrapper) { ((XMessageApaterHeaderWrapper) messageAdpter).removeMessageAtPosition(position); } else { ((XMessageAdapter) messageAdpter).removeMessageAtPosition(position, false); } } /** * scroll to the bottom of the XChatMessageView. */ public void scrollToBottom() { recyclerView.scrollToPosition(messageAdpter.getItemCount() - 1); } /** * save the XChatMessageView current status, you can resume the statuswhen you need. */ public void saveCurrentStatus() { saveCurrent(); } /** * resume the XChatMessageView's saved status. */ public void resumeSaveStatus() { resumeSave(0); } }
package com.pengrad.telegrambot.request; import com.pengrad.telegrambot.response.BaseResponse; /** * Stas Parshin * 01 July 2017 */ public class PromoteChatMember extends BaseRequest<PromoteChatMember, BaseResponse> { public PromoteChatMember(Object chatId, long userId) { super(BaseResponse.class); add("chat_id", chatId).add("user_id", userId); } public PromoteChatMember isAnonymous(boolean isAnonymous) { return add("is_anonymous", isAnonymous); } public PromoteChatMember canManageChat(boolean canManageChat) { return add("can_manage_chat", canManageChat); } public PromoteChatMember canChangeInfo(boolean canChangeInfo) { return add("can_change_info", canChangeInfo); } public PromoteChatMember canPostMessages(boolean canPostMessages) { return add("can_post_messages", canPostMessages); } public PromoteChatMember canEditMessages(boolean canEditMessages) { return add("can_edit_messages", canEditMessages); } public PromoteChatMember canDeleteMessages(boolean canDeleteMessages) { return add("can_delete_messages", canDeleteMessages); } /** * @Deprecated Use canManageVideoChats(boolean canManageVideoChats) instead */ public PromoteChatMember canManageVoiceChats(boolean canManageVoiceChats) { return add("can_manage_video_chats", canManageVoiceChats); } public PromoteChatMember canManageVideoChats(boolean canManageVideoChats) { return add("can_manage_video_chats", canManageVideoChats); } public PromoteChatMember canInviteUsers(boolean canInviteUsers) { return add("can_invite_users", canInviteUsers); } public PromoteChatMember canRestrictMembers(boolean canRestrictMembers) { return add("can_restrict_members", canRestrictMembers); } public PromoteChatMember canPinMessages(boolean canPinMessages) { return add("can_pin_messages", canPinMessages); } public PromoteChatMember canPromoteMembers(boolean canPromoteMembers) { return add("can_promote_members", canPromoteMembers); } }
package liquibase.change.core; import liquibase.change.DatabaseChange; import liquibase.change.ChangeMetaData; import liquibase.change.DatabaseChangeProperty; import liquibase.database.Database; import liquibase.datatype.DataTypeFactory; import liquibase.exception.RollbackImpossibleException; import liquibase.exception.LiquibaseException; import liquibase.statement.SqlStatement; import liquibase.statement.core.DeleteStatement; import liquibase.statement.core.InsertOrUpdateStatement; import liquibase.statement.core.InsertStatement; import java.util.ArrayList; import java.util.List; @DatabaseChange(name="loadUpdateData", description = "Loads or updates data from a CSV file into an existing table. Differs from loadData by issuing a SQL batch that checks for the existence of a record. If found, the record is UPDATEd, else the record is INSERTed. Also, generates DELETE statements for a rollback.\n" + "\n" + "A value of NULL in a cell will be converted to a database NULL rather than the string 'NULL'", priority = ChangeMetaData.PRIORITY_DEFAULT, appliesTo = "table", since = "2.0") public class LoadUpdateDataChange extends LoadDataChange { private String primaryKey; @Override @DatabaseChangeProperty(description = "Name of the table to insert or update data in", requiredForDatabase = "all") public String getTableName() { return super.getTableName(); } public void setPrimaryKey(String primaryKey) throws LiquibaseException { this.primaryKey = primaryKey; } @DatabaseChangeProperty(description = "Comma delimited list of the columns for the primary key", requiredForDatabase = "all") public String getPrimaryKey() { return primaryKey; } @Override protected InsertStatement createStatement(String catalogName, String schemaName, String tableName) { return new InsertOrUpdateStatement(catalogName, schemaName, tableName, this.primaryKey); } @Override public SqlStatement[] generateRollbackStatements(Database database) throws RollbackImpossibleException { List<SqlStatement> statements = new ArrayList<SqlStatement>(); SqlStatement[] forward = this.generateStatements(database); for(SqlStatement thisForward: forward){ InsertOrUpdateStatement thisInsert = (InsertOrUpdateStatement)thisForward; DeleteStatement delete = new DeleteStatement(getCatalogName(), getSchemaName(),getTableName()); delete.setWhere(getWhere(thisInsert,database)); statements.add(delete); } return statements.toArray(new SqlStatement[statements.size()]); } private String getWhere(InsertOrUpdateStatement insertOrUpdateStatement, Database database) { StringBuilder where = new StringBuilder(); String[] pkColumns = insertOrUpdateStatement.getPrimaryKey().split(","); for(String thisPkColumn:pkColumns) { where.append(database.escapeColumnName(insertOrUpdateStatement.getCatalogName(), insertOrUpdateStatement.getSchemaName(), insertOrUpdateStatement.getTableName(), thisPkColumn)).append(" = "); Object newValue = insertOrUpdateStatement.getColumnValues().get(thisPkColumn); where.append(DataTypeFactory.getInstance().fromObject(newValue, database).objectToSql(newValue, database)); where.append(" AND "); } where.delete(where.lastIndexOf(" AND "),where.lastIndexOf(" AND ") + " AND ".length()); return where.toString(); } }
package datafu.test.pig.stats; import static org.testng.Assert.*; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import org.adrianwalker.multilinestring.Multiline; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.pigunit.PigTest; import org.testng.annotations.Test; import datafu.pig.stats.QuantileUtil; import datafu.pig.stats.StreamingQuantile; import datafu.test.pig.PigTests; public class QuantileTests extends PigTests { /** register $JAR_PATH define Quantile datafu.pig.stats.Quantile($QUANTILES); data_in = LOAD 'input' as (val:int); --describe data_in; data_out = GROUP data_in ALL; --describe data_out; data_out = FOREACH data_out { sorted = ORDER data_in BY val; GENERATE Quantile(sorted) as quantiles; } data_out = FOREACH data_out GENERATE FLATTEN(quantiles); --describe data_out; STORE data_out into 'output'; */ @Multiline private String quantileTest; @Test public void quantileTest() throws Exception { PigTest test = createPigTestFromString(quantileTest, "QUANTILES='0.0','0.25','0.5','0.75','1.0'"); String[] input = {"1","2","3","4","10","5","6","7","8","9"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,3.0,5.5,8.0,10.0)"); } @Test public void quantile2Test() throws Exception { PigTest test = createPigTestFromString(quantileTest, "QUANTILES='5'"); String[] input = {"1","2","3","4","10","5","6","7","8","9"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,3.0,5.5,8.0,10.0)"); } @Test public void quantile3Test() throws Exception { PigTest test = createPigTestFromString(quantileTest, "QUANTILES='0.0013','0.0228','0.1587','0.5','0.8413','0.9772','0.9987'"); List<String> input = new ArrayList<String>(); for (int i=100000; i>=0; i { input.add(Integer.toString(i)); } writeLinesToFile("input", input.toArray(new String[0])); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(130.0,2280.0,15870.0,50000.0,84130.0,97720.0,99870.0)"); } @Test public void quantile4aTest() throws Exception { PigTest test = createPigTestFromString(quantileTest, "QUANTILES='4'"); String[] input = {"1","2","3","4","10","5","6","7","8","9"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,4.0,7.0,10.0)"); } @Test public void quantile4bTest() throws Exception { PigTest test = createPigTestFromString(quantileTest, "QUANTILES='0.0','0.333','0.666','1.0'"); String[] input = {"1","2","3","4","10","5","6","7","8","9"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,4.0,7.0,10.0)"); } @Test public void quantile5aTest() throws Exception { PigTest test = createPigTestFromString(quantileTest, "QUANTILES='10'"); String[] input = {"1","2","3","4","10","5","6","7","8","9"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0)"); } @Test public void quantile5bTest() throws Exception { PigTest test = createPigTestFromString(quantileTest, "QUANTILES='0.0','0.111','0.222','0.333','0.444','0.555','0.666','0.777','0.888','1.0'"); String[] input = {"1","2","3","4","10","5","6","7","8","9"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0)"); } /** register $JAR_PATH define Median datafu.pig.stats.Median(); data_in = LOAD 'input' as (val:int); --describe data_in; data_out = GROUP data_in ALL; --describe data_out; data_out = FOREACH data_out { sorted = ORDER data_in BY val; GENERATE Median(sorted) as medians; } data_out = FOREACH data_out GENERATE FLATTEN(medians); --describe data_out; STORE data_out into 'output'; */ @Multiline private String medianTest; @Test public void medianTest() throws Exception { PigTest test = createPigTestFromString(medianTest); String[] input = {"4","5","6","9","10","7","8","2","3","1"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(5.5)"); } /** register $JAR_PATH define Median datafu.pig.stats.StreamingMedian(); data_in = LOAD 'input' as (val:int); --describe data_in; data_out = GROUP data_in ALL; --describe data_out; data_out = FOREACH data_out { GENERATE Median(data_in) as medians; } data_out = FOREACH data_out GENERATE FLATTEN(medians); --describe data_out; STORE data_out into 'output'; */ @Multiline private String streamingMedianTest; @Test public void streamingMedianTest() throws Exception { PigTest test = createPigTestFromString(streamingMedianTest); String[] input = {"0","4","5","6","9","10","7","8","2","3","1"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(5.0)"); } /** register $JAR_PATH define Quantile datafu.pig.stats.StreamingQuantile($QUANTILES); data_in = LOAD 'input' as (val:int); --describe data_in; data_out = GROUP data_in ALL; --describe data_out; data_out = FOREACH data_out GENERATE Quantile(data_in.val) as quantiles; data_out = FOREACH data_out GENERATE FLATTEN(quantiles); --describe data_out; STORE data_out into 'output'; */ @Multiline private String streamingQuantileTest; @Test public void streamingQuantileTest() throws Exception { PigTest test = createPigTestFromString(streamingQuantileTest, "QUANTILES='5'"); String[] input = {"1","2","3","4","10","5","6","7","8","9"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,3.0,5.0,8.0,10.0)"); } @Test public void streamingQuantile2Test() throws Exception { PigTest test = createPigTestFromString(streamingQuantileTest, "QUANTILES='0.5','0.75','1.0'"); String[] input = {"1","2","3","4","10","5","6","7","8","9"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(5.0,8.0,10.0)"); } @Test public void streamingQuantile3Test() throws Exception { PigTest test = createPigTestFromString(streamingQuantileTest, "QUANTILES='0.07','0.03','0.37','1.0','0.0'"); List<String> input = new ArrayList<String>(); for (int i=1000; i>=1; i { input.add(Integer.toString(i)); } writeLinesToFile("input", input.toArray(new String[0])); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(70.0,30.0,370.0,1000.0,1.0)"); } @Test public void streamingQuantile4Test() throws Exception { PigTest test = createPigTestFromString(streamingQuantileTest, "QUANTILES='0.0013','0.0228','0.1587','0.5','0.8413','0.9772','0.9987'"); List<String> input = new ArrayList<String>(); for (int i=100000; i>=0; i { input.add(Integer.toString(i)); } writeLinesToFile("input", input.toArray(new String[0])); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(130.0,2280.0,15870.0,50000.0,84130.0,97720.0,99870.0)"); } @Test public void streamingQuantile5aTest() throws Exception { PigTest test = createPigTestFromString(streamingQuantileTest, "QUANTILES='10'"); String[] input = {"1","2","3","4","10","5","6","7","8","9"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0)"); } @Test public void streamingQuantile5bTest() throws Exception { PigTest test = createPigTestFromString(streamingQuantileTest, "QUANTILES='0.0','0.111','0.222','0.333','0.444','0.555','0.666','0.777','0.888','1.0'"); String[] input = {"1","2","3","4","10","5","6","7","8","9"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0)"); } @Test public void streamingQuantile6Test() throws Exception { PigTest test = createPigTestFromString(streamingQuantileTest, "QUANTILES='0.0','0.333','0.666','1.0'"); String[] input = {"1","2","3","4","10","5","6","7","8","9"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,4.0,7.0,10.0)"); } @Test public void streamingQuantile7Test() throws Exception { PigTest test = createPigTestFromString(streamingQuantileTest, "QUANTILES='4'"); String[] input = {"1","2","3","4","10","5","6","7","8","9"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,4.0,7.0,10.0)"); } @Test public void streamingQuantileExecTest() throws Exception { StreamingQuantile quantile = new StreamingQuantile("4"); DataBag bag; Tuple input; Tuple result; bag = BagFactory.getInstance().newDefaultBag(); for (int i=1; i<=10; i++) { Tuple t = TupleFactory.getInstance().newTuple(1); t.set(0, i); bag.add(t); } input = TupleFactory.getInstance().newTuple(bag); result = quantile.exec(input); Assert.assertEquals(4, result.size()); Assert.assertEquals(1.0, result.get(0)); Assert.assertEquals(4.0, result.get(1)); Assert.assertEquals(7.0, result.get(2)); Assert.assertEquals(10.0, result.get(3)); // do twice to check cleanup works bag = BagFactory.getInstance().newDefaultBag(); for (int i=11; i<=20; i++) { Tuple t = TupleFactory.getInstance().newTuple(1); t.set(0, i); bag.add(t); } input = TupleFactory.getInstance().newTuple(bag); result = quantile.exec(input); Assert.assertEquals(4, result.size()); Assert.assertEquals(11.0, result.get(0)); Assert.assertEquals(14.0, result.get(1)); Assert.assertEquals(17.0, result.get(2)); Assert.assertEquals(20.0, result.get(3)); } @Test public void streamingQuantileAccumulateTest() throws Exception { StreamingQuantile quantile = new StreamingQuantile("4"); Tuple result; for (int i=1; i<=10; i++) { Tuple t = TupleFactory.getInstance().newTuple(1); t.set(0, i); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(t); Tuple input = TupleFactory.getInstance().newTuple(bag); quantile.accumulate(input); } result = quantile.getValue(); Assert.assertEquals(4, result.size()); Assert.assertEquals(1.0, result.get(0)); Assert.assertEquals(4.0, result.get(1)); Assert.assertEquals(7.0, result.get(2)); Assert.assertEquals(10.0, result.get(3)); // do twice to check cleanup works quantile.cleanup(); for (int i=11; i<=20; i++) { Tuple t = TupleFactory.getInstance().newTuple(1); t.set(0, i); DataBag bag = BagFactory.getInstance().newDefaultBag(); bag.add(t); Tuple input = TupleFactory.getInstance().newTuple(bag); quantile.accumulate(input); } result = quantile.getValue(); Assert.assertEquals(4, result.size()); Assert.assertEquals(11.0, result.get(0)); Assert.assertEquals(14.0, result.get(1)); Assert.assertEquals(17.0, result.get(2)); Assert.assertEquals(20.0, result.get(3)); } @Test public void quantileParamsTest() throws Exception { List<Double> quantiles = QuantileUtil.getQuantilesFromParams("5"); assertEquals(quantiles.size(),5); assertAboutEqual(quantiles.get(0), 0.0); assertAboutEqual(quantiles.get(1), 0.25); assertAboutEqual(quantiles.get(2), 0.5); assertAboutEqual(quantiles.get(3), 0.75); assertAboutEqual(quantiles.get(4), 1.0); } @Test public void quantileParamsTest2() throws Exception { List<Double> quantiles = QuantileUtil.getQuantilesFromParams("2"); assertEquals(quantiles.size(),2); assertAboutEqual(quantiles.get(0), 0.0); assertAboutEqual(quantiles.get(1), 1.0); } @Test public void quantileParamsTest3() throws Exception { List<Double> quantiles = QuantileUtil.getQuantilesFromParams("11"); assertEquals(quantiles.size(),11); assertAboutEqual(quantiles.get(0), 0.0); assertAboutEqual(quantiles.get(1), 0.1); assertAboutEqual(quantiles.get(2), 0.2); assertAboutEqual(quantiles.get(3), 0.3); assertAboutEqual(quantiles.get(4), 0.4); assertAboutEqual(quantiles.get(5), 0.5); assertAboutEqual(quantiles.get(6), 0.6); assertAboutEqual(quantiles.get(7), 0.7); assertAboutEqual(quantiles.get(8), 0.8); assertAboutEqual(quantiles.get(9), 0.9); assertAboutEqual(quantiles.get(10), 1.0); } @Test public void quantileParamsTest4() throws Exception { List<Double> quantiles = QuantileUtil.getQuantilesFromParams("10"); assertEquals(quantiles.size(),10); assertAboutEqual(quantiles.get(0), 0.0); assertAboutEqual(quantiles.get(1), 0.11111); assertAboutEqual(quantiles.get(2), 0.22222); assertAboutEqual(quantiles.get(3), 0.33333); assertAboutEqual(quantiles.get(4), 0.44444); assertAboutEqual(quantiles.get(5), 0.55555); assertAboutEqual(quantiles.get(6), 0.66666); assertAboutEqual(quantiles.get(7), 0.77777); assertAboutEqual(quantiles.get(8), 0.88888); assertAboutEqual(quantiles.get(9), 1.0); } @Test public void quantileParamsTest5() throws Exception { List<Double> quantiles = QuantileUtil.getQuantilesFromParams("4"); assertEquals(quantiles.size(),4); assertAboutEqual(quantiles.get(0), 0.0); assertAboutEqual(quantiles.get(1), 0.333); assertAboutEqual(quantiles.get(2), 0.666); assertAboutEqual(quantiles.get(3), 1.0); } private void assertAboutEqual(double actual, double expected) { assertTrue(Math.abs(actual-expected) < 0.001); } /** register $JAR_PATH define Quantile datafu.pig.stats.$UDF($QUANTILES); data_in = LOAD 'input' as (val:int); --describe data_in; data_out = GROUP data_in ALL; --describe data_out; data_out = FOREACH data_out { sorted = ORDER data_in BY val; GENERATE Quantile(sorted) as quantiles; } data_out = FOREACH data_out GENERATE FLATTEN(quantiles); --describe data_out; data_out = FOREACH data_out GENERATE $EXPECTED_OUTPUT; STORE data_out into 'output'; */ @Multiline private String quantileSchemaTest; @Test public void quantileSchemaTest() throws Exception { PigTest test = createPigTestFromString(quantileSchemaTest, "UDF=Quantile", "QUANTILES='0.0','0.5','1.0'", "EXPECTED_OUTPUT=quantiles::quantile_0_0, "+ "quantiles::quantile_0_5, "+ "quantiles::quantile_1_0"); String[] input = {"1","5","3","4","2"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,3.0,5.0)"); } @Test public void quantileSchemaTest2() throws Exception { PigTest test = createPigTestFromString(quantileSchemaTest, "UDF=Quantile", "QUANTILES='3'", "EXPECTED_OUTPUT=quantiles::quantile_0, "+ "quantiles::quantile_1, "+ "quantiles::quantile_2"); String[] input = {"1","5","3","4","2"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,3.0,5.0)"); } @Test public void quantileSchemaTest3() throws Exception { PigTest test = createPigTestFromString(quantileSchemaTest, "UDF=StreamingQuantile", "QUANTILES='0.0','0.5','1.0'", "EXPECTED_OUTPUT=quantiles::quantile_0_0, "+ "quantiles::quantile_0_5, "+ "quantiles::quantile_1_0"); String[] input = {"1","5","3","4","2"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,3.0,5.0)"); } @Test public void quantileSchemaTest4() throws Exception { PigTest test = createPigTestFromString(quantileSchemaTest, "UDF=StreamingQuantile", "QUANTILES='3'", "EXPECTED_OUTPUT=quantiles::quantile_0, "+ "quantiles::quantile_1, "+ "quantiles::quantile_2"); String[] input = {"1","5","3","4","2"}; writeLinesToFile("input", input); test.runScript(); List<Tuple> output = getLinesForAlias(test, "data_out", true); assertEquals(output.size(),1); assertEquals(output.get(0).toString(), "(1.0,3.0,5.0)"); } }
package com.angkorteam.mbaas.server.nashorn; import com.angkorteam.mbaas.configuration.Constants; import com.angkorteam.mbaas.model.entity.Tables; import com.angkorteam.mbaas.model.entity.tables.QueryTable; import com.angkorteam.mbaas.model.entity.tables.UserTable; import com.angkorteam.mbaas.model.entity.tables.records.QueryRecord; import com.angkorteam.mbaas.plain.Identity; import com.angkorteam.mbaas.plain.enums.QueryReturnTypeEnum; import com.angkorteam.mbaas.plain.enums.SecurityEnum; import com.angkorteam.mbaas.plain.request.document.DocumentCreateRequest; import com.angkorteam.mbaas.plain.request.document.DocumentModifyRequest; import com.angkorteam.mbaas.server.function.DocumentFunction; import jdk.nashorn.api.scripting.JSObject; import org.apache.commons.configuration.XMLPropertiesConfiguration; import org.jooq.DSLContext; import org.jooq.impl.DSL; import org.springframework.dao.*; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.IncorrectResultSetColumnCountException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import javax.script.ScriptException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; public class Database { private final NamedParameterJdbcTemplate namedParameterJdbcTemplate; private final JdbcTemplate jdbcTemplate; private final MBaaS mbaas; private final DSLContext context; private final Identity identity; public Database(DSLContext context, Identity identity, JdbcTemplate jdbcTemplate, MBaaS mbaas) { this.jdbcTemplate = jdbcTemplate; this.identity = identity; this.context = context; this.mbaas = mbaas; this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate); } public String uuid() { return UUID.randomUUID().toString(); } public String insert(String collection, JSObject document) throws ScriptException { String ownerUserId = identity.getUserId(); if (ownerUserId == null || "".equals(ownerUserId)) { XMLPropertiesConfiguration configuration = Constants.getXmlPropertiesConfiguration(); String userAdmin = configuration.getString(Constants.USER_ADMIN); UserTable userTable = com.angkorteam.mbaas.model.entity.Tables.USER.as("userTable"); ownerUserId = jdbcTemplate.queryForObject("SELECT " + userTable.USER_ID.getName() + " FROM " + userTable.getName() + " WHERE " + userTable.LOGIN.getName() + " = ?", String.class, userAdmin); } return insert(ownerUserId, collection, document); } public String insert(String ownerUserId, String collection, JSObject document) { Map<String, Object> params = new HashMap<>(); if (document.isArray() || document.isStrictFunction() || document.isFunction()) { throw new DataIntegrityViolationException("could not insert into " + collection); } parse(params, document, collection); DocumentCreateRequest request = new DocumentCreateRequest(); request.setDocument(params); return DocumentFunction.insertDocument(context, jdbcTemplate, ownerUserId, collection, request); } private void parse(Map<String, Object> params, JSObject document, String collection) { for (String key : document.keySet()) { Object value = document.getMember(key); if (value instanceof Boolean || value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double || value instanceof Character || value instanceof String || value instanceof Date) { params.put(key, value); } else { throw new DataIntegrityViolationException("could not insert into " + collection); } } } public void delete(String collection, String documentId) { DocumentFunction.deleteDocument(context, jdbcTemplate, collection, documentId); } public void modify(String collection, String documentId, JSObject document) { Map<String, Object> params = new HashMap<>(); if (document.isArray() || document.isStrictFunction() || document.isFunction()) { throw new DataIntegrityViolationException("could not insert into " + collection); } parse(params, document, collection); DocumentModifyRequest request = new DocumentModifyRequest(); request.setDocument(params); DocumentFunction.modifyDocument(context, jdbcTemplate, collection, documentId, request); } public Object executeQuery(String query) throws DataAccessException { QueryTable queryTable = com.angkorteam.mbaas.model.entity.Tables.QUERY.as("queryTable"); QueryRecord queryRecord = context.select(queryTable.fields()).from(queryTable).where(queryTable.NAME.eq(query)).fetchOneInto(queryTable); if (queryRecord == null || queryRecord.getScript() == null || "".equals(queryRecord.getScript()) || SecurityEnum.Denied.getLiteral().equals(queryRecord.getSecurity())) { throw new DataAccessResourceFailureException("query is not available"); } XMLPropertiesConfiguration configuration = Constants.getXmlPropertiesConfiguration(); try { if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Boolean.getLiteral())) { return jdbcTemplate.queryForObject(queryRecord.getScript(), Boolean.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Byte.getLiteral())) { return jdbcTemplate.queryForObject(queryRecord.getScript(), Byte.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Short.getLiteral())) { return jdbcTemplate.queryForObject(queryRecord.getScript(), Short.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Integer.getLiteral())) { return jdbcTemplate.queryForObject(queryRecord.getScript(), Integer.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Long.getLiteral())) { return jdbcTemplate.queryForObject(queryRecord.getScript(), Long.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Float.getLiteral())) { return jdbcTemplate.queryForObject(queryRecord.getScript(), Float.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Double.getLiteral())) { return jdbcTemplate.queryForObject(queryRecord.getScript(), Double.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Character.getLiteral())) { return jdbcTemplate.queryForObject(queryRecord.getScript(), Character.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.String.getLiteral())) { return jdbcTemplate.queryForObject(queryRecord.getScript(), String.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Time.getLiteral())) { DateFormat dateFormat = new SimpleDateFormat(configuration.getString(Constants.PATTERN_TIME)); Date value = jdbcTemplate.queryForObject(queryRecord.getScript(), Date.class); if (value != null) { return dateFormat.format(value); } } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Date.getLiteral())) { DateFormat dateFormat = new SimpleDateFormat(configuration.getString(Constants.PATTERN_DATE)); Date value = jdbcTemplate.queryForObject(queryRecord.getScript(), Date.class); if (value != null) { return dateFormat.format(value); } } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.DateTime.getLiteral())) { DateFormat dateFormat = new SimpleDateFormat(configuration.getString(Constants.PATTERN_DATETIME)); Date value = jdbcTemplate.queryForObject(queryRecord.getScript(), Date.class); if (value != null) { return dateFormat.format(value); } } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Map.getLiteral())) { return jdbcTemplate.queryForMap(queryRecord.getScript()); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.List.getLiteral())) { if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Boolean.getLiteral())) { return jdbcTemplate.queryForList(queryRecord.getScript(), Boolean.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Byte.getLiteral())) { return jdbcTemplate.queryForList(queryRecord.getScript(), Byte.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Short.getLiteral())) { return jdbcTemplate.queryForList(queryRecord.getScript(), Short.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Integer.getLiteral())) { return jdbcTemplate.queryForList(queryRecord.getScript(), Integer.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Long.getLiteral())) { return jdbcTemplate.queryForList(queryRecord.getScript(), Long.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Float.getLiteral())) { return jdbcTemplate.queryForList(queryRecord.getScript(), Float.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Double.getLiteral())) { return jdbcTemplate.queryForList(queryRecord.getScript(), Double.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Character.getLiteral())) { return jdbcTemplate.queryForList(queryRecord.getScript(), Character.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.String.getLiteral())) { return jdbcTemplate.queryForList(queryRecord.getScript(), String.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Time.getLiteral())) { return jdbcTemplate.queryForList(queryRecord.getScript(), Date.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Date.getLiteral())) { return jdbcTemplate.queryForList(queryRecord.getScript(), Date.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.DateTime.getLiteral())) { return jdbcTemplate.queryForList(queryRecord.getScript(), Date.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Map.getLiteral())) { return jdbcTemplate.queryForList(queryRecord.getScript()); } else { return jdbcTemplate.queryForList(queryRecord.getScript()); } } } catch (EmptyResultDataAccessException e) { } catch (IncorrectResultSetColumnCountException | IncorrectResultSizeDataAccessException | BadSqlGrammarException e) { throw new DataAccessResourceFailureException(e.getMessage()); } return null; } public Object executeQuery(String query, JSObject js) throws DataAccessException { if (js.isArray() || js.isStrictFunction() || js.isStrictFunction()) { throw new DataAccessResourceFailureException(query); } QueryTable queryTable = com.angkorteam.mbaas.model.entity.Tables.QUERY.as("queryTable"); QueryRecord queryRecord = context.select(queryTable.fields()).from(queryTable).where(queryTable.NAME.eq(query)).fetchOneInto(queryTable); if (queryRecord == null || queryRecord.getScript() == null || "".equals(queryRecord.getScript()) || SecurityEnum.Denied.getLiteral().equals(queryRecord.getSecurity())) { throw new DataAccessResourceFailureException(query + " is not available"); } Map<String, Object> params = new HashMap<>(); for (String key : js.keySet()) { Object object = js.getMember(key); if (object instanceof JSObject) { if (((JSObject) object).isArray()) { List<Object> values = new LinkedList<>(); for (Object value : ((JSObject) object).values()) { values.add(value); } params.put(key, values); } else { throw new DataAccessResourceFailureException(key + " type is not supported"); } } else { params.put(key, object); } } XMLPropertiesConfiguration configuration = Constants.getXmlPropertiesConfiguration(); NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate); try { if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Boolean.getLiteral())) { return namedParameterJdbcTemplate.queryForObject(queryRecord.getScript(), params, Boolean.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Byte.getLiteral())) { return namedParameterJdbcTemplate.queryForObject(queryRecord.getScript(), params, Byte.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Short.getLiteral())) { return namedParameterJdbcTemplate.queryForObject(queryRecord.getScript(), params, Short.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Integer.getLiteral())) { return namedParameterJdbcTemplate.queryForObject(queryRecord.getScript(), params, Integer.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Long.getLiteral())) { return namedParameterJdbcTemplate.queryForObject(queryRecord.getScript(), params, Long.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Float.getLiteral())) { return namedParameterJdbcTemplate.queryForObject(queryRecord.getScript(), params, Float.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Double.getLiteral())) { return namedParameterJdbcTemplate.queryForObject(queryRecord.getScript(), params, Double.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Character.getLiteral())) { return namedParameterJdbcTemplate.queryForObject(queryRecord.getScript(), params, Character.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.String.getLiteral())) { return namedParameterJdbcTemplate.queryForObject(queryRecord.getScript(), params, String.class); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Time.getLiteral())) { DateFormat dateFormat = new SimpleDateFormat(configuration.getString(Constants.PATTERN_TIME)); Date value = namedParameterJdbcTemplate.queryForObject(queryRecord.getScript(), params, Date.class); if (value != null) { return dateFormat.format(value); } } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Date.getLiteral())) { DateFormat dateFormat = new SimpleDateFormat(configuration.getString(Constants.PATTERN_DATE)); Date value = namedParameterJdbcTemplate.queryForObject(queryRecord.getScript(), params, Date.class); if (value != null) { return dateFormat.format(value); } } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.DateTime.getLiteral())) { DateFormat dateFormat = new SimpleDateFormat(configuration.getString(Constants.PATTERN_DATETIME)); Date value = namedParameterJdbcTemplate.queryForObject(queryRecord.getScript(), params, Date.class); if (value != null) { return dateFormat.format(value); } } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.Map.getLiteral())) { return namedParameterJdbcTemplate.queryForMap(queryRecord.getScript(), params); } else if (queryRecord.getReturnType().equals(QueryReturnTypeEnum.List.getLiteral())) { if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Boolean.getLiteral())) { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params, Boolean.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Byte.getLiteral())) { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params, Byte.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Short.getLiteral())) { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params, Short.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Integer.getLiteral())) { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params, Integer.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Long.getLiteral())) { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params, Long.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Float.getLiteral())) { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params, Float.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Double.getLiteral())) { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params, Double.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Character.getLiteral())) { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params, Character.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.String.getLiteral())) { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params, String.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Time.getLiteral())) { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params, Date.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Date.getLiteral())) { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params, Date.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.DateTime.getLiteral())) { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params, Date.class); } else if (queryRecord.getReturnSubType().equals(QueryReturnTypeEnum.Map.getLiteral())) { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params); } else { return namedParameterJdbcTemplate.queryForList(queryRecord.getScript(), params); } } } catch (EmptyResultDataAccessException e) { } catch (IncorrectResultSetColumnCountException | IncorrectResultSizeDataAccessException | BadSqlGrammarException e) { throw new DataAccessResourceFailureException(e.getMessage()); } return null; } public Map<String, Object> queryForMap(String sql) throws DataAccessException { if (!sql.trim().substring(0, "select".length()).toLowerCase().equals("select")) { throw new DataAccessResourceFailureException(sql); } return this.jdbcTemplate.queryForMap(sql); } public Map<String, Object> queryForMap(String sql, JSObject js) throws DataAccessException { if (js.isArray() || js.isStrictFunction() || js.isStrictFunction()) { throw new DataAccessResourceFailureException(sql); } Map<String, Object> paramMap = new HashMap<>(); for (String key : js.keySet()) { paramMap.put(key, js.getMember(key)); } if (!sql.trim().substring(0, "select".length()).toLowerCase().equals("select")) { throw new DataAccessResourceFailureException(sql); } return this.namedParameterJdbcTemplate.queryForMap(sql, paramMap); } public boolean queryForBoolean(String sql) throws DataAccessException { return queryForObject(sql, boolean.class); } public boolean queryForBoolean(String sql, JSObject js) throws DataAccessException { return queryForObject(sql, js, boolean.class); } public byte queryForByte(String sql) throws DataAccessException { return queryForObject(sql, byte.class); } public byte queryForByte(String sql, JSObject js) throws DataAccessException { return queryForObject(sql, js, byte.class); } public short queryForShort(String sql) throws DataAccessException { return queryForObject(sql, short.class); } public short queryForShort(String sql, JSObject js) throws DataAccessException { return queryForObject(sql, js, short.class); } public int queryForInteger(String sql) throws DataAccessException { return queryForObject(sql, int.class); } public int queryForInteger(String sql, JSObject js) throws DataAccessException { return queryForObject(sql, js, int.class); } public long queryForLong(String sql) throws DataAccessException { return queryForObject(sql, long.class); } public long queryForLong(String sql, JSObject js) throws DataAccessException { return queryForObject(sql, js, long.class); } public float queryForFloat(String sql) throws DataAccessException { return queryForObject(sql, float.class); } public float queryForFloat(String sql, JSObject js) throws DataAccessException { return queryForObject(sql, js, float.class); } public double queryForDouble(String sql) throws DataAccessException { return queryForObject(sql, double.class); } public double queryForDouble(String sql, JSObject js) throws DataAccessException { return queryForObject(sql, js, double.class); } public Date queryForDate(String sql) throws DataAccessException { return queryForObject(sql, Date.class); } public Date queryForDate(String sql, JSObject js) throws DataAccessException { return queryForObject(sql, js, Date.class); } public String queryForString(String sql) throws DataAccessException { return queryForObject(sql, String.class); } public String queryForString(String sql, JSObject js) throws DataAccessException { return queryForObject(sql, js, String.class); } public char queryForCharacter(String sql) throws DataAccessException { return queryForObject(sql, char.class); } public char queryForCharacter(String sql, JSObject js) throws DataAccessException { return queryForObject(sql, js, char.class); } public <T> T queryForObject(String sql, Class<T> clazz) throws DataAccessException { if (!sql.trim().substring(0, "select".length()).toLowerCase().equals("select")) { throw new DataAccessResourceFailureException(sql); } return this.jdbcTemplate.queryForObject(sql, clazz); } private <T> T queryForObject(String sql, JSObject js, Class<T> clazz) throws DataAccessException { if (js.isArray() || js.isStrictFunction() || js.isStrictFunction()) { throw new DataAccessResourceFailureException(sql); } Map<String, Object> paramMap = new HashMap<>(); for (String key : js.keySet()) { paramMap.put(key, js.getMember(key)); } if (!sql.trim().substring(0, "select".length()).toLowerCase().equals("select")) { throw new DataAccessResourceFailureException(sql); } return this.namedParameterJdbcTemplate.queryForObject(sql, paramMap, clazz); } private List<Map<String, Object>> queryForList(String sql) throws DataAccessException { if (!sql.trim().substring(0, "select".length()).toLowerCase().equals("select")) { throw new DataAccessResourceFailureException(sql); } return this.jdbcTemplate.queryForList(sql); } public List<Map<String, Object>> queryForList(String sql, JSObject js) throws DataAccessException { if (js.isArray() || js.isStrictFunction() || js.isStrictFunction()) { throw new DataAccessResourceFailureException(sql); } Map<String, Object> paramMap = new HashMap<>(); for (String key : js.keySet()) { paramMap.put(key, js.getMember(key)); } if (!sql.trim().substring(0, "select".length()).toLowerCase().equals("select")) { throw new DataAccessResourceFailureException(sql); } return this.namedParameterJdbcTemplate.queryForList(sql, paramMap); } public int update(String sql) throws DataAccessException { audit(sql); return this.jdbcTemplate.update(sql); } public int update(String sql, JSObject js) throws DataAccessException { if (js.isArray() || js.isStrictFunction() || js.isStrictFunction()) { throw new DataAccessResourceFailureException(sql); } Map<String, Object> paramMap = new HashMap<>(); for (String key : js.keySet()) { paramMap.put(key, js.getMember(key)); } audit(sql); return this.namedParameterJdbcTemplate.update(sql, paramMap); } private void audit(String sql) { String sqlTrimed = sql.trim(); if (sqlTrimed.substring(0, "drop".length()).toLowerCase().equals("drop")) { throw new DataAccessResourceFailureException(sql); } if (sqlTrimed.substring(0, "create".length()).toLowerCase().equals("create")) { throw new DataAccessResourceFailureException(sql); } if (sqlTrimed.substring(0, "alter".length()).toLowerCase().equals("alter")) { throw new DataAccessResourceFailureException(sql); } if (sqlTrimed.substring(0, "call".length()).toLowerCase().equals("call")) { throw new DataAccessResourceFailureException(sql); } if (sqlTrimed.substring(0, "kill".length()).toLowerCase().equals("kill")) { throw new DataAccessResourceFailureException(sql); } } }
package hudson.model; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import hudson.model.Queue.BlockedItem; import hudson.model.Queue.WaitingItem; import hudson.model.listeners.RunListener; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.SleepBuilder; public class JobQueueTest { @Rule public JenkinsRule j = new JenkinsRule(); private static volatile boolean fireCompletedFlag = false; private static volatile boolean fireFinalizeFlag = false; @Before public void setUp() { RunListener<Run> listener = new RunListener<Run>() { @Override public void onCompleted(Run r, TaskListener listener) { JobQueueTest.fireCompletedFlag = true; try { Thread.sleep(5000); } catch (InterruptedException e) { } } @Override public void onFinalized(Run r) { JobQueueTest.fireFinalizeFlag = true; try { Thread.sleep(2000); } catch (InterruptedException e) { } } }; RunListener.all().add(listener); } @Test public void buildPendingWhenBuildRunning() throws Exception { FreeStyleProject project = j.createFreeStyleProject("project"); project.getBuildersList().add(new SleepBuilder(2000)); //Kick the first Build project.scheduleBuild2(1); //Schedule another build project.scheduleBuild2(1); //The project should be in Queue when Run is in BUILDING stage assertTrue(project.isInQueue()); //Cancel the project from queue j.jenkins.getQueue().cancel(project.getQueueItem()); //Verify the project is removed from Queue assertTrue(j.jenkins.getQueue().isEmpty()); } @Test public void buildPendingWhenBuildInPostProduction() throws Exception { FreeStyleProject project = j.createFreeStyleProject("project"); project.getBuildersList().add(new SleepBuilder(1000)); //Kick the first Build project.scheduleBuild2(1); int count =0; //Now, Wait for run to be in POST_PRODUCTION stage while(!JobQueueTest.fireCompletedFlag && count<100) { Thread.sleep(100); count++; } if(JobQueueTest.fireCompletedFlag) { //Schedule the build for the project and this build should be in Queue since the state is POST_PRODUCTION project.scheduleBuild2(0); assertTrue(project.isInQueue()); //That means it's pending or it's waiting or blocked j.jenkins.getQueue().maintain(); while(j.jenkins.getQueue().getItem(project) instanceof WaitingItem) { System.out.println(j.jenkins.getQueue().getItem(project)); j.jenkins.getQueue().maintain(); Thread.sleep(10); } assertTrue(j.jenkins.getQueue().getItem(project) instanceof BlockedItem); //check is it is blocked } else { fail("The maximum attempts for checking if the job is in POST_PRODUCTION State have reached"); } count=0; while(!JobQueueTest.fireFinalizeFlag && count<100) { Thread.sleep(100); count++; } if(JobQueueTest.fireFinalizeFlag) { //Verify the build is removed from Queue since now it is in Completed state //it should be scheduled for run j.jenkins.getQueue().maintain(); assertFalse(j.jenkins.getQueue().getItem(project) instanceof BlockedItem); } else { fail("The maximum attempts for checking if the job is in COMPLETED State have reached"); } Thread.sleep(1000); //Sleep till job completes. } }
package VASSAL.build.module; import VASSAL.tools.ProblemDialog; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; import java.io.IOException; import java.net.URL; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.text.BadLocationException; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.command.Command; import VASSAL.command.CommandEncoder; import VASSAL.configure.BooleanConfigurer; import VASSAL.configure.ColorConfigurer; import VASSAL.configure.FontConfigurer; import VASSAL.i18n.Resources; import VASSAL.preferences.Prefs; import VASSAL.tools.ErrorDialog; import VASSAL.tools.KeyStrokeSource; import VASSAL.tools.ScrollPane; /** * The chat window component. Displays text messages and accepts input. Also * acts as a {@link CommandEncoder}, encoding/decoding commands that display * message in the text area */ public class Chatter extends JPanel implements CommandEncoder, Buildable { private static final long serialVersionUID = 1L; protected JTextPane conversationPane; protected HTMLDocument doc; protected HTMLEditorKit kit; protected StyleSheet style; protected JTextField input; protected JScrollPane scroll = new ScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); protected JScrollPane scroll2 = new ScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); protected static final String MY_CHAT_COLOR = "HTMLChatColor"; //$NON-NLS-1$ // Different tags to "restart" w/ new default scheme protected static final String OTHER_CHAT_COLOR = "HTMLotherChatColor"; //$NON-NLS-1$ protected static final String GAME_MSG1_COLOR = "HTMLgameMessage1Color"; //$NON-NLS-1$ protected static final String GAME_MSG2_COLOR = "HTMLgameMessage2Color"; //$NON-NLS-1$ protected static final String GAME_MSG3_COLOR = "HTMLgameMessage3Color"; //$NON-NLS-1$ protected static final String GAME_MSG4_COLOR = "HTMLgameMessage4Color"; //$NON-NLS-1$ protected static final String GAME_MSG5_COLOR = "HTMLgameMessage5Color"; //$NON-NLS-1$ protected static final String SYS_MSG_COLOR = "HTMLsystemMessageColor"; //$NON-NLS-1$ @Deprecated(since = "2020-08-06", forRemoval = true) protected static final String GAME_MSG_COLOR = "gameMessageColor"; protected Font myFont; protected Color gameMsg, gameMsg2, gameMsg3, gameMsg4, gameMsg5; protected Color systemMsg, myChat, otherChat; protected JTextArea conversation; // Backward compatibility for overridden classes. Needs something to suppress. public static String getAnonymousUserName() { return Resources.getString("Chat.anonymous"); //$NON-NLS-1$ } public Chatter() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); conversation = new JTextArea(); // For backward override compatibility only. //BR// Conversation is now a JTextPane w/ HTMLEditorKit to process HTML, which gives us HTML support "for free". conversationPane = new JTextPane(); conversationPane.setContentType("text/html"); doc = (HTMLDocument) conversationPane.getDocument(); kit = (HTMLEditorKit) conversationPane.getEditorKit(); style = kit.getStyleSheet(); myFont = new Font("SansSerif", Font.PLAIN, 12); // Will be overridden by the font from Chat preferences try { for (int i = 0; i < 15; ++i) { kit.insertHTML(doc, doc.getLength(), "<br>", 0, 0, null); } } catch (BadLocationException | IOException ble) { ErrorDialog.bug(ble); } conversationPane.setEditable(false); conversationPane.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { scroll.getVerticalScrollBar().setValue(scroll.getVerticalScrollBar().getMaximum()); } }); input = new JTextField(60); input.setFocusTraversalKeysEnabled(false); input.addActionListener(e -> { send(formatChat(e.getActionCommand())); input.setText(""); //$NON-NLS-1$ }); input.setMaximumSize(new Dimension(input.getMaximumSize().width, input.getPreferredSize().height)); FontMetrics fm = getFontMetrics(myFont); int fontHeight = fm.getHeight(); conversationPane.setPreferredSize(new Dimension(input.getMaximumSize().width, fontHeight * 10)); scroll.setViewportView(conversationPane); scroll.getVerticalScrollBar().setUnitIncrement(input.getPreferredSize().height); //Scroll this faster add(scroll); add(input); setPreferredSize(new Dimension(input.getMaximumSize().width, input.getPreferredSize().height + conversationPane.getPreferredSize().height)); } /** * Because our Chatters make themselves visible in their constructor, providing a way for an overriding class to * "turn this chatter off" is friendlier than What Went Before. * * @param vis - whether this chatter should be visible */ protected void setChatterVisible(boolean vis) { conversationPane.setVisible(vis); input.setVisible(vis); scroll.setVisible(vis); } private String formatChat(String text) { final String id = GlobalOptions.getInstance().getPlayerId(); return String.format("&lt;%s&gt; - %s", id.isEmpty() ? "(" + getAnonymousUserName() + ")" : id, text); //HTML-friendly angle brackets //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } public JTextField getInputField() { return input; } /** * Styles a chat message based on the player who sent it. Presently just distinguishes a chat message "from me" from a chat message "from anyone else". * * To make the player colors easy to override in a custom class * (my modules have logic to assign individual player colors -- beyond the scope of the present effort but a perhaps a fun future addition) * @param s - chat message from a player * @return - an entry in our CSS style sheet to use for this chat message */ protected String getChatStyle(String s) { return s.startsWith(formatChat("").trim()) ? "mychat" : "other"; } /** * A hook for inserting a console class that accepts commands * @param s - chat message * @param style - current style name (contains information that might be useful) * @param html_allowed - flag if html_processing is enabled for this message (allows console to apply security considerations) */ @SuppressWarnings("unused") public void consoleHook(String s, String style, boolean html_allowed) { } /** * Display a message in the text area. Ensures we execute in the EDT */ public void show(String s) { if (SwingUtilities.isEventDispatchThread()) { doShow(s); } else { SwingUtilities.invokeLater(() -> doShow(s)); } } /** * Display a message in the text area - use show() from outside the class - MUST run on EventDispatchThread */ private void doShow(String s) { String style; boolean html_allowed; // Choose an appropriate style to display this message in s = s.trim(); if (!s.isEmpty()) { if (s.startsWith("*")) { // Here we just extend the convention of looking at first characters, this time to the second character. // | = msg1 (w/ HTML parsing explicitly opted in) // ! = msg2 // ? = msg3 // ~ = msg4 // ` = msg5 // These characters can be pre-pended to Report messages to produce the color changes. The characters themselves are removed before display. // Reports can also include <b></b> tags for bold and <i></i> for italic. if (s.startsWith("* |") || s.startsWith("*|")) { style = "msg"; s = s.replaceFirst("\\|", ""); html_allowed = true; } else if (s.startsWith("* !") || s.startsWith("*!")) { style = "msg2"; s = s.replaceFirst("!", ""); html_allowed = true; } else if (s.startsWith("* ?") || s.startsWith("*?")) { style = "msg3"; s = s.replaceFirst("\\?", ""); html_allowed = true; } else if (s.startsWith("* ~") || s.startsWith("*~")) { style = "msg4"; s = s.replaceFirst("~", ""); html_allowed = true; } else if (s.startsWith("* `") || s.startsWith("*`")) { style = "msg5"; s = s.replaceFirst("`", ""); html_allowed = true; } else { style = "msg"; html_allowed = GlobalOptions.getInstance().chatterHTMLSupport(); // Generic report lines check compatibility flag (so old modules will not break on e.g. "<" in messages) } } else if (s.startsWith("-")) { style = "sys"; html_allowed = true; } else { style = getChatStyle(s); html_allowed = false; } } else { style = "msg"; html_allowed = false; } // Disable unwanted HTML tags in contexts where it shouldn't be allowed: // (1) Anything received from chat channel, for security reasons // (2) Legacy module "report" text when not explicitly opted in w/ first character or preference setting if (!html_allowed) { s = s.replaceAll("<", "&lt;") // This prevents any unwanted tag from functioning .replaceAll(">", "&gt;"); // This makes sure > doesn't break any of our legit <div> tags } // Systematically search through for html image tags. When we find one, try // to match it with an image from our DataArchive, and substitute the correct // fully qualified URL into the tag. URL url; String keystring = "<img src=\""; String file, tag, replace; int base; while (s.toLowerCase().contains(keystring)) { // Find next key (to-lower so we're not case sensitive) base = s.toLowerCase().indexOf(keystring); file = s.substring(base + keystring.length()).split("\"")[0]; // Pull the filename out from between the quotes tag = s.substring(base, base + keystring.length()) + file + "\""; // Reconstruct the part of the tag we want to remove, leaving all attributes after the filename alone, and properly matching the upper/lowercase of the keystring try { url = GameModule.getGameModule().getDataArchive().getURL("images/" + file); replace = "<img src=\"" + url.toString() + "\""; // Fully qualified URL if we are successful. The extra // space between IMG and SRC in the processed // version ensures we don't re-find THIS tag as we iterate } catch (IOException ex) { replace = "<img src=\"" + file + "\""; // Or just leave in except alter just enough that we won't find this tag again } if (s.contains(tag)) { s = s.replaceFirst(tag, replace); // Swap in our new URL-laden tag for the old one. } else { break; // If something went wrong in matching up the tag, don't loop forever } } // Now we have to fix up any legacy angle brackets around the word <observer> keystring = Resources.getString("PlayerRoster.observer"); replace = keystring.replace("<", "&lt;").replace(">", "&gt;"); if (!replace.equals(keystring)) { s = s.replace(keystring, replace); } // Insert a div of the correct style for our line of text. Module designer // still free to insert <span> tags and <img> tags and the like in Report // messages. try { kit.insertHTML(doc, doc.getLength(), "\n<div class=" + style + ">" + s + "</div>", 0, 0, null); } catch (BadLocationException | IOException ble) { ErrorDialog.bug(ble); } conversationPane.update(conversationPane.getGraphics()); // Force graphics to update consoleHook(s, style, html_allowed); } /** * Adds or updates a CSS stylesheet entry. Styles in the color, font type, and font size. * @param s Style name * @param f Font to use * @param c Color for text * @param font_weight Bold? Italic? * @param size Font size */ protected void addStyle(String s, Font f, Color c, String font_weight, int size) { if ((style == null) || (c == null)) return; style.addRule(s + " {color:" + String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue()) + "; font-family:" + f.getFamily() + "; font-size:" + (size > 0 ? size : f.getSize()) + "; " + ((!font_weight.isBlank()) ? "font-weight:" + font_weight + "; " : "") + "}"); } /** * Build ourselves a CSS stylesheet from our preference font/color settings. * @param f - Font to use for this stylesheet */ protected void makeStyleSheet(Font f) { if (style == null) { return; } if (f == null) { if (myFont == null) { f = new Font("SansSerif", Font.PLAIN, 12); myFont = f; } else { f = myFont; } } addStyle(".msg", f, gameMsg, "", 0); addStyle(".msg2", f, gameMsg2, "", 0); addStyle(".msg3", f, gameMsg3, "", 0); addStyle(".msg4", f, gameMsg4, "", 0); addStyle(".msg5", f, gameMsg5, "", 0); addStyle(".mychat", f, myChat, "bold", 0); addStyle(".other ", f, otherChat, "bold", 0); addStyle(".sys", f, systemMsg, "", 0); // A fun extension would be letting the module designer provide extra class styles. } /** * Set the Font used by the text area */ @Override public void setFont(Font f) { myFont = f; if (input != null) { if (input.getText().isEmpty()) { input.setText("XXX"); //$NON-NLS-1$ input.setFont(f); input.setText(""); //$NON-NLS-1$ } else { input.setFont(f); } } if (conversationPane != null) { conversationPane.setFont(f); } makeStyleSheet(f); // When font changes, rebuild our stylesheet } @Override public void build(org.w3c.dom.Element e) { } @Override public org.w3c.dom.Element getBuildElement(org.w3c.dom.Document doc) { return doc.createElement(getClass().getName()); } /** * Expects to be added to a GameModule. Adds itself to the controls window and * registers itself as a {@link CommandEncoder} */ @Override public void addTo(Buildable b) { GameModule mod = (GameModule) b; mod.setChatter(this); mod.addCommandEncoder(this); mod.addKeyStrokeSource(new KeyStrokeSource(this, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)); final FontConfigurer chatFont = new FontConfigurer("ChatFont", Resources.getString("Chatter.chat_font_preference")); chatFont.addPropertyChangeListener(evt -> setFont((Font) evt.getNewValue())); mod.getPlayerWindow().addChatter(this); chatFont.fireUpdate(); mod.getPrefs().addOption(Resources.getString("Chatter.chat_window"), chatFont); //$NON-NLS-1$ // Bug 10179 - Do not re-read Chat colors each time the Chat Window is // repainted. final Prefs globalPrefs = Prefs.getGlobalPrefs(); // game message color final ColorConfigurer gameMsgColor = new ColorConfigurer(GAME_MSG1_COLOR, Resources.getString("Chatter.game_messages_preference"), Color.black); gameMsgColor.addPropertyChangeListener(e -> { gameMsg = (Color) e.getNewValue(); makeStyleSheet(null); }); globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsgColor); gameMsg = (Color) globalPrefs.getValue(GAME_MSG1_COLOR); // game message color #2 (messages starting with "!") final ColorConfigurer gameMsg2Color = new ColorConfigurer(GAME_MSG2_COLOR, Resources.getString("Chatter.game_messages_preference_2"), new Color(0, 153, 51)); gameMsg2Color.addPropertyChangeListener(e -> { gameMsg2 = (Color) e.getNewValue(); makeStyleSheet(null); }); globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg2Color); gameMsg2 = (Color) globalPrefs.getValue(GAME_MSG2_COLOR); // game message color #3 (messages starting with "?") final ColorConfigurer gameMsg3Color = new ColorConfigurer(GAME_MSG3_COLOR, Resources.getString("Chatter.game_messages_preference_3"), new Color(255, 102, 102)); gameMsg3Color.addPropertyChangeListener(e -> { gameMsg3 = (Color) e.getNewValue(); makeStyleSheet(null); }); globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg3Color); gameMsg3 = (Color) globalPrefs.getValue(GAME_MSG3_COLOR); // game message color #4 (messages starting with "~") final ColorConfigurer gameMsg4Color = new ColorConfigurer(GAME_MSG4_COLOR, Resources.getString("Chatter.game_messages_preference_4"), new Color(255, 0, 0)); gameMsg4Color.addPropertyChangeListener(e -> { gameMsg4 = (Color) e.getNewValue(); makeStyleSheet(null); }); globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg4Color); gameMsg4 = (Color) globalPrefs.getValue(GAME_MSG4_COLOR); // game message color #5 (messages starting with "`") final ColorConfigurer gameMsg5Color = new ColorConfigurer(GAME_MSG5_COLOR, Resources.getString("Chatter.game_messages_preference_5"), new Color(153, 0, 153)); gameMsg5Color.addPropertyChangeListener(e -> { gameMsg5 = (Color) e.getNewValue(); makeStyleSheet(null); }); globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg5Color); gameMsg5 = (Color) globalPrefs.getValue(GAME_MSG5_COLOR); final ColorConfigurer systemMsgColor = new ColorConfigurer(SYS_MSG_COLOR, Resources.getString("Chatter.system_message_preference"), new Color(160, 160, 160)); systemMsgColor.addPropertyChangeListener(e -> { systemMsg = (Color) e.getNewValue(); makeStyleSheet(null); }); globalPrefs.addOption(Resources.getString("Chatter.chat_window"), systemMsgColor); systemMsg = (Color) globalPrefs.getValue(SYS_MSG_COLOR); final ColorConfigurer myChatColor = new ColorConfigurer( MY_CHAT_COLOR, Resources.getString("Chatter.my_text_preference"), new Color(9, 32, 229)); myChatColor.addPropertyChangeListener(e -> { myChat = (Color) e.getNewValue(); makeStyleSheet(null); }); globalPrefs.addOption(Resources.getString("Chatter.chat_window"), myChatColor); myChat = (Color) globalPrefs.getValue(MY_CHAT_COLOR); final ColorConfigurer otherChatColor = new ColorConfigurer(OTHER_CHAT_COLOR, Resources.getString("Chatter.other_text_preference"), new Color (0, 153, 255)); otherChatColor.addPropertyChangeListener(e -> { otherChat = (Color) e.getNewValue(); makeStyleSheet(null); }); globalPrefs.addOption(Resources.getString("Chatter.chat_window"), otherChatColor); otherChat = (Color) globalPrefs.getValue(OTHER_CHAT_COLOR); // Put up the HTML Enable/Disable checkbox if we're supposed to have it. if (GlobalOptions.PROMPT.equals(GlobalOptions.getInstance().chatterHTMLSetting())) { BooleanConfigurer config2 = new BooleanConfigurer(GlobalOptions.CHATTER_HTML_SUPPORT, Resources.getString("GlobalOptions.chatter_html_support")); //$NON-NLS-1$ globalPrefs.addOption(Resources.getString("Chatter.chat_window"), config2); } makeStyleSheet(myFont); } @Override public void add(Buildable b) { } @Override public Command decode(String s) { if (!s.startsWith(DisplayText.PREFIX)) { return null; } return new DisplayText(this, s.substring(DisplayText.PREFIX.length())); } @Override public String encode(Command c) { if (!(c instanceof DisplayText)) { return null; } return DisplayText.PREFIX + ((DisplayText) c).getMessage(); } /** * Displays the message, Also logs and sends to the server a {@link Command} * that displays this message. */ public void send(String msg) { if (msg != null && !msg.isEmpty()) { show(msg); GameModule.getGameModule().sendAndLog(new DisplayText(this, msg)); } } /** * Warning message method -- same as send, but accepts messages from static methods. For reporting soft-fail problems in modules. */ public static void warning(String msg) { Chatter chatter = GameModule.getGameModule().getChatter(); chatter.send(msg); } /** * Classes other than the Chatter itself may forward KeyEvents to the Chatter by * using this method */ public void keyCommand(KeyStroke e) { if ((e.getKeyCode() == 0 || e.getKeyCode() == KeyEvent.CHAR_UNDEFINED) && !Character.isISOControl(e.getKeyChar())) { if (!e.toString().contains("alt")) { //$NON-NLS-1$ input.setText(input.getText() + e.getKeyChar()); } } else if (e.isOnKeyRelease()) { switch (e.getKeyCode()) { case KeyEvent.VK_ENTER: if (!input.getText().isEmpty()) send(formatChat(input.getText())); input.setText(""); //$NON-NLS-1$ break; case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: String s = input.getText(); if (!s.isEmpty()) input.setText(s.substring(0, s.length() - 1)); break; } } } /** * This is a {@link Command} object that, when executed, displays * a text message in the Chatter's text area */ public static class DisplayText extends Command { public static final String PREFIX = "CHAT"; //$NON-NLS-1$ private String msg; private final Chatter c; public DisplayText(Chatter c, String s) { this.c = c; msg = s; if (msg.startsWith("<>")) { msg = "&lt;(" + Chatter.getAnonymousUserName() + ")&gt;" + s.substring(2); // HTML-friendly // angle brackets } else { msg = s; } } @Override public void executeCommand() { c.show(msg); } @Override public Command myUndoCommand() { return new DisplayText(c, Resources.getString("Chatter.undo_message", msg)); //$NON-NLS-1$ } public String getMessage() { return msg; } @Override public String getDetails() { return msg; } } public static void main(String[] args) { Chatter chat = new Chatter(); JFrame f = new JFrame(); f.add(chat); f.pack(); f.setVisible(true); } /** @deprecated No Replacement */ @Deprecated(since = "2020-08-06", forRemoval = true) public void setHandle(@SuppressWarnings("unused") String s) { ProblemDialog.showDeprecated("2020-08-06"); } /** @deprecated use {@link GlobalOptions#getPlayerId()} */ @Deprecated(since = "2020-08-06", forRemoval = true) public String getHandle() { ProblemDialog.showDeprecated("2020-08-06"); return GlobalOptions.getInstance().getPlayerId(); } }
package com.ecyrd.jspwiki; import junit.framework.*; import java.io.*; import java.util.*; public class TranslatorReaderTest extends TestCase { Properties props = new Properties(); public TranslatorReaderTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( getClass().getClassLoader().getResourceAsStream("/jspwiki.properties") ); } public void tearDown() { } private String translate( String src ) throws IOException { Reader r = new TranslatorReader( new TestEngine( props ), new BufferedReader( new StringReader(src)) ); StringWriter out = new StringWriter(); int c; while( ( c=r.read()) != -1 ) { out.write( c ); } return out.toString(); } public void testHyperlinks2() throws Exception { String src = "This should be a [hyperlink]"; assertEquals( "This should be a <A HREF=\"Wiki.jsp?page=Hyperlink\">hyperlink</A>\n", translate(src) ); } public void testHyperlinks3() throws Exception { String src = "This should be a [hyperlink too]"; assertEquals( "This should be a <A HREF=\"Wiki.jsp?page=HyperlinkToo\">hyperlink too</A>\n", translate(src) ); } public void testHyperlinks4() throws Exception { String src = "This should be a [HyperLink]"; assertEquals( "This should be a <A HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>\n", translate(src) ); } public void testHyperlinks5() throws Exception { String src = "This should be a [here|HyperLink]"; assertEquals( "This should be a <A HREF=\"Wiki.jsp?page=HyperLink\">here</A>\n", translate(src) ); } public void testHyperlinksExt() throws Exception { String src = "This should be a [http: assertEquals( "This should be a <A HREF=\"http: translate(src) ); } public void testHyperlinksExt2() throws Exception { String src = "This should be a [link|http: assertEquals( "This should be a <A HREF=\"http: translate(src) ); } public void testParagraph() throws Exception { String src = "1\n\n2\n\n3"; assertEquals( "1\n<P>\n2\n<P>\n3\n", translate(src) ); } public void testLinebreak() throws Exception { String src = "1\\\\2"; assertEquals( "1<BR>2\n", translate(src) ); } public void testTT() throws Exception { String src = "1{{2345}}6"; assertEquals( "1<TT>2345</TT>6\n", translate(src) ); } public void testPre() throws Exception { String src = "1{{{2345}}}6"; assertEquals( "1<PRE>2345</PRE>6\n", translate(src) ); } public void testList1() throws Exception { String src = "A list:\n* One\n* Two\n* Three\n"; assertEquals( "A list:\n<UL>\n<LI> One\n<LI> Two\n<LI> Three\n</UL>\n", translate(src) ); } public void testHTML() throws Exception { String src = "<B>Test</B>"; assertEquals( "&lt;B&gt;Test&lt;/B&gt;\n", translate(src) ); } public void testHTML2() throws Exception { String src = "<P>"; assertEquals( "&lt;P&gt;\n", translate(src) ); } public static Test suite() { return new TestSuite( TranslatorReaderTest.class ); } }
package com.ecyrd.jspwiki; import junit.framework.*; import java.io.*; import java.util.*; import javax.servlet.*; public class TranslatorReaderTest extends TestCase { Properties props = new Properties(); WikiEngine testEngine1; WikiEngine testEngine2; public TranslatorReaderTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( getClass().getClassLoader().getResourceAsStream("/jspwiki.properties") ); testEngine1 = new TestEngine( props ); props.setProperty( "jspwiki.translatorReader.matchEnglishPlurals", "true" ); testEngine2 = new TestEngine2( props ); } public void tearDown() { } private String translate( String src ) throws IOException, NoRequiredPropertyException, ServletException { WikiContext context = new WikiContext( testEngine1, "testpage" ); Reader r = new TranslatorReader( context, new BufferedReader( new StringReader(src)) ); StringWriter out = new StringWriter(); int c; while( ( c=r.read()) != -1 ) { out.write( c ); } return out.toString(); } private String translate2( String src ) throws IOException, NoRequiredPropertyException, ServletException { WikiContext context = new WikiContext( testEngine2, "testpage" ); Reader r = new TranslatorReader( context, new BufferedReader( new StringReader(src)) ); StringWriter out = new StringWriter(); int c; while( ( c=r.read()) != -1 ) { out.write( c ); } return out.toString(); } public void testHyperlinks2() throws Exception { String src = "This should be a [hyperlink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Hyperlink\">hyperlink</A>\n", translate(src) ); } public void testHyperlinks3() throws Exception { String src = "This should be a [hyperlink too]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperlinkToo\">hyperlink too</A>\n", translate(src) ); } public void testHyperlinks4() throws Exception { String src = "This should be a [HyperLink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>\n", translate(src) ); } public void testHyperlinks5() throws Exception { String src = "This should be a [here|HyperLink]"; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">here</A>\n", translate(src) ); } /** When using CC links, this seems to crash 1.9.2. */ public void testHyperLinks6() throws Exception { String src = "[DiscussionAboutWiki] [WikiMarkupDevelopment]."; assertEquals( "<A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=DiscussionAboutWiki\">DiscussionAboutWiki</A> <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=WikiMarkupDevelopment\">WikiMarkupDevelopment</A>.\n", translate(src) ); } public void testHyperlinksCC() throws Exception { String src = "This should be a HyperLink."; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>.\n", translate(src) ); } public void testHyperlinksCCNonExistant() throws Exception { String src = "This should be a HyperLink."; assertEquals( "This should be a <U>HyperLink</U><A HREF=\"Edit.jsp?page=HyperLink\">?</A>.\n", translate2(src) ); } /** * Check if the CC hyperlink translator gets confused with * unorthodox bracketed links. */ public void testHyperlinksCC2() throws Exception { String src = "This should be a [ HyperLink ]."; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\"> HyperLink </A>.\n", translate(src) ); } public void testHyperlinksCC3() throws Exception { String src = "This should be a nonHyperLink."; assertEquals( "This should be a nonHyperLink.\n", translate(src) ); } /** Two links on same line. */ public void testHyperlinksCC4() throws Exception { String src = "This should be a HyperLink, and ThisToo."; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>, and <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ThisToo\">ThisToo</A>.\n", translate(src) ); } /** Two mixed links on same line. */ public void testHyperlinksCC5() throws Exception { String src = "This should be a [HyperLink], and ThisToo."; assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>, and <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ThisToo\">ThisToo</A>.\n", translate(src) ); } /** Closing tags only. */ public void testHyperlinksCC6() throws Exception { String src = "] This ] should be a HyperLink], and ThisToo."; assertEquals( "] This ] should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>], and <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ThisToo\">ThisToo</A>.\n", translate(src) ); } /** First and last words on line. */ public void testHyperlinksCCFirstAndLast() throws Exception { String src = "HyperLink, and ThisToo"; assertEquals( "<A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLink</A>, and <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ThisToo\">ThisToo</A>\n", translate(src) ); } /** Hyperlinks inside URIs. */ public void testHyperlinksCCURLs() throws Exception { String src = "http: assertEquals( "http: translate(src) ); } public void testHyperlinksExt() throws Exception { String src = "This should be a [http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinksExt2() throws Exception { String src = "This should be a [link|http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinksPluralMatch() throws Exception { String src = "This should be a [HyperLinks]"; testEngine2.saveText( "HyperLink", "foobar" ); try { assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLink\">HyperLinks</A>\n", translate2(src) ); } finally { ((TestEngine2)testEngine2).deletePage( "HyperLink" ); } } public void testHyperlinksPluralMatch2() throws Exception { String src = "This should be a [HyperLinks]"; try { assertEquals( "This should be a <U>HyperLinks</U><A HREF=\"Edit.jsp?page=HyperLinks\">?</A>\n", translate2(src) ); } finally { // FIXME } } public void testHyperlinksPluralMatch3() throws Exception { String src = "This should be a [HyperLink]"; testEngine2.saveText( "HyperLinks", "foobar" ); try { assertEquals( "This should be a <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=HyperLinks\">HyperLink</A>\n", translate2(src) ); } finally { ((TestEngine2)testEngine2).deletePage( "HyperLinks" ); } } public void testHyperlinkJS1() throws Exception { String src = "This should be a [link|http: assertEquals( "This should be a <A CLASS=\"external\" HREF=\"http: translate(src) ); } public void testHyperlinksInterWiki1() throws Exception { String src = "This should be a [link|JSPWiki:HyperLink]"; assertEquals( "This should be a <A CLASS=\"interwiki\" HREF=\"http: translate(src) ); } public void testExtraPagename1() throws Exception { String src = "Link [test_page]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Test_page\">test_page</A>\n", translate(src) ); } public void testExtraPagename2() throws Exception { String src = "Link [test.page]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=Test.page\">test.page</A>\n", translate(src) ); } public void testExtraPagename3() throws Exception { String src = "Link [.testpage_]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=.testpage_\">.testpage_</A>\n", translate(src) ); } public void testInlineImages() throws Exception { String src = "Link [test|http: assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http: translate2(src) ); } public void testInlineImages2() throws Exception { String src = "Link [test|http: assertEquals("Link <A CLASS=\"external\" HREF=\"http: translate2(src) ); } public void testInlineImages3() throws Exception { String src = "Link [test|http://images.com/testi]"; assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http://images.com/testi\" ALT=\"test\">\n", translate2(src) ); } public void testInlineImages4() throws Exception { String src = "Link [test|http://foobar.jpg]"; assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http://foobar.jpg\" ALT=\"test\">\n", translate2(src) ); } // No link text should be just embedded link. public void testInlineImagesLink2() throws Exception { String src = "Link [http://foobar.jpg]"; assertEquals("Link <IMG CLASS=\"inline\" SRC=\"http: translate2(src) ); } public void testInlineImagesLink() throws Exception { String src = "Link [http: assertEquals("Link <A HREF=\"http: translate2(src) ); } public void testInlineImagesLink3() throws Exception { String src = "Link [SandBox|http://foobar.jpg]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=SandBox\"><IMG CLASS=\"inline\" SRC=\"http://foobar.jpg\" ALT=\"SandBox\"></A>\n", translate(src) ); } public void testScandicPagename1() throws Exception { String src = "Link [Test]"; assertEquals("Link <A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=%C5%E4Test\">Test</A>\n", translate(src)); } public void testParagraph() throws Exception { String src = "1\n\n2\n\n3"; assertEquals( "1\n<P>\n2\n<P>\n3\n", translate(src) ); } public void testLinebreak() throws Exception { String src = "1\\\\2"; assertEquals( "1<BR>2\n", translate(src) ); } public void testTT() throws Exception { String src = "1{{2345}}6"; assertEquals( "1<TT>2345</TT>6\n", translate(src) ); } public void testTTAcrossLines() throws Exception { String src = "1{{\n2345\n}}6"; assertEquals( "1<TT>\n2345\n</TT>6\n", translate(src) ); } public void testTTLinks() throws Exception { String src = "1{{\n2345\n[a link]\n}}6"; assertEquals( "1<TT>\n2345\n<A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ALink\">a link</A>\n</TT>6\n", translate(src) ); } public void testPre() throws Exception { String src = "1{{{2345}}}6"; assertEquals( "1<PRE>2345</PRE>6\n", translate(src) ); } public void testPre2() throws Exception { String src = "1 {{{ {{{ 2345 }}} }}} 6"; assertEquals( "1 <PRE> {{{ 2345 </PRE> }}} 6\n", translate(src) ); } public void testList1() throws Exception { String src = "A list:\n* One\n* Two\n* Three\n"; assertEquals( "A list:\n<UL>\n<LI> One\n<LI> Two\n<LI> Three\n</UL>\n", translate(src) ); } /** Plain multi line testing: <pre> * One continuing * Two * Three </pre> */ public void testMultilineList1() throws Exception { String src = "A list:\n* One\n continuing.\n* Two\n* Three\n"; assertEquals( "A list:\n<UL>\n<LI> One\n continuing.\n<LI> Two\n<LI> Three\n</UL>\n", translate(src) ); } public void testMultilineList2() throws Exception { String src = "A list:\n* One\n continuing.\n* Two\n* Three\nShould be normal."; assertEquals( "A list:\n<UL>\n<LI> One\n continuing.\n<LI> Two\n<LI> Three\n</UL>\nShould be normal.\n", translate(src) ); } public void testHTML() throws Exception { String src = "<B>Test</B>"; assertEquals( "&lt;B&gt;Test&lt;/B&gt;\n", translate(src) ); } public void testHTML2() throws Exception { String src = "<P>"; assertEquals( "&lt;P&gt;\n", translate(src) ); } public void testQuotes() throws Exception { String src = "\"Test\"\""; assertEquals( "&quot;Test&quot;&quot;\n", translate(src) ); } public void testItalicAcrossLinebreak() throws Exception { String src="''This is a\ntest.''"; assertEquals( "<I>This is a\ntest.</I>\n", translate(src) ); } public void testBoldAcrossLinebreak() throws Exception { String src="__This is a\ntest.__"; assertEquals( "<B>This is a\ntest.</B>\n", translate(src) ); } public void testBoldItalic() throws Exception { String src="__This ''is'' a test.__"; assertEquals( "<B>This <I>is</I> a test.</B>\n", translate(src) ); } public void testFootnote1() throws Exception { String src="Footnote[1]"; assertEquals( "Footnote<A CLASS=\"footnoteref\" HREF=\"#ref-testpage-1\">[1]</A>\n", translate(src) ); } public void testFootnote2() throws Exception { String src="[#2356] Footnote."; assertEquals( "<A CLASS=\"footnote\" NAME=\"ref-testpage-2356\">[#2356]</A> Footnote.\n", translate(src) ); } /** Check an reported error condition where empty list items could cause crashes */ public void testEmptySecondLevelList() throws Exception { String src="A\n\n**\n\nB"; assertEquals( "A\n<P>\n<UL>\n<UL>\n<LI>\n</UL>\n</UL>\n<P>\nB\n", translate(src) ); } public void testEmptySecondLevelList2() throws Exception { String src="A\n\n##\n\nB"; assertEquals( "A\n<P>\n<OL>\n<OL>\n<LI>\n</OL>\n</OL>\n<P>\nB\n", translate(src) ); } /** * <pre> * *Item A * ##Numbered 1 * ##Numbered 2 * *Item B * </pre> * * would come out as: *<ul> * <li>Item A * </ul> * <ol> * <ol> * <li>Numbered 1 * <li>Numbered 2 * <ul> * <li></ol> * </ol> * Item B * </ul> * * (by Mahlen Morris). */ // FIXME: does not run - code base is too screwed for that. /* public void testMixedList() throws Exception { String src="*Item A\n##Numbered 1\n##Numbered 2\n*Item B\n"; String result = translate(src); // Remove newlines for easier parsing. result = TextUtil.replaceString( result, "\n", "" ); assertEquals( "<UL><LI>Item A"+ "<OL><OL><LI>Numbered 1"+ "<LI>Numbered 2"+ "</OL></OL>"+ "<LI>Item B"+ "</UL>", result ); } */ /** * Like testMixedList() but the list types have been reversed. */ // FIXME: does not run - code base is too screwed for that. /* public void testMixedList2() throws Exception { String src="#Item A\n**Numbered 1\n**Numbered 2\n#Item B\n"; String result = translate(src); // Remove newlines for easier parsing. result = TextUtil.replaceString( result, "\n", "" ); assertEquals( "<OL><LI>Item A"+ "<UL><UL><LI>Numbered 1"+ "<LI>Numbered 2"+ "</UL></UL>"+ "<LI>Item B"+ "</OL>", result ); } */ public void testPluginInsert() throws Exception { String src="[{INSERT com.ecyrd.jspwiki.plugin.SamplePlugin WHERE text=test}]"; assertEquals( "test\n", translate(src) ); } public void testPluginInsertJS() throws Exception { String src="Today: [{INSERT JavaScriptPlugin}] ''day''."; assertEquals( "Today: <script language=\"JavaScript\"><!--\nfoo='';\n--></script>\n <I>day</I>.\n", translate(src) ); } public void testShortPluginInsert() throws Exception { String src="[{INSERT SamplePlugin WHERE text=test}]"; assertEquals( "test\n", translate(src) ); } public void testTable1() throws Exception { String src="|| heading || heading2 \n| Cell 1 | Cell 2 \n| Cell 3 | Cell 4\n\n"; assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+ "<TR><TH> heading <TH> heading2 </TR>\n"+ "<TR><TD> Cell 1 <TD> Cell 2 </TR>\n"+ "<TR><TD> Cell 3 <TD> Cell 4</TR>\n"+ "</TABLE><P>\n", translate(src) ); } public void testTable2() throws Exception { String src="||heading||heading2\n|Cell 1| Cell 2\n| Cell 3 |Cell 4\n\n"; assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+ "<TR><TH>heading<TH>heading2</TR>\n"+ "<TR><TD>Cell 1<TD> Cell 2</TR>\n"+ "<TR><TD> Cell 3 <TD>Cell 4</TR>\n"+ "</TABLE><P>\n", translate(src) ); } public void testTable3() throws Exception { String src="|Cell 1| Cell 2\n| Cell 3 |Cell 4\n\n"; assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+ "<TR><TD>Cell 1<TD> Cell 2</TR>\n"+ "<TR><TD> Cell 3 <TD>Cell 4</TR>\n"+ "</TABLE><P>\n", translate(src) ); } public void testTableLink() throws Exception { String src="|Cell 1| Cell 2\n|[Cell 3|ReallyALink]|Cell 4\n\n"; assertEquals( "<TABLE CLASS=\"wikitable\" BORDER=\"1\">\n"+ "<TR><TD>Cell 1<TD> Cell 2</TR>\n"+ "<TR><TD><A CLASS=\"wikipage\" HREF=\"Wiki.jsp?page=ReallyALink\">Cell 3</A><TD>Cell 4</TR>\n"+ "</TABLE><P>\n", translate(src) ); } public void testDescription() throws Exception { String src=";:Foo"; assertEquals( "<DL>\n<DT></DT><DD>Foo</DD>\n</DL>\n", translate(src) ); } public void testDescription2() throws Exception { String src=";Bar:Foo"; assertEquals( "<DL>\n<DT>Bar</DT><DD>Foo</DD>\n</DL>\n", translate(src) ); } public void testDescription3() throws Exception { String src=";:"; assertEquals( "<DL>\n<DT><STRONG></STRONG></DT><DD></DD>\n</DL>\n", translate(src) ); } public static Test suite() { return new TestSuite( TranslatorReaderTest.class ); } }
package net.katsuster.strview.media.ts; import net.katsuster.strview.io.*; import net.katsuster.strview.media.*; /** * @author katsuhiro */ public class TSPacketList extends AbstractLargeList<TSPacket> { public LargeBitList buf; public TSPacketList() { super(LENGTH_UNKNOWN); } public TSPacketList(LargeBitList l) { super(LENGTH_UNKNOWN); buf = l; } @Override public void count() { setLength(buf.length() / 188 / 8); } @Override protected TSPacket getInner(long index) { TSPacket p = new TSPacket(); FromBitListConverter c = new FromBitListConverter(buf); c.doInit(); c.position(index * 188 * 8); p.setNumber(index); p.setLevel(0); p.read(c); c.doFinal(); return p; } @Override protected void setInner(long index, TSPacket data) { } }
package me.exphc.Chestpack; import java.util.Collections; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.UUID; import java.util.Iterator; import java.util.logging.Logger; import java.util.concurrent.ConcurrentHashMap; import java.util.Formatter; import java.lang.Byte; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.io.*; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.*; import org.bukkit.event.*; import org.bukkit.event.block.*; import org.bukkit.event.player.*; import org.bukkit.event.entity.*; import org.bukkit.event.inventory.*; import org.bukkit.Material.*; import org.bukkit.material.*; import org.bukkit.block.*; import org.bukkit.entity.*; import org.bukkit.command.*; import org.bukkit.inventory.*; import org.bukkit.configuration.*; import org.bukkit.configuration.file.*; import org.bukkit.scheduler.*; import org.bukkit.enchantments.*; import org.bukkit.inventory.*; import org.bukkit.*; import net.minecraft.server.CraftingManager; class ChestpackListener implements Listener { Chestpack plugin; public ChestpackListener(Chestpack plugin) { this.plugin = plugin; Bukkit.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled=true) public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); //player.getInventory().setChestplate(new ItemStack(Material.CHEST, 1)); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled=true) public void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); ItemStack item = event.getItem(); if (item == null || !isPack(item)) { return; } Action action = event.getAction(); if (action == Action.LEFT_CLICK_AIR || action == action.LEFT_CLICK_BLOCK) { // left-click to open openPack(player, item); } } private void openPack(Player player, ItemStack item) { Inventory inventory = Bukkit.createInventory(player, 54, "Backpack"); plugin.log.info("open"); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled=true) public void onInventoryClose(InventoryCloseEvent event) { for (HumanEntity viewer: event.getViewers()) { if (!(viewer instanceof Player)) { continue; } // crafted a backpack? wear it! checkEquipPack((Player)viewer); } } // TODO: why broken? @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled=true) public void onPlayerPickupItem(PlayerPickupItemEvent event) { // picked up a backpack item? (TODO: prevent?) checkEquipPack(event.getPlayer()); } /** Wear a player's pack in their chestplate slot, if they have one in their inventory. */ private void checkEquipPack(Player player) { ItemStack[] inventory = player.getInventory().getContents(); for (int i = 0; i < inventory.length; i += 1) { ItemStack item = inventory[i]; if (item == null || item.equals(player.getItemInHand())) { // You're allowed to hold backpacks in your hand (or on your back, but nowhere else) continue; } if (isPack(item)) { // existing armor falls off ItemStack drop = player.getInventory().getChestplate(); if (drop != null) { player.getWorld().dropItemNaturally(player.getLocation(), drop); } // equip pack player.getInventory().setChestplate(item); player.getInventory().clear(i); player.sendMessage("Backpack equipped"); } } } final Enchantment FORTUNE = Enchantment.LOOT_BONUS_BLOCKS; /** Get whether the item is a chestpack. */ private boolean isPack(ItemStack item) { // Represented by a chest with a special enchantment return item != null && item.getType() == Material.CHEST && item.containsEnchantment(FORTUNE); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled=true) public void onPlayerDropItem(PlayerDropItemEvent event) { Item itemEntity = event.getItemDrop(); ItemStack itemStack = itemEntity.getItemStack(); if (!isPack(itemStack)) { return; } Player player = event.getPlayer(); itemEntity.remove(); player.sendMessage("Backpack dropped"); // Find out where to drop backpack as a block Block block = player.getTargetBlock(null, 5).getRelative(BlockFace.UP); // TODO: get face of targetted block // TODO: only place in air if (block == null) { // TODO: set in a more reasonable location block = itemEntity.getLocation().getBlock(); } block.setTypeIdAndData(Material.CHEST.getId(), (byte)0, true); // TODO: identify as pack // TODO: populate contents } } public class Chestpack extends JavaPlugin { Logger log = Logger.getLogger("Minecraft"); public void onEnable() { loadRecipe(); new ChestpackListener(this); } public void onDisable() { Bukkit.resetRecipes(); // TODO: can we reset only ours? } final Enchantment FORTUNE = Enchantment.LOOT_BONUS_BLOCKS; private void loadRecipe() { ItemStack emptyPack = new ItemStack(Material.CHEST, 1); emptyPack.addUnsafeEnchantment(FORTUNE, 1); // as a workaround, do shapeless instead ShapelessRecipe recipe = new ShapelessRecipe(emptyPack); recipe.addIngredient(8, Material.LEATHER); recipe.addIngredient(1, Material.CHEST); Bukkit.addRecipe(recipe); } }
package org.geotools.geopkg; import static java.lang.String.format; import static org.geotools.sql.SqlUtil.prepare; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.dbcp.DelegatingConnection; import org.apache.commons.io.IOUtils; import org.geotools.coverage.grid.GridCoverage2D; import org.geotools.coverage.grid.io.AbstractGridFormat; import org.geotools.data.DataStore; import org.geotools.data.DefaultTransaction; import org.geotools.data.FeatureWriter; import org.geotools.data.Query; import org.geotools.data.Transaction; import org.geotools.data.jdbc.datasource.ManageableDataSource; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.simple.SimpleFeatureReader; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.data.simple.SimpleFeatureWriter; import org.geotools.factory.Hints; import org.geotools.filter.identity.FeatureIdImpl; import org.geotools.geometry.GeneralEnvelope; import org.geotools.geometry.jts.Geometries; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.geopkg.geom.GeoPkgGeomReader; import org.geotools.geopkg.geom.GeoPkgGeomWriter; import org.geotools.geopkg.geom.GeometryFunction; import org.geotools.jdbc.JDBCDataStore; import org.geotools.jdbc.JDBCFeatureStore; import org.geotools.jdbc.PrimaryKey; import org.geotools.referencing.CRS; import org.geotools.sql.SqlUtil; import org.geotools.util.logging.Logging; import org.opengis.coverage.grid.GridCoverageReader; import org.opengis.coverage.grid.GridCoverageWriter; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.GeometryDescriptor; import org.opengis.feature.type.PropertyDescriptor; import org.opengis.filter.Filter; import org.opengis.filter.identity.Identifier; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.sqlite.Function; import com.vividsolutions.jts.geom.Geometry; /** * Provides access to a GeoPackage database. * * @author Justin Deoliveira, OpenGeo * @author Niels Charlier */ public class GeoPackage { static final Logger LOGGER = Logging.getLogger("org.geotools.geopkg"); public static final String GEOPACKAGE_CONTENTS = "gpkg_contents"; public static final String GEOMETRY_COLUMNS = "gpkg_geometry_columns"; public static final String SPATIAL_REF_SYS = "gpkg_spatial_ref_sys"; public static final String RASTER_COLUMNS = "gpkg_data_columns"; public static final String TILE_MATRIX_METADATA = "gpkg_tile_matrix"; public static final String METADATA = "gpkg_metadata"; public static final String METADATA_REFERENCE = "gpkg_metadata_reference"; public static final String TILE_MATRIX_SET = "gpkg_tile_matrix_set"; public static final String DATA_COLUMN_CONSTRAINTS = "gpkg_data_column_constraints"; public static final String EXTENSIONS = "gpkg_extensions"; public static final String SPATIAL_INDEX = "gpkg_spatial_index"; public static enum DataType { Feature("features"), Raster("rasters"), Tile("tiles"), FeatureWithRaster( "featuresWithRasters"); String value; DataType(String value) { this.value = value; } public String value() { return value; } } static final String DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; /** * database file */ File file; /** * connection pool */ final DataSource connPool; /** * datastore for vector access, lazily created */ volatile JDBCDataStore dataStore; protected GeoPkgGeomWriter.Configuration writerConfig = new GeoPkgGeomWriter.Configuration(); public GeoPkgGeomWriter.Configuration getWriterConfiguration() { return writerConfig; } /** * Creates a new empty GeoPackage, generating a new file. */ public GeoPackage() throws IOException { this(File.createTempFile("geopkg", "db")); } /** * Creates a GeoPackage from an existing file. * <p> * This constructor assumes no credentials are required to connect to the database. * </p> */ public GeoPackage(File file) throws IOException { this(file, null, null); } /** * Creates a GeoPackage from an existing file specifying database credentials. */ public GeoPackage(File file, String user, String passwd) throws IOException { this.file = file; Map params = new HashMap(); if (user != null) { params.put(GeoPkgDataStoreFactory.USER.key, user); } if (passwd != null) { params.put(GeoPkgDataStoreFactory.PASSWD.key, passwd); } params.put(GeoPkgDataStoreFactory.DATABASE.key, file.getPath()); params.put(GeoPkgDataStoreFactory.DBTYPE.key, GeoPkgDataStoreFactory.DBTYPE.sample); this.connPool = new GeoPkgDataStoreFactory(writerConfig).createDataSource(params); } GeoPackage(DataSource dataSource) { this.connPool = dataSource; } GeoPackage(JDBCDataStore dataStore) { this.dataStore = dataStore; this.connPool = dataStore.getDataSource(); } /** * The underlying database file. * <p> * Note: this value may be <code>null</code> depending on how the geopackage was initialized. * </p> */ public File getFile() { return file; } /** * The database data source. */ public DataSource getDataSource() { return connPool; } /** * Initializes the geopackage database. * <p> * This method creates all the necessary metadata tables. * </p> */ public void init() throws IOException { try { Connection cx = connPool.getConnection(); try { init(cx); } finally { close(cx); } } catch (SQLException e) { throw new IOException(e); } } /** * Initializes a geopackage connection. * <p> * This method creates all the necessary metadata tables. * </p> */ static void init(Connection cx) throws SQLException { createFunctions(cx); runSQL("PRAGMA application_id = 0x47503130;", cx); // runSQL("SELECT InitSpatialMetaData();"); runScript(SPATIAL_REF_SYS + ".sql", cx); runScript(GEOMETRY_COLUMNS + ".sql", cx); runScript(GEOPACKAGE_CONTENTS + ".sql", cx); runScript(TILE_MATRIX_SET + ".sql", cx); runScript(TILE_MATRIX_METADATA + ".sql", cx); runScript(RASTER_COLUMNS + ".sql", cx); runScript(METADATA + ".sql", cx); runScript(METADATA_REFERENCE + ".sql", cx); runScript(DATA_COLUMN_CONSTRAINTS + ".sql", cx); runScript(EXTENSIONS + ".sql", cx); addDefaultSpatialReferences(cx); } static void createFunctions(Connection cx) throws SQLException { while (cx instanceof DelegatingConnection) { cx = ((DelegatingConnection) cx).getDelegate(); } // minx Function.create(cx, "ST_MinX", new GeometryFunction() { @Override public Object execute(GeoPkgGeomReader reader) throws IOException { return reader.getEnvelope().getMinX(); } }); // maxx Function.create(cx, "ST_MaxX", new GeometryFunction() { @Override public Object execute(GeoPkgGeomReader reader) throws IOException { return reader.getEnvelope().getMaxX(); } }); // miny Function.create(cx, "ST_MinY", new GeometryFunction() { @Override public Object execute(GeoPkgGeomReader reader) throws IOException { return reader.getEnvelope().getMinY(); } }); // maxy Function.create(cx, "ST_MaxY", new GeometryFunction() { @Override public Object execute(GeoPkgGeomReader reader) throws IOException { return reader.getEnvelope().getMaxY(); } }); // empty Function.create(cx, "ST_IsEmpty", new GeometryFunction() { @Override public Object execute(GeoPkgGeomReader reader) throws IOException { return reader.getHeader().getFlags().isEmpty(); } }); } /** * Closes the geopackage database connection. * <p> * The application should always call this method when done with a geopackage to prevent connection leakage. * </p> */ public void close() { if (dataStore != null) { dataStore.dispose(); } try { if (connPool instanceof BasicDataSource) { ((BasicDataSource) connPool).close(); } else if (connPool instanceof ManageableDataSource) { ((ManageableDataSource) connPool).close(); } } catch (SQLException e) { LOGGER.log(Level.WARNING, "Error closing database connection", e); } } /** * Adds an epsg crs to the geopackage, registering it in the spatial_ref_sys table. * <p> * This method will look up the <tt>srid</tt> in the local epsg database. Use {@link #addCRS(CoordinateReferenceSystem, int)} to specify an * explicit CRS, authority, code entry. * </p> */ public void addCRS(int srid) throws IOException { try { addCRS(CRS.decode("EPSG:" + srid), "epsg", srid); } catch (Exception e) { throw new IOException(e); } } protected static void addDefaultSpatialReferences(Connection cx) throws SQLException { try { addCRS(cx, -1, "Undefined cartesian SRS", "NONE", -1, "undefined", "undefined cartesian coordinate reference system"); addCRS(cx, 0, "Undefined geographic SRS", "NONE", 0, "undefined", "undefined geographic coordinate reference system"); addCRS(cx, 4326, "WGS 84 geodetic", "EPSG", 4326, "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\"," + "6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]]," + "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433," + "AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]]", "longitude/latitude coordinates in decimal degrees on the WGS 84 spheroid"); } catch (IOException ex) { throw new SQLException("Unable to add default spatial references.", ex); } } public static void addCRS(Connection cx, int srid, String srsName, String organization, int organizationCoordSysId, String definition, String description) throws IOException { // try { // Connection cx = connPool.getConnection(); try { PreparedStatement ps = cx.prepareStatement( String.format("SELECT srs_id FROM %s WHERE srs_id = ?", SPATIAL_REF_SYS)); try { ResultSet rs = prepare(ps).set(srid).log(Level.FINE).statement().executeQuery(); try { if (rs.next()) { return; } } finally { close(rs); } } finally { close(ps); } ps = cx.prepareStatement(String .format("INSERT INTO %s (srs_id, srs_name, organization, organization_coordsys_id, definition, description) " + "VALUES (?,?,?,?,?,?)", SPATIAL_REF_SYS)); try { prepare(ps).set(srid).set(srsName).set(organization).set(organizationCoordSysId) .set(definition).set(description).log(Level.FINE).statement().execute(); } finally { close(ps); } /* * finally { close(cx); } */ } catch (SQLException e) { throw new IOException(e); } } /** * Adds a crs to the geopackage, registring it in the spatial_ref_sys table. * * @param crs The crs to add. * @param auth The authority code, example: epsg * @param srid The spatial reference system id. * */ public void addCRS(CoordinateReferenceSystem crs, String auth, int srid) throws IOException { Connection cx; try { cx = connPool.getConnection(); try { GeoPackage.addCRS(cx, srid, auth + ":" + srid, auth, srid, crs.toWKT(), auth + ":" + srid); } finally { cx.close(); } } catch (SQLException e) { throw new RuntimeException(e); } } private CoordinateReferenceSystem getCRS(int srid) { try { Connection cx = connPool.getConnection(); try { PreparedStatement ps = cx.prepareStatement(String .format("SELECT definition FROM %s WHERE srs_id = ?", SPATIAL_REF_SYS)); try { ResultSet rs = prepare(ps).set(srid).log(Level.FINE).statement().executeQuery(); try { if (rs.next()) { try { return CRS.parseWKT(rs.getString("definition")); } catch (FactoryException e) { LOGGER.log(Level.FINE, "Error parsing CRS definitions!", e); } } } finally { close(rs); } } finally { close(ps); } } finally { close(cx); } } catch (SQLException e) { throw new RuntimeException(e); } return null; } /** * Returns list of contents of the geopackage. */ public List<Entry> contents() { List<Entry> contents = new ArrayList<Entry>(); try { Connection cx = connPool.getConnection(); try { Statement st = cx.createStatement(); try { ResultSet rs = st.executeQuery("SELECT * FROM " + GEOPACKAGE_CONTENTS); try { while (rs.next()) { } } finally { close(rs); } } finally { close(st); } } finally { close(cx); } } catch (SQLException e) { throw new RuntimeException(e); } return contents; } // // feature methods /** * Lists all the feature entries in the geopackage. * */ public List<FeatureEntry> features() throws IOException { try { Connection cx = connPool.getConnection(); try { List<FeatureEntry> entries = new ArrayList(); String sql = format( "SELECT a.*, b.column_name, b.geometry_type_name, b.z, b.m, c.organization_coordsys_id, c.definition" + " FROM %s a, %s b, %s c" + " WHERE a.table_name = b.table_name" + " AND a.srs_id = c.srs_id" + " AND a.data_type = ?", GEOPACKAGE_CONTENTS, GEOMETRY_COLUMNS, SPATIAL_REF_SYS); PreparedStatement ps = cx.prepareStatement(sql); try { ps.setString(1, DataType.Feature.value()); ResultSet rs = ps.executeQuery(); try { while (rs.next()) { entries.add(createFeatureEntry(rs)); } } finally { close(rs); } } finally { close(ps); } return entries; } finally { close(cx); } } catch (SQLException e) { throw new IOException(e); } } /** * Looks up a feature entry by name. * * @param name THe name of the feature entry. * @return The entry, or <code>null</code> if no such entry exists. */ public FeatureEntry feature(String name) throws IOException { try { Connection cx = connPool.getConnection(); try { String sql = format( "SELECT a.*, b.column_name, b.geometry_type_name, b.m, b.z, c.organization_coordsys_id, c.definition" + " FROM %s a, %s b, %s c" + " WHERE a.table_name = b.table_name " + " AND a.srs_id = c.srs_id " + " AND a.table_name = ?" + " AND a.data_type = ?", GEOPACKAGE_CONTENTS, GEOMETRY_COLUMNS, SPATIAL_REF_SYS); PreparedStatement ps = cx.prepareStatement(sql); try { ps.setString(1, name); ps.setString(2, DataType.Feature.value()); ResultSet rs = ps.executeQuery(); try { if (rs.next()) { return createFeatureEntry(rs); } } finally { close(rs); } } finally { close(ps); } } finally { close(cx); } } catch (SQLException e) { throw new IOException(e); } return null; } /** * Creates a new feature entry in the geopackage. * <p> * The resulting feature dataset will be empty. The {@link #writer(FeatureEntry, boolean, Transaction)} method returns a writer object that can be * used to populate the dataset. * </p> * * @param entry Contains metadata about the feature entry. * @param schema The schema of the feature dataset. * * @throws IOException Any errors occurring while creating the new feature entry. */ public void create(FeatureEntry entry, SimpleFeatureType schema) throws IOException { // clone entry so we can work on it FeatureEntry e = new FeatureEntry(); e.init(entry); e.setTableName(schema.getTypeName()); if (e.getGeometryColumn() != null) { // check it if (schema.getDescriptor(e.getGeometryColumn()) == null) { throw new IllegalArgumentException(format( "Geometry column %s does not exist in schema", e.getGeometryColumn())); } } else { e.setGeometryColumn(findGeometryColumn(schema)); } if (e.getIdentifier() == null) { e.setIdentifier(schema.getTypeName()); } if (e.getDescription() == null) { e.setDescription(e.getIdentifier()); } // check for bounds if (e.getBounds() == null) { throw new IllegalArgumentException("Entry must have bounds"); } // check for srid if (e.getSrid() == null) { try { e.setSrid(findSRID(schema)); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } if (e.getSrid() == null) { throw new IllegalArgumentException("Entry must have srid"); } if (e.getGeometryType() == null) { e.setGeometryType(findGeometryType(schema)); } // mark changed e.setLastChange(new Date()); // pass in teh feature entry to the datsatore as user data schema.getUserData().put(FeatureEntry.class, e); JDBCDataStore dataStore = dataStore(); // create the feature table dataStore.createSchema(schema); // update the metadata tables // addGeoPackageContentsEntry(e); // update the entry entry.init(e); } /** * Adds a new feature dataset to the geopackage. * * @param entry Contains metadata about the feature entry. * @param collection The simple feature collection to add to the geopackage. * * @throws IOException Any errors occurring while adding the new feature dataset. */ public void add(FeatureEntry entry, SimpleFeatureCollection collection) throws IOException { FeatureEntry e = new FeatureEntry(); e.init(entry); if (e.getBounds() == null) { e.setBounds(collection.getBounds()); } create(e, collection.getSchema()); Transaction tx = new DefaultTransaction(); try { SimpleFeatureWriter w = writer(e, true, null, tx); SimpleFeatureIterator it = collection.features(); try { while (it.hasNext()) { SimpleFeature f = it.next(); SimpleFeature g = w.next(); for (PropertyDescriptor pd : collection.getSchema().getDescriptors()) { String name = pd.getName().getLocalPart(); g.setAttribute(name, f.getAttribute(name)); } w.write(); } } finally { w.close(); it.close(); } tx.commit(); } catch (Exception ex) { tx.rollback(); throw new IOException(ex); } finally { tx.close(); } entry.init(e); } /** * Adds a new feature dataset to the geopackage. * * @param entry Contains metadata about the feature entry. * @param source The dataset to add to the geopackage. * @param filter Filter specifying what subset of feature dataset to include, may be <code>null</code> to specify no filter. * * @throws IOException Any errors occurring while adding the new feature dataset. */ public void add(FeatureEntry entry, SimpleFeatureSource source, Filter filter) throws IOException { // copy over features // TODO: make this more robust, won't handle case issues going between datasources, etc... // TODO: for big datasets we need to break up the transaction if (filter == null) { filter = Filter.INCLUDE; } add(entry, source.getFeatures(filter)); } /** * Returns a writer used to modify or add to the contents of a feature dataset. * * @param entry The feature entry. * @param append Flag controlling whether to modify existing contents, or append to the dataset. * @param filter Filter determining what subset of dataset to modify, only relevant when <tt>append</tt> set to false. May be <code>null</code> to * specify no filter. * @param tx Transaction object, may be <code>null</code> to specify auto commit transaction. * */ public SimpleFeatureWriter writer(FeatureEntry entry, boolean append, Filter filter, Transaction tx) throws IOException { DataStore dataStore = dataStore(); FeatureWriter w = append ? dataStore.getFeatureWriterAppend(entry.getTableName(), tx) : dataStore.getFeatureWriter(entry.getTableName(), filter, tx); return Features.simple(w); } /** * Returns a reader for the contents of a feature dataset. * * @param entry The feature entry. * @param filter Filter Filter determining what subset of dataset to return. May be <code>null</code> to specify no filter. * @param tx Transaction object, may be <code>null</code> to specify auto commit transaction. */ public SimpleFeatureReader reader(FeatureEntry entry, Filter filter, Transaction tx) throws IOException { Query q = new Query(entry.getTableName()); q.setFilter(filter != null ? filter : Filter.INCLUDE); return Features.simple(dataStore().getFeatureReader(q, tx)); } static Integer findSRID(SimpleFeatureType schema) throws Exception { CoordinateReferenceSystem crs = schema.getCoordinateReferenceSystem(); if (crs == null) { GeometryDescriptor gd = findGeometryDescriptor(schema); crs = gd.getCoordinateReferenceSystem(); } return crs != null ? CRS.lookupEpsgCode(crs, true) : null; } static String findGeometryColumn(SimpleFeatureType schema) { GeometryDescriptor gd = findGeometryDescriptor(schema); return gd != null ? gd.getLocalName() : null; } static Geometries findGeometryType(SimpleFeatureType schema) { GeometryDescriptor gd = findGeometryDescriptor(schema); return gd != null ? Geometries.getForBinding((Class<? extends Geometry>) gd.getType().getBinding()) : null; } static GeometryDescriptor findGeometryDescriptor(SimpleFeatureType schema) { GeometryDescriptor gd = schema.getGeometryDescriptor(); if (gd == null) { for (PropertyDescriptor pd : schema.getDescriptors()) { if (pd instanceof GeometryDescriptor) { return (GeometryDescriptor) pd; } } } return gd; } FeatureEntry createFeatureEntry(ResultSet rs) throws SQLException, IOException { FeatureEntry e = new FeatureEntry(); initEntry(e, rs); e.setGeometryColumn(rs.getString("column_name")); e.setGeometryType(Geometries.getForName(rs.getString("geometry_type_name"))); e.setZ(rs.getBoolean("z")); e.setM(rs.getBoolean("m")); return e; } void addGeoPackageContentsEntry(Entry e) throws IOException { final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(DATE_FORMAT_STRING); DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT")); addCRS(e.getSrid()); StringBuilder sb = new StringBuilder(); StringBuilder vals = new StringBuilder(); sb.append(format("INSERT INTO %s (table_name, data_type, identifier", GEOPACKAGE_CONTENTS)); vals.append("VALUES (?,?,?"); if (e.getDescription() != null) { sb.append(", description"); vals.append(",?"); } if (e.getLastChange() != null) { sb.append(", last_change"); vals.append(",?"); } sb.append(", min_x, min_y, max_x, max_y"); vals.append(",?,?,?,?"); if (e.getSrid() != null) { sb.append(", srs_id"); vals.append(",?"); } sb.append(") ").append(vals.append(")").toString()); try { Connection cx = connPool.getConnection(); try { SqlUtil.PreparedStatementBuilder psb = prepare(cx, sb.toString()) .set(e.getTableName()).set(e.getDataType().value()).set(e.getIdentifier()); if (e.getDescription() != null) { psb.set(e.getDescription()); } if (e.getLastChange() != null) { psb.set(DATE_FORMAT.format(e.getLastChange())); } if (e.getBounds() != null) { psb.set(e.getBounds().getMinX()).set(e.getBounds().getMinY()) .set(e.getBounds().getMaxX()).set(e.getBounds().getMaxY()); } else { double minx = 0; double miny = 0; double maxx = 0; double maxy = 0; if (e.getSrid() != null) { CoordinateReferenceSystem crs = getCRS(e.getSrid()); if (crs != null) { org.opengis.geometry.Envelope env = CRS.getEnvelope(crs); if (env != null) { minx = env.getMinimum(0); miny = env.getMinimum(1); maxx = env.getMaximum(0); maxy = env.getMaximum(1); } } } psb.set(minx).set(miny).set(maxx).set(maxy); } if (e.getSrid() != null) { psb.set(e.getSrid()); } PreparedStatement ps = psb.log(Level.FINE).statement(); try { ps.execute(); } finally { close(ps); } } finally { close(cx); } } catch (SQLException ex) { throw new IOException(ex); } } void deleteGeoPackageContentsEntry(Entry e) throws IOException { String sql = format("DELETE FROM %s WHERE table_name = ?", GEOPACKAGE_CONTENTS); try { Connection cx = connPool.getConnection(); try { PreparedStatement ps = prepare(cx, sql).set(e.getTableName()).log(Level.FINE) .statement(); try { ps.execute(); } finally { close(ps); } } finally { close(cx); } } catch (SQLException ex) { throw new IOException(ex); } } void addGeometryColumnsEntry(FeatureEntry e) throws IOException { String sql = format("INSERT INTO %s VALUES (?, ?, ?, ?, ?, ?);", GEOMETRY_COLUMNS); try { Connection cx = connPool.getConnection(); try { PreparedStatement ps = prepare(cx, sql).set(e.getTableName()) .set(e.getGeometryColumn()) .set(e.getGeometryType() != null ? e.getGeometryType().getName() : null) .set(e.getSrid()).set(e.isZ()).set(e.isM()).log(Level.FINE).statement(); try { ps.execute(); } finally { close(ps); } } finally { close(cx); } } catch (SQLException ex) { throw new IOException(ex); } } void deleteGeometryColumnsEntry(FeatureEntry e) throws IOException { String sql = format("DELETE FROM %s WHERE table_name = ?", GEOMETRY_COLUMNS); try { Connection cx = connPool.getConnection(); try { PreparedStatement ps = prepare(cx, sql).set(e.getTableName()).log(Level.FINE) .statement(); try { ps.execute(); } finally { close(ps); } } finally { close(cx); } } catch (SQLException ex) { throw new IOException(ex); } } /** * Create a spatial index * * @param e feature entry to create spatial index for */ public void createSpatialIndex(FeatureEntry e) throws IOException { Map<String, String> properties = new HashMap<String, String>(); PrimaryKey pk = ((JDBCFeatureStore) (dataStore.getFeatureSource(e.getTableName()))) .getPrimaryKey(); if (pk.getColumns().size() != 1) { throw new IOException("Spatial index only supported for primary key of single column."); } properties.put("t", e.getTableName()); properties.put("c", e.getGeometryColumn()); properties.put("i", pk.getColumns().get(0).getName()); Connection cx; try { cx = connPool.getConnection(); try { runScript(SPATIAL_INDEX + ".sql", cx, properties); } finally { cx.close(); } } catch (SQLException ex) { throw new IOException(ex); } } // raster methods /** * Lists all the raster entries in the geopackage. */ public List<RasterEntry> rasters() throws IOException { try { Connection cx = connPool.getConnection(); try { List<RasterEntry> entries = new ArrayList(); String sql = format( "SELECT a.*, b.column_name, b.name, b.title, b.mime_type, b.description column_description, b.constraint_name, c.organization_coordsys_id, c.definition" + " FROM %s a, %s b, %s c" + " WHERE a.table_name = b.table_name" + " AND a.srs_id = c.srs_id " + " AND a.data_type = ?", GEOPACKAGE_CONTENTS, RASTER_COLUMNS, SPATIAL_REF_SYS); PreparedStatement ps = cx.prepareStatement(sql); try { ps.setString(1, DataType.Raster.value()); ResultSet rs = ps.executeQuery(); try { while (rs.next()) { entries.add(createRasterEntry(rs)); } } finally { close(rs); } } finally { close(ps); } return entries; } finally { close(cx); } } catch (SQLException e) { throw new IOException(e); } } /** * Looks up a raster entry by name. * * @param name THe name of the raster entry. * @return The entry, or <code>null</code> if no such entry exists. */ public RasterEntry raster(String name) throws IOException { try { Connection cx = connPool.getConnection(); try { String sql = format( "SELECT a.*, b.name, b.title, b.mime_type, b.column_name, b.description column_description, b.constraint_name, c.organization_coordsys_id, c.definition" + " FROM %s a, %s b, %s c" + " WHERE a.table_name = b.table_name" + " AND a.srs_id = c.srs_id" + " AND a.table_name = ?" + " AND a.data_type = ?", GEOPACKAGE_CONTENTS, RASTER_COLUMNS, SPATIAL_REF_SYS); PreparedStatement ps = cx.prepareStatement(sql); try { ps.setString(1, name); ps.setString(2, DataType.Raster.value()); ResultSet rs = ps.executeQuery(); try { if (rs.next()) { return createRasterEntry(rs); } } finally { close(rs); } } finally { close(ps); } } finally { close(cx); } } catch (SQLException e) { throw new IOException(e); } return null; } /** * Adds a new raster dataset to the geopackage. * * @param entry Contains metadata about the raster entry. * @param raster The raster dataset. * @param format The format in which to store the raster in the database. * * @throws IOException Any errors occurring while adding the new feature dataset. */ public void add(RasterEntry entry, GridCoverage2D raster, AbstractGridFormat format) throws IOException { RasterEntry e = new RasterEntry(); e.init(entry); if (e.getTableName() == null) { if (raster.getName() == null) { throw new IllegalArgumentException("No table name specified for raster"); } e.setTableName(raster.getName().toString()); } if (e.getRasterColumn() == null) { e.setRasterColumn("raster"); } if (e.getSrid() == null) { try { e.setSrid(findSRID(raster)); } catch (Exception ex) { throw new IOException(ex); } } if (e.getSrid() == null) { throw new IllegalArgumentException("Entry must have srid"); } if (e.getBounds() == null) { e.setBounds(findBounds(raster)); } if (e.getBounds() == null) { throw new IllegalArgumentException("Entry must have bounds"); } if (e.getIdentifier() == null) { e.setIdentifier(raster.getName().toString()); } if (e.getDescription() == null) { e.setDescription(e.getIdentifier()); } e.setLastChange(new Date()); // write out raster to temp file File tmpFile = File.createTempFile(e.getTableName(), "raster"); GridCoverageWriter writer = format.getWriter(tmpFile); writer.write(raster, null); writer.dispose(); // create the raster table try { Connection cx = connPool.getConnection(); try { Statement st = cx.createStatement(); try { String sql = format( "CREATE TABLE %s (id INTEGER PRIMARY KEY AUTOINCREMENT, %s BLOB NOT NULL)", e.getTableName(), e.getRasterColumn()); LOGGER.fine(sql); st.execute(sql); } finally { close(st); } // TODO: ideally we would stream this in BufferedInputStream bin = new BufferedInputStream(new FileInputStream(tmpFile)); byte[] blob = IOUtils.toByteArray(bin); try { PreparedStatement ps = prepare(cx, format("INSERT INTO %s (%s) VALUES (?)", e.getTableName(), e.getRasterColumn())).set(blob).log(Level.FINE) .statement(); try { ps.execute(); } finally { close(ps); } } finally { bin.close(); } } finally { close(cx); } } catch (SQLException ex) { throw new IOException(ex); } tmpFile.delete(); addGeoPackageContentsEntry(e); addRasterColumnsEntry(e); entry.init(e); } /** * Returns a reader for the contents of a raster dataset. * * @param entry The raster entry. * @param format Format of the raster dataset. */ public GridCoverageReader reader(RasterEntry entry, AbstractGridFormat format) throws IOException { try { Connection cx = connPool.getConnection(); try { Statement st = cx.createStatement(); try { ResultSet rs = st.executeQuery(format("SELECT %s FROM %s;", entry.getRasterColumn(), entry.getTableName())); try { if (rs.next()) { byte[] blob = rs.getBytes(1); Hints hints = new Hints(); // if (format instanceof WorldImageFormat) { // TODO: get this patch submitted // hints.put(WorldImageFormat.ORIGINAL_ENVELOPE, toGeneralEnvelope(entry.getBounds())); return format.getReader(blob, hints); } } finally { close(rs); } } finally { close(st); } } finally { close(cx); } } catch (SQLException e) { throw new IOException(e); } return null; } static Integer findSRID(GridCoverage2D raster) throws Exception { return CRS.lookupEpsgCode(raster.getCoordinateReferenceSystem(), true); } static ReferencedEnvelope findBounds(GridCoverage2D raster) { org.opengis.geometry.Envelope e = raster.getEnvelope(); return new ReferencedEnvelope(e.getMinimum(0), e.getMaximum(0), e.getMinimum(1), e.getMaximum(1), raster.getCoordinateReferenceSystem()); } static GeneralEnvelope toGeneralEnvelope(ReferencedEnvelope e) { GeneralEnvelope ge = new GeneralEnvelope(new double[] { e.getMinX(), e.getMinY() }, new double[] { e.getMaxX(), e.getMaxY() }); ge.setCoordinateReferenceSystem(e.getCoordinateReferenceSystem()); return ge; } RasterEntry createRasterEntry(ResultSet rs) throws SQLException, IOException { RasterEntry e = new RasterEntry(); initEntry(e, rs); e.setRasterColumn(rs.getString("column_name")); e.setName(rs.getString("name")); e.setTitle(rs.getString("title")); e.setDescription(rs.getString("column_description")); e.setMimeType(rs.getString("mime_type")); e.setConstraint(rs.getString("constraint_name")); return e; } void addRasterColumnsEntry(RasterEntry e) throws IOException { String sql = format("INSERT INTO %s VALUES (?, ?, ?, ?, ?, ?, ?);", RASTER_COLUMNS); try { Connection cx = connPool.getConnection(); try { PreparedStatement ps = prepare(cx, sql).set(e.getTableName()) .set(e.getRasterColumn()).set(e.getName()).set(e.getTitle()) .set(e.getDescription()).set(e.getMimeType()).set(e.getConstraint()) .log(Level.FINE).statement(); try { ps.execute(); } finally { close(ps); } } finally { close(cx); } } catch (SQLException ex) { throw new IOException(ex); } } // tile methods /** * Lists all the tile entries in the geopackage. */ public List<TileEntry> tiles() throws IOException { try { Connection cx = connPool.getConnection(); try { List<TileEntry> entries = new ArrayList(); String sql = format( "SELECT a.*, c.organization_coordsys_id, c.definition" + " FROM %s a, %s c" + " WHERE a.srs_id = c.srs_id" + " AND a.data_type = ?", GEOPACKAGE_CONTENTS, SPATIAL_REF_SYS); LOGGER.fine(sql); PreparedStatement ps = cx.prepareStatement(sql); try { ps.setString(1, DataType.Tile.value()); ResultSet rs = ps.executeQuery(); try { while (rs.next()) { entries.add(createTileEntry(rs, cx)); } } finally { close(rs); } } finally { close(ps); } return entries; } finally { close(cx); } } catch (SQLException e) { throw new IOException(e); } } /** * Looks up a tile entry by name. * * @param name THe name of the tile entry. * @return The entry, or <code>null</code> if no such entry exists. */ public TileEntry tile(String name) throws IOException { try { Connection cx = connPool.getConnection(); try { String sql = format("SELECT a.*, c.organization_coordsys_id, c.definition" + " FROM %s a, %s c" + " WHERE a.srs_id = c.srs_id" + " AND a.table_name = ?" + " AND a.data_type = ?", GEOPACKAGE_CONTENTS, SPATIAL_REF_SYS); LOGGER.fine(sql); PreparedStatement ps = cx.prepareStatement(sql); try { ps.setString(1, name); ps.setString(2, DataType.Tile.value()); ResultSet rs = ps.executeQuery(); try { if (rs.next()) { return createTileEntry(rs, cx); } } finally { close(rs); } } finally { close(ps); } } finally { close(cx); } } catch (SQLException e) { throw new IOException(e); } return null; } /** * Creates a new tile entry in the geopackage. * * @param entry The tile entry. */ public void create(TileEntry entry) throws IOException { if (entry.getBounds() == null) { throw new IllegalArgumentException("Tile entry must specify bounds"); } TileEntry e = new TileEntry(); e.init(entry); if (e.getTableName() == null) { e.setTableName("tiles"); } if (e.getIdentifier() == null) { e.setIdentifier(e.getTableName()); } if (e.getDescription() == null) { e.setDescription(e.getIdentifier()); } if (e.getSrid() == null) { try { e.setSrid(findSRID(entry.getBounds())); } catch (Exception ex) { throw new IOException(ex); } } e.setLastChange(new Date()); try { Connection cx = connPool.getConnection(); // TODO: do all of this in a transaction try { PreparedStatement st; // add entry to tile matrix set table st = prepare(cx, format("INSERT INTO %s VALUES (?,?,?,?,?,?)", TILE_MATRIX_SET)) .set(e.getTableName()).set(e.getSrid()).set(e.getBounds().getMinX()) .set(e.getBounds().getMinY()).set(e.getBounds().getMaxX()) .set(e.getBounds().getMaxY()).statement(); try { st.execute(); } finally { close(st); } // create the tile_matrix_metadata entries st = prepare(cx, format("INSERT INTO %s VALUES (?,?,?,?,?,?,?,?)", TILE_MATRIX_METADATA)) .statement(); try { for (TileMatrix m : e.getTileMatricies()) { prepare(st).set(e.getTableName()).set(m.getZoomLevel()) .set(m.getMatrixWidth()).set(m.getMatrixHeight()) .set(m.getTileWidth()).set(m.getTileHeight()).set(m.getXPixelSize()) .set(m.getYPixelSize()).statement().execute(); } } finally { close(st); } // create the tile table itself st = cx.prepareStatement(format( "CREATE TABLE %s (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "zoom_level INTEGER NOT NULL DEFAULT 0," + "tile_column INTEGER NOT NULL DEFAULT 0," + "tile_row INTEGER NOT NULL DEFAULT 0," + "tile_data BLOB NOT NULL DEFAULT (zeroblob(4)))", e.getTableName())); try { st.execute(); } finally { close(st); } // create an index on the tile st = cx.prepareStatement( format("create index %s_zyx_idx on %s(zoom_level, tile_column, tile_row);", e.getTableName(), e.getTableName())); try { st.execute(); } finally { close(st); } } finally { close(cx); } } catch (SQLException ex) { throw new IOException(ex); } // update the metadata tables addGeoPackageContentsEntry(e); entry.init(e); } /** * Adds a tile to the geopackage. * * @param entry The tile metadata entry. * @param tile The tile. */ public void add(TileEntry entry, Tile tile) throws IOException { try { Connection cx = connPool.getConnection(); try { PreparedStatement ps = prepare(cx, format("INSERT INTO %s (zoom_level, tile_column," + " tile_row, tile_data) VALUES (?,?,?,?)", entry.getTableName())) .set(tile.getZoom()).set(tile.getColumn()) .set(tile.getRow()).set(tile.getData()).log(Level.FINE) .statement(); try { ps.execute(); } finally { close(ps); } } finally { close(cx); } } catch (SQLException e) { throw new IOException(e); } } /** * Retrieve tiles within certain zooms and column/row boundaries * * @param entry the tile entry * @param lowZoom low zoom boundary * @param highZoom high zoom boundary * @param lowCol low column boundary * @param highCol high column boundary * @param lowRow low row boundary * @param highRow high row boundary * @return * @throws IOException */ public TileReader reader(TileEntry entry, Integer lowZoom, Integer highZoom, Integer lowCol, Integer highCol, Integer lowRow, Integer highRow) throws IOException { try { List<String> q = new ArrayList(); if (lowZoom != null) { q.add("zoom_level >= " + lowZoom); } if (highZoom != null) { q.add("zoom_level <= " + highZoom); } if (lowCol != null) { q.add("tile_column >= " + lowCol); } if (highCol != null) { q.add("tile_column <= " + highCol); } if (lowRow != null) { q.add("tile_row >= " + lowRow); } if (highRow != null) { q.add("tile_row <= " + highRow); } StringBuffer sql = new StringBuffer("SELECT * FROM ").append(entry.getTableName()); if (!q.isEmpty()) { sql.append(" WHERE "); for (String s : q) { sql.append(s).append(" AND "); } sql.setLength(sql.length() - 5); } Connection cx = connPool.getConnection(); Statement st = cx.createStatement(); ResultSet rs = st.executeQuery(sql.toString()); return new TileReader(rs, cx); } catch (SQLException e) { throw new IOException(e); } } protected String getSpatialIndexName(FeatureEntry entry) { return "rtree_" + entry.getTableName() + "_" + entry.getGeometryColumn(); } /** * Verifies if a spatial index is present * * @param entry The feature entry. * @return whether this feature entry has a spatial index available. * @throws IOException */ public boolean hasSpatialIndex(FeatureEntry entry) throws IOException { try { Connection cx = connPool.getConnection(); try { PreparedStatement ps = prepare(cx, "SELECT name FROM sqlite_master WHERE type='table' AND name=? ") .set(getSpatialIndexName(entry)).log(Level.FINE).statement(); try { ResultSet rs = ps.executeQuery(); try { return rs.next(); } finally { close(rs); } } finally { close(ps); } } finally { close(cx); } } catch (SQLException e) { throw new IOException(e); } } /** * Searches a spatial index. * * @param entry The feature entry. * @param minX Optional minimum x boundary. * @param minY Optional minimum y boundary. * @param maxX Optional maximum x boundary. * @param maxY Optional maximum y boundary. */ public Set<Identifier> searchSpatialIndex(FeatureEntry entry, Double minX, Double minY, Double maxX, Double maxY) throws IOException { List<String> q = new ArrayList(); if (minX != null) { q.add("minx >= " + minX); } if (minY != null) { q.add("miny >= " + minY); } if (maxX != null) { q.add("maxx <= " + maxX); } if (maxY != null) { q.add("maxy <= " + maxY); } StringBuffer sql = new StringBuffer("SELECT id FROM ").append(getSpatialIndexName(entry)); if (!q.isEmpty()) { sql.append(" WHERE "); for (String s : q) { sql.append(s).append(" AND "); } sql.setLength(sql.length() - 5); } try { Connection cx = connPool.getConnection(); try { Statement st = cx.createStatement(); try { ResultSet rs = st.executeQuery(sql.toString()); try { HashSet<Identifier> ids = new HashSet<Identifier>(); while (rs.next()) { ids.add(new FeatureIdImpl(rs.getString(1))); } return ids; } finally { close(rs); } } finally { close(st); } } finally { close(cx); } } catch (SQLException e) { throw new IOException(e); } } /** * Retrieve tile boundaries (min row, max row, min column and max column) for a particular zoom level, available in the actual data * * @param entry The tile entry * @param zoom the zoom level * @param isMax true for max boundary, false for min boundary * @param isRow true for rows, false for columns * @return the min/max column/row of the zoom level available in the data * @throws IOException */ public int getTileBound(TileEntry entry, int zoom, boolean isMax, boolean isRow) throws IOException { try { int tileBounds = -1; StringBuffer sql = new StringBuffer("SELECT " + (isMax ? "MAX" : "MIN") + "( " + (isRow ? "tile_row" : "tile_column") + ") FROM "); sql.append(entry.getTableName()); sql.append(" WHERE zoom_level == "); sql.append(zoom); Connection cx = connPool.getConnection(); try { Statement st = cx.createStatement(); try { ResultSet rs = st.executeQuery(sql.toString()); try { rs.next(); tileBounds = rs.getInt(1); } finally { close(rs); } } finally { close(st); } } finally { close(cx); } return tileBounds; } catch (SQLException e) { throw new IOException(e); } } static TileEntry createTileEntry(ResultSet rs, Connection cx) throws SQLException, IOException { TileEntry e = new TileEntry(); initEntry(e, rs); // load all the tile matrix entries PreparedStatement psm = cx.prepareStatement( format("SELECT * FROM %s" + " WHERE table_name = ?" + " ORDER BY zoom_level ASC", TILE_MATRIX_METADATA)); try { psm.setString(1, e.getTableName()); ResultSet rsm = psm.executeQuery(); try { while (rsm.next()) { TileMatrix m = new TileMatrix(); m.setZoomLevel(rsm.getInt("zoom_level")); m.setMatrixWidth(rsm.getInt("matrix_width")); m.setMatrixHeight(rsm.getInt("matrix_height")); m.setTileWidth(rsm.getInt("tile_width")); m.setTileHeight(rsm.getInt("tile_height")); m.setXPixelSize(rsm.getDouble("pixel_x_size")); m.setYPixelSize(rsm.getDouble("pixel_y_size")); e.getTileMatricies().add(m); } } finally { close(rsm); } } finally { close(psm); } return e; } static Integer findSRID(ReferencedEnvelope e) throws Exception { return CRS.lookupEpsgCode(e.getCoordinateReferenceSystem(), true); } // sql utility methods static void initEntry(Entry e, ResultSet rs) throws SQLException, IOException { e.setIdentifier(rs.getString("identifier")); e.setDescription(rs.getString("description")); e.setTableName(rs.getString("table_name")); try { final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(DATE_FORMAT_STRING); DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT")); e.setLastChange(DATE_FORMAT.parse(rs.getString("last_change"))); } catch (ParseException ex) { throw new IOException(ex); } int srid = rs.getInt("organization_coordsys_id"); e.setSrid(srid); CoordinateReferenceSystem crs; try { crs = CRS.decode("EPSG:" + srid); } catch (Exception ex) { // try parsing srtext directly try { crs = CRS.parseWKT(rs.getString("srtext")); } catch (Exception e2) { throw new IOException(ex); } } e.setBounds(new ReferencedEnvelope(rs.getDouble("min_x"), rs.getDouble("max_x"), rs.getDouble("min_y"), rs.getDouble("max_y"), crs)); } static void runSQL(String sql, Connection cx) throws SQLException { Statement st = cx.createStatement(); try { st.execute(sql); } finally { close(st); } } static void runScript(String filename, Connection cx) throws SQLException { try { SqlUtil.runScript(new GeoPackage().getClass().getResourceAsStream(filename), cx); } catch (IOException e) { } } void runScript(String filename, Connection cx, Map<String, String> properties) throws SQLException { SqlUtil.runScript(getClass().getResourceAsStream(filename), cx, properties); } private static void close(Connection cx) { if (cx != null) { try { cx.close(); } catch (SQLException e) { LOGGER.log(Level.WARNING, "Error closing connection", e); } } } private static void close(Statement st) { if (st != null) { try { st.close(); } catch (SQLException e) { LOGGER.log(Level.WARNING, "Error closing statement", e); } } } private static void close(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOGGER.log(Level.WARNING, "Error closing resultset", e); } } } JDBCDataStore dataStore() throws IOException { if (dataStore == null) { synchronized (this) { if (dataStore == null) { dataStore = createDataStore(); } } } return dataStore; } JDBCDataStore createDataStore() throws IOException { Map<String, Object> params = new HashMap<>(); params.put(GeoPkgDataStoreFactory.DATASOURCE.key, connPool); return new GeoPkgDataStoreFactory(writerConfig).createDataStore(params); } }
package com.gurkensalat.osm.mosques; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.util.Properties; @Configuration @EnableTransactionManagement public class PersistenceJPAConfig { @Value("${spring.datasource.driver-class-name:org.h2.Driver}") private String dataSourceDriverClassName; @Value("${spring.datasource.url:jdbc:h2:mem:testdb}") private String dataSourceUrl; @Value("${spring.datasource.data-username:sa}") private String dataSourceUserName; @Value("${spring.datasource.data-password:}") private String dataSourcePassword; @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan("com.gurkensalat", "com.tandogan"); JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); return em; } private Properties additionalProperties() { Properties properties = new Properties(); properties.setProperty("hibernate.jdbc.time_zone", "UTC"); properties.setProperty("hibernate.hbm2ddl.auto", "update"); return properties; } @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(dataSourceDriverClassName); dataSource.setUrl(dataSourceUrl); dataSource.setUsername(dataSourceUserName); dataSource.setPassword(dataSourcePassword); return dataSource; } // transactionManager // exceptionTranslator }
package com.shinemo.mpush.api.connection; public final class SessionContext { public String osName; public String osVersion; public String clientVersion; public String deviceId; public int heartbeat; public Cipher cipher; public void changeCipher(Cipher cipher) { this.cipher = cipher; } public SessionContext setOsName(String osName) { this.osName = osName; return this; } public SessionContext setOsVersion(String osVersion) { this.osVersion = osVersion; return this; } public SessionContext setClientVersion(String clientVersion) { this.clientVersion = clientVersion; return this; } public SessionContext setDeviceId(String deviceId) { this.deviceId = deviceId; return this; } public void setHeartbeat(int heartbeat) { this.heartbeat = heartbeat; } public boolean handshakeOk() { return deviceId != null && deviceId.length() > 0; } @Override public String toString() { return "SessionContext [osName=" + osName + ", osVersion=" + osVersion + ", clientVersion=" + clientVersion + ", deviceId=" + deviceId + ", heartbeat=" + heartbeat + ", cipher=" + cipher + "]"; } }
package de.dpunkt.myaktion.services; import de.dpunkt.myaktion.model.Campaign; import de.dpunkt.myaktion.model.Organizer; import javax.annotation.Resource; import javax.ejb.SessionContext; import javax.ejb.Stateless; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import java.util.List; @Stateless public class CampaignServiceBean implements CampaignService { @Inject EntityManager entityManager; @Resource private SessionContext sessionContext; @Override public List<Campaign> getAllCampaigns() { TypedQuery<Campaign> query = entityManager.createNamedQuery(Campaign.findByOrganizer, Campaign.class); query.setParameter("organizer", getLoggedinOrganizer()); List<Campaign> campaigns = query.getResultList(); campaigns.forEach(campaign -> campaign.setAmountDonatedSoFar(getAmountDonatedSoFar(campaign))); return campaigns; } @Override public void addCampaign(Campaign campaign) { Organizer organizer = getLoggedinOrganizer(); campaign.setOrganizer(organizer); entityManager.persist(campaign); } @Override public void deleteCampaign(Campaign campaign) { Campaign managedCampaign = entityManager.find(Campaign.class, campaign.getId()); entityManager.remove(managedCampaign); } @Override public void updateCampaign(Campaign campaign) { entityManager.merge(campaign); } private Double getAmountDonatedSoFar(Campaign campaign) { TypedQuery<Double> query = entityManager.createNamedQuery(Campaign.getAmountDonatedSoFar, Double.class); query.setParameter("campaign", campaign); Double result = query.getSingleResult(); if (result == null) result = 0d; return result; } private Organizer getLoggedinOrganizer() { String organizerEmail = sessionContext.getCallerPrincipal().getName(); Organizer organizer = entityManager.createNamedQuery(Organizer.findByEmail, Organizer.class) .setParameter("email", organizerEmail).getSingleResult(); return organizer; } }
package net.winstone; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.ObjectInputStream; import java.io.OutputStream; import java.lang.reflect.Constructor; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import net.winstone.boot.Command; import net.winstone.boot.ShutdownHook; import net.winstone.cluster.Cluster; import net.winstone.cluster.SimpleCluster; import net.winstone.core.HostConfiguration; import net.winstone.core.HostGroup; import net.winstone.core.ObjectPool; import net.winstone.core.listener.Ajp13Listener; import net.winstone.core.listener.HttpListener; import net.winstone.core.listener.HttpsListener; import net.winstone.core.listener.Listener; import net.winstone.jndi.JndiManager; import net.winstone.jndi.resources.DataSourceConfig; import net.winstone.util.LifeCycle; import net.winstone.util.MapConverter; import net.winstone.util.StringUtils; import org.slf4j.LoggerFactory; /** * Implements the main launcher daemon thread. * * @author <a href="mailto:jguibert@intelligents-ia.com" >Jerome Guibert</a> */ public class Server implements LifeCycle { protected static org.slf4j.Logger logger = LoggerFactory.getLogger(Server.class); /** * Default control port. */ private final int DEFAULT_CONTROL_PORT = -1; /** * parameter */ private final Map<String, String> args; /** * control */ private Thread controlThread = null; /** * control Port */ private int controlPort = DEFAULT_CONTROL_PORT; /** * hostGroup instance. */ private HostGroup hostGroup = null; /** * cluster instance. */ private Cluster cluster = null; /** * object pool instance. */ private ObjectPool objectPool = null; /** * listener instance. */ private final List<Listener> listeners = new ArrayList<Listener>(); /** * jndi manager instance. */ private JndiManager globalJndiManager = null; public Server(final Map<String, String> args) throws IllegalArgumentException { super(); if (args == null) { throw new IllegalArgumentException("arg can not be null or empty"); } this.args = args; } /** * Start server */ public void start() { initialize(); } /** * initialises the web app, object pools, control port and the available * protocol listeners. */ @Override public void initialize() { try { Server.logger.debug("Winstone startup arguments: {}", args.toString()); initializeJndi(); objectPool = new ObjectPool(args); controlPort = (args.get("controlPort") == null ? DEFAULT_CONTROL_PORT : Integer.parseInt(args.get("controlPort"))); initializeCluster(); // Open the web apps hostGroup = new HostGroup(cluster, objectPool, globalJndiManager, args); initializeListener(); if (!listeners.isEmpty()) { controlThread = new Thread(new ServerControlThread(), "LauncherControlThread[ControlPort=" + Integer.toString(controlPort) + "]]"); controlThread.setDaemon(Boolean.FALSE); controlThread.start(); } Runtime.getRuntime().addShutdownHook(new ShutdownHook(this)); } catch (final IOException iOException) { try { destroy(); } catch (Throwable e) { // IGNORE } throw new WinstoneException("Server.initialize", iOException); } } @Override public void destroy() { // Release all listeners/pools/webapps if (listeners != null) { for (final Listener listener : listeners) { listener.destroy(); } listeners.clear(); } if (objectPool != null) { objectPool.destroy(); objectPool = null; } if (cluster != null) { cluster.destroy(); cluster = null; } if (hostGroup != null) { hostGroup.destroy(); hostGroup = null; } if (globalJndiManager != null) { globalJndiManager.destroy(); globalJndiManager = null; } if (controlThread != null) { controlThread.interrupt(); controlThread = null; } } /** * Shutdown this server. */ public void shutdown() { Server.logger.info("Winstone shutdown..."); destroy(); Thread.yield(); Server.logger.info("Exiting"); } /** * @return Boolean.TRUE is the server is running. */ public boolean isRunning() { return (controlThread != null) && controlThread.isAlive(); } /** * Instantiate listener. * * @throws IOException */ private void initializeListener() throws IOException { // Create connectors (http, https and ajp) spawnListener(HttpListener.class.getName()); spawnListener(Ajp13Listener.class.getName()); try { Class.forName("javax.net.ServerSocketFactory"); spawnListener(HttpsListener.class.getName()); } catch (final ClassNotFoundException err) { Server.logger.debug("Listener class {} needs JDK1.4 support. Disabling", HttpsListener.class.getName()); } } /** * Instantiate cluster if needed. */ private void initializeCluster() { // Optionally set up clustering if enabled and libraries are available final String useCluster = args.get("useCluster"); final boolean switchOnCluster = (useCluster != null) && (useCluster.equalsIgnoreCase("true") || useCluster.equalsIgnoreCase("yes")); if (switchOnCluster) { if (controlPort < 0) { Server.logger.info("Clustering disabled - control port must be enabled"); } else { final String clusterClassName = StringUtils.stringArg(args, "clusterClassName", SimpleCluster.class.getName()).trim(); try { final Class<?> clusterClass = Class.forName(clusterClassName); final Constructor<?> clusterConstructor = clusterClass.getConstructor(new Class[] { Map.class, Integer.class }); cluster = (Cluster) clusterConstructor.newInstance(new Object[] { args, new Integer(controlPort) }); } catch (final Throwable err) { Server.logger.error("WARNING: Error during startup of cluster implementation - ignoring", err); } } } } /** * Instantiate Jndi Manager if needed. */ private void initializeJndi() { // If jndi is enabled, run the container wide jndi populator if (StringUtils.booleanArg(args, "useJNDI", Boolean.FALSE)) { // Set jndi resource handler if not set (workaround for JamVM bug) try { final Class<?> ctxFactoryClass = Class.forName("net.winstone.jndi.url.java.javaURLContextFactory"); if (System.getProperty("java.naming.factory.initial") == null) { System.setProperty("java.naming.factory.initial", ctxFactoryClass.getName()); } if (System.getProperty("java.naming.factory.url.pkgs") == null) { System.setProperty("java.naming.factory.url.pkgs", "net.winstone.jndi"); } } catch (final ClassNotFoundException err) { Server.logger.error("JNDI Error ", err); } // instanciate Jndi Manager final String jndiMgrClassName = StringUtils.stringArg(args, "containerJndiClassName", JndiManager.class.getName()).trim(); try { // Build the realm final Class<?> jndiMgrClass = Class.forName(jndiMgrClassName); globalJndiManager = (JndiManager) jndiMgrClass.newInstance(); globalJndiManager.initialize(); Server.logger.info("JNDI Started {}", jndiMgrClass.getName()); } catch (final ClassNotFoundException err) { Server.logger.error("JNDI disabled at container level - can't find JNDI Manager class", err); } catch (final Throwable err) { Server.logger.error("JNDI disabled at container level - couldn't load JNDI Manager: " + jndiMgrClassName, err); } // instanciate data final Collection<String> keys = new ArrayList<String>(args != null ? args.keySet() : (Collection<String>) new ArrayList<String>()); for (final Iterator<String> i = keys.iterator(); i.hasNext();) { final String key = i.next(); if (key.startsWith("jndi.resource.")) { final String resourceName = key.substring(14); final String className = args.get(key); final String value = args.get("jndi.param." + resourceName + ".value"); Server.logger.debug("Creating object: {} from startup arguments", resourceName); createObject(resourceName.trim(), className.trim(), value, args); } } } } /** * Build an object to insert into the jndi space */ protected final boolean createObject(final String name, final String className, final String value, final Map<String, String> args) { // basic check if ((className == null) || (name == null)) { return Boolean.FALSE; } // If we are working with a datasource if (className.equals("javax.sql.DataSource")) { try { final DataSourceConfig dataSourceConfig = MapConverter.apply(extractRelevantArgs(args, name), new DataSourceConfig()); globalJndiManager.bind(dataSourceConfig); return Boolean.TRUE; } catch (final Throwable err) { Server.logger.error("Error building JDBC Datasource object " + name, err); } } // If we are working with a mail session else if (className.equals("javax.mail.Session")) { try { final Properties p = new Properties(); p.putAll(extractRelevantArgs(args, name)); globalJndiManager.bindSmtpSession(name, p, Thread.currentThread().getContextClassLoader()); return Boolean.TRUE; } catch (final Throwable err) { Server.logger.error("Error building JavaMail session " + name, err); } } // If unknown type, try to instantiate with the string constructor else if (value != null) { try { globalJndiManager.bind(name, className, value, Thread.currentThread().getContextClassLoader()); return Boolean.TRUE; } catch (final Throwable err) { Server.logger.error("Error building JNDI object " + name + " (class: " + className + ")", err); } } return Boolean.FALSE; } /** * Rips the parameters relevant to a particular resource from the command * args */ private Map<String, String> extractRelevantArgs(final Map<String, String> input, final String name) { final Map<String, String> relevantArgs = new HashMap<String, String>(); for (final Iterator<String> i = input.keySet().iterator(); i.hasNext();) { final String key = i.next(); if (key.startsWith("jndi.param." + name + ".")) { relevantArgs.put(key.substring(12 + name.length()), input.get(key)); } } relevantArgs.put("name", name); return relevantArgs; } /** * Instantiates listeners. Note that an exception thrown in the constructor * is interpreted as the listener being disabled, so don't do anything too * adventurous in the constructor, or if you do, catch and log any errors * locally before rethrowing. * * @throws IOException */ protected final void spawnListener(final String listenerClassName) throws IOException { try { final Class<?> listenerClass = Class.forName(listenerClassName); final Constructor<?> listenerConstructor = listenerClass.getConstructor(new Class[] { Map.class, ObjectPool.class, HostGroup.class }); final Listener listener = (Listener) listenerConstructor.newInstance(new Object[] { args, objectPool, hostGroup }); if (listener.start()) { listeners.add(listener); } } catch (final ClassNotFoundException err) { Server.logger.warn("Listener {} not found / disabled - ignoring", listenerClassName); } catch (final Throwable err) { Server.logger.error("Error during listener startup " + listenerClassName, err); throw (IOException) new IOException("Failed to start a listener: " + listenerClassName).initCause(err); } } /** * ServerControl Thread. * * @author Jerome Guibert */ private final class ServerControlThread implements Runnable { private final static transient int CONTROL_TIMEOUT = 2000; // wait 2s // for // control // connection /** * The main run method. This handles the normal thread processing. */ @Override public void run() { boolean interrupted = Boolean.FALSE; try { ServerSocket controlSocket = null; if (controlPort > 0) { // Without password, we limit control port on local // interface or from controlAddress in parameter. InetAddress inetAddress = null; final String controlAddress = StringUtils.stringArg(args, "controlAddress", null); if (controlAddress != null) { inetAddress = InetAddress.getByName(controlAddress); } if (inetAddress == null) { inetAddress = InetAddress.getLocalHost(); } controlSocket = new ServerSocket(controlPort, 0, inetAddress); controlSocket.setSoTimeout(ServerControlThread.CONTROL_TIMEOUT); } if (Server.logger.isInfoEnabled()) { Server.logger.info("{} running: controlPort={}", new Object[] { WinstoneResourceBundle.getInstance().getString("ServerVersion"), (controlPort > 0 ? Integer.toString(controlPort) : "disabled") }); } // Enter the main loop while (!interrupted) { // this.objectPool.removeUnusedRequestHandlers(); // this.hostGroup.invalidateExpiredSessions(); // Check for control request Socket accepted = null; try { if (controlSocket != null) { accepted = controlSocket.accept(); if (accepted != null) { handleControlRequest(accepted); } } else { Thread.sleep(ServerControlThread.CONTROL_TIMEOUT); } } catch (final InterruptedIOException err) { } catch (final InterruptedException err) { interrupted = Boolean.TRUE; } catch (final Throwable err) { Server.logger.error("Error during listener init or shutdown", err); } finally { if (accepted != null) { try { accepted.close(); } catch (final IOException err) { } } if (Thread.interrupted()) { interrupted = Boolean.TRUE; } } } // Close server socket if (controlSocket != null) { controlSocket.close(); } } catch (final Throwable err) { Server.logger.error("Error during listener init or shutdown", err); } Server.logger.info("Winstone shutdown successfully"); } protected void handleControlRequest(final Socket csAccepted) throws IOException { InputStream inSocket = null; OutputStream outSocket = null; ObjectInputStream inControl = null; try { inSocket = csAccepted.getInputStream(); final int reqType = inSocket.read(); if ((byte) reqType == Command.SHUTDOWN.getCode()) { Server.logger.info("Shutdown request received via the controlPort. Commencing Winstone shutdowny"); shutdown(); } else if ((byte) reqType == Command.RELOAD.getCode()) { inControl = new ObjectInputStream(inSocket); final String host = inControl.readUTF(); final String prefix = inControl.readUTF(); Server.logger.info("Reload request received via the controlPort. Commencing Winstone reload from {}{}", host, prefix); final HostConfiguration hostConfig = hostGroup.getHostByName(host); hostConfig.reloadWebApp(prefix); } else if (cluster != null) { outSocket = csAccepted.getOutputStream(); cluster.clusterRequest((byte) reqType, inSocket, outSocket, csAccepted, hostGroup); } } finally { if (inControl != null) { try { inControl.close(); } catch (final IOException err) { } } if (inSocket != null) { try { inSocket.close(); } catch (final IOException err) { } } if (outSocket != null) { try { outSocket.close(); } catch (final IOException err) { } } } } } /** * @return the controlPort */ public int getControlPort() { return controlPort; } /** * @return the args */ public Map<String, String> getArgs() { return args; } public ObjectPool getObjectPool() throws IllegalStateException { if (!isRunning()) { throw new IllegalStateException("Server is not started"); } return objectPool; } public HostGroup getHostGroup() throws IllegalStateException { if (hostGroup == null) { throw new IllegalStateException("Server is not started"); } return hostGroup; } public JndiManager getJndiManager() throws IllegalStateException { if (!isRunning()) { throw new IllegalStateException("Server is not started"); } return globalJndiManager; } public Cluster getCluster() throws IllegalStateException { if (!isRunning()) { throw new IllegalStateException("Server is not started"); } return cluster; } public List<Listener> getListeners() throws IllegalStateException { if (!isRunning()) { throw new IllegalStateException("Server is not started"); } return Collections.unmodifiableList(listeners); } /** * Log an information message. * * @param message */ public void info(final String message) { logger.info(message); } }
package com.sun.star.wizards.db; import com.sun.star.awt.XWindow; import com.sun.star.lang.XInitialization; import com.sun.star.ui.dialogs.XExecutableDialog; import com.sun.star.lang.IllegalArgumentException; import com.sun.star.lang.WrappedTargetException; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.awt.VclWindowPeerAttribute; import com.sun.star.awt.XWindowPeer; import com.sun.star.beans.PropertyValue; import com.sun.star.beans.UnknownPropertyException; import com.sun.star.beans.XPropertySet; import com.sun.star.container.XChild; import com.sun.star.container.XHierarchicalNameAccess; import com.sun.star.container.XHierarchicalNameContainer; import com.sun.star.container.XNameAccess; import com.sun.star.container.XNameContainer; import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XModel; import com.sun.star.frame.XStorable; import com.sun.star.lang.XComponent; import com.sun.star.sdbc.DataType; import com.sun.star.sdb.XOfficeDatabaseDocument; import com.sun.star.sdb.XDocumentDataSource; import com.sun.star.sdb.tools.XConnectionTools; import com.sun.star.sdbcx.XColumnsSupplier; import com.sun.star.ucb.XSimpleFileAccess; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import com.sun.star.uno.AnyConverter; import com.sun.star.util.XCloseable; import com.sun.star.util.XNumberFormatsSupplier; import com.sun.star.wizards.common.*; import com.sun.star.task.XInteractionHandler; import com.sun.star.sdb.XFormDocumentsSupplier; import com.sun.star.sdb.XQueryDefinitionsSupplier; import com.sun.star.sdb.XReportDocumentsSupplier; import com.sun.star.sdbc.SQLException; import com.sun.star.sdbc.XDatabaseMetaData; import com.sun.star.sdbc.XDataSource; import com.sun.star.sdbc.XResultSet; import com.sun.star.sdbc.XRow; import com.sun.star.sdb.XCompletedConnection; import com.sun.star.lang.Locale; import com.sun.star.lang.XSingleServiceFactory; import com.sun.star.sdb.XQueriesSupplier; import com.sun.star.sdbc.XConnection; import com.sun.star.sdbcx.XTablesSupplier; import com.sun.star.uno.Any; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; public class DBMetaData { private XNameAccess xQueryNames; public XDatabaseMetaData xDBMetaData; private XDataSource m_dataSource; private XPropertySet m_dataSourceSettings; private XOfficeDatabaseDocument xModel; private XPropertySet xDataSourcePropertySet; public String[] DataSourceNames; public String[] CommandNames; public java.util.Vector CommandObjects = new Vector(1); public Locale aLocale; public int[] CommandTypes; public String DataSourceName; public com.sun.star.sdbc.XConnection DBConnection; public com.sun.star.sdb.tools.XConnectionTools ConnectionTools; public com.sun.star.lang.XMultiServiceFactory xMSF; public XComponent xConnectionComponent; public SQLQueryComposer oSQLQueryComposer; private XNameAccess m_xTableNames; private XInteractionHandler oInteractionHandler; private XNameAccess xNameAccess; private XInterface xDatabaseContext; private XCompletedConnection xCompleted; // private int[] nDataTypes = null; private XWindowPeer xWindowPeer; private String[] TableNames = new String[] {}; private String[] QueryNames = new String[] {}; protected int[][] WidthList; protected static final int[] NumericTypes = { DataType.TINYINT, DataType.BIGINT, DataType.NUMERIC, DataType.DECIMAL, DataType.INTEGER, DataType.SMALLINT, DataType.FLOAT, DataType.REAL, DataType.DOUBLE, }; protected static final int[] BinaryTypes = { //new int[12]; DataType.BINARY, DataType.VARBINARY, DataType.LONGVARBINARY, DataType.BLOB, DataType.SQLNULL, DataType.OBJECT, DataType.DISTINCT, DataType.STRUCT, DataType.ARRAY, DataType.CLOB, DataType.REF /* DataType.OTHER, */ }; private int iMaxColumnsInSelect; private int iMaxColumnsInGroupBy; private int iMaxColumnsInTable; private int iMaxColumnNameLength = -1; private int iMaxTableNameLength = -1; private boolean bPasswordIsRequired; private final static int NOLIMIT = 9999999; protected final static int RID_DB_COMMON = 1000; private final static int INVALID = 9999999; public TypeInspector oTypeInspector; private NumberFormatter oNumberFormatter = null; private long lDateCorrection = INVALID; private boolean bdisposeConnection = false; public XPropertySet getDataSourcePropertySet() { return xDataSourcePropertySet; } public DBMetaData(XMultiServiceFactory xMSF) { getInterfaces(xMSF); InitializeWidthList(); } public DBMetaData(XMultiServiceFactory xMSF, Locale _aLocale, NumberFormatter _oNumberFormatter) { oNumberFormatter = _oNumberFormatter; aLocale = _aLocale; getInterfaces(xMSF); InitializeWidthList(); } public NumberFormatter getNumberFormatter() { if (oNumberFormatter == null) { try { XNumberFormatsSupplier xNumberFormatsSupplier = (XNumberFormatsSupplier) AnyConverter.toObject(XNumberFormatsSupplier.class, xDataSourcePropertySet.getPropertyValue("NumberFormatsSupplier")); //TODO get the locale from the datasource aLocale = Configuration.getOfficeLocale(xMSF); oNumberFormatter = new NumberFormatter(xMSF, xNumberFormatsSupplier, aLocale); lDateCorrection = oNumberFormatter.getNullDateCorrection(); } catch (Exception e) { e.printStackTrace(System.out); } } return oNumberFormatter; } public long getNullDateCorrection() { if (lDateCorrection == INVALID) { if (oNumberFormatter == null) { oNumberFormatter = getNumberFormatter(); } lDateCorrection = oNumberFormatter.getNullDateCorrection(); } return lDateCorrection; } void getInterfaces(XMultiServiceFactory xMSF) { try { this.xMSF = xMSF; xDatabaseContext = (XInterface) xMSF.createInstance("com.sun.star.sdb.DatabaseContext"); xNameAccess = UnoRuntime.queryInterface(XNameAccess.class, xDatabaseContext); XInterface xInteractionHandler = (XInterface) xMSF.createInstance("com.sun.star.sdb.InteractionHandler"); oInteractionHandler = UnoRuntime.queryInterface(XInteractionHandler.class, xInteractionHandler); DataSourceNames = xNameAccess.getElementNames(); } catch (Exception exception) { exception.printStackTrace(System.out); } } public void setCommandTypes() { int TableCount; int QueryCount; int CommandCount; int i; int a; TableCount = JavaTools.getArraylength(TableNames); QueryCount = JavaTools.getArraylength(QueryNames); CommandCount = TableCount + QueryCount; CommandTypes = new int[CommandCount]; if (TableCount > 0) { for (i = 0; i < TableCount; i++) { CommandTypes[i] = com.sun.star.sdb.CommandType.TABLE; } a = i; for (i = 0; i < QueryCount; i++) { CommandTypes[a] = com.sun.star.sdb.CommandType.QUERY; a += 1; } } } public boolean hasTableByName(String _stablename) { // getTableNames(); return getTableNamesAsNameAccess().hasByName(_stablename); } public void setTableByName(String _tableName) { CommandObject oTableObject = new CommandObject(_tableName, com.sun.star.sdb.CommandType.TABLE); this.CommandObjects.addElement(oTableObject); } public CommandObject getTableByName(String _tablename) { return getCommandByName(_tablename, com.sun.star.sdb.CommandType.TABLE); } public CommandObject getQueryByName(String _queryname) { return getCommandByName(_queryname, com.sun.star.sdb.CommandType.QUERY); } public CommandObject getCommandByName(String _commandname, int _commandtype) { CommandObject oCommand = null; for (int i = 0; i < CommandObjects.size(); i++) { oCommand = (CommandObject) CommandObjects.elementAt(i); if ((oCommand.Name.equals(_commandname)) && (oCommand.CommandType == _commandtype)) { return oCommand; } } if (oCommand == null) { oCommand = new CommandObject(_commandname, _commandtype); CommandObjects.addElement(oCommand); } return oCommand; } public void setQueryByName(String _QueryName) { CommandObject oQueryObject = new CommandObject(_QueryName, com.sun.star.sdb.CommandType.QUERY); this.CommandObjects.addElement(oQueryObject); } public class CommandObject { private XNameAccess xColumns; private XPropertySet xPropertySet; private String Name; private int CommandType; public CommandObject(String _CommandName, int _CommandType) { try { Object oCommand; this.Name = _CommandName; this.CommandType = _CommandType; // if (getTableNamesAsNameAccess() == null) // initCommandNames(); if (CommandType == com.sun.star.sdb.CommandType.TABLE) { oCommand = getTableNamesAsNameAccess().getByName(Name); } else { oCommand = getQueryNamesAsNameAccess().getByName(Name); } XColumnsSupplier xCommandCols = UnoRuntime.queryInterface(XColumnsSupplier.class, oCommand); xPropertySet = UnoRuntime.queryInterface(XPropertySet.class, oCommand); // TODO: Performance leak getColumns() take very long. xColumns = UnoRuntime.queryInterface(XNameAccess.class, xCommandCols.getColumns()); } catch (Exception exception) { exception.printStackTrace(System.out); } } public XNameAccess getColumns() { return xColumns; } public String getName() { return Name; } public XPropertySet getPropertySet() { return xPropertySet; } } public boolean hasEscapeProcessing(XPropertySet _xQueryPropertySet) { boolean bHasEscapeProcessing = false; try { if (_xQueryPropertySet.getPropertySetInfo().hasPropertyByName("EscapeProcessing")) { bHasEscapeProcessing = AnyConverter.toBoolean(_xQueryPropertySet.getPropertyValue("EscapeProcessing")); } } catch (Exception e) { e.printStackTrace(System.out); } return bHasEscapeProcessing; } // public void initCommandNames() // getTableNames(); public XNameAccess getQueryNamesAsNameAccess() { XQueriesSupplier xDBQueries = (XQueriesSupplier) UnoRuntime.queryInterface(XQueriesSupplier.class, DBConnection); xQueryNames = xDBQueries.getQueries(); return xQueryNames; } public XNameAccess getTableNamesAsNameAccess() { XTablesSupplier xDBTables = UnoRuntime.queryInterface(XTablesSupplier.class, DBConnection); XNameAccess xTableNames = xDBTables.getTables(); return xTableNames; } public String[] getQueryNames() { if (QueryNames != null) { if (QueryNames.length > 0) { return QueryNames; } } QueryNames = getQueryNamesAsNameAccess().getElementNames(); return QueryNames; } public String[] getTableNames() { if (TableNames != null) { if (TableNames.length > 0) { return TableNames; } } TableNames = getTableNamesAsNameAccess().getElementNames(); return TableNames; } void InitializeWidthList() { WidthList = new int[17][2]; WidthList[0][0] = DataType.BIT; WidthList[1][0] = DataType.BOOLEAN; WidthList[2][0] = DataType.TINYINT; WidthList[3][0] = DataType.BIGINT; WidthList[4][0] = DataType.LONGVARCHAR; WidthList[5][0] = DataType.CHAR; WidthList[6][0] = DataType.NUMERIC; WidthList[7][0] = DataType.DECIMAL; // == 3; [mit Nachkommastellen] WidthList[8][0] = DataType.INTEGER; WidthList[9][0] = DataType.SMALLINT; WidthList[10][0] = DataType.FLOAT; WidthList[11][0] = DataType.REAL; WidthList[12][0] = DataType.DOUBLE; WidthList[13][0] = DataType.VARCHAR; WidthList[14][0] = DataType.DATE; WidthList[15][0] = DataType.TIME; WidthList[16][0] = DataType.TIMESTAMP; // NumericTypes are all types where aggregate functions can be performed on. // Similarly to a major competitor date/time/timmestamp fields are not included } public boolean isBinaryDataType(int _itype) { if (NumericTypes == null) { InitializeWidthList(); } return (JavaTools.FieldInIntTable(BinaryTypes, _itype) > -1); } public int getMaxTablesInSelect() { try { int itablecount = xDBMetaData.getMaxTablesInSelect(); if (itablecount == 0) { return DBMetaData.NOLIMIT; } else { return itablecount; } } catch (SQLException e) { e.printStackTrace(System.out); return - 1; } } public int getMaxColumnsInSelect() { return iMaxColumnsInSelect; } public int getMaxColumnsInGroupBy() { return iMaxColumnsInGroupBy; } private void setMaxColumnsInSelect() throws SQLException { iMaxColumnsInSelect = xDBMetaData.getMaxColumnsInSelect(); if (iMaxColumnsInSelect == 0) { iMaxColumnsInSelect = DBMetaData.NOLIMIT; } } private void setMaxColumnsInGroupBy() throws SQLException { iMaxColumnsInGroupBy = xDBMetaData.getMaxColumnsInGroupBy(); if (iMaxColumnsInGroupBy == 0) { iMaxColumnsInGroupBy = DBMetaData.NOLIMIT; } } public int getMaxColumnsInTable() throws SQLException { iMaxColumnsInTable = xDBMetaData.getMaxColumnsInTable(); if (iMaxColumnsInTable == 0) { iMaxColumnsInTable = DBMetaData.NOLIMIT; } return iMaxColumnsInTable; } private void getDataSourceObjects() throws Exception { try { xDBMetaData = DBConnection.getMetaData(); XChild xChild = UnoRuntime.queryInterface( XChild.class, DBConnection ); getDataSourceInterfaces(); setMaxColumnsInGroupBy(); setMaxColumnsInSelect(); } catch (SQLException e) { e.printStackTrace(System.out); } } private void ensureDataSourceSettings() throws UnknownPropertyException, WrappedTargetException { if ( m_dataSourceSettings != null ) return; XPropertySet dataSourceProperties = UnoRuntime.queryInterface( XPropertySet.class, getDataSource() ); m_dataSourceSettings = UnoRuntime.queryInterface( XPropertySet.class, dataSourceProperties.getPropertyValue( "Settings" ) ); } public boolean isSQL92CheckEnabled() { boolean isSQL92CheckEnabled = false; try { ensureDataSourceSettings(); isSQL92CheckEnabled = AnyConverter.toBoolean( m_dataSourceSettings.getPropertyValue( "EnableSQL92Check" ) ); } catch (Exception e) { e.printStackTrace(); } return isSQL92CheckEnabled; } public String verifyName(String _sname, int _maxlen) { if (_sname.length() > _maxlen) { return _sname.substring(0, _maxlen); } if (this.isSQL92CheckEnabled()) { return Desktop.removeSpecialCharacters(xMSF, Configuration.getOfficeLocale(xMSF), _sname); } return _sname; } public XDataSource getDataSource() { if (m_dataSource == null) { try { Object oDataSource = xNameAccess.getByName(DataSourceName); m_dataSource = UnoRuntime.queryInterface( XDataSource.class, oDataSource ); } catch (com.sun.star.container.NoSuchElementException e) { } catch (com.sun.star.lang.WrappedTargetException e) { } } return m_dataSource; } private void setDataSourceByName(String _DataSourceName, boolean bgetInterfaces) { try { this.DataSourceName = _DataSourceName; getDataSourceInterfaces(); XDocumentDataSource xDocu = UnoRuntime.queryInterface( XDocumentDataSource.class, getDataSource() ); if (xDocu != null) { xModel = xDocu.getDatabaseDocument(); } } catch (Exception exception) { exception.printStackTrace(System.out); } } public void getDataSourceInterfaces() throws Exception { xCompleted = UnoRuntime.queryInterface( XCompletedConnection.class, getDataSource() ); xDataSourcePropertySet = UnoRuntime.queryInterface( XPropertySet.class, getDataSource() ); bPasswordIsRequired = ((Boolean) xDataSourcePropertySet.getPropertyValue("IsPasswordRequired")).booleanValue(); } public boolean getConnection(PropertyValue[] curproperties) { try { XConnection xConnection = null; if (Properties.hasPropertyValue(curproperties, "ActiveConnection")) { xConnection = UnoRuntime.queryInterface( XConnection.class, Properties.getPropertyValue( curproperties, "ActiveConnection" ) ); if (xConnection != null) { com.sun.star.container.XChild child = UnoRuntime.queryInterface( com.sun.star.container.XChild.class, xConnection ); m_dataSource = UnoRuntime.queryInterface( XDataSource.class, child.getParent() ); XDocumentDataSource xDocu = UnoRuntime.queryInterface( XDocumentDataSource.class, m_dataSource ); if (xDocu != null) { xModel = xDocu.getDatabaseDocument(); } XPropertySet xPSet = UnoRuntime.queryInterface( XPropertySet.class, m_dataSource ); if (xPSet != null) { DataSourceName = AnyConverter.toString(xPSet.getPropertyValue("Name")); } return getConnection(xConnection); } else { bdisposeConnection = true; } } else { bdisposeConnection = true; } if (Properties.hasPropertyValue(curproperties, "DataSourceName")) { String sDataSourceName = AnyConverter.toString(Properties.getPropertyValue(curproperties, "DataSourceName")); return getConnection(sDataSourceName); } else if (Properties.hasPropertyValue(curproperties, "DataSource")) { m_dataSource = UnoRuntime.queryInterface( XDataSource.class, Properties.getPropertyValue( curproperties, "DataSource" ) ); XDocumentDataSource xDocu = UnoRuntime.queryInterface( XDocumentDataSource.class, this.m_dataSource ); if (xDocu != null) { xModel = xDocu.getDatabaseDocument(); } return getConnection(m_dataSource); } if (Properties.hasPropertyValue(curproperties, "DatabaseLocation")) { String sDataSourceName = AnyConverter.toString(Properties.getPropertyValue(curproperties, "DatabaseLocation")); return getConnection(sDataSourceName); } else if (xConnection != null) { bdisposeConnection = false; return getConnection(xConnection); } } catch (IllegalArgumentException e) { e.printStackTrace(System.out); } catch (UnknownPropertyException e) { e.printStackTrace(System.out); } catch (WrappedTargetException e) { e.printStackTrace(System.out); } return false; } private boolean getConnection(String _DataSourceName) { setDataSourceByName(_DataSourceName, true); return getConnection( getDataSource() ); } private boolean getConnection(com.sun.star.sdbc.XConnection _DBConnection) { try { this.DBConnection = _DBConnection; this.ConnectionTools = UnoRuntime.queryInterface( XConnectionTools.class, this.DBConnection ); getDataSourceObjects(); return true; } catch (Exception e) { e.printStackTrace(System.out); return false; } } private boolean getConnection(XDataSource _dataSource) { Resource oResource = new Resource(xMSF, "Database", "dbw"); try { int iMsg = 0; boolean bgetConnection = false; if (DBConnection != null) { xConnectionComponent.dispose(); } getDataSourceInterfaces(); if (bPasswordIsRequired == false) { DBConnection = _dataSource.getConnection("", ""); bgetConnection = true; } else { XInteractionHandler xInteractionHandler = UnoRuntime.queryInterface( XInteractionHandler.class, xMSF.createInstance("com.sun.star.sdb.InteractionHandler") ); boolean bExitLoop = true; do { XCompletedConnection xCompleted2 = UnoRuntime.queryInterface( XCompletedConnection.class, _dataSource ); try { DBConnection = xCompleted2.connectWithCompletion( xInteractionHandler ); bgetConnection = DBConnection != null; if (bgetConnection == false) { bExitLoop = true; } } catch (Exception exception) { // Note: WindowAttributes from toolkit/source/awt/vclxtoolkit.cxx String sMsgNoConnection = oResource.getResText(RID_DB_COMMON + 14); iMsg = showMessageBox("QueryBox", VclWindowPeerAttribute.RETRY_CANCEL, sMsgNoConnection); bExitLoop = iMsg == 0; bgetConnection = false; } } while (bExitLoop == false); } if (bgetConnection == false) { String sMsgConnectionImpossible = oResource.getResText(RID_DB_COMMON + 35); showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, sMsgConnectionImpossible); } else { xConnectionComponent = UnoRuntime.queryInterface( XComponent.class, DBConnection ); ConnectionTools = UnoRuntime.queryInterface( XConnectionTools.class, DBConnection ); getDataSourceObjects(); } return bgetConnection; } catch (Exception exception) { String sMsgConnectionImpossible = oResource.getResText(RID_DB_COMMON + 35); showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, sMsgConnectionImpossible); exception.printStackTrace(System.out); return false; } } public int getMaxColumnNameLength() { try { if (iMaxColumnNameLength <= 0) { iMaxColumnNameLength = xDBMetaData.getMaxColumnNameLength(); } return iMaxColumnNameLength; } catch (SQLException e) { e.printStackTrace(System.out); return 0; } } public int getMaxTableNameLength() { try { if (iMaxTableNameLength <= 0) { iMaxTableNameLength = xDBMetaData.getMaxTableNameLength(); } return iMaxTableNameLength; } catch (SQLException e) { e.printStackTrace(System.out); return 0; } } public boolean supportsPrimaryKeys() { boolean supportsPrimaryKeys = false; try { ensureDataSourceSettings(); Any primaryKeySupport = (Any)m_dataSourceSettings.getPropertyValue( "PrimaryKeySupport" ); if ( AnyConverter.isVoid( primaryKeySupport ) ) supportsPrimaryKeys = supportsCoreSQLGrammar(); else supportsPrimaryKeys = AnyConverter.toBoolean( primaryKeySupport ); } catch ( Exception ex ) { Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, ex ); } return supportsPrimaryKeys; } public boolean supportsCoreSQLGrammar() { try { return xDBMetaData.supportsCoreSQLGrammar(); } catch (SQLException e) { e.printStackTrace(System.out); return false; } } public boolean supportsAutoIncrementation() { return false; } /** * inserts a Query to a datasource; There is no validation if the queryname is already existing in the datasource * @param oQuery * @param QueryName */ public boolean createQuery(SQLQueryComposer _oSQLQueryComposer, String _QueryName) { try { XQueryDefinitionsSupplier xQueryDefinitionsSuppl = UnoRuntime.queryInterface( XQueryDefinitionsSupplier.class, m_dataSource ); XNameAccess xQueryDefs = xQueryDefinitionsSuppl.getQueryDefinitions(); XSingleServiceFactory xSSFQueryDefs = UnoRuntime.queryInterface( XSingleServiceFactory.class, xQueryDefs ); Object oQuery = xSSFQueryDefs.createInstance(); //"com.sun.star.sdb.QueryDefinition" XPropertySet xPSet = UnoRuntime.queryInterface( XPropertySet.class, oQuery ); String s = _oSQLQueryComposer.m_xQueryAnalyzer.getQuery(); xPSet.setPropertyValue("Command", s); XNameContainer xNameCont = UnoRuntime.queryInterface( XNameContainer.class, xQueryDefs ); XNameAccess xNameAccess = UnoRuntime.queryInterface( XNameAccess.class, xQueryDefs ); ConnectionTools.getObjectNames().checkNameForCreate(com.sun.star.sdb.CommandType.QUERY, _QueryName); xNameCont.insertByName(_QueryName, oQuery); return true; } catch (WrappedTargetException exception) { SQLException sqlError = null; try { sqlError = (SQLException) exception.TargetException; } catch (ClassCastException castError) { } if (sqlError != null) { callSQLErrorMessageDialog(sqlError, null); return false; } exception.printStackTrace(System.out); } catch (SQLException exception) { callSQLErrorMessageDialog(exception, null); } catch (Exception exception) { exception.printStackTrace(System.out); } return false; } public void dispose() { if ((DBConnection != null) && (this.bdisposeConnection)) { xConnectionComponent.dispose(); } } public XHierarchicalNameAccess getReportDocuments() { XReportDocumentsSupplier xReportDocumentSuppl = UnoRuntime.queryInterface( XReportDocumentsSupplier.class, this.xModel ); xReportDocumentSuppl.getReportDocuments(); XHierarchicalNameAccess xReportHier = UnoRuntime.queryInterface( XHierarchicalNameAccess.class, xReportDocumentSuppl.getReportDocuments() ); return xReportHier; } public XHierarchicalNameAccess getFormDocuments() { XFormDocumentsSupplier xFormDocumentSuppl = UnoRuntime.queryInterface( XFormDocumentsSupplier.class, xModel ); XHierarchicalNameAccess xFormHier = UnoRuntime.queryInterface( XHierarchicalNameAccess.class, xFormDocumentSuppl.getFormDocuments() ); return xFormHier; } public boolean hasFormDocumentByName(String _sFormName) { XFormDocumentsSupplier xFormDocumentSuppl = UnoRuntime.queryInterface( XFormDocumentsSupplier.class, xModel ); XNameAccess xFormNameAccess = UnoRuntime.queryInterface( XNameAccess.class, xFormDocumentSuppl.getFormDocuments() ); return xFormNameAccess.hasByName(_sFormName); } public void addFormDocument(XComponent _xComponent) { XHierarchicalNameAccess _xFormDocNameAccess = getFormDocuments(); addDatabaseDocument(_xComponent, _xFormDocNameAccess, false); } public void addReportDocument(XComponent _xComponent, boolean _bcreatedynamicreport) { XHierarchicalNameAccess xReportDocNameAccess = getReportDocuments(); addDatabaseDocument(_xComponent, xReportDocNameAccess, _bcreatedynamicreport); } /** * adds the passed document as a report or a form to the database. Afterwards the document is deleted. * the document may not be open * @param _xComponent * @param _xDocNameAccess * @param _bcreateTemplate describes the type of the document: "form" or "report" */ public void addDatabaseDocument(XComponent _xComponent, XHierarchicalNameAccess _xDocNameAccess, boolean _bcreateTemplate) { try { PropertyValue[] aDocProperties; XModel xDocumentModel = UnoRuntime.queryInterface( XModel.class, _xComponent ); String sPath = xDocumentModel.getURL(); String basename = FileAccess.getBasename(sPath, "/"); XCloseable xCloseable = UnoRuntime.queryInterface( XCloseable.class, _xComponent ); _xComponent.dispose(); xCloseable.close(false); if (_bcreateTemplate) { aDocProperties = new PropertyValue[5]; } else { aDocProperties = new PropertyValue[4]; } aDocProperties[0] = Properties.createProperty("Name", basename); aDocProperties[1] = Properties.createProperty("Parent", _xDocNameAccess); aDocProperties[2] = Properties.createProperty("URL", sPath); aDocProperties[3] = Properties.createProperty("DocumentTitle", basename); if (_bcreateTemplate) { aDocProperties[4] = Properties.createProperty("AsTemplate", new Boolean(_bcreateTemplate)); } XMultiServiceFactory xDocMSF = UnoRuntime.queryInterface( XMultiServiceFactory.class, _xDocNameAccess ); Object oDBDocument = xDocMSF.createInstanceWithArguments("com.sun.star.sdb.DocumentDefinition", aDocProperties); XHierarchicalNameContainer xHier = UnoRuntime.queryInterface( XHierarchicalNameContainer.class, _xDocNameAccess ); String sdocname = Desktop.getUniqueName(_xDocNameAccess, basename); xHier.insertByHierarchicalName(sdocname, oDBDocument); XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess"); XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface( XSimpleFileAccess.class, xInterface ); xSimpleFileAccess.kill(sPath); } catch (Exception e) { e.printStackTrace(System.out); } } public XComponent[] openDatabaseDocument(String _docname, boolean _bAsTemplate, boolean _bOpenInDesign, XHierarchicalNameAccess _xDocuments) { XComponent[] xRetComponent = new XComponent[2]; try { XComponentLoader xComponentLoader = UnoRuntime.queryInterface( XComponentLoader.class, _xDocuments ); PropertyValue[] aPropertyValues = new PropertyValue[4]; aPropertyValues[0] = Properties.createProperty("OpenMode", _bOpenInDesign ? "openDesign" : "open"); aPropertyValues[1] = Properties.createProperty("ActiveConnection", this.DBConnection); aPropertyValues[2] = Properties.createProperty("DocumentTitle", _docname); aPropertyValues[3] = Properties.createProperty("AsTemplate", new Boolean(_bAsTemplate)); XHierarchicalNameContainer xHier = UnoRuntime.queryInterface( XHierarchicalNameContainer.class, _xDocuments ); if (xHier.hasByHierarchicalName(_docname)) { xRetComponent[0] = UnoRuntime.queryInterface( XComponent.class, xHier.getByHierarchicalName( _docname ) ); xRetComponent[1] = xComponentLoader.loadComponentFromURL(_docname, "", 0, aPropertyValues); } } catch (Exception e) { e.printStackTrace(System.out); } return xRetComponent; } public XComponent[] openFormDocument(String _sformname, boolean _bOpenInDesign) { XHierarchicalNameAccess xFormDocuments = getFormDocuments(); return openDatabaseDocument(_sformname, false, _bOpenInDesign, xFormDocuments); } public XComponent[] openReportDocument(String _sreportname, boolean _bAsTemplate, boolean _bOpenInDesign) { XHierarchicalNameAccess xReportDocuments = getReportDocuments(); return openDatabaseDocument(_sreportname, _bAsTemplate, _bOpenInDesign, xReportDocuments); } public void createTypeInspector() throws SQLException { oTypeInspector = new TypeInspector(xDBMetaData.getTypeInfo()); } public TypeInspector getDBDataTypeInspector() { return oTypeInspector; } private String[] StringsFromResultSet(XResultSet _xResultSet, int _icol) { String[] sColValues = null; try { XRow xRow = UnoRuntime.queryInterface( XRow.class, _xResultSet ); Vector aColVector = new Vector(); while (_xResultSet.next()) { aColVector.addElement(xRow.getString(_icol)); } sColValues = new String[aColVector.size()]; aColVector.toArray(sColValues); } catch (SQLException e) { e.printStackTrace(); } return sColValues; } public String[] getCatalogNames() { try { XResultSet xResultSet = xDBMetaData.getCatalogs(); return StringsFromResultSet(xResultSet, 1); } catch (SQLException e) { e.printStackTrace(System.out); return null; } } public String[] getSchemaNames() { try { XResultSet xResultSet = xDBMetaData.getSchemas(); return StringsFromResultSet(xResultSet, 1); } catch (SQLException e) { e.printStackTrace(System.out); return null; } } public boolean storeDatabaseDocumentToTempPath(XComponent _xcomponent, String _storename) { try { XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess"); XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface( XSimpleFileAccess.class, xInterface ); String storepath = FileAccess.getOfficePath(xMSF, "Temp", xSimpleFileAccess) + "/" + _storename; XStorable xStoreable = UnoRuntime.queryInterface( XStorable.class, _xcomponent ); PropertyValue[] oStoreProperties = new PropertyValue[1]; oStoreProperties[0] = Properties.createProperty("FilterName", "writer8"); storepath += ".odt"; xStoreable.storeAsURL(storepath, oStoreProperties); return true; } catch (Exception e) { e.printStackTrace(System.out); return false; } } public int showMessageBox(String windowServiceName, int windowAttribute, String MessageText) { if (getWindowPeer() != null) { return SystemDialog.showMessageBox(xMSF, xWindowPeer, windowServiceName, windowAttribute, MessageText); } else { return SystemDialog.showMessageBox(xMSF, windowServiceName, windowAttribute, MessageText); } } /** * @return Returns the xWindowPeer. */ public XWindowPeer getWindowPeer() { return xWindowPeer; } /** * @param windowPeer The xWindowPeer to set. * Should be called as soon as a Windowpeer of a wizard dialog is available * The windowpeer is needed to call a Messagebox */ public void setWindowPeer(XWindowPeer windowPeer) { xWindowPeer = windowPeer; } public void callSQLErrorMessageDialog(SQLException oSQLException, XWindow _xWindow) { try { Object oDialog = xMSF.createInstance("com.sun.star.sdb.ErrorMessageDialog"); XInitialization xInitialization = UnoRuntime.queryInterface( XInitialization.class, oDialog ); PropertyValue[] aPropertyValue = new PropertyValue[2]; aPropertyValue[0] = Properties.createProperty("SQLException", oSQLException); aPropertyValue[1] = Properties.createProperty("ParentWindow", _xWindow); xInitialization.initialize(aPropertyValue); XExecutableDialog xExecutableDialog = UnoRuntime.queryInterface( XExecutableDialog.class, oDialog ); xExecutableDialog.execute(); } catch (com.sun.star.uno.Exception ex) { ex.printStackTrace(); } } public void finish() { xQueryNames = null; oInteractionHandler = null; xNameAccess = null; xDatabaseContext = null; xDBMetaData = null; m_dataSource = null; xModel = null; xCompleted = null; xDataSourcePropertySet = null; xWindowPeer = null; DBConnection = null; ConnectionTools = null; xMSF = null; xConnectionComponent = null; oSQLQueryComposer = null; CommandObjects = null; } }
package org.openlca.app.editors.graphical.command; import org.eclipse.gef.commands.Command; import org.openlca.app.Messages; import org.openlca.app.editors.graphical.model.ProcessNode; public class ExpansionCommand extends Command { final static int EXPAND = 1; final static int COLLAPSE = 2; final static int LEFT = 1; final static int RIGHT = 2; private ProcessNode node; private int side; private int type; ExpansionCommand(int type, int side) { this.side = side; this.type = type; } @Override public boolean canExecute() { if (side != LEFT && side != RIGHT) return false; if (type != EXPAND && type != COLLAPSE) return false; return true; } @Override public boolean canUndo() { return false; } @Override public void execute() { if (type == EXPAND) { if (side == LEFT) node.expandLeft(); else if (side == RIGHT) node.expandRight(); } else if (type == COLLAPSE) { if (side == LEFT) node.collapseLeft(); else if (side == RIGHT) node.collapseRight(); } node.layout(); node.getParent().getEditor().setDirty(true); node.select(); node.reveal(); } @Override public String getLabel() { if (type == EXPAND) return Messages.Systems_ExpansionCommand_ExpandText; else if (type == COLLAPSE) return Messages.Systems_ExpansionCommand_CollapseText; return null; } void setNode(ProcessNode node) { this.node = node; } }
package it.unibz.krdb.obda.gui; import org.semanticweb.ontop.protege.utils.OptionPaneUtils; import javax.swing.*; public class PrettyOptionPaneTest { public static void main(String[] args) { String longMessage = "Here we have an test to show when PrettyOptionPane can be really useful. "+ "This text is super long and it will take a few lines to get everything that is written here. " + "It looks really horrible when the default JOption pane is used. " + "It is is better to create a PrettyOptionPane that reduces the default size of the window and makes it looks really pretty. "; // create a jframe JFrame frame = new JFrame("JOptionPane showPrettyMessageDialog example"); // show a joptionpane dialog using showPrettyMessageDialog OptionPaneUtils.showPrettyMessageDialog(frame, longMessage, "Error", JOptionPane.ERROR_MESSAGE); System.exit(0); } }
package org.opennms.netmgt.collectd; import java.util.Collection; import java.util.Iterator; import org.apache.log4j.Category; import org.opennms.core.utils.ThreadCategory; public class AliasedGroup extends AttributeGroup { AttributeGroup m_group; public AliasedGroup(CollectionResource resource, AttributeGroup group) { super(resource, group.getGroupType()); m_group = group; } public void addAttribute(Attribute attr) { m_group.addAttribute(attr); } public boolean equals(Object obj) { return m_group.equals(obj); } public Collection getAttributes() { return m_group.getAttributes(); } public AttributeGroupType getGroupType() { return m_group.getGroupType(); } public String getName() { return m_group.getName(); } public int hashCode() { return m_group.hashCode(); } public boolean shouldPersist(ServiceParameters params) { return m_group.shouldPersist(params); } public String toString() { return m_group.toString(); } Category log(){ return ThreadCategory.getInstance(getClass()); } public void visit(CollectionSetVisitor visitor) { visitor.visitGroup(this); for (Iterator iter = getAttributes().iterator(); iter.hasNext();) { Attribute attr = (Attribute) iter.next(); AliasedAttribute aliased = new AliasedAttribute(getResource(), attr); log().debug("visiting at aliased = " + aliased); aliased.visit(visitor); } visitor.completeGroup(this); } }
//This file is part of the OpenNMS(R) Application. //OpenNMS(R) is a derivative work, containing both original code, included code and modified //and included code are below. //OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. //This program is free software; you can redistribute it and/or modify //(at your option) any later version. //This program is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //along with this program; if not, write to the Free Software //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //For more information contact: package org.opennms.netmgt.collectd; import java.io.InputStreamReader; import java.util.Collections; import java.util.List; import java.util.Map; import org.jmock.Mock; import org.jmock.cglib.MockObjectTestCase; import org.opennms.netmgt.config.CollectdPackage; import org.opennms.netmgt.config.DataSourceFactory; import org.opennms.netmgt.config.DatabaseSchemaConfigFactory; import org.opennms.netmgt.config.PollOutagesConfigFactory; import org.opennms.netmgt.config.collectd.Collector; import org.opennms.netmgt.config.collectd.Filter; import org.opennms.netmgt.config.collectd.Package; import org.opennms.netmgt.config.collectd.Parameter; import org.opennms.netmgt.config.collectd.Service; import org.opennms.netmgt.dao.CollectorConfigDao; import org.opennms.netmgt.dao.IpInterfaceDao; import org.opennms.netmgt.dao.MonitoredServiceDao; import org.opennms.netmgt.eventd.EventIpcManager; import org.opennms.netmgt.mock.MockDatabase; import org.opennms.netmgt.mock.MockNetwork; import org.opennms.netmgt.model.OnmsIpInterface; import org.opennms.netmgt.model.OnmsNode; import org.opennms.netmgt.poller.mock.MockScheduler; import org.opennms.netmgt.scheduler.Scheduler; import org.opennms.netmgt.utils.EventProxy; import org.opennms.test.mock.MockLogAppender; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class CollectdTest extends MockObjectTestCase { private Collectd m_collectd; private Mock m_eventIpcManager; private Mock m_collectorConfigDao; private Mock m_ipIfDao; private Mock m_monSvcDao; private Mock m_collector; private MockScheduler m_scheduler; private CollectionSpecification m_spec; protected void setUp() throws Exception { MockLogAppender.setupLogging(); // Test setup m_eventIpcManager = mock(EventIpcManager.class); m_collectorConfigDao = mock(CollectorConfigDao.class); m_ipIfDao = mock(IpInterfaceDao.class); m_monSvcDao = mock(MonitoredServiceDao.class); m_collector = mock(ServiceCollector.class); m_scheduler = new MockScheduler(); m_eventIpcManager.stubs(); MockNetwork m_network = new MockNetwork(); m_network.setCriticalService("ICMP"); m_network.addNode(1, "Router"); m_network.addInterface("192.168.1.1"); m_network.addService("ICMP"); m_network.addService("SMTP"); m_network.addInterface("192.168.1.2"); m_network.addService("ICMP"); m_network.addService("SMTP"); m_network.addNode(2, "Server"); m_network.addInterface("192.168.1.3"); m_network.addService("ICMP"); m_network.addService("HTTP"); m_network.addNode(3, "Firewall"); m_network.addInterface("192.168.1.4"); m_network.addService("SMTP"); m_network.addService("HTTP"); m_network.addInterface("192.168.1.5"); m_network.addService("SMTP"); m_network.addService("HTTP"); MockDatabase m_db = new MockDatabase(); m_db.populate(m_network); DataSourceFactory.setInstance(m_db); Resource dbConfig = new ClassPathResource("/org/opennms/netmgt/config/test-database-schema.xml"); InputStreamReader r = new InputStreamReader(dbConfig.getInputStream()); DatabaseSchemaConfigFactory dscf = new DatabaseSchemaConfigFactory(r); r.close(); DatabaseSchemaConfigFactory.setInstance(dscf); Resource resource = new ClassPathResource("etc/poll-outages.xml"); InputStreamReader pollOutagesRdr = new InputStreamReader(resource.getInputStream()); PollOutagesConfigFactory.setInstance(new PollOutagesConfigFactory(pollOutagesRdr)); pollOutagesRdr.close(); m_collectd = new Collectd(); m_collectd.setEventIpcManager(getEventIpcManager()); m_collectd.setCollectorConfigDao(getCollectorConfigDao()); m_collectd.setIpInterfaceDao(getIpInterfaceDao()); m_collectd.setMonitoredServiceDao(getMonitoredServiceDao()); m_collectd.setScheduler(m_scheduler); Package pkg = new Package(); pkg.setName("pkg"); Filter filter = new Filter(); filter.setContent("IPADDR IPLIKE *.*.*.*"); pkg.setFilter(filter); Service svc = new Service(); pkg.addService(svc); svc.setName("SNMP"); Parameter parm = new Parameter(); parm.setKey("parm1"); parm.setValue("value1"); svc.addParameter(parm); CollectdPackage wpkg = new CollectdPackage(pkg, "localhost", false); m_spec = new CollectionSpecification(wpkg, "SNMP", null, getCollector()); } private ServiceCollector getCollector() { return (ServiceCollector)m_collector.proxy(); } private MonitoredServiceDao getMonitoredServiceDao() { return (MonitoredServiceDao)m_monSvcDao.proxy(); } private IpInterfaceDao getIpInterfaceDao() { return (IpInterfaceDao)m_ipIfDao.proxy(); } private CollectorConfigDao getCollectorConfigDao() { return (CollectorConfigDao)m_collectorConfigDao.proxy(); } private EventIpcManager getEventIpcManager() { return (EventIpcManager)m_eventIpcManager.proxy(); } private CollectionSpecification getCollectionSpecification() { return m_spec; } private OnmsIpInterface getInterface() { OnmsNode node = new OnmsNode(); node.setId(new Integer(1)); OnmsIpInterface iface = new OnmsIpInterface("192.168.1.1", node); return iface; } protected void tearDown() throws Exception { // TODO Auto-generated method stub super.tearDown(); } public void testCreate() { String svcName = "SNMP"; setupCollector(svcName); Mock m_scheduler = mock(Scheduler.class); m_collectd.setScheduler((Scheduler)m_scheduler.proxy()); m_scheduler.expects(once()).method("schedule").with(eq(0L), ANYTHING); m_collectd.init(); m_scheduler.expects(once()).method("start"); m_collectd.start(); m_scheduler.expects(once()).method("stop"); m_collectd.stop(); } public void FIXMEtestScheduling() { FIXMEtestNoMatchingSpecs(); } public void FIXMEtestNoMatchingSpecs() { m_collectd.init(); m_collectd.start(); String svcName = "SNMP"; OnmsIpInterface iface = getInterface(); List specs = Collections.EMPTY_LIST; setupCollector(svcName); setupInterface(iface); setupSpecs(iface, svcName, specs); m_scheduler.next(); assertEquals(0, m_scheduler.getEntryCount()); m_collectd.stop(); } public void FIXMEtestOneMatchingSpec() { m_collectd.init(); m_collectd.start(); String svcName = "SNMP"; OnmsIpInterface iface = getInterface(); List specs = Collections.singletonList(getCollectionSpecification()); setupCollector(svcName); setupInterface(iface); setupSpecs(iface, svcName, specs); m_collector.expects(once()).method("initialize").with(isA(CollectionAgent.class), isA(Map.class)); m_scheduler.next(); assertEquals(1, m_scheduler.getEntryCount()); //public int collect(CollectionAgent agent, EventProxy eproxy, Map parameters); m_collector.expects(once()).method("collect").with(isA(CollectionAgent.class), isA(EventProxy.class), isA(Map.class)); m_scheduler.next(); m_collectd.stop(); } private void setupSpecs(OnmsIpInterface iface, String svcName, List specs) { m_collectorConfigDao.expects(once()).method("getSpecificationsForInterface"). with(same(iface), eq(svcName)). will(returnValue(specs)); } private void setupInterface(OnmsIpInterface iface) { m_ipIfDao.expects(once()).method("findByServiceType"). with(eq("SNMP")). will(returnValue(Collections.singleton(iface))); } private void setupCollector(String svcName) { Collector collector = new Collector(); collector.setService(svcName); collector.setClassName(MockServiceCollector.class.getName()); m_collectorConfigDao.expects(once()).method("getCollectors"). will(returnValue(Collections.singleton(collector))); } public void runTest() throws Throwable { super.runTest(); MockLogAppender.assertNoWarningsOrGreater(); } public static class MockServiceCollector implements ServiceCollector { public int collect(CollectionAgent agent, EventProxy eproxy, Map<String, String> parameters) { return 0; } public void initialize(Map parameters) { } public void initialize(CollectionAgent agent, Map parameters) { } public void release() { } public void release(CollectionAgent agent) { } } }
// This file is part of the OpenNMS(R) Application. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // and included code are below. // OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. // This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // For more information contact: package org.opennms.web.category; import java.io.IOException; import org.apache.log4j.Category; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.ValidationException; import org.opennms.core.resource.Vault; import org.opennms.core.utils.ThreadCategory; import org.opennms.netmgt.EventConstants; import org.opennms.netmgt.config.ViewsDisplayFactory; import org.opennms.netmgt.config.viewsdisplay.Section; import org.opennms.netmgt.config.viewsdisplay.View; import org.opennms.netmgt.utils.EventProxy; import org.opennms.netmgt.utils.EventProxyException; import org.opennms.netmgt.xml.event.Event; import org.opennms.netmgt.xml.event.Parm; import org.opennms.netmgt.xml.event.Parms; import org.opennms.netmgt.xml.event.Value; import org.opennms.web.Util; public class RTCPostSubscriber extends Object { protected EventProxy m_proxy; protected String m_url; protected String m_username; protected String m_password; protected static Category log = ThreadCategory.getInstance("RTC"); public RTCPostSubscriber() throws IOException, MarshalException, ValidationException { m_proxy = Util.createEventProxy(); } public static void sendSubscribeEvent(EventProxy proxy, String url, String username, String password, String categoryName) throws IllegalArgumentException, EventProxyException { if (proxy == null || url == null || username == null || password == null || categoryName == null) { throw new IllegalArgumentException("Cannot take null parameters."); } Event event = new Event(); event.setSource("RTCPostSubscriber"); event.setUei(EventConstants.RTC_SUBSCRIBE_EVENT_UEI); event.setHost("host"); event.setTime(EventConstants.formatToString(new java.util.Date())); Parms parms = new Parms(); // URL Value value = new Value(); value.setContent(url); Parm parm = new Parm(); parm.setParmName(EventConstants.PARM_URL); parm.setValue(value); parms.addParm(parm); // User value = new Value(); value.setContent(username); parm = new Parm(); parm.setParmName(EventConstants.PARM_USER); parm.setValue(value); parms.addParm(parm); // Password value = new Value(); value.setContent(password); parm = new Parm(); parm.setParmName(EventConstants.PARM_PASSWD); parm.setValue(value); parms.addParm(parm); // category value = new Value(); value.setContent(categoryName); parm = new Parm(); parm.setParmName(EventConstants.PARM_CAT_LABEL); parm.setValue(value); parms.addParm(parm); event.setParms(parms); proxy.send(event); log.info("Subscription requested for " + username + " to " + url); } public static void sendUnsubscribeEvent(EventProxy proxy, String url) throws IllegalArgumentException, EventProxyException { if (proxy == null || url == null) { throw new IllegalArgumentException("Cannot take null parameters."); } Event event = new Event(); event.setSource("RTCPostSubscriber"); event.setUei(EventConstants.RTC_UNSUBSCRIBE_EVENT_UEI); event.setHost("host"); event.setTime(EventConstants.formatToString(new java.util.Date())); // URL Parms parms = new Parms(); Value value = new Value(); value.setContent(url); Parm parm = new Parm(); parm.setParmName(EventConstants.PARM_URL); parm.setValue(value); parms.addParm(parm); event.setParms(parms); proxy.send(event); log.info("Unsubscription sent for " + url); } public String subscribe(String categoryName) throws IllegalArgumentException, EventProxyException { if (categoryName == null) { throw new IllegalArgumentException("Cannot take null parameters."); } initFromRtcPropertyFile(categoryName); sendSubscribeEvent(m_proxy, m_url, m_username, m_password, categoryName); return (m_url); } public void unsubscribe() throws IllegalArgumentException, EventProxyException { sendUnsubscribeEvent(m_proxy, m_url); } public void close() { m_proxy = null; } protected void initFromRtcPropertyFile(String categoryName) { if (categoryName == null) { throw new IllegalArgumentException("categoryName can not be null"); } m_username = Vault.getProperty("opennms.rtc-client.http-post.username"); m_password = Vault.getProperty("opennms.rtc-client.http-post.password"); String baseUrl = Vault.getProperty("opennms.rtc-client.http-post.base-url"); if (baseUrl == null) { throw new IllegalArgumentException("Property 'opennms.rtc-client.http-post.base-url' is null"); } if (baseUrl.endsWith("/")) { m_url = baseUrl + Util.encode(categoryName); } else { m_url = baseUrl + "/" + Util.encode(categoryName); } log.debug("RTCPostSubscriber initialized: url=" + m_url + ", user=" + m_username); } public static void subscribeAll(String viewName) throws IOException, MarshalException, ValidationException, EventProxyException { if (viewName == null) { throw new IllegalArgumentException("Cannot take null parameters."); } // get the list of categories from the viewsdisplay.xml ViewsDisplayFactory.init(); ViewsDisplayFactory factory = ViewsDisplayFactory.getInstance(); View view = factory.getView(viewName); if (view != null) { Section[] sections = view.getSection(); // create a JMS connection to subscribe RTCPostSubscriber subscriber = new RTCPostSubscriber(); for (int i = 0; i < sections.length; i++) { Section section = sections[i]; String[] categories = section.getCategory(); for (int j = 0; j < categories.length; j++) { subscriber.subscribe(categories[j]); log.info("Sent subscription event to RTC for " + "category: " + categories[j]); } } // Close the subscription JMS connection. subscriber.close(); } } }
package org.opennms.web.rest; import java.net.InetAddress; import java.net.UnknownHostException; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.bind.annotation.XmlRootElement; import org.opennms.netmgt.config.SnmpEventInfo; import org.opennms.netmgt.config.SnmpPeerFactory; import org.opennms.netmgt.snmp.SnmpAgentConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.sun.jersey.spi.resource.PerRequest; @Component @PerRequest @Scope("prototype") @Path("snmpConfiguration") @Transactional public class SnmpConfigRestService extends OnmsRestService { @XmlRootElement(name="snmp-info") public static class SnmpInfo { private String m_community; private String m_version; private int m_port; private int m_retries; private int m_timeout; public SnmpInfo() { } /** * @param config */ public SnmpInfo(SnmpAgentConfig config) { m_community = config.getReadCommunity(); m_port = config.getPort(); m_timeout = config.getTimeout(); m_retries = config.getRetries(); m_version = config.getVersionAsString(); } /** * @return the community */ public String getCommunity() { return m_community; } /** * @param community the community to set */ public void setCommunity(String community) { m_community = community; } /** * @return the version */ public String getVersion() { return m_version; } /** * @param version the version to set */ public void setVersion(String version) { m_version = version; } /** * @return the port */ public int getPort() { return m_port; } /** * @param port the port to set */ public void setPort(int port) { m_port = port; } /** * @return the retries */ public int getRetries() { return m_retries; } /** * @param retries the retries to set */ public void setRetries(int retries) { m_retries = retries; } /** * @return the timeout */ public int getTimeout() { return m_timeout; } /** * @param timeout the timeout to set */ public void setTimeout(int timeout) { m_timeout = timeout; } /** * @return */ public SnmpEventInfo createEventInfo(String ipAddr) throws UnknownHostException { SnmpEventInfo eventInfo = new SnmpEventInfo(); eventInfo.setCommunityString(m_community); eventInfo.setVersion(m_version); eventInfo.setPort(m_port); eventInfo.setTimeout(m_timeout); eventInfo.setRetryCount(m_retries); eventInfo.setFirstIPAddress(ipAddr); return eventInfo; } } @Autowired private SnmpPeerFactory m_snmpPeerFactory; @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Path("{ipAddr}") public SnmpInfo getSnmpInfo(@PathParam("ipAddr") String ipAddr) { try { SnmpAgentConfig config = m_snmpPeerFactory.getAgentConfig(InetAddress.getByName(ipAddr)); return new SnmpInfo(config); } catch (UnknownHostException e) { throw new WebApplicationException(Response.serverError().build()); } } @PUT @Consumes(MediaType.APPLICATION_XML) @Path("{ipAddr}") public Response setSnmpInfo(@PathParam("ipAddr") String ipAddr, SnmpInfo snmpInfo) { try { SnmpEventInfo eventInfo = snmpInfo.createEventInfo(ipAddr); m_snmpPeerFactory.define(eventInfo); //TODO: this shouldn't be a static call SnmpPeerFactory.saveCurrent(); return Response.ok().build(); } catch (Exception e) { return Response.serverError().build(); } } }
package org.eclipse.mylyn.tasks.ui; import java.text.MessageFormat; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.hyperlink.IHyperlink; import org.eclipse.mylyn.internal.tasks.ui.Messages; import org.eclipse.mylyn.tasks.core.TaskRepository; /** * Immutable. Encapsulates information for linking to tasks from text. * * @author Eugene Kuleshov * @author Steffen Pingel */ public final class TaskHyperlink implements IHyperlink { private final IRegion region; private final TaskRepository repository; private final String taskId; public TaskHyperlink(IRegion region, TaskRepository repository, String taskId) { this.region = region; this.repository = repository; // remove leading blanks while (taskId.startsWith("0")) { taskId = taskId.substring(1); } this.taskId = taskId; } public IRegion getHyperlinkRegion() { return region; } public String getTaskId() { return taskId; } public String getTypeLabel() { return null; } /** * @Since 2.1 * @return */ public TaskRepository getRepository() { return repository; } public String getHyperlinkText() { return MessageFormat.format(Messages.TaskHyperlink_Open_Task_X_in_X, taskId, repository.getRepositoryLabel()); } public void open() { if (repository != null) { TasksUiUtil.openTask(repository, taskId); } else { MessageDialog.openError(null, "Mylyn", Messages.TaskHyperlink_Could_not_determine_repository_for_report); //$NON-NLS-1$ } } }
package org.hive2hive.core.tomp2p; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import net.tomp2p.connection.ChannelClientConfiguration; import net.tomp2p.connection.ChannelServerConfiguration; import net.tomp2p.connection.DSASignatureFactory; import net.tomp2p.connection.SignatureFactory; import net.tomp2p.dht.FutureGet; import net.tomp2p.dht.FuturePut; import net.tomp2p.dht.FutureRemove; import net.tomp2p.dht.PeerBuilderDHT; import net.tomp2p.dht.PeerDHT; import net.tomp2p.message.SignatureCodec; import net.tomp2p.p2p.PeerBuilder; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number640; import net.tomp2p.storage.Data; import org.hive2hive.core.H2HJUnitTest; import org.hive2hive.core.security.H2HSignatureCodec; import org.hive2hive.core.security.H2HSignatureFactory; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; /** * A test which test the content protection mechanisms (signing of put/remove messages) and data signing of * <code>TomP2P</code>. Tests should be completely independent of <code>Hive2Hive</code>. * * @author Seppi */ public class SecurityTest extends H2HJUnitTest { @BeforeClass public static void initTest() throws Exception { testClass = SecurityTest.class; beforeClass(); } @Test public void testPutOverwriteWithoutContentProtectionKeys() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1).start()) .start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); String testData = "data"; Data data = new Data(testData).protectEntry(keyPair); // put with protection key FuturePut futurePut1 = p1.put(lKey).data(cKey, data).domainKey(dKey).keyPair(keyPair).start(); futurePut1.awaitUninterruptibly(); assertTrue(futurePut1.isSuccess()); // verify put from peer 1 FutureGet futureGet1a = p1.get(lKey).contentKey(cKey).domainKey(dKey).start(); futureGet1a.awaitUninterruptibly(); assertTrue(futureGet1a.isSuccess()); Data retData = futureGet1a.data(); assertEquals(testData, (String) retData.object()); assertEquals(keyPair.getPublic(), retData.publicKey()); // verify put from peer 2 FutureGet futureGet1b = p2.get(lKey).contentKey(cKey).domainKey(dKey).start(); futureGet1b.awaitUninterruptibly(); assertTrue(futureGet1b.isSuccess()); retData = futureGet1b.data(); assertEquals(testData, (String) retData.object()); assertEquals(keyPair.getPublic(), retData.publicKey()); // try a put without a protection key (through peer 2) Data data2 = new Data("data2"); FuturePut futurePut2 = p2.put(lKey).data(cKey, data2).domainKey(dKey).start(); futurePut2.awaitUninterruptibly(); assertFalse(futurePut2.isSuccess()); // verify that nothing changed from peer 1 FutureGet futureGet2a = p1.get(lKey).contentKey(cKey).domainKey(dKey).start(); futureGet2a.awaitUninterruptibly(); assertTrue(futureGet2a.isSuccess()); retData = futureGet2a.data(); // should have been not modified assertEquals(testData, (String) retData.object()); assertEquals(keyPair.getPublic(), retData.publicKey()); // verify that nothing changed from peer 2 FutureGet futureGet2b = p2.get(lKey).contentKey(cKey).domainKey(dKey).start(); futureGet2b.awaitUninterruptibly(); assertTrue(futureGet2b.isSuccess()); retData = futureGet2b.data(); // should have been not modified assertEquals(testData, (String) retData.object()); assertEquals(keyPair.getPublic(), retData.publicKey()); // overwrite String newTestData = "new data"; data = new Data(newTestData).protectEntry(keyPair); // sign put message with protection keys FuturePut futurePut4 = p1.put(lKey).data(cKey, data).keyPair(keyPair).domainKey(dKey).start(); futurePut4.awaitUninterruptibly(); Assert.assertTrue(futurePut4.isSuccess()); // verify overwrite from peer 1 FutureGet futureGet4a = p1.get(lKey).contentKey(cKey).domainKey(dKey).start(); futureGet4a.awaitUninterruptibly(); assertTrue(futureGet4a.isSuccess()); retData = futureGet4a.data(); assertEquals(keyPair.getPublic(), retData.publicKey()); // should have been modified assertEquals(newTestData, (String) retData.object()); // verify overwrite from peer 2 FutureGet futureGet4b = p2.get(lKey).contentKey(cKey).domainKey(dKey).start(); futureGet4b.awaitUninterruptibly(); assertTrue(futureGet4b.isSuccess()); retData = futureGet4b.data(); assertEquals(keyPair.getPublic(), retData.publicKey()); // should have been modified assertEquals(newTestData, (String) retData.object()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testPutSignedAndContentProtectedData() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); SignatureFactory factory = new DSASignatureFactory(); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1).start()) .start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); Number160 vKey = Number160.createHash("version"); Number160 bKey = Number160.createHash("based on"); String testData = "data"; Data data = new Data(testData).protectEntry().signatureFactory(factory).sign(keyPair); data.ttlSeconds(10000).addBasedOn(bKey); FuturePut futurePut1 = p1.put(lKey).data(cKey, data).domainKey(dKey).versionKey(vKey).keyPair(keyPair).start(); futurePut1.awaitUninterruptibly(); assertTrue(futurePut1.isSuccess()); FutureGet futureGet1a = p1.get(lKey).contentKey(cKey).domainKey(dKey).versionKey(vKey).start(); futureGet1a.awaitUninterruptibly(); assertTrue(futureGet1a.isSuccess()); Data retData = futureGet1a.data(); assertEquals(testData, (String) retData.object()); assertTrue(retData.verify(keyPair.getPublic(), factory)); assertEquals(keyPair.getPublic(), retData.publicKey()); FutureGet futureGet1b = p2.get(lKey).contentKey(cKey).domainKey(dKey).versionKey(vKey).start(); futureGet1b.awaitUninterruptibly(); assertTrue(futureGet1b.isSuccess()); retData = futureGet1b.data(); assertEquals(testData, (String) retData.object()); assertTrue(retData.verify(keyPair.getPublic(), factory)); assertEquals(keyPair.getPublic(), retData.publicKey()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testPutOverwriteWithWrongContentProtectionKeys() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); SignatureFactory factory = new DSASignatureFactory(); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1).start()) .start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = gen.generateKeyPair(); KeyPair keyPair2 = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); // initial put using content protection keys 1 String testData1 = "data1"; Data data = new Data(testData1).protectEntry(keyPair1); FuturePut futurePut1 = p1.put(lKey).data(cKey, data).domainKey(dKey).keyPair(keyPair1).start(); futurePut1.awaitUninterruptibly(); assertTrue(futurePut1.isSuccess()); FutureGet futureGet1a = p1.get(lKey).contentKey(cKey).domainKey(dKey).start(); futureGet1a.awaitUninterruptibly(); assertTrue(futureGet1a.isSuccess()); Data retData = futureGet1a.data(); assertEquals(testData1, (String) retData.object()); assertEquals(keyPair1.getPublic(), retData.publicKey()); FutureGet futureGet1b = p2.get(lKey).contentKey(cKey).domainKey(dKey).start(); futureGet1b.awaitUninterruptibly(); assertTrue(futureGet1b.isSuccess()); retData = futureGet1b.data(); assertEquals(testData1, (String) retData.object()); assertEquals(keyPair1.getPublic(), retData.publicKey()); // try to put with wrong content protection keys 2 String testData2 = "data2"; Data data2 = new Data(testData2).protectEntry().signatureFactory(factory).sign(keyPair2); FuturePut futurePut2 = p2.put(lKey).data(cKey, data2).domainKey(dKey).keyPair(keyPair2).start(); futurePut2.awaitUninterruptibly(); assertFalse(futurePut2.isSuccess()); FutureGet futureGet2a = p1.get(lKey).contentKey(cKey).domainKey(dKey).start(); futureGet2a.awaitUninterruptibly(); assertTrue(futureGet2a.isSuccess()); // should have been not modified retData = futureGet2a.data(); assertEquals(testData1, (String) retData.object()); assertEquals(keyPair1.getPublic(), retData.publicKey()); FutureGet futureGet2b = p2.get(lKey).contentKey(cKey).domainKey(dKey).start(); futureGet2b.awaitUninterruptibly(); assertTrue(futureGet2b.isSuccess()); // should have been not modified retData = futureGet2b.data(); assertEquals(testData1, (String) retData.object()); assertEquals(keyPair1.getPublic(), retData.publicKey()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testRemoveWithWrongOrWrongContentProtectionKeys() throws NoSuchAlgorithmException, IOException, InvalidKeyException, SignatureException, ClassNotFoundException { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1).start()) .start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = gen.generateKeyPair(); KeyPair keyPair2 = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 cKey = Number160.createHash("content"); // put with content protection keys 1 String testData1 = "data1"; Data data = new Data(testData1).protectEntry(keyPair1); FuturePut futurePut1 = p1.put(lKey).data(cKey, data).keyPair(keyPair1).start(); futurePut1.awaitUninterruptibly(); assertTrue(futurePut1.isSuccess()); // try to remove without content protection keys FutureRemove futureRemove1 = p1.remove(lKey).contentKey(cKey).start(); futureRemove1.awaitUninterruptibly(); assertFalse(futureRemove1.isSuccess()); // verify failed remove FutureGet futureGet2 = p1.get(lKey).contentKey(cKey).start(); futureGet2.awaitUninterruptibly(); assertTrue(futureGet2.isSuccess()); // should have been not modified assertEquals(testData1, (String) futureGet2.data().object()); assertEquals(keyPair1.getPublic(), futureGet2.data().publicKey()); // try to remove with wrong content protection keys 2 FutureRemove futureRemove2 = p1.remove(lKey).contentKey(cKey).keyPair(keyPair2).start(); futureRemove2.awaitUninterruptibly(); assertFalse(futureRemove2.isSuccess()); // verify failed remove FutureGet futureGet3 = p1.get(lKey).contentKey(cKey).start(); futureGet3.awaitUninterruptibly(); assertTrue(futureGet3.isSuccess()); // should have been not modified assertEquals(testData1, (String) futureGet3.data().object()); assertEquals(keyPair1.getPublic(), futureGet3.data().publicKey()); // remove with correct content protection keys FutureRemove futureRemove4 = p1.remove(lKey).contentKey(cKey).keyPair(keyPair1).start(); futureRemove4.awaitUninterruptibly(); assertTrue(futureRemove4.isSuccess()); // verify remove from peer 1 FutureGet futureGet4a = p1.get(lKey).contentKey(cKey).start(); futureGet4a.awaitUninterruptibly(); assertFalse(futureGet4a.isSuccess()); // should have been removed assertNull(futureGet4a.data()); // verify remove from peer 2 FutureGet futureGet4b = p2.get(lKey).contentKey(cKey).start(); futureGet4b.awaitUninterruptibly(); assertFalse(futureGet4b.isSuccess()); // should have been removed assertNull(futureGet4b.data()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testRemoveVersionWithWrongContentProtectionKeys() throws NoSuchAlgorithmException, IOException, InvalidKeyException, SignatureException, ClassNotFoundException { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1).start()) .start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = gen.generateKeyPair(); KeyPair keyPair2 = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 cKey = Number160.createHash("content"); Number160 vKey = Number160.createHash("version"); // put with content protection keys 1 String testData1 = "data1"; Data data = new Data(testData1).protectEntry(keyPair1); FuturePut futurePut1 = p1.put(lKey).data(cKey, data).versionKey(vKey).keyPair(keyPair1).start(); futurePut1.awaitUninterruptibly(); assertTrue(futurePut1.isSuccess()); // try to remove without content protection keys FutureRemove futureRemove1 = p1.remove(lKey).contentKey(cKey).versionKey(vKey).start(); futureRemove1.awaitUninterruptibly(); assertFalse(futureRemove1.isSuccess()); // verify failed remove FutureGet futureGet2 = p1.get(lKey).contentKey(cKey).versionKey(vKey).start(); futureGet2.awaitUninterruptibly(); assertTrue(futureGet2.isSuccess()); // should have been not modified assertEquals(testData1, (String) futureGet2.data().object()); assertEquals(keyPair1.getPublic(), futureGet2.data().publicKey()); // try to remove with wrong content protection keys 2 FutureRemove futureRemove2 = p1.remove(lKey).contentKey(cKey).versionKey(vKey).keyPair(keyPair2).start(); futureRemove2.awaitUninterruptibly(); assertFalse(futureRemove2.isSuccess()); // verify failed remove FutureGet futureGet3 = p1.get(lKey).contentKey(cKey).versionKey(vKey).start(); futureGet3.awaitUninterruptibly(); assertTrue(futureGet3.isSuccess()); // should have been not modified assertEquals(testData1, (String) futureGet3.data().object()); assertEquals(keyPair1.getPublic(), futureGet3.data().publicKey()); // remove with correct content protection keys FutureRemove futureRemove4 = p1.remove(lKey).contentKey(cKey).versionKey(vKey).keyPair(keyPair1).start(); futureRemove4.awaitUninterruptibly(); assertTrue(futureRemove4.isSuccess()); // verify remove from peer 1 FutureGet futureGet4a = p1.get(lKey).contentKey(cKey).versionKey(vKey).start(); futureGet4a.awaitUninterruptibly(); assertFalse(futureGet4a.isSuccess()); // should have been removed assertNull(futureGet4a.data()); // verify remove from peer 2 FutureGet futureGet4b = p2.get(lKey).contentKey(cKey).versionKey(vKey).start(); futureGet4b.awaitUninterruptibly(); assertFalse(futureGet4b.isSuccess()); // should have been removed assertNull(futureGet4b.data()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testRemoveWithFromToContentProtectedEntry() throws NoSuchAlgorithmException, IOException, InvalidKeyException, SignatureException, ClassNotFoundException { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1).start()) .start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair key1 = gen.generateKeyPair(); KeyPair key2 = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); Number160 vKey = Number160.createHash("version"); // put with content protection keys 1 String testData1 = "data1"; Data data = new Data(testData1).protectEntry(key1); FuturePut futurePut1 = p1.put(lKey).domainKey(dKey).data(cKey, data).versionKey(vKey).keyPair(key1).start(); futurePut1.awaitUninterruptibly(); assertTrue(futurePut1.isSuccess()); // try to remove without content protection keys using from/to FutureRemove futureRemove1 = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO)) .to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start(); futureRemove1.awaitUninterruptibly(); assertFalse(futureRemove1.isSuccess()); // verify failed remove FutureGet futureGet2 = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start(); futureGet2.awaitUninterruptibly(); assertTrue(futureGet2.isSuccess()); // should have been not modified assertEquals(testData1, (String) futureGet2.data().object()); assertEquals(key1.getPublic(), futureGet2.data().publicKey()); // remove with wrong content protection keys 2 using from/to FutureRemove futureRemove2a = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO)) .to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).keyPair(key2).start(); futureRemove2a.awaitUninterruptibly(); assertFalse(futureRemove2a.isSuccess()); // verify failed remove FutureGet futureGet3 = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start(); futureGet3.awaitUninterruptibly(); assertTrue(futureGet3.isSuccess()); // should have been not modified assertEquals(testData1, (String) futureGet3.data().object()); assertEquals(key1.getPublic(), futureGet3.data().publicKey()); // remove with correct content protection keys 1 using from/to FutureRemove futureRemove4 = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO)) .to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).keyPair(key1).start(); futureRemove4.awaitUninterruptibly(); assertTrue(futureRemove4.isSuccess()); // verify remove FutureGet futureGet4 = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start(); futureGet4.awaitUninterruptibly(); // we did not find the data Assert.assertTrue(futureGet4.isFailed()); // should have been removed assertNull(futureGet4.data()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testRemoveWithFromToSeveralVersionWithContentProtection() throws NoSuchAlgorithmException, IOException, InvalidKeyException, SignatureException, ClassNotFoundException { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1).start()) .start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair key = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); // put version 1 with content protection keys Data data1 = new Data("data1").protectEntry(key); Number160 vKey1 = Number160.createHash("version1"); FuturePut futurePut1 = p1.put(lKey).domainKey(dKey).data(cKey, data1).versionKey(vKey1).keyPair(key).start(); futurePut1.awaitUninterruptibly(); assertTrue(futurePut1.isSuccess()); // put version 2 basing on version 1 with content protection keys Data data2 = new Data("data2").addBasedOn(vKey1).protectEntry(key); Number160 vKey2 = Number160.createHash("version2"); FuturePut futurePut2 = p1.put(lKey).domainKey(dKey).data(cKey, data2).versionKey(vKey2).keyPair(key).start(); futurePut2.awaitUninterruptibly(); assertTrue(futurePut2.isSuccess()); // remove with correct content protection keys using from/to FutureRemove futureRemove = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO)) .to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).keyPair(key).start(); futureRemove.awaitUninterruptibly(); assertTrue(futureRemove.isSuccess()); // verify remove of version 1 FutureGet futureGet4a = p2.get(lKey).contentKey(cKey).versionKey(vKey1).start(); futureGet4a.awaitUninterruptibly(); // we did not find the data Assert.assertTrue(futureGet4a.isFailed()); // should have been removed assertNull(futureGet4a.data()); // verify remove of version 2 FutureGet futureGet4b = p2.get(lKey).contentKey(cKey).versionKey(vKey2).start(); futureGet4b.awaitUninterruptibly(); // we did not find the data Assert.assertTrue(futureGet4b.isFailed()); // should have been removed assertNull(futureGet4b.data()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testChangeProtectionKeyWithoutDataSignature() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1).start()) .start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = gen.generateKeyPair(); KeyPair keyPair2 = gen.generateKeyPair(); Number160 lKey = Number160.createHash(2); // same like node 2 Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); // initial put with protection keys 1 Data data1 = new Data("data1").protectEntry(keyPair1); FuturePut futurePut1 = p1.put(lKey).data(cKey, data1).domainKey(dKey).keyPair(keyPair1).start(); futurePut1.awaitUninterruptibly(); assertTrue(futurePut1.isSuccess()); // change protection keys to protection keys 2, create meta data Data data3 = new Data().protectEntry().publicKey(keyPair2.getPublic()).duplicateMeta(); // use the old protection key 1 to sign the message FuturePut futurePut3 = p1.put(lKey).domainKey(dKey).putMeta().data(cKey, data3).keyPair(keyPair1).start(); futurePut3.awaitUninterruptibly(); assertTrue(futurePut3.isSuccess()); // verify that nothing changed FutureGet futureGet = p2.get(lKey).contentKey(cKey).domainKey(dKey).start().awaitUninterruptibly(); assertEquals("data1", (String) futureGet.data().object()); // verify new content protection keys 2 assertEquals(keyPair2.getPublic(), futureGet.data().publicKey()); // overwrite with protection keys 2 Data data4 = new Data("data4").protectEntry(keyPair2); FuturePut futurePut4 = p1.put(lKey).data(cKey, data4).domainKey(dKey).keyPair(keyPair2).start(); futurePut4.awaitUninterruptibly(); assertTrue(futurePut4.isSuccess()); // verify overwrite futureGet = p2.get(lKey).contentKey(cKey).domainKey(dKey).start().awaitUninterruptibly(); assertEquals("data4", (String) futureGet.data().object()); assertEquals(keyPair2.getPublic(), futureGet.data().publicKey()); // try to overwrite without protection keys (expected to fail) Data data5A = new Data("data5A"); FuturePut futurePut5A = p1.put(lKey).data(cKey, data5A).domainKey(dKey).start(); futurePut5A.awaitUninterruptibly(); assertFalse(futurePut5A.isSuccess()); // verify that nothing changed futureGet = p2.get(lKey).contentKey(cKey).domainKey(dKey).start().awaitUninterruptibly(); assertEquals("data4", (String) futureGet.data().object()); assertEquals(keyPair2.getPublic(), futureGet.data().publicKey()); // try to overwrite with wrong protection keys 1 (expected to fail) Data data5B = new Data("data5B").protectEntry(keyPair1); FuturePut futurePut5B = p1.put(lKey).data(cKey, data5B).domainKey(dKey).keyPair(keyPair1).start(); futurePut5B.awaitUninterruptibly(); assertFalse(futurePut5B.isSuccess()); // verify that nothing changed futureGet = p2.get(lKey).contentKey(cKey).domainKey(dKey).start().awaitUninterruptibly(); assertEquals("data4", (String) futureGet.data().object()); assertEquals(keyPair2.getPublic(), futureGet.data().publicKey()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testChangeProtectionKeyWithVersionKeyWithoutDataSignature() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, InvalidKeyException, SignatureException { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1).start()) .start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = gen.generateKeyPair(); KeyPair keyPair2 = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); Number160 vKey = Number160.createHash("version"); Number160 bKey = Number160.createHash("based on"); // initial put with protection keys 1 Data data1 = new Data("data1").addBasedOn(bKey).protectEntry(keyPair1); FuturePut futurePut1 = p1.put(lKey).data(cKey, data1).domainKey(dKey).versionKey(vKey).keyPair(keyPair1).start(); futurePut1.awaitUninterruptibly(); assertTrue(futurePut1.isSuccess()); // overwrite with protection keys 1 Data data2 = new Data("data2").addBasedOn(bKey).protectEntry(keyPair1); FuturePut futurePut2 = p1.put(lKey).data(cKey, data2).domainKey(dKey).versionKey(vKey).keyPair(keyPair1).start(); futurePut2.awaitUninterruptibly(); assertTrue(futurePut2.isSuccess()); // verify overwrite FutureGet futureGet = p2.get(lKey).contentKey(cKey).domainKey(dKey).versionKey(vKey).start().awaitUninterruptibly(); assertEquals("data2", (String) futureGet.data().object()); assertEquals(keyPair1.getPublic(), futureGet.data().publicKey()); // try to overwrite without protection keys (expected to fail) Data data2A = new Data("data2A").addBasedOn(bKey); FuturePut futurePut2A = p1.put(lKey).data(cKey, data2A).domainKey(dKey).versionKey(vKey).start(); futurePut2A.awaitUninterruptibly(); assertFalse(futurePut2A.isSuccess()); // verify that nothing changed futureGet = p2.get(lKey).contentKey(cKey).domainKey(dKey).versionKey(vKey).start().awaitUninterruptibly(); assertEquals("data2", (String) futureGet.data().object()); assertEquals(keyPair1.getPublic(), futureGet.data().publicKey()); // try to overwrite with wrong protection keys 2 (expected to fail) Data data2B = new Data("data2B").addBasedOn(bKey).protectEntry(keyPair2); FuturePut futurePut2B = p1.put(lKey).data(cKey, data2B).domainKey(dKey).versionKey(vKey).keyPair(keyPair2).start(); futurePut2B.awaitUninterruptibly(); assertFalse(futurePut2B.isSuccess()); // verify that nothing changed futureGet = p2.get(lKey).contentKey(cKey).domainKey(dKey).versionKey(vKey).start().awaitUninterruptibly(); assertEquals("data2", (String) futureGet.data().object()); assertEquals(keyPair1.getPublic(), futureGet.data().publicKey()); // change protection keys to protection keys 2, create meta data Data data3 = new Data().protectEntry().publicKey(keyPair2.getPublic()).duplicateMeta(); // use the old protection key 1 to sign the message FuturePut futurePut3 = p1.put(lKey).domainKey(dKey).versionKey(vKey).putMeta().data(cKey, data3).keyPair(keyPair1) .start(); futurePut3.awaitUninterruptibly(); assertTrue(futurePut3.isSuccess()); // verify change futureGet = p2.get(lKey).contentKey(cKey).domainKey(dKey).versionKey(vKey).start().awaitUninterruptibly(); // data stays the same assertEquals("data2", (String) futureGet.data().object()); // should be new protection key assertEquals(keyPair2.getPublic(), futureGet.data().publicKey()); // overwrite with protection keys 2 Data data4 = new Data("data4").addBasedOn(bKey).protectEntry(keyPair2); FuturePut futurePut4 = p1.put(lKey).data(cKey, data4).domainKey(dKey).versionKey(vKey).keyPair(keyPair2).start(); futurePut4.awaitUninterruptibly(); assertTrue(futurePut4.isSuccess()); // verify overwrite futureGet = p2.get(lKey).contentKey(cKey).domainKey(dKey).versionKey(vKey).start().awaitUninterruptibly(); assertEquals("data4", (String) futureGet.data().object()); assertEquals(keyPair2.getPublic(), futureGet.data().publicKey()); // try to overwrite without protection keys (expected to fail) Data data5A = new Data("data5A").addBasedOn(bKey); FuturePut futurePut5A = p1.put(lKey).data(cKey, data5A).domainKey(dKey).versionKey(vKey).start(); futurePut5A.awaitUninterruptibly(); assertFalse(futurePut5A.isSuccess()); // verify that nothing changed futureGet = p2.get(lKey).contentKey(cKey).domainKey(dKey).versionKey(vKey).start().awaitUninterruptibly(); assertEquals("data4", (String) futureGet.data().object()); assertEquals(keyPair2.getPublic(), futureGet.data().publicKey()); // try to overwrite with wrong protection keys 1 (expected to fail) Data data5B = new Data("data5B").addBasedOn(bKey).protectEntry(keyPair1); FuturePut futurePut5B = p1.put(lKey).data(cKey, data5B).domainKey(dKey).versionKey(vKey).keyPair(keyPair1).start(); futurePut5B.awaitUninterruptibly(); assertFalse(futurePut5B.isSuccess()); // verify that nothing changed futureGet = p2.get(lKey).contentKey(cKey).domainKey(dKey).versionKey(vKey).start().awaitUninterruptibly(); assertEquals("data4", (String) futureGet.data().object()); assertEquals(keyPair2.getPublic(), futureGet.data().publicKey()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testChangeDataSignatureWithReusedHashWithoutContentProtection() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, InvalidKeyException, SignatureException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); // create custom RSA factories SignatureFactory factory = new H2HSignatureFactory(); SignatureCodec codec = new H2HSignatureCodec(); // replace default signature factories ChannelClientConfiguration clientConfig = PeerBuilder.createDefaultChannelClientConfiguration(); clientConfig.signatureFactory(factory); ChannelServerConfiguration serverConfig = PeerBuilder.createDefaultChannelServerConfiguration(); serverConfig.signatureFactory(factory); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1) .channelClientConfiguration(clientConfig).channelServerConfiguration(serverConfig).start()).start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .channelClientConfiguration(clientConfig).channelServerConfiguration(serverConfig).start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = gen.generateKeyPair(); KeyPair keyPair2 = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); Number160 vKey = Number160.createHash("version"); Number160 bKey = Number160.createHash("based on"); int ttl = 10; // initial put with keys 1 and data signature Data data = new Data("data").signatureFactory(factory).sign(keyPair1); data.ttlSeconds(ttl).addBasedOn(bKey); FuturePut futurePut = p1.put(lKey).domainKey(dKey).data(cKey, data).versionKey(vKey).start(); futurePut.awaitUninterruptibly(); Assert.assertTrue(futurePut.isSuccess()); // create signature with keys 1 having the data object byte[] signature1 = factory.sign(keyPair1.getPrivate(), data.buffer()).encode(); // decrypt signature to get hash of the object Cipher rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.DECRYPT_MODE, keyPair1.getPublic()); byte[] hash = rsa.doFinal(signature1); // encrypt hash with new key pair to get the new signature (without having the data object) rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.ENCRYPT_MODE, keyPair2.getPrivate()); byte[] signatureNew = rsa.doFinal(hash); // verify data signature Assert.assertTrue(p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly() .data().verify(keyPair1.getPublic(), factory)); // change data signature to keys 2, assign the reused hash from signature data = new Data().ttlSeconds(ttl).signature(codec.decode(signatureNew)); // don't forget to set signed flag, create meta data data.signed(true).duplicateMeta(); FuturePut futurePutMeta = p1.put(lKey).domainKey(dKey).putMeta().data(cKey, data).versionKey(vKey).start(); futurePutMeta.awaitUninterruptibly(); Assert.assertTrue(futurePutMeta.isSuccess()); // verify new data signature Data retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertTrue(retData.verify(keyPair2.getPublic(), factory)); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testChangeDataSignatureWithReusedHashWithContentProtection() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, InvalidKeyException, SignatureException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); // create custom RSA factories SignatureFactory factory = new H2HSignatureFactory(); SignatureCodec codec = new H2HSignatureCodec(); // replace default signature factories ChannelClientConfiguration clientConfig = PeerBuilder.createDefaultChannelClientConfiguration(); clientConfig.signatureFactory(factory); ChannelServerConfiguration serverConfig = PeerBuilder.createDefaultChannelServerConfiguration(); serverConfig.signatureFactory(factory); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1) .channelClientConfiguration(clientConfig).channelServerConfiguration(serverConfig).start()).start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .channelClientConfiguration(clientConfig).channelServerConfiguration(serverConfig).start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = gen.generateKeyPair(); KeyPair keyPair2 = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); Number160 vKey = Number160.createHash("version"); Number160 bKey = Number160.createHash("based on"); int ttl = 10; // initial put with data signature and entry protection Data intialData = new Data("data").protectEntry(); intialData.ttlSeconds(ttl).addBasedOn(bKey).signatureFactory(factory).sign(keyPair1); // put using content protection key 1 to sign message FuturePut futureIntialPut = p1.put(lKey).domainKey(dKey).data(cKey, intialData).versionKey(vKey).keyPair(keyPair1) .start(); futureIntialPut.awaitUninterruptibly(); Assert.assertTrue(futureIntialPut.isSuccess()); // verify put Data retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // verify data signature Assert.assertTrue(retData.verify(keyPair1.getPublic(), factory)); // try to overwrite without content protection and data signature (expected to fail) Data data = new Data("dataA"); data.ttlSeconds(ttl).addBasedOn(bKey).signatureFactory(factory).sign(keyPair1); // put using content protection key 1 to sign message FuturePut futureTryOverwrite = p1.put(lKey).domainKey(dKey).data(cKey, data).versionKey(vKey).start(); futureTryOverwrite.awaitUninterruptibly(); Assert.assertFalse(futureTryOverwrite.isSuccess()); // verify that nothing changed retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // verify that data signature is still the same Assert.assertTrue(retData.verify(keyPair1.getPublic(), factory)); // try to overwrite with wrong protection keys 2 and data signature (expected to fail) data = new Data("dataB").protectEntry(); data.ttlSeconds(ttl).addBasedOn(bKey).signatureFactory(factory).sign(keyPair1); // put using wrong content protection keys 2 to sign message futureTryOverwrite = p1.put(lKey).domainKey(dKey).data(cKey, data).versionKey(vKey).keyPair(keyPair2).start(); futureTryOverwrite.awaitUninterruptibly(); Assert.assertFalse(futureTryOverwrite.isSuccess()); // verify that nothing changed retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // verify that data signature is still the same Assert.assertTrue(retData.verify(keyPair1.getPublic(), factory)); // try to overwrite without content protection and without data signature (expected to fail) data = new Data("dataC"); data.ttlSeconds(ttl).addBasedOn(bKey).signatureFactory(factory).sign(keyPair1); // put using wrong content protection keys 2 to sign message futureTryOverwrite = p1.put(lKey).domainKey(dKey).data(cKey, data).versionKey(vKey).start(); futureTryOverwrite.awaitUninterruptibly(); Assert.assertFalse(futureTryOverwrite.isSuccess()); // verify that nothing changed retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // verify that data signature is still the same Assert.assertTrue(retData.verify(keyPair1.getPublic(), factory)); // try to overwrite with wrong protection keys 2 and without data signature (expected to fail) data = new Data("dataD").protectEntry(); data.ttlSeconds(ttl).addBasedOn(bKey).signatureFactory(factory).sign(keyPair1); // put using wrong content protection keys 2 to sign message futureTryOverwrite = p1.put(lKey).domainKey(dKey).data(cKey, data).versionKey(vKey).keyPair(keyPair2).start(); futureTryOverwrite.awaitUninterruptibly(); Assert.assertFalse(futureTryOverwrite.isSuccess()); // verify that nothing changed retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // verify that data signature is still the same Assert.assertTrue(retData.verify(keyPair1.getPublic(), factory)); // overwrite with content protection keys 1 and no data signature intialData = new Data("data2").protectEntry(); intialData.ttlSeconds(ttl).addBasedOn(bKey); // put using content protection key 1 to sign message FuturePut futureOverwrite1 = p1.put(lKey).domainKey(dKey).data(cKey, intialData).versionKey(vKey).keyPair(keyPair1) .start(); futureOverwrite1.awaitUninterruptibly(); Assert.assertTrue(futureOverwrite1.isSuccess()); // verify overwrite retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data2", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // verify no signature Assert.assertNull(retData.signature()); // overwrite with content protection key1 and with data signature intialData = new Data("data3").protectEntry(); intialData.ttlSeconds(ttl).addBasedOn(bKey).signatureFactory(factory).sign(keyPair1); // put using content protection key 1 to sign message FuturePut futureOverwrite2 = p1.put(lKey).domainKey(dKey).data(cKey, intialData).versionKey(vKey).keyPair(keyPair1) .start(); futureOverwrite2.awaitUninterruptibly(); Assert.assertTrue(futureOverwrite2.isSuccess()); // verify overwrite retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data3", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // verify that data signature is still the same Assert.assertTrue(retData.verify(keyPair1.getPublic(), factory)); // create signature with keys 1 having the data object byte[] signature1 = factory.sign(keyPair1.getPrivate(), intialData.buffer()).encode(); // decrypt signature to get hash of the object Cipher rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.DECRYPT_MODE, keyPair1.getPublic()); byte[] hash = rsa.doFinal(signature1); // encrypt hash with new key pair to get the new signature (without having the data object) rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.ENCRYPT_MODE, keyPair2.getPrivate()); byte[] signatureNew = rsa.doFinal(hash); // change data signature to keys 2, assign the reused hash from signature data = new Data().ttlSeconds(ttl).signature(codec.decode(signatureNew)).protectEntry(); // don't forget to set signed flag, create meta data data.signed(true).duplicateMeta(); // put meta using content content protection key 1 to sign message FuturePut futurePutMeta = p1.put(lKey).domainKey(dKey).putMeta().data(cKey, data).versionKey(vKey).keyPair(keyPair1) .start(); futurePutMeta.awaitUninterruptibly(); Assert.assertTrue(futurePutMeta.isSuccess()); // verify change retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data3", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // verify new data signature Assert.assertTrue(retData.verify(keyPair2.getPublic(), factory)); // overwrite with content protection key 1 and data signature data = new Data("data4").protectEntry(); data.ttlSeconds(ttl).addBasedOn(bKey).signatureFactory(factory).sign(keyPair1); // put using content content protection key 1 to sign message FuturePut futureOverwrite3 = p1.put(lKey).domainKey(dKey).data(cKey, data).versionKey(vKey).keyPair(keyPair1) .start(); futureOverwrite3.awaitUninterruptibly(); Assert.assertTrue(futureOverwrite3.isSuccess()); // verify change retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data4", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // verify that data signature wasn't changed Assert.assertTrue(retData.verify(keyPair1.getPublic(), factory)); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testChangeDataSignatureAndChangeContentProtectionSimultanously() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, InvalidKeyException, SignatureException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); // create custom RSA factories SignatureFactory factory = new H2HSignatureFactory(); // replace default signature factories ChannelClientConfiguration clientConfig = PeerBuilder.createDefaultChannelClientConfiguration(); clientConfig.signatureFactory(factory); ChannelServerConfiguration serverConfig = PeerBuilder.createDefaultChannelServerConfiguration(); serverConfig.signatureFactory(factory); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1) .channelClientConfiguration(clientConfig).channelServerConfiguration(serverConfig).start()).start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .channelClientConfiguration(clientConfig).channelServerConfiguration(serverConfig).start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = gen.generateKeyPair(); KeyPair keyPair2 = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); Number160 vKey = Number160.createHash("version"); Number160 bKey = Number160.createHash("based on"); int ttl = 10; // initial put with data signature and entry protection Data data = new Data("data1").protectEntry(); data.ttlSeconds(ttl).addBasedOn(bKey).signatureFactory(factory).sign(keyPair1); // put using content protection key 1 to sign message FuturePut futureIntialPut = p1.put(lKey).domainKey(dKey).data(cKey, data).versionKey(vKey).keyPair(keyPair1).start(); futureIntialPut.awaitUninterruptibly(); Assert.assertTrue(futureIntialPut.isSuccess()); // verify put Data retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data1", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // verify data signature Assert.assertTrue(retData.verify(keyPair1.getPublic(), factory)); // change data signature to keys 2 using same data, sign with new key 2 data = new Data("data1").ttlSeconds(ttl).protectEntry().signatureFactory(factory).sign(keyPair2); // change content protection keys to keys 2 // data.publicKey(keyPair2.getPublic()); is already done with data.sign(...) // create meta data data.duplicateMeta(); // put meta using content content protection key 1 to sign message FuturePut futurePutMeta = p1.put(lKey).domainKey(dKey).putMeta().data(cKey, data).versionKey(vKey).keyPair(keyPair1) .start(); futurePutMeta.awaitUninterruptibly(); Assert.assertTrue(futurePutMeta.isSuccess()); // verify change retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data1", (String) retData.object()); // verify new content protection keys 2 Assert.assertEquals(keyPair2.getPublic(), retData.publicKey()); // verify new data signature Assert.assertTrue(retData.verify(keyPair2.getPublic(), factory)); // try overwrite with content protection key 1 and data signature (expected to fail) data = new Data("data2").protectEntry(); data.ttlSeconds(ttl).addBasedOn(bKey).signatureFactory(factory).sign(keyPair2); // put using content wrong protection keys 1 to sign message FuturePut futureOverwrite3 = p1.put(lKey).domainKey(dKey).data(cKey, data).versionKey(vKey).keyPair(keyPair1) .start(); futureOverwrite3.awaitUninterruptibly(); Assert.assertFalse(futureOverwrite3.isSuccess()); // verify that nothing changed retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data1", (String) retData.object()); Assert.assertEquals(keyPair2.getPublic(), retData.publicKey()); // verify not changed signature Assert.assertTrue(retData.verify(keyPair2.getPublic(), factory)); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testChangeDataSignatureWithReusedHashAndChangeContentProtectionSimultanously() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, InvalidKeyException, SignatureException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); // create custom RSA factories SignatureFactory factory = new H2HSignatureFactory(); SignatureCodec codec = new H2HSignatureCodec(); // replace default signature factories ChannelClientConfiguration clientConfig = PeerBuilder.createDefaultChannelClientConfiguration(); clientConfig.signatureFactory(factory); ChannelServerConfiguration serverConfig = PeerBuilder.createDefaultChannelServerConfiguration(); serverConfig.signatureFactory(factory); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1) .channelClientConfiguration(clientConfig).channelServerConfiguration(serverConfig).start()).start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .channelClientConfiguration(clientConfig).channelServerConfiguration(serverConfig).start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = gen.generateKeyPair(); KeyPair keyPair2 = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); Number160 vKey = Number160.createHash("version"); Number160 bKey = Number160.createHash("based on"); int ttl = 10; // initial put with data signature and entry protection Data data = new Data("data1").protectEntry(); data.ttlSeconds(ttl).addBasedOn(bKey).signatureFactory(factory).sign(keyPair1); // put using content protection key 1 to sign message FuturePut futureIntialPut = p1.put(lKey).domainKey(dKey).data(cKey, data).versionKey(vKey).keyPair(keyPair1).start(); futureIntialPut.awaitUninterruptibly(); Assert.assertTrue(futureIntialPut.isSuccess()); // verify put Data retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data1", (String) retData.object()); // verify content protection keys 1 is set Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // verify data signature Assert.assertTrue(retData.verify(keyPair1.getPublic(), factory)); // create signature with keys 1 having the data object byte[] signature1 = factory.sign(keyPair1.getPrivate(), data.buffer()).encode(); // decrypt signature to get hash of the object Cipher rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.DECRYPT_MODE, keyPair1.getPublic()); byte[] hash = rsa.doFinal(signature1); // encrypt hash with new key pair to get the new signature (without having the data object) rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.ENCRYPT_MODE, keyPair2.getPrivate()); byte[] signatureNew = rsa.doFinal(hash); // change data signature to keys 2, assign the reused hash from signature data = new Data().ttlSeconds(ttl).signature(codec.decode(signatureNew)).protectEntry(); // don't forget to set signed flag data.signed(true); // change the content protection keys to 2 data.publicKey(keyPair2.getPublic()); // create meta data data.duplicateMeta(); // put meta using content content protection key 1 to sign message FuturePut futurePutMeta = p1.put(lKey).domainKey(dKey).putMeta().data(cKey, data).versionKey(vKey).keyPair(keyPair1) .start(); futurePutMeta.awaitUninterruptibly(); Assert.assertTrue(futurePutMeta.isSuccess()); // verify change retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data1", (String) retData.object()); // verify change to content protection keys 2 Assert.assertEquals(keyPair2.getPublic(), retData.publicKey()); // verify new data signature Assert.assertTrue(retData.verify(keyPair2.getPublic(), factory)); // try overwrite with content protection key 1 and data signature (exptected to fail) data = new Data("data2").protectEntry(); data.ttlSeconds(ttl).addBasedOn(bKey).signatureFactory(factory).sign(keyPair2); // put using content wrong protection keys 1 to sign message FuturePut futureOverwrite3 = p1.put(lKey).domainKey(dKey).data(cKey, data).versionKey(vKey).keyPair(keyPair1) .start(); futureOverwrite3.awaitUninterruptibly(); Assert.assertFalse(futureOverwrite3.isSuccess()); // verify that nothing changed retData = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey).start().awaitUninterruptibly().data(); Assert.assertEquals("data1", (String) retData.object()); Assert.assertEquals(keyPair2.getPublic(), retData.publicKey()); // verify not changed signature Assert.assertTrue(retData.verify(keyPair2.getPublic(), factory)); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testContentProtectionAppliesToAllVersionKeys() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, InvalidKeyException, SignatureException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1).start()) .start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = gen.generateKeyPair(); KeyPair keyPair2 = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); // put version 1 with protection keys 1 Data data1 = new Data("data1").protectEntry(keyPair1); Number160 vKey1 = Number160.ZERO; FuturePut futurePut1 = p1.put(lKey).data(cKey, data1).domainKey(dKey).versionKey(vKey1).keyPair(keyPair1).start(); futurePut1.awaitUninterruptibly(); assertTrue(futurePut1.isSuccess()); // verify put of version 1 Data retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey1).start().awaitUninterruptibly().data(); Assert.assertEquals("data1", (String) retData.object()); // verify content protection keys 1 is set Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // try to overwrite version 1 without protection keys (expected to fail) Data data1A = new Data("data1A"); FuturePut futurePut1A = p1.put(lKey).data(cKey, data1A).domainKey(dKey).versionKey(vKey1).start(); futurePut1A.awaitUninterruptibly(); assertFalse(futurePut1A.isSuccess()); // verify that nothing changed retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey1).start().awaitUninterruptibly().data(); Assert.assertEquals("data1", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // try to overwrite version 1 with wrong protection keys 2 (expected to fail) Data data1B = new Data("data1B").protectEntry(keyPair2); FuturePut futurePut1B = p1.put(lKey).data(cKey, data1B).domainKey(dKey).versionKey(vKey1).keyPair(keyPair2).start(); futurePut1B.awaitUninterruptibly(); assertFalse(futurePut1B.isSuccess()); // verify that nothing changed retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey1).start().awaitUninterruptibly().data(); Assert.assertEquals("data1", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // overwrite version 1 with protection keys 1 Data data1Overwrite = new Data("data1Overwrite").protectEntry(keyPair1); FuturePut futurePutOverwrite = p1.put(lKey).data(cKey, data1Overwrite).domainKey(dKey).versionKey(vKey1) .keyPair(keyPair1).start(); futurePutOverwrite.awaitUninterruptibly(); assertTrue(futurePutOverwrite.isSuccess()); // verify overwrite retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey1).start().awaitUninterruptibly().data(); Assert.assertEquals("data1Overwrite", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // try to put new version 2 (basing on version 1) with wrong protection keys 2 (expected to fail) Data data2 = new Data("data2").addBasedOn(vKey1).protectEntry(keyPair2); // version 2 takes new version key Number160 vKey2 = Number160.createHash("version2"); FuturePut futurePut2 = p1.put(lKey).data(cKey, data2).domainKey(dKey).versionKey(vKey2).keyPair(keyPair2).start(); futurePut2.awaitUninterruptibly(); assertFalse(futurePut2.isSuccess()); // verify no put of version 2 assertNull(p2.get(lKey).contentKey(cKey).versionKey(vKey2).domainKey(dKey).start().awaitUninterruptibly().data()); // put new version 3 (basing on version 1) with correct protection keys 1 Data data3 = new Data("data3").addBasedOn(vKey1).protectEntry(keyPair1); Number160 vKey3 = Number160.createHash("version3"); FuturePut futurePut3 = p1.put(lKey).data(cKey, data3).domainKey(dKey).versionKey(vKey3).keyPair(keyPair1).start(); futurePut3.awaitUninterruptibly(); assertTrue(futurePut3.isSuccess()); // verify put of version 3 assertEquals("data3", (String) p2.get(lKey).contentKey(cKey).versionKey(vKey3).domainKey(dKey).start() .awaitUninterruptibly().data().object()); retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey3).start().awaitUninterruptibly().data(); Assert.assertEquals("data3", (String) retData.object()); Assert.assertEquals(keyPair1.getPublic(), retData.publicKey()); // try to put a version X in version key range of version 1 and 3 with wrong protection keys 2 // (expected to fail) Data dataX = new Data("dataX").protectEntry(keyPair2); Number160 vKeyX = Number160.createHash("versionX"); FuturePut futurePut4 = p1.put(lKey).data(cKey, dataX).domainKey(dKey).versionKey(vKeyX).keyPair(keyPair2).start(); futurePut4.awaitUninterruptibly(); assertFalse(futurePut4.isSuccess()); // verify no put of version X assertNull(p2.get(lKey).contentKey(cKey).versionKey(vKeyX).domainKey(dKey).start().awaitUninterruptibly().data()); // try to put random version Y in version key range of version 1 and 3 without protection keys // (expected to fail) Data dataY = new Data("dataY").protectEntry(); Number160 vKeyY = Number160.createHash("versionX"); futurePut4 = p1.put(lKey).data(cKey, dataY).domainKey(dKey).versionKey(vKeyY).start(); futurePut4.awaitUninterruptibly(); assertFalse(futurePut4.isSuccess()); // verify no put of version Y assertNull(p2.get(lKey).contentKey(cKey).versionKey(vKeyY).domainKey(dKey).start().awaitUninterruptibly().data()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test @Ignore public void testContentProtectionChangeAppliesToAllVersionKeys() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, InvalidKeyException, SignatureException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPair keyPairPeer1 = gen.generateKeyPair(); PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1).start()) .start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).keyPair(keyPairPeer2) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = gen.generateKeyPair(); KeyPair keyPair2 = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); // put version 1 with protection keys 1 Data data1 = new Data("data1").protectEntry(keyPair1); Number160 vKey1 = Number160.ZERO; FuturePut futurePut1 = p1.put(lKey).data(cKey, data1).domainKey(dKey).versionKey(vKey1).keyPair(keyPair1).start(); futurePut1.awaitUninterruptibly(); assertTrue(futurePut1.isSuccess()); // put new version 2 (basing on version 1) with protection keys 1 Data data2 = new Data("data2").addBasedOn(vKey1).protectEntry(keyPair1); // version 2 takes new version key Number160 vKey2 = Number160.createHash("version2"); FuturePut futurePut2 = p1.put(lKey).data(cKey, data2).domainKey(dKey).versionKey(vKey2).keyPair(keyPair1).start(); futurePut2.awaitUninterruptibly(); assertTrue(futurePut2.isSuccess()); // change protection key on version 1 with a put meta Data dataMeta = new Data().protectEntry().publicKey(keyPair2.getPublic()).duplicateMeta(); // use the old protection key 1 to sign the message FuturePut futurePutMeta = p1.put(lKey).domainKey(dKey).versionKey(vKey1).putMeta().data(cKey, dataMeta) .keyPair(keyPair1).start(); futurePutMeta.awaitUninterruptibly(); assertTrue(futurePutMeta.isSuccess()); // verify change at version 1 Data retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey1).start().awaitUninterruptibly().data(); Assert.assertEquals("data1", (String) retData.object()); // verify change of content protection keys to 2 Assert.assertEquals(keyPair2.getPublic(), retData.publicKey()); // verify change at version 2 retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey2).start().awaitUninterruptibly().data(); Assert.assertEquals("data2", (String) retData.object()); // verify change of content protection keys to 2 Assert.assertEquals(keyPair2.getPublic(), retData.publicKey()); // keypair2 // overwrite version 1 with protection keys 2 Data data1Overwrite = new Data("data1Overwrite").protectEntry(keyPair2); FuturePut futurePut1Overwrite = p1.put(lKey).data(cKey, data1Overwrite).domainKey(dKey).versionKey(vKey1) .keyPair(keyPair2).start(); futurePut1Overwrite.awaitUninterruptibly(); assertTrue(futurePut1Overwrite.isSuccess()); // verify overwrite version 1 retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey1).start().awaitUninterruptibly().data(); Assert.assertEquals("data1Overwrite", (String) retData.object()); Assert.assertEquals(keyPair2.getPublic(), retData.publicKey()); // overwrite version 2 with protection keys 2 Data data2Overwrite = new Data("data2Overwrite").protectEntry(keyPair2); FuturePut futurePut2Overwrite = p1.put(lKey).data(cKey, data2Overwrite).domainKey(dKey).versionKey(vKey2) .keyPair(keyPair2).start(); futurePut2Overwrite.awaitUninterruptibly(); assertTrue(futurePut2Overwrite.isSuccess()); // verify overwrite version 2 retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey2).start().awaitUninterruptibly().data(); Assert.assertEquals("data2Overwrite", (String) retData.object()); Assert.assertEquals(keyPair2.getPublic(), retData.publicKey()); // put new version 3 (basing on version 2) with protection keys 2 Data data3 = new Data("data3").addBasedOn(vKey2).protectEntry(keyPair2); Number160 vKey3 = Number160.createHash("version3"); FuturePut futurePut3 = p1.put(lKey).data(cKey, data3).domainKey(dKey).versionKey(vKey3).keyPair(keyPair2).start(); futurePut3.awaitUninterruptibly(); assertTrue(futurePut3.isSuccess()); // verify put version 3 retData = p2.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(vKey3).start().awaitUninterruptibly().data(); Assert.assertEquals("data3", (String) retData.object()); Assert.assertEquals(keyPair2.getPublic(), retData.publicKey()); // try to put a version X in version key range of version 1, 2 and 3 with wrong protection keys 1 // (expected to fail) Data dataX = new Data("dataX").protectEntry(keyPair1); Number160 vKeyX = Number160.createHash("versionX"); FuturePut futurePut4 = p1.put(lKey).data(cKey, dataX).domainKey(dKey).versionKey(vKeyX).keyPair(keyPair1).start(); futurePut4.awaitUninterruptibly(); assertFalse(futurePut4.isSuccess()); // verify no put of version X assertNull(p2.get(lKey).contentKey(cKey).versionKey(vKeyX).domainKey(dKey).start().awaitUninterruptibly().data()); // try to put random version Y in version key range of version 1, 2 and 3 without protection keys // (expected to fail) Data dataY = new Data("dataY").protectEntry(); Number160 vKeyY = Number160.createHash("versionX"); futurePut4 = p1.put(lKey).data(cKey, dataY).domainKey(dKey).versionKey(vKeyY).start(); futurePut4.awaitUninterruptibly(); assertFalse(futurePut4.isSuccess()); // verify no put of version Y assertNull(p2.get(lKey).contentKey(cKey).versionKey(vKeyY).domainKey(dKey).start().awaitUninterruptibly().data()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @AfterClass public static void cleanAfterClass() { afterClass(); } }
package entity; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Transient; import javax.xml.bind.annotation.XmlElement; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Entity public class Point implements Serializable { private static final long serialVersionUID = 1L; @Id private String id; private double longitude; private double latitude; private String name; private String hint; private boolean isFinal; @Transient @XmlElement(name="_links") private List<Link> links = new ArrayList<>(); /** * Empty constructor */ public Point() {} /** * Constructor for a Point * @param longitude x * @param latitude y * @param hint (image url) * @param aFinal : answer if the point is the final one */ public Point(String name, double longitude, double latitude, String hint, boolean aFinal) { this.longitude = longitude; this.latitude = latitude; this.hint = hint; this.name = name; isFinal = aFinal; } /** * Constructor for a Point without isFinal attribute * @param longitude x * @param latitude y * @param hint (image url) */ public Point(String name, double longitude, double latitude, String hint) { this.longitude = longitude; this.latitude = latitude; this.hint = hint; this.name = name; isFinal = false; } /** * Constructor for a Point without hints * @param longitude x * @param latitude y */ public Point(String name, double longitude, double latitude) { this.longitude = longitude; this.latitude = latitude; this.name = name; isFinal = false; } /** * Method to update a point from another one * @param point */ public void update(Point point) { longitude = point.getLongitude(); latitude = point.getLatitude(); name = point.getName(); hint = point.getHint(); isFinal = isFinal(); } /** * Helper method to generate an id and set it to this.id * this method also removes hyphens */ public void generateId() { id = UUID.randomUUID().toString().replaceAll("-", ""); } /** * Helper method to know if critical fields have been filled * @return if the point is valid */ public boolean isValid() { return (name != null && hint != null && (Double.toString(longitude) != null) && (Double.toString(latitude) != null)); } /** * Method to add a link * @param uri uri link * @param rel name */ public void addLink(String uri, String rel) { this.links.add(new Link(rel, uri)); } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getHint() { return hint; } public void setHint(String hint) { this.hint = hint; } public boolean isFinal() { return isFinal; } public void setFinal(boolean aFinal) { isFinal = aFinal; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Link> getLinks() { return links; } }
package imj3.draft; import static imj3.core.Channels.Predefined.a8r8g8b8; import static imj3.core.Channels.Predefined.blue8; import static imj3.core.Channels.Predefined.green8; import static imj3.core.Channels.Predefined.red8; import static imj3.draft.VisualSegmentation.getSharedProperty; import static imj3.draft.VisualSegmentation.newItem; import static imj3.draft.VisualSegmentation.property; import static imj3.draft.VisualSegmentation.repeat; import static imj3.draft.VisualSegmentation.setSharedProperty; import static imj3.draft.VisualSegmentation.showEditDialog; import static java.lang.Math.abs; import static java.util.Arrays.stream; import static net.sourceforge.aprog.swing.SwingTools.scrollable; import static net.sourceforge.aprog.tools.Tools.array; import static net.sourceforge.aprog.tools.Tools.baseName; import static net.sourceforge.aprog.tools.Tools.cast; import static net.sourceforge.aprog.tools.Tools.ignore; import static net.sourceforge.aprog.tools.Tools.instances; import static net.sourceforge.aprog.tools.Tools.join; import imj2.draft.PaletteBasedHistograms; import imj2.pixel3d.MouseHandler; import imj2.tools.Canvas; import imj3.core.Channels.Predefined; import imj3.draft.TrainableSegmentation.ImageComponent.Painter; import imj3.draft.TrainableSegmentation.QuantizerNode; import imj3.tools.AwtImage2D; import imj3.tools.IMJTools; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Composite; import java.awt.CompositeContext; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDropEvent; import java.awt.event.ActionEvent; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicInteger; import java.util.prefs.Preferences; import javax.imageio.ImageIO; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPopupMenu; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import jgencode.primitivelists.IntList; import net.sourceforge.aprog.swing.SwingTools; import net.sourceforge.aprog.tools.CommandLineArgumentsParser; import net.sourceforge.aprog.tools.IllegalInstantiationException; import net.sourceforge.aprog.tools.Pair; import net.sourceforge.aprog.tools.TicToc; import net.sourceforge.aprog.tools.Tools; import net.sourceforge.aprog.xml.XMLTools; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; /** * @author codistmonk (creation 2015-01-16) */ public final class TrainableSegmentation { private TrainableSegmentation() { throw new IllegalInstantiationException(); } public static final String PALETTE_XML = "palette.xml"; static final Preferences preferences = Preferences.userNodeForPackage(TrainableSegmentation.class); public static final Iterable<int[]> cartesian(final int... minMaxes) { return new Iterable<int[]>() { @Override public final Iterator<int[]> iterator() { final int n = minMaxes.length / 2; return new Iterator<int[]>() { private int[] result; @Override public final boolean hasNext() { if (this.result == null) { this.result = new int[n]; for (int i = 0; i < n; ++i) { this.result[i] = minMaxes[2 * i + 0]; } --this.result[n - 1]; } for (int i = 0; i < n; ++i) { if (this.result[i] < minMaxes[2 * i + 1]) { return true; } } return false; } @Override public final int[] next() { for (int i = n - 1; minMaxes[2 * i + 1] < ++this.result[i] && 0 < i; --i) { this.result[i] = minMaxes[2 * i + 0]; } return this.result; } }; } }; } public static final Iterable<double[]> valuesAndWeights(final BufferedImage image, final IntList pixels, final int patchSize) { return new Iterable<double[]>() { @Override public final Iterator<double[]> iterator() { final int n = patchSize * patchSize; return new Iterator<double[]>() { private final int[] buffer = new int[n]; private final double[] result = new double[n * 3 + 1]; private int i = 0; { this.result[n * 3] = 1.0; } @Override public final boolean hasNext() { return this.i < pixels.size(); } @Override public final double[] next() { final int pixel = pixels.get(this.i++); Quantizer.extractValues(image, pixel % image.getWidth(), pixel / image.getWidth(), patchSize, this.buffer); for (int i = 0; i < n; ++i) { final int rgb = this.buffer[i]; this.result[3 * i + 0] = red8(rgb); this.result[3 * i + 1] = green8(rgb); this.result[3 * i + 2] = blue8(rgb); } return this.result; } }; } }; } public static final double f1(final int[][] confusionMatrix, final int i) { final int n = confusionMatrix.length; final int tp = confusionMatrix[i][i]; int fp = 0; int fn = 0; for (int j = 0; j < n; ++j) { if (i != j) { fp += confusionMatrix[j][i]; fn += confusionMatrix[i][j]; } } return 2.0 * tp / (2.0 * tp + fp + fn); } public static final <A> A deepCopy(final A array) { if (!array.getClass().isArray()) { return array; } final int n = Array.getLength(array); final Object result = Array.newInstance(array.getClass().getComponentType(), n); for (int i = 0; i < n; ++i) { Array.set(result, i, deepCopy(Array.get(array, i))); } return (A) result; } /** * @param commandLineArguments * <br>Must not be null */ public static final void main(final String[] commandLineArguments) { final CommandLineArgumentsParser arguments = new CommandLineArgumentsParser(commandLineArguments); SwingTools.useSystemLookAndFeel(); SwingUtilities.invokeLater(new Runnable() { @Override public final void run() { final JFrame mainFrame = new JFrame(); final JToolBar toolBar = new JToolBar(); final JTree tree = newQuantizerTree(); final Component[] view = { null }; final JComboBox<String> actionSelector = new JComboBox<>(array("Train and classify", "classify")); final double[] bestScore = { 0.0 }; final int[][][] bestConfusionMatrix = { null }; final JLabel bestScoreView = new JLabel(" toolBar.add(actionSelector); toolBar.add(new JButton(new AbstractAction("Run") { private static final long serialVersionUID = 1L; @Override public final void actionPerformed(final ActionEvent event) { final Quantizer quantizer = (Quantizer) tree.getModel().getRoot(); final BufferedImage image = ((ImageComponent) getSharedProperty(mainFrame, "view")).getImage(); final Canvas groundTruth = getSharedProperty(mainFrame, "groundtruth"); final Canvas labels = getSharedProperty(mainFrame, "labels"); if ("Train and classify".equals(actionSelector.getSelectedItem())) { final int clusterCount = quantizer.getChildCount(); final int[] minMaxes = new int[clusterCount * 2]; final IntList[] classPixels = instances(clusterCount, IntList.FACTORY); final int[][] clusterings = new int[clusterCount][]; for (int i = 0; i < clusterCount; ++i) { minMaxes[2 * i + 0] = 1; minMaxes[2 * i + 1] = ((QuantizerCluster) quantizer.getChildAt(i)).getMaximumPrototypeCount(); } final BufferedImage groundtruthImage = groundTruth.getImage(); final int imageWidth = image.getWidth(); PaletteBasedHistograms.forEachPixelIn(groundtruthImage, (x, y) -> { final int label = groundtruthImage.getRGB(x, y); final QuantizerCluster cluster = quantizer.findCluster(label); if (cluster != null) { classPixels[quantizer.getIndex(cluster)].add(y * imageWidth + x); } return true; }); Tools.debugPrint(Arrays.stream(classPixels).map(IntList::size).toArray()); Quantizer bestQuantizer = quantizer.copy(); bestScore[0] = 0.0; bestConfusionMatrix[0] = null; bestScoreView.setText(" for (int scale = 1; scale <= quantizer.getMaximumScale(); ++scale) { quantizer.setScale(scale); Tools.debugPrint(scale); for (final int[] prototypeCounts : cartesian(minMaxes)) { Tools.debugPrint(Arrays.toString(prototypeCounts)); for (int clusterIndex = 0; clusterIndex < clusterCount; ++clusterIndex) { final QuantizerCluster cluster = (QuantizerCluster) quantizer.getChildAt(clusterIndex); final IntList pixels = classPixels[clusterIndex]; final int n = pixels.size(); final int prototypeCount = prototypeCounts[clusterIndex]; clusterings[clusterIndex] = new int[n]; for (int j = 0; j < n; ++j) { clusterings[clusterIndex][j] = j % prototypeCount; } final Iterable<double[]> points = valuesAndWeights(image, classPixels[clusterIndex], scale); double[][] means = null; for (int j = 0; j < 8; ++j) { means = new double[prototypeCount][scale * scale * 3]; final double[] sizes = new double[prototypeCount]; final int[] counts = new int[prototypeCount]; KMeans.computeMeans(points, clusterings[clusterIndex], means, sizes, counts); KMeans.recluster(points, clusterings[clusterIndex], means); } cluster.removeAllChildren(); for (int j = 0; j < prototypeCount; ++j) { final QuantizerPrototype prototype = new QuantizerPrototype(); cluster.add(prototype); final double[] prototypeElements = means[j]; final int[] data = prototype.getData(); for (int k = 0; k < data.length; ++k) { data[k] = a8r8g8b8(0xFF, (int) prototypeElements[3 * k + 0], (int) prototypeElements[3 * k + 1], (int) prototypeElements[3 * k + 2]); } } } final int[][] confusionMatrix = new int[clusterCount][clusterCount]; for (int clusterIndex = 0; clusterIndex < clusterCount; ++clusterIndex) { final int truthIndex = clusterIndex; classPixels[clusterIndex].forEach(pixel -> { final int x = pixel % imageWidth; final int y = pixel / imageWidth; final QuantizerCluster prediction = quantizer.quantize(image, x, y); final int predictionIndex = quantizer.getIndex(prediction); ++confusionMatrix[truthIndex][predictionIndex]; return true; }); } double score = 1.0; for (int i = 0; i < clusterCount; ++i) { score *= f1(confusionMatrix, i); } if (bestScore[0] < score) { bestScore[0] = score; bestConfusionMatrix[0] = deepCopy(confusionMatrix); bestQuantizer = quantizer.copy(); } } } bestScoreView.setText(bestScore[0] + ""); quantizer.set(bestQuantizer); ((DefaultTreeModel) tree.getModel()).nodeStructureChanged(quantizer); mainFrame.validate(); } // TODO Classify Tools.debugPrint("TODO"); } })); toolBar.addSeparator(); toolBar.add(new JButton(new AbstractAction("Confusion matrix...") { @Override public final void actionPerformed(final ActionEvent event) { final List<List<String>> table = new ArrayList<>(); { final Quantizer quantizer = (Quantizer) tree.getModel().getRoot(); final int n = quantizer.getChildCount(); final List<String> header = new ArrayList<>(n + 1); header.add("<td></td>"); for (int i = 0; i < n; ++i) { header.add("<td>" + ((QuantizerCluster) quantizer.getChildAt(i)).getName() + "</td>"); } table.add(header); for (int i = 0; i < n; ++i) { final List<String> row = new ArrayList<>(n + 1); row.add(header.get(i + 1)); for (int j = 0; j < n; ++j) { row.add("<td>" + bestConfusionMatrix[0][i][j] + "</td>"); } table.add(row); } } final JLabel confusionMatrixView = new JLabel("<html><body><table>" + join("", table.stream().map(row -> "<tr>" + join("", row.stream().map(e -> "<td>" + e + "</td>").toArray()) + "</tr>\n" ).toArray()) + "</table></body></html>"); SwingTools.show(confusionMatrixView, "Confusion matrix", false); } private static final long serialVersionUID = -148814823214636457L; })); toolBar.addSeparator(); toolBar.add(new JLabel(" F1: ")); toolBar.add(bestScoreView); tree.addTreeExpansionListener(new TreeExpansionListener() { @Override public final void treeExpanded(final TreeExpansionEvent event) { mainFrame.validate(); } @Override public final void treeCollapsed(final TreeExpansionEvent event) { mainFrame.validate(); } }); mainFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); mainFrame.setPreferredSize(new Dimension(512, 512)); mainFrame.add(toolBar, BorderLayout.NORTH); mainFrame.add(scrollable(tree), BorderLayout.WEST); setSharedProperty(mainFrame, "tree", tree); mainFrame.setDropTarget(new DropTarget() { @Override public final synchronized void drop(final DropTargetDropEvent event) { final File file = SwingTools.getFiles(event).get(0); setView(mainFrame, view, file); preferences.put("filePath", file.getPath()); } /** * {@value}. */ private static final long serialVersionUID = 5442000733451223725L; }); SwingTools.packAndCenter(mainFrame).setVisible(true); { final String filePath = preferences.get("filePath", ""); if (!filePath.isEmpty()) { setView(mainFrame, view, new File(filePath)); } } repeat(mainFrame, 30_000, e -> { final DefaultTreeModel model = (DefaultTreeModel) tree.getModel(); try (final OutputStream output = new FileOutputStream(PALETTE_XML)) { synchronized (model) { writePaletteXML((Quantizer) model.getRoot(), output); final File imageFile = getSharedProperty(mainFrame, "file"); final File groundtruthFile = groundtruthFile(imageFile); Tools.debugPrint("Writing", groundtruthFile); ImageIO.write(((Canvas) getSharedProperty(mainFrame, "groundtruth")).getImage(), "png", groundtruthFile); } } catch (final IOException exception) { exception.printStackTrace(); } }); } }); } public static final File groundtruthFile(final File imageFile) { return new File(baseName(imageFile.getPath()) + "_groundtruth.png"); } public static final void writePaletteXML(final Quantizer quantizer, final OutputStream output) { XMLTools.write(quantizer.accept(new ToXML()), output, 0); } /** * @author codistmonk (creation 2015-01-19) */ public static final class InvertComposite implements Composite { @Override public final CompositeContext createContext(final ColorModel srcColorModel, final ColorModel dstColorModel, final RenderingHints hints) { return new CompositeContext() { @Override public final void dispose() { // NOP } @Override public final void compose(final Raster src, final Raster dstIn, final WritableRaster dstOut) { final Rectangle inBounds = dstIn.getBounds(); final Rectangle outBounds = dstOut.getBounds(); final int[] buffer = dstIn.getPixels(inBounds.x, inBounds.y, inBounds.width, inBounds.height, (int[]) null); int n = buffer.length; for (int i = 0; i < n; ++i) { if (((i + 1) % 4) != 0) { buffer[i] ^= ~0; } } dstOut.setPixels(outBounds.x, outBounds.y, outBounds.width, outBounds.height, buffer); } }; } } /** * @author codistmonk (creation 2015-01-18) */ public static final class ToXML implements QuantizerNode.Visitor<Node> { private final Document xml = XMLTools.newDocument(); @Override public Element visit(final Quantizer quantizer) { final Element result = (Element) this.xml.appendChild(this.xml.createElement("palette")); final int n = quantizer.getChildCount(); result.setAttribute("scale", quantizer.getScaleAsString()); result.setAttribute("maximumScale", quantizer.getMaximumScaleAsString()); for (int i = 0; i < n; ++i) { result.appendChild(((QuantizerCluster) quantizer.getChildAt(i)).accept(this)); } return result; } @Override public final Element visit(final QuantizerCluster cluster) { final Element result = this.xml.createElement("cluster"); final int n = cluster.getChildCount(); result.setAttribute("name", cluster.getName()); result.setAttribute("label", cluster.getLabelAsString()); result.setAttribute("minimumSegmentSize", cluster.getMinimumSegmentSizeAsString()); result.setAttribute("maximumSegmentSize", cluster.getMaximumSegmentSizeAsString()); result.setAttribute("maximumPrototypeCount", cluster.getMaximumPrototypeCountAsString()); for (int i = 0; i < n; ++i) { result.appendChild(((QuantizerPrototype) cluster.getChildAt(i)).accept(this)); } return result; } @Override public final Element visit(final QuantizerPrototype prototype) { final Element result = this.xml.createElement("prototype"); result.setTextContent(prototype.getDataAsString()); return result; } private static final long serialVersionUID = -8012834350224027358L; } public static final QuantizerCluster getSelectedCluster(final JTree tree) { final TreePath selectionPath = tree.getSelectionPath(); return selectionPath == null ? null : cast(QuantizerCluster.class, selectionPath.getLastPathComponent()); } public static final void setView(final JFrame mainFrame, final Component[] view, final File file) { final BufferedImage image = AwtImage2D.awtRead(file.getPath()); final Canvas filtered = new Canvas().setFormat(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); final Canvas groundtruth = new Canvas().setFormat(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); final Canvas labels = new Canvas().setFormat(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); { final File groundtruthFile = groundtruthFile(file); try { groundtruth.getGraphics().drawImage(ImageIO.read(groundtruthFile), 0, 0, null); } catch (final IOException exception) { Tools.debugError(exception); } } setSharedProperty(mainFrame, "groundtruth", groundtruth); setSharedProperty(mainFrame, "labels", labels); setSharedProperty(mainFrame, "file", file); final BufferedImage mask = VisualSegmentation.newMaskFor(image); final ImageComponent newView = new ImageComponent(filtered.getImage()); final JTree tree = getSharedProperty(mainFrame, "tree"); final int[] xys = { -1, 0, 16 }; newView.getBuffer().getSecond().add(new Painter() { @Override public final void paint(final Canvas canvas) { canvas.getGraphics().drawImage(groundtruth.getImage(), 0, 0, null); VisualSegmentation.outlineSegments(labels.getImage(), labels.getImage(), mask, canvas.getImage()); final QuantizerCluster cluster = getSelectedCluster(tree); if (0 <= xys[0]) { final int x = xys[0]; final int y = xys[1]; final int s = xys[2]; final Composite savedComposite = canvas.getGraphics().getComposite(); if (cluster == null) { canvas.getGraphics().setComposite(new InvertComposite()); } else { canvas.getGraphics().setColor(new Color(cluster.getLabel())); } canvas.getGraphics().drawOval(x - s / 2, y - s / 2, s, s); if (cluster == null) { canvas.getGraphics().setComposite(savedComposite); } } } private static final long serialVersionUID = -891880936915736755L; }); new MouseHandler(null) { @Override public final void mousePressed(final MouseEvent event) { this.mouseDragged(event); } @Override public final void mouseDragged(final MouseEvent event) { final int oldX = xys[0]; final int oldY = xys[1]; final int x = xys[0] = event.getX(); final int y = xys[1] = event.getY(); final int s = xys[2]; final QuantizerCluster cluster = getSelectedCluster(tree); final Composite savedComposite = groundtruth.getGraphics().getComposite(); final Stroke savedStroke = groundtruth.getGraphics().getStroke(); if (cluster == null) { groundtruth.getGraphics().setComposite(AlphaComposite.Clear); } else { groundtruth.getGraphics().setColor(new Color(cluster.getLabel())); } groundtruth.getGraphics().setStroke(new java.awt.BasicStroke(s, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); groundtruth.getGraphics().drawLine(oldX, oldY, x, y); groundtruth.getGraphics().setStroke(savedStroke); if (cluster == null) { groundtruth.getGraphics().setComposite(savedComposite); } newView.repaint(); } @Override public final void mouseMoved(final MouseEvent event) { xys[0] = event.getX(); xys[1] = event.getY(); newView.repaint(); } @Override public final void mouseWheelMoved(final MouseWheelEvent event) { if (event.getWheelRotation() < 0) { xys[2] = Math.max(1, xys[2] - 1); } else { ++xys[2]; } newView.repaint(); } @Override public final void mouseExited(final MouseEvent event) { xys[0] = -1; newView.repaint(); } @Override public final void mouseClicked(final MouseEvent event) { if (event.getClickCount() == 2) { final TreePath selectionPath = tree.getSelectionPath(); if (selectionPath != null) { final QuantizerPrototype node = cast(QuantizerPrototype.class, selectionPath.getLastPathComponent()); if (node != null) { Quantizer.extractValues(image, event.getX(), event.getY(), node.getQuantizer().getScale(), node.getData()); tree.getModel().valueForPathChanged(selectionPath, node.renewUserObject()); mainFrame.validate(); } } } } /** * {@value}. */ private static final long serialVersionUID = 6325908040300578842L; }.addTo(newView); final Semaphore modelChanged = new Semaphore(1); final Thread updater = new Thread() { @Override public final void run() { while (!this.isInterrupted()) { try { modelChanged.acquire(); modelChanged.drainPermits(); } catch (final InterruptedException exception) { break; } filtered.getGraphics().drawImage(image, 0, 0, null); final TicToc timer = new TicToc(); // final Map<Integer, List<Pair<Point, Integer>>> labelCells = extractCells( // file, image, mask, labels, segments.getImage(), (PaletteRoot) treeModel.getRoot()); // outlineSegments(segments.getImage(), labels.getImage(), null, filtered.getImage()); // Tools.debugPrint(labelCells.size()); // TODO Tools.debugPrint(timer.toc()); newView.repaint(); } } }; updater.start(); tree.getModel().addTreeModelListener(new TreeModelListener() { @Override public final void treeStructureChanged(final TreeModelEvent event) { this.modelChanged(event); } @Override public final void treeNodesRemoved(final TreeModelEvent event) { this.modelChanged(event); } @Override public final void treeNodesInserted(final TreeModelEvent event) { this.modelChanged(event); } @Override public final void treeNodesChanged(final TreeModelEvent event) { this.modelChanged(event); } private final void modelChanged(final TreeModelEvent event) { ignore(event); modelChanged.release(); mainFrame.validate(); } }); newView.addHierarchyListener(new HierarchyListener() { @Override public final void hierarchyChanged(final HierarchyEvent event) { if ((event.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && !newView.isShowing()) { updater.interrupt(); } } }); setSharedProperty(mainFrame, "view", newView); VisualSegmentation.setView(mainFrame, view, scrollable(VisualSegmentation.center(newView)), file.getName()); } public static final JTree newQuantizerTree() { final DefaultTreeModel treeModel = loadModel(); final JTree result = new JTree(treeModel); result.addMouseListener(new MouseAdapter() { private final JPopupMenu rootPopup; private final JPopupMenu clusterPopup; private final JPopupMenu prototypePopup; private final TreePath[] currentPath; { this.rootPopup = new JPopupMenu(); this.clusterPopup = new JPopupMenu(); this.prototypePopup = new JPopupMenu(); this.currentPath = new TreePath[1]; this.rootPopup.add(newItem("Edit quantizer properties...", e -> { final Quantizer currentNode = (Quantizer) this.currentPath[0].getLastPathComponent(); showEditDialog("Edit quantizer properties", () -> { treeModel.valueForPathChanged(this.currentPath[0], currentNode.renewUserObject()); result.getRootPane().validate(); }, property("scale:", currentNode::getScale, currentNode::setScale), property("maximumScale:", currentNode::getMaximumScale, currentNode::setMaximumScale) ); })); this.rootPopup.add(newItem("Add cluster", e -> { final Quantizer currentNode = (Quantizer) this.currentPath[0].getLastPathComponent(); final QuantizerCluster newNode = new QuantizerCluster().setName("cluster").setLabel(1).setUserObject(); treeModel.insertNodeInto(newNode, currentNode, currentNode.getChildCount()); result.getRootPane().validate(); })); this.clusterPopup.add(newItem("Edit cluster properties...", e -> { final QuantizerCluster currentNode = (QuantizerCluster) this.currentPath[0].getLastPathComponent(); showEditDialog("Edit cluster properties", () -> { treeModel.valueForPathChanged(this.currentPath[0], currentNode.renewUserObject()); result.getRootPane().validate(); }, property("name:", currentNode::getName, currentNode::setName), property("label:", currentNode::getLabelAsString, currentNode::setLabel), property("minimumSegmentSize:", currentNode::getMinimumSegmentSize, currentNode::setMinimumSegmentSize), property("maximumSegmentSize:", currentNode::getMaximumSegmentSize, currentNode::setMaximumSegmentSize), property("maximumPrototypeCount:", currentNode::getMaximumPrototypeCount, currentNode::setMaximumPrototypeCount) ); })); this.clusterPopup.add(newItem("Add prototype", e -> { final QuantizerCluster currentNode = (QuantizerCluster) this.currentPath[0].getLastPathComponent(); final QuantizerNode newNode = new QuantizerPrototype().setUserObject(); treeModel.insertNodeInto(newNode, currentNode, currentNode.getChildCount()); result.getRootPane().validate(); })); this.clusterPopup.add(newItem("Remove cluster", e -> { final QuantizerCluster currentNode = (QuantizerCluster) this.currentPath[0].getLastPathComponent(); treeModel.removeNodeFromParent(currentNode); result.getRootPane().validate(); })); this.prototypePopup.add(newItem("Remove prototype", e -> { final QuantizerPrototype currentNode = (QuantizerPrototype) this.currentPath[0].getLastPathComponent(); treeModel.removeNodeFromParent(currentNode); result.getRootPane().validate(); })); } @Override public final void mouseClicked(final MouseEvent event) { this.mouseUsed(event); } @Override public final void mousePressed(final MouseEvent event) { this.mouseUsed(event); } @Override public final void mouseReleased(final MouseEvent event) { this.mouseUsed(event); } private final void mouseUsed(final MouseEvent event) { if (event.isPopupTrigger()) { final TreePath path = result.getPathForLocation(event.getX(), event.getY()); this.currentPath[0] = path; if (path != null) { final Object node = path.getLastPathComponent(); JPopupMenu popup = null; if (node instanceof Quantizer) { popup = this.rootPopup; } else if (node instanceof QuantizerCluster) { popup = this.clusterPopup; } else if (node instanceof QuantizerPrototype) { popup = this.prototypePopup; } if (popup != null) { popup.show(event.getComponent(), event.getX(), event.getY()); } } } } }); return result; } public static final DefaultTreeModel loadModel() { try { return new DefaultTreeModel(fromXML(Tools.getResourceAsStream(PALETTE_XML))); } catch (final Exception exception) { exception.printStackTrace(); } return new DefaultTreeModel(new Quantizer().setUserObject()); } public static final Quantizer fromXML(final InputStream input) { return load(XMLTools.parse(input), new Quantizer().setUserObject()); } public static final Quantizer load(final Document xml, final Quantizer result) { result.removeAllChildren(); result.setScale(((Element) XMLTools.getNode(xml, "palette")).getAttribute("scale")); result.setMaximumScale(((Element) XMLTools.getNode(xml, "palette")).getAttribute("maximumScale")); for (final Node clusterNode : XMLTools.getNodes(xml, "palette/cluster")) { final Element clusterElement = (Element) clusterNode; final QuantizerCluster cluster = new QuantizerCluster() .setName(clusterElement.getAttribute("name")) .setLabel(clusterElement.getAttribute("label")) .setMinimumSegmentSize(clusterElement.getAttribute("minimumSegmentSize")) .setMaximumSegmentSize(clusterElement.getAttribute("maximumSegmentSize")) .setMaximumPrototypeCount(clusterElement.getAttribute("maximumPrototypeCount")) .setUserObject(); result.add(cluster); for (final Node prototypeNode : XMLTools.getNodes(clusterNode, "prototype")) { final QuantizerPrototype prototype = new QuantizerPrototype(); cluster.add(prototype); prototype.setData(prototypeNode.getTextContent()).setUserObject(); } } return result; } /** * @author codistmonk (creation 2015-01-16) */ public static final class ImageComponent extends JComponent { private final BufferedImage image; private final Pair<Canvas, List<Painter>> buffer; public ImageComponent(final BufferedImage image) { this.image = image; final int imageWidth = image.getWidth(); final int imageHeight = image.getHeight(); this.buffer = new Pair<>( new Canvas().setFormat(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB), new ArrayList<>()); this.setMinimumSize(new Dimension(imageWidth, imageHeight)); this.setMaximumSize(new Dimension(imageWidth, imageHeight)); this.setPreferredSize(new Dimension(imageWidth, imageHeight)); this.setSize(new Dimension(imageWidth, imageHeight)); } public final BufferedImage getImage() { return this.image; } public final Pair<Canvas, List<Painter>> getBuffer() { return this.buffer; } @Override protected final void paintComponent(final Graphics g) { super.paintComponent(g); final Pair<Canvas, List<Painter>> buffer = this.getBuffer(); final Canvas canvas = buffer.getFirst(); canvas.getGraphics().drawImage(this.getImage(), 0, 0, null); buffer.getSecond().forEach(p -> p.paint(canvas)); g.drawImage(canvas.getImage(), 0, 0, null); } private static final long serialVersionUID = 1260599901446126551L; public static final Color CLEAR = new Color(0, true); /** * @author codistmonk (creation 2015-01-16) */ public static abstract interface Painter extends Serializable { public abstract void paint(Canvas canvas); } } /** * @author codistmonk (creation 2015-01-16) */ public static abstract class QuantizerNode extends DefaultMutableTreeNode { public abstract QuantizerNode copy(); public abstract <V> V accept(Visitor<V> visitor); public abstract QuantizerNode setUserObject(); public final UserObject renewUserObject() { return (UserObject) this.setUserObject().getUserObject(); } protected final <N extends QuantizerNode> N copyChildrenTo(final N node) { final int n = this.getChildCount(); for (int i = 0; i < n; ++i) { final QuantizerNode child = ((QuantizerNode) this.getChildAt(i)).copy(); node.add(child); } return node; } @SuppressWarnings("unchecked") public final <N extends QuantizerNode> N visitChildren(final Visitor<?> visitor) { final int n = this.getChildCount(); for (int i = 0; i < n; ++i) { ((QuantizerNode) this.getChildAt(i)).accept(visitor); } return (N) this; } private static final long serialVersionUID = 7636724853656189383L; public static final int parseARGB(final String string) { return string.startsWith("#") ? (int) Long.parseLong(string.substring(1), 16) : Integer.parseInt(string); } /** * @author codistmonk (creation 2015-01-18) */ public abstract class UserObject implements Serializable { private static final long serialVersionUID = 1543313797613503533L; } /** * @author codistmonk (creation 2015-01-16) */ public static abstract interface Visitor<V> extends Serializable { public abstract V visit(Quantizer quantizer); public abstract V visit(QuantizerCluster cluster); public abstract V visit(QuantizerPrototype prototype); } } /** * @author codistmonk (creation 2015-01-16) */ public static final class Quantizer extends QuantizerNode { private int[] buffer = new int[1]; private int scale = 1; private int maximumScale = 1; @Override public final Quantizer copy() { final Quantizer result = new Quantizer(); result.buffer = this.buffer.clone(); result.scale = this.scale; result.maximumScale = this.maximumScale; return this.copyChildrenTo(result); } public final Quantizer set(final Quantizer that) { this.buffer = that.buffer.clone(); this.scale = that.scale; this.maximumScale = that.maximumScale; final int n = that.getChildCount(); this.removeAllChildren(); for (int i = 0; i < n; ++i) { this.add(((QuantizerNode) that.getChildAt(i)).copy()); } return (Quantizer) this.accept(new Visitor<QuantizerNode>() { @Override public final QuantizerNode visit(final Quantizer quantizer) { return quantizer.visitChildren(this).setUserObject(); } @Override public final QuantizerNode visit(final QuantizerCluster cluster) { return cluster.visitChildren(this).setUserObject(); } @Override public final QuantizerNode visit(final QuantizerPrototype prototype) { return prototype.visitChildren(this).setUserObject(); } private static final long serialVersionUID = 6586780367368082696L; }); } @Override public final Quantizer setUserObject() { this.setUserObject(this.new UserObject() { @Override public final String toString() { return "scale: " + Quantizer.this.getScaleAsString(); } private static final long serialVersionUID = 948766593376210016L; }); return this; } public final int getScale() { return this.scale; } public final Quantizer setScale(final int scale) { if (scale <= 0) { throw new IllegalArgumentException(); } if (scale != this.getScale()) { this.scale = scale; this.buffer = new int[scale * scale]; } return this; } public final String getScaleAsString() { return Integer.toString(this.getScale()); } public final Quantizer setScale(final String scaleAsString) { return this.setScale(Integer.parseInt(scaleAsString)); } public final int getMaximumScale() { return this.maximumScale; } public final Quantizer setMaximumScale(final int maximumScale) { if (maximumScale <= 0) { throw new IllegalArgumentException(); } this.maximumScale = maximumScale; return this; } public final String getMaximumScaleAsString() { return Integer.toString(this.getMaximumScale()); } public final Quantizer setMaximumScale(final String maximumScaleAsString) { this.setMaximumScale(Integer.parseInt(maximumScaleAsString)); return this; } public final QuantizerCluster quantize(final BufferedImage image, final int x, final int y) { extractValues(image, x, y, this.getScale(), this.buffer); final int n = this.getChildCount(); QuantizerCluster result = null; double bestDistance = Double.POSITIVE_INFINITY; for (int i = 0; i < n; ++i) { final QuantizerCluster cluster = (QuantizerCluster) this.getChildAt(i); final double distance = cluster.distanceTo(this.buffer); if (distance < bestDistance) { result = cluster; bestDistance = distance; } } return result; } public final QuantizerCluster findCluster(final String name) { final int n = this.getChildCount(); for (int i = 0; i < n; ++i) { final QuantizerCluster cluster = (QuantizerCluster) this.getChildAt(i); if (name.equals(cluster.getName())) { return cluster; } } return null; } public final QuantizerCluster findCluster(final int label) { final int n = this.getChildCount(); for (int i = 0; i < n; ++i) { final QuantizerCluster cluster = (QuantizerCluster) this.getChildAt(i); if (label == cluster.getLabel()) { return cluster; } } return null; } @Override public final <V> V accept(final Visitor<V> visitor) { return visitor.visit(this); } private static final long serialVersionUID = 3228746395868315788L; public static final int[] extractValues(final BufferedImage image, final int x, final int y, final int patchSize, final int[] result) { Arrays.fill(result, 0); final int width = image.getWidth(); final int height = image.getHeight(); final int s = patchSize / 2; final int left = x - s; final int right = left + patchSize; final int top = y - s; final int bottom = top + patchSize; for (int yy = top, i = 0; yy < bottom; ++yy) { if (0 <= yy && yy < height) { for (int xx = left; xx < right; ++xx, ++i) { if (0 <= xx && xx < width) { result[i] = image.getRGB(xx, yy); } } } else { i += patchSize; } } return result; } } /** * @author codistmonk (creation 2015-01-16) */ public static final class QuantizerCluster extends QuantizerNode { private String name = "cluster"; private int label = 1; private int minimumSegmentSize = 0; private int maximumSegmentSize = Integer.MAX_VALUE; private int maximumPrototypeCount = 1; @Override public final QuantizerCluster copy() { final QuantizerCluster result = new QuantizerCluster(); result.name = this.name; result.label = this.label; result.minimumSegmentSize = this.minimumSegmentSize; result.maximumSegmentSize = this.maximumSegmentSize; result.maximumPrototypeCount = this.maximumPrototypeCount; return this.copyChildrenTo(result).setUserObject(); } @Override public final QuantizerCluster setUserObject() { this.setUserObject(this.new UserObject() { @Override public final String toString() { final boolean showMaximum = QuantizerCluster.this.getMaximumSegmentSize() != Integer.MAX_VALUE; return QuantizerCluster.this.getName() + " (" + QuantizerCluster.this.getLabelAsString() + " " + QuantizerCluster.this.getMinimumSegmentSizeAsString() + ".." + (showMaximum ? QuantizerCluster.this.getMaximumSegmentSizeAsString() : "") + ")"; } private static final long serialVersionUID = 1507012060737286549L; }); return this; } public final String getName() { return this.name; } public final QuantizerCluster setName(final String name) { this.name = name; return this; } @Override public final Quantizer getParent() { return (Quantizer) super.getParent(); } public final Quantizer getQuantizer() { return this.getParent(); } public final int getLabel() { return this.label; } public final QuantizerCluster setLabel(final int label) { this.label = label; return this; } public final String getLabelAsString() { return "#" + Integer.toHexString(this.label).toUpperCase(Locale.ENGLISH); } public final QuantizerCluster setLabel(final String labelAsString) { this.setLabel(parseARGB(labelAsString)); return this; } public final int getMinimumSegmentSize() { return this.minimumSegmentSize; } public final QuantizerCluster setMinimumSegmentSize(final int minimumSegmentSize) { this.minimumSegmentSize = minimumSegmentSize; return this; } public final String getMinimumSegmentSizeAsString() { return Integer.toString(this.getMinimumSegmentSize()); } public final QuantizerCluster setMinimumSegmentSize(final String minimumSegmentSizeAsString) { this.setMinimumSegmentSize(Integer.parseInt(minimumSegmentSizeAsString)); return this; } public final int getMaximumSegmentSize() { return this.maximumSegmentSize; } public final QuantizerCluster setMaximumSegmentSize(final int maximumSegmentSize) { this.maximumSegmentSize = maximumSegmentSize; return this; } public final String getMaximumSegmentSizeAsString() { return Integer.toString(this.getMaximumSegmentSize()); } public final QuantizerCluster setMaximumSegmentSize(final String maximumSegmentSizeAsString) { this.setMaximumSegmentSize(Integer.parseInt(maximumSegmentSizeAsString)); return this; } public final int getMaximumPrototypeCount() { return this.maximumPrototypeCount; } public final QuantizerCluster setMaximumPrototypeCount(final int maximumPrototypeCount) { if (maximumPrototypeCount <= 0) { throw new IllegalArgumentException(); } this.maximumPrototypeCount = maximumPrototypeCount; return this; } public final String getMaximumPrototypeCountAsString() { return Integer.toString(this.getMaximumPrototypeCount()); } public final QuantizerCluster setMaximumPrototypeCount(final String maximumPrototypeCountAsString) { this.setMaximumPrototypeCount(Integer.parseInt(maximumPrototypeCountAsString)); return this; } public final double distanceTo(final int[] values) { final int n = this.getChildCount(); double result = Double.POSITIVE_INFINITY; for (int i = 0; i < n; ++i) { final double distance = ((QuantizerPrototype) this.getChildAt(i)).distanceTo(values); if (distance < result) { result = distance; } } return result; } @Override public final <V> V accept(final Visitor<V> visitor) { return visitor.visit(this); } private static final long serialVersionUID = -3727849715989585298L; } /** * @author codistmonk (creation 2015-01-16) */ public static final class QuantizerPrototype extends QuantizerNode { private int[] data = new int[0]; @Override public final QuantizerPrototype copy() { final QuantizerPrototype result = new QuantizerPrototype(); result.data = this.data.clone(); return this.copyChildrenTo(result).setUserObject(); } @Override public final QuantizerPrototype setUserObject() { this.setUserObject(this.new UserObject() { @Override public final String toString() { return QuantizerPrototype.this.getDataAsString(); } private static final long serialVersionUID = 4617070174363518324L; }); return this; } public final int[] getData() { final Quantizer root = cast(Quantizer.class, this.getRoot()); if (root == null) { return null; } final int n = root.getScale() * root.getScale(); if (this.data.length != n) { this.data = new int[n]; } return this.data; } public final String getDataAsString() { return Tools.join(",", Arrays.stream(this.getData()).mapToObj( i -> "#" + Integer.toHexString(i).toUpperCase(Locale.ENGLISH)).toArray()); } public final QuantizerPrototype setData(final String dataAsString) { final int[] parsed = Arrays.stream(dataAsString.split(",")).mapToInt(QuantizerNode::parseARGB).toArray(); System.arraycopy(parsed, 0, this.getData(), 0, this.getData().length); return this; } @Override public final QuantizerCluster getParent() { return (QuantizerCluster) super.getParent(); } public final Quantizer getQuantizer() { return this.getParent().getParent(); } public final double distanceTo(final int[] values) { final int n = values.length; if (n != this.getData().length) { throw new IllegalArgumentException(); } double result = 0.0; for (int i = 0; i < n; ++i) { final int thisRGB = this.data[i]; final int thatRGB = values[i]; result += abs(red8(thisRGB) - red8(thatRGB)) + abs(green8(thisRGB) - green8(thatRGB)) + abs(blue8(thisRGB) - blue8(thatRGB)); } return result; } @Override public final <V> V accept(final Visitor<V> visitor) { return visitor.visit(this); } private static final long serialVersionUID = 946728342547485375L; } }
package logbook.gui.logic; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import logbook.constants.AppConstants; import logbook.dto.AirBattleDto; import logbook.dto.BattleAtackDto; import logbook.dto.BattleExDto; import logbook.dto.BattleExDto.Phase; import logbook.dto.BattleResultDto; import logbook.dto.ItemDto; import logbook.dto.ShipBaseDto; import logbook.dto.ShipDto; import logbook.internal.Item; /** * @author Nekopanda * */ public class BattleHtmlGenerator extends HTMLGenerator { private static String getRowSpan(int span) { return "rowspan=\"" + span + "\""; } private static String getColSpan(int span) { return "colspan=\"" + span + "\""; } private static DateFormat dateFormat = new SimpleDateFormat(AppConstants.DATE_FORMAT); private static String[] BOX_CLASS = new String[] { "box" }; private static String[][][] TEXT_CLASS = new String[][][] { new String[][] { new String[] { "friend" }, new String[] { "enemy" } }, new String[][] { new String[] { "friend" }, new String[] { "enemy" } } }; private static String[] DAMAGE_CLASS = new String[] { "damage" }; private static String[][] DAMAGE_LABEL_CLASS = new String[][] { new String[] { "label-mukizu" }, new String[] { "label-kenzai" }, new String[] { "label-syoha" }, new String[] { "label-tyuha" }, new String[] { "label-taiha" }, new String[] { "label-gotin" } }; private static String[][] PARAM_TABLE_CLASS = new String[][] { new String[] { "friend", "friend-param" }, new String[] { "enemy", "enemy-param" } }; private static String[][] SLOTITEM_TABLE_CLASS = new String[][] { new String[] { "friend", "friend-slotitem" }, new String[] { "enemy", "enemy-slotitem" } }; private static String[][] FORMATION_CLASS = new String[][] { new String[] { "friend", "friend-formation" }, new String[] { "enemy", "enemy-formation" } }; private static String[][] DAMAGE_TABLE_CLASS = new String[][] { new String[] { "friend", "friend-damage" }, new String[] { "enemy", "enemy-damage" } }; private static String[][][] AIR_DAMAGE_TABLE_CLASS = new String[][][] { new String[][] { new String[] { "friend", "friend-air-atack" }, new String[] { "enemy", "enemy-air-damage" } }, new String[][] { new String[] { "enemy", "enemy-air-atack" }, new String[] { "friend", "friend-air-damage" } } }; private static String[] AIR_TABLE_CLASS = new String[] { "air-stage12" }; private static String[][][] RAIGEKI_DAMAGE_TABLE_CLASS = new String[][][] { new String[][] { new String[] { "friend", "friend-raigeki-atack" }, new String[] { "enemy", "enemy-raigeki-damage" } }, new String[][] { new String[] { "enemy", "enemy-raigeki-atack" }, new String[] { "friend", "friend-raigeki-damage" } } }; private String getShipName(ShipBaseDto[] ships, int index) { return String.valueOf(index + 1) + "." + ships[index].getFriendlyName(); } /** * * @param gen * @param tableTitle * @param ships * @param hp * @param phaseName */ private <SHIP extends ShipBaseDto> void genParmeters(String tableTitle, List<SHIP> ships, int[][] hp, String[] phaseName) { if (ships.size() == 0) { return; } boolean isFriend; int ci; if (ships.get(0) instanceof ShipDto) { isFriend = true; ci = 0; } else { isFriend = false; ci = 1; } int numPhases = (hp.length / 2) - 1; this.begin("div", BOX_CLASS); this.begin("table", PARAM_TABLE_CLASS[ci]); this.inline("caption", tableTitle, null); this.begin("tr", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "cond.", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); for (int i = 0; i < numPhases; ++i) { this.inline("th", "", null); this.inline("th", "Dmg", null); this.inline("th", "", null); this.inline("th", "", null); } this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); this.end(); int totalSeiku = 0; double totalSakuteki = 0; int totalNowHp = 0; int totalMaxHp = 0; for (int i = 0; i < ships.size(); ++i) { SHIP ship = ships.get(i); int seiku = ship.getSeiku(); SakutekiString sakuteki = new SakutekiString(ship); int nowhp = hp[0][i]; int maxhp = hp[1][i]; totalSeiku += seiku; totalSakuteki += sakuteki.getValue(); totalNowHp += nowhp; totalMaxHp += maxhp; this.begin("tr", null); this.inline("td", String.valueOf(i + 1), null); this.inline("td", ship.getFriendlyName(), null); if (isFriend) { this.inline("td", String.valueOf(((ShipDto) ship).getCond()), null); } else { this.inline("td", "", null); } this.inline("td", String.valueOf(seiku), null); this.inline("td", sakuteki.toString(), null); this.inline("td", nowhp + "/" + maxhp, null); for (int p = 1; p <= numPhases; ++p) { if (i == 0) { this.inline("td", getRowSpan(ships.size()), "→", null); } int dam = hp[(p * 2) + 0][i]; int remain = hp[(p * 2) + 1][i]; DamageRate rate = DamageRate.fromHP(remain, maxhp); this.inline("td", String.valueOf(dam), null); this.inline("td", String.valueOf(remain), null); this.inline("td", rate.toString(), DAMAGE_LABEL_CLASS[rate.getLevel()]); } this.inline("td", String.valueOf(ship.getKaryoku()), null); this.inline("td", String.valueOf(ship.getRaisou()), null); this.inline("td", String.valueOf(ship.getTaiku()), null); this.inline("td", String.valueOf(ship.getSoukou()), null); this.inline("td", String.valueOf(ship.getKaihi()), null); this.inline("td", String.valueOf(ship.getTaisen()), null); this.inline("td", String.valueOf(ship.getSakuteki()), null); this.inline("td", String.valueOf(ship.getLucky()), null); this.inline("td", String.valueOf(ship.getParam().getSoku()), null); this.inline("td", String.valueOf(ship.getParam().getLeng()), null); this.end(); } this.begin("tr", null); this.inline("td", "", null); this.inline("td", "", null); this.inline("td", "", null); this.inline("td", String.valueOf(totalSeiku), null); this.inline("td", String.format("%.1f", totalSakuteki), null); this.inline("td", totalNowHp + "/" + totalMaxHp, null); for (int i = 0; i < numPhases; ++i) { this.inline("td", "", null); this.inline("td", getColSpan(3), phaseName[i], null); } this.inline("td", getColSpan(10), "", null); this.end(); this.end(); // table this.end(); } /** * * @param gen * @param ships */ private <SHIP extends ShipBaseDto> void genSlotitemTable(List<SHIP> ships) { if (ships.size() == 0) { return; } int ci = (ships.get(0) instanceof ShipDto) ? 0 : 1; this.begin("div", BOX_CLASS); this.begin("table", SLOTITEM_TABLE_CLASS[ci]); this.begin("tr", null); this.inline("th", "", null); for (int c = 0; c < 5; ++c) { this.inline("th", getColSpan(2), "" + (c + 1), null); } this.end(); for (int i = 0; i < ships.size(); ++i) { this.begin("tr", null); SHIP ship = ships.get(i); this.inline("td", String.valueOf(i + 1) + "." + ship.getFriendlyName(), null); List<ItemDto> items = ship.getItem(); for (int c = 0; c < 5; ++c) { String onSlot = ""; String itemName = String.valueOf(c + 1) + ". "; int[] onSlots = ship.getOnSlot(); int[] maxeq = ship.getShipInfo().getMaxeq(); if (c < items.size()) { ItemDto item = items.get(c); if (item != null) { if (item.isPlane()) { String max = (maxeq == null) ? "?" : String.valueOf(maxeq[c]); onSlot = String.valueOf(onSlots[c]) + "/" + max; } itemName += item.getName(); } } this.inline("td", itemName, null); this.inline("td", onSlot, null); } this.end(); } this.end(); // table this.end(); } /** * * @param gen * @param battle */ private void genFormation(BattleExDto battle) { String fSakuteki = ""; String eSakuteki = ""; if (battle.getSakuteki() != null) { fSakuteki = battle.getSakuteki()[0]; eSakuteki = battle.getSakuteki()[1]; } this.inline("span", ": " + battle.getFormationMatch(), null); this.begin("table", null); this.begin("tr", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); this.end(); this.begin("tr", FORMATION_CLASS[0]); this.inline("td", "", null); this.inline("td", battle.getFormation()[0], null); this.inline("td", fSakuteki, null); this.end(); this.begin("tr", null); this.inline("td", "", FORMATION_CLASS[1]); this.inline("td", battle.getFormation()[1], null); this.inline("td", eSakuteki, null); this.end(); this.end(); // table } /** * * @param stage * @return */ private static String[] getNumPlaneString(int[] stage) { if (stage == null) { return new String[] { "", "" }; } int flost = stage[0]; int fall = stage[1]; int elost = stage[2]; int eall = stage[3]; int fremain = fall - flost; int eremain = eall - elost; return new String[] { String.valueOf(fall) + "→" + fremain + " (-" + flost + ")", String.valueOf(eall) + "→" + eremain + " (-" + elost + ")" }; } /** * * @param touchPlane * @return */ private static String[] getTouchPlane(int[] touchPlane) { if (touchPlane == null) { return new String[] { "", "" }; } String[] ret = new String[2]; for (int i = 0; i < 2; ++i) { if (touchPlane[i] == -1) { ret[i] = ""; } else { ItemDto item = Item.get(touchPlane[i]); if (item != null) { ret[i] = item.getName(); } else { ret[i] = ""; } } } return ret; } private static <T> void copyToOffset(List<? extends T> src, T[] array, int offset) { if (src == null) { return; } for (int i = 0; i < src.size(); ++i) { array[i + offset] = src.get(i); } } private static void copyToOffset(int[] src, int[] dst, int offset) { if (src == null) { return; } System.arraycopy(src, 0, dst, offset, src.length); } /** * * @param hp * @param target * @param damage * @param index * @return */ private static String doDamage(int[] hp, int[] target, int[] damage, int index) { int before = hp[target[index]]; int after = before - damage[index]; if (after < 0) { after = 0; } if (before == after) { return ""; } hp[target[index]] = after; return String.valueOf(before) + "→" + after; } private static String getDamageString(int damage) { if (damage == 0) { return ""; } return String.valueOf(damage); } private void genDamageTableContent(BattleAtackDto atack, ShipBaseDto[] targetShips, int[] targetHp) { if (atack.damage.length == 0) { this.begin("tr", null); this.inline("td", "", null); this.end(); return; } this.begin("tr", null); this.inline("th", "", null); this.inline("th", "", DAMAGE_CLASS); this.inline("th", "HP", null); this.end(); for (int i = 0; i < atack.damage.length; ++i) { this.begin("tr", null); this.inline("td", this.getShipName(targetShips, atack.target[i]), null); this.inline("td", getDamageString(atack.damage[i]), DAMAGE_CLASS); this.inline("td", doDamage(targetHp, atack.target, atack.damage, i), null); this.end(); } } private void genAtackTableContent(BattleAtackDto atack, ShipBaseDto[] originShips, ShipBaseDto[] targetShips) { int ci = (atack.friendAtack) ? 0 : 1; this.begin("tr", null); this.inline("th", "", TEXT_CLASS[ci][0]); this.inline("th", "", null); this.inline("th", "", TEXT_CLASS[ci][1]); this.inline("th", "", DAMAGE_CLASS); this.end(); for (int i = 0; i < atack.origin.length; ++i) { this.begin("tr", null); this.inline("td", this.getShipName(originShips, atack.origin[i]), TEXT_CLASS[ci][0]); this.inline("td", "→", null); this.inline("td", this.getShipName(targetShips, atack.target[atack.ot[i]]), TEXT_CLASS[ci][1]); this.inline("td", getDamageString(atack.ydam[i]), DAMAGE_CLASS); this.end(); } } /** * * @param gen * @param atacks * @param friendShips * @param enemyShips * @param friendHp * @param enemyHp */ private void genHougekiTableContent(List<BattleAtackDto> atacks, ShipBaseDto[] friendShips, ShipBaseDto[] enemyShips, int[] friendHp, int[] enemyHp) { this.begin("tr", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "", null); this.inline("th", "HP", null); this.end(); for (BattleAtackDto atack : atacks) { ShipBaseDto[] origin; ShipBaseDto[] target; int[] targetHp; String[] text; String[][] textClass; if (atack.friendAtack) { origin = friendShips; target = enemyShips; targetHp = enemyHp; text = new String[] { "", "" }; textClass = TEXT_CLASS[0]; } else { origin = enemyShips; target = friendShips; targetHp = friendHp; text = new String[] { "", "" }; textClass = TEXT_CLASS[1]; } for (int i = 0; i < atack.damage.length; ++i) { this.begin("tr", null); if (i == 0) { this.inline("td", text[0], null); this.inline("td", this.getShipName(origin, atack.origin[0]), textClass[0]); } else { this.inline("td", getColSpan(2), "", null); } this.inline("td", "→", null); this.inline("td", text[1], null); this.inline("td", this.getShipName(target, atack.target[i]), textClass[1]); this.inline("td", getDamageString(atack.damage[i]), DAMAGE_CLASS); this.inline("td", doDamage(targetHp, atack.target, atack.damage, i), textClass[1]); this.end(); } } } /** * * @param gen * @param air * @param title * @param friendShips * @param enemyShips * @param friendHp * @param enemyHp */ private void genAirBattle(AirBattleDto air, String title, ShipBaseDto[] friendShips, ShipBaseDto[] enemyShips, int[] friendHp, int[] enemyHp) { if (air == null) { return; } this.inline("h3", title, AIR_TABLE_CLASS); String[] stage1 = getNumPlaneString(air.stage1); String[] stage2 = getNumPlaneString(air.stage2); String[] touch = getTouchPlane(air.touchPlane); this.begin("table", null); this.begin("tr", null); this.inline("th", getRowSpan(2), "", null); this.inline("th", getRowSpan(2), "", null); this.inline("th", getColSpan(2), "", null); this.inline("th", getRowSpan(2), "", null); this.end(); this.begin("tr", null); this.inline("th", "1", null); this.inline("th", "2", null); this.end(); this.begin("tr", TEXT_CLASS[0][0]); this.inline("td", "", null); this.inline("td", air.seiku, null); this.inline("td", stage1[0], null); this.inline("td", stage2[0], null); this.inline("td", touch[0], null); this.end(); this.begin("tr", null); this.inline("td", "", TEXT_CLASS[0][1]); this.inline("td", "", null); this.inline("td", stage1[1], null); this.inline("td", stage2[1], null); this.inline("td", touch[1], null); this.end(); this.end(); // table if ((air.atacks == null) || (air.atacks.size() == 0)) { this.inline("h4", "", null); return; } for (BattleAtackDto atack : air.atacks) { ShipBaseDto[] origin; ShipBaseDto[] target; int[] targetHp; String[] text; String[][] textClass; if (atack.friendAtack) { origin = friendShips; target = enemyShips; targetHp = enemyHp; text = new String[] { "", "" }; textClass = AIR_DAMAGE_TABLE_CLASS[0]; } else { origin = enemyShips; target = friendShips; targetHp = friendHp; text = new String[] { "", "" }; textClass = AIR_DAMAGE_TABLE_CLASS[1]; } this.begin("div", BOX_CLASS); this.inline("span", text[0] + ": ", null); this.begin("table", textClass[0]); if (atack.origin.length == 0) { this.begin("tr", null); this.inline("td", "", null); this.end(); } else { for (int i = 0; i < atack.origin.length; ++i) { this.begin("tr", null); this.inline("td", this.getShipName(origin, atack.origin[i]), null); this.end(); } } this.end(); // table this.end(); this.begin("div", BOX_CLASS); this.inline("span", text[1], null); this.begin("table", textClass[1]); this.genDamageTableContent(atack, target, targetHp); this.end(); // table this.end(); } } /** * * @param gen * @param raigeki * @param title * @param friendShips * @param enemyShips * @param friendHp * @param enemyHp */ private void genRaigekiBattle(List<BattleAtackDto> raigeki, String title, ShipBaseDto[] friendShips, ShipBaseDto[] enemyShips, int[] friendHp, int[] enemyHp) { if ((raigeki == null) || (raigeki.size() == 0)) { return; } this.inline("h3", title, null); for (BattleAtackDto atack : raigeki) { ShipBaseDto[] origin; ShipBaseDto[] target; int[] targetHp; String[] text; String[][] textClass; if (atack.friendAtack) { origin = friendShips; target = enemyShips; targetHp = enemyHp; text = new String[] { "", "" }; textClass = RAIGEKI_DAMAGE_TABLE_CLASS[0]; } else { origin = enemyShips; target = friendShips; targetHp = friendHp; text = new String[] { "", "" }; textClass = RAIGEKI_DAMAGE_TABLE_CLASS[1]; } this.begin("div", BOX_CLASS); this.inline("span", text[0], null); this.begin("table", textClass[0]); this.genAtackTableContent(atack, origin, target); this.end(); // table this.end(); this.begin("div", BOX_CLASS); this.inline("span", text[1], null); this.begin("table", textClass[1]); this.genDamageTableContent(atack, target, targetHp); this.end(); // table this.end(); } } /** * * @param gen * @param battle * @param index */ private void genPhase(BattleExDto battle, int index, ShipBaseDto[] friendShips, ShipBaseDto[] enemyShips, int[] friendHp, int[] enemyHp) { BattleExDto.Phase phase = battle.getPhaseList().get(index); List<AirBattleDto> airList = new ArrayList<>(); List<List<BattleAtackDto>> hougekiList = new ArrayList<>(); if (phase.getAir() != null) airList.add(phase.getAir()); if (phase.getAir2() != null) airList.add(phase.getAir2()); if (phase.getHougeki1() != null) hougekiList.add(phase.getHougeki1()); if (phase.getHougeki2() != null) hougekiList.add(phase.getHougeki2()); if (phase.getHougeki3() != null) hougekiList.add(phase.getHougeki3()); for (int i = 0; i < airList.size(); ++i) { this.genAirBattle(airList.get(i), "(" + (i + 1) + "/" + airList.size() + ")", friendShips, enemyShips, friendHp, enemyHp); if (i == 0) { if (phase.getSupport() != null) { for (BattleAtackDto atack : phase.getSupport()) { this.inline("span", "", null); this.begin("table", DAMAGE_TABLE_CLASS[1]); this.genDamageTableContent(atack, enemyShips, enemyHp); this.end(); // table } } if (phase.getOpening() != null) { this.genRaigekiBattle(phase.getOpening(), "", friendShips, enemyShips, friendHp, enemyHp); } } } if (phase.getHougeki() != null) { this.inline("h3", "", null); this.begin("table", null); this.genHougekiTableContent(phase.getHougeki(), friendShips, enemyShips, friendHp, enemyHp); this.end(); // table } for (int i = 0; i < hougekiList.size(); ++i) { this.inline("h3", "(" + (i + 1) + "/" + hougekiList.size() + ")", null); this.begin("table", null); this.genHougekiTableContent(hougekiList.get(i), friendShips, enemyShips, friendHp, enemyHp); this.end(); // table if (battle.isCombined() && (i == 0)) { this.genRaigekiBattle(phase.getRaigeki(), "", friendShips, enemyShips, friendHp, enemyHp); } } if (battle.isCombined() == false) { this.genRaigekiBattle(phase.getRaigeki(), "", friendShips, enemyShips, friendHp, enemyHp); } } /** * * @param friend * @param enemy * @param phase */ private void computeDamages(int[] friend, int[] enemy, BattleExDto.Phase phase) { for (int i = 0; i < friend.length; ++i) { friend[i] = 0; } for (int i = 0; i < enemy.length; ++i) { enemy[i] = 0; } for (BattleAtackDto[] atacks : phase.getAtackSequence()) { if (atacks != null) { for (BattleAtackDto dto : atacks) { for (int i = 0; i < dto.target.length; ++i) { int target = dto.target[i]; int damage = dto.damage[i]; if (dto.friendAtack) { enemy[target] += damage; } else { friend[target] += damage; } } } } } } /** * HP -> HP * @param start * @param inDam * @param offset * @param dam * @param after */ private void storeDamageAndHp(int[] start, int[] inDam, int offset, int[] dam, int[] after) { if (start != null) { for (int i = 0; i < start.length; ++i) { dam[i] = inDam[offset + i]; after[i] = Math.max(0, start[i] - inDam[offset + i]); } } } /** * HP * [][now, max, , ][] * @param battle * @return */ private int[][][] calcHP(BattleExDto battle) { int[][][] hp = new int[3][2 + (battle.getPhaseList().size() * 2)][6]; int[][] startHp = new int[][] { battle.getStartFriendHp(), battle.getStartFriendHpCombined(), battle.getStartEnemyHp() }; hp[0][0] = battle.getStartFriendHp(); hp[1][0] = battle.getStartFriendHpCombined(); hp[2][0] = battle.getStartEnemyHp(); hp[0][1] = battle.getMaxFriendHp(); hp[1][1] = battle.getMaxFriendHpCombined(); hp[2][1] = battle.getMaxEnemyHp(); int[] friendDamages = new int[12]; int[] enemyDamages = new int[6]; for (int pi = 0; pi < battle.getPhaseList().size(); ++pi) { BattleExDto.Phase phase = battle.getPhaseList().get(pi); this.computeDamages(friendDamages, enemyDamages, phase); this.storeDamageAndHp(startHp[0], friendDamages, 0, hp[0][(pi * 2) + 2], hp[0][(pi * 2) + 3]); this.storeDamageAndHp(startHp[1], friendDamages, 6, hp[1][(pi * 2) + 2], hp[1][(pi * 2) + 3]); this.storeDamageAndHp(startHp[2], enemyDamages, 0, hp[2][(pi * 2) + 2], hp[2][(pi * 2) + 3]); startHp = new int[][] { hp[0][(pi * 2) + 3], hp[1][(pi * 2) + 3], hp[2][(pi * 2) + 3] }; } return hp; } private void genResultTable(BattleResultDto result, BattleExDto detail) { this.begin("table", null); this.begin("tr", null); this.inline("td", "", null); this.inline("td", detail.getRank().toString(), null); this.end(); String mvp1 = (result.getMvp() == null) ? "" : result.getMvp().getFriendlyName(); String mvp2 = (result.getMvpCombined() == null) ? "" : result.getMvpCombined().getFriendlyName(); if (detail.isCombined()) { this.begin("tr", null); this.inline("td", "MVP()", null); this.inline("td", mvp1, null); this.end(); this.begin("tr", null); this.inline("td", "MVP()", null); this.inline("td", mvp2, null); this.end(); } else { this.begin("tr", null); this.inline("td", "MVP", null); this.inline("td", mvp1, null); this.end(); } this.begin("tr", null); this.inline("td", "", null); this.inline("td", detail.isDropFlag() ? detail.getDropName() : "", null); this.end(); this.end(); // table } /** null */ public String generateHTML(String title, BattleResultDto result, BattleExDto battle, boolean genCharset) throws IOException { if (battle.isCompleteResult() == false) { return null; } this.genHeader(title, genCharset); this.begin("body", null); String[] sectionTitleClass = new String[] { "sec-title" }; String time = dateFormat.format(result.getBattleDate()); String header; if (battle.isPractice()) { header = "" + battle.getEnemyName() + " (" + time + ")"; } else { header = result.getMapCell().detailedString() + " (" + time + ")"; } this.inline("div", "<h1>" + header + "</h1>", new String[] { "title" }); this.inline("div", "<h2></h2>", sectionTitleClass); this.genResultTable(result, battle); this.inline("div", "<h2></h2>", sectionTitleClass); int[][][] hpList = this.calcHP(battle); String[] phaseName = (battle.getPhase1().isNight() ? new String[] { "", "" } : new String[] { "", "" }); this.genParmeters(battle.getDock().getName(), battle.getDock().getShips(), hpList[0], phaseName); if (battle.isCombined()) { this.genParmeters(battle.getDockCombined().getName(), battle.getDockCombined().getShips(), hpList[1], phaseName); } this.genParmeters(battle.getEnemyName(), battle.getEnemy(), hpList[2], phaseName); this.genSlotitemTable(battle.getDock().getShips()); if (battle.isCombined()) { this.genSlotitemTable(battle.getDockCombined().getShips()); } this.genSlotitemTable(battle.getEnemy()); this.inline("div", "<h2></h2>", sectionTitleClass); this.genFormation(battle); ShipBaseDto[] friendShips = new ShipBaseDto[12]; ShipBaseDto[] enemyShips = new ShipBaseDto[6]; int[] friendHp = new int[12]; int[] enemyHp = new int[6]; copyToOffset(battle.getDock().getShips(), friendShips, 0); copyToOffset(battle.getEnemy(), enemyShips, 0); copyToOffset(battle.getStartFriendHp(), friendHp, 0); copyToOffset(battle.getStartEnemyHp(), enemyHp, 0); if (battle.isCombined()) { copyToOffset(battle.getDockCombined().getShips(), friendShips, 6); copyToOffset(battle.getStartFriendHpCombined(), friendHp, 6); } int numPhases = battle.getPhaseList().size(); for (int i = 0; i < numPhases; ++i) { Phase phase = battle.getPhaseList().get(i); String phaseTitle = (i + 1) + "/" + numPhases + ": " + (phase.isNight() ? "" : ""); this.inline("div", "<h2>" + phaseTitle + "</h2>", sectionTitleClass); this.genPhase(battle, i, friendShips, enemyShips, friendHp, enemyHp); } this.end(); // body return this.result(); } }
package reka.api; import static java.lang.String.format; import static reka.util.Util.unchecked; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.hash.Hasher; import com.google.common.io.BaseEncoding; public class Path implements Iterable<Path.PathElement>, Comparable<Path>, Hashable { private static final BaseEncoding HEX = BaseEncoding.base16(); private static final Pattern INDEX_MATCHER = Pattern.compile("^([^\\[\\]]*)\\[([0-9]+|\\+)?\\]$"); private static final Pattern DOT_SCANNER = Pattern.compile("(?:[^\\\\])\\.+"); private static final Splitter slashSplitter = Splitter.on("/").omitEmptyStrings(); private static final Joiner slashJoiner = Joiner.on("/").skipNulls(); private final List<PathElement> elements; private final int size; public static Path fromURL(String url) { Path.Builder builder = newBuilder(); try { for (PathElement e : slashes(url)) { if (e.isKey()) { builder.add(URLDecoder.decode(e.name(), Charsets.UTF_8.name())); } else { builder.add(e); } } } catch (UnsupportedEncodingException e) { throw unchecked(e); } return builder.build(); } public Path reverse() { return new Path(Lists.reverse(elements)); } public boolean containsNextIndex() { return elements.stream().anyMatch(PathElement::isNextIndex); } public Path parent() { return size > 0 ? subpath(0, size - 1) : null; } public Path[] parents() { if (size < 2) return new Path[0]; Path[] parents = new Path[size]; Path parent = parent(); int i = 0; while (parent != null) { parents[i++] = parent; parent = parent.parent(); } return parents; } public String toURL() { StringBuilder s = new StringBuilder(); try { for (PathElement e : this) { if (e.isKey()) { s.append(URLEncoder.encode(e.name(), Charsets.UTF_8.name()).replaceAll("\\+", "%20")); } else { s.append(e.toString()); } if (!e.equals(last())) s.append("/"); } } catch (UnsupportedEncodingException e) { throw unchecked(e); } return s.toString(); } public static Builder newBuilder() { return new Builder(); } public static class PathElements { public static PathElement name(String name) { return new NamedPathElement(name); } public static PathElement index(int index) { return new IndexedPathElement(index); } public static PathElement nextIndex() { return new NextIndexPathElement(); } public static PathElement empty() { return EmptyPathElement.INSTANCE; } } public static abstract class PathElement implements Comparable<PathElement>, Hashable { public boolean isKey() { return false; } public boolean isIndex() { return false; } public boolean isNextIndex() { return false; } public boolean isEmpty() { return false; } public int index() { return -1; } public String name() { return null; } } private static class EmptyPathElement extends PathElement { static final EmptyPathElement INSTANCE = new EmptyPathElement(); private EmptyPathElement() { } @Override public boolean isEmpty() { return true; } @Override public int compareTo(PathElement o) { return 0; } @Override public Hasher hash(Hasher hasher) { return hasher; // is nothing ok? } @Override public String toString() { return ""; } } private static class IndexedPathElement extends PathElement { private final int index; IndexedPathElement(int index) { this.index = index; } @Override public boolean isIndex() { return true; } @Override public int index() { return index; } @Override public int compareTo(PathElement o) { if (o instanceof IndexedPathElement) { return Integer.compare(index, ((IndexedPathElement)o).index()); } else if (o.isKey()) { return 1; } else { return -1; } } @Override public String toString() { return format("[%d]", index); } @Override public int hashCode() { return Objects.hash(index); } @Override public boolean equals(Object object) { if (!(object instanceof IndexedPathElement)) return false; return index == ((IndexedPathElement)object).index; } @Override public Hasher hash(Hasher hasher) { return hasher.putInt(index); } } private static class NextIndexPathElement extends PathElement { @Override public boolean isNextIndex() { return true; } @Override public int compareTo(PathElement o) { if (o instanceof NextIndexPathElement) { return 0; } else if (o.isKey()) { return 1; } else { return -1; } } @Override public String toString() { return "[]"; } @Override public int hashCode() { return Objects.hash(93874938749837498L); } @Override public boolean equals(Object object) { return object instanceof NextIndexPathElement; } @Override public Hasher hash(Hasher hasher) { return hasher.putInt(-5765765); } } private static class NamedPathElement extends PathElement { private final String name; private NamedPathElement(String name) { assert name != null; this.name = name; } @Override public boolean isKey() { return true; } @Override public String name() { return name; } @Override public String toString() { return name; } @Override public int compareTo(PathElement o) { if (o instanceof NamedPathElement) { return name.compareTo(((NamedPathElement)o).name); } else if (o.isIndex()) { return -1; } else { return 1; } } @Override public boolean equals(Object object) { if (!(object instanceof NamedPathElement)) return false; NamedPathElement other = (NamedPathElement) object; return name.equals(other.name); } @Override public int hashCode() { return Objects.hash(name); } @Override public Hasher hash(Hasher hasher) { return hasher.putString(name); } } public static class Builder { private final List<PathElement> elements = new ArrayList<>(); public Builder add(String element) { elements.add(PathElements.name(element)); return this; } public Builder add(int index) { elements.add(PathElements.index(index)); return this; } public Builder add(PathElement element) { if (!element.isEmpty()) { elements.add(element); } return this; } public Builder add(Iterator<PathElement> iterator) { iteratorToList(elements, iterator); return this; } public Builder remove(int i) { elements.remove(i); return this; } public Path build() { return new Path(elements); } } @Override public int hashCode() { return Arrays.hashCode(toArray()); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Path)) return false; Path other = (Path) obj; if (other.size != size) return false; for (int i = 0; i < size; i++) { if (!elements.get(i).equals(other.elements.get(i))) { return false; } } return true; } private static final Path EMPTY_PATH = new Path(); public static final Path REQUEST = Path.path("request"); public static final Path RESPONSE = Path.path("response"); public static final class Request { public static final Path METHOD = REQUEST.add("method"); public static final Path PATH = REQUEST.add("path"); public static final Path PARAMS = REQUEST.add("params"); public static final Path DATA = REQUEST.add("data"); public static final Path UPLOADS = REQUEST.add("uploads"); public static final Path CONTENT = REQUEST.add("content"); public static final Path HEADERS = REQUEST.add("headers"); public static final Path COOKIES = REQUEST.add("cookies"); public static final Path HOST = REQUEST.add("host"); public static final class Headers { public static final Path CONTENT_TYPE = HEADERS.add("Content-Type"); public static final Path CONTENT_LENGTH = HEADERS.add("Content-Length"); public static final Path IF_NONE_MATCH = HEADERS.add("If-None-Match"); public static final Path AUTHORIZATION = HEADERS.add("Authorization"); public static final Path ACCEPT = HEADERS.add("Accept"); } } public static final class Response { public static final Path STATUS = RESPONSE.add("status"); public static final Path CONTENT = RESPONSE.add("content"); public static final Path HEADERS = RESPONSE.add("headers"); public static final Path COOKIES = RESPONSE.add("cookies"); public static final Path HEAD = RESPONSE.add("head"); // are we sending a head response public static final class Headers { public static final Path DATE = HEADERS.add("Date"); public static final Path LOCATION = HEADERS.add("Location"); public static final Path CONTENT_TYPE = HEADERS.add("Content-Type"); public static final Path CONTENT_DISPOSITION = HEADERS.add("Content-Disposition"); public static final Path CONTENT_LENGTH = HEADERS.add("Content-Length"); public static final Path ETAG = HEADERS.add("ETag"); public static final Path LINK = HEADERS.add("Link"); public static final Path EXPIRES = HEADERS.add("Expires"); public static final Path CACHE_CONTROL = HEADERS.add("Cache-Control"); public static final Path WWW_AUTHENTICATE = HEADERS.add("WWW-Authenticate"); } } public static Path slashes(String value) { return fromStringWithSplitter(value, slashSplitter); } public static Path dots(String value) { List<PathElement> elements = new ArrayList<>(); Matcher m = DOT_SCANNER.matcher(value); int pos = 0; while (m.find()) { String segment = value.substring(pos, m.start() + 1); addElementTo(segment.replaceAll("\\\\", ""), elements); pos = m.end(); } if (pos < value.length()) { addElementTo(value.substring(pos, value.length()).replaceAll("\\\\", ""), elements); } return new Path(elements); } private static void addElementTo(String element, Collection<PathElement> elements) { Matcher matcher = INDEX_MATCHER.matcher(element); if (matcher.matches()) { String firstbit = matcher.group(1); if (firstbit != null && !"".equals(firstbit)) { elements.add(PathElements.name(firstbit)); } String indexStr = matcher.group(2); if ("+".equals(indexStr) || indexStr == null) { elements.add(PathElements.nextIndex()); } else { elements.add(PathElements.index(Integer.parseInt(indexStr))); } } else { elements.add(PathElements.name(element)); } } private static Path fromStringWithSplitter(String value, Splitter splitter) { if (value == null || value.isEmpty()) { return EMPTY_PATH; } else { String[] items = Iterables.toArray(splitter.split(value), String.class); if (items.length == 0) { return EMPTY_PATH; } else { return new Path(parse(items)); } } } private static List<PathElement> parse(String[] items) { List<PathElement> elements = new ArrayList<>(); for (int i = 0; i < items.length; i++) { String item = items[i]; if (item != null) { addElementTo(item, elements); } } return elements; } public static Path empty() { return EMPTY_PATH; } public static Path root() { return EMPTY_PATH; } public static Path path(String... elements) { return new Path(parse(elements)); } public static Path path(Iterator<PathElement> iterator) { if (!iterator.hasNext()) { return EMPTY_PATH; } return new Path(iteratorToList(new ArrayList<PathElement>(), iterator)); } public static Path fromHex(String hex) { return fromByteArray(HEX.decode(hex)); } public static Path fromByteArray(byte[] bytes) { try { DataInput di = new DataInputStream(new ByteArrayInputStream(bytes)); int size = di.readInt(); if (size == 0) { return EMPTY_PATH; } List<PathElement> elements = new ArrayList<>(size); for (int i = 0; i < size; i++) { if (di.readBoolean()) { elements.add(PathElements.name(di.readUTF())); } else { elements.add(PathElements.index(di.readInt())); } } return new Path(elements); } catch (Exception e) { throw unchecked(e); } } public static Path path(PathElement... elements) { return elements.length == 0 ? EMPTY_PATH : new Path(elements); } private Path(List<PathElement> elements) { int emptyCount = 0; for (PathElement e : elements) { if (e.isEmpty()) emptyCount++; } if (emptyCount > 0) { this.elements = new ArrayList<>(elements.size() - emptyCount); for (PathElement e : elements) { if (!e.isEmpty()) { this.elements.add(e); } } } else { this.elements = elements; } this.size = this.elements.size(); } private Path() { this(new ArrayList<PathElement>()); } private Path(PathElement... elements) { this(Arrays.asList(elements)); } public String wrapAndJoin(String wrap, String seperator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < elements.size(); i++) { sb.append(wrap.replaceAll("\\{\\}", elements.get(i).toString())); if (i < elements.size() - 1) { sb.append(seperator); } } return sb.toString(); } public String join(String seperator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < elements.size(); i++) { sb.append(elements.get(i)); if (i < elements.size() - 1) { sb.append(seperator); } } return sb.toString(); } public Path add(Path other) { if (other.isEmpty()) return this; List<PathElement> newElements = new ArrayList<>(elements); newElements.addAll(other.elements); return new Path(newElements); } public Path add(PathElement element) { if (element.isEmpty()) return this; List<PathElement> newElements = new ArrayList<>(elements); newElements.add(element); return new Path(newElements); } public Path add(PathElement... es) { List<PathElement> newElements = new ArrayList<>(elements); for (PathElement e : es) { newElements.add(e); } return new Path(newElements); } public Path add(String element) { return add(PathElements.name(element)); } public Path add(int element) { return add(PathElements.index(element)); } public PathElement last() { return isEmpty() ? null : elements.get(elements.size() - 1); } public Path butlast() { return size > 1 ? new Path(elements.subList(0, elements.size() - 1)) : empty(); } @Override public Iterator<PathElement> iterator() { return Collections.unmodifiableList(elements).iterator(); } public int length() { return size; } public PathElement get(int i) { return elements.get(i); } public byte[] toByteArray() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeInt(size); for (PathElement element : elements) { dos.writeBoolean(element.name() != null); if (element.name() != null) { dos.writeUTF(element.name()); } else { dos.writeInt(element.index()); } } dos.close(); baos.close(); return baos.toByteArray(); } catch (Exception e) { throw unchecked(e); } } public String hex() { return HEX.encode(toByteArray()); } public PathElement[] toArray() { return elements.toArray(new PathElement[elements.size()]); } public Path subpath(int fromIndex) { return subpath(fromIndex, size); } public Path subpath(int fromIndex, int toIndex) { return new Path(elements.subList(fromIndex, toIndex)); } public PathElement first() { return elements.isEmpty() ? null : elements.get(0); } public boolean startsWith(Path other) { if (length() < other.length()) { return false; } for (int i = 0; i < other.length(); i++) { if (!other.get(i).equals(elements.get(i))) { return false; } } return true; } public boolean endsWith(Path other) { int otherLength = other.length(); int thisLength = length(); if (thisLength < otherLength) { return false; } int min = Math.min(thisLength, otherLength); for (int i = 1; i <= min; i++) { if (!other.get(otherLength - i).equals(elements.get(thisLength - i))) { return false; } } return true; } @Override public String toString() { return elements.toString(); } public boolean isEmpty() { return size == 0; } public String dots() { StringBuilder b = new StringBuilder(); for (int i = 0; i < size; i++) { PathElement e = elements.get(i); if (e.isKey()) { b.append(e.name().replaceAll("\\.", "\\\\.")); } else if (e.isNextIndex()) { b.append("[+]"); } else { b.append(e); } if (i < size - 1 && elements.get(i + 1).isKey()) { b.append("."); } } return b.toString(); } public String slashes() { return slashJoiner.join(elements); } public String url() { try { StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; i++) { PathElement element = elements.get(i); if (element.isKey()) { sb.append(URLEncoder.encode(element.name(), Charsets.UTF_8.name())); } else { sb.append(element.toString()); } if (i < size - 1) { sb.append("/"); } } return sb.toString(); } catch (UnsupportedEncodingException e) { throw unchecked(e); } } private static <T> List<T> iteratorToList(List<T> list, Iterator<T> iterator) { while (iterator.hasNext()) { list.add(iterator.next()); } return list; } @Override public int compareTo(Path o) { if (o.equals(this)) { return 0; } else { int count = Math.min(size, o.size); for (int i = 0; i < count; i++) { int val = get(i).compareTo(o.get(i)); if (val != 0) { return val; } } return size - o.size; } } @Override public Hasher hash(Hasher hasher) { hasher.putInt(size); for (PathElement e : elements) { e.hash(hasher); } return hasher; } }
package com.thoughtworks.xstream.core; import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.security.AccessControlException; import java.text.AttributedString; import java.util.HashMap; import java.util.Map; public class JVM { private ReflectionProvider reflectionProvider; private transient Map loaderCache = new HashMap(); private final boolean supportsAWT = loadClass("java.awt.Color") != null; private final boolean supportsSwing = loadClass("javax.swing.LookAndFeel") != null; private final boolean supportsSQL = loadClass("java.sql.Date") != null; private static final boolean reverseFieldOrder; private static final String vendor = System.getProperty("java.vm.vendor"); private static final float majorJavaVersion = getMajorJavaVersion(); static final float DEFAULT_JAVA_VERSION = 1.3f; static { boolean reverse = false; final Field[] fields = AttributedString.class.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].getName().equals("text")) { reverse = i > 3; } } reverseFieldOrder = reverse; } /** * Parses the java version system property to determine the major java version, * ie 1.x * * @return A float of the form 1.x */ private static final float getMajorJavaVersion() { try { return Float.parseFloat(System.getProperty("java.specification.version")); } catch ( NumberFormatException e ){ // Some JVMs may not conform to the x.y.z java.version format return DEFAULT_JAVA_VERSION; } } public static boolean is14() { return majorJavaVersion >= 1.4f; } public static boolean is15() { return majorJavaVersion >= 1.5f; } public static boolean is16() { return majorJavaVersion >= 1.6f; } private static boolean isSun() { return vendor.indexOf("Sun") != -1; } private static boolean isApple() { return vendor.indexOf("Apple") != -1; } private static boolean isHPUX() { return vendor.indexOf("Hewlett-Packard Company") != -1; } private static boolean isIBM() { return vendor.indexOf("IBM") != -1; } private static boolean isBlackdown() { return vendor.indexOf("Blackdown") != -1; } /* * Support for sun.misc.Unsafe and sun.reflect.ReflectionFactory is present * in JRockit versions R25.1.0 and later, both 1.4.2 and 5.0 (and in future * 6.0 builds). */ private static boolean isBEAWithUnsafeSupport() { // This property should be "BEA Systems, Inc." if (vendor.indexOf("BEA") != -1) { /* * Recent 1.4.2 and 5.0 versions of JRockit have a java.vm.version * string starting with the "R" JVM version number, i.e. * "R26.2.0-38-57237-1.5.0_06-20060209..." */ String vmVersion = System.getProperty("java.vm.version"); if (vmVersion.startsWith("R")) { /* * We *could* also check that it's R26 or later, but that is * implicitly true */ return true; } /* * For older JRockit versions we can check java.vm.info. JRockit * 1.4.2 R24 -> "Native Threads, GC strategy: parallel" and JRockit * 5.0 R25 -> "R25.2.0-28". */ String vmInfo = System.getProperty("java.vm.info"); if (vmInfo != null) { // R25.1 or R25.2 supports Unsafe, other versions do not return (vmInfo.startsWith("R25.1") || vmInfo .startsWith("R25.2")); } } // If non-BEA, or possibly some very old JRockit version return false; } private static boolean isHitachi() { return vendor.indexOf("Hitachi") != -1; } private static boolean isSAP() { return vendor.indexOf("SAP AG") != -1; } public Class loadClass(String name) { try { WeakReference reference = (WeakReference) loaderCache.get(name); if (reference != null) { Class cached = (Class) reference.get(); if (cached != null) { return cached; } } Class clazz = Class.forName(name, false, getClass().getClassLoader()); loaderCache.put(name, new WeakReference(clazz)); return clazz; } catch (ClassNotFoundException e) { return null; } } public synchronized ReflectionProvider bestReflectionProvider() { if (reflectionProvider == null) { try { if ( canUseSun14ReflectionProvider() ) { String cls = "com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider"; reflectionProvider = (ReflectionProvider) loadClass(cls).newInstance(); } else { reflectionProvider = new PureJavaReflectionProvider(); } } catch (InstantiationException e) { reflectionProvider = new PureJavaReflectionProvider(); } catch (IllegalAccessException e) { reflectionProvider = new PureJavaReflectionProvider(); } catch (AccessControlException e) { // thrown when trying to access sun.misc package in Applet context. reflectionProvider = new PureJavaReflectionProvider(); } } return reflectionProvider; } private boolean canUseSun14ReflectionProvider() { return (isSun() || isApple() || isHPUX() || isIBM() || isBlackdown() || isBEAWithUnsafeSupport() || isHitachi() || isSAP()) && is14() && loadClass("sun.misc.Unsafe") != null; } public static boolean reverseFieldDefinition() { return reverseFieldOrder; } /** * Checks if the jvm supports awt. */ public boolean supportsAWT() { return this.supportsAWT; } /** * Checks if the jvm supports swing. */ public boolean supportsSwing() { return this.supportsSwing; } /** * Checks if the jvm supports sql. */ public boolean supportsSQL() { return this.supportsSQL; } private Object readResolve() { loaderCache = new HashMap(); return this; } public static void main(String[] args) { JVM jvm = new JVM(); System.out.println("XStream JVM diagnostics"); System.out.println("java.specification.version: " + System.getProperty("java.specification.version")); System.out.println("java.vm.vendor: " + vendor); System.out.println("Version: " + majorJavaVersion); System.out.println("Reverse field order: " + reverseFieldOrder); System.out.println("XStream support for enhanced Mode: " + jvm.canUseSun14ReflectionProvider()); System.out.println("Supports AWT: " + jvm.supportsAWT()); System.out.println("Supports SQL: " + jvm.supportsSQL()); } }
package mockit.internal; import static java.lang.reflect.Modifier.*; import mockit.external.asm4.*; import mockit.internal.state.*; import mockit.internal.util.*; import static mockit.external.asm4.ClassWriter.*; import static mockit.external.asm4.Opcodes.*; import org.jetbrains.annotations.*; @SuppressWarnings("ClassWithTooManyFields") public class BaseClassModifier extends ClassVisitor { private static final int METHOD_ACCESS_MASK = 0xFFFF - ACC_ABSTRACT - ACC_NATIVE; protected static final Type VOID_TYPE = Type.getType("Ljava/lang/Void;"); @NotNull protected final MethodVisitor methodAnnotationsVisitor = new MethodVisitor() { @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return mw.visitAnnotation(desc, visible); } @Override public void visitLocalVariable( @NotNull String name, @NotNull String desc, String signature, @NotNull Label start, @NotNull Label end, int index) { registerParameterName(name, index); } @Override public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) { return mw.visitParameterAnnotation(parameter, desc, visible); } }; protected final void registerParameterName(@NotNull String name, int index) { ParameterNames.registerName(classDesc, methodAccess, methodName, methodDesc, name, index); } @NotNull protected final ClassWriter cw; protected MethodWriter mw; protected boolean useMockingBridge; protected String superClassName; protected String classDesc; protected int methodAccess; protected String methodName; protected String methodDesc; private boolean callToAnotherConstructorAlreadyDisregarded; protected BaseClassModifier(@NotNull ClassReader classReader) { super(new ClassWriter(classReader, COMPUTE_FRAMES)); //noinspection ConstantConditions cw = (ClassWriter) cv; } protected final void setUseMockingBridge(@Nullable ClassLoader classLoader) { useMockingBridge = classLoader == null; } @Override public void visit( int version, int access, @NotNull String name, @Nullable String signature, @Nullable String superName, @Nullable String[] interfaces) { int modifiedVersion = version; int originalVersion = version & 0xFFFF; if (originalVersion < V1_5) { // LDC instructions (see MethodVisitor#visitLdcInsn) are more capable in JVMs with support for class files of // version 49 (Java 1.5) or newer, so we "upgrade" it to avoid a VerifyError: modifiedVersion = V1_5; } cw.visit(modifiedVersion, access, name, signature, superName, interfaces); superClassName = superName; classDesc = name; } /** * Just creates a new MethodWriter which will write out the method bytecode when visited. * <p/> * Removes any "abstract" or "native" modifiers for the modified version. */ protected final void startModifiedMethodVersion( int access, @NotNull String name, @NotNull String desc, @Nullable String signature, @Nullable String[] exceptions) { mw = cw.visitMethod(access & METHOD_ACCESS_MASK, name, desc, signature, exceptions); methodAccess = access; methodName = name; methodDesc = desc; callToAnotherConstructorAlreadyDisregarded = false; if (isNative(access)) { TestRun.mockFixture().addRedefinedClassWithNativeMethods(classDesc); } } protected final void generateCallToSuperConstructor() { mw.visitVarInsn(ALOAD, 0); String constructorDesc; if ("java/lang/Object".equals(superClassName)) { constructorDesc = "()V"; } else { constructorDesc = SuperConstructorCollector.INSTANCE.findConstructor(classDesc, superClassName); for (Type paramType : Type.getArgumentTypes(constructorDesc)) { pushDefaultValueForType(paramType); } } mw.visitMethodInsn(INVOKESPECIAL, superClassName, "<init>", constructorDesc); } protected final void generateReturnWithObjectAtTopOfTheStack(@NotNull String mockedMethodDesc) { Type returnType = Type.getReturnType(mockedMethodDesc); TypeConversion.generateCastFromObject(mw, returnType); mw.visitInsn(returnType.getOpcode(IRETURN)); } public static boolean generateCodeToPassThisOrNullIfStaticMethod(@NotNull MethodWriter mw, int access) { boolean isStatic = isStatic(access); if (isStatic) { mw.visitInsn(ACONST_NULL); } else { mw.visitVarInsn(ALOAD, 0); } return isStatic; } public static void generateCodeToCreateArrayOfObject(@NotNull MethodWriter mw, int arrayLength) { mw.visitIntInsn(BIPUSH, arrayLength); mw.visitTypeInsn(ANEWARRAY, "java/lang/Object"); } public static void generateCodeToFillArrayWithParameterValues( @NotNull MethodWriter mw, @NotNull Type[] parameterTypes, int initialArrayIndex, int initialParameterIndex) { int i = initialArrayIndex; int j = initialParameterIndex; for (Type parameterType : parameterTypes) { mw.visitInsn(DUP); mw.visitIntInsn(BIPUSH, i++); mw.visitVarInsn(parameterType.getOpcode(ILOAD), j); TypeConversion.generateCastToObject(mw, parameterType); mw.visitInsn(AASTORE); j += parameterType.getSize(); } } protected final void generateCodeToObtainInstanceOfMockingBridge(@NotNull MockingBridge mockingBridge) { mw.visitFieldInsn(GETSTATIC, "org/omg/IOP/IORHelper", mockingBridge.id, "Ljava/lang/reflect/InvocationHandler;"); } protected final void generateCodeToFillArrayElement(int arrayIndex, @Nullable Object value) { mw.visitInsn(DUP); mw.visitIntInsn(BIPUSH, arrayIndex); if (value == null) { mw.visitInsn(ACONST_NULL); } else if (value instanceof Integer) { mw.visitIntInsn(SIPUSH, (Integer) value); mw.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); } else if (value instanceof Boolean) { mw.visitInsn((Boolean) value ? ICONST_1 : ICONST_0); mw.visitMethodInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;"); } else { mw.visitLdcInsn(value); } mw.visitInsn(AASTORE); } private void pushDefaultValueForType(@NotNull Type type) { switch (type.getSort()) { case Type.VOID: break; case Type.BOOLEAN: case Type.CHAR: case Type.BYTE: case Type.SHORT: case Type.INT: mw.visitInsn(ICONST_0); break; case Type.LONG: mw.visitInsn(LCONST_0); break; case Type.FLOAT: mw.visitInsn(FCONST_0); break; case Type.DOUBLE: mw.visitInsn(DCONST_0); break; case Type.ARRAY: generateCreationOfEmptyArray(type); break; default: mw.visitInsn(ACONST_NULL); } } private void generateCreationOfEmptyArray(@NotNull Type arrayType) { int dimensions = arrayType.getDimensions(); for (int dimension = 0; dimension < dimensions; dimension++) { mw.visitInsn(ICONST_0); } if (dimensions > 1) { mw.visitMultiANewArrayInsn(arrayType.getDescriptor(), dimensions); return; } Type elementType = arrayType.getElementType(); int elementSort = elementType.getSort(); if (elementSort == Type.OBJECT) { mw.visitTypeInsn(ANEWARRAY, elementType.getInternalName()); } else { int typ = getArrayElementTypeCode(elementSort); mw.visitIntInsn(NEWARRAY, typ); } } private static int getArrayElementTypeCode(int elementSort) { switch (elementSort) { case Type.BOOLEAN: return T_BOOLEAN; case Type.CHAR: return T_CHAR; case Type.BYTE: return T_BYTE; case Type.SHORT: return T_SHORT; case Type.INT: return T_INT; case Type.FLOAT: return T_FLOAT; case Type.LONG: return T_LONG; default: return T_DOUBLE; } } protected final void generateCallToInvocationHandler() { mw.visitMethodInsn( INVOKEINTERFACE, "java/lang/reflect/InvocationHandler", "invoke", "(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;"); } protected final void generateEmptyImplementation(@NotNull String desc) { Type returnType = Type.getReturnType(desc); pushDefaultValueForType(returnType); mw.visitInsn(returnType.getOpcode(IRETURN)); mw.visitMaxs(1, 0); } protected final void generateEmptyImplementation() { mw.visitInsn(RETURN); mw.visitMaxs(1, 0); } protected final void disregardIfInvokingAnotherConstructor( int opcode, @NotNull String owner, @NotNull String name, @NotNull String desc) { if ( callToAnotherConstructorAlreadyDisregarded || opcode != INVOKESPECIAL || !"<init>".equals(name) || !owner.equals(superClassName) && !owner.equals(classDesc) ) { mw.visitMethodInsn(opcode, owner, name, desc); } else { mw.visitInsn(POP); callToAnotherConstructorAlreadyDisregarded = true; } } public final boolean wasModified() { return methodName != null; } }
package com.box.l10n.mojito; import com.box.l10n.mojito.entity.BaseEntity; import com.box.l10n.mojito.json.ObjectMapper; import com.fasterxml.jackson.databind.DeserializationFeature; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration; import org.springframework.boot.context.ApplicationPidFileWriter; import org.springframework.context.annotation.AdviceMode; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.aspectj.EnableSpringConfigured; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.retry.annotation.EnableRetry; import org.springframework.retry.backoff.ExponentialRandomBackOffPolicy; import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetryTemplate; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.io.IOException; @SpringBootApplication( scanBasePackageClasses = Application.class, exclude = { QuartzAutoConfiguration.class, // We integrated with Quartz before spring supported it } ) @EnableSpringConfigured @EnableJpaAuditing @EnableJpaRepositories @EnableScheduling @EnableTransactionManagement(mode = AdviceMode.ASPECTJ) @EnableRetry @EntityScan(basePackageClasses = BaseEntity.class) public class Application { // TODO(spring2), find replacement - this was commented in previous attempt // @Value("${org.springframework.http.converter.json.indent_output}") boolean shouldIndentJacksonOutput; public static void main(String[] args) throws IOException { SpringApplication springApplication = new SpringApplication(Application.class); springApplication.addListeners(new ApplicationPidFileWriter("application.pid")); springApplication.run(args); } /** * Fix Spring scanning issue. * <p> * without this the ObjectMapper instance is not created/available in the * container. * * @return */ @Bean @Primary public ObjectMapper getObjectMapper() { return new ObjectMapper(); } @Bean(name = "fail_on_unknown_properties_false") public ObjectMapper getObjectMapperFailOnUnknownPropertiesFalse() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return objectMapper; } /** * Configuration Jackson ObjectMapper * * @return */ @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter mjhmc = new MappingJackson2HttpMessageConverter(); Jackson2ObjectMapperFactoryBean jomfb = new Jackson2ObjectMapperFactoryBean(); jomfb.setAutoDetectFields(false); jomfb.setIndentOutput(shouldIndentJacksonOutput); jomfb.afterPropertiesSet(); mjhmc.setObjectMapper(jomfb.getObject()); return mjhmc; } @Bean public ThreadPoolTaskScheduler threadPoolTaskScheduler() { ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); threadPoolTaskScheduler.setPoolSize(5); threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler"); return threadPoolTaskScheduler; } @Bean public RetryTemplate retryTemplate() { SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); retryPolicy.setMaxAttempts(6); ExponentialRandomBackOffPolicy exponentialRandomBackOffPolicy = new ExponentialRandomBackOffPolicy(); exponentialRandomBackOffPolicy.setInitialInterval(10); exponentialRandomBackOffPolicy.setMultiplier(3); exponentialRandomBackOffPolicy.setMaxInterval(5000); RetryTemplate template = new RetryTemplate(); template.setRetryPolicy(retryPolicy); template.setBackOffPolicy(exponentialRandomBackOffPolicy); template.setThrowLastExceptionOnExhausted(true); return template; } }
package test.ccn.data; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.Security; import java.security.SignatureException; import java.security.cert.X509Certificate; import java.sql.Timestamp; import java.util.Arrays; import java.util.Date; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import test.ccn.data.util.XMLEncodableTester; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.ContentObject; import com.parc.ccn.data.security.KeyLocator; import com.parc.ccn.data.security.PublisherPublicKeyDigest; import com.parc.ccn.data.security.Signature; import com.parc.ccn.data.security.SignedInfo; import com.parc.security.crypto.certificates.BCX509CertificateGenerator; public class ContentObjectTest { static final String baseName = "test"; static final String subName2 = "smetters"; static final String document2 = "test2.txt"; static public byte [] document3 = new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x1f, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x2e, 0x3c, 0x4a, 0x5c, 0x6d, 0x7e, 0xf}; static ContentName name; static final String rootDN = "C=US,O=Organization,OU=Organizational Unit,CN=Issuer"; static final String endDN = "C=US,O=Final Org,L=Locality,CN=Fred Jones,E=fred@final.org"; static final Date start = new Date(); static final Date end = new Date(start.getTime() + (60*60*24*365)); static final String keydoc = "key"; static ContentName keyname; static KeyPair pair = null; static X509Certificate cert = null; static KeyLocator nameLoc = null; static KeyLocator keyLoc = null; static public Signature signature; static public byte [] contenthash = new byte[32]; static public byte [] publisherid = new byte[32]; static PublisherPublicKeyDigest pubkey = null; static SignedInfo auth = null; static SignedInfo authKey = null; @BeforeClass public static void setUpBeforeClass() throws Exception { try { name = ContentName.fromURI(new String[]{baseName, subName2, document2}); keyname = ContentName.fromURI(new String[]{baseName, subName2, keydoc}); Security.addProvider(new BouncyCastleProvider()); // generate key pair KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(512); // go for fast pair = kpg.generateKeyPair(); cert = BCX509CertificateGenerator.GenerateX509Certificate( pair.getPublic(), rootDN, endDN, null, start, end, null, pair.getPrivate(), null); nameLoc = new KeyLocator(keyname); keyLoc = new KeyLocator(pair.getPublic()); byte [] signaturebuf = new byte[64]; Arrays.fill(signaturebuf, (byte)1); signature = new Signature(signaturebuf); Arrays.fill(contenthash, (byte)2); Arrays.fill(publisherid, (byte)3); pubkey = new PublisherPublicKeyDigest(publisherid); auth = new SignedInfo(pubkey, new Timestamp(System.currentTimeMillis()), SignedInfo.ContentType.DATA, nameLoc); authKey = new SignedInfo(pubkey, new Timestamp(System.currentTimeMillis()), SignedInfo.ContentType.KEY, keyLoc); } catch (Exception ex) { XMLEncodableTester.handleException(ex); System.out.println("Unable To Initialize Test!!!"); } } @Test public void testDecodeInputStream() { try { ContentObject co = new ContentObject(name, auth, document3, pair.getPrivate()); ContentObject tdco = new ContentObject(); ContentObject bdco = new ContentObject(); XMLEncodableTester.encodeDecodeTest("ContentObject", co, tdco, bdco); Assert.assertTrue(co.verify(pair.getPublic())); ContentObject cokey = new ContentObject(name, authKey, document3, pair.getPrivate()); ContentObject tdcokey = new ContentObject(); ContentObject bdcokey = new ContentObject(); XMLEncodableTester.encodeDecodeTest("ContentObjectKey", cokey, tdcokey, bdcokey); Assert.assertTrue(cokey.verify(pair.getPublic())); // Dump one to file for testing on the C side. java.io.FileOutputStream fdump = new java.io.FileOutputStream("ContentObject.ccnb"); co.encode(fdump); fdump.flush(); fdump.close(); } catch (Exception e) { System.out.println("Exception : " + e.getClass().getName() + ": " + e.getMessage()); e.printStackTrace(); Assert.fail("Exception: " + e.getClass().getName() + ": " + e.getMessage()); } } @Test public void testImmutable() { try { ContentObject co = new ContentObject(name, auth, document2.getBytes(), pair.getPrivate()); byte [] bs = co.content(); bs[0] = 1; Signature sig = co.signature(); sig.signature()[0] = 2; } catch (InvalidKeyException e) { Assert.fail("Invalid key exception: " + e.getMessage()); } catch (SignatureException e) { Assert.fail("Signature exception: " + e.getMessage()); } } }
package mocha.ui.collectionview; import mocha.graphics.Rect; import mocha.ui.Highlightable; import mocha.ui.LongPressGestureRecognizer; import mocha.ui.View; import java.util.List; class CollectionViewCell extends CollectionReusableView implements Highlightable { private View contentView; private View backgroundView; private View selectedBackgroundView; private LongPressGestureRecognizer menuGesture; private CollectionCellFlagsStruct collectionCellFlags = new CollectionCellFlagsStruct(); private class CollectionCellFlagsStruct { boolean selected; boolean highlighted; boolean showingMenu; boolean clearSelectionWhenMenuDisappears; boolean waitingForSelectionAnimationHalfwayPoint; } public CollectionViewCell(mocha.graphics.Rect frame) { super(frame); Rect bounds = this.getBounds(); this.backgroundView = new View(bounds); this.backgroundView.setAutoresizing(Autoresizing.FLEXIBLE_WIDTH, Autoresizing.FLEXIBLE_HEIGHT); this.addSubview(this.backgroundView); this.contentView = new View(bounds); this.contentView.setAutoresizing(Autoresizing.FLEXIBLE_WIDTH, Autoresizing.FLEXIBLE_HEIGHT); this.addSubview(this.contentView); // this.menuGesture = new mocha.ui.LongPressGestureRecognizer(new GestureRecognizer.GestureHandler() { // public void handleGesture(GestureRecognizer gestureRecognizer) { // menuGesture((LongPressGestureRecognizer)gestureRecognizer); } public void prepareForReuse() { this.setLayoutAttributes(null); this.setSelected(false); this.setHighlighted(false); this.setAccessibilityTraits(Trait.NONE); } public void setHighlighted(boolean highlighted) { this.collectionCellFlags.highlighted = highlighted; this.updateBackgroundView(highlighted); } void updateBackgroundView(boolean highlight) { this.selectedBackgroundView.setAlpha(highlight ? 1.0f : 0.0f); this.setHighlightedForViews(highlight, this.getContentView().getSubviews()); } void setHighlightedForViews(boolean highlighted, List<View> subviews) { for (View view : subviews) { // Ignore the events if view wants to if (!view.isUserInteractionEnabled() && view instanceof Highlightable && !(view instanceof mocha.ui.Control)) { ((Highlightable) view).setHighlighted(highlighted); this.setHighlightedForViews(highlighted, view.getSubviews()); } } } private void menuGesture(LongPressGestureRecognizer recognizer) { } public void setBackgroundView(View backgroundView) { if (this.backgroundView != backgroundView) { if (this.backgroundView != null) { this.backgroundView.removeFromSuperview(); } this.backgroundView = backgroundView; if (this.backgroundView != null) { this.backgroundView.setFrame(this.getBounds()); this.backgroundView.setAutoresizing(Autoresizing.FLEXIBLE_WIDTH, Autoresizing.FLEXIBLE_HEIGHT); this.insertSubview(this.backgroundView, 0); } } } public void setSelectedBackgroundView(View selectedBackgroundView) { if (this.selectedBackgroundView != selectedBackgroundView) { if (this.selectedBackgroundView != null) { this.selectedBackgroundView.removeFromSuperview(); } this.selectedBackgroundView = selectedBackgroundView; if (this.selectedBackgroundView != null) { this.selectedBackgroundView.setFrame(this.getBounds()); this.selectedBackgroundView.setAutoresizing(Autoresizing.FLEXIBLE_WIDTH, Autoresizing.FLEXIBLE_HEIGHT); this.selectedBackgroundView.setAlpha(this.isSelected() ? 1.0f : 0.0f); if (this.backgroundView != null) { this.insertSubviewAboveSubview(this.selectedBackgroundView, this.backgroundView); } else { this.insertSubview(this.selectedBackgroundView, 0); } } } } /* Setters & Getters */ public View getContentView() { return this.contentView; } public void setContentView(View contentView) { this.contentView = contentView; } public boolean isSelected() { return this.collectionCellFlags.selected; } public void setSelected(boolean selected) { this.collectionCellFlags.selected = selected; this.setAccessibilityTraits(selected ? Trait.SELECTED : Trait.NONE); this.updateBackgroundView(selected); } public boolean isHighlighted() { return collectionCellFlags.highlighted; } public View getBackgroundView() { return this.backgroundView; } public View getSelectedBackgroundView() { return this.selectedBackgroundView; } }
package pdp.web; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import org.apache.openaz.xacml.api.Decision; import org.apache.openaz.xacml.std.json.JSONResponse; import org.apache.openaz.xacml.std.json.JSONStructureException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; import pdp.AbstractPdpIntegrationTest; import pdp.PdpApplication; import pdp.domain.JsonPolicyRequest; import pdp.domain.PdpPolicy; import pdp.domain.PdpPolicyDefinition; import pdp.domain.PdpPolicyViolation; import pdp.policies.PolicyLoader; import pdp.teams.VootClientConfig; import pdp.xacml.PolicyTemplateEngine; import java.io.IOException; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static pdp.util.StreamUtils.singletonCollector; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = PdpApplication.class) @WebIntegrationTest(randomPort = true, value = {"spring.profiles.active=no-csrf"}) public class PdpControllerShibbolethIntegrationTest extends AbstractPdpIntegrationTest { private static final ParameterizedTypeReference<List<PdpPolicyDefinition>> pdpPolicyDefinitionsType = new ParameterizedTypeReference<List<PdpPolicyDefinition>>() { }; private RestTemplate restTemplate = new TestRestTemplate(); @Before public void before() throws IOException { super.before(); addShibHeaders(); } @Test public void testPolicyDefinitionsImpersonated() { impersonate(PolicyLoader.authenticatingAuthority, VootClientConfig.URN_COLLAB_PERSON_EXAMPLE_COM_ADMIN, "John Doe"); List<PdpPolicyDefinition> definitions = getForObject("/internal/policies", pdpPolicyDefinitionsType); // only one, the policy with no IdP and a SP with allowedAll assertEquals(definitions.size(), 5); } @Test public void testInternalDecide() throws IOException, JSONStructureException { ResponseEntity<String> response = post("/internal/decide/policy", getJsonPolicyRequest()); assertEquals(Decision.NOTAPPLICABLE, JSONResponse.load(response.getBody()).getResults().stream().collect(singletonCollector()).getDecision()); } @Test public void testPolicyDefinitionsAdmin() { List<PdpPolicyDefinition> definitions = getForObject("/internal/policies", pdpPolicyDefinitionsType); assertThat(definitions, hasSize(greaterThan(9))); } @Test public void testPolicyDefinitionsByServiceProvider() { List<PdpPolicyDefinition> definitions = getForObject("/internal/policies/sp?serviceProvider=http://mock-sp", pdpPolicyDefinitionsType); assertThat(definitions, hasSize(1)); } @Test public void testViolations() { setUpViolation(policyId); setUpViolation(policyId); List<PdpPolicyViolation> violations = getForObject("/internal/violations", new ParameterizedTypeReference<List<PdpPolicyViolation>>() { }); assertViolations(violations, 2); } @Test public void testViolationsByPolicyId() { Long policyId = setUpViolation(PdpControllerShibbolethIntegrationTest.policyId).getId(); List<PdpPolicyViolation> violations = getForObject("/internal/violations/" + policyId, new ParameterizedTypeReference<List<PdpPolicyViolation>>() { }); assertViolations(violations, 1); } @Test public void findPolicyById() { PdpPolicy policy = getExistingPolicy(); PdpPolicyDefinition definition = getForObject("/internal/policies/" + policy.getId(), new ParameterizedTypeReference<PdpPolicyDefinition>() { }); assertNotNull(definition.getId()); } @Test public void testRevisionsByPolicyIdWithExistingPolicy() { //we use the API to set up the revisions PdpPolicy policy = getExistingPolicy(); PdpPolicyDefinition policyDefinition = pdpPolicyDefinitionParser.parse(policy); String initialDenyAdvice = policyDefinition.getDenyAdvice(); policyDefinition.setDenyAdvice("advice_changed"); assertThat(post("/internal/policies", policyDefinition).getStatusCode(), is(HttpStatus.OK)); policyDefinition.setDenyAdvice("advice_changed_again"); assertThat(post("/internal/policies", policyDefinition).getStatusCode(), is(HttpStatus.OK)); List<PdpPolicyDefinition> definitions = getForObject("/internal/revisions/" + policy.getId(), pdpPolicyDefinitionsType); assertThat(definitions, hasSize(3)); assertEquals(initialDenyAdvice, findByRevisionNbr(definitions, 0).getDenyAdvice()); assertEquals("advice_changed", findByRevisionNbr(definitions, 1).getDenyAdvice()); assertEquals("advice_changed_again", findByRevisionNbr(definitions, 2).getDenyAdvice()); PdpPolicy newRevision = getExistingPolicy(); assertEquals("advice_changed_again", pdpPolicyDefinitionParser.parse(newRevision).getDenyAdvice()); } @Test public void testRevisionsByPolicyIdWithNewPolicy() { PdpPolicy policy = getExistingPolicy(); PdpPolicyDefinition policyDefinition = pdpPolicyDefinitionParser.parse(policy); // this will ensure a new policy is created policyDefinition.setId(null); policyDefinition.setName("some name"); assertThat(post("/internal/policies", policyDefinition).getStatusCode(), is(HttpStatus.OK)); PdpPolicy saved = pdpPolicyRepository.findFirstByPolicyIdAndLatestRevision( PolicyTemplateEngine.getPolicyId(policyDefinition.getName()), true).get(0); List<PdpPolicyDefinition> definitions = getForObject("/internal/revisions/" + saved.getId(), pdpPolicyDefinitionsType); assertThat(definitions, hasSize(1)); assertEquals(policyDefinition.getName(), definitions.get(0).getName()); } @Test public void testDefaultPolicy() { PdpPolicyDefinition definition = getForObject("/internal/default-policy", new ParameterizedTypeReference<PdpPolicyDefinition>() { }); assertFalse(definition.isAllAttributesMustMatch()); assertFalse(definition.isDenyRule()); } @Test public void testAllowedAttributes() { List<JsonPolicyRequest.Attribute> allowedAttributes = getForObject("/internal/attributes", new ParameterizedTypeReference<List<JsonPolicyRequest.Attribute>>() { }); assertThat(allowedAttributes, hasSize(9)); assertAttributes(allowedAttributes); } @Test public void testAllowedSamlAttributes() { List<JsonPolicyRequest.Attribute> samlAttributes = getForObject("/internal/saml-attributes", new ParameterizedTypeReference<List<JsonPolicyRequest.Attribute>>() { }); assertThat(samlAttributes, hasSize(10)); JsonPolicyRequest.Attribute nameId = samlAttributes.get(0); assertEquals("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified", nameId.attributeId); assertNotNull(nameId.value); assertAttributes(samlAttributes); } @Test public void testDeletePdpPolicy() { // verify that violations are also deleted - so we create one setUpViolation(policyIdToDelete); PdpPolicy policy = getExistingPolicy(policyIdToDelete); PdpPolicyDefinition policyDefinition = pdpPolicyDefinitionParser.parse(policy); // verify that revisions are also deleted - so we create one assertThat(post("/internal/policies", policyDefinition).getStatusCode(), is(HttpStatus.OK)); PdpPolicy latestRevision = getExistingPolicy(policyIdToDelete); assertThat(delete("/internal/policies/" + latestRevision.getId()).getStatusCode(), is(HttpStatus.OK)); List<PdpPolicyViolation> violations = getForObject("/internal/violations", new ParameterizedTypeReference<List<PdpPolicyViolation>>() { }); assertViolations(violations, 0); assertPolicyIsDeleted(policy); assertPolicyIsDeleted(latestRevision); } @Test public void testUser() { Map<String, Object> shibbolethUser = getForObject("/internal/users/me", new ParameterizedTypeReference<Map<String, Object>>() { }); assertEquals("urn:collab:person:example.com:admin", shibbolethUser.get("username")); assertEquals("John Doe", shibbolethUser.get("displayName")); assertEquals(PolicyLoader.authenticatingAuthority, shibbolethUser.get("authenticatingAuthority")); assertEquals(2, ((Collection) shibbolethUser.get("idpEntities")).size()); assertEquals(3, ((Collection) shibbolethUser.get("spEntities")).size()); } @Test public void testCreatePolicyWithNameError() throws JsonParseException, JsonMappingException, IOException { PdpPolicyDefinition policyDefinition = pdpPolicyDefinitionParser.parse(getExistingPolicy()); policyDefinition.setId(null); ResponseEntity<String> response = post("/internal/policies", policyDefinition); assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); Map<String, Object> map = objectMapper.readValue(response.getBody(), new TypeReference<Map<String, Object>>() { }); String message = (String) ((Map<?, ?>) map.get("details")).get("name"); assertTrue(message.contains("Policy name must be unique")); } @Test public void testAssertBadRequestUnknownIdentityProvider() { PdpPolicyDefinition policyDefinition = getPdpPolicyDefinitionFromExistingPolicy(); impersonate("http://xxx-idp", "urn:collab:person:example.com:mary.doe", "Mary Doe"); ResponseEntity<String> post = post("/internal/policies", policyDefinition); assertEquals(HttpStatus.BAD_REQUEST, post.getStatusCode()); assertTrue(post.getBody().contains("http://xxx-idp is not a valid or known IdP / SP entityId")); } @Test public void testConflicts() { ResponseEntity<String> response = get("/internal/conflicts"); assertNotNull(response.getBody()); } @Override public RestTemplate getRestTemplate() { return restTemplate; } private PdpPolicyDefinition findByRevisionNbr(List<PdpPolicyDefinition> definitions, int revisionNbr) { return definitions.stream().filter(def -> def.getRevisionNbr() == revisionNbr).collect(singletonCollector()); } private void assertViolations(List<PdpPolicyViolation> violations, int expectedSize) { assertThat(violations, hasSize(expectedSize)); violations.forEach(v -> assertTrue(v.getCreated().before(new Date()))); } private void assertAttributes(List<JsonPolicyRequest.Attribute> allowedAttributes) { allowedAttributes.forEach(attr -> { assertTrue(attr.attributeId.startsWith("urn")); assertNotNull(attr.value); }); } }
package uk.ac.ebi.biosamples.export; import java.io.File; import java.io.FileWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.hateoas.Resource; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import uk.ac.ebi.biosamples.client.BioSamplesClient; import uk.ac.ebi.biosamples.model.Sample; @Component public class ExportRunner implements ApplicationRunner { private final Logger log = LoggerFactory.getLogger(getClass()); private final BioSamplesClient bioSamplesClient; private final ObjectMapper objectMapper; public ExportRunner(BioSamplesClient bioSamplesClient, ObjectMapper objectMapper) { this.bioSamplesClient = bioSamplesClient; this.objectMapper = objectMapper; } @Override public void run(ApplicationArguments args) throws Exception { String jsonSampleFilename = args.getNonOptionArgs().get(0); long oldTime = System.nanoTime(); try { boolean first = true; try ( FileWriter jsonSampleWriter = new FileWriter(new File(jsonSampleFilename)); ) { jsonSampleWriter.write("[\n"); for (Resource<Sample> sampleResource : bioSamplesClient.fetchSampleResourceAll()) { log.trace("Handling "+sampleResource); Sample sample = sampleResource.getContent(); if (sample == null) { throw new RuntimeException("Sample should not be null"); } if (!first) { jsonSampleWriter.write(",\n"); } jsonSampleWriter.write(objectMapper.writeValueAsString(sample)); first = false; } jsonSampleWriter.write("\n]"); } finally { } } finally { } long elapsed = System.nanoTime()-oldTime; log.info("Exported samples from in "+(elapsed/1000000000l)+"s"); } }
package com.intellij.openapi.options.ex; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurableGroup; import com.intellij.openapi.options.OptionsBundle; import com.intellij.openapi.options.CompositeConfigurable; import java.util.Iterator; import java.util.List; public class IdeConfigurablesGroup implements ConfigurableGroup { public String getDisplayName() { return OptionsBundle.message("ide.settings.display.name"); } public String getShortName() { return OptionsBundle.message("ide.settings.short.name"); } public Configurable[] getConfigurables() { final Application app = ApplicationManager.getApplication(); final Configurable[] extensions = app.getExtensions(Configurable.APPLICATION_CONFIGURABLES); Configurable[] components = app.getComponents(Configurable.class); List<Configurable> result = ProjectConfigurablesGroup.buildConfigurablesList(extensions, components); removeAssistants(result); removeEmptyComposites(result); return result.toArray(new Configurable[result.size()]); } static void removeAssistants(final List<Configurable> result) { final Iterator<Configurable> iterator = result.iterator(); while (iterator.hasNext()) { Configurable each = iterator.next(); if (each instanceof Configurable.Assistant) { iterator.remove(); } } } private static void removeEmptyComposites(final List<Configurable> result) { for (Iterator<Configurable> iterator = result.iterator(); iterator.hasNext();) { Configurable configurable = iterator.next(); if (configurable instanceof CompositeConfigurable) { final List children = ((CompositeConfigurable)configurable).getConfigurables(); if (children.isEmpty()) { iterator.remove(); } } } } public boolean equals(Object object) { return object instanceof IdeConfigurablesGroup; } public int hashCode() { return 0; } }
package com.intellij.util.indexing; import com.intellij.diagnostic.PerformanceWatcher; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.ControlFlowException; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.impl.ProgressSuspender; import com.intellij.openapi.project.*; import com.intellij.openapi.roots.ContentIterator; import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.openapi.roots.impl.PushedFilePropertiesUpdater; import com.intellij.openapi.roots.impl.PushedFilePropertiesUpdaterImpl; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.RefreshQueue; import com.intellij.util.ExceptionUtil; import com.intellij.util.SystemProperties; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.containers.ConcurrentBitSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.contentQueue.IndexUpdateRunner; import com.intellij.util.indexing.diagnostic.IndexDiagnosticDumper; import com.intellij.util.indexing.diagnostic.IndexingJobStatistics; import com.intellij.util.indexing.diagnostic.ProjectIndexingHistory; import com.intellij.util.indexing.diagnostic.ScanningStatistics; import com.intellij.util.indexing.roots.IndexableFilesIterator; import com.intellij.util.indexing.roots.SdkIndexableFilesIterator; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.progress.ConcurrentTasksProgressManager; import com.intellij.util.progress.SubTaskProgressIndicator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.VisibleForTesting; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; public final class UnindexedFilesUpdater extends DumbModeTask { private static final Logger LOG = Logger.getInstance(UnindexedFilesUpdater.class); private static final int DEFAULT_MAX_INDEXER_THREADS = 4; @VisibleForTesting public static volatile boolean ONLY_SCANNING = false; public static final ExecutorService GLOBAL_INDEXING_EXECUTOR = AppExecutorUtil.createBoundedApplicationPoolExecutor( "Indexing", getMaxNumberOfIndexingThreads() ); private static final @NotNull Key<Boolean> CONTENT_SCANNED = Key.create("CONTENT_SCANNED"); private static final @NotNull Key<UnindexedFilesUpdater> RUNNING_TASK = Key.create("RUNNING_INDEX_UPDATER_TASK"); private static final Object ourLastRunningTaskLock = new Object(); private final FileBasedIndexImpl myIndex = (FileBasedIndexImpl)FileBasedIndex.getInstance(); private final Project myProject; private final boolean myStartSuspended; private final boolean myRunExtensionsForFilesMarkedAsIndexed; private final PushedFilePropertiesUpdater myPusher; public UnindexedFilesUpdater(@NotNull Project project, boolean startSuspended, boolean runExtensionsForFilesMarkedAsIndexed) { super(project); myProject = project; myStartSuspended = startSuspended; myRunExtensionsForFilesMarkedAsIndexed = runExtensionsForFilesMarkedAsIndexed; myPusher = PushedFilePropertiesUpdater.getInstance(myProject); myProject.putUserData(CONTENT_SCANNED, null); synchronized (ourLastRunningTaskLock) { UnindexedFilesUpdater runningTask = myProject.getUserData(RUNNING_TASK); if (runningTask != null) { DumbService.getInstance(project).cancelTask(runningTask); } myProject.putUserData(RUNNING_TASK, this); } } @Override public void dispose() { synchronized (ourLastRunningTaskLock) { UnindexedFilesUpdater lastRunningTask = myProject.getUserData(RUNNING_TASK); if (lastRunningTask == this) { myProject.putUserData(RUNNING_TASK, null); } } } public UnindexedFilesUpdater(@NotNull Project project) { // If we haven't succeeded to fully scan the project content yet, then we must keep trying to run // file based index extensions for all project files until at least one of UnindexedFilesUpdater-s finishes without cancellation. // This is important, for example, for shared indexes: all files must be associated with their locally available shared index chunks. this(project, false, !isProjectContentFullyScanned(project)); } private void updateUnindexedFiles(@NotNull ProjectIndexingHistory projectIndexingHistory, @NotNull ProgressIndicator indicator) { if (!IndexInfrastructure.hasIndices()) return; ProgressSuspender suspender = ProgressSuspender.getSuspender(indicator); if (suspender != null) { listenToProgressSuspenderForSuspendedTimeDiagnostic(suspender, projectIndexingHistory); } if (myStartSuspended) { if (suspender == null) { throw new IllegalStateException("Indexing progress indicator must be suspendable!"); } if (!suspender.isSuspended()) { suspender.suspendProcess(IndexingBundle.message("progress.indexing.started.as.suspended")); } } indicator.setIndeterminate(true); indicator.setText(IndexingBundle.message("progress.indexing.scanning")); boolean trackResponsiveness = !ApplicationManager.getApplication().isUnitTestMode(); PerformanceWatcher.Snapshot snapshot = PerformanceWatcher.takeSnapshot(); Instant pushPropertiesStart = Instant.now(); try { myPusher.pushAllPropertiesNow(); } finally { projectIndexingHistory.getTimes().setPushPropertiesDuration(Duration.between(pushPropertiesStart, Instant.now())); } if (trackResponsiveness) snapshot.logResponsivenessSinceCreation("Pushing properties"); myIndex.clearIndicesIfNecessary(); snapshot = PerformanceWatcher.takeSnapshot(); Instant indexExtensionsStart = Instant.now(); try { FileBasedIndexInfrastructureExtension.EP_NAME.extensions().forEach(ex -> ex.processIndexingProject(myProject, indicator)); } finally { projectIndexingHistory.getTimes().setIndexExtensionsDuration(Duration.between(indexExtensionsStart, Instant.now())); } Instant scanFilesStart = Instant.now(); List<IndexableFilesIterator> orderedProviders; Map<IndexableFilesIterator, List<VirtualFile>> providerToFiles; try { orderedProviders = getOrderedProviders(); providerToFiles = collectIndexableFilesConcurrently(myProject, indicator, orderedProviders, projectIndexingHistory); myProject.putUserData(CONTENT_SCANNED, true); } finally { projectIndexingHistory.getTimes().setScanFilesDuration(Duration.between(scanFilesStart, Instant.now())); } if (trackResponsiveness) snapshot.logResponsivenessSinceCreation("Indexable file iteration"); if (!ApplicationManager.getApplication().isUnitTestMode()) { // full VFS refresh makes sense only after it's loaded, i.e. after scanning files to index is finished scheduleInitialVfsRefresh(); } int totalFiles = providerToFiles.values().stream().mapToInt(it -> it.size()).sum(); if (trackResponsiveness) { LOG.info("Unindexed files update started: " + totalFiles + " files to index"); } if (totalFiles == 0 || SystemProperties.getBooleanProperty("idea.indexes.pretendNoFiles", false)) { return; } snapshot = PerformanceWatcher.takeSnapshot(); ProgressIndicator poweredIndicator = PoweredProgressIndicator.wrap(indicator, getPowerForSmoothProgressIndicator()); poweredIndicator.setIndeterminate(false); poweredIndicator.setFraction(0); poweredIndicator.setText(IndexingBundle.message("progress.indexing.updating")); ConcurrentTasksProgressManager concurrentTasksProgressManager = new ConcurrentTasksProgressManager(poweredIndicator, totalFiles); int numberOfIndexingThreads = getNumberOfIndexingThreads(); LOG.info("Using " + numberOfIndexingThreads + " " + StringUtil.pluralize("thread", numberOfIndexingThreads) + " for indexing"); IndexUpdateRunner indexUpdateRunner = new IndexUpdateRunner(myIndex, GLOBAL_INDEXING_EXECUTOR, numberOfIndexingThreads); Instant startIndexing = Instant.now(); try { for (IndexableFilesIterator provider : orderedProviders) { List<VirtualFile> providerFiles = providerToFiles.get(provider); if (providerFiles == null || providerFiles.isEmpty()) { continue; } concurrentTasksProgressManager.setText(provider.getIndexingProgressText()); SubTaskProgressIndicator subTaskIndicator = concurrentTasksProgressManager.createSubTaskIndicator(providerFiles.size()); try { IndexingJobStatistics statistics; IndexUpdateRunner.IndexingInterruptedException exception = null; try { statistics = indexUpdateRunner.indexFiles(myProject, provider.getDebugName(), providerFiles, subTaskIndicator); } catch (IndexUpdateRunner.IndexingInterruptedException e) { exception = e; statistics = e.myStatistics; } try { projectIndexingHistory.addProviderStatistics(statistics); } catch (Exception e) { LOG.error("Failed to add indexing statistics for " + provider.getDebugName(), e); } if (exception != null) { ExceptionUtil.rethrow(exception.getCause()); } } finally { subTaskIndicator.finished(); } } } finally { projectIndexingHistory.getTimes().setIndexingDuration(Duration.between(startIndexing, Instant.now())); } if (trackResponsiveness) snapshot.logResponsivenessSinceCreation("Unindexed files update"); myIndex.dumpIndexStatistics(); } private void listenToProgressSuspenderForSuspendedTimeDiagnostic(@NotNull ProgressSuspender suspender, @NotNull ProjectIndexingHistory projectIndexingHistory) { MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(this); connection.subscribe(ProgressSuspender.TOPIC, new ProgressSuspender.SuspenderListener() { private volatile Instant suspensionStart = null; @Override public void suspendedStatusChanged(@NotNull ProgressSuspender changedSuspender) { if (suspender == changedSuspender) { if (suspender.isSuspended()) { suspensionStart = Instant.now(); } else { Instant now = Instant.now(); Instant start = suspensionStart; suspensionStart = null; if (start != null && start.compareTo(now) < 0) { Duration thisDuration = Duration.between(start, now); Duration currentTotalDuration = projectIndexingHistory.getTimes().getSuspendedDuration(); Duration newTotalSuspendedDuration = currentTotalDuration.plus(thisDuration); projectIndexingHistory.getTimes().setSuspendedDuration(newTotalSuspendedDuration); } } } } }); } static boolean isProjectContentFullyScanned(@NotNull Project project) { return Boolean.TRUE.equals(project.getUserData(CONTENT_SCANNED)); } /** * Returns providers of files. Since LAB-22 (Smart Dumb Mode) is not implemented yet, the order of the providers is not strictly specified. * For shared indexes it is a good idea to index JDKs in the last turn (because they likely have shared index available) * so this method moves all SDK providers to the end. */ @NotNull private List<IndexableFilesIterator> getOrderedProviders() { List<IndexableFilesIterator> originalOrderedProviders = myIndex.getOrderedIndexableFilesProviders(myProject); List<IndexableFilesIterator> orderedProviders = new ArrayList<>(); originalOrderedProviders.stream() .filter(p -> !(p instanceof SdkIndexableFilesIterator)) .collect(Collectors.toCollection(() -> orderedProviders)); originalOrderedProviders.stream() .filter(p -> p instanceof SdkIndexableFilesIterator) .collect(Collectors.toCollection(() -> orderedProviders)); return orderedProviders; } @NotNull private Map<IndexableFilesIterator, List<VirtualFile>> collectIndexableFilesConcurrently( @NotNull Project project, @NotNull ProgressIndicator indicator, @NotNull List<IndexableFilesIterator> providers, @NotNull ProjectIndexingHistory projectIndexingHistory ) { if (providers.isEmpty()) { return Collections.emptyMap(); } UnindexedFilesFinder unindexedFileFilter = new UnindexedFilesFinder(project, myIndex, myRunExtensionsForFilesMarkedAsIndexed); Map<IndexableFilesIterator, List<VirtualFile>> providerToFiles = new IdentityHashMap<>(); ConcurrentBitSet visitedFileSet = new ConcurrentBitSet(); indicator.setText(IndexingBundle.message("progress.indexing.scanning")); indicator.setIndeterminate(false); indicator.setFraction(0); ConcurrentTasksProgressManager concurrentTasksProgressManager = new ConcurrentTasksProgressManager(indicator, providers.size()); List<Runnable> tasks = ContainerUtil.map(providers, provider -> { SubTaskProgressIndicator subTaskIndicator = concurrentTasksProgressManager.createSubTaskIndicator(1); List<VirtualFile> files = new ArrayList<>(); ScanningStatistics scanningStatistics = new ScanningStatistics(provider.getDebugName()); providerToFiles.put(provider, files); ContentIterator collectingIterator = fileOrDir -> { if (subTaskIndicator.isCanceled()) { return false; } UnindexedFileStatus status; long statusTime = System.nanoTime(); try { status = ONLY_SCANNING ? null : unindexedFileFilter.getFileStatus(fileOrDir); } finally { statusTime = System.nanoTime() - statusTime; } if (status != null) { if (status.getShouldIndex()) { files.add(fileOrDir); } scanningStatistics.addStatus(status, statusTime); } return true; }; return () -> { subTaskIndicator.setText(provider.getRootsScanningProgressText()); try { provider.iterateFiles(project, collectingIterator, visitedFileSet); } finally { synchronized (projectIndexingHistory) { projectIndexingHistory.addScanningStatistics(scanningStatistics); } subTaskIndicator.finished(); } }; }); PushedFilePropertiesUpdaterImpl.invokeConcurrentlyIfPossible(tasks); return providerToFiles; } private void scheduleInitialVfsRefresh() { ProjectRootManagerEx.getInstanceEx(myProject).markRootsForRefresh(); Application app = ApplicationManager.getApplication(); if (!app.isCommandLine()) { long sessionId = VirtualFileManager.getInstance().asyncRefresh(null); MessageBusConnection connection = app.getMessageBus().connect(); connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectClosed(@NotNull Project project) { if (project == myProject) { RefreshQueue.getInstance().cancelSession(sessionId); connection.disconnect(); } } }); } else { ApplicationManager.getApplication().invokeAndWait(() -> VirtualFileManager.getInstance().syncRefresh()); } } private static double getPowerForSmoothProgressIndicator() { String rawValue = Registry.stringValue("indexing.progress.indicator.power"); if ("-".equals(rawValue)) { return 1.0; } try { return Double.parseDouble(rawValue); } catch (NumberFormatException e) { return 1.0; } } @Override public void performInDumbMode(@NotNull ProgressIndicator indicator) { ProjectIndexingHistory projectIndexingHistory = new ProjectIndexingHistory(myProject); projectIndexingHistory.getTimes().setTotalStart(Instant.now()); myIndex.filesUpdateStarted(myProject); try { updateUnindexedFiles(projectIndexingHistory, indicator); } catch (Throwable e) { projectIndexingHistory.getTimes().setWasInterrupted(true); if (e instanceof ControlFlowException) { LOG.info("Unindexed files update canceled"); } throw e; } finally { myIndex.filesUpdateFinished(myProject); projectIndexingHistory.getTimes().setUpdatingEnd(ZonedDateTime.now(ZoneOffset.UTC)); IndexDiagnosticDumper.INSTANCE.dumpProjectIndexingHistoryIfNecessary(projectIndexingHistory); } } /** * Returns the best number of threads to be used for indexing at this moment. * It may change during execution of the IDE depending on other activities' load. */ public static int getNumberOfIndexingThreads() { int threadsCount = Registry.intValue("caches.indexerThreadsCount"); if (threadsCount <= 0) { int coresToLeaveForOtherActivity = ApplicationManager.getApplication().isCommandLine() ? 0 : 1; threadsCount = Math.max(1, Math.min(Runtime.getRuntime().availableProcessors() - coresToLeaveForOtherActivity, DEFAULT_MAX_INDEXER_THREADS)); } return threadsCount; } /** * Returns the maximum number of threads to be used for indexing during this execution of the IDE. */ public static int getMaxNumberOfIndexingThreads() { // Change of the registry option requires IDE restart. int threadsCount = Registry.intValue("caches.indexerThreadsCount"); if (threadsCount <= 0) { return DEFAULT_MAX_INDEXER_THREADS; } return threadsCount; } }
package poussecafe.processing; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import org.slf4j.Logger; import poussecafe.apm.ApplicationPerformanceMonitoring; import poussecafe.environment.MessageListener; import poussecafe.environment.MessageListenerConsumptionReport; import poussecafe.environment.MessageListenerGroupConsumptionState; import poussecafe.runtime.MessageConsumptionHandler; import poussecafe.runtime.OriginalAndMarshaledMessage; import poussecafe.util.ExponentialBackoff; public class MessageConsumption { public static class Builder { private MessageConsumption consumption = new MessageConsumption(); public Builder consumptionId(String consumptionId) { consumption.consumptionId = consumptionId; return this; } public Builder logger(Logger logger) { consumption.logger = logger; return this; } public Builder listenersPartition(ListenersSetPartition listenersPartition) { consumption.listenersPartition = listenersPartition; return this; } public Builder failFast(boolean failFast) { consumption.failFast = failFast; return this; } public Builder messageConsumptionHandler(MessageConsumptionHandler messageConsumptionHandler) { consumption.messageConsumptionHandler = messageConsumptionHandler; return this; } public Builder applicationPerformanceMonitoring(ApplicationPerformanceMonitoring applicationPerformanceMonitoring) { consumption.applicationPerformanceMonitoring = applicationPerformanceMonitoring; return this; } public Builder message(OriginalAndMarshaledMessage message) { consumption.message = message; return this; } public Builder messageConsumptionConfiguration(MessageConsumptionConfiguration messageConsumptionConfiguration) { consumption.messageConsumptionConfiguration = messageConsumptionConfiguration; return this; } public MessageConsumption build() { Objects.requireNonNull(consumption.consumptionId); Objects.requireNonNull(consumption.listenersPartition); Objects.requireNonNull(consumption.messageConsumptionHandler); Objects.requireNonNull(consumption.applicationPerformanceMonitoring); Objects.requireNonNull(consumption.logger); Objects.requireNonNull(consumption.message); Objects.requireNonNull(consumption.messageConsumptionConfiguration); consumption.messageConsumptionState = new MessageConsumptionState(consumption.message); return consumption; } } private MessageConsumption() { } private String consumptionId; private OriginalAndMarshaledMessage message; public void execute() { logger.debug("Handling received message {}", message.original()); List<MessageListenerGroup> groups = buildMessageListenerGroups(); logGroup(groups); if(!groups.isEmpty()) { List<MessageListenerGroup> toRetryInitially = consumeMessageOrRetryGroups(groups); if(!toRetryInitially.isEmpty()) { retryConsumption(toRetryInitially); } } logger.debug("Message {} handled (consumption ID {})", message.original(), consumptionId); } private void logGroup(List<MessageListenerGroup> groups) { if(logger.isDebugEnabled()) { logger.debug("Built {} groups:", groups.size()); for(MessageListenerGroup group : groups) { logger.debug(" group {}", group.aggregateRootClass()); for(MessageListener listener : group.listeners()) { logger.debug(" - {}", listener.shortId()); } } } } private List<MessageListenerGroup> buildMessageListenerGroups() { Collection<MessageListener> listeners = listenersPartition.partitionListenersSet() .messageListenersOf(message.original().getClass()); return new MessageListenersGroupsFactory.Builder() .applicationPerformanceMonitoring(applicationPerformanceMonitoring) .consumptionId(consumptionId) .failFast(failFast) .message(message) .messageConsumptionHandler(messageConsumptionHandler) .build() .buildMessageListenerGroups(listeners); } private ListenersSetPartition listenersPartition; private List<MessageListenerGroup> consumeMessageOrRetryGroups(List<MessageListenerGroup> groups) { List<MessageListenerGroup> toRetry = new ArrayList<>(); for (MessageListenerGroup group : groups) { boolean mustRetry = consumeMessage(group); if(mustRetry) { toRetry.add(group); } } return toRetry; } private boolean consumeMessage(MessageListenerGroup group) { MessageListenerGroupConsumptionState consumptionState = messageConsumptionState.buildMessageListenerGroupState(); List<MessageListenerConsumptionReport> reports = group.consumeMessageOrRetry(consumptionState); messageConsumptionState.update(reports); return reports.stream().anyMatch(MessageListenerConsumptionReport::mustRetry); } private void retryConsumption(List<MessageListenerGroup> toRetryInitially) { messageConsumptionState.isFirstConsumption(false); ExponentialBackoff exponentialBackoff = new ExponentialBackoff.Builder() .slotTime(messageConsumptionConfiguration.backOffSlotTime()) .ceiling(messageConsumptionConfiguration.backOffCeiling()) .build(); int retry = 1; List<MessageListenerGroup> toRetry = toRetryInitially; while(!toRetry.isEmpty() && retry <= messageConsumptionConfiguration.maxConsumptionRetries()) { long waitTime = (long) exponentialBackoff.nextValue(); try { Thread.sleep(waitTime); } catch (InterruptedException e) { logger.error("Thread was interrupted during backoff"); Thread.currentThread().interrupt(); break; } logger.info("Retrying consumption of {} for {} groups after {} ms", message.original().getClass().getSimpleName(), toRetry.size(), waitTime); toRetry = consumeMessageOrRetryGroups(toRetry); ++retry; } if(!toRetry.isEmpty()) { logger.error("Reached max. # of retries ({}), giving up handling of {} with {} remaining groups", messageConsumptionConfiguration.maxConsumptionRetries(), message.original().getClass().getName(), toRetry.size()); logger.error("Unhandled message: {}", message.marshaled()); } else { logger.info("Message {} successfully consumed after {} retries", message.original().getClass().getSimpleName(), (retry - 1)); } } private MessageConsumptionConfiguration messageConsumptionConfiguration; protected Logger logger; private MessageConsumptionState messageConsumptionState; private MessageConsumptionHandler messageConsumptionHandler; private boolean failFast; private ApplicationPerformanceMonitoring applicationPerformanceMonitoring; }
package com.gravity.player; import java.util.List; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.Shape; import org.newdawn.slick.geom.Transform; import org.newdawn.slick.geom.Vector2f; import com.gravity.gameplay.GravityGameController; import com.gravity.map.GameWorld; import com.gravity.physics.Collision; import com.gravity.physics.Entity; public class Player implements Entity { public enum Movement { LEFT, RIGHT, STOP } private GravityGameController game; // PLAYER STARTING CONSTANTS private final float JUMP_POWER = 5; private final float MOVEMENT_INCREMENT = 10000.0f / 1000f; private float MAX_HEALTH = 10; private float MAX_VEL = 200f / 1000f; private float VEL_DAMP = 0.5f; private float GRAVITY = 1.0f / 1000f; // PLAYER CURRENT VALUES private GameWorld map; // position and magnitude private Vector2f acceleration = new Vector2f(0, 0); public Vector2f oldPosition = new Vector2f(0, 0); private Vector2f newPosition = new Vector2f(0, 0); private Vector2f velocity = new Vector2f(0, 0); private Vector2f facing = new Vector2f(0, 1); private float health; private Shape myShape; private float starty; // GAME STATE STUFF private boolean onGround = true; public Player(GameWorld map, GravityGameController game) { health = MAX_HEALTH; velocity = new Vector2f(0, 0); this.map = map; this.game = game; this.myShape = new Rectangle(-.5f, -.5f, 1f, 1f); } public void takeDamage(float damage) { health -= damage; } public void heal(float heal) { health += heal; } /** * @param jumping * true if keydown, false if keyup */ public void jump(boolean jumping) { if (onGround) { starty = oldPosition.y; onGround = false; velocity.y -= JUMP_POWER; } else { if (newPosition.y < starty){ acceleration.y = (GRAVITY); } else { onGround = true; velocity.y = 0; acceleration.y = 0; } } } /** * * @param direction */ public void move(Movement direction) { switch (direction) { case LEFT: { acceleration.x = -MOVEMENT_INCREMENT; break; } case RIGHT: { acceleration.x = MOVEMENT_INCREMENT; break; } case STOP: { acceleration.x = 0; break; } } } // Get where you WILL be in "ticks" time @Override public Vector2f getPosition(int ticks) { return newPosition; } @Override public Shape getShape(int ticks) { return myShape.transform(Transform.createTranslateTransform( oldPosition.x + (velocity.x * ticks), oldPosition.y + (velocity.y * ticks))); } @Override public Vector2f getVelocity(int ticks) { return velocity.copy(); } @Override public Shape handleCollisions(int ticks, List<Collision> collisions) { Collision first = null; int earliest = -1; for (Collision c : collisions) { if (earliest == -1) { earliest = c.time; first = c; } else if (c.time < earliest) { earliest = c.time; first = c; } else { continue; } } if (earliest == -1) { System.out.println("WTF???"); return this.getShape(0); } Entity me = this; Entity them = first.getOtherEntity(this); if ((them.getShape(earliest) instanceof Rectangle)) { newPosition = oldPosition.add(velocity .scale((float) (earliest - (1.0 / 1000)))); // If I'm overlapping their xcoord if (me.getShape(earliest + 1).getMaxX() > them.getShape( earliest + 1).getMinX()) { velocity.x = 0; } else if (me.getShape(earliest + 1).getMinX() < them.getShape( earliest + 1).getMaxX()) { velocity.x = 0; } // If I'm overlapping their ycoord else if (me.getShape(earliest + 1).getMinY() < them.getShape( earliest + 1).getMaxY()) { velocity.y = 0; } else if (me.getShape(earliest + 1).getMinY() < them.getShape( earliest + 1).getMaxY()) { velocity.y = 0; } } // TODO: Write code for non-rectangles return null; } @Override public Shape rehandleCollisions(int ticks, List<Collision> collisions) { // TODO Auto-generated method stub return null; } @Override public void tick(int millis) { handleMotion(millis); } /** * Makes sure maximum velocities are respected, player position is updated, * etc */ public void handleMotion(float millis) { oldPosition = newPosition; // Check to see if the player is on the ground isOnGround(); // Change the velocity depending on the accelerations velocity.add(acceleration.copy().scale(millis)); // Makes sure velocity does not exceed max velocity if (velocity.length() > MAX_VEL * millis) velocity.scale(MAX_VEL * millis / velocity.length()); // Updates position to reflect velocity newPosition = oldPosition.add(velocity); System.out.println("oldPosition = " + oldPosition.x); } /* * Sets onGround depending on if the player is on the ground or not */ public void isOnGround() { // TODO } }
package edu.wpi.first.wpilibj.templates; /** * * @author Tyler */ public class Pickup { public static final double SHOOTER_POSITION = 50; public static final double PICKUP_TOLERANCE = 2; public static boolean rollerArmUp; public static boolean rollerArmDown; public static double pickupMechSpeed; public static double gamePieceIntakeSpeed; public static double pickupEncoder; public static boolean lowerLimit; public static boolean upperLimit; public static boolean loaded; // initializes everything public static void init() { } // moves to the desired shoot location // Might have to be done using PIDs later on public static void moveToShoot() { if (pickupEncoder < SHOOTER_POSITION) { pickupMechSpeed = 1.0; } else if (pickupEncoder > SHOOTER_POSITION) { pickupMechSpeed = -1.0; } else { pickupMechSpeed = 0.0; } } // moves the pickup mech to the floor public static void moveToFloor() { if (!lowerLimit) { pickupMechSpeed = -1.0; } else { pickupMechSpeed = 0.0; } } // moves the pickup mech to catch public static void moveToCatch() { if (!upperLimit) { pickupMechSpeed = 1.0; } else { pickupMechSpeed = 0.0; } } // moves the pickup mech public static void movePickup(double speed) { pickupMechSpeed = speed; } // checks if the gamePiece is in the position to be loaded public static boolean isLoaded() { return loaded; } // raises the top arm public static void raiseTopArm() { rollerArmUp = true; rollerArmDown = false; } // lowers the top arm public static void lowerTopArm() { rollerArmUp = false; rollerArmDown = true; } // intakes the game piece public static void intakeGamePiece() { if (!loaded) { gamePieceIntakeSpeed = 1.0; } else { gamePieceIntakeSpeed = 0.0; } } // passes the game piece public static void passGamePiece() { gamePieceIntakeSpeed = -1.0; } // stops the pickup mech public static void stopMovingMech() { pickupMechSpeed = 0.0; } // stops the game piece intake mech public static void stopGamePieceMech() { gamePieceIntakeSpeed = 0.0; } // updates everything public static void update() { // gets all the sensors needed pickupEncoder = RobotSensors.pickupPotentiometer.get(); lowerLimit = RobotSensors.pickupSystemDownLim.get(); upperLimit = RobotSensors.pickupSystemUpLim.get(); loaded = RobotSensors.shooterLoadedLim.get(); // sets all the actuators needed RobotActuators.rollerArmUp.set(rollerArmUp); RobotActuators.rollerArmDown.set(rollerArmDown); RobotActuators.pickupSystemMotor.set(pickupMechSpeed); RobotActuators.pickupSystemMotor.set(gamePieceIntakeSpeed); } }
package org.noear.weed; public class DbQuery extends DbAccess<DbQuery> { public DbQuery(DbContext context) { super(context); } public DbQuery sql(SQLBuilder sqlBuilder) { this.commandText = sqlBuilder.toString(); this.paramS.clear(); this._weedKey = null; for (Object p1 : sqlBuilder.paramS) { doSet("", p1); } return this; } @Override protected String getCommandID() { return this.commandText; } @Override protected Command getCommand() { Command cmd = new Command(this.context,_tran); cmd.key = getCommandID(); cmd.paramS = this.paramS; StringBuilder sb = new StringBuilder(commandText); //1.schema int idx=0; while (true) { idx = sb.indexOf("$",idx); if(idx>0) { if(context.schema() == null){ sb.replace(idx, idx + 2, ""); }else { sb.replace(idx, idx + 1, context.schema()); } idx++; } else { break; } } cmd.text = sb.toString(); runCommandBuiltEvent(cmd); return cmd; } }
package ui.monitor.input; import input.InputManager; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JLabel; import javax.swing.LayoutStyle.ComponentPlacement; import java.awt.Color; import java.util.Vector; import javax.swing.JScrollPane; import javax.swing.BoxLayout; import coordinates.Coordinate; import coordinates.CoordinateImage; import events.event.AcceptingStateEvent; import events.event.CoordinateEvent; import events.listeners.CoordinateListener; import javax.swing.JToggleButton; import java.awt.Dimension; import java.awt.TextArea; import java.awt.FlowLayout; import javax.swing.ScrollPaneConstants; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; /** * A JFrame to display and monitor input Coordinate data * @author Balazs Pete * */ public class InputMonitor extends JFrame { private static final long serialVersionUID = 8902258483370822829L; private JFrame frame; private JPanel contentPane; private InputCanvas canvas; private Vector<Coordinate> coordinates = new Vector<Coordinate>(); private JScrollPane scrollPane; private JToggleButton tglbtnAutoScroll; private int coordinateCounter = 0; private JLabel lblNumberOfInputsCouter; private JPanel panel_1; private JPanel statesDisplay; private JScrollPane scrollPane_1; /** * Create the frame with a specified InputManager. */ public InputMonitor(InputManager inputManager) { initialize(); addListener(inputManager); } /** * Initialize the components */ private void initialize() { frame = new JFrame(); frame.setTitle("GestureRecogniser: Input Monitor"); frame.setBounds(100, 100, 600, 360); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); frame.setContentPane(contentPane); JPanel panel = new JPanel(); JLabel lblNumberOfInputs = new JLabel("Number of inputs: "); lblNumberOfInputsCouter = new JLabel("0000"); lblNumberOfInputsCouter.setForeground(Color.GRAY); tglbtnAutoScroll = new JToggleButton("Auto Scroll"); tglbtnAutoScroll.setSelected(true); panel_1 = new JPanel(); GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane.setHorizontalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(panel, GroupLayout.DEFAULT_SIZE, 590, Short.MAX_VALUE) .addGroup(gl_contentPane.createSequentialGroup() .addContainerGap() .addComponent(lblNumberOfInputs) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(lblNumberOfInputsCouter) .addPreferredGap(ComponentPlacement.RELATED, 314, Short.MAX_VALUE) .addComponent(tglbtnAutoScroll)) .addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 590, Short.MAX_VALUE) ); gl_contentPane.setVerticalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addComponent(panel, GroupLayout.PREFERRED_SIZE, 216, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 64, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.UNRELATED) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(lblNumberOfInputs) .addComponent(lblNumberOfInputsCouter) .addComponent(tglbtnAutoScroll)) .addContainerGap(14, Short.MAX_VALUE)) ); panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.X_AXIS)); scrollPane_1 = new JScrollPane(); scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); scrollPane_1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); panel_1.add(scrollPane_1); statesDisplay = new JPanel(); statesDisplay.setBackground(Color.black); scrollPane_1.setViewportView(statesDisplay); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); scrollPane = new JScrollPane(); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane.getHorizontalScrollBar().addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent arg0) { syncHorizontalScrollBars(); } }); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); panel.add(scrollPane); canvas = new InputCanvas(); scrollPane.setViewportView(canvas); contentPane.setLayout(gl_contentPane); } /** * Handle the input AcceptinStateEvent * @param e The AcceptingStateEvent to handle */ public void handleAcceptingState(AcceptingStateEvent e) { canvas.addAcceptingStatePoint(coordinates.size()); frame.paintComponents(frame.getGraphics()); } /** * Add a CoordinateListener * @param inputManager The input manager */ private void addListener(InputManager inputManager) { inputManager.addEventListener(new CoordinateListener() { @Override public void handleCoordinate(CoordinateEvent e) { addCoordinate(e.getCoordinate()); } }); } /** * Add and handle a new Coordinate * @param coordinate The Coordinate to be handled */ private void addCoordinate(Coordinate coordinate) { coordinateCounter++; coordinates.add(coordinate); frame.setVisible(true); CoordinateImage image = new CoordinateImage(coordinates.size(), canvas.getHeight()-1, coordinates, 1); canvas.replaceImage(image); Dimension d = new Dimension(coordinates.size() + 10, scrollPane_1.getHeight()-1); statesDisplay.setSize(d); statesDisplay.setPreferredSize(d); frame.paintComponents(frame.getGraphics()); lblNumberOfInputsCouter.setText("" + coordinateCounter); if(tglbtnAutoScroll.isSelected()) scrollPane.getHorizontalScrollBar().setValue(image.getWidth()); } /** * Method to sync the horizontal scrollbard */ private void syncHorizontalScrollBars() { scrollPane_1.getHorizontalScrollBar() .setValue(scrollPane.getHorizontalScrollBar().getValue()); } }
package org.codehaus.xfire.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import org.codehaus.xfire.XFireRuntimeException; /** * Resolves a File, classpath resource, or URL according to the follow rules: * <ul> * <li>Check to see if a file exists, relative to the base URI.</li> * <li>If the file doesn't exist, check the classpath</li> * <li>If the classpath doesn't exist, try to create URL from the URI.</li> * </ul> * @author Dan Diephouse */ public class Resolver { private File file; private URI uri; private InputStream is; public Resolver(String path) throws IOException { this("", path); } public Resolver(String baseUriStr, String uriStr) throws IOException { try { URI relative; File uriFile = new File(uriStr); uriFile = new File(uriFile.getAbsolutePath()); if (uriFile.exists()) { relative = uriFile.toURI(); } else relative = new URI(uriStr); if (relative.isAbsolute()) { uri = relative; is = relative.toURL().openStream(); } else if (baseUriStr != null) { URI base; File baseFile = new File(baseUriStr); if (baseFile.exists()) base = baseFile.toURI(); else base = new URI(baseUriStr); base = base.resolve(relative); if (base.isAbsolute()) { is = base.toURL().openStream(); uri = base; } } } catch (URISyntaxException e) { } if (uri != null && "file".equals(uri.getScheme())) { file = new File(uri); } if (is == null && file != null && file.exists()) { uri = file.toURI(); try { is = new FileInputStream(file); } catch (FileNotFoundException e) { throw new XFireRuntimeException("File was deleted! " + uriStr, e); } } else if (is == null) { URL url = ClassLoaderUtils.getResource(uriStr, getClass()); if (url == null) { try { url = new URL(uriStr); uri = new URI(url.toString()); is = url.openStream(); } catch (MalformedURLException e) { } catch (URISyntaxException e) { } } else { is = url.openStream(); } } if (is == null) throw new IOException("Could not find resource '" + uriStr + "' relative to '" + baseUriStr + "'"); } public URI getURI() { return uri; } public InputStream getInputStream() { return is; } public boolean isFile() { return file.exists(); } public File getFile() { return file; } }
package tankattack; import Sprites.*; import java.util.*; import javafx.animation.*; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.image.*; import javafx.scene.input.*; import javafx.scene.paint.*; import javafx.scene.shape.*; import javafx.stage.*; import javafx.util.*; /** * * @author Ruslan */ public abstract class World { public static boolean isListeningForInput = true; private Stage myStage; private Scene scene; private Group root; private Circle myEnemy; private Point2D myEnemyVelocity; private Random myGenerator = new Random(); private ArrayList<Sprite> sprites; private Player playerSprite; private Timeline timeline; // Performance-Improving Variables // created to not create objects @ 60Hz private double[] playerLocation; private double[] newXY; // Setters, Getters public void addSprite(Sprite s) { if (sprites == null) { sprites = new ArrayList(); } sprites.add(s); root.getChildren().add(s); } public void removeSprite(Sprite s) { if (sprites == null) { return; } sprites.remove(s); root.getChildren().remove(s); } public void setPlayerSprite(Player player) { playerSprite = player; } public Player getPlayerSprite() { return playerSprite; } public Group getGroup() { return this.root; } public void setGroup(Group root) { this.root = root; } public Scene getScene() { return this.scene; } public void setScene(Scene scene) { this.scene = scene; } // Real Methods // Constructors // Create Scene, Then Init Animation. Rest of methods are helpers. public World() { throw new UnsupportedOperationException("need to pass in a stage"); } public World(Stage stage) { this.myStage = stage; } public Scene createScene() { root = new Group(); createInitialSprites(); scene = new Scene(root, TankAttack.gameWidth, TankAttack.gameHeight, Color.CORNFLOWERBLUE); scene.setOnKeyPressed(e -> handleKeyInput(e)); scene.setOnKeyReleased(e -> handleKeyRelease(e)); return scene; } public void initAnimation() { KeyFrame frame = new KeyFrame(Duration.millis(1000 / TankAttack.NUM_FRAMES_PER_SECOND), e -> updateSprites()); if (timeline == null) { timeline = new Timeline(); } timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(frame); timeline.play(); } public abstract void createInitialSprites(); public void createPlayerSprite() { Player player = new Player(TankAttack.gameWidth/2 , TankAttack.gameHeight / 2); setPlayerSprite(player); addSprite(player); } private void updateSprites() { // System.out.println("All is well. Printing animation 60 times a second."); ////// DONE //////////////////////////// updatePlayerLocation(); ////// DONE //////////////////////////// ////// IMPLEMENT //////////////////////////// // Other Updates // updateEnemySprites(); // Handle Firing handleFiring(); // Register Collisions / Hits // handleCollision(); // Check for win checkForWin(); ////// IMPLEMENT //////////////////////////// } private void updatePlayerLocation() { if (playerLocation == null) { playerLocation = new double[2]; } playerLocation[0] = playerSprite.getTranslateX(); playerLocation[1] = playerSprite.getTranslateY(); double playerWidth = playerSprite.width(); double playerHeight = playerSprite.height(); if (newXY == null) { newXY = new double[2]; } newXY = DirController.getNewXY(playerLocation, playerWidth, playerHeight, TankAttack.PLAYER_SPEED); playerSprite.setTranslateX(newXY[0]); playerSprite.setTranslateY(newXY[1]); } private void endOfLevel() { timeline.pause(); // TODO: Display level complete. showEndOfLevelText(); // Tell TankAttack to put up the next world. signalEndOfLevel(); } private void showEndOfLevelText() { System.out.println("TODO: Animate text over this level's end saying END OF LEVEL."); } public abstract void signalEndOfLevel(); public void handleKeyInput(KeyEvent e) { KeyCode keyCode = e.getCode(); if (keyCode == KeyCode.RIGHT) { DirController.rightPressed = true; } else if (keyCode == KeyCode.LEFT) { DirController.leftPressed = true; } else if (keyCode == KeyCode.UP) { DirController.upPressed = true; } else if (keyCode == KeyCode.DOWN) { DirController.downPressed = true; } // TODO: Implement space bar to shoot, and cheat codes, here. } public void handleKeyRelease(KeyEvent e) { KeyCode keyCode = e.getCode(); if (keyCode == KeyCode.RIGHT) { DirController.rightPressed = false; } else if (keyCode == KeyCode.LEFT) { DirController.leftPressed = false; } else if (keyCode == KeyCode.UP) { DirController.upPressed = false; } else if (keyCode == KeyCode.DOWN) { DirController.downPressed = false; } } }
package com.ehpefi.iforgotthat; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewSwitcher; import com.ehpefi.iforgotthat.swipelistview.BaseSwipeListViewListener; import com.ehpefi.iforgotthat.swipelistview.SwipeListView; /** * The main activity which displays all the available lists * * @author Per Erik Finstad * @author Even Holthe * @since 1.0.0 */ public class MainActivity extends Activity { // UI Elements SwipeListView listView; EditText listNameInput; TextView hasNoLists; // Utilities ViewSwitcher switcher; public int position; InputMethodManager imm; // Database related ListHelper listHelper; ListElementHelper listElementHelper; ArrayList<ListObject> allLists; ListObjectAdapter listAdapter; // Used for logging private static final String TAG = "MainActivity"; // Notification Toast toast; // Context of this class final Context context = this; ListObject currentList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Find our UI elements listView = (SwipeListView) findViewById(R.id.mainView); listNameInput = (EditText) findViewById(R.id.editable_add_list_input); hasNoLists = (TextView) findViewById(R.id.text_has_no_lists); switcher = (ViewSwitcher) findViewById(R.id.add_list_switcher); // Initialize helpers listHelper = new ListHelper(this); listElementHelper = new ListElementHelper(this); imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); // Fetch all the lists from the database allLists = listHelper.getAllLists(ListHelper.COL_ID); // Create a new list adapter for all our lists listAdapter = new ListObjectAdapter(this, R.layout.list_row, allLists); listView.setAdapter(listAdapter); // Swipe listener listView.setSwipeListViewListener(new BaseSwipeListViewListener() { }); listView.setSwipeListViewListener(new BaseSwipeListViewListener() { // Whenever a row has been slided to show the back, update the list position @Override public void onOpened(int pos, boolean toRight) { position = pos; Log.d(TAG, "Updated list position to " + pos); } // For clicks on the list names @Override public void onClickFrontView(int position) { // Get the object for the clicked list ListObject list = (ListObject) listView.getItemAtPosition(position); // Create an intent and pass the title and id Intent intent = new Intent(getApplicationContext(), ListWithElementsActivity.class); intent.putExtra("title", list.getTitle()); intent.putExtra("listID", list.getId()); startActivity(intent); // Transition smoothly :) overridePendingTransition(R.anim.right_in, R.anim.left_out); } }); showLists(); } /** * Takes care of showing an empty message if there are no lists, and all the lists if number of lists > 0 * * @since 1.0.0 */ private void showLists() { // If the database doesn't contain any lists if (listHelper.numberOfLists() == 0) { // Hide the list view listView.setVisibility(View.GONE); hasNoLists.setVisibility(View.VISIBLE); Log.d(TAG, "No lists in the database"); return; } Log.d(TAG, "Lists in the datbase"); // Show the list view if we have data hasNoLists.setVisibility(View.GONE); listView.setVisibility(View.VISIBLE); } /** * Shows the completed items * * @param view The view * @since 1.0.0 */ public void showCompletedItems(View view) { Intent completed = new Intent(this, ListWithElementsActivity.class); completed.putExtra("title", getResources().getString(R.string.completed_items)); completed.putExtra("listID", ListElementHelper.COMPLETED_LIST_ID); startActivity(completed); // Transition smoothly :) overridePendingTransition(R.anim.right_in, R.anim.left_out); } /** * Requests the change from TextView to EditText * * @param view The view * @since 1.0.0 */ public void addNewListClicked(View view) { switcher.showNext(); if (listNameInput.hasFocus()) { imm.toggleSoftInputFromWindow(listNameInput.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0); } } /** * Convenience method for displaying a toast message * * @param message The message to display * @since 1.0.0 */ private void displayToast(String message) { // If there is an active toast, cancel it if (toast != null) { toast.cancel(); } // Create a toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG); // Set the position to right above the keyboard (on Nexus S at least) toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, -50); toast.show(); } /** * Handles clicks on the "delete list" button * * @param view The view * @since 1.0.0 */ public void deleteList(View view) { // Get the object to be deleted currentList = (ListObject) listAdapter.getItem(position); // Create a dialog box to confirm deletion AlertDialog confirmDeletion = new AlertDialog.Builder(this).setTitle(getResources().getString(R.string.list_deletion_title)) .setMessage(String.format(getResources().getString(R.string.list_deletion_confirm), currentList.getTitle())) .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // If we successfully deleted the list if (listHelper.deleteList(currentList.getId(), context)) { // Close the slider listView.closeAnimate(position); // Remove the list from the array allLists.remove(position); displayToast(String.format(getResources().getString(R.string.list_deletion_ok), currentList.getTitle())); } else { // Couldn't delete the list displayToast(String.format(getResources().getString(R.string.list_deletion_fail), currentList.getTitle())); } // Refresh view listAdapter.notifyDataSetChanged(); showLists(); } }).setNegativeButton(getResources().getString(R.string.no), new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { listView.closeAnimate(position); dialog.cancel(); } }).create(); confirmDeletion.show(); } public void renameList(View view) { // Get the object to be renamed currentList = (ListObject) listAdapter.getItem(position); // Inflate layout View renameLayout = getLayoutInflater().inflate(R.layout.rename_list, null); // Set text inside the EditText (the current list name) ((EditText) renameLayout.findViewById(R.id.new_list_name)).setText(currentList.getTitle()); AlertDialog renameDialog = new AlertDialog.Builder(this).setView(renameLayout) .setTitle(String.format(getResources().getString(R.string.rename_list_title), currentList.getTitle())) .setPositiveButton(R.string.rename_list_okbutton, new DialogInterface.OnClickListener() { @Override // When the user has pressed "Rename" public void onClick(DialogInterface dialog, int id) { // Get the input text (the new title) EditText newTitleET = (EditText) ((AlertDialog) dialog).findViewById(R.id.new_list_name); String newTitle = newTitleET.getText().toString(); // Check for empty input if (newTitle.equals("") || newTitle == null || newTitle.trim().length() == 0) { displayToast(getResources().getString(R.string.list_name_empty)); } else { // Try to rename the list if (listHelper.renameList(currentList.getId(), newTitle)) { displayToast(String.format(getResources().getString(R.string.list_rename_ok), currentList.getTitle(), newTitle)); // Rename the local object currentList.setTitle(newTitle); // Close the slider listView.closeAnimate(position); // Update the dataset listAdapter.notifyDataSetChanged(); showLists(); } else { displayToast(String.format(getResources().getString(R.string.list_rename_fail), currentList.getTitle())); } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { // Cancel button public void onClick(DialogInterface dialog, int id) { dialog.cancel(); // Close the slider listView.closeAnimate(position); } }).create(); renameDialog.show(); } /** * Handle the user input after they have provided a list name * * @param view The view * @since 1.0.0 */ public void addNewListTextEntered(View view) { // The list name the user typed in String inputName = listNameInput.getText().toString(); Log.d(TAG, "The list name that was entered was: " + inputName); if (inputName.equals("") || inputName == null || inputName.trim().length() == 0) { // Send toast to user displayToast(getResources().getString(R.string.list_name_empty)); // Dismiss keyboard and switch back to text saying "Add new list" imm.hideSoftInputFromWindow(listNameInput.getWindowToken(), 0); switcher.showNext(); return; } // Check for a list named the same as the input if (listHelper.doesListWithTitleExist(inputName)) { displayToast(String.format(getResources().getString(R.string.list_already_exists), inputName)); } else { // Try to create the list int listID = listHelper.createNewList(inputName); if (listID > 0) { // All good, update the data and tell the listAdapter to refresh allLists.add(listHelper.getList(listID)); listAdapter.notifyDataSetChanged(); showLists(); // Tell the user that everything went OK displayToast(String.format(getResources().getString(R.string.list_creation_ok), inputName)); // Close the keyboard imm.hideSoftInputFromWindow(listNameInput.getWindowToken(), 0); // Show the add new list text switcher.showNext(); // Reset the text in the EditText listNameInput.setText(""); } else { // Just display a toast telling the user that the creation of a new list failed displayToast(String.format(getResources().getString(R.string.list_creation_fail), inputName)); } } } @Override protected void onDestroy() { super.onDestroy(); } public void onBackPressed() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }
import org.junit.Test; import static org.junit.Assert.*; import hageldave.imagingkit.filter.settings.FilterSettings; public class FilterSettings_test { @Test public void testSetGet(){ String id = "testSetting"; FilterSettings settings = new FilterSettings(); assertFalse(settings.containsSetting(id)); assertEquals(0, settings.getSettingIds().size()); assertEquals(null, settings.get(id)); assertEquals(4, settings.get(id, 4)); settings.set(id, 5); assertTrue(settings.containsSetting(id)); assertEquals(1, settings.getSettingIds().size()); assertEquals(5, settings.get(id)); assertEquals(5, settings.getAs(id, Integer.class)); assertEquals(null, settings.getAs(id, String.class)); assertEquals("hello", settings.getAs(id, String.class, "hello")); settings.clear(id); assertFalse(settings.containsSetting(id)); assertEquals(0, settings.getSettingIds().size()); assertEquals(null, settings.get(id)); testException(()->{settings.set(null,null);}, NullPointerException.class); testException(()->{settings.set(id,null);}, NullPointerException.class); testException(()->{settings.set(null,5);}, NullPointerException.class); } @Test public void testTypeConstraint(){ String id1 = "testSetting1"; String id2 = "testSetting2"; { FilterSettings settings = new FilterSettings(true); settings.set(id1, 5); settings.set(id2, 8); assertEquals(0, settings.getSettingIds().size()); assertEquals(null, settings.get(id1)); assertEquals(null, settings.get(id1)); } { testException(()-> { new FilterSettings(new Object[]{id1}); }, IllegalArgumentException.class); testException(()-> { new FilterSettings(new Object[]{id1,id2}); }, IllegalArgumentException.class); testException(()-> { new FilterSettings(new Object[]{id1,5}); }, IllegalArgumentException.class); testException(()-> { new FilterSettings(new Object[]{id1,Object.class, id1, Integer.class}); }, IllegalArgumentException.class); FilterSettings settings = new FilterSettings(new Object[]{id1, Integer.class, id2, null}); assertEquals(true, settings.isTypeConstrained(id1)); assertEquals(true, settings.isTypeConstrained(id2)); assertEquals(Integer.class, settings.getTypeConstraint(id1)); assertEquals(Object.class, settings.getTypeConstraint(id2)); testException(()-> { settings.set(id1, "stringvalue"); }, IllegalArgumentException.class); settings.set(id2, "stringvalue"); assertEquals(String.class, settings.get(id2).getClass()); settings.set(id1, 5); assertEquals(5, settings.get(id1)); } } public static void testException(Runnable codeThatThrows, Class<? extends Throwable> exClass){ boolean wasThrown = true; try{ codeThatThrows.run(); wasThrown = false; } catch(Throwable t){ if(!exClass.isInstance(t)){ fail(String.format("Expected Exception %s but got %s", exClass, t.getClass())); } } if(!wasThrown){ fail(String.format("Expected Exception %s but none was thrown",exClass)); } } }
package org.a0z.mpd; import org.a0z.mpd.connection.MPDConnection; import org.a0z.mpd.event.StatusChangeListener; import org.a0z.mpd.event.TrackPositionListener; import org.a0z.mpd.exception.MPDConnectionException; import org.a0z.mpd.exception.MPDServerException; import java.util.LinkedList; import java.util.List; /** * Monitors MPD Server and sends events on status changes. */ public class MPDStatusMonitor extends Thread { /** The song database has been modified after update. */ public static final String IDLE_DATABASE = "database"; /** A message was received on a channel this client is subscribed to. */ public static final String IDLE_MESSAGE = "message"; /** Emitted after the mixer volume has been modified. */ public static final String IDLE_MIXER = "mixer"; /** Emitted after an option (repeat, random, cross fade, Replay Gain) modification. */ public static final String IDLE_OPTIONS = "options"; /** Emitted after a output has been enabled or disabled. */ public static final String IDLE_OUTPUT = "output"; /** Emitted after upon current playing status change. */ public static final String IDLE_PLAYER = "player"; /** Emitted after the playlist queue has been modified. */ public static final String IDLE_PLAYLIST = "playlist"; /** Emitted after the sticker database has been modified. */ public static final String IDLE_STICKER = "sticker"; /** Emitted after a server side stored playlist has been added, removed or modified. */ public static final String IDLE_STORED_PLAYLIST = "stored_playlist"; /** Emitted after a client has added or removed subscription to a channel. */ public static final String IDLE_SUBSCRIPTION = "subscription"; /** Emitted after a database update has started or finished. See IDLE_DATABASE */ public static final String IDLE_UPDATE = "update"; private static final String TAG = "MPDStatusMonitor"; private final long delay; private final MPD mpd; private volatile boolean giveup; private final LinkedList<StatusChangeListener> statusChangedListeners; private final LinkedList<TrackPositionListener> trackPositionChangedListeners; private final MPDCommand mIdleCommand; /** * Constructs a MPDStatusMonitor. * * @param mpd MPD server to monitor. * @param delay status query interval. * @param supportedIdle Idle subsystems to support, see IDLE fields in this class. */ public MPDStatusMonitor(MPD mpd, long delay, final String[] supportedIdle) { super("MPDStatusMonitor"); this.mpd = mpd; this.delay = delay; this.giveup = false; this.statusChangedListeners = new LinkedList<>(); this.trackPositionChangedListeners = new LinkedList<>(); mIdleCommand = new MPDCommand(MPDCommand.MPD_CMD_IDLE, supportedIdle); } /** * Adds a {@code StatusChangeListener}. * * @param listener a {@code StatusChangeListener}. */ public void addStatusChangeListener(StatusChangeListener listener) { statusChangedListeners.add(listener); } /** * Adds a {@code TrackPositionListener}. * * @param listener a {@code TrackPositionListener}. */ public void addTrackPositionListener(TrackPositionListener listener) { trackPositionChangedListeners.add(listener); } /** * Gracefully terminate tread. */ public void giveup() { this.giveup = true; } public boolean isGivingUp() { return this.giveup; } /** * Main thread method */ public void run() { // initialize value cache int oldSong = -1; int oldSongId = -1; int oldPlaylistVersion = -1; long oldElapsedTime = -1L; int oldState = MPDStatus.STATE_UNKNOWN; int oldVolume = -1; boolean oldUpdating = false; boolean oldRepeat = false; boolean oldRandom = false; boolean oldConnectionState = false; boolean connectionLost = false; /** Objects to keep cached in {@link MPD} */ final MPDStatus status = mpd.getStatus(); final MPDPlaylist playlist = mpd.getPlaylist(); while (!giveup) { Boolean connectionState = Boolean.valueOf(mpd.isConnected()); boolean connectionStateChanged = false; if (connectionLost || oldConnectionState != connectionState) { for (StatusChangeListener listener : statusChangedListeners) { listener.connectionStateChanged(connectionState.booleanValue(), connectionLost); } if (mpd.isConnected()) { try { mpd.updateStatistics(); mpd.updateStatus(); playlist.refresh(status); } catch (final MPDServerException e) { Log.error(TAG, "Failed to force a status update.", e); } } connectionLost = false; oldConnectionState = connectionState; connectionStateChanged = true; } if (connectionState == Boolean.TRUE) { // playlist try { boolean dbChanged = false; boolean statusChanged = false; if (connectionStateChanged) { dbChanged = statusChanged = true; } else { final List<String> changes = waitForChanges(); mpd.updateStatus(); for (final String change : changes) { switch(change.substring("changed: ".length())) { case "database": mpd.updateStatistics(); dbChanged = true; statusChanged = true; break; case "playlist": statusChanged = true; break; default: statusChanged = true; break; } if (dbChanged && statusChanged) { break; } } } if (statusChanged) { // playlist if (connectionStateChanged || (oldPlaylistVersion != status.getPlaylistVersion() && status .getPlaylistVersion() != -1)) { playlist.refresh(status); for (StatusChangeListener listener : statusChangedListeners) { listener.playlistChanged(status, oldPlaylistVersion); } oldPlaylistVersion = status.getPlaylistVersion(); } // song /** * songId is used here, otherwise, once consume mode is enabled getSongPos * would never iterate without manual user playlist queue intervention and * trackChanged() would never be called. */ if (connectionStateChanged || oldSongId != status.getSongId()) { for (StatusChangeListener listener : statusChangedListeners) { listener.trackChanged(status, oldSong); } oldSong = status.getSongPos(); oldSongId = status.getSongId(); } // time if (connectionStateChanged || oldElapsedTime != status.getElapsedTime()) { for (TrackPositionListener listener : trackPositionChangedListeners) { listener.trackPositionChanged(status); } oldElapsedTime = status.getElapsedTime(); } // state if (connectionStateChanged || !status.isState(oldState)) { for (StatusChangeListener listener : statusChangedListeners) { listener.stateChanged(status, oldState); } oldState = status.getState(); } // volume if (connectionStateChanged || oldVolume != status.getVolume()) { for (StatusChangeListener listener : statusChangedListeners) { listener.volumeChanged(status, oldVolume); } oldVolume = status.getVolume(); } // repeat if (connectionStateChanged || oldRepeat != status.isRepeat()) { for (StatusChangeListener listener : statusChangedListeners) { listener.repeatChanged(status.isRepeat()); } oldRepeat = status.isRepeat(); } // volume if (connectionStateChanged || oldRandom != status.isRandom()) { for (StatusChangeListener listener : statusChangedListeners) { listener.randomChanged(status.isRandom()); } oldRandom = status.isRandom(); } // update database if (connectionStateChanged || oldUpdating != status.isUpdating()) { for (StatusChangeListener listener : statusChangedListeners) { listener.libraryStateChanged(status.isUpdating(), dbChanged); } oldUpdating = status.isUpdating(); } } } catch (MPDConnectionException e) { // connection lost connectionState = Boolean.FALSE; connectionLost = true; } catch (MPDServerException e) { e.printStackTrace(); } } try { synchronized (this) { this.wait(delay); } } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Wait for server changes using "idle" command on the dedicated connection. * * @return Data read from the server. * @throws MPDServerException if an error occur while contacting server */ private List<String> waitForChanges() throws MPDServerException { final MPDConnection mpdIdleConnection = mpd.getMpdIdleConnection(); while (mpdIdleConnection != null && mpdIdleConnection.isConnected()) { final List<String> data = mpdIdleConnection.sendCommand(mIdleCommand); if (data.isEmpty()) { continue; } return data; } throw new MPDConnectionException("IDLE connection lost"); } }
/* * $Log: FixedResult.java,v $ * Revision 1.7 2004-09-01 07:21:11 L190409 * correction in documentation * */ package nl.nn.adapterframework.pipes; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.PipeRunException; import nl.nn.adapterframework.core.PipeRunResult; import nl.nn.adapterframework.core.PipeStartException; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.Misc; import nl.nn.adapterframework.util.StringResolver; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; import java.io.IOException; import java.util.Properties; /** * Provides an example of a pipe. It may return the contents of a file * (in the classpath) when <code>setFileName</code> is specified, otherwise the * input of <code>setReturnString</code> is returned. * * <p><b>Configuration:</b> * <table border="1"> * <tr><th>attributes</th><th>description</th><th>default</th></tr> * <tr><td>{@link #setName(String) name}</td><td>name of the Pipe</td><td>&nbsp;</td></tr> * <tr><td>{@link #setMaxThreads(int) maxThreads}</td><td>maximum number of threads that may call {@link #doPipe(Object, PipeLineSession)} simultaneously</td><td>0 (unlimited)</td></tr> * <tr><td>{@link #setForwardName(String) forwardName}</td> <td>name of forward returned upon completion</td><td>"success"</td></tr> * <tr><td>{@link #setFileName(String) fileName}</td> <td>name of the file containing the resultmessage</td><td>&nbsp;</td></tr> * <tr><td>{@link #setReturnString(String) returnString}</td><td>returned message</td><td>&nbsp;</td></tr> * <tr><td>{@link #setSubstituteVars(boolean) substituteVars}</td><td>Should values between ${ and } be resolved from the PipeLineSession</td><td>False</td></tr> * </table> * </p> * <p><b>Exits:</b> * <table border="1"> * <tr><th>state</th><th>condition</th></tr> * <tr><td>"success"</td><td>default</td></tr> * <tr><td><i>{@link #setForwardName(String) forwardName}</i></td><td>if specified</td></tr> * </table> * </p> * @version Id * @author Johan Verrips */ public class FixedResult extends FixedForwardPipe { public static final String version="$Id: FixedResult.java,v 1.7 2004-09-01 07:21:11 L190409 Exp $"; private String fileName; private String returnString; private boolean substituteVars=false; public void setSubstituteVars(boolean substitute){ this.substituteVars=substitute; } public boolean getSubstituteVars(){ return this.substituteVars; } /** * checks for correct configuration, and translates the fileName to * a file, to check existence. * If a fileName was specified, the contents of the file is put in the * <code>returnString</code>, so that allways the <code>returnString</code> * may be returned. * @throws ConfigurationException */ public void configure() throws ConfigurationException { super.configure(); if (StringUtils.isNotEmpty(fileName)) { try { returnString = Misc.resourceToString(ClassUtils.getResourceURL(this,fileName), SystemUtils.LINE_SEPARATOR); } catch (Throwable e) { throw new ConfigurationException("Pipe [" + getName() + "] got exception loading ["+fileName+"]", e); } } if ((StringUtils.isEmpty(fileName)) && (StringUtils.isEmpty(returnString))) { throw new ConfigurationException("Pipe [" + getName() + "] has neither fileName nor returnString specified"); } } public PipeRunResult doPipe(Object input, PipeLineSession session) throws PipeRunException { String result=returnString; if (getSubstituteVars()){ result=StringResolver.substVars(returnString, session); } log.debug(getLogPrefix(session)+ " returning fixed result [" + result + "]"); return new PipeRunResult(getForward(), result); } public String getFileName() { return fileName; } public String getReturnString() { return returnString; } /** * Sets the name of the filename. The fileName should not be specified * as an absolute path, but as a resource in the classpath. * * @param fileName the name of the file to return the contents from */ public void setFileName(String fileName) { this.fileName = fileName; } public void setReturnString(String returnString) { this.returnString = returnString; } }
import java.util.ArrayList; import java.util.List; class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> result = new ArrayList<>(); if (n <= 0 || k <= 0 || k > n) { return result; } generateCombinations(n, k, 1, new ArrayList<Integer>(), result); return result; } private void generateCombinations(int n, int k, int start, List<Integer> p, List<List<Integer>> result) { if (p.size() == k) { result.add(new ArrayList<Integer>(p)); return; } for (int i = start; i <= n - (k - p.size()) + 1; i++) { p.add(i); generateCombinations(n, k, i + 1, p, result); p.remove(p.size() - 1); } return; } }
package restaurants.tests; import org.openqa.selenium.remote.BrowserType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import restaurants.appmanager.ApplicationManager; import restaurants.tests.MainPageOfRestTests.NameOfRestTests; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.Arrays; public class TestBase { Logger logger = LoggerFactory.getLogger(TestBase.class); public static ApplicationManager app; protected String usernameAdmin = "manager@lunch.ua"; protected String passwordAdmin = "2CDTx8Wz"; protected String usernameGuest = "slava17puh999@gmail.com"; protected String passwordGuest = "bigdig2"; @BeforeSuite public void setUp() throws Exception { app = new ApplicationManager(BrowserType.CHROME); app.init(); } @AfterSuite(alwaysRun = true) public void tearDown() { app.stop(); } @BeforeMethod public void logTestStart(Method m, Object[] p){ logger.info("Start test "+ m.getName() + " with parameters "+ Arrays.asList(p)); } @AfterMethod(alwaysRun = true) public void logTestStop(Method m){ logger.info("Stop test "+ m.getName()); } }
package com.uoit.freeroomfinder; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; /** * LoginActivity Provides the activity for signing in to the app. Displays a sign-in field. * * @author Jonathan Gillett * @author Joseph Heron * @author Daniel Smullen * */ public class LoginActivity extends Activity { /** * Determines whether the login fields are open. */ private static boolean open = false; /** * Provides the task for the user's login process. */ private UserLoginTask authTask = null; /** * Stores the dialog for the sign in. */ private ProgressDialog dialog; /** * Success return code for a good login. */ public static final int LOGIN_SUCCESSFUL = 100; /** * The user who is attempting to login. */ private static User user = null; /* * (non-Javadoc) * * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_screen); // Open the database interface to attempt the sign in. DatabaseInterface dbi = new DatabaseInterface(this.getBaseContext()); if (open || dbi.getUser() != null) { this.finish(); } else { open = true; } } /* * (non-Javadoc) * * @see android.app.Activity#onPause() */ @Override protected void onPause() { // Default method implementation. Resets the open database connection state. super.onPause(); open = false; } /* * (non-Javadoc) * * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } /* * (non-Javadoc) * * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(final MenuItem item) { // Default method implementation. switch (item.getItemId()) { case R.id.action_settings: this.startActivity(new Intent(this, SettingsActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } /** * submit Submits the user name and password field contents to sign in with. * * @param v * Requires a handle to a view which initiates the method. */ public void submit(View v) { // Grab the user name and password input fields. EditText username = (EditText) findViewById(R.id.username); EditText password = (EditText) findViewById(R.id.password); // Ensure the fields aren't blank. if (username.getText() != null && password.getText() != null) { user = new User(username.getText().toString(), password.getText().toString()); // Validate the user name and password. if (user.validUsername() && user.validPassword()) { // Show the progress alert. showProgress(true); // Do the login. authTask = new UserLoginTask(); authTask.execute((Void) null); } else { // Error conditions. Show toasts for each one. if (!user.validUsername() && user.validPassword()) { Toast.makeText(this, R.string.username_error, Toast.LENGTH_LONG).show(); } else if (user.validUsername() && !user.validPassword()) { Toast.makeText(this, R.string.password_error, Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, R.string.username_password_error, Toast.LENGTH_LONG) .show(); } user = null; } } } /** * reset Opens the password reset web site. * * @param v * Requires a handle to the view which initiates the method. */ public void reset(View v) { // Go to password reset site in the browser. Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(this.getString(R.string.reset_site))); this.startActivity(i); } /** * register Opens the registration web site. * * @param v * Requires a handle to the view which initiates the method. */ public void register(View v) { // Go to registration site in the browser. Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(this.getString(R.string.register_site))); this.startActivity(i); } /** * showProgress Show or hide the progress dialog. * * @param show * Show the dialog if true. Otherwise, don't show it. */ private void showProgress(boolean show) { if (show) { dialog = ProgressDialog.show(this, getString(R.string.login_heading), getString(R.string.login_progress_signing_in), true, true, new OnCancelListener() { public void onCancel(DialogInterface dialog) { LoginActivity.this.finish(); } }); } else { dialog.dismiss(); } } /** * UserLoginTask An asynchronous task for connecting and validating the user login credentials * with the external database server. * * @author Daniel Smullen * @author Jonathan Gillett * @author Joseph Heron * */ public class UserLoginTask extends AsyncTask<Void, Void, Boolean> { /* * (non-Javadoc) * * @see android.os.AsyncTask#doInBackground(Params[]) */ @Override protected Boolean doInBackground(Void... params) { if (user != null) { /** * Validate the login credentials using REST API request. */ if (Request.validateCredentials(user.getUsername(), user.getPassword())) { /** * Add the user into the internal database if the validation is successful. */ DatabaseInterface dbi = new DatabaseInterface( LoginActivity.this.getBaseContext()); dbi.insertUser(user); return true; } } return false; } /* * (non-Javadoc) * * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(final Boolean success) { // Shows a toast when the validation is successful. Shows an error message if it wasn't. authTask = null; showProgress(false); if (success) { LoginActivity.this.setResult(LoginActivity.LOGIN_SUCCESSFUL); LoginActivity.this.finish(); } else { Toast.makeText(LoginActivity.this, R.string.error_invalid_account, Toast.LENGTH_LONG).show(); } } /* * (non-Javadoc) * * @see android.os.AsyncTask#onCancelled() */ @Override protected void onCancelled() { // Default method implementation. Stops the progress dialog from showing. authTask = null; showProgress(false); } } }
package br.ufrn.Myeclone.controler; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class EnviarEmail { public static void main(String[] args) { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("leyenasd@gmail.com","vigorolass"); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("leyenasd@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("leyenasd@gmail.com")); message.setSubject("Testing Subject"); message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
package owltools.sim2; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.log4j.Logger; import org.semanticweb.elk.owlapi.ElkReasonerFactory; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLNamedIndividual; import org.semanticweb.owlapi.model.OWLNamedObject; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.reasoner.Node; import org.semanticweb.owlapi.reasoner.NodeSet; import org.semanticweb.owlapi.reasoner.OWLReasoner; import org.semanticweb.owlapi.reasoner.impl.OWLClassNode; import owltools.mooncat.ontologymetadata.OntologySetMetadata; import owltools.sim2.SimpleOwlSim.Direction; import owltools.sim2.SimpleOwlSim.Metric; import owltools.sim2.SimpleOwlSim.SimConfigurationProperty; import owltools.sim2.io.SimResultRenderer.AttributesSimScores; import owltools.sim2.scores.AttributePairScores; import owltools.sim2.scores.ElementPairScores; import owltools.sim2.scores.ScoreMatrix; import com.googlecode.javaewah.EWAHCompressedBitmap; import com.googlecode.javaewah.IntIterator; /** * Faster implementation of OwlSim * * Makes use of integers to index classes, and bitmaps to represent class sets. * * @author cjm * */ public class FastOwlSim extends AbstractOwlSim implements OwlSim { private Logger LOG = Logger.getLogger(FastOwlSim.class); public OWLClass debugClass; int debugClassMessages = 0; int debugClassMessages2 = 0; private Map<OWLNamedIndividual, Set<OWLClass>> elementToDirectAttributesMap; // CACHES // all direct and inferred classes for al individual // todo: resolve redundancy with inferredTypesMap private Map<OWLNamedIndividual, Set<Node<OWLClass>>> elementToInferredAttributesMap; private Map<OWLClass,Set<Node<OWLClass>>> superclassMap; // cache of Type(i)->Cs private Map<OWLNamedIndividual,Set<Node<OWLClass>>> inferredTypesMap; private Map<OWLClass,Set<Integer>> superclassIntMap; private Map<OWLNamedIndividual,Set<Integer>> inferredTypesIntMap; // BITMAP CACHES // for efficiency, we store sets of classes as bitmaps. // each class is assigned an integer value, resulting // it bitmaps of with |c| bits // given a class index, return superclasses, as a bitmap // e.g. if class C has index 7, then superclassBitmapIndex[7] returns a bitmap, // in which every "1" value is the index of a superclass of C private EWAHCompressedBitmap[] superclassBitmapIndex; private Map<OWLClass,EWAHCompressedBitmap> superclassBitmapMap; // given an individual, return superclasses as a bit map private Map<OWLNamedIndividual, EWAHCompressedBitmap> inferredTypesBitmapMap; // cache of Type(i)->BM Map<OWLClass,EWAHCompressedBitmap> properSuperclassBitmapMap; // CLASS INDICES // Each class is assigned a numeric index. // We can collapse sets of equivalent classes into a node, which // has an arbitrarily assigned representative element. // note that the following are for *all* classes in the ontology. // E.g. may include anatomy classes in a phenotype analysis. // to limit memory usage, first filter ontology to classes with members // (being sure to retain inferred axioms). // in practice this may not be necessary, as 2D arrays are only used // for classes with members. // maps a set of equivalent classes to a representative Map<Node<OWLClass>, OWLClass> representativeClassMap; // maps a class to a representative for that class (typically itself) Map<OWLClass, OWLClass> classTorepresentativeClassMap; // maps a class to a unique integer Map<OWLClass,Integer> classIndex; // maps a class index to a class OWLClass[] classArray; // all types used directly. // same as elementToDirectAttributesMap.values() private Set<OWLClass> allTypesDirect = null; // all Types used in Type(e) for all e in E. // note this excludes classes with no (inferred) members // same as elementToInferredAttributesMap.values() private Set<OWLClass> allTypesInferred = null; // cache of information content, by class private Map<OWLClass, Double> icCache = new HashMap<OWLClass,Double>(); private Map<OWLClass, Integer> numElementsCache = new HashMap<OWLClass,Integer>(); // cache of information content, by class index Double[] icClassArray = null; // private Map<ClassIntPair, Set<Integer>> classPairLCSMap; // private Map<ClassIntPair, ScoreAttributeSetPair> classPairICLCSMap; // used for storing IC values as integers final int scaleFactor = 1000; //short[][] ciPairScaledScore; ScoreAttributeSetPair[][] testCache = null; boolean[][] ciPairIsCached = null; int[][] ciPairLCS = null; // maps an individual to a unique integer Map<OWLNamedIndividual,Integer> individualIndex; @Override public void dispose() { showTimings(); } // represents a pair of classes using their indices // NOTE; replaced by arrays @Deprecated private class ClassIntPair { int c; int d; public ClassIntPair(int c, int d) { super(); this.c = c; this.d = d; } @Override public int hashCode() { final int prime = 991; int result = 1; result = prime * result + c; result = prime * result + d; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ClassIntPair other = (ClassIntPair) obj; return c == other.c && d == other.d; } } /** * @param sourceOntology */ public FastOwlSim(OWLOntology sourceOntology) { reasoner = new ElkReasonerFactory().createReasoner(sourceOntology); } /** * @param reasoner */ public FastOwlSim(OWLReasoner reasoner) { this.reasoner = reasoner; } @Override public Set<OWLClass> getAllAttributeClasses() { return allTypesInferred; // note - only attributes used directly or indirectly } private int getClassIndex(OWLClass c) throws UnknownOWLClassException { Integer ix = classIndex.get(c); if (ix == null) { throw new UnknownOWLClassException(c); } return ix; } private int getClassIndex(Node<OWLClass> n) throws UnknownOWLClassException { OWLClass c = getDeterministicRepresentative(n); return getClassIndex(c); } private <T extends OWLNamedObject> T getDeterministicRepresentative(Node<T> n) { T rep = null; // find lexical maximal entry as representative node for (T entry : n) { if (rep == null) { rep = entry; } else { // use IRI for comparison IRI repIRI = rep.getIRI(); IRI entryIRI = entry.getIRI(); if (entryIRI.compareTo(repIRI) > 0) { rep = entry; } } } return rep; } // not yet implemented: guaranteed to yield and indexed class private OWLClass getIndexedClass(Node<OWLClass> n) throws UnknownOWLClassException { if (representativeClassMap == null) representativeClassMap = new HashMap<Node<OWLClass>, OWLClass>(); else if (representativeClassMap.containsKey(n)) return representativeClassMap.get(n); for (OWLClass c : n.getEntities()) { if (classIndex.containsKey(c)) { representativeClassMap.put(n,c); return c; } } throw new UnknownOWLClassException(getDeterministicRepresentative(n)); } /* (non-Javadoc) * @see owltools.sim2.OwlSim#createElementAttributeMapFromOntology() */ @Override public void createElementAttributeMapFromOntology() throws UnknownOWLClassException { getReasoner().flush(); // cache E -> Type(E) elementToDirectAttributesMap = new HashMap<OWLNamedIndividual,Set<OWLClass>>(); elementToInferredAttributesMap = new HashMap<OWLNamedIndividual,Set<Node<OWLClass>>>(); allTypesDirect = new HashSet<OWLClass>(); allTypesInferred = new HashSet<OWLClass>(); Set<OWLNamedIndividual> inds = getSourceOntology().getIndividualsInSignature(true); for (OWLNamedIndividual e : inds) { // The attribute classes for an individual are the direct inferred // named types. We assume that grouping classes have already been // generated. NodeSet<OWLClass> nodesetDirect = getReasoner().getTypes(e, true); NodeSet<OWLClass> nodesetInferred = getReasoner().getTypes(e, false); allTypesDirect.addAll(nodesetDirect.getFlattened()); allTypesInferred.addAll(nodesetInferred.getFlattened()); elementToDirectAttributesMap.put(e, nodesetDirect.getFlattened()); elementToInferredAttributesMap.put(e, nodesetInferred.getNodes()); // TODO - remove deprecated classes elementToDirectAttributesMap.get(e).remove(owlThing()); elementToInferredAttributesMap.get(e).remove(owlThing()); } LOG.info("|TypesUsedDirectly|="+allTypesDirect.size()); LOG.info("|TypesUsedInferred|="+allTypesInferred.size()); Set<OWLClass> cset; //cset = getSourceOntology().getClassesInSignature(true); cset = allTypesInferred; LOG.info("|C|="+cset.size()); LOG.info("|I|="+inds.size()); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (OWLClass c : cset) { nodes.add(getReasoner().getEquivalentClasses(c)); } LOG.info("|N|="+nodes.size()); // TODO - use thisg // classes are collapsed into nodes. Create a map from node to // class, and a map of every class // to the representative element from its node representativeClassMap = new HashMap<Node<OWLClass>, OWLClass>(); classTorepresentativeClassMap = new HashMap<OWLClass, OWLClass>(); for (Node<OWLClass> n : nodes) { OWLClass c = getDeterministicRepresentative(n); representativeClassMap.put(n, c); for (OWLClass c2 : n.getEntities()) { classTorepresentativeClassMap.put(c2, c); } } // Create a bidirectional index, class by number int n=0; classArray = (OWLClass[]) Array.newInstance(OWLClass.class, cset.size()+1); classIndex = new HashMap<OWLClass,Integer>(); // 0th element is always owlThing (root) classArray[n] = owlThing(); classIndex.put(owlThing(), n); n++; // TODO - investigate if ordering elements makes a difference; // e.g. if more frequent classes recieve lower bit indices this // may speed certain BitMap operations? for (OWLClass c : cset) { if (c.equals(owlThing())) continue; classArray[n] = c; classIndex.put(c, n); n++; } // ensure cached cset.add(owlThing()); for (OWLClass c : cset) { ancsCachedModifiable(c); ancsIntsCachedModifiable(c); ancsBitmapCachedModifiable(c); } for (OWLNamedIndividual e : inds) { // force cacheing ancsBitmapCachedModifiable(e); } // cache - this is for ALL classes in signature for (OWLClass c : cset) { getInformationContentForAttribute(c); getInformationContentForAttribute(classIndex.get(c)); } this.computeSystemStats(); } // TODO - change set to be (ordered) List, to avoid sorting each time private EWAHCompressedBitmap convertIntsToBitmap(Set<Integer> bits) { EWAHCompressedBitmap bm = new EWAHCompressedBitmap(); ArrayList<Integer> bitlist = new ArrayList<Integer>(bits); // necessary for EWAH API, otherwise silently fails Collections.sort(bitlist); for (Integer i : bitlist) { bm.set(i.intValue()); } return bm; } // cached proper superclasses (i.e. excludes equivalent classes) as BitMap private EWAHCompressedBitmap ancsProperBitmapCachedModifiable(OWLClass c) { if (properSuperclassBitmapMap != null && properSuperclassBitmapMap.containsKey(c)) { return properSuperclassBitmapMap.get(c); } Set<Integer> ancsInts = new HashSet<Integer>(); for (Node<OWLClass> anc : reasoner.getSuperClasses(c, false)) { // TODO - verify robust for non-Rep elements OWLClass ac = getDeterministicRepresentative(anc); if (ac.equals(thing)) continue; ancsInts.add(classIndex.get(ac)); } EWAHCompressedBitmap bm = convertIntsToBitmap(ancsInts); if (properSuperclassBitmapMap == null) properSuperclassBitmapMap = new HashMap<OWLClass,EWAHCompressedBitmap>(); properSuperclassBitmapMap.put(c, bm); return bm; } private EWAHCompressedBitmap ancsBitmapCachedModifiable(OWLClass c) throws UnknownOWLClassException { if (superclassBitmapMap != null && superclassBitmapMap.containsKey(c)) { return superclassBitmapMap.get(c); } Set<Integer> caints = ancsIntsCachedModifiable(c); EWAHCompressedBitmap bm = convertIntsToBitmap(caints); if (superclassBitmapMap == null) superclassBitmapMap = new HashMap<OWLClass,EWAHCompressedBitmap>(); superclassBitmapMap.put(c, bm); return bm; } private EWAHCompressedBitmap ancsBitmapCachedModifiable(int cix) throws UnknownOWLClassException { if (superclassBitmapIndex != null && superclassBitmapIndex[cix] != null) { return superclassBitmapIndex[cix]; } Set<Integer> caints = ancsIntsCachedModifiable(classArray[cix]); EWAHCompressedBitmap bm = convertIntsToBitmap(caints); if (superclassBitmapIndex == null) superclassBitmapIndex = new EWAHCompressedBitmap[classArray.length]; superclassBitmapIndex[cix] = bm; return bm; } private EWAHCompressedBitmap ancsBitmapCachedModifiable(OWLNamedIndividual i) throws UnknownOWLClassException { if (inferredTypesBitmapMap != null && inferredTypesBitmapMap.containsKey(i)) { return inferredTypesBitmapMap.get(i); } Set<Integer> caints = ancsIntsCachedModifiable(i); EWAHCompressedBitmap bm = convertIntsToBitmap(caints); if (inferredTypesBitmapMap == null) inferredTypesBitmapMap = new HashMap<OWLNamedIndividual,EWAHCompressedBitmap>(); inferredTypesBitmapMap.put(i, bm); return bm; } private EWAHCompressedBitmap ancsBitmapCached(Set<OWLClass> cset) throws UnknownOWLClassException { Set<Integer> csetInts = new HashSet<Integer>(); for (OWLClass c : cset) { csetInts.add(classIndex.get(c)); } return convertIntsToBitmap(csetInts); } private Set<Integer> ancsIntsCachedModifiable(OWLClass c) throws UnknownOWLClassException { if (superclassIntMap != null && superclassIntMap.containsKey(c)) { return superclassIntMap.get(c); } Set<Integer> a = ancsInts(c); if (superclassIntMap == null) superclassIntMap = new HashMap<OWLClass,Set<Integer>>(); superclassIntMap.put(c, a); return a; } // TODO - make this an ordered list, for faster bitmaps private Set<Integer> ancsIntsCachedModifiable(OWLNamedIndividual i) throws UnknownOWLClassException { if (inferredTypesIntMap != null && inferredTypesIntMap.containsKey(i)) { return inferredTypesIntMap.get(i); } Set<Integer> a = ancsInts(i); if (inferredTypesIntMap == null) inferredTypesIntMap = new HashMap<OWLNamedIndividual,Set<Integer>>(); inferredTypesIntMap.put(i, a); return a; } // all ancestors as IntSet // note that for equivalence sets, the representative element is returned private Set<Integer> ancsInts(OWLClass c) throws UnknownOWLClassException { Set<Node<OWLClass>> ancs = ancsCachedModifiable(c); Set<Integer> ancsInts = new HashSet<Integer>(); OWLClass thing = owlThing(); for (Node<OWLClass> anc : ancs) { // TODO - verify robust for non-Rep elements OWLClass ac = getDeterministicRepresentative(anc); if (ac.equals(thing)) continue; Integer ix = classIndex.get(ac); if (ix == null) { throw new UnknownOWLClassException(ac); } ancsInts.add(ix.intValue()); } return ancsInts; } private Set<Integer> ancsInts(OWLNamedIndividual i) throws UnknownOWLClassException { Set<Node<OWLClass>> ancs = ancsCachedModifiable(i); Set<Integer> ancsInts = new HashSet<Integer>(); OWLClass thing = owlThing(); for (Node<OWLClass> anc : ancs) { // TODO - verify robust for non-Rep elements OWLClass ac = getDeterministicRepresentative(anc); if (ac.equals(thing)) continue; Integer ix = classIndex.get(ac); if (ix == null) { throw new UnknownOWLClassException(ac); } ancsInts.add(ix.intValue()); } return ancsInts; } private Set<Node<OWLClass>> ancsCachedModifiable(OWLClass c) { if (superclassMap != null && superclassMap.containsKey(c)) { return superclassMap.get(c); } Set<Node<OWLClass>> a = ancs(c); if (superclassMap == null) superclassMap = new HashMap<OWLClass,Set<Node<OWLClass>>>(); superclassMap.put(c, a); return a; } private Set<Node<OWLClass>> ancsCachedModifiable(OWLNamedIndividual i) { if (inferredTypesMap != null && inferredTypesMap.containsKey(i)) { return inferredTypesMap.get(i); } Set<Node<OWLClass>> a = ancs(i); if (inferredTypesMap == null) inferredTypesMap = new HashMap<OWLNamedIndividual,Set<Node<OWLClass>>>(); inferredTypesMap.put(i, a); return a; } private Set<Node<OWLClass>> ancs(OWLClass c) { NodeSet<OWLClass> ancs = getReasoner().getSuperClasses(c, false); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(ancs.getNodes()); nodes.add(getReasoner().getEquivalentClasses(c)); nodes.remove(owlThingNode()); return nodes; } private Set<Node<OWLClass>> ancs(OWLNamedIndividual i) { Set<Node<OWLClass>> nodes = getReasoner().getTypes(i, false).getNodes(); nodes.remove(owlThingNode()); return nodes; } @Override public Set<OWLClass> getAttributesForElement(OWLNamedIndividual e) throws UnknownOWLClassException { if (elementToDirectAttributesMap == null) createElementAttributeMapFromOntology(); return new HashSet<OWLClass>(elementToDirectAttributesMap.get(e)); } @Override public Set<OWLNamedIndividual> getElementsForAttribute(OWLClass c) throws UnknownOWLClassException { if (!this.getAllAttributeClasses().contains(c)) { throw new UnknownOWLClassException(c); } return getReasoner().getInstances(c, false).getFlattened(); } @Override public int getNumSharedElements(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap cebm = getElementsForAttributeAsBitmao(c); EWAHCompressedBitmap debm = getElementsForAttributeAsBitmao(d); return cebm.andCardinality(debm); } Map<OWLClass,EWAHCompressedBitmap> classToElementBitmapMap; private EWAHCompressedBitmap getElementsForAttributeAsBitmao(OWLClass c) throws UnknownOWLClassException { if (classToElementBitmapMap == null) classToElementBitmapMap = new HashMap<OWLClass,EWAHCompressedBitmap>(); if (classToElementBitmapMap.containsKey(c)) { return classToElementBitmapMap.get(c); } Set<OWLNamedIndividual> inds = getElementsForAttribute(c); Set<Integer> indInts = new HashSet<Integer>(); makeIndividualIndex(); for (OWLNamedIndividual i : inds) { indInts.add(individualIndex.get(i)); } EWAHCompressedBitmap bm = convertIntsToBitmap(indInts); classToElementBitmapMap.put(c, bm); return bm; } private void makeIndividualIndex() { if (individualIndex == null) { individualIndex = new HashMap<OWLNamedIndividual, Integer>(); int n=0; for (OWLNamedIndividual i : this.getAllElements()) { individualIndex.put(i, n); n++; } } } @Override public int getNumElementsForAttribute(OWLClass c) { if (numElementsCache == null) numElementsCache = new HashMap<OWLClass, Integer>(); if (numElementsCache.containsKey(c)) { return numElementsCache.get(c); } int num = 0; try { num = this.getElementsForAttribute(c).size(); } catch (UnknownOWLClassException e) { //return 0; } numElementsCache.put(c, num); return num; } @Override public Set<OWLNamedIndividual> getAllElements() { // Note: will only return elements that have >=1 attributes return elementToDirectAttributesMap.keySet(); } @Override public Double getInformationContentForAttribute(OWLClass c) throws UnknownOWLClassException { if (icCache.containsKey(c)) return icCache.get(c); int freq = getNumElementsForAttribute(c); Double ic = null ; if (freq > 0) { ic = -Math.log(((double) (freq) / getCorpusSize())) / Math.log(2); // experimental: use depth in graph as tie-breaker. // where SF is large enough to make overall increase negligible int numAncs = ancsBitmapCachedModifiable(c).cardinality(); double bump = numAncs / (double) scaleFactor; if (bump > 0.2) { LOG.warn("Bump = "+bump+" for "+c); } ic += bump; } icCache.put(c, ic); return ic; } // gets IC by class index, cacheing if required Double getInformationContentForAttribute(int cix) throws UnknownOWLClassException { // check if present in cache; if so, use cached value if (icClassArray != null && icClassArray[cix] != null) { return icClassArray[cix]; } // not cached - retrieve IC using the class OWLClass c = classArray[cix]; Double ic = getInformationContentForAttribute(c); if (debugClass != null && c.equals(debugClass)) { LOG.info("DEBUG "+c+" IX:"+cix+" IC= "+ic); } // place results in cache, creating a new cache if none exists if (icClassArray == null) { icClassArray = new Double[classArray.length]; } icClassArray[cix] = ic; return ic; } @Override public Set<Node<OWLClass>> getInferredAttributes(OWLNamedIndividual a) { return new HashSet<Node<OWLClass>>(elementToInferredAttributesMap.get(a)); } @Override public Set<Node<OWLClass>> getNamedReflexiveSubsumers(OWLClass a) { return ancs(a); } @Override public Set<Node<OWLClass>> getNamedCommonSubsumers(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); EWAHCompressedBitmap cad = bmc.and(bmd); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } private Set<Node<OWLClass>> getNamedCommonSubsumers(int cix, int dix) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(cix); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(dix); EWAHCompressedBitmap cad = bmc.and(bmd); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } private EWAHCompressedBitmap getNamedCommonSubsumersAsBitmap(int cix, int dix) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(cix); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(dix); EWAHCompressedBitmap cad = bmc.and(bmd); return cad; } //@Override public Set<Node<OWLClass>> getNamedUnionSubsumers(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); EWAHCompressedBitmap cud = bmc.or(bmd); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (int ix : cud.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } @Override public int getNamedCommonSubsumersCount(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); return bmc.andCardinality(bmd); } @Override public Set<Node<OWLClass>> getNamedCommonSubsumers(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); EWAHCompressedBitmap cad = bmc.and(bmd); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } private Set<Node<OWLClass>> getNamedUnionSubsumers(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); EWAHCompressedBitmap cad = bmc.or(bmd); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } @Override public Set<Node<OWLClass>> getNamedLowestCommonSubsumers(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap cad = getNamedLowestCommonSubsumersAsBitmap(c, d); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); // TODO - optimize this & ensure all elements of an equivalence set are included for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } private Set<Node<OWLClass>> getNamedLowestCommonSubsumers(int cix, int dix) throws UnknownOWLClassException { EWAHCompressedBitmap cad = getNamedLowestCommonSubsumersAsBitmap(cix, dix); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); // TODO - optimize this & ensure all elements of an equivalence set are included for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } return nodes; } // fast bitmap implementation of LCS private EWAHCompressedBitmap getNamedLowestCommonSubsumersAsBitmap(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); EWAHCompressedBitmap cad = bmc.and(bmd); int[] csInts = cad.toArray(); for (int ix : csInts) { cad = cad.andNot(ancsProperBitmapCachedModifiable(classArray[ix])); } return cad; } private EWAHCompressedBitmap getNamedLowestCommonSubsumersAsBitmap(int cix, int dix) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(cix); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(dix); EWAHCompressedBitmap cad = bmc.and(bmd); int[] csInts = cad.toArray(); for (int ix : csInts) { cad = cad.andNot(ancsProperBitmapCachedModifiable(classArray[ix])); } return cad; } @Deprecated private Set<Node<OWLClass>> getNamedLowestCommonSubsumersNaive(OWLClass a, OWLClass b) throws UnknownOWLClassException { // currently no need to cache this, as only called from // getLowestCommonSubsumerIC, which does its own caching Set<Node<OWLClass>> commonSubsumerNodes = getNamedCommonSubsumers(a, b); Set<Node<OWLClass>> rNodes = new HashSet<Node<OWLClass>>(); // remove redundant for (Node<OWLClass> node : commonSubsumerNodes) { rNodes.addAll(getReasoner().getSuperClasses( getDeterministicRepresentative(node), false).getNodes()); } commonSubsumerNodes.removeAll(rNodes); return commonSubsumerNodes; } @Override public double getAttributeSimilarity(OWLClass c, OWLClass d, Metric metric) throws UnknownOWLClassException { if (metric.equals(Metric.JACCARD)) { return getAttributeJaccardSimilarity(c, d); } else if (metric.equals(Metric.OVERLAP)) { return getNamedCommonSubsumers(c, d).size(); } else if (metric.equals(Metric.NORMALIZED_OVERLAP)) { return getNamedCommonSubsumers(c, d).size() / Math.min(getNamedReflexiveSubsumers(c).size(), getNamedReflexiveSubsumers(d).size()); } else if (metric.equals(Metric.DICE)) { // TODO return -1; } else { return 0; } } @Override public AttributePairScores getPairwiseSimilarity(OWLClass c, OWLClass d) throws UnknownOWLClassException { AttributePairScores s = new AttributePairScores(c,d); EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); s.simjScore = bmc.andCardinality(bmd) / (double) bmc.orCardinality(bmd); s.asymmetricSimjScore = bmc.andCardinality(bmd) / (double) bmd.cardinality(); s.inverseAsymmetricSimjScore = bmc.andCardinality(bmd) / (double) bmc.cardinality(); ScoreAttributeSetPair sap = getLowestCommonSubsumerWithIC(c, d); s.lcsIC = sap.score; s.lcsSet = sap.attributeClassSet; return s; } @Override public double getAttributeJaccardSimilarity(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); return bmc.andCardinality(bmd) / (double) bmc.orCardinality(bmd); } @Override public int getAttributeJaccardSimilarityAsPercent(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); return (bmc.andCardinality(bmd) * 100) / bmc.orCardinality(bmd); } @Override public double getElementJaccardSimilarity(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); return bmc.andCardinality(bmd) / (double) bmc.orCardinality(bmd); } @Override public int getElementJaccardSimilarityAsPercent(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); return (bmc.andCardinality(bmd) * 100) / bmc.orCardinality(bmd); } @Override public double getAsymmetricAttributeJaccardSimilarity(OWLClass c, OWLClass d) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(c); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(d); return bmc.andCardinality(bmd) / (double) bmd.cardinality(); } //@Override public double getAsymmetricElementJaccardSimilarity(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); return bmc.andCardinality(bmd) / (double) bmd.cardinality(); } //@Override public int getAsymmetricElementJaccardSimilarityAsPercent(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); return (bmc.andCardinality(bmd) * 100) / bmd.cardinality(); } // SimGIC // TODO - optimize @Override public double getElementGraphInformationContentSimilarity( OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { // TODO - optimize long t = System.currentTimeMillis(); EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); EWAHCompressedBitmap cad = bmc.and(bmd); EWAHCompressedBitmap cud = bmc.or(bmd); //Set<Node<OWLClass>> ci = getNamedCommonSubsumers(i, j); //Set<Node<OWLClass>> cu = getNamedUnionSubsumers(i, j); double sumICboth = 0; double sumICunion = 0; // faster than translating to integer list IntIterator it = cud.intIterator(); while (it.hasNext()) { int x = it.next(); double ic = getInformationContentForAttribute(x); // TODO - we can avoid doing this twice by using xor in the bitmap sumICunion += ic; if (cad.get(x)) { sumICboth += ic; } } totalTimeGIC += tdelta(t); this.totalCallsGIC++; return sumICboth / sumICunion; } // TODO - optimize @Override public double getAttributeGraphInformationContentSimilarity( OWLClass c, OWLClass d) throws UnknownOWLClassException { return getAttributeGraphInformationContentSimilarity(classIndex.get(c), classIndex.get(d)); } private double getAttributeGraphInformationContentSimilarity( int cix, int dix) throws UnknownOWLClassException { long t = System.currentTimeMillis(); EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(cix); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(dix); EWAHCompressedBitmap cad = bmc.and(bmd); EWAHCompressedBitmap cud = bmc.or(bmd); double sumICboth = 0; double sumICunion = 0; // faster than translating to integer list IntIterator it = cud.intIterator(); while (it.hasNext()) { int x = it.next(); double ic = getInformationContentForAttribute(x); // TODO - we can avoid doing this twice by using xor in the bitmap sumICunion += ic; if (cad.get(x)) { sumICboth += ic; } } totalTimeGIC += tdelta(t); this.totalCallsGIC++; return sumICboth / sumICunion; } //@Override public double getAsymmetricElementGraphInformationContentSimilarity( OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { // TODO - optimize Set<Node<OWLClass>> ci = getNamedCommonSubsumers(i, j); Set<Node<OWLClass>> cu = this.getInferredAttributes(j); double sumICboth = 0; double sumICunion = 0; for (Node<OWLClass> c : cu) { // TODO - we can avoid doing this twice by using xor in the bitmap OWLClass rep = getDeterministicRepresentative(c); sumICunion += getInformationContentForAttribute(rep); if (ci.contains(c)) { sumICboth += getInformationContentForAttribute(rep); } } return sumICboth / sumICunion; } // NOTE: current implementation will also return redundant classes if // they rank the same - use groupwise if true maxIC required @Override public ScoreAttributeSetPair getSimilarityMaxIC(OWLNamedIndividual i, OWLNamedIndividual j) throws UnknownOWLClassException { Set<Node<OWLClass>> atts = getNamedCommonSubsumers(i,j); ScoreAttributeSetPair best = new ScoreAttributeSetPair(0.0); for (Node<OWLClass> n : atts) { OWLClass c = getDeterministicRepresentative(n); Double ic = getInformationContentForAttribute(c); if (Math.abs(ic - best.score) < 0.000001) { // tie for best attribute best.addAttributeClass(c); } if (ic > best.score) { best = new ScoreAttributeSetPair(ic, c); } } return best; } @Override public ScoreAttributeSetPair getSimilarityBestMatchAverageAsym( OWLNamedIndividual i, OWLNamedIndividual j) { // TODO Auto-generated method stub return null; } @Override public ScoreAttributeSetPair getSimilarityBestMatchAverageAsym( OWLNamedIndividual i, OWLNamedIndividual j, Metric metric) { // TODO Auto-generated method stub return null; } @Override public ScoreAttributeSetPair getSimilarityBestMatchAverage( OWLNamedIndividual i, OWLNamedIndividual j, Metric metric, Direction dir) { // TODO Auto-generated method stub return null; } protected void populateSimilarityMatrix( OWLNamedIndividual i, OWLNamedIndividual j, ElementPairScores ijscores) throws UnknownOWLClassException, NoElementAttributeMapException { /* EWAHCompressedBitmap bmc = ancsBitmapCachedModifiable(i); EWAHCompressedBitmap bmd = ancsBitmapCachedModifiable(j); EWAHCompressedBitmap cad = bmc.and(bmd); EWAHCompressedBitmap cud = bmc.or(bmd); Set<Node<OWLClass>> nodes = new HashSet<Node<OWLClass>>(); for (int ix : cad.toArray()) { OWLClassNode node = new OWLClassNode(classArray[ix]); nodes.add(node); } */ /* ijscores.simGIC = getElementGraphInformationContentSimilarity(i, j); ijscores.asymmetricSimGIC = getAsymmetricElementGraphInformationContentSimilarity(i, j); ijscores.inverseAsymmetricSimGIC = getAsymmetricElementGraphInformationContentSimilarity(j, i); */ ijscores.simjScore = getElementJaccardSimilarity(i, j); if (ijscores.simjScore == null || ijscores.simjScore.isNaN()) { //the elementattributemap probably hasn't been populated. //log an error and exit. throw new NoElementAttributeMapException(); } ijscores.asymmetricSimjScore = getAsymmetricElementJaccardSimilarity(i, j); ijscores.inverseAsymmetricSimjScore = getAsymmetricElementJaccardSimilarity(j, i); Vector<OWLClass> cs = new Vector<OWLClass>(getAttributesForElement(i)); Vector<OWLClass> ds = new Vector<OWLClass>(getAttributesForElement(j)); populateSimilarityMatrix(cs, ds, ijscores); } private void populateSimilarityMatrix(Vector<OWLClass> cs, Vector<OWLClass> ds, ElementPairScores ijscores) throws UnknownOWLClassException { ScoreAttributeSetPair bestsap = null; int csize = cs.size(); int dsize = ds.size(); ijscores.cs = cs; ijscores.ds = ds; double total = 0.0; double[][] scoreMatrix = new double[csize][dsize]; ScoreAttributeSetPair[][] sapMatrix = new ScoreAttributeSetPair[csize][dsize]; ScoreAttributeSetPair[] bestSapForC = new ScoreAttributeSetPair[csize]; ScoreAttributeSetPair[] bestSapForD = new ScoreAttributeSetPair[dsize]; double bestMatchCTotal = 0; double bestMatchDTotal = 0; // populate matrix for (int cx=0; cx<csize; cx++) { OWLClass c = cs.elementAt(cx); int cix = classIndex.get(c); ScoreAttributeSetPair bestcsap = null; for (int dx=0; dx<dsize; dx++) { OWLClass d = ds.elementAt(dx); int dix = classIndex.get(d); ScoreAttributeSetPair sap = getLowestCommonSubsumerWithIC(cix,dix); if (sap == null) continue; sapMatrix[cx][dx] = sap; double score = sap.score; total += score; if (bestsap == null || score >= bestsap.score) { bestsap = sap; } if (bestcsap == null || score >= bestcsap.score) { bestcsap = sap; } } bestSapForC[cx] = bestcsap; if (bestcsap != null) bestMatchCTotal += bestcsap.score; } // retrieve best values for each D for (int dx=0; dx<dsize; dx++) { ScoreAttributeSetPair bestdsap = null; for (int cx=0; cx<csize; cx++) { ScoreAttributeSetPair sap = sapMatrix[cx][dx]; if (sap != null && (bestdsap == null || sap.score >= bestdsap.score)) { bestdsap = sap; } } if (bestdsap != null) { bestSapForD[dx] = bestdsap; bestMatchDTotal += bestdsap.score; } } // TODO - use these ijscores.avgIC = total / (csize * dsize); ijscores.bmaAsymIC = bestMatchCTotal / (double)csize; ijscores.bmaInverseAsymIC = bestMatchDTotal / (double)dsize; ijscores.bmaSymIC = (bestMatchCTotal + bestMatchDTotal) / (double)(csize+dsize); ijscores.iclcsMatrix = new ScoreMatrix<ScoreAttributeSetPair>(); ijscores.iclcsMatrix.matrix = sapMatrix; ijscores.iclcsMatrix.bestForC = bestSapForC; ijscores.iclcsMatrix.bestForD = bestSapForD; if (bestsap != null) { ijscores.maxIC = bestsap.score; ijscores.maxICwitness = bestsap.attributeClassSet; } else { //LOG.warn("No best S.A.P. for "+ijscores); ijscores.maxIC = 0.0; ijscores.maxICwitness = null; } } // uses integer 2D array cache private ScoreAttributeSetPair getLowestCommonSubsumerWithIC(int cix, int dix) throws UnknownOWLClassException { return getLowestCommonSubsumerWithIC(cix, dix, null); } private ScoreAttributeSetPair getLowestCommonSubsumerWithIC(int cix, int dix, Double thresh) throws UnknownOWLClassException { // if cache is disabled altogether, head straight for the implementation if (isDisableLCSCache) { return getLowestCommonSubsumerWithICNoCache(cix, dix); } // if the cache does not exist, initialize it if (ciPairIsCached == null) { // Estimates: 350mb for MP // 5.4Gb for 30k classes //int size = this.getAllAttributeClasses().size(); int size = classArray.length; LOG.info("Creating 2D cache of "+size+" * "+size); ciPairIsCached = new boolean[size][size]; ciPairLCS = new int[size][size]; LOG.info("Created LCS cache"+size+" * "+size); //ciPairScaledScore = new short[size][size]; //LOG.info("Created score cache cache"+size+" * "+size); } // if either (1) an entry exists in the cache or (2) we are // building the cache from fresh, then do a lookup if (!isNoLookupForLCSCache && ciPairIsCached[cix][dix]) { // TODO null vs 0 int lcsix = ciPairLCS[cix][dix]; return new ScoreAttributeSetPair(icClassArray[lcsix], classArray[lcsix]); } if (!isNoLookupForLCSCache && isLCSCacheFullyPopulated) { // true if a pre-generated cache has been loaded and there is no entry for this pair; // a cache excludes certain pairs if they are below threshold (see below) return null; } // use base method and cache results. // if score is below threshold, then nothing is returned or cached. // This reduces the size of the cache. ScoreAttributeSetPair sap = getLowestCommonSubsumerWithICNoCache(cix, dix); if (debugClass != null && sap.attributeClassSet != null && debugClassMessages < 100 && sap.attributeClassSet.contains(debugClass)) { LOG.info("DEBUG1 "+debugClass+" ix="+ classIndex.get(debugClass)+" "+sap.score); debugClassMessages++; } if (thresh != null && sap.score < thresh) { return null; } ciPairIsCached[cix][dix] = true; OWLClass lcsCls = null; if (sap.attributeClassSet != null && !sap.attributeClassSet.isEmpty()) { // we take an arbitrary member lcsCls = sap.attributeClassSet.iterator().next(); int lcsix = classIndex.get(lcsCls); ciPairLCS[cix][dix] = lcsix; if (debugClass != null && lcsCls.equals(debugClass) && debugClassMessages2 < 100) { LOG.info("DEBUG2 "+lcsix+" " +sap.attributeClassSet+" sap.score="+sap.score); debugClassMessages2++; } //icClassArray[lcsix] = sap.score; } else { //TODO - remove obsoletes LOG.warn("uh oh"+classArray[cix] + " "+ classArray[dix]+" "+sap.attributeClassSet); } return sap; } @Override public ScoreAttributeSetPair getLowestCommonSubsumerWithIC(OWLClass c, OWLClass d) throws UnknownOWLClassException { return getLowestCommonSubsumerWithIC(classIndex.get(c), classIndex.get(d)); } @Override public ScoreAttributeSetPair getLowestCommonSubsumerWithIC(OWLClass c, OWLClass d, Double thresh) throws UnknownOWLClassException { return getLowestCommonSubsumerWithIC(classIndex.get(c), classIndex.get(d), thresh); } private ScoreAttributeSetPair getLowestCommonSubsumerWithICNoCache(int cix, int dix) throws UnknownOWLClassException { long t = System.currentTimeMillis(); EWAHCompressedBitmap cad = getNamedLowestCommonSubsumersAsBitmap(cix, dix); Set<OWLClass> lcsClasses = new HashSet<OWLClass>(); double maxScore = 0.0; for (int ix : cad.toArray()) { double score = getInformationContentForAttribute(ix); double sdiff = score - maxScore; if (sdiff >= 0) { if (sdiff > 0.01) { lcsClasses= new HashSet<OWLClass>(Collections.singleton(classArray[ix])); maxScore = score; } else { lcsClasses.add(classArray[ix]); maxScore = score; } } // if (score == maxScore) { // lcsClasses.add(classArray[ix]); // maxScore = score; // else if (score >= maxScore) { // lcsClasses= new HashSet<OWLClass>(Collections.singleton(classArray[ix])); // maxScore = score; } if (lcsClasses.size() == 0) { // TODO - remove obsoletes //LOG.warn("Hmmmm "+c+" "+d+" "+lcs); } totalTimeLCSIC += tdelta(t); this.totalCallsLCSIC++; return new ScoreAttributeSetPair(maxScore, lcsClasses); } public List<ElementPairScores> findMatches(Set<OWLClass> atts, String targetIdSpace) throws Exception { double minSimJPct = getPropertyAsDouble(SimConfigurationProperty.minimumSimJ, 0.05) * 100; double minMaxIC = getPropertyAsDouble(SimConfigurationProperty.minimumMaxIC, 2.5); return findMatches(atts, targetIdSpace, minSimJPct, minMaxIC); } public List<ElementPairScores> findMatches(Set<OWLClass> atts, String targetIdSpace, double minSimJPct, double minMaxIC) throws Exception { Set<OWLClass> csetFilteredDirect = new HashSet<OWLClass>(); // direct Set<OWLClass> cset = new HashSet<OWLClass>(); // closure Set<OWLClass> redundant = new HashSet<OWLClass>(); // closure boolean isIgnoreUnknownClasses = false; List<ElementPairScores> scoreSets = new ArrayList<ElementPairScores>(); // FIND CLOSURE for (OWLClass c : atts) { if (!this.getAllAttributeClasses().contains(c)) { if (isIgnoreUnknownClasses) continue; throw new UnknownOWLClassException(c); } csetFilteredDirect.add(c); for (Node<OWLClass> n : getNamedReflexiveSubsumers(c)) { cset.add(getDeterministicRepresentative(n)); } for (Node<OWLClass> n :getNamedSubsumers(c)) { redundant.addAll(n.getEntities()); } } csetFilteredDirect.removeAll(redundant); Vector csetV = new Vector<OWLClass>(atts.size()); for (OWLClass c : csetFilteredDirect) { csetV.add(c); } // benchmarking long tSimJ = 0; int nSimJ = 0; long tMaxIC = 0; int nMaxIC = 0; long tSimGIC = 0; int nSimGIC = 0; long tBMA = 0; int nBMA = 0; long startTime = System.currentTimeMillis(); // for calculation of phenodigm score double maxMaxIC = 0.0; double maxBMA = 0.0; EWAHCompressedBitmap searchProfileBM = ancsBitmapCached(cset); for (OWLNamedIndividual j : getAllElements()) { // todo - provide other ways of filtering the set of candidates // for now we limit this to the ID space if (targetIdSpace != null && !j.getIRI().toString().contains("/"+targetIdSpace+"_")) { continue; } long t = System.currentTimeMillis(); //LOG.info(" Comparing with:"+j); // SIMJ EWAHCompressedBitmap jAttsBM = ancsBitmapCachedModifiable(j); int cadSize = searchProfileBM.andCardinality(jAttsBM); int cudSize = searchProfileBM.orCardinality(jAttsBM); int simJPct = (cadSize * 100) / cudSize; nSimJ++; tSimJ += tdelta(t); if (nSimJ % 1000 == 0) { LOG.info("tSimJ = "+tSimJ +" / "+nSimJ); LOG.info("tMaxIC = "+tMaxIC +" / "+nMaxIC); LOG.info("tSimGIC = "+tSimGIC +" / "+nSimGIC); LOG.info("tBMA = "+tBMA +" / "+nBMA); } if (simJPct < minSimJPct) { //LOG.info("simJ pct too low : "+simJPct+" = "+cadSize+" / "+cudSize); continue; } ElementPairScores s = new ElementPairScores(null, j); s.simjScore = simJPct / (double) 100; EWAHCompressedBitmap cad = searchProfileBM.and(jAttsBM); // COMMON SUBSUMERS (ALL) Set<OWLClass> csSet = new HashSet<OWLClass>(); for (int ix : cad.toArray()) { csSet.add(classArray[ix]); } // MAXIC // TODO - evaluate if this is optimal; // MaxIC falls out of BMA calculation, but it may be useful // to calculate here to test if more expensive AxA is required t = System.currentTimeMillis(); ScoreAttributeSetPair best = new ScoreAttributeSetPair(0.0); double icBest = 0; double icSumCAD = 0; for (int ix : cad.toArray()) { Double ic = getInformationContentForAttribute(ix); //OWLClass c = n.getRepresentativeElement(); if (ic > icBest) { icBest = ic; } icSumCAD += ic; } tMaxIC += tdelta(t); nMaxIC++; if (icBest > maxMaxIC) { maxMaxIC = icBest; } if (icBest < minMaxIC) { //LOG.info("maxIC too low : "+icBest); continue; } s.maxIC = icBest; //LOG.info("computing simGIC"); // SIMGIC t = System.currentTimeMillis(); EWAHCompressedBitmap cud = searchProfileBM.or(jAttsBM); double icSumCUD = 0; for (int ix : cud.toArray()) { Double ic = getInformationContentForAttribute(ix); icSumCUD += ic; } s.simGIC = icSumCAD / icSumCUD; tSimGIC += tdelta(t); nSimGIC++; // BEST MATCHES t = System.currentTimeMillis(); Vector dsetV = new Vector<OWLClass>(atts.size()); for (OWLClass d : this.getAttributesForElement(j)) { dsetV.add(d); } populateSimilarityMatrix(csetV, dsetV, s); if (s.bmaSymIC > maxBMA) { maxBMA = s.bmaAsymIC; } tBMA += tdelta(t); nBMA++; scoreSets.add(s); } // calculate combined/phenodigm score calculateCombinedScores(scoreSets, maxMaxIC, maxBMA); LOG.info("tSimJ = "+tSimJ +" / "+nSimJ); LOG.info("tSearch = "+tdelta(startTime) +" / "+nSimJ); LOG.info("Sorting "+scoreSets.size()+" matches"); Collections.sort(scoreSets); return scoreSets; } public List<ElementPairScores> findMatchesRefactored(Set<OWLClass> atts, String targetIdSpace) throws Exception { double minSimJPct = getPropertyAsDouble(SimConfigurationProperty.minimumSimJ, 0.05) * 100; double minMaxIC = getPropertyAsDouble(SimConfigurationProperty.minimumMaxIC, 2.5); return findMatchesRefactored(atts, targetIdSpace, minSimJPct, minMaxIC); } public List<ElementPairScores> findMatchesRefactored(Set<OWLClass> atts, String targetIdSpace, double minSimJPct, double minMaxIC) throws Exception { List<ElementPairScores> scoreSets = new ArrayList<ElementPairScores>(); // for calculation of phenodigm score double maxMaxIC = 0.0; double maxBMA = 0.0; for (OWLNamedIndividual j : getAllElements()) { if (targetIdSpace != null && !j.getIRI().toString().contains("/"+targetIdSpace+"_")) { continue; } try { ElementPairScores s = getGroupwiseSimilarity(atts, j, minSimJPct, minMaxIC); maxMaxIC = Math.max(maxMaxIC, s.maxIC); maxBMA = Math.max(maxBMA, s.bmaAsymIC); scoreSets.add(s); } catch (CutoffException e) { // e.printMessage(); continue; } } // calculate combined/phenodigm score calculateCombinedScores(scoreSets, maxMaxIC, maxBMA); LOG.info("Sorting "+scoreSets.size()+" matches"); Collections.sort(scoreSets); return scoreSets; } private double computeSimJwithBM(EWAHCompressedBitmap iAttsBM, EWAHCompressedBitmap jAttsBM) { int cadSize = iAttsBM.andCardinality(jAttsBM); int cudSize = iAttsBM.orCardinality(jAttsBM); double simJPct = (cadSize * 100) / cudSize; return simJPct; } private ElementPairScores computeMatchWithBM(EWAHCompressedBitmap iAttsBM, EWAHCompressedBitmap jAttsBM, double minSimJPct, double minMaxIC) throws CutoffException, UnknownOWLClassException { ElementPairScores s = new ElementPairScores(null, null); // benchmarking long tSimJ = 0; int nSimJ = 0; long tMaxIC = 0; int nMaxIC = 0; long tSimGIC = 0; int nSimGIC = 0; long tBMA = 0; int nBMA = 0; // long startTime = System.currentTimeMillis(); long t = System.currentTimeMillis(); // SIMJ double simJPct = computeSimJwithBM(iAttsBM, jAttsBM); if (simJPct < minSimJPct) { throw new CutoffException("minSimJPct",minSimJPct,simJPct); } s.simjScore = simJPct / (double) 100; //benchmarking nSimJ++; tSimJ += tdelta(t); if (nSimJ % 100 == 0) { LOG.info("tSimJ = "+tSimJ +" / "+nSimJ); LOG.info("tMaxIC = "+tMaxIC +" / "+nMaxIC); LOG.info("tSimGIC = "+tSimGIC +" / "+nSimGIC); LOG.info("tBMA = "+tBMA +" / "+nBMA); } EWAHCompressedBitmap cad = iAttsBM.and(jAttsBM); // COMMON SUBSUMERS (ALL) Set<OWLClass> csSet = new HashSet<OWLClass>(); for (int ix : cad.toArray()) { csSet.add(classArray[ix]); } // MAXIC // TODO - evaluate if this is optimal; // MaxIC falls out of BMA calculation, but it may be useful // to calculate here to test if more expensive AxA is required t = System.currentTimeMillis(); double icBest = 0; double icSumCAD = 0; for (int ix : cad.toArray()) { Double ic = getInformationContentForAttribute(ix); //OWLClass c = n.getRepresentativeElement(); if (ic > icBest) { icBest = ic; } icSumCAD += ic; } tMaxIC += tdelta(t); nMaxIC++; if (icBest < minMaxIC) { throw new CutoffException("minMaxIC",minMaxIC,icBest); } s.maxIC = icBest; // SIMGIC t = System.currentTimeMillis(); EWAHCompressedBitmap cud = iAttsBM.or(jAttsBM); double icSumCUD = 0; for (int ix : cud.toArray()) { Double ic = getInformationContentForAttribute(ix); icSumCUD += ic; } s.simGIC = icSumCAD / icSumCUD; tSimGIC += tdelta(t); nSimGIC++; // BEST MATCHES t = System.currentTimeMillis(); tBMA += tdelta(t); nBMA++; return s; } public ElementPairScores getGroupwiseSimilarity(OWLNamedIndividual i) throws Exception { return getGroupwiseSimilarity(i,i,-1,-1); } public ElementPairScores getGroupwiseSimilarity(Set<OWLClass> attsI, Set<OWLClass> attsJ) throws Exception { double minSimJPct = getPropertyAsDouble(SimConfigurationProperty.minimumSimJ, 0.05) * 100; double minMaxIC = getPropertyAsDouble(SimConfigurationProperty.minimumMaxIC, 2.5); return getGroupwiseSimilarity(attsI, attsJ, minSimJPct, minMaxIC); } public ElementPairScores getGroupwiseSimilarity(OWLNamedIndividual i, OWLNamedIndividual j) throws Exception { double minSimJPct = getPropertyAsDouble(SimConfigurationProperty.minimumSimJ, 0.05) * 100; double minMaxIC = getPropertyAsDouble(SimConfigurationProperty.minimumMaxIC, 2.5); return getGroupwiseSimilarity(i,j, minSimJPct, minMaxIC); } public ElementPairScores getGroupwiseSimilarity(OWLNamedIndividual i, OWLNamedIndividual j, double minSimJPct, double minMaxIC) throws Exception { ElementPairScores s = new ElementPairScores(i,j); // EWAHCompressedBitmap iAttsBM = ancsBitmapCachedModifiable(i); // EWAHCompressedBitmap jAttsBM = ancsBitmapCachedModifiable(j); // s = computeMatchWithBM(iAttsBM,jAttsBM, minSimJPct, minMaxIC); populateSimilarityMatrix(i, j, s); s.simGIC = getElementGraphInformationContentSimilarity(i, j); s.combinedScore = (int) (s.simGIC * 100); // default return s; } public ElementPairScores getGroupwiseSimilarity(Set<OWLClass> atts, OWLNamedIndividual j) throws Exception { double minSimJPct = getPropertyAsDouble(SimConfigurationProperty.minimumSimJ, 0.05) * 100; double minMaxIC = getPropertyAsDouble(SimConfigurationProperty.minimumMaxIC, 2.5); return getGroupwiseSimilarity(atts, j, minSimJPct, minMaxIC); } @SuppressWarnings({ "rawtypes", "unchecked" }) public ElementPairScores getGroupwiseSimilarity(Set<OWLClass> atts, OWLNamedIndividual j, double minSimJPct, double minMaxIC) throws Exception { ElementPairScores s = new ElementPairScores(null, j); s = getGroupwiseSimilarity(atts, this.getAttributesForElement(j), minSimJPct,minMaxIC); s.j = j; return s; } @SuppressWarnings({ "rawtypes", "unchecked" }) public ElementPairScores getGroupwiseSimilarity(Set<OWLClass> attsI, Set<OWLClass> attsJ, double minSimJPct, double minMaxIC) throws Exception { ElementPairScores s = new ElementPairScores(null, null); Set<OWLClass> csetFilteredDirect = new HashSet<OWLClass>(); // direct Set<OWLClass> cset = new HashSet<OWLClass>(); // closure Set<OWLClass> credundant = new HashSet<OWLClass>(); // closure Set<OWLClass> dsetFilteredDirect = new HashSet<OWLClass>(); // direct Set<OWLClass> dset = new HashSet<OWLClass>(); // closure Set<OWLClass> dredundant = new HashSet<OWLClass>(); // closure boolean isIgnoreUnknownClasses = false; // FIND CLOSURE for (OWLClass c : attsI) { if (!this.getAllAttributeClasses().contains(c)) { if (isIgnoreUnknownClasses) continue; throw new UnknownOWLClassException(c); } csetFilteredDirect.add(c); for (Node<OWLClass> n : getNamedReflexiveSubsumers(c)) { cset.add(getDeterministicRepresentative(n)); } for (Node<OWLClass> n :getNamedSubsumers(c)) { credundant.addAll(n.getEntities()); } } csetFilteredDirect.removeAll(credundant); Vector csetV = new Vector<OWLClass>(attsI.size()); for (OWLClass c : csetFilteredDirect) { csetV.add(c); } EWAHCompressedBitmap iAttsBM = ancsBitmapCached(cset); for (OWLClass c : attsJ) { if (!this.getAllAttributeClasses().contains(c)) { if (isIgnoreUnknownClasses) continue; throw new UnknownOWLClassException(c); } dsetFilteredDirect.add(c); for (Node<OWLClass> n : getNamedReflexiveSubsumers(c)) { dset.add(getDeterministicRepresentative(n)); } for (Node<OWLClass> n :getNamedSubsumers(c)) { dredundant.addAll(n.getEntities()); } } dsetFilteredDirect.removeAll(dredundant); Vector dsetV = new Vector<OWLClass>(attsJ.size()); for (OWLClass c : dsetFilteredDirect) { dsetV.add(c); } EWAHCompressedBitmap jAttsBM = ancsBitmapCached(dset); s = computeMatchWithBM(iAttsBM,jAttsBM, minSimJPct, minMaxIC); populateSimilarityMatrix(csetV, dsetV, s); return s; } public void calculateCombinedScores(List<ElementPairScores> scoreSets, double maxMaxIC, double maxBMA) { int maxMaxIC100 = (int)(maxMaxIC * 100); int maxBMA100 = (int)(maxBMA * 100); LOG.info("Calculating combinedScores - upper bounds = "+maxMaxIC100+ " " + maxBMA100); // TODO - optimize this by using % scores as inputs for (ElementPairScores s : scoreSets) { int pctMaxScore = ((int) (s.maxIC * 10000)) / maxMaxIC100; int pctAvgScore = ((int) (s.bmaSymIC * 10000)) / maxBMA100; s.combinedScore = (pctMaxScore + pctAvgScore)/2; //calculateCombinedScore(s,maxMaxIC,maxBMA); } } /** * * @param c * @param ds * @return scores * @throws UnknownOWLClassException */ // TODO - rewrite @Override public List<AttributesSimScores> compareAllAttributes(OWLClass c, Set<OWLClass> ds) throws UnknownOWLClassException { List<AttributesSimScores> scoresets = new ArrayList<AttributesSimScores>(); EWAHCompressedBitmap bmc = this.ancsBitmapCachedModifiable(c); int cSize = bmc.cardinality(); Set<AttributesSimScores> best = new HashSet<AttributesSimScores>(); Double bestScore = null; for (OWLClass d : ds) { EWAHCompressedBitmap bmd = this.ancsBitmapCachedModifiable(d); int dSize = bmd.cardinality(); int cadSize = bmc.andCardinality(bmd); int cudSize = bmc.orCardinality(bmd); AttributesSimScores s = new AttributesSimScores(c,d); s.simJScore = cadSize / (double)cudSize; s.AsymSimJScore = cadSize / (double) dSize; //ClassExpressionPair pair = new ClassExpressionPair(c, d); //ScoreAttributePair lcs = getLowestCommonSubsumerIC(pair, cad, null); //s.lcsScore = lcs; scoresets.add(s); if (bestScore == null) { best.add(s); bestScore = s.simJScore; } else if (bestScore == s.simJScore) { best.add(s); } else if (s.simJScore > bestScore) { bestScore = s.simJScore; best = new HashSet<AttributesSimScores>(Collections.singleton(s)); } } for (AttributesSimScores s : best) { s.isBestMatch = true; } return scoresets; } // UTIL OWLClass thing = null; Node<OWLClass> thingNode = null; /** * Convenience method. Warning: method name may change * @return owl:Thing (root class) */ public OWLClass owlThing() { if (thing == null) thing = getSourceOntology().getOWLOntologyManager().getOWLDataFactory().getOWLThing(); return thing; } /** * Convenience method. Warning: method name may change * @return root class (owl:Thing and anything equivalent) */ public Node<OWLClass> owlThingNode() { if (thingNode == null) thingNode = getReasoner().getTopClassNode(); return thingNode; } /* (non-Javadoc) * @see owltools.sim2.AbstractOwlSim#saveState(java.lang.String) */ public void saveState(String fileName) throws IOException { FileOutputStream fos = new FileOutputStream(fileName); IOUtils.write("classArray:"+classArray.length+"\n", fos); for (int i=0; i<classArray.length; i++) { IOUtils.write("classArray "+i+" "+classArray[i]+"\n", fos); } IOUtils.write("classIndex:"+classIndex.keySet().size()+"\n", fos); for (OWLClass c : classIndex.keySet()) { IOUtils.write("classIndex "+c+" "+classIndex.get(c)+"\n", fos); } IOUtils.write("attributeClass-index: "+getAllAttributeClasses().size()+"\n", fos); for (OWLClass c : this.getAllAttributeClasses()) { IOUtils.write("attributeClass-index "+c+" "+classIndex.get(c)+"\n", fos); } IOUtils.write("icClassArray:\n", fos); for (int i=0; i<icClassArray.length; i++) { IOUtils.write("icClassArray "+i+" "+icClassArray[i]+"\n", fos); } IOUtils.write("icCache:\n", fos); for (OWLClass c : icCache.keySet()) { IOUtils.write("icCache "+c+" "+icCache.get(c)+"\n", fos); } IOUtils.write("classToRepresentativeClassMap:\n", fos); for (OWLClass c : classTorepresentativeClassMap.keySet()) { IOUtils.write("classTorepresentativeClassMap "+c+" "+classTorepresentativeClassMap.get(c)+"\n", fos); } IOUtils.write("representativeClassMap:\n", fos); for (Node<OWLClass> n : representativeClassMap.keySet()) { IOUtils.write("representativeClassMap "+n+" "+representativeClassMap.get(n)+"\n", fos); } fos.close(); } @Override public void saveLCSCache(String fileName, Double thresholdIC) throws IOException { FileOutputStream fos = new FileOutputStream(fileName); // iterate through all classes fetching their ICs, using the class index. // this has the side effect of ensuring that icClassArray is populated. int n=0; for (OWLClass c : this.getAllAttributeClasses()) { try { int cix = classIndex.get(c); Double ic = getInformationContentForAttribute(cix); Double icCheck = icClassArray[cix]; // for debugging Double icBase = getInformationContentForAttribute(c); LOG.info("Class "+c+" has ix="+cix+" IC="+ic+ " IC(check)="+icCheck+" IC(base)="+icBase+ " C(check)="+getShortId(classArray[cix])); n++; } catch (UnknownOWLClassException e) { LOG.error("cannot find IC values for class "+c, e); throw new IOException("unknown: "+c); } } // We assume ciPairIsCached is populated for ( int cix = 0; cix< ciPairIsCached.length; cix++) { boolean[] arr = ciPairIsCached[cix]; OWLClass c = classArray[cix]; for ( int dix = 0; dix< arr.length; dix++) { if (arr[dix]) { //double s = ciPairScaledScore[cix][dix] / (double) scaleFactor; int lcsix = ciPairLCS[cix][dix]; Double s = icClassArray[lcsix]; if (s == null || s.isNaN() || s.isInfinite()) { throw new IOException("No IC for "+classArray[lcsix]); } if (thresholdIC == null || s.doubleValue() >= thresholdIC) { OWLClass d = classArray[dix]; OWLClass lcs = classArray[lcsix]; IOUtils.write(getShortId((OWLClass) c) +"\t" + getShortId((OWLClass) d) + "\t" + s + "\t" + getShortId(lcs) + "\n", fos); } } } } fos.close(); } /** * @param fileName * @throws IOException */ @Override public void loadLCSCache(String fileName) throws IOException { try { clearLCSCache(); } catch (UnknownOWLClassException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new IOException("Cannot clear cache"); } LOG.info("Loading LCS cache from "+fileName); FileInputStream s = new FileInputStream(fileName); //List<String> lines = IOUtils.readLines(s); LineIterator itr = IOUtils.lineIterator(s, null); while (itr.hasNext()) { //for (String line : lines) { String line = itr.nextLine(); String[] vals = line.split("\t"); OWLClass c1 = getOWLClassFromShortId(vals[0]); OWLClass c2 = getOWLClassFromShortId(vals[1]); OWLClass a = getOWLClassFromShortId(vals[3]); Integer cix = classIndex.get(c1); Integer dix = classIndex.get(c2); Integer aix = classIndex.get(a); if (cix == null) { LOG.error("Unknown class C: "+c1); } if (dix == null) { LOG.error("Unknown class D: "+c2); } if (aix == null) { LOG.error("Unknown ancestor class: "+a); } ciPairIsCached[cix][dix] = true; //ciPairScaledScore[cix][dix] = (short)(Double.valueOf(vals[2]) * scaleFactor); // TODO - set all IC caches ciPairLCS[cix][dix] = aix; } s.close(); LOG.info("Finished loading LCS cache from "+fileName); isLCSCacheFullyPopulated = true; } @Override protected void setInformtionContectForAttribute(OWLClass c, Double v) { icCache.put(c, v); if (icClassArray == null) icClassArray = new Double[classArray.length]; if (!classIndex.containsKey(c)) { LOG.warn("Non-indexed class: "+c); } icClassArray[classIndex.get(c)] = v; } @Override protected void clearInformationContentCache() { LOG.info("Clearing IC cache"); testCache = null; icCache = new HashMap<OWLClass,Double>(); icClassArray = null; } protected void clearLCSCache() throws UnknownOWLClassException { LOG.info("Clearing LCS cache"); if (classArray == null) { createElementAttributeMapFromOntology(); } ciPairLCS = new int[classArray.length][classArray.length]; //ciPairScaledScore = new short[classArray.length][classArray.length]; ciPairIsCached = new boolean[classArray.length][classArray.length]; } @Override public Map<OWLNamedIndividual, Set<OWLClass>> getElementToAttributesMap() { if (elementToDirectAttributesMap == null) try { createElementAttributeMapFromOntology(); } catch (UnknownOWLClassException e) { // TODO Auto-generated catch block e.printStackTrace(); } return elementToDirectAttributesMap; } @Override public SummaryStatistics getSimStatistics(String stat) { // TODO Auto-generated method stub return null; } @Override public void calculateMetricStats(Set<OWLNamedIndividual> iset, Set<OWLNamedIndividual> jset) throws Exception { LOG.info("Calculating all-by-all summary statistics for all metrics"); for (String m : metrics) { metricStatMeans.put(m, new SummaryStatistics()); metricStatMins.put(m, new SummaryStatistics()); metricStatMaxes.put(m, new SummaryStatistics()); } for (OWLNamedIndividual i : iset) { HashMap<String,SummaryStatistics> metricStatIndividual = new HashMap<String,SummaryStatistics>(); for (String m : metrics) { metricStatIndividual.put(m, new SummaryStatistics()); } for (OWLNamedIndividual j : jset) { ElementPairScores gwsim = null; try { gwsim = this.getGroupwiseSimilarity(i, j,-1,-1); } catch (CutoffException e) { //should never happen e.printStackTrace(); } metricStatIndividual.get("bmaAsymIC").addValue(gwsim.bmaAsymIC); metricStatIndividual.get("bmaSymIC").addValue(gwsim.bmaSymIC); metricStatIndividual.get("bmaInverseAsymIC").addValue(gwsim.bmaInverseAsymIC); metricStatIndividual.get("combinedScore").addValue(gwsim.combinedScore); metricStatIndividual.get("simJ").addValue(gwsim.simjScore); metricStatIndividual.get("simGIC").addValue(gwsim.simGIC); metricStatIndividual.get("maxIC").addValue(gwsim.maxIC); } for (String m : metrics) { metricStatMins.get(m).addValue(metricStatIndividual.get(m).getMin()); metricStatMeans.get(m).addValue(metricStatIndividual.get(m).getMean()); metricStatMaxes.get(m).addValue(metricStatIndividual.get(m).getMax()); } } } @Override public OwlSimMetadata getMetadata() { OwlSimMetadata md = super.getMetadata(); md.classCount = this.getAllAttributeClasses().size(); md.classIndexSize = classArray.length; md.individualCount = getAllElements().size(); md.lcsCacheWidth = ciPairLCS.length; md.scaleFactor = scaleFactor; md.reasonerClass = this.getReasoner().getClass().toString(); md.allTypesDirectCount = allTypesDirect.size(); md.allTypesInferredCount = allTypesInferred.size(); return md; } }
// This file is part of OpenTSDB. // This program is free software: you can redistribute it and/or modify it // option) any later version. This program is distributed in the hope that it // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser package net.opentsdb.tsd; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicInteger; import static java.util.concurrent.TimeUnit.MILLISECONDS; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.opentsdb.core.Aggregator; import net.opentsdb.core.Aggregators; import net.opentsdb.core.Const; import net.opentsdb.core.DataPoint; import net.opentsdb.core.DataPoints; import net.opentsdb.core.Query; import net.opentsdb.core.TSDB; import net.opentsdb.core.Tags; import net.opentsdb.graph.Plot; import net.opentsdb.stats.Histogram; import net.opentsdb.stats.StatsCollector; import net.opentsdb.uid.NoSuchUniqueName; import net.opentsdb.utils.DateTime; import net.opentsdb.utils.JSON; /** * Stateless handler of HTTP graph requests (the {@code /q} endpoint). */ final class GraphHandler implements HttpRpc { private static final Logger LOG = LoggerFactory.getLogger(GraphHandler.class); private static final boolean IS_WINDOWS = System.getProperty("os.name").contains("Windows"); /** Number of times we had to do all the work up to running Gnuplot. */ private static final AtomicInteger graphs_generated = new AtomicInteger(); /** Number of times a graph request was served from disk, no work needed. */ private static final AtomicInteger graphs_diskcache_hit = new AtomicInteger(); /** Keep track of the latency of graphing requests. */ private static final Histogram graphlatency = new Histogram(16000, (short) 2, 100); /** Keep track of the latency (in ms) introduced by running Gnuplot. */ private static final Histogram gnuplotlatency = new Histogram(16000, (short) 2, 100); /** Executor to run Gnuplot in separate bounded thread pool. */ private final ThreadPoolExecutor gnuplot; /** * Constructor. */ public GraphHandler() { // Gnuplot is mostly CPU bound and does only a little bit of IO at the // beginning to read the input data and at the end to write its output. // We want to avoid running too many Gnuplot instances concurrently as // it can steal a significant number of CPU cycles from us. Instead, we // allow only one per core, and we nice it (the nicing is done in the // shell script we use to start Gnuplot). Similarly, the queue we use // is sized so as to have a fixed backlog per core. final int ncores = Runtime.getRuntime().availableProcessors(); gnuplot = new ThreadPoolExecutor( ncores, ncores, // Thread pool of a fixed size. 300000, MILLISECONDS, // How long to keep idle threads. new ArrayBlockingQueue<Runnable>(20 * ncores), // XXX Don't hardcode? thread_factory); // ArrayBlockingQueue does not scale as much as LinkedBlockingQueue in terms // of throughput but we don't need high throughput here. We use ABQ instead // of LBQ because it creates far fewer references. } public void execute(final TSDB tsdb, final HttpQuery query) { if (!query.hasQueryStringParam("json") && !query.hasQueryStringParam("png") && !query.hasQueryStringParam("ascii")) { String uri = query.request().getUri(); if (uri.length() < 4) { // Shouldn't happen... uri = "/"; // But just in case, redirect. } else { uri = "/#" + uri.substring(3); // Remove "/q?" } query.redirect(uri); return; } try { doGraph(tsdb, query); } catch (IOException e) { query.internalError(e); } catch (IllegalArgumentException e) { query.badRequest(e.getMessage()); } } private void doGraph(final TSDB tsdb, final HttpQuery query) throws IOException { final String basepath = getGnuplotBasePath(tsdb, query); long start_time = DateTime.parseDateTimeString( query.getRequiredQueryStringParam("start"), query.getQueryStringParam("tz")); final boolean nocache = query.hasQueryStringParam("nocache"); if (start_time == -1) { throw BadRequestException.missingParameter("start"); } else { // temp fixup to seconds from ms until the rest of TSDB supports ms // Note you can't append this to the DateTime.parseDateTimeString() call as // it clobbers -1 results start_time /= 1000; } long end_time = DateTime.parseDateTimeString( query.getQueryStringParam("end"), query.getQueryStringParam("tz")); final long now = System.currentTimeMillis() / 1000; if (end_time == -1) { end_time = now; } else { // temp fixup to seconds from ms until the rest of TSDB supports ms // Note you can't append this to the DateTime.parseDateTimeString() call as // it clobbers -1 results end_time /= 1000; } final int max_age = computeMaxAge(query, start_time, end_time, now); if (!nocache && isDiskCacheHit(query, end_time, max_age, basepath)) { return; } Query[] tsdbqueries; List<String> options; tsdbqueries = parseQuery(tsdb, query); options = query.getQueryStringParams("o"); if (options == null) { options = new ArrayList<String>(tsdbqueries.length); for (int i = 0; i < tsdbqueries.length; i++) { options.add(""); } } else if (options.size() != tsdbqueries.length) { throw new BadRequestException(options.size() + " `o' parameters, but " + tsdbqueries.length + " `m' parameters."); } for (final Query tsdbquery : tsdbqueries) { try { tsdbquery.setStartTime(start_time); } catch (IllegalArgumentException e) { throw new BadRequestException("start time: " + e.getMessage()); } try { tsdbquery.setEndTime(end_time); } catch (IllegalArgumentException e) { throw new BadRequestException("end time: " + e.getMessage()); } } final Plot plot = new Plot(start_time, end_time, DateTime.timezones.get(query.getQueryStringParam("tz"))); setPlotDimensions(query, plot); setPlotParams(query, plot); final int nqueries = tsdbqueries.length; @SuppressWarnings("unchecked") final HashSet<String>[] aggregated_tags = new HashSet[nqueries]; int npoints = 0; for (int i = 0; i < nqueries; i++) { try { // execute the TSDB query! // XXX This is slow and will block Netty. TODO(tsuna): Don't block. // TODO(tsuna): Optimization: run each query in parallel. final DataPoints[] series = tsdbqueries[i].run(); for (final DataPoints datapoints : series) { plot.add(datapoints, options.get(i)); aggregated_tags[i] = new HashSet<String>(); aggregated_tags[i].addAll(datapoints.getAggregatedTags()); npoints += datapoints.aggregatedSize(); } } catch (RuntimeException e) { logInfo(query, "Query failed (stack trace coming): " + tsdbqueries[i]); throw e; } tsdbqueries[i] = null; // free() } tsdbqueries = null; // free() if (query.hasQueryStringParam("ascii")) { respondAsciiQuery(query, max_age, basepath, plot); return; } try { gnuplot.execute(new RunGnuplot(query, max_age, plot, basepath, aggregated_tags, npoints)); } catch (RejectedExecutionException e) { query.internalError(new Exception("Too many requests pending," + " please try again later", e)); } } /** * Decides how long we're going to allow the client to cache our response. * <p> * Based on the query, we'll decide whether or not we want to allow the * client to cache our response and for how long. * @param query The query to serve. * @param start_time The start time on the query (32-bit unsigned int, secs). * @param end_time The end time on the query (32-bit unsigned int, seconds). * @param now The current time (32-bit unsigned int, seconds). * @return A positive integer, in seconds. */ private static int computeMaxAge(final HttpQuery query, final long start_time, final long end_time, final long now) { // If the end time is in the future (1), make the graph uncacheable. // Otherwise, if the end time is far enough in the past (2) such that // no TSD can still be writing to rows for that time span and it's not // specified in a relative fashion (3) (e.g. "1d-ago"), make the graph // cacheable for a day since it's very unlikely that any data will change // for this time span. // Otherwise (4), allow the client to cache the graph for ~0.1% of the // time span covered by the request e.g., for 1h of data, it's OK to // serve something 3s stale, for 1d of data, 84s stale. if (end_time > now) { return 0; } else if (end_time < now - Const.MAX_TIMESPAN && !DateTime.isRelativeDate( query.getQueryStringParam("start")) && !DateTime.isRelativeDate( query.getQueryStringParam("end"))) { return 86400; } else { return (int) (end_time - start_time) >> 10; } } // Runs Gnuplot in a subprocess to generate the graph. private static final class RunGnuplot implements Runnable { private final HttpQuery query; private final int max_age; private final Plot plot; private final String basepath; private final HashSet<String>[] aggregated_tags; private final int npoints; public RunGnuplot(final HttpQuery query, final int max_age, final Plot plot, final String basepath, final HashSet<String>[] aggregated_tags, final int npoints) { this.query = query; this.max_age = max_age; this.plot = plot; if (IS_WINDOWS) this.basepath = basepath.replace("\\", "\\\\").replace("/", "\\\\"); else this.basepath = basepath; this.aggregated_tags = aggregated_tags; this.npoints = npoints; } public void run() { try { execute(); } catch (BadRequestException e) { query.badRequest(e.getMessage()); } catch (GnuplotException e) { query.badRequest("<pre>" + e.getMessage() + "</pre>"); } catch (RuntimeException e) { query.internalError(e); } catch (IOException e) { query.internalError(e); } } private void execute() throws IOException { final int nplotted = runGnuplot(query, basepath, plot); if (query.hasQueryStringParam("json")) { final HashMap<String, Object> results = new HashMap<String, Object>(); results.put("plotted", nplotted); results.put("points", npoints); // 1.0 returned an empty inner array if the 1st hashset was null, to do // the same we need to fudge it with an empty set if (aggregated_tags != null && aggregated_tags.length > 0 && aggregated_tags[0] == null) { aggregated_tags[0] = new HashSet<String>(); } results.put("etags", aggregated_tags); results.put("timing", query.processingTimeMillis()); query.sendReply(JSON.serializeToBytes(results)); writeFile(query, basepath + ".json", JSON.serializeToBytes(results)); } else if (query.hasQueryStringParam("png")) { query.sendFile(basepath + ".png", max_age); } else { query.internalError(new Exception("Should never be here!")); } // TODO(tsuna): Expire old files from the on-disk cache. graphlatency.add(query.processingTimeMillis()); graphs_generated.incrementAndGet(); } } /** Shuts down the thread pool used to run Gnuplot. */ public void shutdown() { gnuplot.shutdown(); } /** * Collects the stats and metrics tracked by this instance. * @param collector The collector to use. */ public static void collectStats(final StatsCollector collector) { collector.record("http.latency", graphlatency, "type=graph"); collector.record("http.latency", gnuplotlatency, "type=gnuplot"); collector.record("http.graph.requests", graphs_diskcache_hit, "cache=disk"); collector.record("http.graph.requests", graphs_generated, "cache=miss"); } /** Returns the base path to use for the Gnuplot files. */ private String getGnuplotBasePath(final TSDB tsdb, final HttpQuery query) { final Map<String, List<String>> q = query.getQueryString(); q.remove("ignore"); // Super cheap caching mechanism: hash the query string. final HashMap<String, List<String>> qs = new HashMap<String, List<String>>(q); // But first remove the parameters that don't influence the output. qs.remove("png"); qs.remove("json"); qs.remove("ascii"); return tsdb.getConfig().getString("tsd.http.cachedir") + Integer.toHexString(qs.hashCode()); } /** * Checks whether or not it's possible to re-serve this query from disk. * @param query The query to serve. * @param end_time The end time on the query (32-bit unsigned int, seconds). * @param max_age The maximum time (in seconds) we wanna allow clients to * cache the result in case of a cache hit. * @param basepath The base path used for the Gnuplot files. * @return {@code true} if this request was served from disk (in which * case processing can stop here), {@code false} otherwise (in which case * the query needs to be processed). */ private boolean isDiskCacheHit(final HttpQuery query, final long end_time, final int max_age, final String basepath) throws IOException { final String cachepath = basepath + (query.hasQueryStringParam("ascii") ? ".txt" : ".png"); final File cachedfile = new File(cachepath); if (cachedfile.exists()) { final long bytes = cachedfile.length(); if (bytes < 21) { // Minimum possible size for a PNG: 21 bytes. // For .txt files, <21 bytes is almost impossible. logWarn(query, "Cached " + cachepath + " is too small (" + bytes + " bytes) to be valid. Ignoring it."); return false; } if (staleCacheFile(query, end_time, max_age, cachedfile)) { return false; } if (query.hasQueryStringParam("json")) { HashMap<String, Object> map = loadCachedJson(query, end_time, max_age, basepath); if (map == null) { map = new HashMap<String, Object>(); } map.put("timing", query.processingTimeMillis()); map.put("cachehit", "disk"); query.sendReply(JSON.serializeToBytes(map)); } else if (query.hasQueryStringParam("png") || query.hasQueryStringParam("ascii")) { query.sendFile(cachepath, max_age); } else { query.sendReply(HttpQuery.makePage("TSDB Query", "Your graph is ready", "<img src=\"" + query.request().getUri() + "&amp;png\"/><br/>" + "<small>(served from disk cache)</small>")); } graphs_diskcache_hit.incrementAndGet(); return true; } // We didn't find an image. Do a negative cache check. If we've seen // this query before but there was no result, we at least wrote the JSON. final HashMap<String, Object> map = loadCachedJson(query, end_time, max_age, basepath); // If we don't have a JSON file it's a complete cache miss. If we have // one, and it says 0 data points were plotted, it's a negative cache hit. if (map == null || !map.containsKey("plotted") || ((Integer)map.get("plotted")) == 0) { return false; } if (query.hasQueryStringParam("json")) { map.put("timing", query.processingTimeMillis()); map.put("cachehit", "disk"); query.sendReply(JSON.serializeToBytes(map)); } else if (query.hasQueryStringParam("png")) { query.sendReply(" "); // Send back an empty response... } else { query.sendReply(HttpQuery.makePage("TSDB Query", "No results", "Sorry, your query didn't return anything.<br/>" + "<small>(served from disk cache)</small>")); } graphs_diskcache_hit.incrementAndGet(); return true; } /** * Returns whether or not the given cache file can be used or is stale. * @param query The query to serve. * @param end_time The end time on the query (32-bit unsigned int, seconds). * @param max_age The maximum time (in seconds) we wanna allow clients to * cache the result in case of a cache hit. If the file is exactly that * old, it is not considered stale. * @param cachedfile The file to check for staleness. */ private static boolean staleCacheFile(final HttpQuery query, final long end_time, final long max_age, final File cachedfile) { final long mtime = cachedfile.lastModified() / 1000; if (mtime <= 0) { return true; // File doesn't exist, or can't be read. } final long now = System.currentTimeMillis() / 1000; // How old is the cached file, in seconds? final long staleness = now - mtime; if (staleness < 0) { // Can happen if the mtime is "in the future". logWarn(query, "Not using file @ " + cachedfile + " with weird" + " mtime in the future: " + mtime); return true; // Play it safe, pretend we can't use this file. } // Case 1: The end time is an absolute point in the past. // We might be able to re-use the cached file. if (0 < end_time && end_time < now) { // If the file was created prior to the end time, maybe we first // executed this query while the result was uncacheable. We can // tell by looking at the mtime on the file. If the file was created // before the query end time, then it contains partial results that // shouldn't be served again. return mtime < end_time; } // Case 2: The end time of the query is now or in the future. // The cached file contains partial data and can only be re-used if it's // not too old. if (staleness > max_age) { logInfo(query, "Cached file @ " + cachedfile.getPath() + " is " + staleness + "s stale, which is more than its limit of " + max_age + "s, and needs to be regenerated."); return true; } return false; } /** * Writes the given byte array into a file. * This function logs an error but doesn't throw if it fails. * @param query The query being handled (for logging purposes). * @param path The path to write to. * @param contents The contents to write into the file. */ private static void writeFile(final HttpQuery query, final String path, final byte[] contents) { try { final FileOutputStream out = new FileOutputStream(path); try { out.write(contents); } finally { out.close(); } } catch (FileNotFoundException e) { logError(query, "Failed to create file " + path, e); } catch (IOException e) { logError(query, "Failed to write file " + path, e); } } /** * Reads a file into a byte array. * @param query The query being handled (for logging purposes). * @param file The file to read. * @param max_length The maximum number of bytes to read from the file. * @return {@code null} if the file doesn't exist or is empty or couldn't be * read, otherwise a byte array of up to {@code max_length} bytes. */ private static byte[] readFile(final HttpQuery query, final File file, final int max_length) { final int length = (int) file.length(); if (length <= 0) { return null; } FileInputStream in; try { in = new FileInputStream(file.getPath()); } catch (FileNotFoundException e) { return null; } try { final byte[] buf = new byte[Math.min(length, max_length)]; final int read = in.read(buf); if (read != buf.length) { logError(query, "When reading " + file + ": read only " + read + " bytes instead of " + buf.length); return null; } return buf; } catch (IOException e) { logError(query, "Error while reading " + file, e); return null; } finally { try { in.close(); } catch (IOException e) { logError(query, "Error while closing " + file, e); } } } /** * Attempts to read the cached {@code .json} file for this query. * @param query The query to serve. * @param end_time The end time on the query (32-bit unsigned int, seconds). * @param max_age The maximum time (in seconds) we wanna allow clients to * cache the result in case of a cache hit. * @param basepath The base path used for the Gnuplot files. * @return {@code null} in case no file was found, or the contents of the * file if it was found. * @throws IOException If the file cannot be loaded * @throws JsonMappingException If the JSON cannot be parsed to a HashMap * @throws JsonParseException If the JSON is improperly formatted */ @SuppressWarnings("unchecked") private HashMap<String, Object> loadCachedJson(final HttpQuery query, final long end_time, final long max_age, final String basepath) throws JsonParseException, JsonMappingException, IOException { final String json_path = basepath + ".json"; File json_cache = new File(json_path); if (staleCacheFile(query, end_time, max_age, json_cache)) { return null; } final byte[] json = readFile(query, json_cache, 4096); if (json == null) { return null; } json_cache = null; return (HashMap<String, Object>) JSON.parseToObject(json, HashMap.class); } /** Parses the {@code wxh} query parameter to set the graph dimension. */ static void setPlotDimensions(final HttpQuery query, final Plot plot) { final String wxh = query.getQueryStringParam("wxh"); if (wxh != null && !wxh.isEmpty()) { final int wxhlength = wxh.length(); if (wxhlength < 7) { // 100x100 minimum. throw new BadRequestException("Parameter wxh too short: " + wxh); } final int x = wxh.indexOf('x', 3); // Start at 2 as min size is 100x100 if (x < 0) { throw new BadRequestException("Invalid wxh parameter: " + wxh); } try { final short width = Short.parseShort(wxh.substring(0, x)); final short height = Short.parseShort(wxh.substring(x + 1, wxhlength)); try { plot.setDimensions(width, height); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid wxh parameter: " + wxh + ", " + e.getMessage()); } } catch (NumberFormatException e) { throw new BadRequestException("Can't parse wxh '" + wxh + "': " + e.getMessage()); } } } /** * Formats and quotes the given string so it's a suitable Gnuplot string. * @param s The string to stringify. * @return A string suitable for use as a literal string in Gnuplot. */ private static String stringify(final String s) { final StringBuilder buf = new StringBuilder(1 + s.length() + 1); buf.append('"'); HttpQuery.escapeJson(s, buf); // Abusing this function gets the job done. buf.append('"'); return buf.toString(); } /** * Pops out of the query string the given parameter. * @param querystring The query string. * @param param The name of the parameter to pop out. * @return {@code null} if the parameter wasn't passed, otherwise the * value of the last occurrence of the parameter. */ private static String popParam(final Map<String, List<String>> querystring, final String param) { final List<String> params = querystring.remove(param); if (params == null) { return null; } return params.get(params.size() - 1); } /** * Applies the plot parameters from the query to the given plot. * @param query The query from which to get the query string. * @param plot The plot on which to apply the parameters. */ static void setPlotParams(final HttpQuery query, final Plot plot) { final HashMap<String, String> params = new HashMap<String, String>(); final Map<String, List<String>> querystring = query.getQueryString(); String value; if ((value = popParam(querystring, "yrange")) != null) { params.put("yrange", value); } if ((value = popParam(querystring, "y2range")) != null) { params.put("y2range", value); } if ((value = popParam(querystring, "ylabel")) != null) { params.put("ylabel", stringify(value)); } if ((value = popParam(querystring, "y2label")) != null) { params.put("y2label", stringify(value)); } if ((value = popParam(querystring, "yformat")) != null) { params.put("format y", stringify(value)); } if ((value = popParam(querystring, "y2format")) != null) { params.put("format y2", stringify(value)); } if ((value = popParam(querystring, "xformat")) != null) { params.put("format x", stringify(value)); } if ((value = popParam(querystring, "ylog")) != null) { params.put("logscale y", ""); } if ((value = popParam(querystring, "y2log")) != null) { params.put("logscale y2", ""); } if ((value = popParam(querystring, "key")) != null) { params.put("key", value); } if ((value = popParam(querystring, "title")) != null) { params.put("title", stringify(value)); } if ((value = popParam(querystring, "bgcolor")) != null) { params.put("bgcolor", value); } if ((value = popParam(querystring, "fgcolor")) != null) { params.put("fgcolor", value); } if ((value = popParam(querystring, "smooth")) != null) { params.put("smooth", value); } // This must remain after the previous `if' in order to properly override // any previous `key' parameter if a `nokey' parameter is given. if ((value = popParam(querystring, "nokey")) != null) { params.put("key", null); } plot.setParams(params); } /** * Runs Gnuplot in a subprocess to generate the graph. * <strong>This function will block</strong> while Gnuplot is running. * @param query The query being handled (for logging purposes). * @param basepath The base path used for the Gnuplot files. * @param plot The plot object to generate Gnuplot's input files. * @return The number of points plotted by Gnuplot (0 or more). * @throws IOException if the Gnuplot files can't be written, or * the Gnuplot subprocess fails to start, or we can't read the * graph from the file it produces, or if we have been interrupted. * @throws GnuplotException if Gnuplot returns non-zero. */ static int runGnuplot(final HttpQuery query, final String basepath, final Plot plot) throws IOException { final int nplotted = plot.dumpToFiles(basepath); final long start_time = System.nanoTime(); final Process gnuplot = new ProcessBuilder(GNUPLOT, basepath + ".out", basepath + ".err", basepath + ".gnuplot").start(); final int rv; try { rv = gnuplot.waitFor(); // Couldn't find how to do this asynchronously. } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Restore the interrupted status. throw new IOException("interrupted", e); // I hate checked exceptions. } finally { // We need to always destroy() the Process, otherwise we "leak" file // descriptors and pipes. Unless I'm blind, this isn't actually // documented in the Javadoc of the !@#$%^ JDK, and in Java 6 there's no // way to ask the stupid-ass ProcessBuilder to not create fucking pipes. // I think when the GC kicks in the JVM may run some kind of a finalizer // that closes the pipes, because I've never seen this issue on long // running TSDs, except where ulimit -n was low (the default, 1024). gnuplot.destroy(); } gnuplotlatency.add((int) ((System.nanoTime() - start_time) / 1000000)); if (rv != 0) { final byte[] stderr = readFile(query, new File(basepath + ".err"), 4096); // Sometimes Gnuplot will error out but still create the file. new File(basepath + ".png").delete(); if (stderr == null) { throw new GnuplotException(rv); } throw new GnuplotException(new String(stderr)); } // Remove the files for stderr/stdout if they're empty. deleteFileIfEmpty(basepath + ".out"); deleteFileIfEmpty(basepath + ".err"); return nplotted; } private static void deleteFileIfEmpty(final String path) { final File file = new File(path); if (file.length() <= 0) { file.delete(); } } /** * Respond to a query that wants the output in ASCII. * <p> * When a query specifies the "ascii" query string parameter, we send the * data points back to the client in plain text instead of sending a PNG. * @param query The query we're currently serving. * @param max_age The maximum time (in seconds) we wanna allow clients to * cache the result in case of a cache hit. * @param basepath The base path used for the Gnuplot files. * @param plot The plot object to generate Gnuplot's input files. */ private static void respondAsciiQuery(final HttpQuery query, final int max_age, final String basepath, final Plot plot) { final String path = basepath + ".txt"; PrintWriter asciifile; try { asciifile = new PrintWriter(path); } catch (IOException e) { query.internalError(e); return; } try { final StringBuilder tagbuf = new StringBuilder(); for (final DataPoints dp : plot.getDataPoints()) { final String metric = dp.metricName(); tagbuf.setLength(0); for (final Map.Entry<String, String> tag : dp.getTags().entrySet()) { tagbuf.append(' ').append(tag.getKey()) .append('=').append(tag.getValue()); } for (final DataPoint d : dp) { asciifile.print(metric); asciifile.print(' '); asciifile.print((d.timestamp() / 1000)); asciifile.print(' '); if (d.isInteger()) { asciifile.print(d.longValue()); } else { final double value = d.doubleValue(); if (value != value || Double.isInfinite(value)) { throw new IllegalStateException("NaN or Infinity:" + value + " d=" + d + ", query=" + query); } asciifile.print(value); } asciifile.print(tagbuf); asciifile.print('\n'); } } } finally { asciifile.close(); } try { query.sendFile(path, max_age); } catch (IOException e) { query.internalError(e); } } private static Query[] parseQuery(final TSDB tsdb, final HttpQuery query) { final List<String> ms = query.getQueryStringParams("m"); if (ms == null) { throw BadRequestException.missingParameter("m"); } final Query[] tsdbqueries = new Query[ms.size()]; int nqueries = 0; for (final String m : ms) { // m is of the following forms: // agg:[interval-agg:][rate:]metric[{tag=value,...}] // Where the parts in square brackets `[' .. `]' are optional. final String[] parts = Tags.splitString(m, ':'); int i = parts.length; if (i < 2 || i > 4) { throw new BadRequestException("Invalid parameter m=" + m + " (" + (i < 2 ? "not enough" : "too many") + " :-separated parts)"); } final Aggregator agg = getAggregator(parts[0]); i--; // Move to the last part (the metric name). final HashMap<String, String> parsedtags = new HashMap<String, String>(); final String metric = Tags.parseWithMetric(parts[i], parsedtags); final boolean rate = "rate".equals(parts[--i]); if (rate) { i--; // Move to the next part. } final Query tsdbquery = tsdb.newQuery(); try { tsdbquery.setTimeSeries(metric, parsedtags, agg, rate); } catch (NoSuchUniqueName e) { throw new BadRequestException(e.getMessage()); } // downsampling function & interval. if (i > 0) { final int dash = parts[1].indexOf('-', 1); // 1st char can't be `-'. if (dash < 0) { throw new BadRequestException("Invalid downsampling specifier '" + parts[1] + "' in m=" + m); } Aggregator downsampler; try { downsampler = Aggregators.get(parts[1].substring(dash + 1)); } catch (NoSuchElementException e) { throw new BadRequestException("No such downsampling function: " + parts[1].substring(dash + 1)); } final int interval = (int) DateTime.parseDuration(parts[1].substring(0, dash)); tsdbquery.downsample(interval, downsampler); } else { tsdbquery.downsample(1000, agg); } tsdbqueries[nqueries++] = tsdbquery; } return tsdbqueries; } /** * Returns the aggregator with the given name. * @param name Name of the aggregator to get. * @throws BadRequestException if there's no aggregator with this name. */ private static final Aggregator getAggregator(final String name) { try { return Aggregators.get(name); } catch (NoSuchElementException e) { throw new BadRequestException("No such aggregation function: " + name); } } private static final PlotThdFactory thread_factory = new PlotThdFactory(); private static final class PlotThdFactory implements ThreadFactory { private final AtomicInteger id = new AtomicInteger(0); public Thread newThread(final Runnable r) { return new Thread(r, "Gnuplot #" + id.incrementAndGet()); } } /** Name of the wrapper script we use to execute Gnuplot. */ private static final String WRAPPER = IS_WINDOWS ? "mygnuplot.bat" : "mygnuplot.sh"; /** Path to the wrapper script. */ private static final String GNUPLOT; static { GNUPLOT = findGnuplotHelperScript(); } /** * Iterate through the class path and look for the Gnuplot helper script. * @return The path to the wrapper script. */ private static String findGnuplotHelperScript() { final URL url = GraphHandler.class.getClassLoader().getResource(WRAPPER); if (url == null) { throw new RuntimeException("Couldn't find " + WRAPPER + " on the" + " CLASSPATH: " + System.getProperty("java.class.path")); } final String path = url.getFile(); LOG.debug("Using Gnuplot wrapper at {}", path); final File file = new File(path); final String error; if (!file.exists()) { error = "non-existent"; } else if (!file.canExecute()) { error = "non-executable"; } else if (!file.canRead()) { error = "unreadable"; } else { return path; } throw new RuntimeException("The " + WRAPPER + " found on the" + " CLASSPATH (" + path + ") is a " + error + " file... WTF?" + " CLASSPATH=" + System.getProperty("java.class.path")); } // Logging helpers. // static void logInfo(final HttpQuery query, final String msg) { LOG.info(query.channel().toString() + ' ' + msg); } static void logWarn(final HttpQuery query, final String msg) { LOG.warn(query.channel().toString() + ' ' + msg); } static void logError(final HttpQuery query, final String msg) { LOG.error(query.channel().toString() + ' ' + msg); } static void logError(final HttpQuery query, final String msg, final Throwable e) { LOG.error(query.channel().toString() + ' ' + msg, e); } }
package com.util; import java.util.*; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.io.*; public class ACLIManager { private static ACLIManager aclimInstance = null; private static final String CMD_EXEC = "cmd /c"; private static final String ACLI_EXEC = "arduino-cli"; private static final String ACLI_PATH = ""; private static final String BOARD_LIST_FILE = "boardlist.txt"; private static final String SKETCH_CONFIG_FILE = "sketch.json"; private ProcessBuilder processBuilder; private List<String> params; private String port; private String core; private String errorString; /** * Description: Enum used to create, package, and contain all necessary information * to run an Arduino CLI command through the ACLIManager (Arduino CLI Manager). */ public enum ACLICommand { //Installs required core for APM INSTALL_AVR_CORE (Arrays.asList("core", "install", "arduino:avr")), //Generates a list of attached Arduino Boards GENERATE_BOARD_LIST (Arrays.asList("board", "list", ">", BOARD_LIST_FILE)), //Parses the port and core of the APM as it appears in the board list file PARSE_BOARD_INFO (Arrays.asList(BOARD_LIST_FILE)), COMPILE_SKETCH (Arrays.asList("compile")), UPLOAD_SKETCH (Arrays.asList("upload")); public final List<String> params; ACLICommand(List<String> params) { this.params = params; } }; /** * Constructor (Private, accessed by getInstance) */ private ACLIManager() { port = ""; core = ""; errorString = "No error"; } /** * Returns the singleton instance of this class to be used system wide. * @return The Arduino CLI Command manager instance. */ public static ACLIManager getInstance() { if(aclimInstance == null) { aclimInstance = new ACLIManager(); } return aclimInstance; } /** * Executes the given ACLICommand object. as a command line operation using * the Java ProcessBuilder class. * @param command - The action/command to execute */ public void execute(ACLICommand command) { params = new ArrayList<String>(); params.addAll(0, Arrays.asList(CMD_EXEC, ACLI_EXEC, ACLI_PATH)); params.addAll(command.params); switch(command) { case INSTALL_AVR_CORE: //Go straight to exectuion break; case GENERATE_BOARD_LIST: //Go straight to execution break; case PARSE_BOARD_INFO: if(parseInfo()) { params.add(port); } else { System.err.println("ACLI Manager board attach error: " + "parsing operation unsuccessful"); return; } break; default: } processBuilder = new ProcessBuilder(); processBuilder.command(params); try { processBuilder.start(); } catch (Exception e) { System.err.println("ACLI Manager exec error: " + e); } } /** * Executes the given ACLICommand object. as a command line operation using * the Java ProcessBuilder class. Overloaded from previous function to accept a * sketch path. * @param command - The action/command to execute * @param sketchPath - The user selected path to the sketch being used. */ public void execute(ACLICommand command, String sketchPath) { params = new ArrayList<String>(); params.addAll(0, Arrays.asList(CMD_EXEC, ACLI_EXEC, ACLI_PATH)); params.addAll(command.params); switch(command) { case COMPILE_SKETCH: if(core.isEmpty() || port.isEmpty()) { //TODO - CP - Log error here return; } //Check that port and core are not empty //arduino-cli compile -b <core:name> -p <Port name> <Path/To/Sketch> break; case UPLOAD_SKETCH: if(port.isEmpty()) { //TODO - CP - Log error here return; } //arduino-cli upload -p <port name> <Path/To/Sketch> break; default: } processBuilder = new ProcessBuilder(); processBuilder.command(params); try { processBuilder.start(); } catch (Exception e) { System.err.println("ACLI Manager exec error: " + e); } } /** * Reads the board list file of attached arduino devices and parses * out the required port name and core type for an APM module. These are * requirements needed for arduino-cli to compile and upload a sketch. * @return - Whether or not the operation was successful. */ public boolean parseInfo() { //The APM shows up as an avr core. Here is a Regex target line example: //"COM4 Serial Port (USB) Arduino Mega or Mega 2560 arduino:avr:mega arduino:avr" Pattern pattern = Pattern.compile( "^COM\\d+\\s\\w{0,6}\\s\\w{0,4}\\s\\(?\\w{0,5}\\)?\\sArduino"); Matcher matcher; File file; boolean matchFound = false; //Checks for board list file = new File(BOARD_LIST_FILE); if(!file.exists()) { System.err.println( "ACLI Manager file error: Board list not found."); return false; } try { FileReader fileReader = new FileReader(BOARD_LIST_FILE); BufferedReader bufferedReader = new BufferedReader(fileReader); String temp; while((temp = bufferedReader.readLine()) != null) { matcher = pattern.matcher(temp); //If a match was found matchFound = matcher.find(); if(matchFound) { String[] substrings = temp.split(" "); port = "serial://" + substrings[0]; core = substrings[(substrings.length - 1)]; break; } } bufferedReader.close(); //If no match was found if(!matchFound) { System.err.println( "ACLI Manager file error: Failed to find port."); return false; } } catch(Exception e) { System.err.println("ACLI Manager file error: " + e); return false; } return true; } public String getErrorStr() { return errorString; } }
package edu.stuy.starlorn.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.awt.event.KeyEvent; public class Preferences { private static HashMap<String, Integer> _data; public static void put(String key, Integer data){ _data.put(key,data); } public static void load(int width, int height) { _data = new HashMap<String, Integer>(); try { String filename = "preferences.txt"; BufferedReader br = new BufferedReader(new FileReader(filename)); while (br.ready()) { String[] data = br.readLine().split(" : "); _data.put(data[0], Integer.parseInt(data[1])); } br.close(); loadDefault(width, height, false); // load in any missing options save(); } catch (FileNotFoundException e) { System.out.println("You don't seem to have a preferences file. I'll make one for you, then."); loadDefault(width, height, true); save(); } catch (IOException e) { e.printStackTrace(); } } public static void save() { String filename = "preferences.txt"; try { BufferedWriter b = new BufferedWriter(new FileWriter(filename)); for (String key : _data.keySet()) { b.write(key); b.write(" : "); b.write("" + _data.get(key)); b.newLine(); } b.close(); } catch (Exception e) { e.printStackTrace(); } } public static int getValue(String key) { return _data.get(key); } private static void loadDefault(int width, int height, boolean force) { if (force || !_data.containsKey("upKey")) _data.put("upKey", KeyEvent.VK_W); if (force || !_data.containsKey("downKey")) _data.put("downKey", KeyEvent.VK_S); if (force || !_data.containsKey("leftKey")) _data.put("leftKey", KeyEvent.VK_A); if (force || !_data.containsKey("rightKey")) _data.put("rightKey", KeyEvent.VK_D); if (force || !_data.containsKey("shootKey")) _data.put("shootKey", KeyEvent.VK_SPACE); if (force || !_data.containsKey("pauseKey")) _data.put("pauseKey", KeyEvent.VK_P); if (force || !_data.containsKey("fancyGraphics")) _data.put("fancyGraphics", 1); if (force || !_data.containsKey("devMode")) _data.put("devMode", 0); if (force || !_data.containsKey("screenWidth")) _data.put("screenWidth", width); if (force || !_data.containsKey("screenHeight")) _data.put("screenHeight", height); if (force || !_data.containsKey("fullscreen")) _data.put("fullScreen", 0); } }
package util; import java.io.File; import java.io.FileOutputStream; /** * @author ProActiveTeam * @version 1.0, 21 mars 2005 * @since ProActive 2.2 * */ public class buildManual { static FileOutputStream all; static String parent; public static void main(String[] args) throws java.io.IOException { if (args.length == 0) { System.out.println("Missing target files"); System.exit(-1); } parent = new File(args[0]).getParent(); File allFile; if (System.getProperty("proactive.guidedtour") != null) { allFile = new File(parent, "GuidedTour.html"); } else { allFile = new File(parent, "Manual.html"); } allFile.delete(); all = new FileOutputStream(allFile, true); for (int i = 0; i < args.length; i++) { filterFile(new File(args[i])); } all.close(); } private static void filterFile(java.io.File file) throws java.io.IOException { System.out.println("Processing " + file); byte[] b = getBytesFromInputStream(new java.io.FileInputStream(file)); String html = new String(b); html = removeMarkedLine(html); html = html + ("\n <p class=\"print\"/>"); html = changeImagesPath(html, file.getParent()); b = html.getBytes(); all.write(b, 0, b.length); //all.flush(); } /** * Returns an array of bytes containing the bytecodes for * the class represented by the InputStream * @param in the inputstream of the class file * @return the bytecodes for the class * @exception java.io.IOException if the class cannot be read */ private static byte[] getBytesFromInputStream(java.io.InputStream in) throws java.io.IOException { java.io.DataInputStream din = new java.io.DataInputStream(in); byte[] bytecodes = new byte[in.available()]; try { din.readFully(bytecodes); } finally { if (din != null) { din.close(); } } return bytecodes; } private static String removeMarkedLine(String html) { StringBuffer newHtml = new StringBuffer(html.length()); int currentIndex = 0; while (true) { int markerIndex = html.indexOf("~~~", currentIndex); if (markerIndex == -1) { break; } int endIndex = html.indexOf("-->", markerIndex); if (endIndex == -1) { break; } newHtml.append(html.substring(currentIndex, markerIndex)); currentIndex = endIndex + 3; } if (currentIndex < html.length()) { newHtml.append(html.substring(currentIndex, html.length())); } return newHtml.toString(); } private static String changeImagesPath(String html, String path) { StringBuffer newHtml = new StringBuffer(html.length()); int currentIndex = 0; while (true) { int srcimgIndex = html.indexOf("src=\"", currentIndex); if (srcimgIndex == -1) { break; } String image_path = html.substring(srcimgIndex + 5, html.indexOf("\"", srcimgIndex + 5)); if (!new File(parent, image_path).exists() && !image_path.startsWith("http")) { //the path might have changed since the global file is created in the parent dir if (path.length() <= parent.length()) { //we guess that just one level below can occur image_path = "../"+image_path; } else { String subpath = path.substring(parent.length() + 1); // String subdir = subpath.substring(0, // subpath.lastIndexOf("/")); image_path = subpath + "/" + image_path; //System.out.println(image_path); } } String pathWithoutExtension = image_path.substring(0, image_path.lastIndexOf(".")); String pdf_image_path = image_path.replaceFirst(pathWithoutExtension, pathWithoutExtension + "_pdf"); //System.out.println(pdf_image_path); //System.out.println(new File(parent, pdf_image_path).exists()); if (new File(parent, pdf_image_path).exists()) { newHtml.append(html.substring(currentIndex, srcimgIndex + 5)); newHtml.append(pdf_image_path); } else { newHtml.append(html.substring(currentIndex, srcimgIndex + 5)); newHtml.append(image_path); } currentIndex = html.indexOf("\"", srcimgIndex + 5); } if (currentIndex < html.length()) { newHtml.append(html.substring(currentIndex, html.length())); } return newHtml.toString(); } }
package etri.sdn.controller.protocol; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; import org.projectfloodlight.openflow.protocol.OFConfigFlags; import org.projectfloodlight.openflow.protocol.OFDescStatsReply; import org.projectfloodlight.openflow.protocol.OFDescStatsRequest; import org.projectfloodlight.openflow.protocol.OFEchoReply; import org.projectfloodlight.openflow.protocol.OFEchoRequest; import org.projectfloodlight.openflow.protocol.OFFactories; import org.projectfloodlight.openflow.protocol.OFFeaturesReply; import org.projectfloodlight.openflow.protocol.OFFeaturesRequest; import org.projectfloodlight.openflow.protocol.OFFlowAdd; import org.projectfloodlight.openflow.protocol.OFFlowModFlags; import org.projectfloodlight.openflow.protocol.OFHello; import org.projectfloodlight.openflow.protocol.OFHelloElem; import org.projectfloodlight.openflow.protocol.OFMessage; import org.projectfloodlight.openflow.protocol.OFPacketIn; import org.projectfloodlight.openflow.protocol.OFPortConfig; import org.projectfloodlight.openflow.protocol.OFPortDesc; import org.projectfloodlight.openflow.protocol.OFPortDescStatsReply; import org.projectfloodlight.openflow.protocol.OFPortDescStatsRequest; import org.projectfloodlight.openflow.protocol.OFPortReason; import org.projectfloodlight.openflow.protocol.OFPortState; import org.projectfloodlight.openflow.protocol.OFPortStatus; import org.projectfloodlight.openflow.protocol.OFSetConfig; import org.projectfloodlight.openflow.protocol.OFStatsReply; import org.projectfloodlight.openflow.protocol.OFStatsRequest; import org.projectfloodlight.openflow.protocol.OFStatsRequestFlags; import org.projectfloodlight.openflow.protocol.OFStatsType; import org.projectfloodlight.openflow.protocol.OFType; import org.projectfloodlight.openflow.protocol.OFVersion; import org.projectfloodlight.openflow.protocol.action.OFAction; import org.projectfloodlight.openflow.protocol.action.OFActionOutput; import org.projectfloodlight.openflow.protocol.instruction.OFInstruction; import org.projectfloodlight.openflow.protocol.instruction.OFInstructionApplyActions; import org.projectfloodlight.openflow.protocol.match.Match; import org.projectfloodlight.openflow.protocol.match.MatchField; import org.projectfloodlight.openflow.types.ArpOpcode; import org.projectfloodlight.openflow.types.EthType; import org.projectfloodlight.openflow.types.ICMPv4Code; import org.projectfloodlight.openflow.types.ICMPv4Type; import org.projectfloodlight.openflow.types.IPv4Address; import org.projectfloodlight.openflow.types.IpDscp; import org.projectfloodlight.openflow.types.IpEcn; import org.projectfloodlight.openflow.types.IpProtocol; import org.projectfloodlight.openflow.types.MacAddress; import org.projectfloodlight.openflow.types.Masked; import org.projectfloodlight.openflow.types.OFBufferId; import org.projectfloodlight.openflow.types.OFGroup; import org.projectfloodlight.openflow.types.OFPort; import org.projectfloodlight.openflow.types.OFVlanVidMatch; import org.projectfloodlight.openflow.types.TableId; import org.projectfloodlight.openflow.types.TransportPort; import org.projectfloodlight.openflow.types.VlanPcp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import etri.sdn.controller.MessageContext; import etri.sdn.controller.OFController; import etri.sdn.controller.protocol.io.Connection; import etri.sdn.controller.protocol.io.IOFSwitch; /** * This class is for handling Openflow protocol handshaking. * @author bjlee * */ public class OFProtocol { private static final Logger logger = LoggerFactory.getLogger(OFProtocol.class); public static final String STR_IN_PORT = "in_port"; public static final String STR_DL_DST = "dl_dst"; public static final String STR_DL_SRC = "dl_src"; public static final String STR_DL_TYPE = "dl_type"; public static final String STR_DL_VLAN = "dl_vlan"; public static final String STR_DL_VLAN_PCP = "dl_vpcp"; public static final String STR_NW_DST = "nw_dst"; public static final String STR_NW_SRC = "nw_src"; public static final String STR_NW_PROTO = "nw_proto"; public static final String STR_NW_TOS = "nw_tos"; public static final String STR_TP_DST = "tp_dst"; public static final String STR_TP_SRC = "tp_src"; /** * IOFSwitch to SwitchInformation map. */ private Map<IOFSwitch, SwitchInfo> switchInformations = new ConcurrentHashMap<IOFSwitch, SwitchInfo>(); /** * Port Number to PortInformation map. */ private Map<IOFSwitch, Map<OFPort, OFPortDesc>> portInformations = new ConcurrentHashMap<IOFSwitch, Map<OFPort, OFPortDesc>>(); /** * This field is used to exchange information with switch. */ private Map<IOFSwitch, Map<Long/*xid*/, Object>> responsesCache = new ConcurrentHashMap<IOFSwitch, Map<Long, Object>>(); /** * This field used to maintain the list of hello-failed switches. */ private Set<String> helloFailedSwitches = new ConcurrentSkipListSet<>(); /** * reference to OFController object. */ private OFController controller; /** * lock to synchronize. */ private Object portLock = new Object(); /** * Initialize OFProtocol object with OFController reference. * @param controller OFController object. */ public OFProtocol(OFController controller) { this.controller = controller; } /** * Get reference to OFController object. * @return OFController object. */ public OFController getController() { return this.controller; } /** * This method is used with two other companion methods: getResponseCacheItem and removeResponseCacheItem. * @param sw IOFSwitch object * @param xid transaction id * @param item object to set as a response for the transaction id */ public void setResponseCacheItem(IOFSwitch sw, long xid, Object item) { Map<Long, Object> rcache = this.responsesCache.get(sw); if ( rcache == null ) { rcache = new ConcurrentHashMap<Long, Object>(); this.responsesCache.put(sw, rcache); } rcache.put( xid, item ); } /** * This method is used with two other companion methods: setResponseCacheItem and removeResponseCacheItem. * @param sw IOFSwitch object * @param xid transaction id to get the response object * @return Object set by setResponseCacheItem as a response for the transaction id */ public Object getResponseCacheItem(IOFSwitch sw, long xid) { Map<Long, Object> rcache = this.responsesCache.get(sw); if ( rcache == null ) { return null; } return rcache.get(xid); } /** * This method is used with two other companion methods: setResponseCacheItem and getResponseCacheItem. * @param sw IOFSwitch object * @param xid transaction id to remove the response object */ public void removeResponseCacheItem(IOFSwitch sw, long xid) { Map<Long, Object> rcache = this.responsesCache.get(sw); if ( rcache == null ) { return; } rcache.remove(xid); } public SwitchInfo getSwitchInformation(IOFSwitch sw) { return this.switchInformations.get(sw); } public void setSwitchInformation(IOFSwitch sw, OFDescStatsReply r) { SwitchInfo swinfo = this.getSwitchInformation(sw); if ( swinfo == null ) { swinfo = new SwitchInfo(); this.switchInformations.put(sw, swinfo); } swinfo.setDescStatsReply(r); } public void setSwitchInformation(IOFSwitch sw, OFFeaturesReply r) { SwitchInfo swinfo = this.getSwitchInformation(sw); if ( swinfo == null ) { swinfo = new SwitchInfo(); this.switchInformations.put(sw, swinfo); } swinfo.setFeaturesReply(r); } public void setPortInformation(IOFSwitch sw, OFPortDesc desc) { Map<OFPort, OFPortDesc> inner = portInformations.get(sw); if ( inner == null ) { inner = new ConcurrentHashMap<OFPort, OFPortDesc>(); portInformations.put(sw, inner); } inner.put( desc.getPortNo(), desc ); } /** * Get port information by the port number. * If none existent, null is returned. * @param sw Switch to retrieve the port information * @param port port number to retrieve the information * @return PortInformation object */ public OFPortDesc getPortInformation(IOFSwitch sw, OFPort port) { Map<OFPort, OFPortDesc> inner = portInformations.get(sw); if ( inner == null ) { inner = new ConcurrentHashMap<OFPort, OFPortDesc>(); portInformations.put(sw, inner); } return inner.get(port); } /** * Get all PortInformation objects for the given switch * @param sw IOFSwitch object * @return Collection<PortInformation> */ public Collection<OFPortDesc> getPortInformations(IOFSwitch sw) { Map<OFPort, OFPortDesc> inner = portInformations.get(sw); if ( inner != null ) { return inner.values(); } return Collections.emptySet(); } /** * Get all the PortInformation objects for the given switch by datapath id * @param datapathId datapath id of the switch * @return Collection<PortInformation> */ public Collection<OFPortDesc> getPortInformations(long datapathId) { for ( IOFSwitch sw : portInformations.keySet() ) { if ( sw.getId() == datapathId ) { Map<OFPort, OFPortDesc> inner = portInformations.get(sw); if ( inner != null ) { return inner.values(); } } } return Collections.emptySet(); } /** * Remove a specific port information from the switch * @param sw IOFSwitch object * @param pi PortInformation object */ public void removePortInformation(IOFSwitch sw, OFPortDesc pi) { Map<OFPort, OFPortDesc> inner = portInformations.get(sw); if ( inner != null ) { inner.remove(pi.getPortNo()); } } /** * This method should be called after port number is correctly set up. * @param sw IOFSwitch object * @param name name of the port * @return Null can be returned if the item that you looking for is non-existent */ public OFPortDesc getPortInformation(IOFSwitch sw, String name) { Map<OFPort, OFPortDesc> inner = portInformations.get(sw); for ( OFPortDesc i : inner.values() ) { if ( i.getName().equals(name) ) { return i; } } return null; } /** * Callback called by underlying platform when a connection to a switch is established * @param conn Connection object * @return true if correctly handled (always) */ public boolean handleConnectedEvent(Connection conn) { InetSocketAddress peer = null; try { peer = (InetSocketAddress) conn.getClient().getRemoteAddress(); } catch (IOException e) { e.printStackTrace(); return false; } if ( this.helloFailedSwitches.contains(peer.getHostString()) ) { OFHello hello = OFFactories.getFactory(OFVersion.OF_10).hello(Collections.<OFHelloElem>emptyList()); conn.write(hello); this.helloFailedSwitches.remove( peer.getHostString() ); } else { OFHello hello = OFFactories.getFactory(OFVersion.OF_13).hello(Collections.<OFHelloElem>emptyList()); conn.write(hello); logger.debug("hello={}", hello); this.helloFailedSwitches.add( peer.getHostString() ); } return true; } /** * Callback called by underlying platform when a new OFMessage is received for a connection * @param conn Connection object * @param context MessageContext object created for the message * @param m OFMessage object to handle * @return true of correctly handled, false otherwise */ public boolean process(Connection conn, MessageContext context, OFMessage m) { if ( !conn.isConnected() ) { return false; } IOFSwitch sw = conn.getSwitch(); OFType t = m.getType(); switch (t) { case HELLO: // if HELLO received, we send features request. try { logger.debug("GOT HELLO({}) from {}", m, conn.getClient().getRemoteAddress().toString()); } catch (IOException e1) { return false; } // set the version number in the switch. if ( sw != null ) { sw.setVersion(m.getVersion()); } // now the hello is successfully exchanged, so we remove the peer address // from the helloFailedSwitches set. try { InetSocketAddress peer = (InetSocketAddress) conn.getClient().getRemoteAddress(); this.helloFailedSwitches.remove( peer.getHostString() ); } catch (IOException e) { logger.debug("conn.getClient().getRemoteAddress() failed"); e.printStackTrace(); return false; } // send feature request message. OFFeaturesRequest freq = OFFactories.getFactory(m.getVersion()).featuresRequest(); conn.write(freq); break; case ERROR: logger.error("GET ERROR : {}", m.toString()); return false; case ECHO_REQUEST: OFEchoReply.Builder builder = OFFactories.getFactory(m.getVersion()).buildEchoReply(); builder .setXid(m.getXid()) .setData( ((OFEchoRequest)m).getData() ); conn.write( builder.build() ); break; case FEATURES_REPLY: logger.debug("FEATURES_REPLY is recceived: {}", m.toString()); if ( sw == null ) return false; synchronized ( portLock ) { OFFeaturesReply fr = (OFFeaturesReply) m; sw.setId( fr.getDatapathId().getLong() ); this.setSwitchInformation(sw, fr); try { List<OFPortDesc> ports = fr.getPorts(); for ( OFPortDesc port: ports ) { setPortInformation(sw, port); } } catch ( UnsupportedOperationException e ) { // port list is not retrieved. // send port desc request message to retrieve all port list. // preq might be null if m.getVersion() == 0x01. But it's OK because // conn.write ignore null preq. OFPortDescStatsRequest preq = OFFactories .getFactory(m.getVersion()) .portDescStatsRequest(Collections.<OFStatsRequestFlags>emptySet()); conn.write(preq); } } if ( m.getVersion() != OFVersion.OF_10 ) { // set configuration parameters in the switch. // The switch does not reply to a request to set the configuration. // The flags indicate whether IP fragments should be treated normally, dropped, or reassembled. [jshin] OFSetConfig.Builder sc = OFFactories.getFactory(m.getVersion()).buildSetConfig(); sc .setFlags(EnumSet.<OFConfigFlags>of(OFConfigFlags.FRAG_NORMAL)) .setMissSendLen(0xffff); conn.write(sc.build()); } OFDescStatsRequest req = OFFactories.getFactory(m.getVersion()).descStatsRequest(EnumSet.noneOf(OFStatsRequestFlags.class)); conn.write(req); try { // send flow_mod to process table miss packets [jshin] OFInstructionApplyActions.Builder instruction = OFFactories.getFactory(m.getVersion()).instructions().buildApplyActions(); List<OFAction> actions = new LinkedList<OFAction>(); OFActionOutput.Builder action = OFFactories.getFactory(m.getVersion()).actions().buildOutput(); action.setPort(OFPort.CONTROLLER).setMaxLen(0xffff); actions.add( action.build() ); instruction.setActions(actions); List<OFInstruction> instructions = new LinkedList<OFInstruction>(); instructions.add( instruction.build() ); OFFlowAdd.Builder fm = OFFactories.getFactory(m.getVersion()).buildFlowAdd(); fm .setTableId(TableId.ZERO) .setIdleTimeout(0) .setHardTimeout(0) .setPriority(0) .setBufferId(OFBufferId.NO_BUFFER) .setOutGroup(OFGroup.ANY) .setOutPort(OFPort.ANY) .setMatch(OFFactories.getFactory(m.getVersion()).matchWildcardAll()) .setInstructions(instructions) .setFlags(EnumSet.of(OFFlowModFlags.SEND_FLOW_REM)); conn.write(fm.build()); } catch ( UnsupportedOperationException e ) { // we can just ignore this exception. } // now the handshaking is fully done. // therefore, we can safely register the switch object // into the switches map. This map is used heavily by // link discovery module. // Logger.stdout("adding a switch with id = " + conn.getSwitch().getId()); this.getController().addSwitch( conn.getSwitch().getId(), conn.getSwitch() ); this.deliverFeaturesReply( conn.getSwitch(), m.getXid(), (OFFeaturesReply) m ); if ( !getController().handleGeneric(conn, context, m) ) { return false; } break; case PORT_STATUS: if ( sw == null ) return false; OFPortStatus ps = (OFPortStatus) m; OFPortDesc phyport = (OFPortDesc) ps.getDesc(); if ( ps.getReason() == OFPortReason.DELETE ) { removePortInformation( sw, phyport ); } else if ( ps.getReason() == OFPortReason.MODIFY ) { removePortInformation( sw, phyport ); setPortInformation( sw, phyport ); } else { /* ps.getReason() == OFPortReason.ADD */ setPortInformation( sw, phyport ); } if ( !getController().handleGeneric(conn, context, m) ) { return false; } break; case STATS_REPLY: if ( sw == null ) return false; OFStatsReply stat = (OFStatsReply) m; if ( stat.getStatsType() == OFStatsType.PORT_DESC ) { OFPortDescStatsReply portDesc = (OFPortDescStatsReply) m; synchronized ( portLock ) { List<OFPortDesc> ports = portDesc.getEntries(); for ( OFPortDesc port: ports ) { setPortInformation(sw, port); } } deliverSwitchStatistics( sw, portDesc ); } else if ( stat.getStatsType() == OFStatsType.DESC ) { this.setSwitchInformation(sw, (OFDescStatsReply) stat); } else { deliverSwitchStatistics( sw, stat ); } break; case PACKET_IN: if ( sw.getStringId() == null ) { // FEATURES_REPLY is not received. return false; } if ( !getController().handlePacketIn(conn, context, m) ) { return false; } break; default: if ( !getController().handleGeneric(conn, context, m) ) { return false; } } return true; } /** * Modules that use IOFSwitch objects use this method to request statistics to the switch. * @param req OFStatisticsRequest object. */ public List<OFStatsReply> getSwitchStatistics(IOFSwitch sw, @SuppressWarnings("rawtypes") OFStatsRequest req) { List<OFStatsReply> response = new LinkedList<OFStatsReply>(); long xid = req.getXid(); this.setResponseCacheItem(sw, xid, response); if ( sw.getConnection() != null ) { sw.getConnection().write(req); synchronized ( response ) { try { response.wait(1000); } catch ( InterruptedException e ) { // does nothing. } finally { this.removeResponseCacheItem(sw, xid); } } return response; } return null; } private void deliverSwitchStatistics(IOFSwitch sw, OFStatsReply m) { Object response = getResponseCacheItem(sw, m.getXid()); if ( response == null ) { return; } if ( response instanceof List<?> ) { @SuppressWarnings("unchecked") List<OFStatsReply> rl = (List<OFStatsReply>) response; synchronized ( response ) { rl.add( m ); response.notifyAll(); } } } /** * Get OFFeaturesReply for the given switch. * @param sw IOFSwitch object * @return OFFeaturesReply object */ public OFFeaturesReply getFeaturesReply(IOFSwitch sw) { OFFeaturesRequest req = OFFactories.getFactory(sw.getVersion()).featuresRequest(); List<OFFeaturesReply> response = new LinkedList<OFFeaturesReply>(); this.setResponseCacheItem(sw, req.getXid(), response); sw.getConnection().write( req ); synchronized ( response ) { try { response.wait(1000); } catch ( InterruptedException e ) { // does nothing } finally { this.removeResponseCacheItem(sw, req.getXid()); } } if ( response.isEmpty() ) { return null; } else { return response.remove(0); } } private void deliverFeaturesReply(IOFSwitch sw, long xid, OFFeaturesReply reply) { Object response = this.getResponseCacheItem(sw, xid); if ( response == null ) { return; } if ( response instanceof List<?> ) { @SuppressWarnings("unchecked") List<OFFeaturesReply> rl = (List<OFFeaturesReply>) response; synchronized ( response ) { rl.add( reply ); response.notifyAll(); } } } /** * Get all the enabled ports * @param sw IOFSwitch object * @return Collection<OFPortDesc> */ public Collection<OFPortDesc> getEnabledPorts(IOFSwitch sw) { List<OFPortDesc> result = new ArrayList<OFPortDesc>(); Collection<OFPortDesc> allPorts = this.getPortInformations(sw); if ( allPorts == null ) return null; for (OFPortDesc port: allPorts) { if (portEnabled(port)) { result.add(port); } } return result; } /** * Get all the enabled port numbers * @param sw IOFSwitch object * @return Collection<Integer> */ public Collection<OFPort> getEnabledPortNumbers(IOFSwitch sw) { List<OFPort> result = new ArrayList<OFPort>(); Collection<OFPortDesc> allPorts = this.getPortInformations(sw); if ( allPorts == null ) return null; for (OFPortDesc port: allPorts) { if (portEnabled(port)) { result.add(port.getPortNo()); } } return result; } /** * Check if the given port is enabled * @param port OFPortDesc object * @return true if enabled, false otherwise */ public boolean portEnabled(OFPortDesc port) { if ( port == null ) return false; if (port.getConfig().contains(OFPortConfig.PORT_DOWN)) return false; Set<OFPortState> states = port.getState(); if (states.contains(OFPortState.LINK_DOWN) || states.contains(OFPortState.BLOCKED) ) return false; // Port STP state doesn't work with multiple VLANs, so ignore it for now //if ((port.getState() & OFPortState.STP_MASK.getValue()) == OFPortState.STP_BLOCK.getValue()) // return false; return true; } /** * Check if a given port is enabled * @param sw IOFSwitch object to which the port is bound * @param port port number (short) * @return true if enabled, false otherwise */ public boolean portEnabled(IOFSwitch sw, OFPort port) { OFPortDesc desc = this.getPortInformation(sw, port); if ( desc == null ) { return false; } return portEnabled(desc); } /** * Create an OFMatch object from the packet-in data. * This method is called by doDropFlow and doForwardFlow of Forwarding module, and processPacketInMesssage of LearningMac module. * @param sw IOFSwitch object * @param packetIn packet-in data array * @param inputPort input port (short) * @return OFMatch object */ public Match loadOFMatchFromPacket(IOFSwitch sw, OFPacketIn packetIn, OFPort inputPort, boolean l2only) { Match.Builder ret = OFFactories.getFactory(packetIn.getVersion()).buildMatch(); short scratch = 0; int transportOffset = 34; ByteBuffer packetDataBB = ByteBuffer.wrap(packetIn.getData()); int limit = packetDataBB.limit(); ret.setExact(MatchField.IN_PORT, inputPort); assert (limit >= 14); // dl dst byte[] eth_dst = new byte[6]; packetDataBB.get(eth_dst); ret.setExact(MatchField.ETH_DST, MacAddress.of(eth_dst)); // dl src byte[] eth_src = new byte[6]; packetDataBB.get(eth_src); ret.setExact(MatchField.ETH_SRC, MacAddress.of(eth_src)); // dl type short data_layer_type = packetDataBB.getShort(); ret.setExact(MatchField.ETH_TYPE, EthType.of(data_layer_type)); // has vlan if ( data_layer_type == (short) 0x8100 ) { scratch = packetDataBB.getShort(); if ( (0xfff & scratch) != 0 ) { ret.setExact(MatchField.VLAN_VID, OFVlanVidMatch.ofVlan((short)(0xfff & scratch))); ret.setExact(MatchField.VLAN_PCP, VlanPcp.of((byte)((0xe000 & scratch) >> 13))); } } if ( l2only ) { return ret.build(); } byte network_protocol = 0; switch (data_layer_type) { case 0x0800: // IPv4 // check packet length scratch = packetDataBB.get(); scratch = (short) (0xf & scratch); transportOffset = (packetDataBB.position() - 1) + (scratch * 4); // nw tos (dscp & ecn) scratch = packetDataBB.get(); ret.setExact(MatchField.IP_DSCP, IpDscp.of((byte)((0b11111100 & scratch) >> 2))); try { ret.setExact(MatchField.IP_ECN, IpEcn.of((byte)(0b00000011 & scratch))); } catch (UnsupportedOperationException u) { // does nothing } // nw protocol packetDataBB.position(packetDataBB.position() + 7); ret.setExact(MatchField.IP_PROTO, IpProtocol.of(packetDataBB.get())); // nw src & dst packetDataBB.position(packetDataBB.position() + 2); ret.setExact(MatchField.IPV4_SRC, IPv4Address.of(packetDataBB.getInt())); ret.setExact(MatchField.IPV4_DST, IPv4Address.of(packetDataBB.getInt())); packetDataBB.position(transportOffset); break; case 0x0806: // ARP // arp int arpPos = packetDataBB.position(); // opcode scratch = packetDataBB.getShort(arpPos + 6); ret.setExact(MatchField.ARP_OP, ArpOpcode.of(network_protocol = (byte) (0xff & scratch))); scratch = packetDataBB.getShort(arpPos + 2); // if ipv4 and addr len is 4 if (scratch == 0x800 && packetDataBB.get(arpPos + 5) == 4) { ret.setExact(MatchField.ARP_SPA, IPv4Address.of(packetDataBB.getInt(arpPos + 14))); ret.setExact(MatchField.ARP_TPA, IPv4Address.of(packetDataBB.getInt(arpPos + 24))); } break; default: break; } switch (network_protocol) { case 0x01: // icmp // ret.setExact(MatchField.ICMPV4_TYPE, ICMPv4Type.of(packetDataBB.get())); // ret.setExact(MatchField.ICMPV4_CODE, ICMPv4Code.of(packetDataBB.get())); break; case 0x06: // tcp ret.setExact(MatchField.TCP_SRC, TransportPort.of(0x0000ffff & packetDataBB.getShort())); ret.setExact(MatchField.TCP_DST, TransportPort.of(0x0000ffff & packetDataBB.getShort())); break; case 0x11: // udp ret.setExact(MatchField.UDP_SRC, TransportPort.of(0x0000ffff & packetDataBB.getShort())); ret.setExact(MatchField.UDP_DST, TransportPort.of(0x0000ffff & packetDataBB.getShort())); break; default: break; } return ret.build(); } private void setFromCIDR(Match.Builder match, String cidr, String which) throws IllegalArgumentException { String values[] = cidr.split("/"); String[] ip_str = values[0].split("\\."); int ip = 0; ip += Integer.valueOf(ip_str[0]) << 24; ip += Integer.valueOf(ip_str[1]) << 16; ip += Integer.valueOf(ip_str[2]) << 8; ip += Integer.valueOf(ip_str[3]); int prefix = 32; // all bits are fixed, by default if (values.length >= 2) prefix = Integer.valueOf(values[1]); int mask = 0x80000000 >> (prefix-1); if ( which.equals(STR_NW_DST) ) match.setMasked(MatchField.IPV4_DST, Masked.of(IPv4Address.of(ip), IPv4Address.of(mask))); else if ( which.equals(STR_NW_SRC) ) match.setMasked(MatchField.IPV4_SRC, Masked.of(IPv4Address.of(ip), IPv4Address.of(mask))); } public Match loadOFMatchFromString(IOFSwitch sw, String match) throws IllegalArgumentException { Match.Builder ret = OFFactories.getFactory(sw.getVersion()).buildMatch(); if (match.equals("") || match.equalsIgnoreCase("any") || match.equalsIgnoreCase("all") || match.equals("[]")) match = "OFMatch[]"; String[] tokens = match.split("[\\[,\\]]"); String[] values; int initArg = 0; if (tokens[0].equals("OFMatch")) initArg = 1; IpProtocol nw_proto = null; int i; for (i = initArg; i < tokens.length; i++) { values = tokens[i].split("="); if (values.length != 2) throw new IllegalArgumentException("Token " + tokens[i] + " does not have form 'key=value' parsing " + match); values[0] = values[0].toLowerCase(); // try to make this case insens if (values[0].equals(STR_IN_PORT) || values[0].equals("input_port")) { ret.setExact(MatchField.IN_PORT, OFPort.of(Integer.valueOf(values[1]))); } else if (values[0].equals(STR_DL_DST) || values[0].equals("eth_dst")) { ret.setExact(MatchField.ETH_DST, MacAddress.of(values[1])); } else if (values[0].equals(STR_DL_SRC) || values[0].equals("eth_src")) { ret.setExact(MatchField.ETH_SRC, MacAddress.of(values[1])); } else if (values[0].equals(STR_DL_TYPE) || values[0].equals("eth_type")) { if (values[1].startsWith("0x")) ret.setExact(MatchField.ETH_TYPE, EthType.of(Integer.valueOf(values[1].replaceFirst("0x", ""), 16))); else ret.setExact(MatchField.ETH_TYPE, EthType.of(Integer.valueOf(values[1]))); } else if (values[0].equals(STR_DL_VLAN)) { if (values[1].contains("0x")) { ret.setExact(MatchField.VLAN_VID, OFVlanVidMatch.ofVlan(Integer.valueOf(values[1].replaceFirst("0x", ""), 16))); } else { ret.setExact(MatchField.VLAN_VID, OFVlanVidMatch.ofVlan(Integer.valueOf(values[1]))); } } else if (values[0].equals(STR_DL_VLAN_PCP)) { ret.setExact(MatchField.VLAN_PCP, VlanPcp.of(Byte.valueOf(values[1]))); } else if (values[0].equals(STR_NW_DST) || values[0].equals("ip_dst")) setFromCIDR(ret, values[1], STR_NW_DST); else if (values[0].equals(STR_NW_SRC) || values[0].equals("ip_src")) setFromCIDR(ret, values[1], STR_NW_SRC); else if (values[0].equals(STR_NW_PROTO)) { ret.setExact(MatchField.IP_PROTO, nw_proto = IpProtocol.of(Short.valueOf(values[1]))); } else if (values[0].equals(STR_NW_TOS)) { byte scratch = Byte.valueOf(values[1]); ret.setExact(MatchField.IP_DSCP, IpDscp.of((byte)((0b11111100 & scratch) >> 2))); ret.setExact(MatchField.IP_ECN, IpEcn.of((byte)(0b00000011 & scratch))); } else if (values[0].equals(STR_TP_DST)) { if ( nw_proto != null ) { if ( nw_proto == IpProtocol.ICMP ) { ret.setExact(MatchField.ICMPV4_CODE, ICMPv4Code.of(Short.valueOf(values[1]))); } else if ( nw_proto == IpProtocol.TCP ) { ret.setExact(MatchField.TCP_DST, TransportPort.of(Short.valueOf(values[1]))); } else if ( nw_proto == IpProtocol.UDP ) { ret.setExact(MatchField.UDP_DST, TransportPort.of(Short.valueOf(values[1]))); } } } else if (values[0].equals(STR_TP_SRC)) { if ( nw_proto != null ) { if ( nw_proto == IpProtocol.ICMP ) { ret.setExact(MatchField.ICMPV4_TYPE, ICMPv4Type.of(Short.valueOf(values[1]))); } else if ( nw_proto == IpProtocol.TCP ) { ret.setExact(MatchField.TCP_SRC, TransportPort.of(Short.valueOf(values[1]))); } else if ( nw_proto == IpProtocol.UDP ) { ret.setExact(MatchField.UDP_SRC, TransportPort.of(Short.valueOf(values[1]))); } } } else throw new IllegalArgumentException("unknown token " + tokens[i] + " parsing " + match); } return ret.build(); } }
package jlibs.xml.xsd; import jlibs.core.graph.*; import jlibs.core.graph.navigators.FilteredTreeNavigator; import jlibs.core.graph.sequences.DuplicateSequence; import jlibs.core.graph.sequences.IterableSequence; import jlibs.core.graph.sequences.RepeatSequence; import jlibs.core.graph.visitors.ReflectionVisitor; import jlibs.core.graph.walkers.PreorderWalker; import jlibs.core.lang.ImpossibleException; import jlibs.core.lang.OS; import jlibs.core.util.CollectionUtil; import jlibs.core.util.RandomUtil; import jlibs.xml.Namespaces; import jlibs.xml.sax.XMLDocument; import jlibs.xml.xsd.display.XSDisplayFilter; import org.apache.xerces.xs.*; import org.xml.sax.SAXException; import javax.xml.namespace.QName; import javax.xml.transform.stream.StreamResult; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.*; /** * @author Santhosh Kumar T */ @SuppressWarnings({"unchecked"}) public class XSInstance{ public int minimumElementsGenerated = 2; public int maximumElementsGenerated = 2; public int minimumListItemsGenerated = 2; public int maximumListItemsGenerated = 2; public int maximumRecursionDepth = 1; public Boolean generateOptionalElements = Boolean.TRUE; public Boolean generateOptionalAttributes = Boolean.TRUE; public Boolean generateFixedAttributes = Boolean.TRUE; public Boolean generateDefaultAttributes = Boolean.TRUE; public boolean generateAllChoices = false; public boolean showContentModel = true; private int generateRepeatCount(int minOccurs, int maxOccurs){ if(minOccurs==0 && maxOccurs==1) //optional case return RandomUtil.randomBoolean(generateOptionalElements) ? 1 : 0; if(maxOccurs==-1) maxOccurs = Math.max(minOccurs, maximumElementsGenerated); int min, max; if(minimumElementsGenerated>maxOccurs || maximumElementsGenerated<minOccurs){ // doesn't intersect min = minOccurs; max = maxOccurs; }else { // find intersecting range min = Math.max(minOccurs, minimumElementsGenerated); max = Math.min(maxOccurs, maximumElementsGenerated); } return (min == max) ? min : RandomUtil.random(min, max); } public void generate(XSModel xsModel, QName rootElement, XMLDocument doc){ generate(xsModel, rootElement, doc, null, null); } public void generate(XSModel xsModel, QName rootElement, XMLDocument doc, String xsiSchemaLocation, String xsiNoNamespaceSchemaLocation){ String namespace = rootElement.getNamespaceURI(); XSElementDeclaration root = xsModel.getElementDeclaration(rootElement.getLocalPart(), namespace); if(root==null) throw new IllegalArgumentException("Element "+rootElement+" is not found"); Navigator navigator = new FilteredTreeNavigator(new XSSampleNavigator(xsModel), new XSDisplayFilter(){ protected boolean process(XSElementDeclaration elem){ return !elem.getAbstract(); } protected boolean process(XSTypeDefinition type){ return type.getTypeCategory()==XSTypeDefinition.COMPLEX_TYPE; } }); try{ doc.startDocument(); doc.declarePrefix(Namespaces.URI_XSI); if(!rootElement.getNamespaceURI().isEmpty()) doc.declarePrefix(rootElement.getPrefix(), rootElement.getNamespaceURI()); WalkerUtil.walk(new PreorderWalker(root, navigator), new XSSampleVisitor(doc, xsiSchemaLocation, xsiNoNamespaceSchemaLocation)); doc.endDocument(); }catch(SAXException ex){ throw new ImpossibleException(ex); } } private class XSSampleNavigator extends XSNavigator{ private XSModel xsModel; private XSSampleNavigator(XSModel xsModel){ this.xsModel = xsModel; } protected Sequence<XSTerm> process(XSParticle particle){ XSTerm term = particle.getTerm(); if(term instanceof XSModelGroup){ XSModelGroup group = (XSModelGroup)term; if(group.getCompositor()==XSModelGroup.COMPOSITOR_CHOICE){ XSObjectList particles = group.getParticles(); int count = particles.getLength(); if(!generateAllChoices && !particle.getMaxOccursUnbounded()) count = Math.min(count, particle.getMaxOccurs()); List<XSParticle> list = new ArrayList<XSParticle>(particles.getLength()); for(int i=0; i<particles.getLength(); i++) list.add((XSParticle)particles.item(i)); Collections.shuffle(list); return new IterableSequence(list.subList(0, count)); } } int maxOccurs = particle.getMaxOccursUnbounded() ? -1 : particle.getMaxOccurs(); int repeatCount = generateRepeatCount(particle.getMinOccurs(), maxOccurs); return new RepeatSequence<XSTerm>(super.process(particle), repeatCount); } protected Sequence<XSParticle> process(XSModelGroup modelGroup){ String str; switch(modelGroup.getCompositor()){ case XSModelGroup.COMPOSITOR_ALL : XSObjectList particles = modelGroup.getParticles(); List<XSParticle> list = new ArrayList<XSParticle>(particles.getLength()); for(int i=0; i<particles.getLength(); i++) list.add((XSParticle)particles.item(i)); Collections.shuffle(list); return new IterableSequence<XSParticle>(list); default: return super.process(modelGroup); } } protected Sequence process(XSElementDeclaration elem){ if(elem.getAbstract()){ XSObjectList substitutionGroup = xsModel.getSubstitutionGroup(elem); int rand = RandomUtil.random(0, substitutionGroup.getLength() - 1); return new DuplicateSequence(substitutionGroup.item(rand)); } if(elem.getTypeDefinition() instanceof XSComplexTypeDefinition){ XSComplexTypeDefinition complexType = (XSComplexTypeDefinition)elem.getTypeDefinition(); if(complexType.getAbstract()){ List<XSComplexTypeDefinition> subTypes = XSUtil.getSubTypes(xsModel, complexType); int rand = RandomUtil.random(0, subTypes.size() - 1); return new DuplicateSequence<XSTypeDefinition>(subTypes.get(rand)); } } return new DuplicateSequence<XSTypeDefinition>(elem.getTypeDefinition()); } } private class XSSampleVisitor extends ReflectionVisitor<Object, Processor<Object>>{ private XMLDocument doc; private String xsiSchemaLocation; private String xsiNoNamespaceSchemaLocation; private XSSampleVisitor(XMLDocument doc, String xsiSchemaLocation, String xsiNoNamespaceSchemaLocation){ this.doc = doc; this.xsiSchemaLocation = xsiSchemaLocation; this.xsiNoNamespaceSchemaLocation = xsiNoNamespaceSchemaLocation; } private void addXSILocations() throws SAXException{ if(doc.getDepth()==1){ if(xsiSchemaLocation!=null) doc.addAttribute(Namespaces.URI_XSI, "schemaLocation", xsiSchemaLocation); if(xsiNoNamespaceSchemaLocation!=null) doc.addAttribute(Namespaces.URI_XSI, "noNamespaceSchemaLocation", xsiNoNamespaceSchemaLocation); } } @Override protected Processor getDefault(Object elem){ return null; } protected Processor process(XSElementDeclaration elem){ return elemProcessor; } protected Processor process(XSWildcard wildcard){ return wildcardProcessor; } protected Processor process(XSComplexTypeDefinition complexType){ return complexTypeProcessor; } protected Processor process(XSAttributeUse attr){ return attrProcessor; } private Processor<XSElementDeclaration> elemProcessor = new Processor<XSElementDeclaration>(){ @Override public boolean preProcess(XSElementDeclaration elem, Path path){ if(path.getRecursionDepth()>2) return false; try{ if(showContentModel && elem.getTypeDefinition() instanceof XSComplexTypeDefinition){ XSComplexTypeDefinition complexType = (XSComplexTypeDefinition)elem.getTypeDefinition(); switch(complexType.getContentType()){ case XSComplexTypeDefinition.CONTENTTYPE_ELEMENT: case XSComplexTypeDefinition.CONTENTTYPE_MIXED: String contentModel = new XSContentModel().toString(complexType, doc.getNamespaceSupport()); boolean showContentModel = false; for(char ch: "?*+|;[".toCharArray()){ if(contentModel.indexOf(ch)!=-1){ showContentModel = true; break; } } if(showContentModel){ int depth = 0; while(true){ path = path.getParentPath(XSElementDeclaration.class); if(path!=null) depth++; else break; } doc.addText("\n"); for(int i=depth; i>0; i doc.addText(" "); doc.addComment(contentModel); doc.addText("\n"); for(int i=depth; i>0; i doc.addText(" "); } } } doc.startElement(elem.getNamespace(), elem.getName()); addXSILocations(); return true; }catch(SAXException ex){ throw new ImpossibleException(ex); } } @Override public void postProcess(XSElementDeclaration elem, Path path){ if(path.getRecursionDepth()>2) return; try{ XSSimpleTypeDefinition simpleType = null; if(elem.getTypeDefinition().getTypeCategory()==XSTypeDefinition.SIMPLE_TYPE) simpleType = (XSSimpleTypeDefinition)elem.getTypeDefinition(); else{ XSComplexTypeDefinition complexType = (XSComplexTypeDefinition)elem.getTypeDefinition(); if(complexType.getContentType()==XSComplexTypeDefinition.CONTENTTYPE_SIMPLE) simpleType = complexType.getSimpleType(); } if(simpleType!=null){ String sampleValue = null; if(sampleValueGenerator!=null) sampleValue = sampleValueGenerator.generateSampleValue(elem, simpleType); if(sampleValue==null) sampleValue = generateSampleValue(simpleType, elem.getName()); doc.addText(sampleValue); } doc.endElement(); }catch(SAXException ex){ throw new ImpossibleException(ex); } } }; private Processor<XSAttributeUse> attrProcessor = new Processor<XSAttributeUse>(){ @Override public boolean preProcess(XSAttributeUse attr, Path path){ try{ XSAttributeDeclaration decl = attr.getAttrDeclaration(); String sampleValue = null; switch(attr.getConstraintType()){ case XSConstants.VC_FIXED: if(RandomUtil.randomBoolean(generateFixedAttributes)) sampleValue = attr.getConstraintValue(); break; case XSConstants.VC_DEFAULT: if(RandomUtil.randomBoolean(generateDefaultAttributes)) sampleValue = attr.getConstraintValue(); break; default: if(attr.getRequired() || RandomUtil.randomBoolean(generateOptionalAttributes)){ if(sampleValueGenerator!=null) sampleValue = sampleValueGenerator.generateSampleValue(decl, decl.getTypeDefinition()); if(sampleValue==null) sampleValue = generateSampleValue(decl.getTypeDefinition(), decl.getName()); } } if(sampleValue!=null) doc.addAttribute(decl.getNamespace(), decl.getName(), sampleValue); return false; }catch(SAXException ex){ throw new ImpossibleException(ex); } } @Override public void postProcess(XSAttributeUse elem, Path path){} }; private Processor<XSComplexTypeDefinition> complexTypeProcessor = new Processor<XSComplexTypeDefinition>(){ @Override public boolean preProcess(XSComplexTypeDefinition complexType, Path path){ try{ XSElementDeclaration elem = (XSElementDeclaration)path.getParentPath().getElement(); XSComplexTypeDefinition elemType = (XSComplexTypeDefinition)elem.getTypeDefinition(); if(elemType.getAbstract()) doc.addAttribute(Namespaces.URI_XSI, "type", doc.toQName(complexType.getNamespace(), complexType.getName())); return true; }catch(SAXException ex){ throw new ImpossibleException(ex); } } @Override public void postProcess(XSComplexTypeDefinition complexType, Path path){} }; private Processor<XSWildcard> wildcardProcessor = new Processor<XSWildcard>(){ @Override public boolean preProcess(XSWildcard wildcard, Path path){ try{ String uri; switch(wildcard.getConstraintType()){ case XSWildcard.NSCONSTRAINT_ANY: uri = "anyNS"; break; case XSWildcard.NSCONSTRAINT_LIST: StringList list = wildcard.getNsConstraintList(); int rand = RandomUtil.random(0, list.getLength()-1); uri = list.item(rand); if(uri==null) uri = ""; // <xs:any namespace="##local"/> returns nsConstraintList with null break; case XSWildcard.NSCONSTRAINT_NOT: list = wildcard.getNsConstraintList(); List<String> namespaces = new ArrayList<String>(); for(int i=0; i<list.getLength(); i++) namespaces.add(list.item(i)); uri = "anyNS"; if(namespaces.contains(uri)){ for(int i=1;;i++){ if(!namespaces.contains(uri+i)){ uri += i; break; } } } break; default: throw new ImpossibleException(); } if(isAttribute(wildcard, path)) doc.addAttribute(uri, "anyAttr", "anyValue"); else{ doc.startElement(uri, "anyElement"); addXSILocations(); } return true; }catch(SAXException ex){ throw new ImpossibleException(ex); } } @Override public void postProcess(XSWildcard wildcard, Path path){ try{ if(!isAttribute(wildcard, path)) doc.endElement(); }catch(SAXException ex){ throw new ImpossibleException(ex); } } private boolean isAttribute(XSWildcard wildcard, Path path){ if(path.getParentPath().getElement() instanceof XSComplexTypeDefinition){ XSComplexTypeDefinition complexType = (XSComplexTypeDefinition)path.getParentPath().getElement(); if(complexType.getAttributeWildcard()==wildcard) return true; } return false; } }; private Map<String, Integer> counters = new HashMap<String, Integer>(); private static final String XSD_DATE_FORMAT = "yyyy-MM-dd"; private static final String XSD_TIME_FORMAT = "HH:mm:ss"; private String generateSampleValue(XSSimpleTypeDefinition simpleType, String hint){ if(simpleType.getBuiltInKind()==XSConstants.LIST_DT){ XSSimpleTypeDefinition itemType = simpleType.getItemType(); int len; XSFacet facet = getFacet(itemType, XSSimpleTypeDefinition.FACET_LENGTH); if(facet!=null) len = Integer.parseInt(facet.getLexicalFacetValue()); else{ int minOccurs = 0; facet = getFacet(itemType, XSSimpleTypeDefinition.FACET_MINLENGTH); if(facet!=null) minOccurs = Integer.parseInt(facet.getLexicalFacetValue()); int maxOccurs = -1; facet = getFacet(itemType, XSSimpleTypeDefinition.FACET_MAXLENGTH); if(facet!=null) maxOccurs = Integer.parseInt(facet.getLexicalFacetValue()); if(maxOccurs==-1) maxOccurs = Math.max(minOccurs, maximumListItemsGenerated); int min, max; if(minimumListItemsGenerated>maxOccurs || maximumListItemsGenerated<minOccurs){ // doesn't intersect min = minOccurs; max = maxOccurs; }else { // find intersecting range min = Math.max(minOccurs, minimumListItemsGenerated); max = Math.min(maxOccurs, maximumListItemsGenerated); } len = (min == max) ? min : RandomUtil.random(min, max); } List<String> enums = XSUtil.getEnumeratedValues(itemType); if(enums.isEmpty()){ StringBuilder buff = new StringBuilder(); while(len>0){ buff.append(" "); buff.append(generateSampleValue(itemType, hint)); len } return buff.toString().trim(); }else{ while(enums.size()<len) enums.addAll(new ArrayList<String>(enums)); Collections.shuffle(enums); StringBuilder buff = new StringBuilder(); while(len>0){ buff.append(" "); buff.append(enums.remove(0)); len } return buff.toString().trim(); } }else if(simpleType.getMemberTypes().getLength()>0){ XSObjectList members = simpleType.getMemberTypes(); int rand = RandomUtil.random(0, members.getLength()-1); return generateSampleValue((XSSimpleTypeDefinition)members.item(rand), hint); } List<String> enums = XSUtil.getEnumeratedValues(simpleType); if(!enums.isEmpty()) return enums.get(RandomUtil.random(0, enums.size()-1)); XSSimpleTypeDefinition builtInType = simpleType; while(!Namespaces.URI_XSD.equals(builtInType.getNamespace())) builtInType = (XSSimpleTypeDefinition)builtInType.getBaseType(); String name = builtInType.getName().toLowerCase(); if("boolean".equals(name)) return RandomUtil.randomBoolean() ? "true" : "false"; if("double".equals(name) || "decimal".equals(name) || "float".equals(name) || name.endsWith("integer") || name.endsWith("int") || name.endsWith("long") || name.endsWith("short") || name.endsWith("byte")) return new Range(simpleType).randomNumber(); if("date".equals(name)) return new SimpleDateFormat(XSD_DATE_FORMAT).format(new Date()); if("time".equals(name)) return new SimpleDateFormat(XSD_TIME_FORMAT).format(new Date()); if("datetime".equals(name)){ Date date = new Date(); return new SimpleDateFormat(XSD_DATE_FORMAT).format(date)+'T'+new SimpleDateFormat(XSD_TIME_FORMAT).format(date); }else{ Integer count = counters.get(hint); count = count==null ? 1 : ++count; counters.put(hint, count); String countStr = count.toString(); XSFacet facet = getFacet(simpleType, XSSimpleTypeDefinition.FACET_MINLENGTH); if(facet!=null){ int len = Integer.parseInt(facet.getLexicalFacetValue()); len -= hint.length(); len -= countStr.length(); if(len>0){ char ch[] = new char[len]; Arrays.fill(ch, '_'); hint += new String(ch); } } facet = getFacet(simpleType, XSSimpleTypeDefinition.FACET_MAXLENGTH); if(facet!=null){ int maxLen = Integer.parseInt(facet.getLexicalFacetValue()); int len = maxLen; len = hint.length() + countStr.length() - len; if(len>0){ if(hint.length()>len) hint = hint.substring(0, hint.length()-len); else{ hint = hint.substring(0, maxLen); countStr = ""; } } } return hint+countStr; } } private XSFacet getFacet(XSSimpleTypeDefinition simpleType, int kind){ XSObjectList facets = simpleType.getFacets(); for(int i=0; i<facets.getLength(); i++){ XSFacet facet = (XSFacet)facets.item(i); if(facet.getFacetKind()==kind) return facet; } return null; } class Range{ String minInclusive; String minExclusive; String maxInclusive; String maxExclusive; int totalDigits = -1; int fractionDigits = -1; Range(XSSimpleTypeDefinition simpleType){ XSFacet facet = getFacet(simpleType, XSSimpleTypeDefinition.FACET_MININCLUSIVE); if(facet!=null) minInclusive = facet.getLexicalFacetValue(); facet = getFacet(simpleType, XSSimpleTypeDefinition.FACET_MINEXCLUSIVE); if(facet!=null) minExclusive = facet.getLexicalFacetValue(); facet = getFacet(simpleType, XSSimpleTypeDefinition.FACET_MAXINCLUSIVE); if(facet!=null) maxInclusive = facet.getLexicalFacetValue(); facet = getFacet(simpleType, XSSimpleTypeDefinition.FACET_MAXEXCLUSIVE); if(facet!=null) maxExclusive = facet.getLexicalFacetValue(); facet = getFacet(simpleType, XSSimpleTypeDefinition.FACET_TOTALDIGITS); if(facet!=null) totalDigits = Integer.parseInt(facet.getLexicalFacetValue()); facet = getFacet(simpleType, XSSimpleTypeDefinition.FACET_FRACTIONDIGITS); if(facet!=null) fractionDigits = Integer.parseInt(facet.getLexicalFacetValue()); } private String applyDigits(Object obj){ String str = applyExponent(String.valueOf(obj)); String number, fraction; int dot = str.indexOf("."); if(dot==-1){ number = str; fraction = ""; }else{ number = str.substring(0, dot); fraction = str.substring(dot+1); } boolean negative = false; if(number.startsWith("-")){ negative = true; number = number.substring(1); } if(totalDigits>=0){ if(number.length()>totalDigits) number = number.substring(0, totalDigits); } if(fractionDigits>=0){ if(fraction.length()>fractionDigits) fraction = fraction.substring(0, fractionDigits); } str = negative ? "-" : ""; str += number; if(fraction.length()>0) str += '.' + fraction; return str; } private String applyExponent(String str){ int index = str.indexOf('E'); if(index==-1) return str; int exponent = Integer.parseInt(str.substring(index+(str.charAt(index+1)=='+'?2:1))); str = str.substring(0, index); boolean negative = false; if(str.charAt(0)=='-'){ negative = true; str = str.substring(1); } if(exponent!=0){ int dot = str.indexOf('.'); String beforeDot, afterDot; if(dot==-1){ beforeDot = str; afterDot = ""; }else{ beforeDot = str.substring(0, dot); afterDot = str.substring(dot+1); } if(exponent<0){ while(exponent!=0){ if(beforeDot.length()==1) beforeDot = "0"+beforeDot; afterDot = beforeDot.substring(beforeDot.length()-1)+afterDot; beforeDot = beforeDot.substring(0, beforeDot.length()-1); exponent++; } }else{ while(exponent!=0){ if(afterDot.isEmpty()) afterDot = "0"; beforeDot = beforeDot+afterDot.substring(0, 1); afterDot = afterDot.substring(1); exponent } } str = afterDot.isEmpty() ? beforeDot : beforeDot+"."+afterDot; } if(negative) str = "-"+str; return str; } public String randomNumber(){ if(fractionDigits==0){ // NOTE: min/max facets can have fractional part // even though fractionDigits is zero long min = Long.MIN_VALUE; if(minInclusive!=null) min = (long)Double.parseDouble(minInclusive); if(minExclusive!=null) min = (long)Double.parseDouble(minExclusive)+1; long max = Long.MAX_VALUE; if(maxInclusive!=null) max = (long)Double.parseDouble(maxInclusive); if(maxExclusive!=null) max = (long)Double.parseDouble(maxExclusive)-1; return applyDigits(RandomUtil.random(min, max)); }else{ double min = Double.MIN_VALUE; if(minInclusive!=null) min = Double.parseDouble(minInclusive); if(minExclusive!=null) min = Double.parseDouble(minExclusive)+1; double max = Double.MAX_VALUE; if(maxInclusive!=null) max = Double.parseDouble(maxInclusive); if(maxExclusive!=null) max = Double.parseDouble(maxExclusive)-1; return applyDigits(RandomUtil.random(min, max)); } } } } public void loadOptions(Properties options){ String value = options.getProperty("minimumElementsGenerated"); if(value!=null) minimumElementsGenerated = Integer.parseInt(value); value = options.getProperty("maximumElementsGenerated"); if(value!=null) maximumElementsGenerated = Integer.parseInt(value); value = options.getProperty("minimumElementsGenerated"); if(value!=null) minimumListItemsGenerated = Integer.parseInt(value); value = options.getProperty("maximumListItemsGenerated"); if(value!=null) maximumListItemsGenerated = Integer.parseInt(value); value = options.getProperty("maximumRecursionDepth"); if(value!=null) maximumRecursionDepth = Integer.parseInt(value); value = options.getProperty("generateOptionalElements"); if(value!=null) generateOptionalElements = "always".equals(value) ? Boolean.TRUE : ("never".equals(value) ? Boolean.FALSE : null); value = options.getProperty("generateOptionalAttributes"); if(value!=null) generateOptionalAttributes = "always".equals(value) ? Boolean.TRUE : ("never".equals(value) ? Boolean.FALSE : null); value = options.getProperty("generateFixedAttributes"); if(value!=null) generateFixedAttributes = "always".equals(value) ? Boolean.TRUE : ("never".equals(value) ? Boolean.FALSE : null); value = options.getProperty("generateOptionalElements"); if(value!=null) generateOptionalElements = "always".equals(value) ? Boolean.TRUE : ("never".equals(value) ? Boolean.FALSE : null); value = options.getProperty("generateDefaultAttributes"); if(value!=null) generateDefaultAttributes = "always".equals(value) ? Boolean.TRUE : ("never".equals(value) ? Boolean.FALSE : null); value = options.getProperty("generateAllChoices"); if(value!=null) generateDefaultAttributes = Boolean.parseBoolean(value); value = options.getProperty("showContentModel"); if(value!=null) showContentModel = Boolean.parseBoolean(value); } public SampleValueGenerator sampleValueGenerator; public static interface SampleValueGenerator{ public String generateSampleValue(XSElementDeclaration element, XSSimpleTypeDefinition simpleType); public String generateSampleValue(XSAttributeDeclaration attribute, XSSimpleTypeDefinition simpleType); } public static void main(String[] args) throws Exception{ if(args.length==0){ System.err.println("Usage:"); System.err.println("\txsd-instance."+(OS.get().isWindows()?"bat":"sh")+" <xsd-file> [root-element]"); System.err.println("Example:"); System.err.println("\txsd-instance."+(OS.get().isWindows()?"bat":"sh")+" purchase-order.xsd {http://jlibs.org}PurchaseOrder"); System.exit(1); } XSModel xsModel = new XSParser().parse(args[0]); QName rootElement = null; if(args.length>1) rootElement = QName.valueOf(args[1]); else{ List<XSElementDeclaration> elements = XSUtil.guessRootElements(xsModel); if(elements.size()==0){ System.err.println("no elements found in given xml schema"); System.exit(1); }else if(elements.size()==1){ XSElementDeclaration elem = elements.get(0); rootElement = XSUtil.getQName(elem); }else{ int i = 1; for(XSElementDeclaration elem: elements) System.err.println(i++ +": "+XSUtil.getQName(elem)); System.err.print("Select Root Element: "); String line = new BufferedReader(new InputStreamReader(System.in)).readLine(); XSElementDeclaration elem = elements.get(Integer.parseInt(line)-1); rootElement = XSUtil.getQName(elem); } } XSInstance xsInstance = new XSInstance(); InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("xsd-instance.properties"); if(is!=null) xsInstance.loadOptions(CollectionUtil.readProperties(is, null)); xsInstance.generate(xsModel, rootElement, new XMLDocument(new StreamResult(System.out), true, 4, null)); System.out.println(); } }
class VolleyTeam implements Comparable<Team>{ private String name; private int points; private int victories; private int balance; public VolleyTeam(String s){ this.name=s; } public addPoints(int i){ this.points+=i; } public addVictory(){ victories++ } public changeBalance(int i){ balance+=i; } public String toString(){ return this.name; } public boolean equals(Object o){ if (o instanceof Team){ Team t = (Team)o; return this.name.equals(t.name); }else return false; } public int compareTo(Team t){ //compares in descending order, the first has more points, more victories and/or more balance if (this.points!=t.points) return t.point-this.points; if (this.victories!=t.victories) return t.victories-this.points; return t.victories-this.victories; } public Team merge(Team t){ this.victories+=t.victories; this.addPoints(t.points); this.changeBalance(t.balance); return this; } } class LeagueGame{ VolleyTeam home, visitor; public LeagueGame(String s){ Scanner sc = new Scanner(s); String homeName = ""; while (sc.next!="vs"){ } } } public class Counter{ static Set<VolleyTeam> teams = new TreeSet<>(); public static void getGame(String s){ } }
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; import java.io.FileNotFoundException; import java.util.ArrayList; public class Crcheck{ private static String fileName; private static final int POLYNOMIAL = /*0xA053;*/0x0589; private static final int PRESET_VALUE = 0xFFFF; private static byte[] data = new byte[512]; private static int crc; private static byte[] receivedCrc = new byte[4]; private static ArrayList<Integer> elements64 = new ArrayList<>(); public Crcheck(){} public static byte[] XOR(byte[] a, byte[] b) { byte[] result = new byte[Math.min(a.length, b.length)]; for (int i = 0; i < result.length; i++) { result[i] = (byte) (((int) a[i]) ^ ((int) b[i])); } return result; } public static void displayTextFromFile()throws IOException{ System.out.println("CRC16 Input text from file\n"); BufferedReader in = new BufferedReader(new FileReader(fileName)); String line; while((line = in.readLine()) != null){ System.out.println(line); } in.close(); } public static void printMessage(byte data[], String s){ for (int i=0; i<data.length-4; i++ ) { System.out.print((char)data[i]); if ((i+1)%64==0) { System.out.print("\t-"+" "); System.out.print(String.format("0000%x", elements64.get((i+1)/64-1))+"\n"); } } System.out.print(s+Integer.toHexString(crc)); System.out.print("\t-"+" "+"0000"+Integer.toHexString(crc)+"\n"); System.out.println(); } public static void writeMessage(byte data[]){ String data2String = new String(data); String hex = Integer.toHexString(crc); int length = data2String.length(); data2String = data2String.substring(0, length-8) + "0000"+hex; //removing extension from the file... int x; for(x=fileName.length()-1 ; x>=0 && fileName.charAt(x)!='.' ; x fileName = fileName.substring(0,x); //System.out.println(fileName); File file = new File(fileName+".crc"); FileOutputStream fos = null; try{ fos = new FileOutputStream(file); fos.write(data2String.getBytes()); }catch(IOException i){ System.out.println(i); } finally { // close the streams using close method try { if (fos != null) { fos.close(); } } catch (IOException ioe) { System.out.println("Error while closing stream: " + ioe); } } } public static int crc16(byte[] data){ System.out.println("\nCRC 16 calculation progress:\n"); int current_crc_value = PRESET_VALUE; for (int i = 0; i < data.length-8; i++){ current_crc_value ^= data[i] & 0xFF; for (int j = 0; j < 8; j++ ) { if ((current_crc_value & 1) != 0) { current_crc_value = (current_crc_value >>> 1) ^ POLYNOMIAL; } else{ current_crc_value = current_crc_value >>> 1; } } if ((i+1)%64==0) { elements64.add((~current_crc_value & 0xFFFF)); //System.out.println(String.format("\nValue: \t%x", ~current_crc_value & 0xFFFF)); } } current_crc_value = ~current_crc_value; crc = current_crc_value & 0xFFFF; return current_crc_value & 0xFFFF; } public void setCRC(int crc){ //this.crc = crc; } public int getCRC(){ return this.crc; } public byte[] getData(){ return this.data; } public static byte[] readDataFile(File file){ try{ //System.out.println("Trying to reads "+fileName); InputStream is = new FileInputStream(file); long length = file.length(); if(length > Integer.MAX_VALUE){ throw new IOException("Could not completely read the file " + fileName + "as it is too long"); } int offset = 0; int numRead = 0; while (offset < data.length && (numRead=is.read(data, offset, data.length-offset)) >= 0 ){ offset += numRead; } for (int i=(int)length-1; i<504; i++ ) { data[i] = (int) '.'; } if (offset < data.length){ //throw new IOException("Could not completely read file " + fileName); } is.close(); }catch(FileNotFoundException f){ System.out.println("Please enter the correct file,,,,\nThere is no file named "+fileName); } catch(IOException e){ System.out.println(e); } //System.out.println("Inside method.."+data.length); return data; } public static byte[] readcrcFile(File file){ try{ //System.out.println("Trying to reads "+fileName); InputStream is = new FileInputStream(file); long length = file.length(); if(length > Integer.MAX_VALUE){ throw new IOException("Could not completely read the file " + fileName + "as it is too long"); } int offset = 0; int numRead = 0; while (offset < data.length && (numRead=is.read(data, offset, data.length-offset)) >= 0 ){ offset += numRead; } for (int i=508; i<512; i++ ) { receivedCrc[i-508] = data[i]; //System.out.println("Making receivedCrc part..."); //System.out.print((char)data[i]); } if (offset < data.length){ //throw new IOException("Could not completely read file " + fileName); } is.close(); }catch(FileNotFoundException f){ System.out.println("Please enter the correct file,,,,\nThere is no file named "+fileName); } catch(IOException e){ System.out.println(e); } //System.out.println("Inside method.."+data.length); return data; } //checksumcalculate method public void checksumCalculate()throws IOException{ //System.out.println("inside checksumCalculate() method"); byte[] ver = readDataFile(new File(fileName)); displayTextFromFile(); int ans = crc16(ver); printMessage(ver,"0000"); writeMessage(ver); } //checksum verify method public void checksumVerify()throws IOException{ //System.out.println("inside checksumVerify() method"); byte[] ver = readcrcFile(new File(fileName)); displayTextFromFile(); int ans = crc16(ver); String r = new String(receivedCrc); int received = Integer.parseInt(r,16); printMessage(ver,""); System.out.println("\nCRC16 result : 0000"+Integer.toHexString(ans)); if (ans == received) { System.out.println("\nCRC 16 verification passed"); } else{ System.out.println("\nCRC 16 verification failed"); } } //main method public static void main (String[] args)throws IOException{ if (args[0].charAt(0)=='c') { Crcheck c = new Crcheck(); //create object if the command line arguments are correct c.fileName = args[1]; c.checksumCalculate(); } else if (args[0].charAt(0)=='v') { Crcheck c = new Crcheck(); // create object if the command line arguments are correct c.fileName = args[1]; c.checksumVerify(); } else{ System.out.println("Please enter correct arguments "); System.out.println(" System.out.println("calculate checksum ==> $ crcheck [filename] c "); System.out.println("verify checksum ==> $ crcheck [filename] v "); System.out.println(" } } }
// ZeissZVIReader.java package loci.formats; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; /** * ZeissZVIReader is the file format reader for Zeiss ZVI files. * * @author Melissa Linkert linkert at cs.wisc.edu * @author Curtis Rueden ctrueden at wisc.edu */ public class ZeissZVIReader extends FormatReader { // -- Fields -- private LegacyZVIReader legacy; private Hashtable pixelData = new Hashtable(); private Hashtable headerData = new Hashtable(); private byte[] header; // general image header data private int nImages = 0; // number of images private byte[] tags; // tags data private int channels; // -- Fields used by parseDir -- private int counter = 0; // the number of the Image entry private int imageWidth = 0; private int imageHeight = 0; private int bytesPerPixel = 0; private int pixelFormat; private boolean needLegacy; private int width; private int height; private int bitsPerSample; private int dataLength; private int len; private int shuffle; // -- Constructor -- /** Constructs a new Zeiss ZVI reader. */ public ZeissZVIReader() { super("Zeiss Vision Image", "zvi"); } // -- FormatReader API methods -- /** Checks if the given block is a valid header for a Zeiss ZVI file. */ public boolean isThisType(byte[] block) { return OLEParser.isOLE(block); } /** Determines the number of images in the given Zeiss ZVI file. */ public int getImageCount(String id) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); if (needLegacy) return legacy.getImageCount(id); return (isRGB(id) && separated) ? (3 * nImages) : nImages; } /** Checks if the images in the file are RGB. */ public boolean isRGB(String id) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); if (needLegacy) return legacy.isRGB(id); return channels > 1; } /** Obtains the specified image from the given ZVI file, as a byte array. */ public byte[] openBytes(String id, int no) throws FormatException, IOException { if (!id.equals(currentId)) initFile(id); if (no < 0 || no >= getImageCount(id)) { throw new FormatException("Invalid image number: " + no); } if (needLegacy) return legacy.openBytes(id, no); // read image header data int c = (isRGB(id) && separated) ? 3 : 1; byte[] imageHead = (byte[]) headerData.get(new Integer(no / c)); if (imageHead != null) { int pointer = 14; int numBytes = DataTools.bytesToInt(imageHead, pointer, 2, true); pointer += 2 + numBytes; pointer += 2; width = DataTools.bytesToInt(imageHead, pointer, 4, true); pointer += 4 + 2; height = DataTools.bytesToInt(imageHead, pointer, 4, true); pointer += 4 + 2; int depth = DataTools.bytesToInt(imageHead, pointer, 4, true); pointer += 4 + 2; pixelFormat = DataTools.bytesToInt(imageHead, pointer, 4, true); pointer += 4 + 2; pointer += 6; // count field is always 0 int validBPP = DataTools.bytesToInt(imageHead, pointer, 4, true); pointer += 4 + 2; // read image bytes and convert to floats pointer = 0; int numSamples = width*height; bitsPerSample = validBPP; switch (pixelFormat) { case 1: channels = 3; break; case 2: channels = 4; break; case 3: channels = 1; break; case 4: channels = 1; break; case 6: channels = 1; break; case 8: channels = 3; break; default: channels = 1; } if ((width > imageWidth) && (imageWidth > 0)) { width = imageWidth; height = imageHeight; bitsPerSample = bytesPerPixel * 8; } } else { width = imageWidth; height = imageHeight; bitsPerSample = bytesPerPixel * 8; } byte[] px = (byte[]) pixelData.get(new Integer(no / c)); byte[] tempPx = new byte[px.length]; if (bitsPerSample > 64) { bitsPerSample = 8; } int bpp = bitsPerSample / 8; // reverse each row int mul = 0; switch (bpp) { case 1: mul = (int) (width * 0.3); break; case 2: mul = 60; break; case 6: mul = (int) (width * 0.32); break; } mul *= bpp; for (int k=0; k<height; k++) { System.arraycopy(px, k*bpp*imageWidth, tempPx, (k+1)*bpp*imageWidth - mul, mul); System.arraycopy(px, k*bpp*imageWidth+mul, tempPx, k*bpp*imageWidth, bpp*imageWidth - mul); } // reverse row order if ((bitsPerSample / 8) % 3 != 0 && (bitsPerSample != 8)) { px = new byte[tempPx.length]; for (int i=0; i<height; i++) { for (int j=0; j<bpp*width; j++) { px[(bpp * width * i) + j] = tempPx[j + (bpp * width * (height - 1 - i))]; } } tempPx = px; } if (!isRGB(id) || !separated) { return tempPx; } else { return ImageTools.splitChannels(tempPx, 3, false, true)[no % 3]; } } /** Obtains the specified image from the given Zeiss ZVI file. */ public BufferedImage openImage(String id, int no) throws FormatException, IOException { if (needLegacy) return legacy.openImage(id, no); byte[] data = openBytes(id, no); int bpp = bitsPerSample / 8; if (bpp == 0) bpp = bytesPerPixel; if (bpp > 4) bpp /= 3; return ImageTools.makeImage(data, width, height, (!isRGB(id) || separated) ? 1 : 3, true, bpp, false); } /** Closes any open files. */ public void close() throws FormatException, IOException { header = null; tags = null; pixelData = null; headerData = null; } /** Initializes the given Zeiss ZVI file. */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); legacy = new LegacyZVIReader(); OLEParser parser = new OLEParser(id); parser.parse(0); Vector[] files = parser.getFiles(); headerData = new Hashtable(); pixelData = new Hashtable(); int largest = 0; int largestIndex = 0; int nextItem = 0; Vector itemNames = parser.getNames(); for (int i=0; i<files[0].size(); i++) { byte[] data = (byte[]) files[1].get(i); if (data.length > largest) largestIndex = i; String pathName = ((String) files[0].get(i)).trim(); pathName = DataTools.stripString(pathName); boolean isContents = pathName.endsWith("Contents"); boolean isImage = pathName.endsWith("Image"); try { if (((isContents && ((pathName.indexOf("Item") != -1) || pathName.indexOf("Image") != -1) && data.length > 6000)) || (data.length == dataLength)) { header = data; while ((dataLength != 0) && (data.length < dataLength) && isContents && ((pathName.indexOf("Item") != -1) || pathName.indexOf("Image") != -1)) { i++; data = (byte[]) files[1].get(i); if (data.length > largest) largestIndex = i; pathName = ((String) files[0].get(i)).trim(); pathName = DataTools.stripString(pathName); isContents = pathName.endsWith("Contents"); } int imageNum = 0; if (pathName.indexOf("Item") != -1) { String num = pathName.substring(pathName.lastIndexOf("Item") + 5, pathName.lastIndexOf(")")); imageNum = Integer.parseInt(num); } if (nextItem < itemNames.size()) { String num = ((String) itemNames.get(nextItem)).trim(); if (num.length() > 1) num = DataTools.stripString(num); int n = Integer.parseInt(num); // choose whether to use imageNum or n if (n != imageNum) { if (pixelData.containsKey(new Integer(imageNum))) { imageNum = n; } } if (pathName.indexOf("Item") != -1) { num = pathName.substring(0, pathName.lastIndexOf("Item")); while (pixelData.containsKey(new Integer(imageNum)) && (num.indexOf("Item") != -1)) { String s = num.substring(num.lastIndexOf("Item") + 5, num.lastIndexOf(")")); imageNum = Integer.parseInt(s); num = num.substring(0, num.lastIndexOf("Item")); } } // if we *still* don't find a valid key, give up and use // the legacy reader if (pixelData.containsKey(new Integer(imageNum))) { if (legacy.getImageCount(id) == 1) break; needLegacy = true; legacy.initFile(id); return; } nextItem++; } int byteCount = 2; byteCount += 4; // version field byteCount += 6; // type field byteCount += 2; int numBytes = DataTools.bytesToInt(header, byteCount, 2, true); byteCount += 2 + numBytes; byteCount += 2; imageWidth = DataTools.bytesToInt(header, byteCount, 4, true); byteCount += 6; imageHeight = DataTools.bytesToInt(header, byteCount, 4, true); byteCount += 4; byteCount += 6; // depth byteCount += 6; // pixel format byteCount += 6; // count byteCount += 2; bitsPerSample = DataTools.bytesToInt(header, byteCount, 4, true); byteCount += 4; numBytes = DataTools.bytesToInt(header, byteCount, 2, true); byteCount += 2 + numBytes; // plugin CLSID byteCount += 38; // not sure what this is for byteCount += 2; numBytes = DataTools.bytesToInt(header, byteCount, 4, true); byteCount += 4 + numBytes; // layers byteCount += 2; numBytes = DataTools.bytesToInt(header, byteCount, 4, true); byteCount += 4 + numBytes; // scaling byteCount += 2; numBytes = DataTools.bytesToInt(header, byteCount, 2, true); byteCount += 2 + numBytes; // root folder name byteCount += 2; numBytes = DataTools.bytesToInt(header, byteCount, 2, true); byteCount += 2 + numBytes; // display item name byteCount += 28; // streamed header data // get pixel data if (header.length > byteCount) { byte[] head = new byte[byteCount]; System.arraycopy(header, 0, head, 0, head.length); headerData.put(new Integer(imageNum), (Object) head); byte[] px = new byte[header.length - byteCount]; System.arraycopy(header, byteCount, px, 0, px.length); if (!pixelData.containsKey(new Integer(imageNum))) { shuffle = parser.shuffle(); // nasty special case...I pity the person who finds a bug in this if (shuffle > 0) { byte[] chunkOne = new byte[shuffle]; byte[] chunkTwo = new byte[parser.length() - shuffle + 11700]; System.arraycopy(px, 0, chunkOne, 0, chunkOne.length); System.arraycopy(px, chunkOne.length, chunkTwo, 0, chunkTwo.length); byte[] tct = new byte[chunkOne.length]; int bpp = bitsPerSample / 8; int mul = (int) (imageWidth - (imageWidth * 0.01)); mul *= bpp; mul += 2; for (int k=0; k<(chunkOne.length / (bpp*imageWidth)); k++) { System.arraycopy(chunkOne, k*bpp*imageWidth, tct, (k+1)*bpp*imageWidth - mul, mul); System.arraycopy(chunkOne, k*bpp*imageWidth+mul, tct, k*bpp*imageWidth, bpp*imageWidth - mul); } chunkOne = tct; byte[] tco = new byte[chunkTwo.length]; mul = (int) (imageWidth * 0.14); mul *= bpp; for (int k=0; k<(chunkTwo.length / (bpp*imageWidth)); k++) { System.arraycopy(chunkTwo, k*bpp*imageWidth, tco, (k+1)*bpp*imageWidth - mul, mul); System.arraycopy(chunkTwo, k*bpp*imageWidth+mul, tco, k*bpp*imageWidth, bpp*imageWidth - mul); } chunkTwo = tco; px = new byte[px.length]; System.arraycopy(chunkTwo, 0, px, 0, chunkTwo.length); System.arraycopy(chunkOne, 0, px, chunkTwo.length, chunkOne.length); // now we have to shift the whole array to the right by // 0.01 * width pixels mul = imageWidth - ((int) (imageWidth * 0.01)); mul *= bpp; byte[] tmp = new byte[px.length]; for (int k=0; k<imageHeight; k++) { System.arraycopy(px, k*bpp*imageWidth, tmp, (k+1)*bpp*imageWidth - mul, mul); System.arraycopy(px, k*bpp*imageWidth+mul, tmp, k*bpp*imageWidth, bpp*imageWidth - mul); } px = tmp; } pixelData.put(new Integer(imageNum), (Object) px); dataLength = px.length + head.length; nImages++; } } else break; } else if (isContents && isImage) { // we've found the header data header = data; int pointer = 14; int length = DataTools.bytesToInt(header, pointer, 2, true); pointer += 4 + length; imageWidth = DataTools.bytesToInt(header, pointer, 4, true); pointer += 6; imageHeight = DataTools.bytesToInt(header, pointer, 4, true); pointer += 6; pointer += 6; pixelFormat = DataTools.bytesToInt(header, pointer, 4, true); pointer += 6; switch (pixelFormat) { case 1: bytesPerPixel = 3; break; case 2: bytesPerPixel = 4; break; case 3: bytesPerPixel = 1; break; case 4: bytesPerPixel = 2; break; case 6: bytesPerPixel = 4; break; case 8: bytesPerPixel = 6; break; default: bytesPerPixel = 1; } if ((bytesPerPixel % 2) != 0) channels = 3; } else if (pathName.endsWith("Tags") && pathName.startsWith("Root Entry")) { // the main tags stream tags = data; } } catch (Exception e) { } } if (nImages == 0) { // HACK // just grab the largest file header = (byte[]) files[1].get(largestIndex); String pathName = (String) files[0].get(largestIndex); int imageNum = 0; if (pathName.indexOf("Item") != -1) { String num = pathName.substring(pathName.indexOf("Item") + 5, pathName.indexOf(")")); imageNum = Integer.parseInt(num); } int byteCount = 166; byteCount += 2; imageWidth = DataTools.bytesToInt(header, byteCount, 4, true); byteCount += 6; imageHeight = DataTools.bytesToInt(header, byteCount, 4, true); byteCount += 4; byteCount += 6; // depth byteCount += 6; // pixel format byteCount += 6; // count byteCount += 2; bytesPerPixel = DataTools.bytesToInt(header, byteCount, 4, true) / 8; byteCount += 4; int numBytes = DataTools.bytesToInt(header, byteCount, 2, true); byteCount += 2 + numBytes; // plugin CLSID byteCount += 38; // not sure what this is for byteCount += 2; numBytes = DataTools.bytesToInt(header, byteCount, 4, true); byteCount += 4 + numBytes; // layers byteCount += 2; numBytes = DataTools.bytesToInt(header, byteCount, 4, true); byteCount += 4 + numBytes; // scaling byteCount += 2; numBytes = DataTools.bytesToInt(header, byteCount, 2, true); byteCount += 2 + numBytes; // root folder name byteCount += 2; numBytes = DataTools.bytesToInt(header, byteCount, 2, true); byteCount += 2 + numBytes; // display item name byteCount += 28; // streamed header data // get pixel data if (header.length > byteCount) { byte[] head = new byte[byteCount]; System.arraycopy(header, 0, head, 0, head.length); headerData.put(new Integer(nImages), (Object) head); byte[] px = new byte[header.length - byteCount]; System.arraycopy(header, byteCount, px, 0, px.length); pixelData.put(new Integer(nImages), (Object) px); nImages++; } } initMetadata(); } // -- Helper methods -- /** Populates the metadata hashtable. */ protected void initMetadata() { // parse the "header" byte array // right now we're using header data from an image item if (header == null) return; int pt = 14; int numBytes = DataTools.bytesToInt(header, pt, 2, true); pt += 2 + numBytes; pt += 2; metadata.put("ImageWidth", new Integer(DataTools.bytesToInt(header, pt, 4, true))); pt += 6; metadata.put("ImageHeight", new Integer(DataTools.bytesToInt(header, pt, 4, true))); pt += 6; pt += 6; int pixel = DataTools.bytesToInt(header, pt, 4, true); pt += 6; String fmt; switch (pixel) { case 1: fmt = "8-bit RGB Triple (B, G, R)"; break; case 2: fmt = "8-bit RGB Quad (B, G, R, A)"; break; case 3: fmt = "8-bit grayscale"; break; case 4: fmt = "16-bit signed integer"; break; case 5: fmt = "32-bit integer"; break; case 6: fmt = "32-bit IEEE float"; break; case 7: fmt = "64-bit IEEE float"; break; case 8: fmt = "16-bit unsigned RGB Triple (B, G, R)"; break; case 9: fmt = "32-bit RGB Triple (B, G, R)"; break; default: fmt = "unknown"; } metadata.put("PixelFormat", fmt); metadata.put("NumberOfImages", new Integer(nImages)); pt += 6; metadata.put("BitsPerPixel", new Integer(DataTools.bytesToInt(header, pt, 4, true))); pt += 6; if (ome != null) { String type; switch (pixel) { case 1: type = "Uint8"; break; case 2: type = "Uint8"; break; case 3: type = "Uint8"; break; case 4: type = "int16"; break; case 5: type = "Uint32"; break; case 6: type = "float"; break; case 7: type = "float"; break; case 8: type = "Uint16"; break; case 9: type = "Uint32"; break; default: type = "Uint8"; } Integer sizeX = (Integer) metadata.get("ImageWidth"); Integer sizeY = (Integer) metadata.get("ImageHeight"); OMETools.setPixels(ome, sizeX, sizeY, new Integer(1), // SizeZ new Integer(1), // SizeC new Integer(nImages), // SizeT type, // PixelType null, // BigEndian "XYZTC"); // DimensionOrder OMETools.setImageName(ome, currentId); } // parse the "tags" byte array if (tags == null) return; pt = 0; pt += 16; int w = DataTools.bytesToInt(tags, pt, 2, true); pt += 2; int version = DataTools.bytesToInt(tags, pt, 4, true); pt += 4; w = DataTools.bytesToInt(tags, pt, 2, true); pt += 2; int numTags = DataTools.bytesToInt(tags, pt, 4, true); pt += 4; for (int i=0; i<numTags; i++) { // we have duples of {value, ID} form // first read the data type int type = DataTools.bytesToInt(tags, pt, 2, true); pt += 2; // read in appropriate amount of data Object data; int length; switch (type) { case 2: // VT_I2: 16 bit integer data = new Integer(DataTools.bytesToInt(tags, pt, 2, true)); pt += 2; break; case 3: // VT_I4: 32 bit integer data = new Integer(DataTools.bytesToInt(tags, pt, 4, true)); pt += 4; break; case 4: // VT_R4: 32 bit float data = new Float(Float.intBitsToFloat( DataTools.bytesToInt(tags, pt, 4, true))); pt += 4; break; case 5: // VT_R8: 64 bit float data = new Double(Double.longBitsToDouble( DataTools.bytesToLong(tags, pt, 8, true))); pt += 8; break; case 7: data = new Double(Double.longBitsToDouble( DataTools.bytesToLong(tags, pt, 8, true))); pt += 8; break; case 8: // VT_BSTR: streamed storage object length = DataTools.bytesToInt(tags, pt, 2, true); pt += 2; data = new String(tags, pt, length); pt += length; break; case 11: // VT_BOOL: 16 bit integer (true if !0) int temp = DataTools.bytesToInt(tags, pt, 4, true); data = new Boolean(temp != 0); pt += 4; break; case 16: // VT_I1: 8 bit integer data = new Integer(DataTools.bytesToInt(tags, pt, 1, true)); pt += 1; break; case 17: // VT_UI1: 8 bit unsigned integer data = new Integer(DataTools.bytesToInt(tags, pt, 1, true)); pt += 1; break; case 18: // VT_UI2: 16 bit unsigned integer data = new Integer(DataTools.bytesToInt(tags, pt, 2, true)); pt += 2; break; case 19: // VT_UI4: 32 bit unsigned integer data = new Integer(DataTools.bytesToInt(tags, pt, 4, true)); pt += 4; break; case 20: // VT_I8: 64 bit integer data = new Integer(DataTools.bytesToInt(tags, pt, 8, true)); pt += 8; break; case 21: // VT_UI8: 64 bit unsigned integer data = new Integer(DataTools.bytesToInt(tags, pt, 8, true)); pt += 8; break; case 65: // VT_BLOB: binary data length = DataTools.bytesToInt(tags, pt, 4, true); pt += 4; try { data = new String(tags, pt, length); } catch (Throwable e) { data = null; } pt += length; break; case 68: // VT_STORED_OBJECT: streamed storage object length = DataTools.bytesToInt(tags, pt, 2, true); pt += 2; data = new String(tags, pt, length); pt += length; break; default: pt += 4; data = null; } // read in tag ID int tagID = DataTools.bytesToInt(tags, pt, 4, true); pt += 4; // really ugly switch statement to put metadata in hashtable if (data != null) { switch (tagID) { case 222: metadata.put("Compression", data); break; case 258: metadata.put("BlackValue", data); // if (ome != null) { // OMETools.setAttribute(ome, // "Grey Channel", "BlackLevel", "" + data); break; case 259: metadata.put("WhiteValue", data); // if (ome != null) { // OMETools.setAttribute(ome, // "Grey Channel", "WhiteLevel", "" + data); break; case 260: metadata.put("ImageDataMappingAutoRange", data); break; case 261: metadata.put("Thumbnail", data); break; case 262: metadata.put("GammaValue", data); // if (ome != null) { // OMETools.setAttribute(ome, // "Grey Channel", "GammaLevel", "" + data); break; case 264: metadata.put("ImageOverExposure", data); break; case 265: metadata.put("ImageRelativeTime1", data); break; case 266: metadata.put("ImageRelativeTime2", data); break; case 267: metadata.put("ImageRelativeTime3", data); break; case 268: metadata.put("ImageRelativeTime4", data); break; case 515: metadata.put("ImageWidth", data); break; case 516: metadata.put("ImageHeight", data); break; case 518: metadata.put("PixelType", data); break; case 519: metadata.put("NumberOfRawImages", data); break; case 520: metadata.put("ImageSize", data); break; case 523: metadata.put("Acquisition pause annotation", data); break; case 530: metadata.put("Document Subtype", data); break; case 531: metadata.put("Acquisition Bit Depth", data); break; case 534: metadata.put("Z-Stack single representative", data); break; case 769: metadata.put("Scale Factor for X", data); break; case 770: metadata.put("Scale Unit for X", data); break; case 771: metadata.put("Scale Width", data); break; case 772: metadata.put("Scale Factor for Y", data); break; case 773: metadata.put("Scale Unit for Y", data); break; case 774: metadata.put("Scale Height", data); break; case 775: metadata.put("Scale Factor for Z", data); break; case 776: metadata.put("Scale Unit for Z", data); break; case 777: metadata.put("Scale Depth", data); break; case 778: metadata.put("Scaling Parent", data); break; case 1001: metadata.put("Date", data); if (ome != null) OMETools.setCreationDate(ome, data.toString()); break; case 1002: metadata.put("code", data); break; case 1003: metadata.put("Source", data); break; case 1004: metadata.put("Message", data); break; case 1026: metadata.put("8-bit acquisition", data); break; case 1027: metadata.put("Camera Bit Depth", data); break; case 1029: metadata.put("MonoReferenceLow", data); break; case 1030: metadata.put("MonoReferenceHigh", data); break; case 1031: metadata.put("RedReferenceLow", data); break; case 1032: metadata.put("RedReferenceHigh", data); break; case 1033: metadata.put("GreenReferenceLow", data); break; case 1034: metadata.put("GreenReferenceHigh", data); break; case 1035: metadata.put("BlueReferenceLow", data); break; case 1036: metadata.put("BlueReferenceHigh", data); break; case 1041: metadata.put("FrameGrabber Name", data); break; case 1042: metadata.put("Camera", data); break; case 1044: metadata.put("CameraTriggerSignalType", data); break; case 1045: metadata.put("CameraTriggerEnable", data); break; case 1046: metadata.put("GrabberTimeout", data); break; case 1281: metadata.put("MultiChannelEnabled", data); if (((Integer) data).intValue() == 1 && ome != null) { OMETools.setSizeC(ome, nImages); OMETools.setSizeT(ome, 1); OMETools.setDimensionOrder(ome, "XYCZT"); } break; case 1282: metadata.put("MultiChannel Color", data); break; case 1283: metadata.put("MultiChannel Weight", data); break; case 1284: metadata.put("Channel Name", data); break; case 1536: metadata.put("DocumentInformationGroup", data); break; case 1537: metadata.put("Title", data); if (ome != null) OMETools.setImageName(ome, data.toString()); break; case 1538: metadata.put("Author", data); if (ome != null) { // populate Experimenter element String name = data.toString(); if (name != null) { String firstName = null, lastName = null; int ndx = name.indexOf(" "); if (ndx < 0) lastName = name; else { firstName = name.substring(0, ndx); lastName = name.substring(ndx + 1); } OMETools.setExperimenter(ome, firstName, lastName, null, null, null, null); } } break; case 1539: metadata.put("Keywords", data); break; case 1540: metadata.put("Comments", data); if (ome != null) OMETools.setDescription(ome, data.toString()); break; case 1541: metadata.put("SampleID", data); break; case 1542: metadata.put("Subject", data); break; case 1543: metadata.put("RevisionNumber", data); break; case 1544: metadata.put("Save Folder", data); break; case 1545: metadata.put("FileLink", data); break; case 1546: metadata.put("Document Type", data); break; case 1547: metadata.put("Storage Media", data); break; case 1548: metadata.put("File ID", data); break; case 1549: metadata.put("Reference", data); break; case 1550: metadata.put("File Date", data); break; case 1551: metadata.put("File Size", data); break; case 1553: metadata.put("Filename", data); break; case 1792: metadata.put("ProjectGroup", data); if (ome != null) { OMETools.setGroup(ome, data.toString(), null, null); } break; case 1793: metadata.put("Acquisition Date", data); break; case 1794: metadata.put("Last modified by", data); break; case 1795: metadata.put("User company", data); break; case 1796: metadata.put("User company logo", data); break; case 1797: metadata.put("Image", data); break; case 1800: metadata.put("User ID", data); break; case 1801: metadata.put("User Name", data); break; case 1802: metadata.put("User City", data); break; case 1803: metadata.put("User Address", data); break; case 1804: metadata.put("User Country", data); break; case 1805: metadata.put("User Phone", data); break; case 1806: metadata.put("User Fax", data); break; case 2049: metadata.put("Objective Name", data); break; case 2050: metadata.put("Optovar", data); break; case 2051: metadata.put("Reflector", data); break; case 2052: metadata.put("Condenser Contrast", data); break; case 2053: metadata.put("Transmitted Light Filter 1", data); break; case 2054: metadata.put("Transmitted Light Filter 2", data); break; case 2055: metadata.put("Reflected Light Shutter", data); break; case 2056: metadata.put("Condenser Front Lens", data); break; case 2057: metadata.put("Excitation Filter Name", data); break; case 2060: metadata.put("Transmitted Light Fieldstop Aperture", data); break; case 2061: metadata.put("Reflected Light Aperture", data); break; case 2062: metadata.put("Condenser N.A.", data); break; case 2063: metadata.put("Light Path", data); break; case 2064: metadata.put("HalogenLampOn", data); break; case 2065: metadata.put("Halogen Lamp Mode", data); break; case 2066: metadata.put("Halogen Lamp Voltage", data); break; case 2068: metadata.put("Fluorescence Lamp Level", data); break; case 2069: metadata.put("Fluorescence Lamp Intensity", data); break; case 2070: metadata.put("LightManagerEnabled", data); break; case 2072: metadata.put("Focus Position", data); break; case 2073: metadata.put("Stage Position X", data); if (ome != null) { OMETools.setStageX(ome, Integer.parseInt(data.toString())); } break; case 2074: metadata.put("Stage Position Y", data); if (ome != null) { OMETools.setStageY(ome, Integer.parseInt(data.toString())); } break; case 2075: metadata.put("Microscope Name", data); // if (ome != null) { // OMETools.setAttribute(ome, "Microscope", "Name", "" + data); break; case 2076: metadata.put("Objective Magnification", data); break; case 2077: metadata.put("Objective N.A.", data); break; case 2078: metadata.put("MicroscopeIllumination", data); break; case 2079: metadata.put("External Shutter 1", data); break; case 2080: metadata.put("External Shutter 2", data); break; case 2081: metadata.put("External Shutter 3", data); break; case 2082: metadata.put("External Filter Wheel 1 Name", data); break; case 2083: metadata.put("External Filter Wheel 2 Name", data); break; case 2084: metadata.put("Parfocal Correction", data); break; case 2086: metadata.put("External Shutter 4", data); break; case 2087: metadata.put("External Shutter 5", data); break; case 2088: metadata.put("External Shutter 6", data); break; case 2089: metadata.put("External Filter Wheel 3 Name", data); break; case 2090: metadata.put("External Filter Wheel 4 Name", data); break; case 2103: metadata.put("Objective Turret Position", data); break; case 2104: metadata.put("Objective Contrast Method", data); break; case 2105: metadata.put("Objective Immersion Type", data); break; case 2107: metadata.put("Reflector Position", data); break; case 2109: metadata.put("Transmitted Light Filter 1 Position", data); break; case 2110: metadata.put("Transmitted Light Filter 2 Position", data); break; case 2112: metadata.put("Excitation Filter Position", data); break; case 2113: metadata.put("Lamp Mirror Position", data); break; case 2114: metadata.put("External Filter Wheel 1 Position", data); break; case 2115: metadata.put("External Filter Wheel 2 Position", data); break; case 2116: metadata.put("External Filter Wheel 3 Position", data); break; case 2117: metadata.put("External Filter Wheel 4 Position", data); break; case 2118: metadata.put("Lightmanager Mode", data); break; case 2119: metadata.put("Halogen Lamp Calibration", data); break; case 2120: metadata.put("CondenserNAGoSpeed", data); break; case 2121: metadata.put("TransmittedLightFieldstopGoSpeed", data); break; case 2122: metadata.put("OptovarGoSpeed", data); break; case 2123: metadata.put("Focus calibrated", data); break; case 2124: metadata.put("FocusBasicPosition", data); break; case 2125: metadata.put("FocusPower", data); break; case 2126: metadata.put("FocusBacklash", data); break; case 2127: metadata.put("FocusMeasurementOrigin", data); break; case 2128: metadata.put("FocusMeasurementDistance", data); break; case 2129: metadata.put("FocusSpeed", data); break; case 2130: metadata.put("FocusGoSpeed", data); break; case 2131: metadata.put("FocusDistance", data); break; case 2132: metadata.put("FocusInitPosition", data); break; case 2133: metadata.put("Stage calibrated", data); break; case 2134: metadata.put("StagePower", data); break; case 2135: metadata.put("StageXBacklash", data); break; case 2136: metadata.put("StageYBacklash", data); break; case 2137: metadata.put("StageSpeedX", data); break; case 2138: metadata.put("StageSpeedY", data); break; case 2139: metadata.put("StageSpeed", data); break; case 2140: metadata.put("StageGoSpeedX", data); break; case 2141: metadata.put("StageGoSpeedY", data); break; case 2142: metadata.put("StageStepDistanceX", data); break; case 2143: metadata.put("StageStepDistanceY", data); break; case 2144: metadata.put("StageInitialisationPositionX", data); break; case 2145: metadata.put("StageInitialisationPositionY", data); break; case 2146: metadata.put("MicroscopeMagnification", data); break; case 2147: metadata.put("ReflectorMagnification", data); break; case 2148: metadata.put("LampMirrorPosition", data); break; case 2149: metadata.put("FocusDepth", data); break; case 2150: metadata.put("MicroscopeType", data); // if (ome != null) { // OMETools.setAttribute(ome, "Microscope", "Type", "" + data); break; case 2151: metadata.put("Objective Working Distance", data); break; case 2152: metadata.put("ReflectedLightApertureGoSpeed", data); break; case 2153: metadata.put("External Shutter", data); break; case 2154: metadata.put("ObjectiveImmersionStop", data); break; case 2155: metadata.put("Focus Start Speed", data); break; case 2156: metadata.put("Focus Acceleration", data); break; case 2157: metadata.put("ReflectedLightFieldstop", data); break; case 2158: metadata.put("ReflectedLightFieldstopGoSpeed", data); break; case 2159: metadata.put("ReflectedLightFilter 1", data); break; case 2160: metadata.put("ReflectedLightFilter 2", data); break; case 2161: metadata.put("ReflectedLightFilter1Position", data); break; case 2162: metadata.put("ReflectedLightFilter2Position", data); break; case 2163: metadata.put("TransmittedLightAttenuator", data); break; case 2164: metadata.put("ReflectedLightAttenuator", data); break; case 2165: metadata.put("Transmitted Light Shutter", data); break; case 2166: metadata.put("TransmittedLightAttenuatorGoSpeed", data); break; case 2167: metadata.put("ReflectedLightAttenuatorGoSpeed", data); break; case 2176: metadata.put("TransmittedLightVirtualFilterPosition", data); break; case 2177: metadata.put("TransmittedLightVirtualFilter", data); break; case 2178: metadata.put("ReflectedLightVirtualFilterPosition", data); break; case 2179: metadata.put("ReflectedLightVirtualFilter", data); break; case 2180: metadata.put("ReflectedLightHalogenLampMode", data); break; case 2181: metadata.put("ReflectedLightHalogenLampVoltage", data); break; case 2182: metadata.put("ReflectedLightHalogenLampColorTemperature", data); break; case 2183: metadata.put("ContrastManagerMode", data); break; case 2184: metadata.put("Dazzle Protection Active", data); break; case 2195: metadata.put("Zoom", data); // if (ome != null) { // OMETools.setAttribute(ome, // "DisplayOptions", "Zoom", "" + data); break; case 2196: metadata.put("ZoomGoSpeed", data); break; case 2197: metadata.put("LightZoom", data); break; case 2198: metadata.put("LightZoomGoSpeed", data); break; case 2199: metadata.put("LightZoomCoupled", data); break; case 2200: metadata.put("TransmittedLightHalogenLampMode", data); break; case 2201: metadata.put("TransmittedLightHalogenLampVoltage", data); break; case 2202: metadata.put("TransmittedLightHalogenLampColorTemperature", data); break; case 2203: metadata.put("Reflected Coldlight Mode", data); break; case 2204: metadata.put("Reflected Coldlight Intensity", data); break; case 2205: metadata.put("Reflected Coldlight Color Temperature", data); break; case 2206: metadata.put("Transmitted Coldlight Mode", data); break; case 2207: metadata.put("Transmitted Coldlight Intensity", data); break; case 2208: metadata.put("Transmitted Coldlight Color Temperature", data); break; case 2209: metadata.put("Infinityspace Portchanger Position", data); break; case 2210: metadata.put("Beamsplitter Infinity Space", data); break; case 2211: metadata.put("TwoTv VisCamChanger Position", data); break; case 2212: metadata.put("Beamsplitter Ocular", data); break; case 2213: metadata.put("TwoTv CamerasChanger Position", data); break; case 2214: metadata.put("Beamsplitter Cameras", data); break; case 2215: metadata.put("Ocular Shutter", data); break; case 2216: metadata.put("TwoTv CamerasChangerCube", data); break; case 2218: metadata.put("Ocular Magnification", data); break; case 2219: metadata.put("Camera Adapter Magnification", data); break; case 2220: metadata.put("Microscope Port", data); break; case 2221: metadata.put("Ocular Total Magnification", data); break; case 2222: metadata.put("Field of View", data); break; case 2223: metadata.put("Ocular", data); break; case 2224: metadata.put("CameraAdapter", data); break; case 2225: metadata.put("StageJoystickEnabled", data); break; case 2226: metadata.put("ContrastManager Contrast Method", data); break; case 2229: metadata.put("CamerasChanger Beamsplitter Type", data); break; case 2235: metadata.put("Rearport Slider Position", data); break; case 2236: metadata.put("Rearport Source", data); break; case 2237: metadata.put("Beamsplitter Type Infinity Space", data); break; case 2238: metadata.put("Fluorescence Attenuator", data); break; case 2239: metadata.put("Fluorescence Attenuator Position", data); break; case 2307: metadata.put("Camera Framestart Left", data); break; case 2308: metadata.put("Camera Framestart Top", data); break; case 2309: metadata.put("Camera Frame Width", data); break; case 2310: metadata.put("Camera Frame Height", data); break; case 2311: metadata.put("Camera Binning", data); break; case 2312: metadata.put("CameraFrameFull", data); break; case 2313: metadata.put("CameraFramePixelDistance", data); break; case 2318: metadata.put("DataFormatUseScaling", data); break; case 2319: metadata.put("CameraFrameImageOrientation", data); break; case 2320: metadata.put("VideoMonochromeSignalType", data); break; case 2321: metadata.put("VideoColorSignalType", data); break; case 2322: metadata.put("MeteorChannelInput", data); break; case 2323: metadata.put("MeteorChannelSync", data); break; case 2324: metadata.put("WhiteBalanceEnabled", data); break; case 2325: metadata.put("CameraWhiteBalanceRed", data); break; case 2326: metadata.put("CameraWhiteBalanceGreen", data); break; case 2327: metadata.put("CameraWhiteBalanceBlue", data); break; case 2331: metadata.put("CameraFrameScalingFactor", data); break; case 2562: metadata.put("Meteor Camera Type", data); break; case 2564: metadata.put("Exposure Time [ms]", data); break; case 2568: metadata.put("CameraExposureTimeAutoCalculate", data); break; case 2569: metadata.put("Meteor Gain Value", data); break; case 2571: metadata.put("Meteor Gain Automatic", data); break; case 2572: metadata.put("MeteorAdjustHue", data); break; case 2573: metadata.put("MeteorAdjustSaturation", data); break; case 2574: metadata.put("MeteorAdjustRedLow", data); break; case 2575: metadata.put("MeteorAdjustGreenLow", data); break; case 2576: metadata.put("Meteor Blue Low", data); break; case 2577: metadata.put("MeteorAdjustRedHigh", data); break; case 2578: metadata.put("MeteorAdjustGreenHigh", data); break; case 2579: metadata.put("MeteorBlue High", data); break; case 2582: metadata.put("CameraExposureTimeCalculationControl", data); break; case 2585: metadata.put("AxioCamFadingCorrectionEnable", data); break; case 2587: metadata.put("CameraLiveImage", data); break; case 2588: metadata.put("CameraLiveEnabled", data); break; case 2589: metadata.put("LiveImageSyncObjectName", data); break; case 2590: metadata.put("CameraLiveSpeed", data); break; case 2591: metadata.put("CameraImage", data); break; case 2592: metadata.put("CameraImageWidth", data); break; case 2593: metadata.put("CameraImageHeight", data); break; case 2594: metadata.put("CameraImagePixelType", data); break; case 2595: metadata.put("CameraImageShMemoryName", data); break; case 2596: metadata.put("CameraLiveImageWidth", data); break; case 2597: metadata.put("CameraLiveImageHeight", data); break; case 2598: metadata.put("CameraLiveImagePixelType", data); break; case 2599: metadata.put("CameraLiveImageShMemoryName", data); break; case 2600: metadata.put("CameraLiveMaximumSpeed", data); break; case 2601: metadata.put("CameraLiveBinning", data); break; case 2602: metadata.put("CameraLiveGainValue", data); break; case 2603: metadata.put("CameraLiveExposureTimeValue", data); break; case 2604: metadata.put("CameraLiveScalingFactor", data); break; case 2822: metadata.put("ImageTile Index", data); break; case 2823: metadata.put("Image acquisition Index", data); break; case 2841: metadata.put("Original Stage Position X", data); break; case 2842: metadata.put("Original Stage Position Y", data); break; case 3088: metadata.put("LayerDrawFlags", data); break; case 3334: metadata.put("RemainingTime", data); break; case 3585: metadata.put("User Field 1", data); break; case 3586: metadata.put("User Field 2", data); break; case 3587: metadata.put("User Field 3", data); break; case 3588: metadata.put("User Field 4", data); break; case 3589: metadata.put("User Field 5", data); break; case 3590: metadata.put("User Field 6", data); break; case 3591: metadata.put("User Field 7", data); break; case 3592: metadata.put("User Field 8", data); break; case 3593: metadata.put("User Field 9", data); break; case 3594: metadata.put("User Field 10", data); break; case 3840: metadata.put("ID", data); break; case 3841: metadata.put("Name", data); break; case 3842: metadata.put("Value", data); break; case 5501: metadata.put("PvCamClockingMode", data); break; case 8193: metadata.put("Autofocus Status Report", data); break; case 8194: metadata.put("Autofocus Position", data); break; case 8195: metadata.put("Autofocus Position Offset", data); break; case 8196: metadata.put("Autofocus Empty Field Threshold", data); break; case 8197: metadata.put("Autofocus Calibration Name", data); break; case 8198: metadata.put("Autofocus Current Calibration Item", data); break; case 65537: metadata.put("CameraFrameFullWidth", data); break; case 65538: metadata.put("CameraFrameFullHeight", data); break; case 65541: metadata.put("AxioCam Shutter Signal", data); break; case 65542: metadata.put("AxioCam Delay Time", data); break; case 65543: metadata.put("AxioCam Shutter Control", data); break; case 65544: metadata.put("AxioCam BlackRefIsCalculated", data); break; case 65545: metadata.put("AxioCam Black Reference", data); break; case 65547: metadata.put("Camera Shading Correction", data); break; case 65550: metadata.put("AxioCam Enhance Color", data); break; case 65551: metadata.put("AxioCam NIR Mode", data); break; case 65552: metadata.put("CameraShutterCloseDelay", data); break; case 65553: metadata.put("CameraWhiteBalanceAutoCalculate", data); break; case 65556: metadata.put("AxioCam NIR Mode Available", data); break; case 65557: metadata.put("AxioCam Fading Correction Available", data); break; case 65559: metadata.put("AxioCam Enhance Color Available", data); break; case 65565: metadata.put("MeteorVideoNorm", data); break; case 65566: metadata.put("MeteorAdjustWhiteReference", data); break; case 65567: metadata.put("MeteorBlackReference", data); break; case 65568: metadata.put("MeteorChannelInputCountMono", data); break; case 65570: metadata.put("MeteorChannelInputCountRGB", data); break; case 65571: metadata.put("MeteorEnableVCR", data); break; case 65572: metadata.put("Meteor Brightness", data); break; case 65573: metadata.put("Meteor Contrast", data); break; case 65575: metadata.put("AxioCam Selector", data); break; case 65576: metadata.put("AxioCam Type", data); break; case 65577: metadata.put("AxioCam Info", data); break; case 65580: metadata.put("AxioCam Resolution", data); break; case 65581: metadata.put("AxioCam Color Model", data); break; case 65582: metadata.put("AxioCam MicroScanning", data); break; case 65585: metadata.put("Amplification Index", data); break; case 65586: metadata.put("Device Command", data); break; case 65587: metadata.put("BeamLocation", data); break; case 65588: metadata.put("ComponentType", data); break; case 65589: metadata.put("ControllerType", data); break; case 65590: metadata.put("CameraWhiteBalanceCalculationRedPaint", data); break; case 65591: metadata.put("CameraWhiteBalanceCalculationBluePaint", data); break; case 65592: metadata.put("CameraWhiteBalanceSetRed", data); break; case 65593: metadata.put("CameraWhiteBalanceSetGreen", data); break; case 65594: metadata.put("CameraWhiteBalanceSetBlue", data); break; case 65595: metadata.put("CameraWhiteBalanceSetTargetRed", data); break; case 65596: metadata.put("CameraWhiteBalanceSetTargetGreen", data); break; case 65597: metadata.put("CameraWhiteBalanceSetTargetBlue", data); break; case 65598: metadata.put("ApotomeCamCalibrationMode", data); break; case 65599: metadata.put("ApoTome Grid Position", data); break; case 65600: metadata.put("ApotomeCamScannerPosition", data); break; case 65601: metadata.put("ApoTome Full Phase Shift", data); break; case 65602: metadata.put("ApoTome Grid Name", data); break; case 65603: metadata.put("ApoTome Staining", data); break; case 65604: metadata.put("ApoTome Processing Mode", data); break; case 65605: metadata.put("ApotmeCamLiveCombineMode", data); break; case 65606: metadata.put("ApoTome Filter Name", data); break; case 65607: metadata.put("Apotome Filter Strength", data); break; case 65608: metadata.put("ApotomeCamFilterHarmonics", data); break; case 65609: metadata.put("ApoTome Grating Period", data); break; case 65610: metadata.put("ApoTome Auto Shutter Used", data); break; case 65611: metadata.put("Apotome Cam Status", data); break; case 65612: metadata.put("ApotomeCamNormalize", data); break; case 65613: metadata.put("ApotomeCamSettingsManager", data); break; case 65614: metadata.put("DeepviewCamSupervisorMode", data); break; case 65615: metadata.put("DeepView Processing", data); break; case 65616: metadata.put("DeepviewCamFilterName", data); break; case 65617: metadata.put("DeepviewCamStatus", data); break; case 65618: metadata.put("DeepviewCamSettingsManager", data); break; case 65619: metadata.put("DeviceScalingName", data); break; case 65620: metadata.put("CameraShadingIsCalculated", data); break; case 65621: metadata.put("CameraShadingCalculationName", data); break; case 65622: metadata.put("CameraShadingAutoCalculate", data); break; case 65623: metadata.put("CameraTriggerAvailable", data); break; case 65626: metadata.put("CameraShutterAvailable", data); break; case 65627: metadata.put("AxioCam ShutterMicroScanningEnable", data); break; case 65628: metadata.put("ApotomeCamLiveFocus", data); break; case 65629: metadata.put("DeviceInitStatus", data); break; case 65630: metadata.put("DeviceErrorStatus", data); break; case 65631: metadata.put("ApotomeCamSliderInGridPosition", data); break; case 65632: metadata.put("Orca NIR Mode Used", data); break; case 65633: metadata.put("Orca Analog Gain", data); break; case 65634: metadata.put("Orca Analog Offset", data); break; case 65635: metadata.put("Orca Binning", data); break; case 65636: metadata.put("Orca Bit Depth", data); break; case 65637: metadata.put("ApoTome Averaging Count", data); break; case 65638: metadata.put("DeepView DoF", data); break; case 65639: metadata.put("DeepView EDoF", data); break; case 65643: metadata.put("DeepView Slider Name", data); break; } } } } // -- Main method -- public static void main(String[] args) throws FormatException, IOException { new ZeissZVIReader().testRead(args); } }
// $Id: Trace.java,v 1.2 2003/11/27 21:09:14 belaban Exp $ package org.jgroups.log; import java.io.*; import java.net.*; import org.apache.log4j.*; /** * Replacement for regular JGroups Trace, beased on log4j. log4j.properties should be somewhere on * the CLASSPATH * @author Bela Ban */ public class Trace { static { if(Logger.getRootLogger().getEffectiveLevel() == Level.OFF) { Trace.trace=false; } else { Trace.trace=true; } } // static int[] jgroups_levels={DEBUG, TEST, INFO, WARN, ERROR, FATAL}; static Level[] log4j_levels={Level.DEBUG, Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL}; static Level jgToLog4jLevel(int jg_level) { return log4j_levels[jg_level]; } /** Users of Trace can check this flag to determine whether to trace. Example: <pre> if(Trace.trace) Trace.info("UDP.run()", "sending message"); </pre> */ public static boolean trace=true; /** Allows for conditional compilation, e.g. if(Trace.debug) Trace.info(...) would be removed from the code (if recompiled) when this flag is set to false. Therefore, code that should be removed from the final product should use if(Trace.debug) rather than if(Trace.trace). */ public static final boolean debug=false; /** * Used to determine whether to copy messages (copy=true) in retransmission tables, * or whether to use references (copy=false). Once copy=false has worked for some time, this flag * will be removed entirely */ public static final boolean copy=false; static String identifier=null; /** The trace level for all messages. */ public static final int DEBUG=0; /** The trace level for all messages except DEBUG. */ public static final int TEST=1; /** The trace level for all messages except DEBUG and TEST. */ public static final int INFO=2; /** The trace level for all WARN, ERROR, and FATAL messages. */ public static final int WARN=3; /** The trace level for all ERROR and FATAL messages. */ public static final int ERROR=4; /** The trace level for only FATAL messages. */ public static final int FATAL=5; /** Completely private constructor; should never be called. */ private Trace() { } public static void init(String fname) throws IOException, SecurityException { ; } public static void init() { ; } public static void flushStdouts() { } public static void setAutoFlushForAllStdouts(boolean auto) { } public static void flushStderrs() { } public static void setAutoFlushForAllStderrs(boolean auto) { } public static void setIdentifier(String id) { identifier=id; } public static void setTrace(boolean t) { trace=t; } /** * Changes the trace level for <code>module</code>. The output destination * is not changed. No other module (either higher or lower in the module * "inheritance chain") is affected. If this module has no output * associated with it (and thus any output would go to the current * default output), nothing happens. If the module name is not well-formed, * nothing happens. * * @param module a module name * @param level a trace level */ public static void setOutput(String module, int level) { } /** * Sends a module's output to the specified file. Output is only sent * when a call to <code>print</code> or <code>println</code> specifies * a trace level &gt;= <code>level</code>. * <p> * If <code>fileName</code> is the name of a directory, a file name will * be generated using <code>module</code> and <code>level</code> (see * @link{#makeOutputFileName}). * <p> * If the file does not exist, it is created. If the file does exist, the * file is opened for appending. * * @param module a module name * @param level a trace level * @param fileName a file or directory name * @throws IOException when a <code>FileWriter</code> can not be created */ public static void setOutput(String module, int level, String fileName) throws IOException { ; } /** * Sends a module's output to the specified <code>PrintStream</code>. * Output is only sent when a call to <code>print</code> or * <code>println</code> specifies a trace level &gt;= <code>level</code>. * <p> * The most common values of <code>outputStream</code> will be * <code>System.out</code> or <code>System.err</code>. * In fact, that is so likely that we keep pre-generated outputs around for * those two and return one when <code>outputStream</code> is one of those * two values. * * @param module a module name * @param level a trace level * @param outputStream a <code>PrintStream</code> */ public static void setOutput(String module, int level, PrintStream outputStream) { } /** * Sends a module's output to the specified <code>PrintWriter</code>. * Output is only sent when a call to <code>print</code> or * <code>println</code> specifies a trace level &gt;= <code>level</code>. * * @param module a module name * @param level a trace level * @param writer a <code>PrintWriter</code> */ public static void setOutput(String module, int level, PrintWriter writer) { } /** * Sends a module's output to the socket at <code>host</code> on * <code>port</code>. As with the <code>Socket</code> class, if * <code>port</code> is zero then the first available port will be used. * Output is only sent when a call to <code>print</code> or * <code>println</code> specifies a trace level &gt;= <code>level</code>. * * @param module a module name * @param level a trace level * @param host the name of a host machine * @param port a port number * @throws UnknownHostException if <code>host</code> can not be resolved * @throws IOException if an I/O error occurs when creating a socket * @see java.net.Socket */ public static void setOutput(String module, int level, String host, int port) throws UnknownHostException, IOException { ; } /** * Sends a module's output to the socket at <code>addr</code> on * <code>port</code>. As with the <code>Socket</code> class, if * <code>port</code> is zero then the first available port will be used. * Output is only sent when a call to <code>print</code> or * <code>println</code> specifies a trace level &gt;= <code>level</code>. * * @param module a module name * @param level a trace level * @param addr an <code>InetAddress</code> * @param port a port number * @throws IOException if an I/O error occurs when creating a socket * @see java.net.Socket */ public static void setOutput(String module, int level, InetAddress addr, int port) throws IOException { } /** * Closes the output for the specified module. When the output is closed, * it flushes its output first. It's OK to call this for modules that are * using <code>STDOUT</code>, <code>STDERR</code>, or the default output. * * @param module a module name */ public static void closeOutput(String module) { } /** * Closes all outputs for all modules. When an output is closed, it * flushes its output first. */ public static void closeAllOutputs() { } /** * Flushes all output for the specified module. * * @param module a module name */ public static void flushOutput(String module) { } /** * Flushes all output for all modules. */ public static void flushAllOutputs() { } /** * Sets the auto-flush flag for the specified module's output. * * @param module a module name * @param auto if <code>true</code> auto-flushing is turned on */ public static void setAutoFlush(String module, boolean auto) { } /** * Sets the auto-flush flag for all outputs. * <p> * The auto-flush value for <code>STDOUT</code> and <code>STDERR</code> * are also set. * * @param auto if <code>true</code> auto-flushing is turned on */ public static void setAutoFlushAll(boolean auto) { } /** * Sets the auto-flush flag for the current default output. * * @param auto if <code>true</code> auto-flushing is turned on */ public static void setAutoFlushDefault(boolean auto) { } /** * Finds the appropriate output for the specified module and sends * <code>message</code> to it. When looking for which output to use, * the following set of rules are used. If no output is found (the * returned output is <code>null</code>), then nothing is printed. * * <ol> * * <li>If the module name contains no method name (there are no parenthesis), * look for the output associated with this module name. If found, return it. * Else, return the default output (initially <code>null</code>).</li> * * <li>Look for the output associated with this module and method name, * excluding arguments if any.</li> * * <li>Strip off the method name and look for the output associated with the * class name.</li> * * <li>Use the default output (initially <code>null</code>). * * </ol> * * @param module a module name * @param level a trace level * @param message the string to be output */ public static void print(String module, int level, String message) { if(identifier == null) Logger.getLogger(module).log(jgToLog4jLevel(level), message); else Logger.getLogger(identifier + "." + module).log(jgToLog4jLevel(level), message); } /** Prints the identifier (e.g. process name) after the level, before the message. */ public static void print(String module, int level, String identifier, String message) { if(identifier == null) Logger.getLogger(module).log(jgToLog4jLevel(level), "[" + identifier + " ] " + message); else Logger.getLogger(identifier + "." + module).log(jgToLog4jLevel(level), "[" + identifier + " ] " + message); } /** * Appends a line separator to <code>message</code> and calls * <code>print</code>. The system property "line.separator" is used; * this is not necessarily a single newline character ('\n'). * * @param module a module name * @param level a trace level * @param message the string to be output * @see #print */ public static void println(String module, int level, String message) { if(identifier == null) Logger.getLogger(module).log(jgToLog4jLevel(level), message); else Logger.getLogger(identifier + "." + module).log(jgToLog4jLevel(level), message); } /** Helper method. Will call Trace.println(module, Trace.DEBUG, module) */ public static void debug(String module, String message) { if(identifier == null) Logger.getLogger(module).debug(module + ": " + message); else Logger.getLogger(identifier + "." + module).debug(module + ": " + message); } /** Helper method. Will call Trace.println(module, Trace.TEST, module) */ public static void test(String module, String message) { if(identifier == null) Logger.getLogger(module).debug(module + ": " + message); else Logger.getLogger(identifier + "." + module).debug(module + ": " + message); } /** Helper method. Will call Trace.println(module, Trace.INFO, module) */ public static void info(String module, String message) { if(identifier == null) Logger.getLogger(module).info(module + ": " + message); else Logger.getLogger(identifier + "." + module).info(module + ": " + message); } /** Helper method. Will call Trace.println(module, Trace.WARN, module) */ public static void warn(String module, String message) { if(identifier == null) Logger.getLogger(module).warn(module + ": " + message); else Logger.getLogger(identifier + "." + module).warn(module + ": " + message); } /** Helper method. Will call Trace.println(module, Trace.ERROR, module) */ public static void error(String module, String message) { if(identifier == null) Logger.getLogger(module).error(module + ": " + message); else Logger.getLogger(identifier + "." + module).error(module + ": " + message); } /** Helper method. Will call Trace.println(module, Trace.FATAL, module) */ public static void fatal(String module, String message) { if(identifier == null) Logger.getLogger(module).fatal(module + ": " + message); else Logger.getLogger(identifier + "." + module).fatal(module + ": " + message); } /** * Set the timestamp format. The <code>format</code> * string is that used by {@link java.text.SimpleDateFormat}. If * <code>format</code> is <code>null</code>, then the ISO 8601 date * format ("CCYY-MM-DDThh:mm:ss,s") is used. */ public static void setTimestampFormat(String format) { } /** * Sets the default output back to its original value, <code>STDOUT</code>. */ public static synchronized void restoreDefaultOutput() { } /** * Closes the current default output. All output with no other destination * is ignored. */ public static synchronized void closeDefaultOutput() { } /** * Sets the default output to the specified file and trace level. * If <code>fileName</code> is the name of a directory, the file name * <code>DEFAULT_OUTPUT_FILE_NAME</code> ("default.out") is used. * <p> * If the file does not exist, it is created. If the file does exist, the * file is opened for appending. * * @param fileName a file or directory name * @throws IOException when a <code>FileWriter</code> can not be created */ public static synchronized void setDefaultOutput(int level, String fileName) throws IOException { } /** * Sets the default output to the specified file. If <code>fileName</code> * is the name of a directory, the file name * <code>DEFAULT_OUTPUT_FILE_NAME</code> ("default.out") is used. * <p> * If the file does not exist, it is created. If the file does exist, the * file is opened for appending. * * @param fileName a file or directory name * @throws IOException when a <code>FileWriter</code> can not be created */ public static synchronized void setDefaultOutput(String fileName) throws IOException { } /** * Sets the default output to the specified <code>PrintStream</code> and * trace level. * <p> * The most common values of <code>outputStream</code> will be * <code>System.out</code> or <code>System.err</code>. * In fact, that is so likely that we keep pre-generated outputs around for * those two and return one when <code>outputStream</code> is one of those * two values. * * @param outputStream a <code>PrintStream</code> */ public static synchronized void setDefaultOutput(int level, PrintStream outputStream) { } /** * Sets the default output to the specified <code>PrintStream</code>. * <p> * The most common values of <code>outputStream</code> will be * <code>System.out</code> or <code>System.err</code>. * In fact, that is so likely that we keep pre-generated outputs around for * those two and return one when <code>outputStream</code> is one of those * two values. * * @param outputStream a <code>PrintStream</code> */ public static synchronized void setDefaultOutput(PrintStream outputStream) { } /** * Sets the default output to the specified <code>PrintWriter</code> and * trace level. * * @param writer a <code>PrintWriter</code> */ public static synchronized void setDefaultOutput(int level, PrintWriter writer) { } /** * Sets the default output to the specified <code>PrintWriter</code>. * * @param writer a <code>PrintWriter</code> */ public static synchronized void setDefaultOutput(PrintWriter writer) { } /** * Sets the default output to the socket at <code>host</code> on * <code>port</code> with the given trace level. As with the * <code>Socket</code> class, if <code>port</code> is zero then the first * available port will be used. * * @param host the name of a host machine * @param port a port number * @throws UnknownHostException if <code>host</code> can not be resolved * @throws IOException if an I/O error occurs when creating a socket * @see java.net.Socket */ public static synchronized void setDefaultOutput(int level, String host, int port) throws UnknownHostException, IOException { } /** * Sets the default output to the socket at <code>host</code> on * <code>port</code>. As with the <code>Socket</code> class, if * <code>port</code> is zero then the first available port will be used. * * @param host the name of a host machine * @param port a port number * @throws UnknownHostException if <code>host</code> can not be resolved * @throws IOException if an I/O error occurs when creating a socket * @see java.net.Socket */ public static synchronized void setDefaultOutput(String host, int port) throws UnknownHostException, IOException { } /** * Sets the default output to the socket at <code>addr</code> on * <code>port</code> at the specified trace level. As with the * <code>Socket</code> class, if <code>port</code> is zero then the first * available port will be used. * * @param addr an <code>InetAddress</code> * @param port a port number * @throws IOException if an I/O error occurs when creating a socket * @see java.net.Socket */ public static synchronized void setDefaultOutput(int level, InetAddress addr, int port) throws IOException { } /** * Sets the default output to the socket at <code>addr</code> on * <code>port</code>. As with the <code>Socket</code> class, if * <code>port</code> is zero then the first available port will be used. * * @param addr an <code>InetAddress</code> * @param port a port number * @throws IOException if an I/O error occurs when creating a socket * @see java.net.Socket */ public static synchronized void setDefaultOutput(InetAddress addr, int port) throws IOException { } /** * Converts an exception stack trace into a java.lang.String * @param x an exception * @return a string containg the stack trace, null if the exception parameter was null */ public static String getStackTrace(Throwable x) { if(x == null) return null; else { java.io.ByteArrayOutputStream bout=new java.io.ByteArrayOutputStream(); java.io.PrintStream writer=new java.io.PrintStream(bout); x.printStackTrace(writer); String result=new String(bout.toByteArray()); return result; } } }
package scal.io.liger; import android.content.Context; public class Constants { /** RequestCodes used for external Media Capture via * {@link android.app.Activity#startActivityForResult(android.content.Intent, int)} */ public static final int REQUEST_VIDEO_CAPTURE = 100; public static final int REQUEST_IMAGE_CAPTURE = 101; public static final int REQUEST_AUDIO_CAPTURE = 102; public static final int REQUEST_FILE_IMPORT = 103; /** Intent extras used for external Media Capture via * {@link android.app.Activity#startActivityForResult(android.content.Intent, int)} */ public static final String EXTRA_PATH_ID = "EXTRA_PATH_ID"; public static final String EXTRA_FILE_LOCATION = "FILE_LOCATION"; public static final String PREFS_CALLING_CARD_ID = "PREFS_CALLING_CARD_ID"; /** Intent extras used when launching MainActivity */ public static final String EXTRA_LANG = "lang"; public static final String EXTRA_PHOTO_SLIDE_DURATION = "photo_essay_slide_duration"; /** Values for {@link scal.io.liger.model.ExampleCard#medium} and * {@link scal.io.liger.model.MediaFile#medium} */ public static final String AUDIO = "audio"; public static final String PHOTO = "photo"; public static final String VIDEO = "video"; /** Values for {@link scal.io.liger.model.ClipMetadata#type */ public static final String CHARACTER = "character"; public static final String ACTION = "action"; public static final String RESULT = "result"; public static final String PLACE = "place"; public static final String SIGNATURE = "signature"; public static final String NARRATION = "narration"; public static String getClipTypeLocalized(Context context, String clipType) { if (clipType.equalsIgnoreCase(Constants.CHARACTER)) { return context.getString(R.string.cliptype_character); } else if (clipType.equalsIgnoreCase(Constants.ACTION)) { return context.getString(R.string.cliptype_action); } else if (clipType.equalsIgnoreCase(Constants.RESULT)) { return context.getString(R.string.cliptype_result); } else if (clipType.equalsIgnoreCase(Constants.SIGNATURE)) { return context.getString(R.string.cliptype_signature); } else if (clipType.equalsIgnoreCase(Constants.PLACE)) { return context.getString(R.string.cliptype_place); } // else, return the untranslated return clipType; } /** Value returned by {@link scal.io.liger.model.StoryPath#getReferencedValue(String)} * when the requested reference value is external to the StoryPath */ public static final String EXTERNAL = "value_from_external_story_path"; /** StoryMaker Intent Actions */ public static final String ACTION_PUBLISH = "io.scal.liger.PUBLISH"; /** expansion file management */ // TODO switch to .org & https public static final String LIGER_URL = "http://storymaker.cc/appdata/"; public static final String MAIN = "main"; public static final String PATCH = "patch"; public static final int MAIN_VERSION = 1031; public static final int PATCH_VERSION = 1020; public final static String TOR_PROXY_HOST = "localhost"; public final static int TOR_PROXY_PORT = 8118; public static final String EXTRA_STORY_TITLE = "story_title"; public static final String EXTRA_EXPORT_CLIPS = "export_clips"; public static final String EXTRA_EXPORT_AUDIOCLIPS = "export_audioclips"; public final static String DEFAULT_AUDIO_SAMPLE_RATE = "22050"; // FIXME probe if a better audio rate is supported on this device }