��c��RDUCK3 p��-��G0AO���mn-�jBNO8���f$������r�\ �P( �f2�@ �˄�`0 ��`0��b��H,��d�X,��b�X,��b��D$�L��4(Dr�D"����`I�éT*��D"�H$��f�T*����p8�Œ�`0��d2�P(��D�8e�kM*�E#B�`��D"��ӡX,��d�p<����x<����d8��aX ��`0 F���t*�����L&�I��D"ͦ�@ �@ �K��h4*�ǃB�L>��N���tDY�R�TD"�H$�t:��f���2���r�H$�W&c��2���D"�J$�\"�Hd2�L&�Ʌ��T*�J��l6��r�\*�J�R�T*�J�R�T*���r�`>�F��l*�J$�D"�H$�@8��r�\, �B�P( �B��L�L&#�d&��F"�H$�ʫ��t:�N�r�L&��$�@D" �b�X0��f��l6S�L<O��j�Z�V��j�Z�V��j�Z�T�t:�N��jU��X,��b�X,�D"�H$I�R�($�D"�H( �B�P�b1�|L&���zu:�^�g2�L0�J�R�\��f�b�p�����|J�l�`�X�E��P( �B�P( ���P(�m��t:�����|>�OL$:�N���$��@,��t�F��T�,�S�T��@3�����|>�ϧӉH�S(�x<���tr�8�T��byZ�ө%d�^��k�R�L�T��r�^�Z�V��j5��T����X,�F���v��N',�V.����N6U���`��N���n4�m4�F���D� :�F��l��d2��d2�V����r�\.���Zy<����x<��3�L&��(�i4�F��h4�����|>�����|>��H$�D"�H$�D���d�p8�SeV3��d2�L&��d�|>��g��N�� ��|>���Ci4 �@ �@�rqD+��j�F�҈�J�8���p>�N���t:��(:Y,��b�X,��b!jF�RIE"].���pT'h2�P��F��h<�+d2�H�X,�@3�p��Re,����`-� �b�Z�V %��d�(�J�V���f��^1 �ry�\.�% �L,V�eI�X*�j�Z��ȥs ��Z�V�Ռ��RV|�b�en�b�X#��4:�F=T�V��H$�s��<�H$ �BY�V��j�Z�V�����N(ԮV��b,T�U*��_����v��d1�s�\.��媹`��j�r�D"�H$�0 f4j�P0XJ�`0 ��`0 ��t:&�)�tN�өT*�@ P���P�D"qh"�d"�H$�t�Z�ͦR�T*��P��%��d2�+g��,�9mF��3�L&�iE"�L&I��h4����|>��f��h4�F��h4�3��M{�^����z�k4-�x<�W���f��|�r�\�YY�Ϗd2�L&��t:����r��D��X�x����(o���v;^�V�E2P��1����|>���ժ;���tZ(���s�\,��6�L�݂�`�h4�F��F��G��FC�tz��t ���z�^�X-����Y��z�Vs�\�] ���f����p���F��.���r�\.���r�f����r�\.�kg��v���t:�N������~����͒Ij�;�v�ݎ��T>���Z�D"�H$�D��s�|>��d2�D3�H���J"�H$}>O�s�V�`��{�^��K���h4��r�\,��b�@�V+T2�L&��d2�L&��d2�L&��R�\.���r=m6��f�����6��Z����C�L&��dR�l��o�Z�V�V��j�Z2�F��h4 ���L���V��j�Z�V�Ֆ=��t:�`0o�� ��V��j?$�h4�F&�h4J�R��j�Z�V��j�Z�z�P�u�F��H$�V�� �Bu:��Je�l6s�\���b�X,V(������:N��|>���T M�TJ�2�@#���Q�R�N���p8&�ec2�L&��d2�L�L&�Q�T������`0����^�Ti� �D"����tH��' �:�ϧөT*�����x<��3�B���t:��F��h4�F��h4" �B�P( �B�P,�L&��d2���R�d��)�b�X�X���t:����h4�� �D!�F��h4�F��h4��@ w>�����v �@ ���|>_,6z*�H$�D�����|�B���z�^,���d2$ GE��~0 ��`0 ��r��L���d��z�^�,�rW/��%�L���t:&�I$�D)��d2�P���db�Z�V+�h8���h4�F��h4��r�\0 ��`2�J�R�p8���`0�L��`4��'�s�`�M�J��G"�F��h4*�D#)��p-�Q��r�Vkv�z�����a.���tB�N���t:].'�v�����x<����x<����x<�Q(��r�\�:�N���t:�N���t:�N���t:�����|>��h4�ƞ�H��t:�N���t:�N���t:�N���x<����x<��h�@ ����z�^�.�4�N���v�^����x�b�(��v;���\.���r�\.���r�\Nx<����x<���Ϸ��~��n���v@ �@ �@�����|>�����|>�����|��t:��x�����-��b�Xl6��z����b�v;���r�v;�l���v����`0 ��`0 ��`����r�\.���J�H���d8�ͦ��D"�P( Q(0� �<�f3B M� ���<�ϗ��V������v�����d2�f�<�N��q��� ���P( ��\.�:�C�N���t�Z�X�Վ������Z��J���|���z��x5 p��f��.��8���p8���l6��f��l6�͆��|<� �B� �@$���|>�����|:�Œ�H$R,��b�X,��b1"��z�^� ���h4�F��~ ��L&�Hd2�P(�͆B�\.����x<����p8�H$��8 f2�L0���1�x<�@ �@ ���t:�N���t<"�Ht"�b�\.6��f�\�t:�N���$��V�բ�b��eZ�V��j�J�R%(���V��j�Z�V� ��8 GU�x:��i�b�X,��v��J$iD�H$�D��H�T*5"�R)G5�F��J��t:�N���t:�N���t:��d2�J�R�T*Q( �B�P(��o6��l�W�3�F��h4�F�T*��F� �Ŋ�bf���H�zM�p�U��j��O��s#mr��Ǔ�d2�L&��x<�� �n��M�b�X�X��R�<��l6��d�R�$��Z�V �b7��U*�J�Ri4�V�P(*�b��ñX,��:�J�R��b�X��)&[�V�Y�T"�H��j�Z�x�T*C�Z�V��j�T�T,��t:�Ng�R�f��l6��f�P��B�P��K�R�J�R�T*�\.��b�D���s�hH$�D"�H*�J�R�T��jU��|�X,�� �B���l6�X����d-��t:�N�����N,��"�D(���a�X�V����r����I�D����B�N.�k�9�V�-V*�:�Nv:�Z�V�%��d��I��\.�˕J�L��j�[�V,��b�X��,�B�L&*k�Z�V+���J,�+���Z��j�Z�V�V���@ �B�PJ�R���l6��f��l>��''��n��h4�\.���rq8g�T*�f��l6��f��l6��f���d2Y��Qul�L&�J�H*�J�RmB��F�ٰX��pP��i��l6�M��Z�V�L�b�X,�Zm���v�����|>�����T*��f�!�b�S ��T��h4�F��h4�D"�H �BVJ$B�L&�I���Hݍ��݄���x��v��n'4��Q*�B�P�V��j�V��@!����x<�@ �r�\�NG��|B&�)��D"�F��h4!d2�@%�H$�|^YHC��@ �T��h��d2Y*5}>��G$�F#�a>�Z��f�V��h4�t:���b��ŢJ�b�@`fs��~��h�b�@  �Z�V���%�}>����R�@-ͦ�h4�� &��d�NG��l6�N���l6�����p8�N��h0X�R�T( �B�P( �r�P8��b�X,�E�q�x!J( �B�P*-�J�av4�ZF��V��j�Z���l6���Z�V������z�ݎH$�JL(D�P(�tZ�v�ݮ't�\.����fB#����r��Nw: ��X,��b���t:�N<�-�J�R�T*Ut�\��N�B�B:�f�F#���z%��d2 ��D��+T*�J%���@ �H$щD"q8�$�H$���t:�N��F�R�T�N���L&����T*�J�R�T# �B�>�(�"�H$�B�P&Q��U*(����x<.�kC;�H�c��BR�v����d���v���fS�\���5j4����L]�K��J�R�T�\.k5���p8N:}>���d�|>�� �@ ��f�����X�O0�Z�V��M�+�j@�H��<��f��l6��f�2�h�N���t:*����xD"�H��x<OhE�d2�LF&[�� 48( onorri/c/IParay./CiddeiatiisapbotresalusotFiseitroullipeleInatt/teReenanercorectlleconingSersesSet/lilelyte/Ficlitxlmenhttt/ectibus/Evityjavaablenet/HashQueuhashEvenacheFilecessvententBangeActiulti.javaTableInetAationddresbase/nloadleDowGener/java/Shadow/util/s.javar.javae.java/Paralloadert.javareenrom.javaer.javas/androc/org/gcel.javtBus/srset.javogle/comc/com/goguava/srshadows/robolectin/java/android/k/src/maframewor/src/mais/src/macurrent/reactor-/publishctor/corresourcesrc/mainManager.Monitor.library/Map.javaulishuo/filedownFlux.javResourceinternalper.javaiMap.javter.java/ocrasgimetlnuSfMpkd.jbyRFAIhvPLDHTEBCxQ-z2GNWwO_q6U3JX���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������tS���������&�$��&�7��'���MJ����#������m�S�������#����� �1� �� ��J����#������m�S�������#����� ���� ��� W����#������m�S�������#����� ���� ��� WtS����&����������� ����tS����&����������� ����tS����&����������� ����tS����&����������� ����tS����&����������� ����tS���������&�$�� ����������JtS���������&�$��&�7����������MJ� �m�S�����������$��������!%�����������~tS���������&�$���#�����������]tS���������,���� �����VtS���������,���� �����VtS���������,���� �����VtS���������,���� �����VtS���������,���� �����VtS%�����%��# ���� ���� JtS����&����������������tS�������������#�� ������#� �;tS�������������#�� ������#� �;tS�������������#�� ������#� �;tS�������������#�� ������#� �;tS���������,�����������VtS���������,�� �'����VtS���������,�� �'����VtS���������,�� �'����VtS�������������#�� ���!�����#���M�#�WtS�������������#�� ���!�����#���M�#�WtS�������������#�� ���!�����#���M�#�WtS���������,��� �����VtS���������,��� �����V����;m�S������������������J����;m�S������������������J����;m�S������������������J����;m�S������������������J����;m�S������������������JtS�������������J����#������m�S�������#����������������������X�������"$m�S%���������"$�����MJ�������"$m�S%���������"$�����MJ�����m�S=��������")����$����������^tS������������������� JtS������������������� JtS������������������� JtS������������������� JtS������������������� JtS������������������� JtS������������������� JtS������������������� JtS������������������� JtS������������������� JtS������������������� JtS���������������������]tS���������������������]�����m�S=��������"%&������V$���GJ�����m�S=��������"%&���������"���������#����';�����m�S=��������"%&���������"���������#����';tS�������������������&����� WtS�������������������&����� WtS�������������������&����� W����������%��ni%������������������������������ ���BJ�������ni%��������'��������������������������"[tS����������������������������� JtS����������������������������� J�������ni%��������'�����������������������������V��"[tS�� ��������������4����� ��W���m�S����% �������������������<����<����!���;���m�S����% �������������������<����<����!���;������%&m�S%����%��� ������������ �����������[������%&m�S%����%��� �������������;������%&m�S%����%��� �������������;������%&m�S%����%��� �������������;������%&m�S%����%��� �������������;�����5�������m�S%������������5���#�������������#������[�����5�������m�S%������������5���#�������������#������[tS�� ��������������4�����JtS�� ��������������4�����J������%&m�S%����%��� ���������Z���� �u;������%&m�S%����%��� ���������Z���� �u;tS�� ��������������4��� �VtS�� ��������������4��� �VtS�� ��������������4��� �VtS�������������������&������V MJtS������������������������������ W������%&m�S%����%��� ����������������������u;tS%������% ������������ ��������������������tS%������% ������������ ��������������������tS%������% ������������ ��������������������tS����� ����������U� ����';tS����� ����������U� ����';tS����� ����������U� ����';tS����� ����������U� ����';tS����� ����������U� ����';tS����� ����������U� ����';tS����� ����������U� ����';tS����� ����������U� ����';tS����� ����������U� ����';tS����� ����������U� ����';tS����� ���������������#����� $���#���� ^tS%��������� � ���4��������VtS%��������� � ���4��������VtS%��������� � ���4��������VtS%��������� � ���4��������VtS%��������� � ���4��������V���������#��7%��#�����!����#�W���������#��7%��#�����!����#�W���������#��7%��#�����!����#�W������%&m�S%����%��� ��������� ������JtS�� ��������������4����#�JtS�� ��������������4����#�JtS�� ��������������4����#�JtS��������������������������'����WtS�� ��������������4��$��J������E8������m�S%�������������E8�����9F+��������J�������ni%��������'��������������������������������J�������ni%��������'��������������������������������J�������ni%��������'��������������������������������J�������ni%��������'��������������������������������J�������ni%��������'��������������������������������J�������ni%��������'��������������������������������J�������ni%��������'��������������������������������J�������ni%��������'��������������������������������JtS�� ��������������4���V JtS�� ��������������4���V J�������ni%��������'���������������������������+�^�������ni%��������'���������������������������+�^������������" ��m�S%�������������������" ���������������V$������ �;������������" ��m�S%�������������������" ���������������V$������ �;������������" ��m�S%�������������������" ���������������V$������ �;���������#��7%��#�������������%&m�S������#�������&���&X������%&m�S������#�������&���&X������%&m�S������#�������&���&X������%&m�S������#�������&���&X������%&m�S������#�������&���&X������%&m�S������#�������&���&X������%&m�S������#�������&���&X������������" ��m�S%�������������������" ������������� ���������[���������"�������m�S%����%��� ������������"�����'���������J����������$��2������������$������m�S����������$����������������J����������$��2������������$������m�S����������$������������$��������J����������$��2������������$������m�S����������$������������$��������JtS� ��4���� ���� WtS%���������� �����B���������B�� ^����������$���������������$���������m�S����������$�������������������X����������$���������������$���������m�S����������$�������������������X����������$���������������$���������m�S����������$�������������������XtS� ��4���U��$�������~tS� ��4���U��$�������~����������$��2������������$������m�S����������$�����������J����������$��2������������$������m�S����������$�����������J����������$��2������������$������m�S����������$�����������J����������$��2������������$������m�S����������$�����������J����������$���������������$������������m�S����������$������������������� �J����������$��2������������$������m�S����������$����������������������C�������X����������$��2������������$������m�S����������$����������������������C�������X����������$��2������������$������m�S����������$����������������������C�������X����������$��2������������$������m�S����������$����������������������C�������X����������$��2������������$������m�S����������$����������������������C�������XtS� ��4���U�*� �V����������$��2������������$������m�S����������$��������&�$"��������&�$"���XtS� ��4��� �!��7VtS� ��4��� �!��7VtS� ��4��� �!��7V����������$��2������������$������m�S����������$����������������������������������X����������$��2������������$������m�S����������$����������������������������������X����������$��2������������$������m�S����������$����������������������������������X����������$��2������������$������m�S����������$����������������������������������X����������$��2������������$������m�S����������$����������������������������������X����������$��2������������$������m�S����������$����������������������������������X����������$��2������������$������m�S����������$����������������������������������X����������$��2������������$������m�S����������$����������� �V���J����������$��2������������$������m�S����������$����������� �V���J����������$��2������������$������m�S����������$����������� �V���JtS� ��4�������� ���$����� WtS� ��4�������� ���$����� W����������$��2������������$������m�S����������$������������������'�������� ���X����������$��2������������$������m�S����������$������������������'�������� ���X����������$��2������������$������m�S����������$������������������'�������� ���X����������$��2������������$������m�S����������$������������������'������J����������$��2������������$������m�S����������$������������������'������JtS����&��2�������������8���JtS����&��2�������������������8�������0+��������JtS����&��2�������������������8�������0+��������J��� ��m�S��������������� ����*� �V�Bm�S�����������B�����BJ�Bm�S�����������B���������B����[�Bm�S�����������B���������B����[�Bm�S�����������B�����BJ��� ��m�S��������������� ��U����JtS%�������#�&����$�#������"���XtS%�������#�&����$�#������"���XtS%�������#�&����$�#������"����'�����'��'J;�m�S���������;�����CJ;�m�S���������;������#������������!��J;�m�S���������;������#������������!��J;�m�S���������;������#������������!��J;�m�S���������;�"2��]�����m�S�����������&J�����m�S�����������&J�����m�S�����������&J�����m�S�����������&JtS��������������1� ���;tS�������������������'�������!� ;;�m�S���������;������#����!��� VtS��������������~tS��������������~;�m�S���������;�"2���X;�m�S���������;������#�������������� VtS�������������������'�+������'JtS�������������������'�+������'J;�m�S���������;�"2�����J;�m�S���������;�"����!������J;�m�S���������;������#�����������[;�m�S���������;������#�����������[;�m�S���������;������#������!��J;�m�S���������;�������&';;�m�S���������;�"2��������[;�m�S���������;�"2��������[;�m�S���������;�"2��������[;�m�S���������;�"2��������[;�m�S���������;�"2��������[;�m�S���������;�"2��������[;�m�S���������;�"2��������[;�m�S���������;������#�������!��J;�m�S���������;������#�������!��J;�m�S���������;�"2����JtS��������������� ������!��-���;�m�S���������;���  ��*�  J;�m�S���������;�"2���J;�m�S���������;�"�����!������J;�m�S���������;�"�����!������J;�m�S���������;�"�����!������J;�m�S���������;�"�����!������J;�m�S���������;�"�����!������J;�m�S���������;�"�����!������J;�m�S���������;������#����!c�;�m�S���������;������#������!��J;�m�S���������;������#������!��J;�m�S���������;������#������!��J;�m�S���������;������#������!��J;�m�S���������;������#������!��J;�m�S���������;������#������!��J;�m�S���������;������#������!��J;�m�S���������;������#������!��J;�m�S���������;������#������!��J;�m�S���������;������#�����];�m�S���������;������*�&X;�m�S���������;������*�&X;�m�S���������;������*�&X;�m�S���������;������*�&X;�m�S���������;������#��������J;�m�S���������;������#��������J;�m�S���������;������#��������J;�m�S���������;������#��������JtS���������������������;tS���������������������;tS���������������������;tS���������������������;tS���������������������;tS���������������������;;�m�S���������;������#���������� V;�m�S���������;������#���������� V;�m�S���������;������#���������� V;�m�S���������;������#���������� V;�m�S���������;������#���������� VtS��������������� �����tS��������������� �����;�m�S���������;�"���!������J;�m�S���������;�"���!������J;�m�S���������;�"���!������J;�m�S���������;�"���!������J;�m�S���������;�"���!������J;�m�S���������;�"���!������J;�m�S���������;�"���!������J;�m�S���������;������#����!�!��J;�m�S���������;���  ������ �����xtS=��U����'��$�tS=��U����'��$�tS=��U����'��$�tS=��U����'��$�;�m�S���������;������#��������J;�m�S���������;������J;�m�S���������;������J;�m�S���������;������J;�m�S���������;������J;�m�S���������;������JtS��������������� ���� ������WtS��������������� ���� ������WtS��������������� ���� ������W;�m�S���������;�������������� J;�m�S���������;�"2�����J;�m�S���������;������#�������J;�m�S���������;������#�������J;�m�S���������;������V$��J;�m�S���������;�"2����J;�m�S���������;�"2����J;�m�S���������;�"2����J;�m�S���������;�"2����J;�m�S���������;�"2����J;�m�S���������;�"2����J;�m�S���������;�"2����J;�m�S���������;�"2����J;�m�S���������;�"�"�u;;�m�S���������;�"�"�u;;�m�S���������;���  �����  J;�m�S���������;���  �����  J;�m�S���������;���  �����  J;�m�S���������;�����C��� �����'J;�m�S���������;�����C��� �����'J;�m�S���������;�����C��� �����'J;�m�S���������;�����C��� �����'J;�m�S���������;�����C��� �����'JtS���#��������"��U�#����V��RJtS���#��������"����"������������������V��RJtS���#��������"����"������������� �����"��������"JtS���#��������"��U�#����!RJtS���#��������"��U�#����$���MRJtS���#��������"�����$������&������� �� ���JtS���#��������"�����$������&������� �� ���JtS���#��������"�����$������&������� �� ���J�� ����� �m�S�����'������ ����� ������� $�$ ����������� ���DJ�� ����� �m�S�����'������ ����� ������� $�$ ����������� ���DJ�� ����� �m�S�����'������ ����� ������� $�$ ����������� ���DJ�� ����� �m�S�����'������ ����� ������� $�$ ����������� ���DJ�� ����� �m�S�����'������ ����� ������� $�$ ����������� ���DJ�� ����� �m�S�����'������ ����� ������� $�$ ����������� ���DJ�������ni������#����������������+�������� W�������ni������#����������������+�������� W�������ni������#����������������+�������� W�������ni������#����������������+�������� WtS%������������������������� ��������������$������VtS%������������������������� ���^tS%������������������������� ���^tS%������������������������� ���^tS�����������$���#������ �V�� ���&���������m�S������&� ���������������|���� W�� ���&���������m�S������&� ���������������|���� W�� ���&���������m�S������&� ���U�����MJ�� ���&���������m�S������&� ���U�����MJ�����6E8�&��m�S������#����������E89"�!��!��+���XtS%����������������������������u;�� ���&���������m�S�����'������ �������'�|������DJ�� ���&���������m�S������&� ���U��% J�� ���&���������m�S������&� ���U��% J���������m�S������#����������������� ������ J���������m�S������#����������������� ������ JtS%�����������������������������%&WtS%�����������������������������%&WtS%��������������������������������� �����JtS%��������������������������������� �����JtS%��������������������������������� �����J���������� �������$�������ni������#���������������!%�4�M+���X�������ni������#����������������+���X�������ni������#����������������+���X�������ni������#����������������+���X�������ni������#����������������+���X�������ni������#����������������+���X�������ni������#����������������+���X�������ni������#����������������+���X�������ni������#����������������+���X�������ni������#����������������+���XtS%������������������������� ���������&�������%&�����J�� ������������m�S�����'������ �������'�����DJtS%������������������������� ����������������R������'����J�� ���&���������m�S������&� ���U��V�� ���&���������m�S������&� ���U��V�� ���&���������m�S������&� ���U��V�� ���&���������m�S������&� ���U��V�� ���&���������m�S������&� ���U��V�� ���&���������m�S������&� ���U��V��������B�� �ni%������% �������B� ���&��M�!��M�DJ�������������m�S�������������������������������������V����:�����X�������%&m�S%������% ��������� ��������D������^�������%&m�S%������% ��������� ��������D������^�������%&m�S%������% ��������� ��������D������^�������%&m�S%������% ��������� ��������D������^�������%&m�S%������% ��������� ��������D������^�������%&m�S%������% ��������� ��������D������^�������%&m�S%������% ��������� ��������D������^�������%&m�S%������% ����������M� �"�������[�������%&m�S%������% ����������$���������" ���������" ���$�+���X�������%&m�S%������% ����������$���������" ���������" ���$�+���XtS�������&���#������� ���#���������XtS�������&���#������� ���#���������X% ���m�S������������������ ����"��$��&'����*�X% ���m�S������������������ ����"��$��&'����*�X�������%&m�S%������% ����������M� �"����������������������%&m�S%������% ����������M� �"����������������������%&m�S%������% ����������M� �"����������������������������m�S����������������������������������� �J�������������m�S����������������������������������� �J��������B�� �ni%������% �������B� �����(���� ���(W��������B�� �ni%������% �������B� �����(���� ���(W� ���M�� ���M��������tS������������������� ���M��������;������������ �M���[% ���m�S������������������ ����"��$����������������������'J� ���M�� ���M��m�S������������������� ���M���!� ������ J�������%&m�S%������% ������������ ����� ��(W��������B�� �ni%������% �������B� ��������$�B+���X��������B�� �ni%������% �������B� ����������J��������B�� �ni%������% �������B� ���������^��������B�� �ni%������% �������B� ���������^��������B�� �ni%������% �������B� ���������^��������B�� �ni%������% �������B� ���������^��������B�� �ni%������% �������B� ���������^��������B�� �ni%������% �������B� ���������^��������B�� �ni%������% �������B� ���������^��������B�� �ni%������% �������B� ���������^� M�� M��m�S������������������� M������&�������&������� W��������B�� �ni%������% �������B� ���&��%�����>�� ��('J��������B�� �ni%������% �������B� ���&��M����!��M����J��������B�� �ni%������% �������B� ���&��M����!��M����J��������B�� �ni%������% �������B� ���&��M����!��M����J��������B�� �ni%������% �������B� ���&��M����!��M����J�������%&m�S%������% ��������� ����� �V�������%&m�S%������% ��������� ����� �VtS�������&���#������� ��� �����V��)JtS�������&���#������� ��� �����V��)J�������%&m�S%������% ��������� ��B� �V�������%&m�S%������% ��������� ��B� �V�������%&m�S%������% ��������� ��B� �V�������%&m�S%������% ��������� ��B� �V�������%&m�S%������% ��������� ��B� �V�������%&m�S%������% ��������� ��B� �V�������������m�S��������������������������������������!�[�������������m�S��������������������������������������!�[��������B�� �ni%������% �������B� ������� �V��������B�� �ni%������% �������B� ������� �V� M�� M��m�S������������������� M�������� �����'�������������^� M�� M��m�S������������������� M�������� �����'�������������^�������%&m�S%������% ����������$���������" ���������" ���$����7J�������%&m�S%������% ����������$���������" ���������" ���$����7J�������%&m�S%������% ����������$���������" ���������" ���$����7J��������B�� �ni%������% �������B� �����(�����7����� ��&��J��������B�� �ni%������% �������B� ������ ��������+���X��������B�� �ni%������% �������B� ������ ��������+���X%&m�S����� �����"����'����';% ���m�S������������������ ����"��$�������'����$�X% ���m�S������������������ ����"��$�������'����$�X% ���m�S������������������ ����"��$�������'����$�X% ���m�S������������������ ����"��$�������'����$�X� ���M�� ���M��������tS������������������� ���M��������)�$ ������VtS�������&���#������� ��� ���������  JtS�������&���#������� ��� ���������  JtS�������&���#������� ��� ���������  JtS�������&���#������� ��� ���������  JtS�������&���#������� ��� ���������  JtS�������&���#������� ��� ���������  JtS�������&���#����.���OO����'��� ���JtS�������&���#������� ������������� ��������J%&m�S����� �����"����'���$� �<����'��';�������%&m�S%������% ����������$�������M��������$;�������%&m�S%������% ����������$�������M��������$;�������%&m�S%������% ����������$�������M��������$;�������%&m�S%������% ����������$�������M��������$;�������%&m�S%������% ����������M� �"������V�������%&m�S%������% ����������M� �"������V��������B�� �ni%������% �������B� ���&��M������ J��������B�� �ni%������% �������B� ���&��M������ J��������B�� �ni%������% �������B� ���&��M������ J��������B�� �ni%������% �������B� ���&��M������ J��������B�� �ni%������% �������B� ���&��M������ J��������B�� �ni%������% �������B� ���&��M������ J��������B�� �ni%������% �������B� ���&��M������ J��������B�� �ni%������% �������B� ���&��M������ J��������B�� �ni%������% �������B� ���&��M������ J�������������m�S��������������������������������������!��RJ�������������m�S��������������������������������������!��RJ�������������m�S��������������������������������������!��RJ�������%&m�S%������% ��������� ���+�$�����X%&m�S����� �����"����'��!�7� �V%&m�S����� �����"����'��!�7� �V%&m�S����� �����"����'��!�7� �V%&m�S����� �����"����'��!�7� �V� ���M�� ���M��������tS������������������� ���M��������;�����V ���M��������J��������B�� �ni%������% �������B� �����(������$���� A��#�W� ���M�� ���M��� �m�S������������������� ���M��� ��� ����� ��J%&m�S����� �����"����'������'��';%&m�S����� �����"����'������'��';%&m�S����� �����"����'������'��';�������������m�S��������������������������������������������������������J�������������m�S��������������������������������������������������������J��������B�� �ni%������% �������B� �����(���� ���� ������^��������B�� �ni%������% �������B� �����(���� ���� ������^��������B�� �ni%������% �������B� �����(���� ���� ������^��������B�� �ni%������% �������B� �����(���� ���� ������^��������B�� �ni%������% �������B� �����(���� ���� ������^��������B�� �ni%������% �������B� �����(���� ���� ������^��������B�� �ni%������% �������B� �����(���� ���� ������^��������B�� �ni%������% �������B� �����(���� ���� ������^tS�������&���#������� � ������� JtS�������&���#������� � ������� JtS�������&���#������� �����'J�������������m�S�������������������������������)����J�������������m�S�������������������������������)����J�������������m�S���������������������������������������V���M���������JtS�������&���#������� �1��tS%���# �� ���������� �VtS%���# �� ����*� �VtS%���# �� ����*� �VtS%���# �� ����*� �VtS%���# �� ����*� �VtS%���# �� ����*� �VtS%���# �� ����*� �VtS%���# �� ����*� �VtS%���# �� ����*� �VtS%���# �� ����*� �VtS%���# �� ����*� �VtS%���# �� �����#������ �VtS%���# �� �����#������ �VtS%���# �� ���-� �VtS%���# �� ������� �VtS%���# �� ����K��RJtS%���# �� ����K��RJtS%���# �� ���|� �VtS%���# �� ���|� �VtS%���# �� ���|� �VtS%���# �� ���|� �VtS%���# �� ���|� �VtS%���# �� ���|� �VtS%���# �� ���|� �VtS%���# �� ������[tS%���# �� ������[tS%���# �� ������[tS%���# �� ������[tS%���# �� ������[tS%���# �� ����� �VtS%���# �� ����� �VtS%���# �� ����� �VtS%���# �� ����� �VtS%���# �� ����� �V����������m�S����������������������������W����������m�S����������������������������W�������&� ��m�S�����������������!�������������X�������m�S������������������������������JtS����������,���� ���������VtS����������,���� ���������VtS����������,��� �����VtS����������,��� �����VtS����������,��� �����VtS����������,#� ����VtS����������,#� ����VtS����������,#� ����VtS����������,#� ��������VtS����������,#� ��������VtS����������,������ ������VtS����������,������ ������VtS����������,������ ������VtS���������V�����[tS����������,��������VtS����������,��������VtS����������,��������VtS����������,�����������VtS����������,�����������VtS����������,�����������VtS����������,�����������VtS����������,��N�����VtS����������,��7����VtS����������,��7����VtS����������,��7����VtS����������,��*����VtS����������,��*����VtS����������,������&����VtS����������,������&����V������m�S ������=j����������$���V������������J������m�S ������=j����������$���V������������J������m�S ������=j����������$���V������������J������m�S ������=j����������$���V������������J������m�S ������=j����������$���V������������Jl����M���m�S������4����M������� �!�$"�Xl����$�m�S������4����$�� ����V�#�� �Vl����M�"�������ki������4����M�����}����������'��';l����M��m�S������4����M���R��V%����m�S������4��=��J%����m�S������4��=��J%����m�S������4��=��J%����m�S������4��=��Jl����M�"������m�S������4����M�"���������M�����Xl����M������ni������4�����������������$�#�Wl����M������ni������4�����������������$�#�Wl����M������ni������4����������$�<|�#�W%����m�S������4���������� �Vl����MUtS������4����MU�����<������Jl����MUtS������4����MU�����<������Jl����M��m�S������4����M���������������l����M��m�S������4����M���������������l����M��m�S������4����M���������������l����$�m�S������4����$�����������J%����5�m�S������4��5������� �V%����m�S������4�������'$V%����m�S������4�������'$V%����������#m�S������4��������#�������� ����#�X%����m�S������4������=���!�Jl����M������ni������4���������������|���^%����m�S������4������ ������ �J%����5�m�S������4��5�����<��� ��J%����5�m�S������4��5�����<��� ��Jl����M������ni������4�������������� ^l����M������ni������4�������������� ^l����M������ni������4�������������� ^l����M������ni������4�������������� ^l����M��m�S������4����M�������������<�$]l����M������ni������4���������������|!����^%����5�m�S������4��5����� ��V%����5�m�S������4��5����� ��V%����5�m�S������4��5����� ��V%����5�m�S������4��5����� ��Vl����M��m�S������4����M�������*�����Xl����M��m�S������4����M�������*�����X%����m�S������4������=���� �V%����m�S������4������=���� �V%����m�S������4������=���� �Vl����M������ni������4�������������|�#�Wl����M��m�S������4����M��������������'�����<�V������;l����M��m�S������4����M��������������'�����<�V������;l����M��m�S������4����M��������������'�����<�V������;tS%���������j���������V�������*� ����tS������ � �������[tS������ ��������[) ���� $���'�m�S������� ������$ ���� $���'�U������� �V) ���� $���'�m�S������� ������$ ���� $���'�U������� �V) ���� $���'�m�S������� ������$ ���� $���'�U������� �V) ���� $���'�m�S������� ������$ ���� $���'�U������� �V%&m�S������� ������$������������ �����J%&m�S������� ������$������������ �����J%&m�S������� ������$��������������J%&m�S������� ������$��������������J%&m�S������� ������$��������"$����7������� ���� $������7J%&m�S������� ������$��������"$����7������� ���� $������7J) ���� $���'�m�S������� ������$ ���� $���'����������'J� ��m�S������� ������$�� ������ ��  J� ��m�S������� ������$�� ������ ��  J� ��m�S������� ������$�� ������ ��  J� ��m�S������� ������$�� ������ ��  J� ��m�S������� ������$�� ���&�7���� ��������&���X� ��m�S������� ������$�� ���&�7���� ��������&���X� ��m�S������� ������$�� ���&�7���� ��������&���X� ��m�S������� ������$�� ���&�7���� ��������&���X%&m�S������� ������$��'��';%&m�S������� ������$��'��';%&m�S������� ������$��'��';%&m�S������� ������$��'��';%&m�S������� ������$��'��';%&m�S������� ������$��'��';%&m�S������� ������$ ���� $�������~%&m�S������� ������$ ���� $�������~%&m�S������� ������$ ���� $�������~%&m�S������� ������$��������"$�� �����7����� $���7J%&m�S������� ������$�� �������� ��������M�  J%&m�S������� ������$�� �������� ��������M�  J) ���� $�#�M�Dm�S������� ������$ ���� $�������� ������$����'�����M�DJ%&m�S������� ������$��������- ��V) ���� $�#�M�Dm�S������� ������$ ���� $�������� ������$����'���������M�DJ) ���� $�#�M�Dm�S������� ������$ ���� $�������� ������$����'���������M�DJ) ���� $�#�M�Dm�S������� ������$ ���� $�������� ������$����'�DJ) ���� $�����ni������� ������$ ���� $�����������'�����������*�#�WtS;���� ������XtS%�����������������������������JtS%�����������������������������J������ni=�����������=�����J������ni=���������� �&������J������ni=���������� �&������J������ni=������������ ��+���X������ni=������������ ��+���X������ni=������������ ��+���X������ni=������������ ��+���X������ni=������������������V������ni=�����������������H�:J������ni=�����������������H�:J������ni=���������� � ��V������ni=���������� � ��V������ni=��������������������V������ni=��������������������V������ni=���������� ������ ���� ^������ni=���������� ������ ���� ^������ni=������������������������������G� �^������ni=������������������������������G� �^������ni=������������������������������G� �^������ni=����������U�������V������ni=����������U�������V������ni=������������������V������ni=�������������O!������J������ni=������������ ��������V������ni=������������ ���������#��$V������ni=������������ ���������#��$V������ni=�����������������*�����*�� �V������ni=�������������O����V������ni=�������������O����V������ni=�������������O����V������ni=�������������O����V������ni=�������������O����V������ni=�������������O����V������ni=�������������O����V������ni=�������������O����V������ni=�������������������������������������V������ni=�������������������������������������V������ni=���������������H�:�� V������ni=����������U���J������ni=�����������������V���V������ni=����������� ��������<�����������#J������ni=���������������4�V������ni=����������������������������"�V������ni=��������������M��N,J������ni=���������� �� �[������ni=��������������������V������ni=��������������������V������ni=��������������������V������ni=����������� �������#V������ni=�����������#�������V������ni=����������������!��V������ni=����������������!��V������ni=�����������������������V������ni=�����������������������V������ni=���������� ��V�JtS%����������������$�����*��tS%����������������$�����*��tS%����������������$����4 ���tS%������������������KJtS%������������������KJtS%������������������KJtS%������������������KJtS%������������������KJtS%������������������KJtS%�����������������JtS%����������������$����4 �!�[tS%����������������$����4 �!�[tS%����������������$����4 �!�[%�����7����*�%&m�S%�����7����*�����������VtS%����������������$�����*!�[tS%����������������$�����*!�[tS%����������������$����������$��tS%����������������������������JtS%����������������������������JtS%����������������$�����C!�[tS%������������������������JtS%������������������������JtS%���# ������������������� ��� �^tS%���# ������������������� ��� �^tS%�������������������JtS%�������������������J������������"�����J�������2"tS%����������1�9���������������"[�������2"tS%����������1�9���������������"[�������2"tS%����������1�9���������������"[�������2"tS%����������1�9���������������"[tS%�����������������������XtS%�����������������������XtS%�����������������������XtS%�����������������������XtS%�����������������������JtS%������������������������JtS%������������������������JtS%�����������������������XtS%�����������������������XtS%�����������������������XtS%�����������������������XtS%��������������������ZJtS%��������������������ZJtS%��������������������ZJtS%��������������������ZJtS%��������������������ZJtS%��������������������ZJtS%��������������������ZJtS%��������������������ZJtS%�����������������������tS%����������������������;tS%����������������������;tS%����������������������;tS%����������������������;tS%�������������������1�8�JtS%�������������������1�8�JtS%�������������������#����������JtS%���������������������������������JtS%���������������������������������JtS%���������������������������������JtS%�������������#���������������������';tS%�������������#���������������������';tS%�������������#���������������������';tS%�������������#���������������������';tS%�������������#���������������������';tS%�������������#���������������������';tS%�������������#�������������������~tS%�������������#�������������������~tS%�������������#�������������������~tS%�������������#�������������������~tS%�������������#�������������������VtS%�������������#�������������������VtS%�������������#��������������^������"�������m�S�������)��'���'�� �%�������"�����&�����!���;������"�������m�S�������)��'���'�� �%�������"�������*�R�������� ����J���;�������"�������m�S�������)��'���'�� �%����;�������|���� �����J���;�������"�������m�S�������)��'���'�� �%����;�������|���� �����J������"�������m�S�������)��'���'�� �%�������"�����'���� ��'����J������"�������m�S�������)��'���'�� �%�������"�����������u;������"�������m�S�������)��'���'�� �%�������"�����������u;������"�������m�S�������)��'���'�� �%�������"�����������u;������"�������m�S�������)��'���'�� �%�������"�����������u;������"�������m�S�������)��'���'�� �%�������"�����������u;������"�������m�S�������)��'���'�� �%�������"�����������u; �%���M��#���4��������m�S%�� �%���������������V����V �%�����D��� ��������m�S����������������������� J������"�������m�S�������)��'���'�� �%�������"�����������,��������J������"�������m�S�������)��'���'�� �%�������"�����������,��������J �%���M��#���4��������m�S%�� �%���������M�#���4����,J �%�����D��� ��������m�S��������0�0�1�����������������J������"�������m�S�������)��'���'�� �%�������"���������������J �%���M��#���4��������m�S%�� �%���������M�#���4HV������"�������m�S�������)��'���'�� �%�������"�����'������J������"�������m�S�������)��'���'�� �%�������"�����'������J������"�������m�S�������)��'���'�� �%�������"�����'������J �%���M��#���4��������m�S%�� �%���������M�#���4A�V �%���M��#���4��������m�S%�� �%���������M�#���4+���J������"�������m�S�������)��'���'�� �%�������"�����&����������V�^tS%��������������������������*� �^tS%����������������� ������ �VtS%����������������� ��!�$"�XtS%���������������������*���� ��V�WtS%�������������������$����������� WtS%�������������������$��������� JtS%����������������#���������!�7���������� WtS%����������������#���������!�7���������� W$�� ���m�S%���#��"����$�� �������� ���JtS%�����������j����$���7��H���H�:JtS%����������&���������VtS%����������&���!������~tS%����������&���!������~tS%����������&��"[tS%����������&��"[tS%����������&��"[tS%����������&��"[tS%����������&������������� WtS%����������&������������� WtS%����������&������������� WtS%����������&������������� WtS%����������&������������� WtS%����������&������������� WtS%����������&������������� WtS%����������&������������� WtS%����������&������������� WtS%����������&������������� W������ �����%&m�S�����$����� �����������#�~������ �����%&m�S�����$����� �����U�����1�0����� �V������ �����%&m�S�����$����� �����U�����1�0����� �V������ �����%&m�S�����$����� �����U�����1�0����� �V������ �����%&m�S�����$����� �����U�����1�0����� �V������ �����%&m�S�����$����� �����U�����1�0����� �V������ �����%&m�S�����$����� �����U�����1�0����� �V������ �����%&m�S�����$����� �����������!��-� �J������ �����%&m�S�����$����� �����U��#���V������ �����%&m�S�����$����� ��������������X������ �����%&m�S�����$����� ��������������XtS����������� �����JtS����������� �����JtS����������� �����JtS����������� �����JtS����������� �����JtS����������� �����JtS����������� ������ �VtS����������� ��������JtS%����������������������������������JtS%����������������������������������JtS%����������������������������������JtS%����������������������������������JtS%����������������������������������J������������� ������������������ W������������� ������������������ W������������� ��B�����BJ������������� ��B�����BJ������������� ��B�����BJ������������� ��B�����BJ������������� ��B�����BJ������������� ��B�����BJ������������� ��B�����BJ������������� ���������������������J������������� ���������������������J������������� ���������������������J������������� �������4���4�� ��V���J������������� ����V���� �V������������� ��U����4� �V������������� ��U����4� �V������������� ������������ �V������������� ������������ �V������������� ��U!�7� �V������������� ��U!�7� �V������������� ���������������������+���X������������� ���������������������+���X������������� ���" ����W������������� ������ �V������������� ������ �V������������� ������ �V������������� ��������������V���J������������� �������������� ������J������������� �������� �����J������������� ��U��� �V������������� ������������ ���� �� �V������������� ������������ ���� �� �V������������� ������������ ���� �� �V������������� ������������ ���� �� �V������������� ������������ ���� �� �V������������� ������������ ���� �� �V������������� ��������������W������������� ��������������W������������� ��������������������������������� ��������������������������������� ���H� �V������������� ���H� �V������������� ���H� �V������������� ���H� �V������������� ������������������������������ �V�J������������� �����U���� �V ������������ ��� ����������H���!����J������������� ��U�*� �V������������� �����������}��'���'J������������� �������������J������������� ��������������������'���������^������������� ��������������������'���������^������������� ��������������������'���������^������������� ������������������������ ������J������������� �������� �V������������� �������� �V������������� �������� �V������������� �������� �V������������� �������� �V������������� �������� �V������������� �������� �V������������� �������� �V������������� ������&� �V������������� ������&� �V������������� ������&� �V������������� ������&� �V������������� ������&� �V������������� ������&� �V������������� ������&� �V������������� ������&� �V������������� ������&� �V������������� ������&� �V������������� ������&� �V������������� ������&� �V������������� ������������������!� W������������� ������������������!� W������������� ������������������!� W������������� ��������M�������M�����^������������� ��������� � �V������������� ��������� � �V������������� �������������� ��H�:�������� �^������������� ����� ��� �V������������� ����� ��� �V������������� ����� ��� �V������������� ����� ��� �V������������� ����� ��� �V������������� ������������������������ �V������������� ������������������������ �V������������� ������������������������ �V������������� ������������������������ �V������������� ������������������������ �V������������� ������������������������ �V������������� ������������������������ �V������������� ������������������������������������ ����������������J������������� ����������������J������������� ����������������J������������� ����������������J������������� ����������������J������������� ���������������������&������&���*J������������� ���������������������&������&���*J������������� ��������������������V���J������������� ���������������������������� W������������� ���" ������ ��HJ������������� �����������}���������� ���� ������~������������� ����������� �J������������� ����������� �J������������� ����������� �J������������� ����������� �J������������� ��U�����W������������� ����4�� �V������������� ����4�� �V������������� ����4�� �V������������� ����4�� �V������������� ����4�� �V������������� ����4�� �V������������� ����4�� �V������������� ����4�� �V������������� ����4�� �V������������� ������7����&���� �����&� �V������������� ������7����&���� �����&� �V������������� ��������� ������J������������� ��������� ������J������������� ��������� ������J������������� ��������� ������JtS%�������� �����JtS%�������� �����JtS%�������� �����JtS%�������� �����JtS%�������� �����J�������$�����m�S�����_ ��������$������� ���V����$���J�������$�����m�S�����_ ��������$������� ���V����$���J�������$�����m�S�����_ ��������$������� ���V����$���J�������$�����m�S�����_ ��������$������� ���V����$���JtS%���������� �"����}�����������������+����A�VtS%���������� �"���1�������7V������"$��������� ��������������$��������'��V�'�4�J������"$��������� ��������������$��������������������J������"$��������� ��������������$��������������������J������"$��������� ��������������$��������������������J������"$��������� ��������������$��������������������J������"$��������� ��������������$��������������������J������"$��������� ��������������$��������������������J������"$��������� ��������������$��������������������J������"$��������� ��������������$��������'��V�'�4�J������"$��������� ��������������$������������������$���J������"$��������� ��������������$������������������$���J������"$��������� ��������������$������������������$���J������"$��������� ��������������$������������������$���J������"$��������� ��������������$������������������$���J������"$��������� ��������������$������������������$���J������"$��������� ��������������$������������������$���J������"$��������� ��������������$������������������$���J������"$��������� ��������������$������������������$���J������"$��������� ��������������$������������������$���J������"$��������� ��������������$������������������$���J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J������"$��������� ��������������$������R����J��ni%����d�������������������V��ni%����d������������� �|���V��ni%����d�����������������������V��ni%����d�������������������V��ni%����d������������������V��ni%����d������������������VwtS%����������.�������.��������� �����������[wtS%����������.�������.��������� �����������[tS����������� ������� �JtS����������� ������� �JtS����������� ������� �JtS����������� ������+�[tS����������� ������+�[tS������������������!��[tS����������� ��������� ������V$���^tS����������� ��������� ������V$���^tS����������� ���������� �JtS����������� ���������� �JtS����������� ���������� �JtS����������� ���������� �JtS����������� ���������� �JtS����������� ���������� �JtS����������� ���������� �J��������m�S%��������&�����$�1������������������W��������m�S%��������&�����$�1����������������J��������$m�S�����������������$� �<����J��������$m�S�����������������$� �<����J��������$m�S�����������������$� �<����J��������$m�S�����������������$� �<����J��������$m�S�������������}�&����$������!����^�m�S��������������������������H�:J�m�S��������������������������H�:J��������$m�S�������������}U���-J��������$m�S�������������}�������������$+���X��������$m�S�������������}����������X��������$m�S�������������}����������X��������$m�S�������������}����������X��������$m�S�������������}�&����$��!����^��������$m�S�������������}�&����$��!����^��������$m�S�������������}�&����$��!����^tS%����������� ��� WtS%������������������JtS%������������������JtS%������������������JtS%������������������JtS%������������������JtS%������������������JtS%������������������JtS%������������ �����xtS%����������Z1���JtS%���������U� �JtS%����������Z�KJtS%����������Z�KJtS%����������Z�KJtS%����������Z�KJtS%����������Z�KJtS%����������Z�KJtS%����������Z�KJtS%����������Z�KJtS%����������Z�KJtS%����������Z�KJtS%����������Z�KJtS%����������Z�KJtS%����������Z�KJtS%�������������������������JtS%������������ ��+���XtS%�����������������BJtS%�����������������BJtS%����������Z�����K��tS%����������Z�����K��tS%����������Z�����K��tS%����������Z�����K��tS%����������Z�����K��tS%����������Z�����K��tS%����������Z�����K��tS%����������Z�����K��tS%����������Z�����K��tS%����������Z�����K��tS%����������Z�����K��tS%��������������������VtS%��������������������VtS%��������������������VtS%��������������������VtS%���������U������JtS%���������������������$���������������^tS%���������������������$���������������^tS%����������� ����������� �VtS%����������$��!�$"  �����WtS%����������Z��������JtS%����������$������������XtS%����������$������������XtS%����������Z��V ����!�[tS%����������Z���������������$�tS%��������������� ����VtS%��������������� ����VtS%��������������� ����VtS%��������������� ����VtS%��������������� ����VtS%��������������� ����VtS%����������$�����������WtS%����������$�����������WtS%����������$�����������WtS%����������$�����������WtS%��������������JtS%��������������JtS%��������������JtS%��������������JtS%��������������JtS%����������� ��V JtS%����������� ��V JtS%����������Z�������������tS%����������Z�������������tS%����������Z�������^tS%������������ ���&��"�;tS%����������Z��������������tS%����������Z��������������tS%����������Z��������������tS%����������Z��������������tS%����������Z������������ WtS%����������Z������������ WtS%����������Z������������ WtS%����������� �������V JtS%��������������������VtS%��������������������VtS�� ���������������������JtS�� �����������������'��������JtS�� �������������������������JtS�� �������������������������JtS�� �������������������������JtS�� �������������������������J%&m�S��������������$���&'����^%&m�S��������������$���&'����^%&m�S������������������������'����K�;�������jtS%��������������������������u;�����ni%��������������������<���J���4�������ni���4��������Z���� ���� W���4�m�S����$ ��#����4��������+�J���4�������ni���4��������#�� �������������[���4�������ni���4��������#�� �������������[���4�������ni���4��������������#�� ������[���4�������ni���4��������������#�� ������[���4�������ni���4������������*���������� ����*J���4�m�S����$ ��#����4��#�� �������J���4�m�S����$ ��#����4��#�� �������J���4�m�S����$ ��#����4����������������J���4�m�S����$ ��#����4����������������J���4�������ni���4�������������*������*����+�J���4�������ni���4�������������*������*����+�J���4�������ni���4��������#�� ����������������������[���4�m�S����$ ��#����4��� J���4�m�S����$ ��#����4����������� �������������!�&������J���4�������ni���4�����������������������J���4�m�S����$ ��#����4��#��  ���������������� J���4�m�S����$ ��#����4��������B����J���4�m�S����$ ��#����4��������JtS�����������" ��������������!��JtS�����������5������ �VtS�����������5������ �VtS�����������5������ �VtS�����������5������ �VtS�����������5������ �VtS�����������& �������������� JtS�����������& �������������� JtS�����������& �������������� JtS�����������& �������������� JtS�����������& �������������� JtS�����������& �������������� JtS�����������& �������������� JtS�����������& �������������� JtS�����������& �������������� JtS�����������& �������������� JtS�����������& �������������� JtS�����������& �������������� JtS������������ ���������~tS�����������5��!��[tS������������������JtS���������������������������+���XtS������������ ����&)��VtS������������ ����&)��VtS������������ ����&)��VtS������������ ����&)��VtS����������������������JtS����������������������JtS����������������������JtS������������ ����� �VtS������������ ��������������!���� �VtS%��������&�������.� ������&���� ���WtS%��������&���������*������� ���WtS%��������&�������U��� �VtS%��������&�������U��� �VtS%��������&�������U��� �VtS%��������&�������U��� �VtS%��������&�������U���4��&�� �VtS%��������&���������!�����"JtS%��������&���������!���������"[tS%��������&��������"!���� �"[tS%��������&���&��� ���K���V�����tS%��������&�������.� ��������� ���WtS%��������&�������.� ���!��� ���WtS%��������&�������.� ���!��� ���WtS%��������&��������"!�������"[tS%��������&��������"!�������"[%&m�S%���� �����#�������&��������������������4������������J����m�S%���� �����#�����U��C� �J���m�S%���� �����#���������U���� �J���m�S%���� �����#���������U���� �J%&m�S%���� �����#�������&��������������$����m�S%���� �����#������������������"��C����X%&m�S%���� �����#�������&���������������������J%&m�S%���� �����#�����U�7J%&m�S%���� �����#�����U�7J%&m�S%���� �����#�����U�7J%&m�S%���� �����#�����U�7J%&m�S%���� �����#�������&����������&�������������~%&m�S%���� �����#�������&�����������������������J%&m�S%���� �����#�������&����������������-J%&���������������@�����>-J%&��������������BBu;%&��������������BBu;%&��������������������������� W%&��������������������������� W%&��������������������������� W%&��������������������������� W%&��������������������������� W%&��������������������������� W%&��������������������������� W%&��������������������������� W%&�������������������������� ^%&���������������&��� ���I��!����" W%&���������������&��� ���I��!����" W%&���������������&��� ���I��!����" W%&��������������U�������u;%&��������������U�������u;%&���������������������������� ���XwtS%��������j���U���JwtS%��������j���������������XwtS%��������j���U���JwtS%��������j���U���JtS%��������������"�������_ ���1!���^tS%��������������"�������_ �����������~tS%��������������"�������_ ���#���������#�����������JtS%��������������"�������_ ���#���������#�����������JtS%��������������"�������_ ���#���������#�����������JtS%��������������"�������_ ���#���������#�����������JtS%��������������"�������_ ���� ���JtS%��������������"�������_ ���� ���JtS%��������������"�������_ �����0�4�D����,�����������JtS%��������������"�������_ �����0�4�D����,�����������JtS%��������������"�������_ ���������JtS%��������������"�������_ ���#����������������JtS%��������������"�������_ ������&�����������������$�������� ���#[tS%��������������"�������_ ������&�����������������$�������� ���#[tS%��������������"�������_ ������� �����$���~tS%��������������"�������_ ���#���������Z���������JtS%��������������"�������_ �����0�8�&��&���������������JtS%��������������"�������_ �����0�1�"$�����R����������JtS%��������������"�������_ �����0�1�"$�����R����������JtS%��������������"�������_ �����0�1�"$�����R����������JtS%��������������"�������_ �����0�1�"$�����R����������JtS%��������������"�������_ �����0�1�"$�����R����������JtS%��������������"�������_ �����0�1�"$�����R����������JtS%��������������"�������_ �����0�1�"$�����R����������JtS%��������������"�������_ �����0�1�"$�����R����������JtS%��������������"�������_ �����0�1�"$�����R����������JtS%��������������"�������_ �����0�1�"$�����R����������JtS%��������������"�������_ �����0�1�"$�����R����������JtS%��������������"�������_ �����0�1�"$�����R����������JtS%��������������"�������_ ���� ���JtS%��������������"�������_ ���� ���JtS%��������������"�������_ ���� ���JtS%��������������"�������_ ���� ���JtS%��������������"�������_ ���� ���JtS%��������������"�������_ ���� ���JtS%��������������"�������_ ���� ���JtS%��������������"�������_ ���� ���JtS%��������������"�������_ �����0�8�&��&����������8����JtS%��������������"�������_ �����0�9���������������JtS%��������������"�������_ �����0�9���������������JtS%��������������"�������_ ���#�����������������JtS%��������������"�������_ �����0�1�"$�����|�����RJtS%��������������"�������_ �����'��� ����JtS%��������������"�������_ �����'��� ����JtS%��������������"�������_ �����'��� ����JtS%��������������"�������_ �����'��� ����JtS%��������������"�������_ �����'��� ����JtS%��������������"�������_ �����'��� ����JtS%��������������"�������_ �����'��� ����JtS%��������������"�������_ �����'��� ����JtS%��������������"�������_ �����'��� ����JtS%��������������"�������_ ������ ��'!����$���~tS%��������������"�������_ ������� �����('JtS%��������������"�������_ ���#��������������JtS%��������������"�������_ ����������~tS%��������������"�������_ �����'������JtS%��������������"�������_ �����'������JtS%��������������"�������_ �����'������JtS%��������������"�������_ �����'������JtS%��������������"�������_ �����'������JtS%��������������"�������_ �����'������JtS%��������������"�������_ �����'������JtS%��������������"�������_ �����'������JtS%��������������"�������_ �����'������JtS%��������������"�������_ �����'������JtS%��������������"�������_ �����'������JtS%��������������"�������_ �����'������JtS%��������������"�������_ �����'������JtS%��������������"�������_ �����'������J����&��������$�������8m������������������&���������������" �J���"��� ��"�����"��m�S%�������� ���������������M���������������'��������$�����4���������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'�����������'��������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'�����������'��������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'�����������'��������#��$����J�������� ���%��m�S%�������� ��������� ��������������������� �J���"��� ��"�����"��m�S%�������� ���������������M�������$���������� ��������������� ����'�����J����������m�S%�������� ��������������� �#��$����J����������m�S%�������� ��������������� �#��$����J����������m�S%�������� �����������������������+��������J����������m�S%�������� �����������������������+��������J���"��� ��"�����"��m�S%�������� ���������������M��������������'�V���J���"��� ��"�����"��m�S%�������� ���������������M��������������'�V���J���"��� ��"�����"��m�S%�������� ���������������M��������������'�V���J���"��� ��"�����"��m�S%�������� ���������������M��������������'�V���J���"��� ��"�����"��m�S%�������� ���������������M��������������'�V���J�� ���� ��������"�����4���������m�S%�������� ��� ���� ��������"�����4��������������4������$�4[���"��� ��"�����"��m�S%�������� ���������������M�������$������������ �����'������������ ����'�����J�� ��}���M�$�����m�S%�������� ��� ��}���M���� ���������"�;����������m�S%�������� ���������������������'���J�� ���� ������#�� ����&�������m�S%�������� ��� ���� ������#�� ����&����������� ��������'!�������^"�������� m�S%�������� �"���� ��� �����������;"�������� m�S%�������� �"���� ��� �����������;"�������� m�S%�������� �"���� ��� �����������;"�������� m�S%�������� �"���� ��� �����������;�� ���� ��������"��$*�����m�S%�������� ��� ���� ��������"��$*�������������^�� ���� ��������"��$*�����m�S%�������� ��� ���� ��������"��$*�������������^�� ���� �������#��%��������m�S%�������� ��� ���� �������#���������������4[�� ���� �������#��%��������m�S%�������� ��� ���� �������#���������������4[�� ���� �������#��%��������m�S%�������� ��� ���� �������#���������������4[�� ���� ��������"�����������������m�S%�������� ��� ���� ��������"�������������������� �������J�� ���� �������� $�����m�S%�������� ��� ���� �������� $��������� ��7�������$�4[���"��� ��"�����"��m�S%�������� ���������������M���������������'�����������4���������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'�����������4���������#��$����J���"��� ��"�����"��m�S%�������� ���������������M��������������'�����������'�����J���"��� ��"�����"��m�S%�������� ���������������M��������������'�����������'�����J���"��� ��"�����"��m�S%�������� ���������������M��������������'�����������'�����J���"��� ��"�����"��m�S%�������� ���������������M��������������'�����������'�����J�� ���� ��������"��������m�S%�������� ��� ���� ��������"����������$�������4���J�� ���� ��������"��$*�����m�S%�������� ��� ���� ��������"��$*������������4���J����������m�S%�������� �������������7��������#�������%���+���X����������m�S%�������� �������������7��������#�������%���+���X���"��� ��"�����"��m�S%�������� ���������������M���������������'��������������4���������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'��������������4���������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'��������������4���������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'��������������4���������#��$����J�� ���� �������������&�������m�S%�������� ��� ���� �������������&����������� ���4��'!�������^�� ���� ��������"�����������������m�S%�������� ��� ���� ��������"�������������������� ����������^���"��� ��"�����"��m�S%�������� ���������������MU������� �J���"��� ��"�����"��m�S%�������� ���������������MU������� �J�������� ��������"m�S%�������� ��������� ��������"�������������"��� �J�������� ��������"m�S%�������� ��������� ��������"�������������"��� �J�������� ��������"m�S%�������� ��������� ��������"�������������"��� �J�� ���� ��������"�����4��������m�S%�������� ��� ���� ��������"�����4�������������4�!�$"�������^���"��� ��"�����"��m�S%�������� ���������������M�������$������������ �������������- ��������� ����'�����J���"��� ��"�����"��m�S%�������� ���������������M�������$������������ �������������- ��������� ����'�����J���"��� ��"�����"��m�S%�������� ���������������M�������$������������ �������������- ��������� ����'�����J�� ���� �������� $�����m�S%�������� ��� ���� �������� $��������� ��7!��J������%��"����"������m�S%�������� ���������"��"����������"����"$�����������"����+��������J������%��"����"������m�S%�������� ���������"��"����������"����"$�����������"����+��������J������%��"����"������m�S%�������� ���������"��"����������"����"$�����������"����+��������J����������m�S%�������� ������������������'����#�����������J����������m�S%�������� ������������������'����#�����������J����������m�S%�������� �������������7���M�"���� ��V���#��$����J���"��� ��"�����"��m�S%�������� ���������������M�����������������'���������';���"��� ��"�����"��m�S%�������� ���������������M�������$�����4������ �����4����B4�������� ����'�����J���"��� ��"�����"��m�S%�������� ���������������M���������������'���������� ���������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'���������� ���������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'���������� ���������#��$����J�� ���� ��������"��������m�S%�������� ��� ���� ��������"����������$���J�� ���� ��������"��������m�S%�������� ��� ���� ��������"����������$���J�������� ����m�S%�������� ��������� ������������������!� �����J�������� ����m�S%�������� ��������� ������������������!� �����J�������� ����m�S%�������� ��������� ������������������!� �����J�������� ����m�S%�������� ��������� ������������������!� �����J�������� ����m�S%�������� ��������� ������������������!� �����J�������� ����m�S%�������� ��������� ������������������!� �����J���"��� ��"�����"��m�S%�������� ���������������M�������$��� � �������� ��� � ���������������� ����'�����J�������������m�S%�������� ������������������<��'����� J�������������m�S%�������� ������������������<��'����� J�������������m�S%�������� ������������������<��'����� J����������m�S%�������� �������������������� J�������m�S%�������� ����������7�$�����������4�!��J���"��� ��"�����"��m�S%�������� ���������������M����������4���'�����������'�"�� ���'�����J���"��� ��"�����"��m�S%�������� ���������������M����������4���'�����������'�"�� ���'�����J���"��� ��"�����"��m�S%�������� ���������������M����������4���'�����������'�"�� ���'�����J���"��� ��"�����"��m�S%�������� ���������������M�������$����������� �������������� ����'�����J����������m�S%�������� �������������7��������'����+��������J����������m�S%�������� �������������7��������'����+��������J����������m�S%�������� �������������7��������'����+��������J����������m�S%�������� �������������7��������'����+��������J����������m�S%�������� �������������7��������'����+��������J������%��"����"������m�S%�������� ���������"��"����������"���$������������"����+��������J������%��"����"������m�S%�������� ���������"��"����������"���$������������"����+��������J���"��� ��"�����"��m�S%�������� ���������������M���������������'��������������������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'��������������������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'��������������������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'��������������������#��$����J���"��� ��"�����"��m�S%�������� ���������������MU��� ��� �J���"��� ��"�����"��m�S%�������� ���������������MU��� ��� �J���"��� ��"�����"��m�S%�������� ���������������MU��� ��� �J���"��� ��"�����"��m�S%�������� ���������������M���������������'���������� �����������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'���������� �����������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'���������� �����������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'���������� �����������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'���������� �����������#��$����J�� ���� ������#�� ����&�������m�S%�������� ��� ���� ������#�� ����&����������� ��������'!��J����������m�S%�������� �������������7�$�G����+���X���"��� ��"�����"��m�S%�������� ���������������M����������$ ���� �������$����"��� ��"�����"��m�S%�������� ���������������M����������$ ���� �������$�������%��"����"������m�S%�������� ���������"��"����������"����"$��������"�$����R����J���"��� ��"�����"��m�S%�������� ���������������M���������������'��������������4���������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'��������������4���������#��$����J�� ���� ��������"�����4��������m�S%�������� ��� ���� ��������"�����4�������������4��������^�� ���� ��������"�����4��������m�S%�������� ��� ���� ��������"�����4�������������4��������^�� ���� ��������"�����4��������m�S%�������� ��� ���� ��������"�����4�������������4��������^�� ���� ��������"�����4��������m�S%�������� ��� ���� ��������"�����4�������������4��������^�� ���� ��������"�����4��������m�S%�������� ��� ���� ��������"�����4�������������4��������^�� ���� ��������"�����4��������m�S%�������� ��� ���� ��������"�����4�������������4��������^������%��"����"������m�S%�������� ���������"��"���������#�����"$�����#�����R����J���"��� ��"�����"��m�S%�������� ���������������M����������������� �J���"��� ��"�����"��m�S%�������� ���������������M����������������� �J����������m�S%�������� �������������7���M�!� ���+���X�� ���� ��������"�����������m�S%�������� ��� ���� ��������"�������������$��4[�� ���� ��������"�����������m�S%�������� ��� ���� ��������"�������������$��4[�������� ����m�S%�������� ��������� ��������������������J�� ���� ��������"��$*��������m�S%�������� ��� ���� ��������"��$*����������V�� ������$�4[�������� ���%��m�S%�������� ��������� ����������������"�����J�������� ���%��m�S%�������� ��������� ����������������"�����J�������� ��������"m�S%�������� ��������� ��������"�������������"����4��������J�������� ��������"m�S%�������� ��������� ��������"�������������"����4��������J�������� ��������"m�S%�������� ��������� ��������"�������������"����4��������J���"��� ��"�����"��m�S%�������� ���������������M�������$��� � �������� ��� � ���� ������� ����'�����J���"��� ��"�����"��m�S%�������� ���������������M���������������'����������$�4�������������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'����������$�4�������������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'����������$�4�������������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'����������$�4�������������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'����������$�4�������������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'����������$�4�������������#��$����J�� ���� ��������"�����������������m�S%�������� ��� ���� ��������"����������������������������������^����������m�S%�������� �������������������������J����������m�S%�������� �������������������������J���"��� ��"�����"��m�S%�������� ���������������M�������������*��*� �����J���"��� ��"�����"��m�S%�������� ���������������M�������������*��*� �����J�������� �������#ki%�������� ��������� �������#�����������#�����������J�������������m�S%�������� �������������������'R���������J�������������m�S%�������� �������������������'R���������J�� ��}���M�$�����m�S%�������� ��� ��}���M�$����������%��[���"��� ��"�����"��m�S%�������� ���������������M����������4���'�����������"�� ���'�����J���"��� ��"�����"��m�S%�������� ���������������M����������4���'�����������"�� ���'�����J�� ���� �������#�������������m�S%�������� ��� ���� �������#�������������������V���"��� ��"�����"��m�S%�������� ���������������M�����������2��� �$�����'���� �^���"��� ��"�����"��m�S%�������� ���������������M�����������2��� �$�����'���� �^���"��� ��"�����"��m�S%�������� ���������������M�����������2��� �$����V���M��� �!� &����� �^����������m�S%�������� �������������7���M���D���������������D����J����������m�S%�������� �������������7���M���D���������������D����J���"��� ��"�����"��m�S%�������� ���������������M��������������'���������� �����'�����J���"��� ��"�����"��m�S%�������� ���������������M��������������'���������� �����'�����J���"��� ��"�����"��m�S%�������� ���������������M��������������'���������� �����'�����J�� ���� ��������"�����4��������m�S%�������� ��� ���� ��������"�����4�������������4��$�!�$"�������^������%��"����"������m�S%�������� ���������"��"�������#������"��������J�������������m�S%�������� ��������������U���&���������������';���"��� ��"�����"��m�S%�������� ���������������M�������$��� � �������� �����'�� � ������� ����'�����J���"��� ��"�����"��m�S%�������� ���������������M���������������'�����������'��#�������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'�����������'��#�������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'�����������'��#�������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'�����������'��#�������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'�����������'��#�������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'�����������'��#�������#��$����J�������m�S%�������� ����������7�$�-��������" ��& � !��J���"��� ��"�����"��m�S%�������� ���������������M���������������'��������� � ����#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'��������� � ����#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������� �����'������ ����'�����J���"��� ��"�����"��m�S%�������� ���������������M���������������� �����'������ ����'�����J���"��� ��"�����"��m�S%�������� ���������������M���������������� �����'������ ����'�����J���"��� ��"�����"��m�S%�������� ���������������M���������������� �����'������ ����'�����J�� ��}���M�$�����m�S%�������� ��� ��}���M���� �����������M���J�� ���� ��������"�����������������m�S%�������� ��� ���� ��������"�������������������� ���������"���J�� ���� ��������"�����������������m�S%�������� ��� ���� ��������"�������������������� ���������"���J�� ���� �������������&�������m�S%�������� ��� ���� �������������&����������� ��������������^����������m�S%�������� �������������7��������'��������+��������J�� ���� ��������"�����4��������m�S%�������� ��� ���� ��������"�����4�������������4�H�:�����^���"��� ��"�����"��m�S%�������� ���������������M��������������'�����������'�����J���"��� ��"�����"��m�S%�������� ���������������M��������������'�����������'�����J���"��� ��"�����"��m�S%�������� ���������������M��������������'�����������'�����J���"��� ��"�����"��m�S%�������� ���������������M��������������'�����������'�����J�������� ����m�S%�������� ��������� ����������������$�4������ ���%��!� �����J�������� ����m�S%�������� ��������� ����������������$�4������ ���%��!� �����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������������#��$����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������������#��$����J������%��"����"������m�S%�������� ���������"��"����������"���$���������"�V���������$����J���"��� ��"�����"��m�S%�������� ���������������M������������������������ �"�����#�J�� ���� ��������"�����4��������m�S%�������� ��� ���� ��������"�����4�������������4����������^�� ���� ��������"�����������m�S%�������� ��� ���� ��������"�������������$�������4��4[�� ���� �������������&�������m�S%�������� ��� ���� �������������&����������� ���������J�������m�S%�������� ����������7�������#�������!��J�������m�S%�������� ����������7�������#�������!��J�������m�S%�������� ����������7�������#�������!��J����������m�S%�������� ������������������������J�� ���� �������������&�������m�S%�������� ��� ���� �������������&����������� ��������:��J���"��� ��"�����"��m�S%�������� ���������������M�������$��� � �������� ��� � ���$���������� ����'�����J���"��� ��"�����"��m�S%�������� ���������������M����������4���'��������� ��#�*�"�� ���'�����J���"��� ��"�����"��m�S%�������� ���������������M����������4���'��������� ��#�*�"�� ���'�����J���"��� ��"�����"��m�S%�������� ���������������M����������4���'��������� ��#�*�"�� ���'�����J�� ���� ��������"�����4��������m�S%�������� ��� ���� ��������"�����4�������������4�������4������^���"��� ��"�����"��m�S%�������� ���������������M���������������'������������ �����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������ �����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������ �����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������ �����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������ �����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������ �����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������ �����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������ �����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������ �����J���"��� ��"�����"��m�S%�������� ���������������M���������������'������������ �����J�� ���� ��������"�����4��������m�S%�������� ��� ���� ��������"�����4�������������4������������^�� ���� �������#�������������m�S%�������� ��� ���� �������#������������������4[�� ���� �������#�������������m�S%�������� ��� ���� �������#������������������4[�� ���� �������#�������������m�S%�������� ��� ���� �������#������������������4[������%��"����"������m�S%�������� ���������"��"���������#�����"$��������#�����+��������JtS%�����������&U�������tS%�����������&U�������tS%�����������&U�������tS%�����������&U�������tS%�����������&U�������tS%�����������&U�������tS%�����������&U�������tS%�����������&U�������tS%�����������&U�������tS%�����������&U�������tS%�����������&U�������tS%�����������&U�������� �VtS%�����������&U�������� �VtS%�����������&U������WtS%�����������&U������WtS%�����������&U������WtS%�����������&U�������'!����^tS%�����������&U�������'!����^tS%�����������&U�������'!����^tS%�����������&U�����!� WtS%�����������&U�����!� WtS%�����������&U����!����^tS%�����������&U���!����^tS%�����������&U���!����^tS%�����������&U���!����^wtS%��������������#�JwtS%��������������#�JwtS%��������������#�JwtS%����������������JtS�������*�����������������'����WtS�������*�����������������WtS�������*�����������������WtS�������*�������������������WtS�������*�������������������WwtS%���������������4��������"�JwtS%���������������4��������"�JwtS%���������������4��������"�JtS%������% �;����������������������� ���JtS%������% �;���������'�&����<�-JtS%������% �;���������'�&����<�-JtS%������% �;���������'�&����<�-JtS%������% �;���������'�&����<�-JtS%������% �;���������'�&����<�-JtS%������% �;���������'�&����<�-JtS%������% �;�������������������<�����7��JtS%������% �;������������ ���JtS%������% �;��������������&�M��JtS%������% �;���������;tS%������% �;���������;tS%������% �;���������'�&��:�JtS%������% �;���� �� �JtS%������% �;������������V��������XtS��������������������%&m�S%��������#.������#��M�U����� �J��%&m�S%��������#.������#��M��������V�������J��%&m�S%��������#.������#��M��������V�������J��%&m�S%��������#.������#��M��������V�������J��%&m�S%��������#.������#��M��������V�������J���#��Mm�S%��������#.������#��M�����#��M����� � ����������� �^���#��Mm�S%��������#.������#��M�����#��M����� � ����������� �^���#��Mm�S%��������#.������#��M�����#��M��������� �V���#��Mm�S%��������#.������#��M�����#��M�#�����������������������#��Mm�S%��������#.������#��M�����#��M����#�<� �����#�<� �� �������#��Mm�S%��������#.������#��M�����#��M����#�<� �����#�<� �� �������#��Mm�S%��������#.������#��M�����#��M����#�<� �����#�<� �� �������#��Mm�S%��������#.������#��M�����#��M����#�<� �����#�<� �� �������#��Mm�S%��������#.������#��M�����#��M����#�<� �����#�<� �� �������#��Mm�S%��������#.������#��M�����#��M�#����������?X���#��Mm�S%��������#.������#��M�����#��M�#����������?X���#��Mm�S%��������#.������#��M�����#��M��������������#�W���#��Mm�S%��������#.������#��M�����#��M��������������#�W��%&m�S%��������#.������#��M��������������%&m�S������� ���������� ��������J������%&m�S������!�[������%&m�S������!�[������%&m�S������!�[������%&m�S������!�[������%&m�S������!�[������%&m�S�����B�������BJ������%&m�S�����B�������BJ������%&m�S�����B�������BJ������%&m�S������� ���� ���� ���� �������� W������%&m�S������� ����� ��K���X������%&m�S������� ����� ��K���X������%&m�S�����������(����������^������������ ni������������������ V������������ ni������������������ V������������ ni������������������ V������������ ni������������������ V������������ ni������������������ V������������ ni������������������ V������������ ni������������������ V������%&m�S��������#�������'��#�X������%&m�S��������#�������'��#�X������%&m�S��������� ���� �����J������%&m�S������� ���������V������%&m�S������� ���������� ���~���������"�������m�S������������������!�����������X������%&m�S���������������[������%&m�S������� ������������� J������%&m�S������� ������������� J������%&m�S��������#�����#�����~���������"�������m�S���������"�������������J���������"�������m�S���������"�������������J������%&m�S������� ������&�RJ������%&m�S����������*��������������J������%&m�S��������1�8����������J������%&m�S��������1�8����������J������%&m�S������������(W���������"�������m�S����������������4����"��^���������"�������m�S����������������4����"��^������m�S��������������;������m�S��������������;������m�S��������������;������m�S�������������';������m�S�������������';������m�S�������������';������m�S�������������';������m�S���������&�'���������J������m�S���������&�'���������J������m�S���������&�'���������J������m�S���������&�'���������J������m�S����������� J������m�S����������� J������m�S������������� ��1��������� ��J������m�S������������� ��1��������� ��J)���� m�S�������)���� ������ W)���� m�S�������)���� ���� ��� W��ni���������������:����������J��ni�������������# ���[��ni�������������# ���[��ni�������������# ���[)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V)otS�������)o������&V��ni��������������" ����;5��2"tS�������5�"����������������"[�����#��$m�S���������������*���������]����5�����m�S�����������5�������������#+�$���J����5�����m�S�����������5�������������#+�$���J��ni��������������" �������*����J)���� m�S�������)���� ���� ��';5����$m�S�������5����$�����+�$��#���� �^5��2"tS�������5�"��������� W5��2"tS�������5�"��������� W���m�S���������������^���m�S���������������^���m�S���������������^���m�S���������������^����m�S������������ ���$� �V����m�S������������ ���$� �V����m�S������������ ���$� �V����m�S������������ ���$� �V����m�S������������ ���$� �V����m�S������������ ���$� �V��ni���������������:��"���J��ni���������������:��"���J�m�S����������������u;tS%�����������4��������4����������������JtS%�����������4��������4���������� JtS%�����������4��������4���������� JtS%�����������4��������4���������� JtS%�����������4��������4���������� JwtS%������ ���������*�74�.�������*H����JwtS%������ ���������*�74�.�������*H����JwtS%������ ���������*�74�.�������H����JwtS%������ ���������*�74�.����#��M��"�����M�#�WwtS%������ ���������*�74�.�������*H�"�JwtS%������ ���������*�74�.�������*H�"�JwtS%������ ���������*�74�.�������*H�"�JwtS%������ ���������*�74�.�������*H�"�JwtS%������ ���������*�74�.�������*H�"�JwtS%������ ���������*�74�.�������*H�"�JwtS%������ ���������*�74�.�������*H�"�JwtS%������ ���������*�74�.�������*H�"�J��������������Dm�S��������I���� ���������������V��������������Dm�S��������I���� ���������������V�� �����������#����%������*������m�S�������� �������������J��������������Dm�S��������I���� ��������� ������'�D�V�<�����������������������m�S%�������� ����������������J���������������) �������D� ����m�S����������������) �������D� ������D����M���~���������������) �������D� ����m�S����������������) �������D� ������D����M���~���������������) �������D� ����m�S����������������) �������D� ������D����M���~���������������) �������D� ����m�S����������������) �������D� ������D����M���~������.�$��������������$����D���Mm�S������������"����������� ���� ������� u;����������������I� �#��� �#� ����D���Mm�S%�������� ��� �#���������"#����&�D����MJ������������������#���������������#�����D�"�����������m�S��������������������������� ������ �^���������� �����������������������m�S������������"������������ ����" ����D�������� �;������������� � �����������m�S��������������������������~tS���������������������������^tS���������������������������^tS���������������������������^tS����������������������������������JtS���������������������������[��������������<��������������!� W�"$������������<���"$�����$�������('J���������&������������<�������&�"%�*� ����� x���������������<�����o���"�����&V� ����������������<� ���������&������J�����D������������<�������D�������V������� J�����D������������<�������D�������V������� J�����D������������<�������D����������� ���� �!�7J���������������<�����������������J���������������<���������<�����-J���������������<�������������� �V�����D������������<�������D������ �� J�����D������������<�������D������ �� J�����D������������<�������D������ �� J��������������<������� ����'�����������tS��������������������� ���������� �VtS��������������������� ������5�������]wtS%���������*������������*�������V���JwtS%���������*������������*�������V���JwtS%���������*������������*�������V���JwtS%���������*������������*�������V���JwtS%���������*������������*�������V���JwtS%���������*������������*�������V���JwtS%���������*������������*�������V���JwtS%���������*������������*�������V���JwtS%���������*������������*�������V���JwtS%���������*������������*�������V���JwtS%���������*������������*�������V���JwtS%���������*������������*�������V���JtS�������� �������JtS�������� �������JtS�������� ��������JtS���������������JtS���������������JtS���������������JtS���������������JtS�����������&JtS�����������&JtS���������������$���JtS���������������$���JtS���� �������������������XtS���� �������������������XtS���� �������������������XtS���� ��������� ��"���������������JtS���� ���������;tS���� ���������;tS���� ��������� ���� �;�"���%&m�S%���������"������������^�"���%&m�S%���������"������������^�"���%&m�S%���������"������������^�"���%&m�S%���������"������������^�"���%&m�S%���������"������������^�"���%&m�S%���������"����������������������������[�"���%&m�S%���������"������������������V�������[�"���%&m�S%���������"���������������������������[�"���%&m�S%���������"������������������J�"���%&m�S%���������"�������������RJ������������������&�tS%��������������������� �#��+���X%&�jtS%����$�����j%&�����������H�:J����������������m�S%����$�����j���������������H�:J ��jtS%����$�����j ��� �!���������J ��jtS%����$�����j ��� �!���H�:J%&�jtS%����$�����j%&�� ������������~%&�jtS%����$�����j%&�� ������������~%&�jtS%����$�����j%&�� ������������~l�������m�S%���� ������������Xl�����%��m�S%���� ��������#������ �Vl�����%��m�S%���� ����������� �V�������%��m�S%���� ������������$�BJl�����%��m�S%���� �����������V�'��J�������%��m�S%���� ������������ �VtS%�������������4��� �������1�0�����������������JtS%�������������4��� ���������������������%�������+��%�������#�WtS%�������������4��� ���������������������� JtS%�������������4��� ���������������������� JtS%�������������4��� ���������������������� JtS%�������������4��� ����������������&��������������!�!�������������#�WtS%�������������4��� ����������������������������������#�WtS%�������������4��� � ��0�0��������������� JtS%�������������4��� � ��0�0���������&�������E��!������A���������#�WtS%�������������4��� ������4�0�0�����������������&���JtS%�������������4��� � ��0�0���������&������� !�!�������������#�WtS%�������������4��� � ��0�0���������&������ !�������������#�WtS%�������������4��� ������4�0�0��������������� JtS%�������������4��� ������4�0�0��������������� JtS%�������������4��� ������4�0�0��������������� JtS%�������������4��� ������4�0�0��������������� JtS%�������������4��� ������4�0�0��������������� JtS%�������������4��� ������4�0�0��������������� JtS%�������������4��� �������1�0������������������JtS%�������������4��� �������1�0�����������������������������#�WtS%�������������4��� � ��0�0���������&�������E��!������A������JtS%�������������4��� ����������������&�����������!����������JtS%�������������4��� �����������������#��"�$����������������������#�WtS%�������������4��� � ��0�0����������� �����������#�WtS%�������������4��� ����������������&�������E������!������A���������#�WtS%�������������4��� � ��0�0������������ ����� � ������������#�WtS%�������������4��� ����������������&�����������!�������������#�WtS%�������������4��� � ��0�0���������&�������� !���������������#�W�������������ni�����������������DJ�������������m�S�������������������J�������������m�S�������������������J�������������m�S�������������������J�������������m�S�������������������J������������#�$m�S����������#�$���#�^�������������m�S����������������W��������������4��m�S������������4����4�J��������������4��m�S������������4����4�J���������������m�S����������������J�����m�S��������!��V��������������#�m�S����������#����#�J���������������m�S��������}������������+�^����������������m�S���������������������J����������������m�S���������������������J��������������m�S�����������������J��������������m�S�����������������J�����m�S���������#��������#�W��������������m�S�������������������# �����!�����������������m�S������������������J�����m�S����������J�������������m�S��������������� ������J�������������m�S��������������� ������J�������������m�S��������������� ������J�������������ni������������������������ W�������������ni������������������������ W�����m�S���������V���J�����m�S���������V���J�����m�S���������J�����m�S���������J�������������m�S��������}����������$���� W���������������m�S�����������������7!��[�����������������������m�S��������������������J�����������������������m�S��������������������J�����������������������m�S��������������������J�����������������������m�S��������������������J���������������m�S�����������������J���������������m�S�����������������J���������������m�S�����������������J���������������m�S�����������������J����������&��$�m�S��������&��$��!��$;����������&��$�m�S��������&��$��!��$;����������&��$�m�S��������&��$��!��$;����������&��$�m�S��������&��$��!��$;�����m�S��������}�!� �������]�������������m�S���������������J�������������m�S�������������������������J�������������m�S�������������������������J�������������m�S�������������������������J�������������m�S�������������������������J�������������m�S�������������������������J�������������#m�S�����������#����#�;�������������m�S�������������������!��J�������������m�S��������������� !��J�������������m�S��������������� !��J�������������m�S��������������� !��J�������������m�S�������������������J�������������m�S�������������������J�������������m�S�������������������J�����m�S�����������$&�J��������������4�m�S������������4������J��������������4�m�S������������4������J�����������������m�S�������������������J��������������� �m�S������������� ��������������������ni��������������V���������������$m�S�������������$1A��� V�������������m�S���������������������J�������������m�S���������������������J�������������ni��������}���������^�������������ni���������������������W�������������ni���������������������W�����������$�����m�S�������.�$����������!����J���&����������������&��7�����&'������������m�S���������(����������(W���&������m�S%�����������&����������)����&������������" �M� ���������� J���&������m�S%�����������&����������)����&�����+��������������� J���&������m�S%�����������&����������)����&��������&������"[���&������m�S%�����������&����������)����&��������&������"[���&������m�S%�����������&������������������"���4�V�!�[���&������m�S%�����������&��������������"[��$�����m��������������� V��$�����m��������������� V��$�����m��������������� V��$�%&m���������"������ V��$�%&m���������"�� ��G�����G��������4[��$�%&m���������"�� ��G�����G��������4[��$�%&m���������"�� ��G�����G��������4[��$�%&m���������"�� ������ V��$�%&m���������"�� ������ V��$�����m���������������������CJ��$�����m���������������������CJ��$�����m���������������������CJ��$�%&m���������"�� ����MJ��$�%&m����������� ����&���������� J��m�����������������1��8J��m�����������������1��8J��m�����������������1��8J��m�����������'��!� W��m�����������'��!� W��m�����������'��!� W��m�����������'��!� W��m�����������'��!� W��m�������������������'J��$�%&m����������}��7���&������J��$�%&m����������}��7���&������J��$�%&m����������}��7���&������J��$�%&m��������������7�� V��m�����������4[��m�����������4[��$�%&m����������� ��$�!�[��$�%&m����������� ��$�!�[��$�%&m�����������7��7��� J��$�����m����������������!������� W��$�����m���������U����J��$�����m���������U����J��$�����m���������U����J��$�����m���������U����J��$�����m���������U����J��$�����m���������U����J��$�����m���������U����J��m��������������;��m��������������;��$�����m����������!�7������'J��$�����m����������!�7������'J��$�%&m���������"�� ��!���������� �J��m������� ������������� ����� W��m������� ������������� ����� W��$�%&m������������� ����� V��$�%&m������������� ����� V��m�������������4���~��$�%&m����������}��7������#�����������������������#������J��m�������������4[��m�������������4[��m�������������4[��m�������������4[��m�������������4[��m�������������4[��m�������������4[��m�������������4[��m�������������4[��m�������������4[��m�������������4[��m�������������4[��m�������������4[��m�������������4[��m�������������4[��$�%&m����������� &� �� J��$�%&m���������"�� �� �J��$�%&m���������������������'J��$�����m������������� � J��$�����m������������� � J��$�����m������������� � J��$�%&m����������� ��$�J��$�%&m����������� ��$�J��$�%&m����������� ��$�J��$�%&m����������� ��$�J��$�%&m����������� ��$�J��$�%&m����������� ��$�J��$�%&m����������� ��$�J��$�����m��������������"[��$�����m��������������"[��m��������������������'J��m��������������������'J��m��������������������'J��m��������������������'J��m��������������������'J��$�%&m����������}��7���������&��J��$�%&m����������!����$�J��m������� �����% �� �[��$�%&m����������}��7�����'�0���������4[��$�%&m���������"������� ������CJ��$�%&m���������"������� ������CJ��$�%&m���������"&�����!�[��$�%&m�����������7� �- ��V��$�����m�����������!��������#�J��$�����m�����������0V��$�%&m����������}��7�������~��$������ �m��������������� �"����"�V��$������ �m��������������� �"����"�V��$������ �m��������������� �"����"�V��$�%&m����������� ��!��������(7� J��$�����m������������� !������� W��$�����m������������� !������� W��$�%&m����������� ��������� � J��$�����m��������������% ������m���������� ����� V��$�����m���������"�� ������(7���� V��$�%&m������������� �!��[��$�%&m������������� �!��[��m�����������J��m�����������J��m�����������J��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m���������"�� �1� �V��$�%&m����������+�$�NV��$�%&m����������+�$�NV��$�%&m���������������� !�[��$�����m�������������������% W��m����������������������J��$�����m����������������J��$�����m����������������J��$�����m����������������J��$�����m����������������J��$�����m����������������J��$�����m����������������J��$�����m����������������J��$�����m����������������������CJ��$�%&m����������}��7�!�������X��$�%&m����������}��7�!�������X��$�%&m����������}��7�!�������X��$�%&m����������}��7�!�������X��$�%&m����������}��7�!�������X��$�%&m�����������������!��[��$�����m���������U�������������'+ �^��m��������������������^��$�%&m��������������& � J��$�%&m��������������& � J��$�%&m��������������& � J��$�%&m��������������& � J��$�%&m��������������& � J��$�%&m��������������& � J��$�%&m�����������7� ���� J��$�%&m�����������7� ���� J��$�%&m�����������7� ���� J��$�%&m�����������7� ���� J��$�%&m�����������7� ���� J��$�%&m�����������7� ���� J��$�%&m�����������7� ���� J��$�%&m�����������7� ���� J��$�%&m�����������7� ���� J��$�%&m�����������7� ���� J��$�����m�����������������#�J��$�%&m���������"�� �� ��� V��$�%&m����������� ��!��������!���� J��$�%&m���������"�� �������������;��m������U��������;��$�%&m�����������7��7��J��m����������V�X��$�����m�������������J��$�����m�������������J��$�����m�������������J��$�����m�������������J��$�����m�������������J��$�����m�������������J��m�������}�����4J��m�������}�����4J��$�%&m���������"�� ��!������� V��m������U�����x��$�%&m����������}��7���������7����J��$�%&m����������}��7�����$�����X��$�%&m���������"�� �����J��$�%&m���������"�� �����J��$�%&m���������"�� �����J��$�%&m���������"�� �����J��$�%&m���������"�� �����J��$�%&m���������"�� �����J��$�%&m���������"�� �����J��$�%&m���������"�� �����J��$�%&m���������"�� �����J��$�%&m���������"�� �����J��$�%&m���������"�� �����J��$�%&m���������"�� �����J��$�%&m���������"�� �����J��$�%&m���������"�� �����J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��$�����m��������������(7J��m������� ������ ������ �!� ;��$�����m������������J��$�����m������������J��$�����m������������J��$�����m������������J��$�����m������������J��$�����m������������J��$�����m������������J��$�����m������������J��$�����m������������J��$�����m������������J��m������� ������������� �J��$�%&m������������������ [��$������m���������������"����"�V��$�%&m����������}��7��������$�%&m�����������7�*J��m�����������V��m�����������V��m�����������V��m�����������V��m�����������V��$�%&m����������!���&�$"�X��$�%&m����������!���&�$"�X��$�%&m����������!���&�$"�X��$�%&m����������!���&�$"�X��$�%&m����������!���&�$"�X��$�%&m����������!���&�$"�X��$�%&m����������!���&�$"�X��$�%&m����������!���&�$"�X��$�%&m����������!���&�$"�X��$�%&m����������!���&�$"�X��$�%&m����������!���&�$"�X��$�%&m����������!���&�$"�X��$�%&m����������!���&�$"�X��$�%&m����������!���&�$"�X��$�%&m����������� ������������� J��$�%&m����������}��7���&������������X��$�%&m����������}��7���&������������X��$�%&m����������}��7���&������������X��$�%&m����������}��7���&������������X��$�%&m����������}��7���&������������X��$�%&m����������}��7���&������������X��$�%&m����������}��7���&������������X��$�%&m����������}��7���&������������X��$�%&m����������}��7���&������������X��$�%&m����������}��7���&������������X��$�%&m�����������7���� ���������^��$�%&m�����������7���� ���������^��$�%&m�����������7���� ���������^��$�%&m�����������7���� ���������^��$�%&m�����������7���� ���������^��$�%&m���������������������'���� W��$�%&m���������������������'���� W��$�%&m�����������7�+�$��� J��m���������������'��J��m���������������'��J��m���������������'��J��m�����������'������m�����������'������m�����������'������m������� �����% �� �[��m�������}�����������V��$������m���������������"���� ������� J��m������� ��������� �x��$�����m�������������������CJ��$�%&m����������}�� � ����~��$�%&m����������}�� � ����~��m������� �������������� ����� W��$�����m������������#�!�[��$�����m������������#�!�[��$�����m���������"}"��������J��$�����m������������$����� W��$�����m����������!���-��J��$�����m����������!���-��J��$�����m����������!���-��J��$�����m����������!���-��J��$�%&m�����������������&��J��$�%&m����������� �� � �� J��m������� ������������J��m��������������������� [��m��������������������� [��$�����m�������������������J��$�����m�������������������J��$�����m�������������������J��$�����m�������������������J��$�����m�������������������JwtS%������������������������������������������W����������m�S�����������������������������V X����������m�S�����������������������������V X����������m�S�����������������������������'$!� W������'�������5��2"tS%�.������������5�2"�����"[������'�������5��2"tS%�.������������5�2"�����"[������'������m�S%�.�����������������X������'����������2"tS%�.���������������&�����Z�K����J������'����������2"tS%�.���������������&�����Z�K����J������'�������&���2"tS%�.�������&��"����!���F��� W������'�������&���2"tS%�.�������&��")�������V����$�$V������'������m�S%�.������������&��! �����J������'������m�S%�.������������&��! �����J������'������m�S%�.������������&��! �����J������'������m�S%�.������������&��! �����J������'������m�S%�.������������}������ v;������'������m�S%�.������������}������ v;������'������m�S%�.������������������J������'����������2"tS%�.��������������"�Z�K� �J������'������m�S%�.����������������V������'������m�S%�.����������������V������'������������ni%�.������������������������������V������'������������ni%�.������������������������������V������'������������ni%�.������������������������������V������'������m�S%�.�������������� ���� J������'������m�S%�.�������������� ���� J������'������m�S%�.���������������������� W������'������m�S%�.������������������J������'������m�S%�.������������������J������'�������&���2"tS%�.�������&��")����!��������� $����J������'����������*m�S%�.���������������*�������&�M��������J������'����������*m�S%�.���������������*����*���;������'����������*m�S%�.���������������*����*���;������'������m�S%�.������������������X������'����������� ���$m�S%�.�����������������������X������'����������� ���$m�S%�.�����������������������X������'����������� ���$m�S%�.�����������������������X������'����������� ���$m�S%�.�����������������������X������'�������&���2"tS%�.�������&��"����!���"[������'�������&���2"tS%�.�������&��"����!���"[������'�������&���2"tS%�.�������&��"����!���"[������'�������&���2"tS%�.�������&��"����!���"[����#�$�%&m�S������#�$������������������ � ��������� ����J����#�$�%&m�S������#�$������������������ � ��������� ����J����#�$������ni������#�$������������4���������4����� J����#�$�%&m�S������#�$������������!�7�����������������~����#�$�%&m�S������#�$�����%&�������������������������� ���������������������������%&��� W����#�$�%&m�S������#�$�����%&�������������������������� ���������������������������%&��� W����#�$�%&m�S������#�$�����%&�������������������������� ���������������������������%&��� W����#�$�%&m�S������#�$�����������������!�7���~����#�$�%&m�S������#�$�����������������!�7���~����#�$������ni������#�$������������#�*��� ��������#�*RJ����#�$�%&m�S������#�$�������������������&��������MJ����#�$������ni������#�$�������������� �������������M����MJ�������%&m�S%������������������������� �����X�������%&m�S%�������������� u;�������%&m�S%�������������� u;�������%&m�S%�������������� u;�������%&m�S%�������������&�������������� J�������%&m�S%�������������&�������������� J�������%&m�S%�������������&�������������� J�������%&m�S%�������������&�������������� J�������%&m�S%�������������&�������������� J�������%&m�S%�������������&�������������� J�������%&m�S%�������������&�������������� J�������%&m�S%�������������&�������������� J�������%&m�S%���������������'����������^�������%&m�S%�������������&�������� J�������%&m�S%�������������&�������� J�������%&m�S%�������������������������^�������%&m�S%�������������������������^�������%&m�S%�������������������������^�������%&m�S%����������U����� � �V�������%&m�S%����������U����� � �V�������%&m�S%����������U�����V$��!��������V�X�������%&m�S%�����������������~�������%&m�S%�����������������~�������%&m�S%���������������������;�������%&m�S%���������������������;���������ni%�������������������������������4�� ��K�BJ�������%&m�S%������������������������';�������%&m�S%������������������������';�������%&m�S%������������������������';�������%&m�S%������������������������';�������%&m�S%������������������������';�������%&m�S%������������������M�� J��������������m�S%�������������������Z���K�������� �����X�������%&m�S%����������������������� J������%&m�S���O� �����������V!� W������%&m�S���O� �����������V!� W������%&m�S���O� �����������V!� W������%&m�S���O�������������������RJ������%&m�S���O� �����5� �J������%&m�S���O����"$�&������&RJ������%&m�S���O����"$�&������&RJ������%&m�S���O� ������ �J������%&m�S���O� ������ �J������%&m�S���O����� �����V ��';������%&m�S���O��O%&���������J������%&m�S���O� ���V X������%&m�S���O��$�����������G���+ �^������%&m�S���O��$�����������G���+ �^������%&m�S���O��O����'��������J������%&m�S���O��O����'��������J������%&m�S���O��O����'��������J������%&m�S���O��O����'��������J������%&m�S���O� �������*������ J������%&m�S���O��G�G��';������%&m�S���O��G�G��';������%&m�S���O��G�G��';������%&m�S���O��G���������J������%&m�S���O��G���������J������%&m�S���O��G���������J������%&m�S���O��O%&������&�����J������%&m�S���O��G����� ����V J������%&m�S���O��O%&���������J������%&m�S���O��������J������%&m�S���O� ������������#�����������*���;������%&m�S���O� ������������#�����������*���;������%&m�S���O� ������������#���� �������������*���;������%&m�S���O� ������������#���� �������������*���;������%&m�S���O� ������������#���� �������������*���;������%&m�S���O� ������������#���� �������������*���;������%&m�S���O� ������������#���� �������������*���;������%&m�S���O� ������������#���� �������������*���;������%&m�S���O� ������������#���� �������������*���;������%&m�S���O� ������������#���� �������������*���;������%&m�S���O� ������������#���� �������������*���;������%&m�S���O� ����1����� �V������%&m�S���O��G�����'��GJ������%&m�S���O����"$����������R����J������%&m�S���O��G�G������J������%&m�S���O��G�G������J������%&m�S���O�������������������������RJ������%&m�S���O�������������������������RJ������%&m�S���O��G����G����� �V������%&m�S���O� �������������� �J������%&m�S���O�&)����&)����';������%&m�S���O��G������#������G���� ��+���X������%&m�S���O�%J������%&m�S���O��'�&��!�MJ������%&m�S���Os1��� �|��DJ������%&m�S���O�����������J������%&m�S���Os��������� [������%&m�S���O���������� J������%&m�S���O���������� J������%&m�S���O���������� J������%&m�S���O���������� J������%&m�S���O���������� J������%&m�S���O���������� J������%&m�S���O� �����������V�W������%&m�S���O� �����������V�W������%&m�S���O� �����������V�W������%&m�S���O�� � �#�������������J������%&m�S���O�� � �#�������������J������%&m�S���O� �����&���J������%&m�S���O�� � ���#������#�����|��DJ���������"�������m�S�.���O���"������������"� �V���������"�������m�S�.���O���"������������"� �V������%&m�S���O����"$����R��';������%&m�S���O��O%&�������J������%&m�S���O��O%&��������J������%&m�S���O��������������J������%&m�S���O��������������J������%&m�S���O��������������J������%&m�S���O��������������J������%&m�S���O��O������';������%&m�S���O��O������';������%&m�S���O������������G������������G���J������%&m�S���O� ���*���J������%&m�S���O� ���*���J������%&m�S���O� ���*���J������%&m�S���O� ���*���J������%&m�S���O� ���*���J������%&m�S���O� ���*���J������%&m�S���O� ���*���J������%&m�S���O�����������������RJ������%&m�S���O� ���*� �J������%&m�S���O� ���*� �J������%&m�S���O� ���*� �J������%&m�S���O� ���*� �J������%&m�S���O� ���*� �J������%&m�S���O� ���*� �J������%&m�S���O� �1� �J������%&m�S���O��G�������������K�����������GJ������%&m�S���O���������R��';������%&m�S���O���������R��';������%&m�S���O���������R��';������%&m�S���O��������&���J������%&m�S���O� ������$� �V������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O�� � ���#��������J������%&m�S���O� ������������#�����'���V����#J������%&m�S���O� ������������#�����'���V����#J������%&m�S���O�� � �����������������J������%&m�S���O������������J������%&m�S���O���������������K������RJ������%&m�S���O��������&���������������'������J������%&m�S���O�� � ���#������#������ �V������%&m�S���O)���� ������������� J������%&m�S���O� ������� �V������%&m�S���O��G����G-��J������%&m�S���O� �����������W���������m�S���O�� � ������������������� W���������m�S���O�� � ������������������� W������%&m�S���O��'�&��KJ������%&m�S���O���������'����$"�J������%&m�S���O� ������'� �J������%&m�S���O� ������'� �J������%&m�S���O� ������'� �J������%&m�S���O� ������'� �J������%&m�S���O� ������'� �J������%&m�S���O� ������'� �J������%&m�S���O���������������������#�����!����^������%&m�S���O���������������������#�����!����^������%&m�S���O� ������������#������#J������%&m�S���O� ������������#������#J������%&m�S���O� ������������#������#J������%&m�S���O�������J������%&m�S���O�������J������%&m�S���O�������J������%&m�S���O�������J������%&m�S���O����"$�&� �R&����J������%&m�S���O����"$�&� �R&����J������%&m�S���O)���� ���� ���;������%&m�S���O)���� ���� ���;������%&m�S���O)���� ���� ���;������%&m�S���O)���� ���� ���;������%&m�S���O)���� ���� ���;������%&m�S���O�� � ����������+��� �^������%&m�S���O� �����������V��������%&m�S���O� �����������V��������%&m�S���O� �����������V��������%&m�S���O� �����������V�����������"�������m�S�.���O���"�������������'�����������J���������"�������m�S�.���O���"�������������'�����������J���������"�������m�S�.���O���"�������������'�����������J���������"�������m�S�.���O���"�������������'�����������J������%&m�S���O��G������]������%&m�S���O��G������]������%&m�S���O���4������<�&��&����4���J������%&m�S���O���4������<�&��&����4���J������%&m�S���O������������Y�����G����W������%&m�S���O� ��(7� �J������%&m�S���O� ��(7� �J������%&m�S���O��G�G�� �������J������%&m�S���O��G�G�� �������J������%&m�S���O� �������J������%&m�S���O� �������J������%&m�S���O)���� �����'����� �����^������%&m�S���O)���� �����'����� �����^������%&m�S���O� ������������#���� ������������������*���;������%&m�S���O� ������������#���� ������������������*���;�����������&���������'���������0�V�'J�����������&���������'���������0�V�'J�����������&���������'���������0�V�'J�����������&���������'���������0�V�'J�����������&���������'���������0�V�'J�����������&���������'���������0�V�'J�����������&���������'���������0�V�'J�����������&���������'���������0�V�'J�����������&���������'���������0�V�'J�����������&���������'����������J�����������&���������'����������J�����������&���������'����������J�����������&���������'����������J�����������&���������'����������J�����������&���������'����������J�����������&���������'����������J�����������&���������'����������J������������#����V�����������&���������'������������V J�����������&���������'������������V J�����������&���������'������������V J�����������&���������'������������V J�����������&���������'����������X�����������&���������'����������X�����������&���������'����������X�����������&���������'����������X�����������&���������'����������X�����������&���������'����������X�����������&���������'����������X�����������&���������'����������X�����������&���������'����������X�����������&���������'�����������!� W�����������&���������'���������������V J�����������&���������'���������������V J�����������&���������'���������������V J�����������&���������'���������������V J�����������&���������'���������������V J�����������&���������'���������������V J�����������&���������'���������������V J�����������&���������'���������������V J�����������&���������'���������������V J�����������&���������'���������������V J�����������&���������'���������������V J�����������������J�����������������J�����������&���������'�����������M�V J�����������&���������'�����������M�V J�����������&���������'������������������������&���������'������������������������&���������'������������������������&���������'������������������������&���������'������������������������&���������'������������������������&���������'������������������������&���������'���������������������������&���������'���������������������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R��������������&���������'������������R���������������#�U������"��RJ������������#�U������"��RJ������������#�U������"��RJglki��h��gT�����Jglki��h��gT� ����u;glki��h��gT� ����u;glki��h��gT� ��!����^glki��h��gT� ��!����^� ���&�'m�S��h�U&�'�!�'Jsni��h��&���*|Vglki��h��gT����M�����u;glki��h��gT����M�����u;glki��h��gT����M�����u;glki��h��gT����M�����u;glki��h��gT����M�����u;glki��h��gT����M�����u;glki��h��gT�������7Jglki��h��g�������#����Wglki��h��gT��������u;glki��h��gT��� �� �Jglki��h��gT��� �� �Jglki��h��gT��� �� �Jglki��h��gT��� �� �Jglki��h��gT�����u;glki��h��gT�����u;glki��h��j� �o��������+���Xglki��h��j� �o��������+���Xsni��h��&_ 1x� �ni��h�U����'���'Jglki��h��gT��Xglki��h��gT��Xglki��h��gT���Jglki��h��gT��4�MJglki��h��gT��4�MJglki��h��gT�V���Jglki��h��gT�V���Jh�m�S��h�������� Wglki��h��gT�����'Jglki��h��gT�������u;�������m�S��h�U!�7����V�������m�S��h�U!�7����V�������m�S��h�U!�7����V�������m�S��h�U!�7����V�������m�S��h�U!�7����V�������m�S��h�U!�7����V�������m�S��h�U!�7����V�������m�S��h�U!�7����Vg�������4m�S��h��g������4�T��� �������Jglki��h��gT�����u;glki��h��gT���u;glki��h��gT���u;glki��h��gT���u;glki��h��gT���u;glki��h��gT���u;glki��h��gT���u;� �ni��h�U����'�+����� W� �ni��h�U����'�+����� W� �ni��h�U����'�+����� Wsni��h��&_ �|�*Jglki��h����� �������4[glki��h����� �������4[sni��h��&_ �!�KJglki��h��j���|������Jglki��h��j���|������Jglki��h��j���|������J�#��m�S��h��}��0% ���4 ���������g5�2"tS��h��g5�2"�����!�����&'Jg5�2"tS��h��g5�2"�����!�����&'Jglki��h��gT� ���;glki��h��gT� ���;glki��h��gT� ���;glki��h��gT� ���;glki��h��gT� ���;glki��h��gT� ���;glki��h��gT� ���;glki��h��gT� ���;glki��h��gT� ���;glki��h��gT� ���;glki��h��gT� ���;glki��h��gT� ���;glki��h��gT��� ����^glki��h��gT��� ����^glki��h��gT��� ����^glki��h��gT���� ���u;glki��h��gT���� ���u;glki��h��gT���������Jglki��h��gT���������Jglki��h��gT���7�:u;glki��h��gT����MJsni��h��&_ ��������!� ;sni��h��&_ ��������!� ;� �ni��h�U� �Jglki��h��gT�a�glki��h��gT�a�glki��h��gT�a�glki��h��gT�a�glki��h��gT�a�glki��h��gT�a�glki��h��gT�a�glki��h��gT�a�glki��h��gT�a�glki��h��gT�a�glki��h��gT�a�glki��h��gT�a�glki��h��gT�����~glki��h��gT�����~glki��h��gT������u;sni��h��&_ ������#��$�Jsni��h��&_ ������#��$�Jsni��h��&_ ������#��$�Jglki��h��gT����������u;glki��h��gT����������u;glki��h��gT����������u;glki��h��gT����������u;h�m�S��h��}����"�#�����';sni��h��&_ ���� �����Jh�m�S��h��j}����H�:���^glki��h��gT������Wsni��h��&_ �������Jsni��h��&_ �������Jglki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT�����u;glki��h��gT���������~glki��h��gT���������~glki��h��gT�������u;glki��h��gT���&!�[glki��h��gT��A[� ���&�'m�S��h�U&�'���������DJglki��h��gT�����Mu;sni��h���#����� �#��[sni��h���#����� �#��[glki��h��gT���Jsni��h��&���Vglki��h��gT� �����#��$����Jglki��h��gT����������Jh�m�S��h����'�Jh�m�S��h����'�Jh�m�S��h����'�Jh�m�S��h����'�Jglki��h��gT�������?Xglki��h��gT�������?Xglki��h��gT����� ������Jglki��h��gT� ������J� �ni��h�U�����^� �ni��h�U�����^� �ni��h�U�����^� �ni��h�U�����^� �ni��h�U�����^� �ni��h�U�����^� �ni��h�U�����^glki��h��gTH�:Jglki��h��gTH�:Jglki��h��gTH�:Jglki��h��gTH�:Jglki��h��gT�������% Wglki��h��gT�������% Wglki��h��g|���~glki��h��g|���~glki��h��g|���~glki��h��gT������u;glki��h��g�����-��4Jglki��h��gT�DJglki��h��gT�DJglki��h��gT��� ����g5�2"tS��h��g5�2"�����������^glki��h��gT��� ���^g5�2"tS��h��g5�2"��������Jg5�2"tS��h��g5�2"��������Jg5�2"tS��h��g5�2"��������Jglki��h��gT���������u;h�m�S��h����������������������^glki��h��gT� ����~glki��h��gT� ����~sni��h��&_ ��������!�KJsni��h��&_ ��������!�KJ�#��m�S��h��}��0% �������������������4�Jglki��h��gT������������[glki��h��gT��u;glki��h��gT��u;glki��h��gT��u;sni��h��&_ �!�K�)���Jsni��h��&_ �!�K�)���Jsni��h��&_ �!�K�)���Jglki��h��g�B���� ���';glki��h��g�B���� ���';sni��h���#��+������Jh�m�S��h����������'����������Xglki��h��gT�����u;glki��h��j)�(��H�:��(Wglki��h��j)�(��H�:��(Wglki��h��j)�(��H�:��(Wglki��h��g�����#���V�J�#��m�S��h��}��0% ���'�R���glki��h��gT��D������� ��Jglki��h��gT��D������� ��Jglki��h��gT��D������� ��J�#��m�S��h��}��0% ������4�J�#��m�S��h��}��0% ������4�J�#��m�S��h��}��0% ������4�J�#��m�S��h��}��0% ������4�J�#��m�S��h��}��0% ������4�J�#��m�S��h��}��0% ������4�Jsni��h��&�������$Vglki��h��gT- ��Vsni��h��&��|K��';sni��h��&��|K��';sni��h��&��|K��';tS%��������� ��"$���������� �������4�R����VtS%��������� ��"$���������� ���"�#�����$������������������JtS%��������� ��"$���������� ���"�#�������������4�RJtS%��������� ��"$���������� ���"�#�������������4�RJtS%��������� ��"$���������� ���"�#�������������4�RJtS%��������� ��"$���������� ���"�#�������������4�RJtS%��������� ��"$���������� ���"�#�������������4�RJtS%��������� ��"$���������� ���"�#�������������4�RJwtS%�������#���������*H����JwtS%�������#���������*H����JwtS%�������#���������*H�"�JwtS%�.yzZUC���P� �VwtS%�.yzZUC���P� �VwtS%�.yzZUC���P+ �?XwtS%�.yzZUC���P+ �?XwtS%�.yzZ1QP� [wtS%�.yzZ1QP� [wtS%�.yzZ1QP?�-JwtS%�.yzZ�����1QPu;wtS%�.yzZ1QP^wtS%�.yzZ1QP^wtS%�.yzZ1QP^wtS%�.yzZ1QP^wtS%�.yzZ1QP^p%&m�S&�r�q$���������^p%&m�S&�r������� Vp%&m�S&�r�q$Y/{�p%&m�S&�r�q$Y/{�p%&m�S&�r�q$Y/{�p%&m�S&�r�q$Y/{�p%&m�S&�r�q$Y/{�p%&m�S&�r�q$Y/{�p%&m�S&�r�q$Y/{�p%&m�S&�r�q$Y/{�p%&m�S&�r�q$Y/{�p%&m�S&�r�q$Y/{�p%&m�S&�r�q$Y/{�p%&m�S&�r�q$Y/{�p%&m�S&�r�q$�������xp%&m�S&�r�q$�?����������^p%&m�S&�r�q$���������� �Jp%&m�S&�r�q$�����Vp%&m�S&�r�q$���Jp%&m�S&�r�q$���Jp%&m�S&�r�q$���Jp%&m�S&�r�q$���Jp%&m�S&�'U)o�����;p%&m�S&�r�q$���������"Jp%&m�S&�r�q$���Vp%&m�S&�r�q$���Vp%&m�S&�r�q$���Vp%&m�S&�r�q$���Vp%&m�S&�r�q$9"������DJp%&m�S&�r�q$�{�p%&m�S&�r�q$�{�p%&m�S&�r�q$�{�p%&m�S&�r�q$�{�p%&m�S&�r�q$������*�*������^p%&m�S&�r�q$����� �VAb`\6E8U���� �����4���';Ab`\6E8U���� �����4���';Ab`\6E8U���� �����4���';Ab`\6E8U���� ���u;Ab`\6E89F���� WAb`\6E89FJAb`\6E89FJAb`\6E89FJAb`\6E89FJAb`\6E89FJAb`\6E89FJAb`\6E89FJAb`\6E89FJAb`\6E89FJAb`\6E89FJA�����M�D���`\6E8�#�M�D9F���M�DJAb`\6E8U����� ��|��*J3�����m�S%���*��3��������������������7��MJ3�����m�S%���*��3���������������������� �J3�����*m�S%���*��3�����*���*� �[3�����m�S%���*��3�������������&� �!� ����� J3�����m�S%���*��3�������#��7�����#�����+��������J3�����m�S%���*��3�������#��7�����#�����+��������J3�����m�S%���*��3�������#��7�����#�U���� �V3�����m�S%���*��3�������#��7�����#�U���� �V3�����m�S%���*��3�������������������<���4���MJ3�����m�S%���*��3�������������������<���4���MJjfed��������������� Wjfed��������������� Wjfed��('�>��jfed��('�>��jfed��('�>��jfed��('�>��jfed��('�>��jfed��('�>��jfed��('�>��jfed��('�>��fed��������% ���^fed�U)o�����^fed�B�����BJfed�B�����BJjfed��O���7Vjfed��O���7Vjfed��('����<��jfed��('����<��fed������&���������Jfed��������$Vfed��('�!��������^fed�U)o����'����&Jjfed��('��Vjfed��('��Vjfed��('��Vjfed��('��Vfed�������������^fed��('������$�����4Jjfed��('����<� �xjfed��('����<� �xjfed��('����<� �xjfed��('����<� �xjfed��O}1���^jfed��('�����Vjfed�������V��������� Wfed��('����<� �-Jfed��@�>*Jfed��('����<�Gxfed��('����<�Gxjfed������0�����Xjfed������0�����Xjfed������0�����Xjfed������0�����Xjfed��('����<�I�Jjfed��('����<�I�Jfed��('����"�� �Jfed��('����"�� �Jfed��('����"�� �Jjfed��('�����'�����I�Jjfed��('�����'�����I�Jjfed��&�'���!����^jfed��('�(7��Jfed��('��&���$Wfed��('��I�Vjfed��('����<� ��Ic�jfed��('����<� ��Ic�jfed��('�!��������xjfed�BB���� Wjfed�BB���� Wjfed����������^jfed����������^jfed��('�-Vfed��&�'������&Jfed��=��� ��Jfed��=��� ��Jjfed��@������ ��0��;jfed��@������ ��0��;jfed��@������ ��0��;fed�U)o����� � [fed�����������Jjfed�U)o��������Vjfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;jfed�U)ov;fed�������4��� Wfed��@�����������>���7Jfed��('��������:?Xfed��('��������:?Xfed��('����<��fed��('����<��fed����1Vfed����1Vfed����1Vfed����1Vfed����1Vfed����1Vjfed��=LN,Jjfed��=LN,Jjfed��=LN,Jjfed��=LN,Jjfed��=LN,Jjfed��=LN,Jjfed��=LN,Jjfed��=LN,Jjfed��=LN,Jjfed��=LN,Jjfed��=LN,Jjfed��=LN,Jjfed��('����'>-Jjfed��('���&��>�Ic�fed��O�������Jfed��('�+ �MJfed��('�+ �MJfed��('�+ �MJfed��@�>*������]fed��@�>*������]fed����������<���;fed����������<���;fed��O����^jfed�BB���� ���Jjfed�BB���� ���Jjfed������0����Jjfed��(' �Vjfed��(' �Vjfed��(' �Vjfed��(' �Vjfed��(' �Vjfed��(' �Vjfed�����!� �������]jfed�����!� �������]jfed�����!� �������]jfed�����!� �������]jfed������������Xjfed������������Xjfed������������X~�~�X��uu����X�o�6~�_q��&����M��]�iS$�h��)�*�I%ˆ��#%Y�4�0�@a�����w?���ֲ�W��7�ݭ�rF�5���PhU���'�Z턺Ƭ�J԰�����%��Г�[�Ơra��ƾъV�kt�huk �ْNNf�g#P�ޣ�t����y)�*�� ӝ�Z��������xs����[� �����`�*�����%�wP���td�X�+�Atz_֌g������4 �}��� ������NU:�P��i(���<`',�0�͒�3��`w�Է�T�Z7hrӪ���Xf���1}ۘޞ_��5́�!<_k���_�ڦ1h�'a�T�6[���a��Ų�D�&� pX���0��.���`�`M7�9�\�δ��fJڪ�4�饇����D�6d�+�vؚ�u{v`�z���p�*%�5f��t$]ܠ1���j��F�3:�x��Z\�٫�2ʔ��W��ߪ��@� ,�^�����|H�? �����H6� B0��#�J��!!K "!�f��,^�>au��t�� �Y�Ě�]� �ꃏ��VWN7����w$LAe% J ��d�ضίؖ$|�4��91Sha�l�Nn�6yH�8Y����L����EBvr���i���J�#�N��3x�5m����U���ؼ���1�ҝ�����P�v�'�DJ��A �y���"M�U�f�r N�iu[R"B��������2��yR��?)O��<��O0�o��0� �f�nv�>�� 9�E��}.��83�+Q?�S�u����K��}����=�j��ط�Z~���q�8J��2"זGp��GS@��$��뚾K�(���K��)�h��9���c^�}��ע�x �v���)ɍ�nw�Ѩ�4�l_њ����4~F? +�VZ�&U�S��̩�����o�<��_n�7�dؤ�Zn��Yw*��tt �BF3h���8�4~ǰF��+ӄSn���(D�an&��gDŽs�&���W� ����u?���{�:'p<�$;���?�\j��vh8r֡(��zՠl.�;�PJ�ɑ@�XS|��*� `ߒ �腹Ebc�@VW~\�@r���k��rQ9 A8�-�r�P/j�w��(�?b�GsxK1��N�rJ�64�e�P�����Hg�?��Qt�ө�N��� �~O�,�>���p�A�gIK�@�j�[�z��&��@��gɜ�;�ewj,�N��b�n=ɔ_y�P� ���~A]�'�#�7�X��O,ǭ�M�U����5�o������G�M�ں���H�#��;�{�1e~�q��CI:��� V��FZ�]���76����=������'�I�,�'� u������t p�p4�' ���d$�(�)�*�+�,�- /.0�0�7a9(:�<�?�@B C�CTFHG�H�J�K�LQM�M�N�O�PQQ�Q�R�SkT�TX�X�Z{`qb�c�e$g�h�i�j�n�o�pFq2r t|v�z+|����ڄ��K�I����#�`� ����������W�̣���������­x�[�4�������&����� �ܸ˻e����j����T�{�����)�a�p�x�J�������� ���������������r�,���8�A� �2� �y����; ��$F< g �  � )��|��w�!#'%v&8'-�1W264Y5�527r8�93:_B�FQG�HTI�I�J�K�L1R�W�X�Y�\`�aXb�b�c/d0j�j�k�l�n�p=tluuwnxI{K�هy�ړՕ���@�֛k�������ħY�,���n��>����зH�q��\� �(�����U��^���5���v������i�0����������������o�����6�]������ �^���/�����>�����"Y�m� ��+�'��� *!�!�"J#z$�&�'�(��� 2�304569�C�IwLXMNP�PHS\X;Y�Y_Z�[(^_�_``�a�b�d�f�g�h�i�o�q�y_z�z�{�|�}z~����3�ׄ'�k�i��������W����=�T������ϖ#��)���,�����������ޥ����s�8�����|�i�̯����M����p�3����K�v�|�i�e�������Y�G���������%�K�|��������I����x�����������8�>T 4 $ � � � l:���J�"e"F$&'�)�*�-t./ 0�1_223�4�5�8�:p;�?�B�D-I MHN�R�S�W�X�Y[�[p\6`�eofi~j�l�m�n$p�p�q9t)u�v�w{y8|�|�}8�O���'���4������v�K���d�� ��p����%���)����G��������(���������.����F�}�-�F�v������}����m���~�;�0���z����z����g�P���3�3�.�k�2�G�u����������������������������������������������������������������������������������������������������������������������������������������������������private void init(final int var) { // creates and/or resizes the initializations array if necessary if (initializations == null) { initializations = new int[2]; } int n = initializations.length; if (initializationCount >= n) { int[] t = new int[Math.max(initializationCount + 1, 2 * n)]; System.arraycopy(initializations, 0, t, 0, n); initializations = t; } // stores the type to be initialized initializations[initializationCount++] = var; }private void pop(final String desc) { char c = desc.charAt(0); if (c == '(') { pop((Type.getArgumentsAndReturnSizes(desc) >> 2) - 1); } else if (c == 'J' || c == 'D') { pop(2); } else { pop(1); } }private void pop(final int elements) { if (outputStackTop >= elements) { outputStackTop -= elements; } else { // if the number of elements to be popped is greater than the number // of elements in the output stack, clear it, and pops the remaining // elements from the input stack. owner.inputStackTop -= elements - outputStackTop; outputStackTop = 0; } }private static int type(final ClassWriter cw, final String desc) { String t; int index = desc.charAt(0) == '(' ? desc.indexOf(')') + 1 : 0; switch (desc.charAt(index)) { case 'V': return 0; case 'Z': case 'C': case 'B': case 'S': case 'I': return INTEGER; case 'F': return FLOAT; case 'J': return LONG; case 'D': return DOUBLE; case 'L': // stores the internal name, not the descriptor! t = desc.substring(index + 1, desc.length() - 1); return OBJECT | cw.addType(t); // case '[': default: // extracts the dimensions and the element type int data; int dims = index + 1; while (desc.charAt(dims) == '[') { ++dims; } switch (desc.charAt(dims)) { case 'Z': data = BOOLEAN; break; case 'C': data = CHAR; break; case 'B': data = BYTE; break; case 'S': data = SHORT; break; case 'I': data = INTEGER; break; case 'F': data = FLOAT; break; case 'J': data = LONG; break; case 'D': data = DOUBLE; break; // case 'L': default: // stores the internal name, not the descriptor t = desc.substring(dims + 1, desc.length() - 1); data = OBJECT | cw.addType(t); } return (dims - index) << 28 | data; } }private void push(final ClassWriter cw, final String desc) { int type = type(cw, desc); if (type != 0) { push(type); if (type == LONG || type == DOUBLE) { push(TOP); } } }private void set(final int local, final int type) { // creates and/or resizes the output local variables array if necessary if (outputLocals == null) { outputLocals = new int[10]; } int n = outputLocals.length; if (local >= n) { int[] t = new int[Math.max(local + 1, 2 * n)]; System.arraycopy(outputLocals, 0, t, 0, n); outputLocals = t; } // sets the local variable outputLocals[local] = type; }private int get(final int local) { if (outputLocals == null || local >= outputLocals.length) { // this local has never been assigned in this basic block, // so it is still equal to its value in the input frame return LOCAL | local; } else { int type = outputLocals[local]; if (type == 0) { // this local has never been assigned in this basic block, // so it is still equal to its value in the input frame type = outputLocals[local] = LOCAL | local; } return type; } }final void set(ClassWriter cw, final int nLocal, final Object[] local, final int nStack, final Object[] stack) { int i = convert(cw, nLocal, local, inputLocals); while (i < local.length) { inputLocals[i++] = TOP; } int nStackTop = 0; for (int j = 0; j < nStack; ++j) { if (stack[j] == Opcodes.LONG || stack[j] == Opcodes.DOUBLE) { ++nStackTop; } } inputStack = new int[nStack + nStackTop]; convert(cw, nStack, stack, inputStack); outputStackTop = 0; initializationCount = 0; }private int readFrameType(final Object[] frame, final int index, int v, final char[] buf, final Label[] labels) { int type = b[v++] & 0xFF; switch (type) { case 0: frame[index] = Opcodes.TOP; break; case 1: frame[index] = Opcodes.INTEGER; break; case 2: frame[index] = Opcodes.FLOAT; break; case 3: frame[index] = Opcodes.DOUBLE; break; case 4: frame[index] = Opcodes.LONG; break; case 5: frame[index] = Opcodes.NULL; break; case 6: frame[index] = Opcodes.UNINITIALIZED_THIS; break; case 7: // Object frame[index] = readClass(v, buf); v += 2; break; default: // Uninitialized frame[index] = readLabel(readUnsignedShort(v), labels); v += 2; } return v; }public void visitLineNumber(int line, Label start) { if (mv != null) { mv.visitLineNumber(line, start); } }public AnnotationVisitor visitLocalVariableAnnotation(int typeRef, TypePath typePath, Label[] start, Label[] end, int[] index, String desc, boolean visible) { if (api < Opcodes.ASM5) { throw new RuntimeException(); } if (mv != null) { return mv.visitLocalVariableAnnotation(typeRef, typePath, start, end, index, desc, visible); } return null; }public void visitMultiANewArrayInsn(String desc, int dims) { if (mv != null) { mv.visitMultiANewArrayInsn(desc, dims); } }public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) { if (mv != null) { mv.visitLookupSwitchInsn(dflt, keys, labels); } }public void visitTableSwitchInsn(int min, int max, Label dflt, Label... labels) { if (mv != null) { mv.visitTableSwitchInsn(min, max, dflt, labels); } }@Deprecated public void visitMethodInsn(int opcode, String owner, String name, String desc) { if (api >= Opcodes.ASM5) { boolean itf = opcode == Opcodes.INVOKEINTERFACE; visitMethodInsn(opcode, owner, name, desc, itf); return; } if (mv != null) { mv.visitMethodInsn(opcode, owner, name, desc); } }public void visitFieldInsn(int opcode, String owner, String name, String desc) { if (mv != null) { mv.visitFieldInsn(opcode, owner, name, desc); } }public void visitTypeInsn(int opcode, String type) { if (mv != null) { mv.visitTypeInsn(opcode, type); } }public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) { if (mv != null) { return mv.visitParameterAnnotation(parameter, desc, visible); } return null; }public AnnotationVisitor visitAnnotation(String desc, boolean visible) { if (mv != null) { return mv.visitAnnotation(desc, visible); } return null; }public void visitParameter(String name, int access) { if (api < Opcodes.ASM5) { throw new RuntimeException(); } if (mv != null) { mv.visitParameter(name, access); } }private static BufferedImage createJPEG4(Raster raster) { int w = raster.getWidth(); int h = raster.getHeight(); byte[] rgb = new byte[w * h * 3]; float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null); float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null); float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null); float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null); for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) { float k = 220 - K[i], y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i]; double val = y + 1.402 * (cr - 128) - k; val = (val - 128) * .65f + 128; rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k; val = (val - 128) * .65f + 128; rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); val = y + 1.772 * (cb - 128) - k; val = (val - 128) * .65f + 128; rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); } raster = Raster.createInterleavedRaster(new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3, new int[]{0, 1, 2}, null); ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel cm = new ComponentColorModel(cs, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); return new BufferedImage(cm, (WritableRaster) raster, true, null); }private static int pos4twist(double rank, double phase, double period, int hOrW, int xOrY, int yOrX) { double dyOrX = Math.PI * rank * yOrX / hOrW + phase; double dxOrY = Math.sin(dyOrX); return xOrY + (int) (dxOrY * period); }public AnnotationVisitor visitAnnotation(String name, String desc) { if (av != null) { return av.visitAnnotation(name, desc); } return null; }public void visitEnum(String name, String desc, String value) { if (av != null) { av.visitEnum(name, desc, value); } }private void put112(final int b1, final int b2, final int s) { pool.put11(b1, b2).putShort(s); }private void put122(final int b, final int s1, final int s2) { pool.put12(b, s1).putShort(s2); }private Item get(final Item key) { Item i = items[key.hashCode % items.length]; while (i != null && (i.type != key.type || !key.isEqualTo(i))) { i = i.next; } return i; }Item newNameTypeItem(final String name, final String desc) { key2.set(NAME_TYPE, name, desc, null); Item result = get(key2); if (result == null) { put122(NAME_TYPE, newUTF8(name), newUTF8(desc)); result = new Item(index++, key2); put(result); } return result; }private Item newString(final String value) { key2.set(STR, value, null, null); Item result = get(key2); if (result == null) { pool.put12(STR, newUTF8(value)); result = new Item(index++, key2); put(result); } return result; }Item newFloat(final float value) { key.set(value); Item result = get(key); if (result == null) { pool.putByte(FLOAT).putInt(key.intVal); result = new Item(index++, key); put(result); } return result; }Item newMethodItem(final String owner, final String name, final String desc, final boolean itf) { int type = itf ? IMETH : METH; key3.set(type, owner, name, desc); Item result = get(key3); if (result == null) { put122(type, newClass(owner), newNameType(name, desc)); result = new Item(index++, key3); put(result); } return result; }private int startFrame(final int offset, final int nLocal, final int nStack) { int n = 3 + nLocal + nStack; if (frame == null || frame.length < n) { frame = new int[n]; } frame[0] = offset; frame[1] = nLocal; frame[2] = nStack; return 3; }private void visitImplicitFirstFrame() { // There can be at most descriptor.length() + 1 locals int frameIndex = startFrame(0, descriptor.length() + 1, 0); if ((access & Opcodes.ACC_STATIC) == 0) { if ((access & ACC_CONSTRUCTOR) == 0) { frame[frameIndex++] = Frame.OBJECT | cw.addType(cw.thisName); } else { frame[frameIndex++] = 6; // Opcodes.UNINITIALIZED_THIS; } } int i = 1; loop: while (true) { int j = i; switch (descriptor.charAt(i++)) { case 'Z': case 'C': case 'B': case 'S': case 'I': frame[frameIndex++] = 1; // Opcodes.INTEGER; break; case 'F': frame[frameIndex++] = 2; // Opcodes.FLOAT; break; case 'J': frame[frameIndex++] = 4; // Opcodes.LONG; break; case 'D': frame[frameIndex++] = 3; // Opcodes.DOUBLE; break; case '[': while (descriptor.charAt(i) == '[') { ++i; } if (descriptor.charAt(i) == 'L') { ++i; while (descriptor.charAt(i) != ';') { ++i; } } frame[frameIndex++] = Frame.OBJECT | cw.addType(descriptor.substring(j, ++i)); break; case 'L': while (descriptor.charAt(i) != ';') { ++i; } frame[frameIndex++] = Frame.OBJECT | cw.addType(descriptor.substring(j + 1, i++)); break; default: break loop; } } frame[1] = frameIndex - 3; endFrame(); }public void checkCast(final Type type) { if (!type.equals(OBJECT_TYPE)) { typeInsn(Opcodes.CHECKCAST, type); } }public void throwException(final Type type, final String msg) { newInstance(type); dup(); push(msg); invokeConstructor(type, Method.getMethod("void (String)")); throwException(); }public void invokeInterface(final Type owner, final Method method) { invokeInsn(Opcodes.INVOKEINTERFACE, owner, method, true); }public void invokeStatic(final Type owner, final Method method) { invokeInsn(Opcodes.INVOKESTATIC, owner, method, false); }public void invokeConstructor(final Type type, final Method method) { invokeInsn(Opcodes.INVOKESPECIAL, type, method, false); }public void invokeVirtual(final Type owner, final Method method) { invokeInsn(Opcodes.INVOKEVIRTUAL, owner, method, false); }private void invokeInsn(final int opcode, final Type type, final Method method, final boolean itf) { String owner = type.getSort() == Type.ARRAY ? type.getDescriptor() : type.getInternalName(); mv.visitMethodInsn(opcode, owner, method.getName(), method.getDescriptor(), itf); }public void putField(final Type owner, final String name, final Type type) { fieldInsn(Opcodes.PUTFIELD, owner, name, type); }public void getField(final Type owner, final String name, final Type type) { fieldInsn(Opcodes.GETFIELD, owner, name, type); }public void putStatic(final Type owner, final String name, final Type type) { fieldInsn(Opcodes.PUTSTATIC, owner, name, type); }public void getStatic(final Type owner, final String name, final Type type) { fieldInsn(Opcodes.GETSTATIC, owner, name, type); }private void fieldInsn(final int opcode, final Type ownerType, final String name, final Type fieldType) { mv.visitFieldInsn(opcode, ownerType.getInternalName(), name, fieldType.getDescriptor()); }public void ifCmp(final Type type, final int mode, final Label label) { switch (type.getSort()) { case Type.LONG: mv.visitInsn(Opcodes.LCMP); break; case Type.DOUBLE: mv.visitInsn(mode == GE || mode == GT ? Opcodes.DCMPL : Opcodes.DCMPG); break; case Type.FLOAT: mv.visitInsn(mode == GE || mode == GT ? Opcodes.FCMPL : Opcodes.FCMPG); break; case Type.ARRAY: case Type.OBJECT: switch (mode) { case EQ: mv.visitJumpInsn(Opcodes.IF_ACMPEQ, label); return; case NE: mv.visitJumpInsn(Opcodes.IF_ACMPNE, label); return; } throw new IllegalArgumentException("Bad comparison for type " + type); default: int intOp = -1; switch (mode) { case EQ: intOp = Opcodes.IF_ICMPEQ; break; case NE: intOp = Opcodes.IF_ICMPNE; break; case GE: intOp = Opcodes.IF_ICMPGE; break; case LT: intOp = Opcodes.IF_ICMPLT; break; case LE: intOp = Opcodes.IF_ICMPLE; break; case GT: intOp = Opcodes.IF_ICMPGT; break; } mv.visitJumpInsn(intOp, label); return; } mv.visitJumpInsn(mode, label); }public void unbox(final Type type) { Type t = NUMBER_TYPE; Method sig = null; switch (type.getSort()) { case Type.VOID: return; case Type.CHAR: t = CHARACTER_TYPE; sig = CHAR_VALUE; break; case Type.BOOLEAN: t = BOOLEAN_TYPE; sig = BOOLEAN_VALUE; break; case Type.DOUBLE: sig = DOUBLE_VALUE; break; case Type.FLOAT: sig = FLOAT_VALUE; break; case Type.LONG: sig = LONG_VALUE; break; case Type.INT: case Type.SHORT: case Type.BYTE: sig = INT_VALUE; } if (sig == null) { checkCast(type); } else { checkCast(t); invokeVirtual(t, sig); } }public void box(final Type type) { if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) { return; } if (type == Type.VOID_TYPE) { push((String) null); } else { Type boxed = getBoxedType(type); newInstance(boxed); if (type.getSize() == 2) { // Pp -> Ppo -> oPpo -> ooPpo -> ooPp -> o dupX2(); dupX2(); pop(); } else { // p -> po -> opo -> oop -> o dupX1(); swap(); } invokeConstructor(boxed, new Method("", Type.VOID_TYPE, new Type[] { type })); } }public void swap(final Type prev, final Type type) { if (type.getSize() == 1) { if (prev.getSize() == 1) { swap(); // same as dupX1(), pop(); } else { dupX2(); pop(); } } else { if (prev.getSize() == 1) { dup2X1(); pop2(); } else { dup2X2(); pop2(); } } }public void storeLocal(final int local, final Type type) { setLocalType(local, type); storeInsn(type, local); }public void loadLocal(final int local, final Type type) { setLocalType(local, type); loadInsn(type, local); }public void loadArgArray() { push(argumentTypes.length); newArray(OBJECT_TYPE); for (int i = 0; i < argumentTypes.length; i++) { dup(); push(i); loadArg(i); box(argumentTypes[i]); arrayStore(OBJECT_TYPE); } }public void loadArgs(final int arg, final int count) { int index = getArgIndex(arg); for (int i = 0; i < count; ++i) { Type t = argumentTypes[arg + i]; loadInsn(t, index); index += t.getSize(); } }private void storeInsn(final Type type, final int index) { mv.visitVarInsn(type.getOpcode(Opcodes.ISTORE), index); }private void loadInsn(final Type type, final int index) { mv.visitVarInsn(type.getOpcode(Opcodes.ILOAD), index); }private int getArgIndex(final int arg) { int index = (access & Opcodes.ACC_STATIC) == 0 ? 1 : 0; for (int i = 0; i < arg; i++) { index += argumentTypes[i].getSize(); } return index; }private void parse(String expression) throws IllegalArgumentException { String[] fields = Strings.splitIgnoreBlank(expression, " "); if (fields.length != 6) { throw new IllegalArgumentException(String.format( "Cron expression must consist of 6 fields (found %d in \"%s\")", fields.length, expression)); } setNumberHits(this.seconds, fields[0], 0, 60); setNumberHits(this.minutes, fields[1], 0, 60); setNumberHits(this.hours, fields[2], 0, 24); setDaysOfMonth(this.daysOfMonth, fields[3]); setMonths(this.months, fields[4]); setDays(this.daysOfWeek, replaceOrdinals(fields[5], "SUN,MON,TUE,WED,THU,FRI,SAT"), 8); if (this.daysOfWeek.get(7)) { // Sunday can be represented as 0 or 7 this.daysOfWeek.set(0); this.daysOfWeek.clear(7); } }private void reset(Calendar calendar, List fields) { for (int field : fields) { calendar.set(field, field == Calendar.DAY_OF_MONTH ? 1 : 0); } }private int findNext(BitSet bits, int value, Calendar calendar, int field, int nextField, List lowerOrders) { int nextValue = bits.nextSetBit(value); // roll over if needed if (nextValue == -1) { calendar.add(nextField, 1); reset(calendar, Arrays.asList(field)); nextValue = bits.nextSetBit(0); } if (nextValue != value) { calendar.set(field, nextValue); reset(calendar, lowerOrders); } return nextValue; }private static String fixTracePath(String tracePath) { String defaultTraceBody = "dmtrace"; String defaultTraceExtension = ".trace"; if (tracePath == null || tracePath.charAt(0) != '/') { final File dir = RuntimeEnvironment.application.getExternalFilesDir(null); if (tracePath == null) { tracePath = new File(dir, defaultTraceBody).getAbsolutePath(); } else { tracePath = new File(dir, tracePath).getAbsolutePath(); } } if (!tracePath.endsWith(defaultTraceExtension)) { tracePath += defaultTraceExtension; } return tracePath; }static void changeDisplay(int displayId, Consumer consumer) { DisplayInfo displayInfo = DisplayManagerGlobal.getInstance().getDisplayInfo(displayId); if (displayInfo != null) { DisplayConfig displayConfig = new DisplayConfig(displayInfo); consumer.accept(displayConfig); displayConfig.copyTo(displayInfo); fixNominalDimens(displayInfo); } getShadowDisplayManagerGlobal().changeDisplay(displayId, displayInfo); }public static int addDisplay(String qualifiersStr) { int id = getShadowDisplayManagerGlobal().addDisplay(createDisplayInfo(qualifiersStr, null)); shadowMainLooper().idle(); return id; }public Collection getContentObservers(Uri uri) { ArrayList observers = new ArrayList<>(1); for (ContentObserverEntry entry : contentObservers) { if (entry.matches(uri)) { observers.add(entry.observer); } } return observers; }public static Status getStatus(Account account, String authority, boolean create) { Map map = syncableAccounts.get(authority); if (map == null) { map = new HashMap<>(); syncableAccounts.put(authority, map); } Status status = map.get(account); if (status == null && create) { status = new Status(); map.put(account, status); } return status; }public static T reflector(Class iClass, Object target) { Class targetClass = determineTargetClass(iClass); Constructor ctor = (Constructor) CACHE.get(iClass); try { if (ctor == null) { Class reflectorClass = createReflectorClass(iClass, targetClass); ctor = reflectorClass.getConstructor(targetClass); ctor.setAccessible(true); } CACHE.put(iClass, ctor); return ctor.newInstance(target); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException(e); } }private static char[] extractCodePoint(String codePoint) { try { return Character.toChars(Integer.valueOf(codePoint, 16)); } catch (IllegalArgumentException e) { // This may be caused by NumberFormatException of Integer.valueOf() or // IllegalArgumentException of Character.toChars(). throw new IllegalArgumentException("Invalid code point: \\u" + codePoint, e); } }private boolean hasProfileOwnerOrDeviceOwnerOnCurrentUser() { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); return devicePolicyManager.getProfileOwner() != null || (UserHandle.of(UserHandle.myUserId()).isSystem() && devicePolicyManager.getDeviceOwner() != null); }@Implementation(minSdk = LOLLIPOP) protected Drawable getUserBadgedIcon(Drawable icon, UserHandle user) { return icon; }private int getPermissionIndex(PackageInfo packageInfo, String permissionName) { if (packageInfo.requestedPermissions != null) { for (int i = 0; i < packageInfo.requestedPermissions.length; i++) { if (permissionName.equals(packageInfo.requestedPermissions[i])) { return i; } } } return -1; }private void applyFlagsToComponentInfo(ComponentInfo componentInfo, int flags) throws NameNotFoundException { componentInfo.name = (componentInfo.name == null) ? "" : componentInfo.name; ApplicationInfo applicationInfo = componentInfo.applicationInfo; boolean isApplicationEnabled = true; if (applicationInfo != null) { if (applicationInfo.packageName == null) { applicationInfo.packageName = componentInfo.packageName; } applyFlagsToApplicationInfo(componentInfo.applicationInfo, flags); componentInfo.packageName = applicationInfo.packageName; isApplicationEnabled = applicationInfo.enabled; } if ((flags & GET_META_DATA) == 0) { componentInfo.metaData = null; } boolean isComponentEnabled = isComponentEnabled(componentInfo); if ((flags & MATCH_ALL) != 0 && Build.VERSION.SDK_INT >= 23) { return; } // Android don't override the enabled field of component with the actual value. boolean isEnabledForFiltering = isComponentEnabled && (Build.VERSION.SDK_INT >= 24 ? isApplicationEnabled : true); if ((flags & MATCH_DISABLED_COMPONENTS) == 0 && !isEnabledForFiltering) { throw new NameNotFoundException("Disabled component: " + componentInfo); } if (isFlagSet(flags, PackageManager.MATCH_SYSTEM_ONLY)) { if (applicationInfo == null) { // TODO: for backwards compatibility just skip filtering. In future should just remove // invalid resolve infos from list } else { final int applicationFlags = applicationInfo.flags; if ((applicationFlags & ApplicationInfo.FLAG_SYSTEM) != ApplicationInfo.FLAG_SYSTEM) { throw new NameNotFoundException("Not system component: " + componentInfo); } } } if (!isFlagSet(flags, MATCH_UNINSTALLED_PACKAGES) && isValidComponentInfo(componentInfo) && hiddenPackages.contains(componentInfo.applicationInfo.packageName)) { throw new NameNotFoundException("Uninstalled package: " + componentInfo); } }private boolean isGrantedForBackwardsCompatibility(String pkgName, PackageInfo permissionsInfo) { // Note: it might be cleaner to auto-grant these permissions when the package is added to the // PackageManager. But many existing tests modify the requested permissions _after_ adding the // package to the PackageManager, without updating the requestedPermissionsFlags. return permissionsInfo.requestedPermissionsFlags == null // Robolectric uses the PackageParser to create the current test package's PackageInfo from // the manifest XML. The parser populates the requestedPermissionsFlags, but doesn't grant // the permissions. Several tests rely on the test package being granted all permissions, so // we treat this as a special case. || pkgName.equals(RuntimeEnvironment.application.getPackageName()); }private static PackageInfo newPackageInfo(PackageInfo orig) { Parcel parcel = Parcel.obtain(); orig.writeToParcel(parcel, 0); parcel.setDataPosition(0); return PackageInfo.CREATOR.createFromParcel(parcel); }static String convertSQLWithLocalizedUnicodeCollator(String sql) { Matcher matcher = COLLATE_LOCALIZED_UNICODE_PATTERN.matcher(sql); return matcher.replaceAll(" COLLATE NOCASE"); }private static Bundle metaDataToBundle(Map meta) { if (meta.size() == 0) { return null; } Bundle bundle = new Bundle(); for (Map.Entry entry : meta.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (Boolean.class.isInstance(value)) { bundle.putBoolean(key, (Boolean) value); } else if (Float.class.isInstance(value)) { bundle.putFloat(key, (Float) value); } else if (Integer.class.isInstance(value)) { bundle.putInt(key, (Integer) value); } else { bundle.putString(key, value == null ? null : value.toString()); } } return bundle; }public void simulateTimeChange(long offsetToAddInMillis) { ImmutableMap.Builder eventMapBuilder = ImmutableMap.builder(); for (Event event : eventsByTimeStamp.values()) { long newTimestamp = event.getTimeStamp() + offsetToAddInMillis; eventMapBuilder.put( newTimestamp, EventBuilder.fromEvent(event).setTimeStamp(newTimestamp).build()); } eventsByTimeStamp.putAll(eventMapBuilder.build()); }@Implementation(minSdk = LOLLIPOP) protected void releaseOutputBuffer(int index, boolean render, boolean updatePTS, long timeNs) { if (reachedEos) { return; } makeInputBufferAvailable(index); }@Implementation(minSdk = LOLLIPOP) protected void native_queueInputBuffer( int index, int offset, int size, long presentationTimeUs, int flags) { // Check if this should be the last buffer cycle. if ((flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { reachedEos = true; } BufferInfo info = new BufferInfo(); info.set(offset, size, presentationTimeUs, flags); makeOutputBufferAvailable(index, info); }@Implementation(minSdk = LOLLIPOP) protected ByteBuffer getBuffer(boolean input, int index) { ByteBuffer[] buffers = input ? inputBuffers : outputBuffers; return (index >= 0 && index < buffers.length) ? buffers[index] : null; }@Implementation(minSdk = LOLLIPOP) protected void native_start() { // Currently only support async-mode. if (callback == null) { return; } // Report the format as changed, to simulate adding codec specific info before making input // buffers available. HashMap format = new HashMap<>(); format.put("csd-0", ByteBuffer.wrap(new byte[]{0x13, 0x10})); format.put("csd-1", ByteBuffer.wrap(new byte[0])); postFakeNativeEvent(EVENT_CALLBACK, CB_OUTPUT_FORMAT_CHANGE, 0, format); // Reset state. reachedEos = false; makeInputBufferAvailable(0); }@Implementation(minSdk = O) protected int abandonAudioFocusRequest(android.media.AudioFocusRequest audioFocusRequest) { lastAbandonedAudioFocusRequest = audioFocusRequest; return nextResponseValue; }@Implementation(minSdk = O) protected int requestAudioFocus(android.media.AudioFocusRequest audioFocusRequest) { lastAudioFocusRequest = new AudioFocusRequest(audioFocusRequest); return nextResponseValue; }public boolean runNext() { if (!hasQueuedTasks()) { return false; } if (Thread.currentThread().equals(executorThread)) { Logger.info("ignoring request to execute task - called from executor's own thread"); return false; } Runnable task = deferredTasks.poll(); task.run(); return true; }public int runAll() { int numTasksRun = 0; if (Thread.currentThread().equals(executorThread)) { Logger.info("ignoring request to execute task - called from executor's own thread"); return numTasksRun; } while (hasQueuedTasks()) { runNext(); numTasksRun++; } return numTasksRun; }boolean create(String origFileName, int fd, long offset, int length, boolean readOnly) { this.mFileName = origFileName; this.fd = fd; this.mDataOffset = offset; this.readOnly = readOnly; return true; }@SuppressWarnings("unchecked") @Nonnull private synchronized Provider getProvider(final Key key) { // Previously-gotten providers (including those from subinjectors) will already be present. return (Provider) providers.computeIfAbsent(key, k -> { // @AutoFactory requests are always handled by the top-level injector. if (key.isAutoFactory()) { return memoized(new ScopeBuilderProvider<>(key.getDependencyClass())); } // Find a provider locally. return findLocalProvider(key); }); }@Implementation(minSdk = JELLY_BEAN_MR2) protected static void endSection() { if (Trace.isTagEnabled(TRACE_TAG_APP)) { synchronized (lock) { if (currentSections.isEmpty()) { Log.e(TAG, "Trying to end a trace section that was never started"); return; } previousSections.offer(currentSections.removeFirst()); } } }@Implementation(minSdk = JELLY_BEAN_MR2) protected static void beginSection(String sectionName) { if (Trace.isTagEnabled(TRACE_TAG_APP)) { if (crashOnIncorrectUsage) { if (sectionName.length() > MAX_SECTION_NAME_LEN) { throw new IllegalArgumentException("sectionName is too long"); } } else if (sectionName == null) { Log.w(TAG, "Section name cannot be null"); return; } else if (sectionName.length() > MAX_SECTION_NAME_LEN) { Log.w(TAG, "Section name is too long"); return; } synchronized (lock) { currentSections.addFirst(sectionName); } } }@Implementation protected static void RGBToHSV(int red, int green, int blue, float hsv[]) { java.awt.Color.RGBtoHSB(red, green, blue, hsv); hsv[0] = hsv[0] * 360; }private ListenableFuture postIntent( final Wrapper wrapper, final Intent intent, ListenableFuture oldResult, final AtomicBoolean abort, final Context context) { final Handler scheduler = (wrapper.scheduler != null) ? wrapper.scheduler : getMainHandler(context); return Futures.transformAsync( oldResult, new AsyncFunction() { @Override public ListenableFuture apply( BroadcastResultHolder broadcastResultHolder) throws Exception { final BroadcastReceiver.PendingResult result = ShadowBroadcastPendingResult.create( broadcastResultHolder.resultCode, broadcastResultHolder.resultData, broadcastResultHolder.resultExtras, true /*ordered */); wrapper.broadcastReceiver.setPendingResult(result); scheduler.post( () -> { ShadowBroadcastReceiver shadowBroadcastReceiver = Shadow.extract(wrapper.broadcastReceiver); shadowBroadcastReceiver.onReceive(context, intent, abort); }); return BroadcastResultHolder.transform(result); } }, directExecutor()); }private List getAppropriateWrappers(Intent intent, String receiverPermission) { broadcastIntents.add(intent); List result = new ArrayList<>(); List copy = new ArrayList<>(); copy.addAll(registeredReceivers); String intentClass = intent.getComponent() != null ? intent.getComponent().getClassName() : null; for (Wrapper wrapper : copy) { if ((hasMatchingPermission(wrapper.broadcastPermission, receiverPermission) && wrapper.intentFilter.matchAction(intent.getAction())) || (intentClass != null && intentClass.equals(wrapper.broadcastReceiver.getClass().getName()))) { final int match = wrapper.intentFilter.matchData(intent.getType(), intent.getScheme(), intent.getData()); if (match != IntentFilter.NO_MATCH_DATA && match != IntentFilter.NO_MATCH_TYPE) { result.add(wrapper); } } } return result; }@SuppressWarnings("UnusedDeclaration") public static String innerText(View view) { ShadowView shadowView = Shadow.extract(view); return shadowView.innerText(); }@SuppressWarnings("UnusedDeclaration") @Deprecated public static void dump(View view) { ShadowView shadowView = Shadow.extract(view); shadowView.dump(); }@Nonnull synchronized public PackageResourceTable getCompileTimeSdkResourceTable() { if (compiletimeSdkResourceTable == null) { ResourceTableFactory resourceTableFactory = new ResourceTableFactory(); compiletimeSdkResourceTable = resourceTableFactory .newFrameworkResourceTable(new ResourcePath(android.R.class, null, null)); } return compiletimeSdkResourceTable; }@Implementation public static Typeface getFontSync(FontRequest request) { return Typeface.create(request.getQuery(), Typeface.NORMAL); }@Implementation(minSdk = P) protected void startRanging( RangingRequest request, Executor executor, RangingResultCallback callback) { if (!rangingResults.isEmpty()) { executor.execute(() -> callback.onRangingResults(this.rangingResults)); } else { executor.execute(() -> callback.onRangingFailure(RangingResultCallback.STATUS_CODE_FAIL)); } }public static R callConstructor(Class clazz, ClassParameter... classParameters) { try { final Class[] classes = ClassParameter.getClasses(classParameters); final Object[] values = ClassParameter.getValues(classParameters); Constructor constructor = clazz.getDeclaredConstructor(classes); constructor.setAccessible(true); return constructor.newInstance(values); } catch (InstantiationException e) { throw new RuntimeException("error instantiating " + clazz.getName(), e); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof RuntimeException) { throw (RuntimeException) e.getTargetException(); } if (e.getTargetException() instanceof Error) { throw (Error) e.getTargetException(); } throw new RuntimeException(e.getTargetException()); } catch (Exception e) { throw new RuntimeException(e); } }public static T newInstance(Class cl) { try { return cl.getDeclaredConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { throw new RuntimeException(e); } }@SuppressWarnings("unchecked") public static R callStaticMethod(Class clazz, String methodName, ClassParameter... classParameters) { try { Class[] classes = ClassParameter.getClasses(classParameters); Object[] values = ClassParameter.getValues(classParameters); Method method = clazz.getDeclaredMethod(methodName, classes); method.setAccessible(true); if (!Modifier.isStatic(method.getModifiers())) { throw new IllegalArgumentException(method + " is not static"); } return (R) method.invoke(null, values); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof RuntimeException) { throw (RuntimeException) e.getTargetException(); } if (e.getTargetException() instanceof Error) { throw (Error) e.getTargetException(); } throw new RuntimeException(e.getTargetException()); } catch (NoSuchMethodException e) { throw new RuntimeException("no such method " + clazz + "." + methodName, e); } catch (Exception e) { throw new RuntimeException(e); } }public static R callStaticMethod( ClassLoader classLoader, String fullyQualifiedClassName, String methodName, ClassParameter... classParameters) { Class clazz = loadClass(classLoader, fullyQualifiedClassName); return callStaticMethod(clazz, methodName, classParameters); }public static R callInstanceMethod(Class cl, final Object instance, final String methodName, ClassParameter... classParameters) { try { final Class[] classes = ClassParameter.getClasses(classParameters); final Object[] values = ClassParameter.getValues(classParameters); Method method = cl.getDeclaredMethod(methodName, classes); method.setAccessible(true); if (Modifier.isStatic(method.getModifiers())) { throw new IllegalArgumentException(method + " is static"); } return (R) method.invoke(instance, values); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof RuntimeException) { throw (RuntimeException) e.getTargetException(); } if (e.getTargetException() instanceof Error) { throw (Error) e.getTargetException(); } throw new RuntimeException(e.getTargetException()); } catch (Exception e) { throw new RuntimeException(e); } }public static R callInstanceMethod(final Object instance, final String methodName, ClassParameter... classParameters) { try { final Class[] classes = ClassParameter.getClasses(classParameters); final Object[] values = ClassParameter.getValues(classParameters); return traverseClassHierarchy(instance.getClass(), NoSuchMethodException.class, new InsideTraversal() { @Override @SuppressWarnings("unchecked") public R run(Class traversalClass) throws Exception { Method declaredMethod = traversalClass.getDeclaredMethod(methodName, classes); declaredMethod.setAccessible(true); return (R) declaredMethod.invoke(instance, values); } }); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof RuntimeException) { throw (RuntimeException) e.getTargetException(); } if (e.getTargetException() instanceof Error) { throw (Error) e.getTargetException(); } throw new RuntimeException(e.getTargetException()); } catch (Exception e) { throw new RuntimeException(e); } }@SuppressWarnings("unchecked") public static R getField(final Object object, final String fieldName) { try { return traverseClassHierarchy(object.getClass(), NoSuchFieldException.class, new InsideTraversal() { @Override public R run(Class traversalClass) throws Exception { Field field = traversalClass.getDeclaredField(fieldName); field.setAccessible(true); return (R) field.get(object); } }); } catch (Exception e) { throw new RuntimeException(e); } }public static T createDeepProxy(Class clazz) { return (T) Proxy.newProxyInstance( clazz.getClassLoader(), new Class[] {clazz}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (PRIMITIVE_RETURN_VALUES.containsKey(method.getReturnType().getName())) { return PRIMITIVE_RETURN_VALUES.get(method.getReturnType().getName()); } else if (method.getReturnType().isInterface()) { return createDeepProxy(method.getReturnType()); } else { return null; } } }); }public MediaItem createMediaItem(String parentId, String mediaId, String title, int flag) { final MediaMetadataCompat metadataCompat = new MediaMetadataCompat.Builder() .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, mediaId) .putString(MediaMetadataCompat.METADATA_KEY_TITLE, title) .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, Uri.parse(mediaId).toString()) .build(); final MediaItem mediaItem = new MediaItem(metadataCompat.getDescription(), flag); mediaItems.put(mediaId, mediaItem); // If this MediaItem is the child of a MediaItem that has already been created. This applies to // all MediaItems except the root. if (parentId != null) { final MediaItem parentItem = mediaItems.get(parentId); List children = mediaItemChildren.get(parentItem); if (children == null) { children = new ArrayList<>(); mediaItemChildren.put(parentItem, children); } children.add(mediaItem); } return mediaItem; }void addData(String tag, long timestamp, byte[] data) { entries.put(timestamp, new DropBoxManager.Entry(tag, timestamp, data, DropBoxManager.IS_TEXT)); }@Implementation protected ParcelFileDescriptor openAccessory(UsbAccessory accessory) { try { File tmpUsbDir = RuntimeEnvironment.getTempDirectory().createIfNotExists("usb-accessory").toFile(); return ParcelFileDescriptor.open( new File(tmpUsbDir, "usb-accessory-file"), ParcelFileDescriptor.MODE_READ_WRITE); } catch (FileNotFoundException error) { throw new RuntimeException("Error shadowing openAccessory", error); } }public void addPort(String portId) { if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.Q) { usbPorts.put( (UsbPort) createUsbPort(realUsbManager, portId, UsbPortStatus.MODE_DUAL), (UsbPortStatus) createUsbPortStatus( UsbPortStatus.MODE_DUAL, UsbPortStatus.POWER_ROLE_SINK, UsbPortStatus.DATA_ROLE_DEVICE, 0)); return; } usbPorts.put( callConstructor(UsbPort.class, from(String.class, portId), from(int.class, getStaticField(UsbPort.class, "MODE_DUAL"))), (UsbPortStatus) createUsbPortStatus( getStaticField(UsbPort.class, "MODE_DUAL"), getStaticField(UsbPort.class, "POWER_ROLE_SINK"), getStaticField(UsbPort.class, "DATA_ROLE_DEVICE"), 0)); }public void removeUsbDevice(UsbDevice usbDevice) { Preconditions.checkNotNull(usbDevice); usbDevices.remove(usbDevice.getDeviceName()); revokePermission(usbDevice, RuntimeEnvironment.application.getPackageName()); }public void addOrUpdateUsbDevice(UsbDevice usbDevice, boolean hasPermission) { Preconditions.checkNotNull(usbDevice); Preconditions.checkNotNull(usbDevice.getDeviceName()); usbDevices.put(usbDevice.getDeviceName(), usbDevice); if (hasPermission) { grantPermission(usbDevice); } else { revokePermission(usbDevice, RuntimeEnvironment.application.getPackageName()); } }public void revokePermission(UsbDevice device, String packageName) { List usbDevices = grantedPermissions.get(packageName); if (usbDevices != null) { usbDevices.remove(device); } }public boolean hasPermissionForPackage(UsbDevice device, String packageName) { List usbDevices = grantedPermissions.get(packageName); return usbDevices != null && usbDevices.contains(device); }public static S loadFromSystemProperty(final Class service) { try { final String className = System.getProperty(service.getName()); if (className != null) { Class c = ClassLoader.getSystemClassLoader().loadClass(className); return (S) c.newInstance(); } return null; } catch (Exception e) { throw new Error(e); } }public static ServiceFinder loadInstalled(Class service) { ClassLoader cl = ClassLoader.getSystemClassLoader(); ClassLoader prev = null; while (cl != null) { prev = cl; cl = cl.getParent(); } return load(service, prev); }public static ServiceFinder load(Class service, ClassLoader loader) { return new ServiceFinder<>(service, loader); }public static String buildString(char[] data) { int count = 0; for (count=0; count < data.length; count++) { if (data[count] == 0) { break; } } return new String(data, 0, count); }public static void setQualifiers(String newQualifiers) { Configuration configuration; DisplayMetrics displayMetrics = new DisplayMetrics(); if (newQualifiers.startsWith("+")) { configuration = new Configuration(Resources.getSystem().getConfiguration()); displayMetrics.setTo(Resources.getSystem().getDisplayMetrics()); } else { configuration = new Configuration(); } Bootstrap.applyQualifiers(newQualifiers, getApiLevel(), configuration, displayMetrics); Resources systemResources = Resources.getSystem(); systemResources.updateConfiguration(configuration, displayMetrics); if (application != null) { application.getResources().updateConfiguration(configuration, displayMetrics); } }public static String getQualifiers(Configuration configuration, DisplayMetrics displayMetrics) { return ConfigurationV25.resourceQualifierString(configuration, displayMetrics); }int add( Asset asset, Asset idmapAsset, final int cookie, boolean copyData, boolean appAsLib, boolean isSystemAsset) { final byte[] data = asset.getBuffer(true); if (data == NULL) { ALOGW("Unable to get buffer of resource asset file"); return UNKNOWN_ERROR; } int idmapSize = 0; Object idmapData = NULL; if (idmapAsset != NULL) { idmapData = idmapAsset.getBuffer(true); if (idmapData == NULL) { ALOGW("Unable to get buffer of idmap asset file"); return UNKNOWN_ERROR; } idmapSize = (int) idmapAsset.getLength(); } return addInternal(data, (int) asset.getLength(), idmapData, idmapSize, appAsLib, cookie, copyData, isSystemAsset); }private static boolean isAndroidSupportedFeature(String name) { if (name == null) { return false; } for (String feature : AVAILABLE_FEATURES) { if (feature.equals(name)) { return true; } } return false; }int navigateToNextNode(Node node) throws XmlPullParserException { Node nextNode = node.getNextSibling(); if (nextNode != null) { // Move to the next siblings return processNextNodeType(nextNode); } else { // Goes back to the parent if (document.getDocumentElement().equals(node)) { currentNode = null; return END_DOCUMENT; } currentNode = node.getParentNode(); return END_TAG; } }public String qualify(String value) { if (value == null) return null; if (AttributeResource.isResourceReference(value)) { return "@" + ResName.qualifyResourceName(value.trim().substring(1).replace("+", ""), packageName, "attr"); } else if (AttributeResource.isStyleReference(value)) { return "?" + ResName.qualifyResourceName(value.trim().substring(1), packageName, "attr"); } else { return StringResources.processStringResources(value); } }@Override protected String getCommonSuperClass(final String type1, final String type2) { try { ClassNode info1 = typeInfo(type1); ClassNode info2 = typeInfo(type2); if ((info1.access & Opcodes.ACC_INTERFACE) != 0) { if (typeImplements(type2, info2, type1)) { return type1; } if ((info2.access & Opcodes.ACC_INTERFACE) != 0) { if (typeImplements(type1, info1, type2)) { return type2; } } return "java/lang/Object"; } if ((info2.access & Opcodes.ACC_INTERFACE) != 0) { if (typeImplements(type1, info1, type2)) { return type2; } else { return "java/lang/Object"; } } String b1 = typeAncestors(type1, info1); String b2 = typeAncestors(type2, info2); String result = "java/lang/Object"; int end1 = b1.length(); int end2 = b2.length(); while (true) { int start1 = b1.lastIndexOf(';', end1 - 1); int start2 = b2.lastIndexOf(';', end2 - 1); if (start1 != -1 && start2 != -1 && end1 - start1 == end2 - start2) { String p1 = b1.substring(start1 + 1, end1); String p2 = b2.substring(start2 + 1, end2); if (p1.equals(p2)) { result = p1; end1 = start1; end2 = start2; } else { return result; } } else { return result; } } } catch (ClassNotFoundException e) { return "java/lang/Object"; // Handle classes that may be obfuscated } }protected void establishRoute(HttpRoute route, HttpContext context) throws HttpException, IOException { HttpRouteDirector rowdy = new BasicRouteDirector(); int step; do { HttpRoute fact = managedConn.getRoute(); step = rowdy.nextStep(route, fact); switch (step) { case HttpRouteDirector.CONNECT_TARGET: case HttpRouteDirector.CONNECT_PROXY: managedConn.open(route, context, this.params); break; case HttpRouteDirector.TUNNEL_TARGET: { boolean secure = createTunnelToTarget(route, context); this.log.debug("Tunnel to target created."); managedConn.tunnelTarget(secure, this.params); } break; case HttpRouteDirector.TUNNEL_PROXY: { // The most simple example for this case is a proxy chain // of two proxies, where P1 must be tunnelled to P2. // route: Source -> P1 -> P2 -> Target (3 hops) // fact: Source -> P1 -> Target (2 hops) final int hop = fact.getHopCount()-1; // the hop to establish boolean secure = createTunnelToProxy(route, hop, context); this.log.debug("Tunnel to proxy created."); managedConn.tunnelProxy(route.getHopTarget(hop), secure, this.params); } break; case HttpRouteDirector.LAYER_PROTOCOL: managedConn.layerProtocol(context, this.params); break; case HttpRouteDirector.UNREACHABLE: throw new IllegalStateException ("Unable to establish route." + "\nplanned = " + route + "\ncurrent = " + fact); case HttpRouteDirector.COMPLETE: // do nothing break; default: throw new IllegalStateException ("Unknown step indicator "+step+" from RouteDirector."); } // switch } while (step > HttpRouteDirector.COMPLETE); }protected void releaseConnection() { // Release the connection through the ManagedConnection instead of the // ConnectionManager directly. This lets the connection control how // it is released. try { managedConn.releaseConnection(); } catch(IOException ignored) { this.log.debug("IOException releasing connection", ignored); } managedConn = null; }public void setState(int state) { if (!isJB()) { ShadowDisplayManager.changeDisplay(realObject.getDisplayId(), di -> di.state = state); } }public void setRotation(int rotation) { if (isJB()) { this.rotation = rotation; } else { ShadowDisplayManager.changeDisplay(realObject.getDisplayId(), di -> di.rotation = rotation); } }public void setRealHeight(int height) { if (isJB()) { this.realHeight = height; } else { ShadowDisplayManager.changeDisplay(realObject.getDisplayId(), di -> di.logicalHeight = height); } }public void setRealWidth(int width) { if (isJB()) { this.realWidth = width; } else { ShadowDisplayManager.changeDisplay(realObject.getDisplayId(), di -> di.logicalWidth = width); } }public void setHeight(int height) { if (isJB()) { this.height = height; } else { ShadowDisplayManager.changeDisplay(realObject.getDisplayId(), di -> di.appHeight = height); } }public void setWidth(int width) { if (isJB()) { this.width = width; } else { ShadowDisplayManager.changeDisplay(realObject.getDisplayId(), di -> di.appWidth = width); } }public void setFlags(int flags) { reflector(_Display_.class, realObject).setFlags(flags); if (!isJB()) { ShadowDisplayManager.changeDisplay(realObject.getDisplayId(), di -> di.flags = flags); } }public void setName(String name) { if (isJB()) { this.name = name; } else { ShadowDisplayManager.changeDisplay(realObject.getDisplayId(), di -> di.name = name); } }public void setYdpi(float ydpi) { if (isJB()) { this.ydpi = ydpi; } else { ShadowDisplayManager.changeDisplay(realObject.getDisplayId(), di -> di.physicalYDpi = ydpi); } }public void setXdpi(float xdpi) { if (isJB()) { this.xdpi = xdpi; } else { ShadowDisplayManager.changeDisplay(realObject.getDisplayId(), di -> di.physicalXDpi = xdpi); } }public void setDensityDpi(int densityDpi) { if (isJB()) { this.densityDpi = densityDpi; } else { ShadowDisplayManager.changeDisplay(realObject.getDisplayId(), di -> di.logicalDensityDpi = densityDpi); } }public static Display getDefaultDisplay() { WindowManager windowManager = (WindowManager) RuntimeEnvironment.application.getSystemService(Context.WINDOW_SERVICE); return windowManager.getDefaultDisplay(); }public void invokeErrorListener(int what, int extra) { // Calling doStop() un-schedules the next event and // stops normal event flow from continuing. doStop(); state = ERROR; boolean handled = errorListener != null && errorListener.onError(player, what, extra); if (!handled) { // The documentation isn't very clear if onCompletion is // supposed to be called from non-playing states // (ie, states other than STARTED or PAUSED). Testing // revealed that onCompletion is invoked even if playback // hasn't started or is not in progress. invokeCompletionListener(); // Need to set this again because // invokeCompletionListener() will set the state // to PLAYBACK_COMPLETED state = ERROR; } }public void invokeInfoListener(int what, int extra) { if (infoListener != null) { infoListener.onInfo(player, what, extra); } }public void invokeSeekCompleteListener() { int duration = getMediaInfo().duration; setCurrentPosition(pendingSeek > duration ? duration : pendingSeek < 0 ? 0 : pendingSeek); pendingSeek = -1; if (state == STARTED) { doStart(); } if (seekCompleteListener == null) { return; } seekCompleteListener.onSeekComplete(player); }public int[] createWidgets(Class appWidgetProviderClass, int widgetLayoutId, int howManyToCreate) { AppWidgetProvider appWidgetProvider = ReflectionHelpers.callConstructor(appWidgetProviderClass); int[] newWidgetIds = new int[howManyToCreate]; for (int i = 0; i < howManyToCreate; i++) { View widgetView = createWidgetView(widgetLayoutId); int myWidgetId = nextWidgetId++; widgetInfos.put(myWidgetId, new WidgetInfo(widgetView, widgetLayoutId, appWidgetProvider)); newWidgetIds[i] = myWidgetId; } appWidgetProvider.onUpdate(context, realAppWidgetManager, newWidgetIds); return newWidgetIds; }public void reconstructWidgetViewAsIfPhoneWasRotated(int appWidgetId) { WidgetInfo widgetInfo = widgetInfos.get(appWidgetId); widgetInfo.view = createWidgetView(widgetInfo.layoutId); widgetInfo.lastRemoteViews.reapply(context, widgetInfo.view); }@Implementation protected int load(String path, int priority) { int soundId = soundIds.getAndIncrement(); idToPaths.put(soundId, path); return soundId; }@Implementation(maxSdk = LOLLIPOP_MR1) protected int play( int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) { playedSounds.add(new Playback(soundID, leftVolume, rightVolume, priority, loop, rate)); return 1; }public void setDefaultNetworkActive(boolean isActive) { defaultNetworkActive = isActive; if (defaultNetworkActive) { for (ConnectivityManager.OnNetworkActiveListener l : onNetworkActiveListeners) { if (l != null) { l.onNetworkActive(); } } } }public void callAttach(Context context) { ReflectionHelpers.callInstanceMethod(Application.class, realApplication, "attach", ReflectionHelpers.ClassParameter.from(Context.class, context)); }public synchronized T getNativeObject(long nativeId) { T object = nativeObjToIdMap.get(nativeId); if (object != null) { return object; } else { throw new NullPointerException( String.format( "Could not find object with nativeId: %d. Currently registered ids: %s", nativeId, nativeObjToIdMap.keySet())); } }@Deprecated public synchronized long getNativeObjectId(T o) { checkNotNull(o); Long nativeId = nativeObjToIdMap.inverse().get(o); if (nativeId == null) { nativeId = nextId; if (debug) { System.out.printf("NativeObjRegistry %s: register %d -> %s%n", name, nativeId, o); } nativeObjToIdMap.put(nativeId, o); nextId++; } return nativeId; }public static byte[] readBytes(InputStream is) throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(is.available())) { copy(is, bos); return bos.toByteArray(); } }private void writeItem(FakeEncodedItem item) { int endPosition = dataPosition + item.sizeBytes; if (endPosition > data.length) { // Parcel grows by 3/2 of the new size. setDataCapacityAtLeast(endPosition * 3 / 2); } if (endPosition > dataSize) { failNextReadIfPastEnd = true; dataSize = endPosition; } Arrays.fill(data, dataPosition, endPosition, item); dataPosition = endPosition; }private T readPrimitive(int defaultSizeBytes, T defaultValue, Class clazz) { // Check for zeroes first, since partially-overwritten values are not an error for zeroes. if (readZeroes(defaultSizeBytes)) { return defaultValue; } return readValue(defaultValue, clazz, /* allowNull= */ false); }private boolean readZeroes(int bytes) { int endPosition = dataPosition + bytes; if (endPosition > dataSize) { return false; } for (int i = dataPosition; i < endPosition; i++) { if (data[i] == null || !data[i].isEncodedAsAllZeroBytes) { return false; } } // Note in this case we short-circuit other verification -- even if we are reading weirdly // clobbered zeroes, they're still zeroes. Future reads might fail, though. dataPosition = endPosition; return true; }private T readValue(T pastEndValue, Class clazz, boolean allowNull) { if (dataPosition >= dataSize) { // Normally, reading past the end is permitted, and returns the default values. However, // writing to a parcel then reading without setting the position back to 0 is an incredibly // common error to make in tests, and should never really happen in production code, so // this shadow will fail in this condition. if (failNextReadIfPastEnd) { throw new UnreliableBehaviorError( "Did you forget to setDataPosition(0) before reading the parcel?"); } return pastEndValue; } int startPosition = dataPosition; FakeEncodedItem item = readNextItem(clazz); if (item == null) { return pastEndValue; } else if (item.value == null && allowNull) { return null; } else if (clazz.isInstance(item.value)) { return clazz.cast(item.value); } else { // Numerous existing tests rely on ShadowParcel throwing RuntimeException and catching // them. Many of these tests are trying to test what happens when an invalid Parcel is // provided. However, Android has no concept of an "invalid parcel" because Parcel will // happily return garbage if you ask for it. The only runtime exceptions are thrown on // array length mismatches, or higher-level APIs like Parcelable (which has its own safety // checks). Tests trying to test error-handling behavior should instead craft a Parcel // that specifically triggers a BadParcelableException. throw new RuntimeException( new UnreliableBehaviorError( clazz, startPosition, item, "and it is non-portable to reinterpret it")); } }private FakeEncodedItem readNextItem(Class clazz) { FakeEncodedItem item = data[dataPosition]; if (item == null) { // While Parcel will treat these as zeros, in tests, this is almost always an error. throw new UnreliableBehaviorError("Reading uninitialized data at position " + dataPosition); } checkConsistentReadAndIncrementPosition(clazz, item); return item; }private Object peek() { return dataPosition < dataSize && data[dataPosition] != null ? data[dataPosition].value : null; }private void checkConsistentReadAndIncrementPosition(Class clazz, FakeEncodedItem item) { int endPosition = dataPosition + item.sizeBytes; for (int i = dataPosition; i < endPosition; i++) { FakeEncodedItem foundItemItem = i < dataSize ? data[i] : null; if (foundItemItem != item) { throw new UnreliableBehaviorError( clazz, dataPosition, item, String.format( Locale.US, "but [%s] interrupts it at position %d", foundItemItem == null ? "uninitialized data or the end of the buffer" : foundItemItem.value, i)); } } dataPosition = Math.min(dataSize, dataPosition + item.sizeBytes); }public void setDataPosition(int pos) { if (pos > dataSize) { // NOTE: Real parcel ignores this until a write occurs. throw new UnreliableBehaviorError(pos + " greater than dataSize " + dataSize); } dataPosition = pos; failNextReadIfPastEnd = false; }public byte[] toByteArray() { int oldDataPosition = dataPosition; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); // NOTE: Serializing the data array would be simpler, and serialization would actually // preserve reference equality between entries. However, the length-encoded format here // preserves the previous format, which some tests appear to rely on. List entries = new ArrayList<>(); // NOTE: Use readNextItem to scan so the contents can be proactively validated. dataPosition = 0; while (dataPosition < dataSize) { entries.add(readNextItem(Object.class)); } oos.writeInt(entries.size()); for (FakeEncodedItem item : entries) { oos.writeInt(item.sizeBytes); oos.writeObject(item.value); } oos.flush(); return bos.toByteArray(); } catch (IOException e) { throw new UnreliableBehaviorError("ErrorProne unable to serialize its custom format", e); } finally { dataPosition = oldDataPosition; } }@Implementation(minSdk = LOLLIPOP) protected static void nativeWriteBlob(long nativePtr, byte[] b, int offset, int len) { nativeWriteByteArray(nativePtr, b, offset, len); }@Implementation(minSdk = M) protected void writeBlob(byte[] b, int offset, int len) { if (b == null) { realObject.writeInt(-1); return; } throwsIfOutOfBounds(b.length, offset, len); long nativePtr = ReflectionHelpers.getField(realObject, "mNativePtr"); nativeWriteBlob(nativePtr, b, offset, len); }@Implementation(maxSdk = JELLY_BEAN_MR1) @SuppressWarnings("TypeParameterUnusedInFormals") protected T readParcelable(ClassLoader loader) { // prior to JB MR2, readParcelableCreator() is inlined here. Parcelable.Creator creator = readParcelableCreator(loader); if (creator == null) { return null; } if (creator instanceof Parcelable.ClassLoaderCreator) { Parcelable.ClassLoaderCreator classLoaderCreator = (Parcelable.ClassLoaderCreator) creator; return (T) classLoaderCreator.createFromParcel(realObject, loader); } return (T) creator.createFromParcel(realObject); }private void executeOnLooper(ControlRunnable runnable) { if (Thread.currentThread() == realLooper.getThread()) { runnable.run(); } else { if (realLooper.equals(Looper.getMainLooper())) { throw new UnsupportedOperationException( "main looper can only be controlled from main thread"); } looperExecutor.execute(runnable); runnable.waitTillComplete(); } }@Override public void runPaused(Runnable runnable) { if (isPaused && Thread.currentThread() == realLooper.getThread()) { // just run runnable.run(); } else { throw new UnsupportedOperationException(); } }public void addAvailableRestoreSets(long restoreToken, List packages) { serviceState.restoreData.put(restoreToken, packages); }public Asset OpenNonAsset(final String filename, Asset.AccessMode mode, Ref out_cookie) { ATRACE_CALL(); for (int i = apk_assets_.size() - 1; i >= 0; i--) { Asset asset = apk_assets_.get(i).Open(filename, mode); if (isTruthy(asset)) { if (out_cookie != null) { out_cookie.set(ApkAssetsCookie.forInt(i)); } return asset; } } if (out_cookie != null) { out_cookie.set(K_INVALID_COOKIE); } return null; }public Set GetResourceLocales(boolean exclude_system, boolean merge_equivalent_languages) { ATRACE_CALL(); Set locales = new HashSet<>(); for (final PackageGroup package_group : package_groups_) { for (final ConfiguredPackage package_ : package_group.packages_) { if (exclude_system && package_.loaded_package_.IsSystem()) { continue; } package_.loaded_package_.CollectLocales(merge_equivalent_languages, locales); } } return locales; }public Set GetResourceConfigurations(boolean exclude_system, boolean exclude_mipmap) { // ATRACE_NAME("AssetManager::GetResourceConfigurations"); Set configurations = new HashSet<>(); for (final PackageGroup package_group : package_groups_) { for (final ConfiguredPackage package_ : package_group.packages_) { if (exclude_system && package_.loaded_package_.IsSystem()) { continue; } package_.loaded_package_.CollectConfigurations(exclude_mipmap, configurations); } } return configurations; }public boolean activateResetToken(ComponentName admin) { if (!passwordResetTokens.containsKey(admin)) { throw new IllegalArgumentException("No token set for comopnent: " + admin); } return componentsWithActivatedTokens.add(admin); }@Implementation(minSdk = LOLLIPOP) protected boolean setPermittedInputMethods(ComponentName admin, List packageNames) { enforceDeviceOwnerOrProfileOwner(admin); permittedInputMethods = packageNames; return true; }@Implementation(minSdk = LOLLIPOP) protected boolean setPermittedAccessibilityServices( ComponentName admin, List packageNames) { enforceDeviceOwnerOrProfileOwner(admin); permittedAccessibilityServices = packageNames; return true; }@Implementation(minSdk = N) @Nullable protected CharSequence getOrganizationName(ComponentName admin) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { enforceDeviceOwnerOrProfileOwner(admin); } else { enforceProfileOwner(admin); } return organizationName; }private static List findLibraries(Path resDirectory) throws IOException { List libraryBaseDirs = new ArrayList<>(); if (resDirectory != null) { Path baseDir = resDirectory.getParent(); final Properties properties = getProperties(baseDir.resolve("project.properties")); Properties overrideProperties = getProperties(baseDir.resolve("test-project.properties")); properties.putAll(overrideProperties); int libRef = 1; String lib; while ((lib = properties.getProperty("android.library.reference." + libRef)) != null) { Path libraryDir = baseDir.resolve(lib); if (Files.isDirectory(libraryDir)) { // Ignore directories without any files Path[] libraryBaseDirFiles = Fs.listFiles(libraryDir); if (libraryBaseDirFiles != null && libraryBaseDirFiles.length > 0) { List libraries = findLibraries(libraryDir.resolve(Config.DEFAULT_RES_FOLDER)); libraryBaseDirs.add( new ManifestIdentifier( null, libraryDir.resolve(Config.DEFAULT_MANIFEST_NAME), libraryDir.resolve(Config.DEFAULT_RES_FOLDER), libraryDir.resolve(Config.DEFAULT_ASSET_FOLDER), libraries)); } } libRef++; } } return libraryBaseDirs; }static boolean VerifyResTableType(ResTable_type header) { if (header.id == 0) { logError("RES_TABLE_TYPE_TYPE has invalid ID 0."); return false; } int entry_count = dtohl(header.entryCount); // if (entry_count > std.numeric_limits.max()) { if (entry_count > 0xffff) { logError("RES_TABLE_TYPE_TYPE has too many entries (" + entry_count + ")."); return false; } // Make sure that there is enough room for the entry offsets. int offsets_offset = dtohs(header.header.headerSize); int entries_offset = dtohl(header.entriesStart); int offsets_length = 4 * entry_count; if (offsets_offset > entries_offset || entries_offset - offsets_offset < offsets_length) { logError("RES_TABLE_TYPE_TYPE entry offsets overlap actual entry data."); return false; } if (entries_offset > dtohl(header.header.size)) { logError("RES_TABLE_TYPE_TYPE entry offsets extend beyond chunk."); return false; } if (isTruthy(entries_offset & 0x03)) { logError("RES_TABLE_TYPE_TYPE entries start at unaligned address."); return false; } return true; }@Override public Intent getIntentForActivity(Class activityClass) { PackageManager packageManager = getTargetContext().getPackageManager(); ComponentName componentName = new ComponentName(getTargetContext(), activityClass); Intent intent = Intent.makeMainActivity(componentName); if (packageManager.resolveActivity(intent, 0) != null) { return intent; } return Intent.makeMainActivity(new ComponentName(getContext(), activityClass)); }public static Package callParsePackage(Path apkFile) { PackageParser packageParser = new PackageParser(); int flags = PackageParser.PARSE_IGNORE_PROCESSES; try { Package thePackage; if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.LOLLIPOP) { // TODO(christianw/brettchabot): workaround for NPE from probable bug in Q. // Can be removed when upstream properly handles a null callback // PackageParser#setMinAspectRatio(Package) if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.Q) { QHelper.setCallback(packageParser); } thePackage = packageParser.parsePackage(apkFile.toFile(), flags); } else { // JB -> KK thePackage = reflector(_PackageParser_.class, packageParser) .parsePackage( apkFile.toFile(), Fs.externalize(apkFile), new DisplayMetrics(), flags); } if (thePackage == null) { List logItems = ShadowLog.getLogsForTag("PackageParser"); if (logItems.isEmpty()) { throw new RuntimeException( "Failed to parse package " + apkFile); } else { LogItem logItem = logItems.get(0); throw new RuntimeException( "Failed to parse package " + apkFile + ": " + logItem.msg, logItem.throwable); } } return thePackage; } catch (Exception e) { throw new RuntimeException(e); } }static int findAncestors(int[] out, Ref stop_list_index, int packed_locale, final String script, final int[] stop_list, int stop_set_length) { int ancestor = packed_locale; int count = 0; do { if (out != null) { out[count] = ancestor; } count++; for (int i = 0; i < stop_set_length; i++) { if (stop_list[i] == ancestor) { stop_list_index.set((long) i); return count; } } ancestor = findParent(ancestor, script); } while (ancestor != PACKED_ROOT); stop_list_index.set((long) -1); return count; }private static int findParent(int packed_locale, final String script) { if (hasRegion(packed_locale)) { for (Map.Entry> entry : SCRIPT_PARENTS.entrySet()) { if (script.equals(entry.getKey())) { Map map = entry.getValue(); Integer lookup_result = map.get(packed_locale); if (lookup_result != null) { return lookup_result; } break; } } return dropRegion(packed_locale); } return PACKED_ROOT; }public void addIntentFilterForProvider(ComponentName componentName, IntentFilter filter) throws NameNotFoundException { addIntentFilterForComponent(componentName, filter, providerFilters); }public void addIntentFilterForReceiver(ComponentName componentName, IntentFilter filter) throws NameNotFoundException { addIntentFilterForComponent(componentName, filter, receiverFilters); }public void addIntentFilterForService(ComponentName componentName, IntentFilter filter) throws NameNotFoundException { addIntentFilterForComponent(componentName, filter, serviceFilters); }public void addIntentFilterForActivity(ComponentName componentName, IntentFilter filter) throws NameNotFoundException { addIntentFilterForComponent(componentName, filter, activityFilters); }public void addPackageInternal(Package appPackage) { int flags = GET_ACTIVITIES | GET_RECEIVERS | GET_SERVICES | GET_PROVIDERS | GET_INSTRUMENTATION | GET_INTENT_FILTERS | GET_SIGNATURES | GET_RESOLVED_FILTER | GET_META_DATA | GET_GIDS | MATCH_DISABLED_COMPONENTS | GET_SHARED_LIBRARY_FILES | GET_URI_PERMISSION_PATTERNS | GET_PERMISSIONS | MATCH_UNINSTALLED_PACKAGES | GET_CONFIGURATIONS | MATCH_DISABLED_UNTIL_USED_COMPONENTS | MATCH_DIRECT_BOOT_UNAWARE | MATCH_DIRECT_BOOT_AWARE; for (PermissionGroup permissionGroup : appPackage.permissionGroups) { PermissionGroupInfo permissionGroupInfo = PackageParser.generatePermissionGroupInfo(permissionGroup, flags); addPermissionGroupInfo(permissionGroupInfo); } PackageInfo packageInfo = reflector(_PackageParser_.class) .generatePackageInfo(appPackage, new int[] {0}, flags, 0, 0); packageInfo.applicationInfo.uid = Process.myUid(); packageInfo.applicationInfo.dataDir = createTempDir(packageInfo.packageName + "-dataDir"); installPackage(packageInfo); addFilters(activityFilters, appPackage.activities); addFilters(serviceFilters, appPackage.services); addFilters(providerFilters, appPackage.providers); addFilters(receiverFilters, appPackage.receivers); }@Deprecated public void addResolveInfoForIntent(Intent intent, ResolveInfo info) { info.isDefault = true; ComponentInfo[] componentInfos = new ComponentInfo[] { info.activityInfo, info.serviceInfo, Build.VERSION.SDK_INT >= KITKAT ? info.providerInfo : null }; for (ComponentInfo component : componentInfos) { if (component != null && component.applicationInfo != null) { component.applicationInfo.flags |= ApplicationInfo.FLAG_INSTALLED; if (component.applicationInfo.processName == null) { component.applicationInfo.processName = component.applicationInfo.packageName; } } } if (info.match == 0) { info.match = Integer.MAX_VALUE; // make sure, that this is as good match as possible. } addResolveInfoForIntentNoDefaults(intent, info); }@Deprecated public void setResolveInfosForIntent(Intent intent, List info) { resolveInfoForIntent.remove(intent); for (ResolveInfo resolveInfo : info) { addResolveInfoForIntent(intent, resolveInfo); } }@Nullable public ActivityInfo removeReceiver(ComponentName componentName) { return removeComponent( componentName, receiverFilters, p -> p.receivers, (p, a) -> p.receivers = a); }@Nullable public ProviderInfo removeProvider(ComponentName componentName) { return removeComponent( componentName, providerFilters, p -> p.providers, (p, a) -> p.providers = a); }@Nullable public ServiceInfo removeService(ComponentName componentName) { return removeComponent( componentName, serviceFilters, p -> p.services, (p, a) -> p.services = a); }@Nullable public ActivityInfo removeActivity(ComponentName componentName) { return removeComponent( componentName, activityFilters, p -> p.activities, (p, a) -> p.activities = a); }public void addOrUpdateProvider(ProviderInfo providerInfo) { addComponent( providerFilters, p -> p.providers, (p, a) -> p.providers = a, new ProviderInfo(providerInfo), true); }public void addOrUpdateReceiver(ActivityInfo receiverInfo) { addComponent( receiverFilters, p -> p.receivers, (p, a) -> p.receivers = a, new ActivityInfo(receiverInfo), true); }public void addOrUpdateService(ServiceInfo serviceInfo) { addComponent( serviceFilters, p -> p.services, (p, a) -> p.services = a, new ServiceInfo(serviceInfo), true); }public void addOrUpdateActivity(ActivityInfo activityInfo) { addComponent( activityFilters, p -> p.activities, (p, a) -> p.activities = a, new ActivityInfo(activityInfo), true); }public ProviderInfo addProviderIfNotPresent(ComponentName componentName) { return addComponent( providerFilters, p -> p.providers, (p, a) -> p.providers = a, updateName(componentName, new ProviderInfo()), false); }public ActivityInfo addReceiverIfNotPresent(ComponentName componentName) { return addComponent( receiverFilters, p -> p.receivers, (p, a) -> p.receivers = a, updateName(componentName, new ActivityInfo()), false); }public ServiceInfo addServiceIfNotPresent(ComponentName componentName) { return addComponent( serviceFilters, p -> p.services, (p, a) -> p.services = a, updateName(componentName, new ServiceInfo()), false); }public ActivityInfo addActivityIfNotPresent(ComponentName componentName) { return addComponent( activityFilters, p -> p.activities, (p, a) -> p.activities = a, updateName(componentName, new ActivityInfo()), false); }@Override @Deprecated public boolean postAtFrontOfQueue(Runnable runnable) { if (!quit) { getScheduler().postAtFrontOfQueue(runnable); return true; } else { return false; } }@Override @Deprecated public boolean post(Runnable runnable, long delayMillis) { if (!quit) { getScheduler().postDelayed(runnable, delayMillis, TimeUnit.MILLISECONDS); return true; } else { return false; } }@Implementation @HiddenApi protected final int loadResourceBagValue(int ident, int bagEntryId, TypedValue outValue, boolean resolve) { CppAssetManager am = assetManagerForJavaObject(); if (am == null) { return 0; } final ResTable res = am.getResources(); return loadResourceBagValueInternal(ident, bagEntryId, outValue, resolve, res); }@Implementation @Nullable @SuppressWarnings("unchecked") protected T get(Key key) { return (T) resultsKeyToValue.get(key); }@Implementation protected final void transform(Matrix matrix) { checkNotNull(matrix); NativeInput.MotionEvent event = getNativeMotionEvent(); ShadowMatrix shadowMatrix = Shadow.extract(matrix); float[] m = new float[9]; shadowMatrix.getValues(m); event.transform(m); }private static int getJavaVersion() { String version = System.getProperty("java.version"); assert version != null; if (version.startsWith("1.")) { version = version.substring(2); } // Allow these formats: // 1.8.0_72-ea // 9-ea // 9 // 9.0.1 int dotPos = version.indexOf('.'); int dashPos = version.indexOf('-'); return Integer.parseInt( version.substring(0, dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : 1)); }@Implementation(minSdk = Build.VERSION_CODES.O) protected void deleteNotificationChannelGroup(String channelGroupId) { if (getNotificationChannelGroup(channelGroupId) != null) { // Deleting a channel group also deleted all associated channels. See // https://developer.android.com/reference/android/app/NotificationManager.html#deleteNotificationChannelGroup%28java.lang.String%29 // for more info. for (/* NotificationChannel */ Object channel : getNotificationChannels()) { String groupId = ReflectionHelpers.callInstanceMethod(channel, "getGroup"); if (channelGroupId.equals(groupId)) { String channelId = ReflectionHelpers.callInstanceMethod(channel, "getId"); deleteNotificationChannel(channelId); } } notificationChannelGroups.remove(channelGroupId); } }public @Nullable BroadcastReceiverData getBroadcastReceiver(String className) { parseAndroidManifest(); for (BroadcastReceiverData receiver : receivers) { if (receiver.getName().equals(className)) { return receiver; } } return null; }public List getAllManifests() { Set seenManifests = new HashSet<>(); List uniqueManifests = new ArrayList<>(); addTransitiveManifests(seenManifests, uniqueManifests); return uniqueManifests; }public static List getLogsForTag(String tag) { Queue logs = logsByTag.get(tag); return logs == null ? Collections.emptyList() : new ArrayList<>(logs); }private static FileSystem getJarFs(Path jarFile) throws IOException { Path key = jarFile.toAbsolutePath(); synchronized (ZIP_FILESYSTEMS) { FsWrapper fs = ZIP_FILESYSTEMS.get(key); if (fs == null) { fs = new FsWrapper(FileSystems.newFileSystem(key, null), key); fs.incrRefCount(); ZIP_FILESYSTEMS.put(key, fs); } else { fs.incrRefCount(); } return fs; } }@Implementation(minSdk = O_MR1) public Point getStableDisplaySize() throws RemoteException { DisplayInfo defaultDisplayInfo = mDm.getDisplayInfo(Display.DEFAULT_DISPLAY); return new Point(defaultDisplayInfo.getNaturalWidth(), defaultDisplayInfo.getNaturalHeight()); }@Implementation protected int speak( final String text, final int queueMode, final HashMap params) { if (RuntimeEnvironment.getApiLevel() >= LOLLIPOP) { return Shadow.directlyOn(tts, TextToSpeech.class).speak(text, queueMode, params); } return speak( text, queueMode, null, params == null ? null : params.get(Engine.KEY_PARAM_UTTERANCE_ID)); }@Deprecated public static FragmentController buildFragment(Class fragmentClass) { return FragmentController.of(ReflectionHelpers.callConstructor(fragmentClass)); }@Deprecated public static T setupActivity(Class activityClass) { return buildActivity(activityClass).setup().get(); }public static ActivityController buildActivity( Class activityClass, Intent intent) { return ActivityController.of(ReflectionHelpers.callConstructor(activityClass), intent); }public static ActivityController buildActivity(Class activityClass) { return buildActivity(activityClass, null); }@Override public void reset() { ReflectorMessageQueue msgQueue = reflector(ReflectorMessageQueue.class, realQueue); msgQueue.setMessages(null); msgQueue.setIdleHandlers(new ArrayList<>()); msgQueue.setNextBarrierToken(0); }@Implementation(minSdk = 23) public boolean isIdle() { if (Build.VERSION.SDK_INT >= M) { return directlyOn(realQueue, MessageQueue.class).isIdle(); } else { ReflectorMessageQueue internalQueue = reflector(ReflectorMessageQueue.class, realQueue); // this is a copy of the implementation from P synchronized (realQueue) { final long now = SystemClock.uptimeMillis(); Message headMsg = internalQueue.getMessages(); if (headMsg == null) { return true; } long when = shadowOfMsg(headMsg).getWhen(); return now < when; } } }@Implementation protected static boolean setCurrentTimeMillis(long millis) { if (currentTimeMillis > millis) { return false; } currentTimeMillis = millis; for (Listener listener : listeners) { listener.clockUpdated(currentTimeMillis); } return true; }@Implementation(minSdk = LOLLIPOP) protected boolean bindServiceAsUser( Intent intent, final ServiceConnection serviceConnection, int i, UserHandle userHandle) { return getShadowInstrumentation().bindService(intent, serviceConnection, i); }public synchronized boolean runOneTask() { ScheduledRunnable postedRunnable = runnables.poll(); if (postedRunnable != null) { if (postedRunnable.scheduledTime > currentTime) { currentTime = postedRunnable.scheduledTime; } postedRunnable.run(); return true; } return false; }public synchronized boolean advanceTo(long endTime) { if (endTime < currentTime || runnables.isEmpty()) { currentTime = endTime; return false; } int runCount = 0; while (nextTaskIsScheduledBefore(endTime)) { runOneTask(); ++runCount; } currentTime = endTime; return runCount > 0; }public synchronized boolean advanceBy(long amount, TimeUnit unit) { long endingTime = currentTime + unit.toMillis(amount); return advanceTo(endingTime); }public synchronized boolean advanceToLastPostedRunnable() { long currentMaxTime = currentTime; for (ScheduledRunnable scheduled : runnables) { if (currentMaxTime < scheduled.scheduledTime) { currentMaxTime = scheduled.scheduledTime; } } return advanceTo(currentMaxTime); }public synchronized void remove(Runnable runnable) { Iterator iterator = runnables.iterator(); while (iterator.hasNext()) { if (iterator.next().runnable == runnable) { iterator.remove(); } } }public synchronized void postAtFrontOfQueue(Runnable runnable) { if (isPaused() || Thread.currentThread() != associatedThread) { final long timeDisambiguator; if (runnables.isEmpty()) { timeDisambiguator = nextTimeDisambiguator++; } else { timeDisambiguator = runnables.peek().timeDisambiguator - 1; } runnables.add(new ScheduledRunnable(runnable, 0, timeDisambiguator)); } else { runOrQueueRunnable(runnable, currentTime); } }public synchronized void postDelayed(Runnable runnable, long delay, TimeUnit unit) { long delayMillis = unit.toMillis(delay); if ((idleState != CONSTANT_IDLE && (isPaused() || delayMillis > 0)) || Thread.currentThread() != associatedThread) { runnables.add(new ScheduledRunnable(runnable, currentTime + delayMillis)); } else { runOrQueueRunnable(runnable, currentTime + delayMillis); } }@Implementation(minSdk = LOLLIPOP) protected void stopLockTask() { Shadow.extract(getActivityManager()) .setLockTaskModeState(ActivityManager.LOCK_TASK_MODE_NONE); }@Implementation(minSdk = LOLLIPOP) protected void startLockTask() { Shadow.extract(getActivityManager()) .setLockTaskModeState(ActivityManager.LOCK_TASK_MODE_LOCKED); }public void callOnActivityResult(int requestCode, int resultCode, Intent resultData) { final ActivityInvoker invoker = new ActivityInvoker(); invoker .call("onActivityResult", Integer.TYPE, Integer.TYPE, Intent.class) .with(requestCode, resultCode, resultData); }public boolean clickMenuItem(int menuItemResId) { final RoboMenuItem item = new RoboMenuItem(menuItemResId); return realActivity.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item); }@Implementation protected static ImageDecoder nCreate(FileDescriptor fd, Source src) throws IOException { return ImageDecoder_nCreateFd(fd, src); }@Implementation protected static ImageDecoder nCreate(long asset, Source source) throws IOException { return ImageDecoder_nCreateAsset(asset, source); }public static boolean parseFloatAttribute(String attribute, String value, TypedValue outValue, boolean requireUnit) { assert requireUnit == false || attribute != null; // remove the space before and after value = value.trim(); int len = value.length(); if (len <= 0) { return false; } // check that there's no non ascii characters. char[] buf = value.toCharArray(); for (int i = 0 ; i < len ; i++) { if (buf[i] > 255) { return false; } } // check the first character if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.' && buf[0] != '-') { return false; } // now look for the string that is after the float... Matcher m = sFloatPattern.matcher(value); if (m.matches()) { String f_str = m.group(1); String end = m.group(2); float f; try { f = Float.parseFloat(f_str); } catch (NumberFormatException e) { // this shouldn't happen with the regexp above. return false; } if (end.length() > 0 && end.charAt(0) != ' ') { // Might be a unit... if (parseUnit(end, outValue, sFloatOut)) { computeTypedValue(outValue, f, sFloatOut[0]); return true; } return false; } // make sure it's only spaces at the end. end = end.trim(); if (end.length() == 0) { if (outValue != null) { outValue.assetCookie = 0; outValue.string = null; if (requireUnit == false) { outValue.type = TypedValue.TYPE_FLOAT; outValue.data = Float.floatToIntBits(f); } else { // no unit when required? Use dp and out an error. applyUnit(sUnitNames[1], outValue, sFloatOut); computeTypedValue(outValue, f, sFloatOut[0]); System.out.println(String.format( "Dimension \"%1$s\" in attribute \"%2$s\" is missing unit!", value, attribute)); } return true; } } } return false; }public static int getColorType(String value) { if (value != null && value.startsWith("#")) { switch (value.length()) { case 4: return TypedValue.TYPE_INT_COLOR_RGB4; case 5: return TypedValue.TYPE_INT_COLOR_ARGB4; case 7: return TypedValue.TYPE_INT_COLOR_RGB8; case 9: return TypedValue.TYPE_INT_COLOR_ARGB8; } } return TypedValue.TYPE_INT_COLOR_ARGB8; }public static int getColor(String value) { if (value != null) { if (value.startsWith("#") == false) { throw new NumberFormatException( String.format("Color value '%s' must start with #", value)); } value = value.substring(1); // make sure it's not longer than 32bit if (value.length() > 8) { throw new NumberFormatException(String.format( "Color value '%s' is too long. Format is either" + "#AARRGGBB, #RRGGBB, #RGB, or #ARGB", value)); } if (value.length() == 3) { // RGB format char[] color = new char[8]; color[0] = color[1] = 'F'; color[2] = color[3] = value.charAt(0); color[4] = color[5] = value.charAt(1); color[6] = color[7] = value.charAt(2); value = new String(color); } else if (value.length() == 4) { // ARGB format char[] color = new char[8]; color[0] = color[1] = value.charAt(0); color[2] = color[3] = value.charAt(1); color[4] = color[5] = value.charAt(2); color[6] = color[7] = value.charAt(3); value = new String(color); } else if (value.length() == 6) { value = "FF" + value; } // this is a RRGGBB or AARRGGBB value // Integer.parseInt will fail to inferFromValue strings like "ff191919", so we use // a Long, but cast the result back into an int, since we know that we're only // dealing with 32 bit values. return (int)Long.parseLong(value, 16); } throw new NumberFormatException(); }@Implementation(minSdk = P) @HiddenApi @SystemApi @RequiresPermission(android.Manifest.permission.MANAGE_APP_OPS_MODES) public void setMode(String op, int uid, String packageName, int mode) { setMode(AppOpsManager.strOpToOp(op), uid, packageName, mode); }int getIndexOfBit(int n) { // return __builtin_popcountll(value & ~(0xffffffffffffffffULL >> n)); int numMarkedBits = 0; for (int i = 0; i < n; i++) { if (hasBit(i)) { numMarkedBits++; } } return numMarkedBits; }@Implementation protected static final int getThreadPriority(int tid) { if (tid == 0) { tid = ShadowProcess.myTid(); } synchronized (threadPrioritiesLock) { return threadPriorities.getOrDefault(tid, 0); } }@Implementation protected static final void setThreadPriority(int tid, int priority) { checkArgument( priority >= android.os.Process.THREAD_PRIORITY_URGENT_AUDIO && priority <= android.os.Process.THREAD_PRIORITY_LOWEST, "priority %s out of range. Use a Process.THREAD_PRIORITY_* constant.", priority); if (tid == 0) { tid = ShadowProcess.myTid(); } synchronized (threadPrioritiesLock) { threadPriorities.put(tid, priority); } }public void addBluetoothRoute() { updateBluetoothAudioRoute(BLUETOOTH_DEVICE_NAME); if (RuntimeEnvironment.getApiLevel() <= JELLY_BEAN_MR1) { ReflectionHelpers.callInstanceMethod( MediaRouter.class, realObject, "selectRouteInt", ClassParameter.from(int.class, MediaRouter.ROUTE_TYPE_LIVE_AUDIO), ClassParameter.from(RouteInfo.class, getBluetoothA2dpRoute())); } else { realObject.selectRoute(MediaRouter.ROUTE_TYPE_LIVE_AUDIO, getBluetoothA2dpRoute()); } }public void addHttpResponseRule(RequestMatcher requestMatcher, List responses) { addHttpResponseRule(new RequestMatcherResponseRule(requestMatcher, responses)); }@Implementation protected static void nativeStop(long nativeObject) { try { // Close the output stream. getStream(nativeObject).close(); // Clear the stream from both internal caches. fdToStream.remove(outputStreams.remove(nativeObject).getFD()); } catch (IOException e) { throw new RuntimeException("Unable to close temporary file.", e); } }public static void addHttpResponseRule(RequestMatcher requestMatcher, List responses) { getFakeHttpLayer().addHttpResponseRule(requestMatcher, responses); }public static void addHttpResponseRule(String method, String uri, HttpResponse response) { getFakeHttpLayer().addHttpResponseRule(method, uri, response); }public static HttpRequest getNextSentHttpRequest() { HttpRequestInfo httpRequestInfo = getFakeHttpLayer().getNextSentHttpRequestInfo(); return httpRequestInfo == null ? null : httpRequestInfo.getHttpRequest(); }private static Path getFileFromZip(Path path) { byte[] buffer = new byte[1024]; try { Path outputDir = new TempDirectory("robolectric_assets").create("fromzip"); try (InputStream zis = Fs.getInputStream(path)) { Path fileFromZip = outputDir.resolve(path.getFileName().toString()); try (OutputStream fos = Files.newOutputStream(fileFromZip)) { int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } } return fileFromZip; } } catch (IOException e) { throw new RuntimeException(e); } }@Override @Nonnull public List selectSdks(Configuration configuration, UsesSdk usesSdk) { Config config = configuration.get(Config.class); Set sdks = new TreeSet<>(configuredSdks(config, usesSdk)); if (enabledSdks != null) { sdks = Sets.intersection(sdks, enabledSdks); } return Lists.newArrayList(sdks); }public void denyPermissions(int pid, int uid, String... permissions) { getShadowInstrumentation().denyPermissions(pid, uid, permissions); }public void grantPermissions(int pid, int uid, String... permissions) { getShadowInstrumentation().grantPermissions(pid, uid, permissions); }int addMapping(final String packageName, byte packageId) { Byte index = mEntries.get(packageName); if (index == null) { return UNKNOWN_ERROR; } mLookupTable[index] = packageId; return NO_ERROR; }int addMappings(final DynamicRefTable other) { if (mAssignedPackageId != other.mAssignedPackageId) { return UNKNOWN_ERROR; } // final int entryCount = other.mEntries.size(); // for (size_t i = 0; i < entryCount; i++) { // ssize_t index = mEntries.indexOfKey(other.mEntries.keyAt(i)); // if (index < 0) { // mEntries.add(other.mEntries.keyAt(i), other.mEntries[i]); // } else { // if (other.mEntries[i] != mEntries[index]) { // return UNKNOWN_ERROR; // } // } // } for (Entry otherEntry : other.mEntries.entrySet()) { String key = otherEntry.getKey(); Byte curValue = mEntries.get(key); if (curValue == null) { mEntries.put(key, otherEntry.getValue()); } else { if (!Objects.equals(otherEntry.getValue(), curValue)) { return UNKNOWN_ERROR; } } } // Merge the lookup table. No entry can conflict // (value of 0 means not set). for (int i = 0; i < 256; i++) { if (mLookupTable[i] != other.mLookupTable[i]) { if (mLookupTable[i] == 0) { mLookupTable[i] = other.mLookupTable[i]; } else if (other.mLookupTable[i] != 0) { return UNKNOWN_ERROR; } } } return NO_ERROR; }private void interceptInvokeVirtualMethodWithInvokeDynamic( ListIterator instructions, MethodInsnNode targetMethod) { instructions.remove(); // remove the method invocation Type type = Type.getObjectType(targetMethod.owner); String description = targetMethod.desc; String owner = type.getClassName(); if (targetMethod.getOpcode() != Opcodes.INVOKESTATIC) { String thisType = type.getDescriptor(); description = "(" + thisType + description.substring(1); } instructions.add(new InvokeDynamicInsnNode(targetMethod.name, description, BOOTSTRAP_INTRINSIC, owner)); }@Implementation protected void connect() throws IOException { if (state == SocketState.CLOSED) { throw new IOException("socket closed"); } state = SocketState.CONNECTED; }public UserHandle addUser(int id, String name, int flags) { UserHandle userHandle = id == UserHandle.USER_SYSTEM ? Process.myUserHandle() : new UserHandle(id); addUserProfile(userHandle); setSerialNumberForUser(userHandle, (long) id); userInfoMap.put(id, new UserInfo(id, name, flags)); userPidMap.put( id, id == UserHandle.USER_SYSTEM ? Process.myUid() : id * UserHandle.PER_USER_RANGE + ShadowProcess.getRandomApplicationUid()); return userHandle; }public long addUserProfile(UserHandle userHandle) { long serialNumber = nextUserSerial++; userProfiles.put(userHandle, serialNumber); return serialNumber; }@Implementation(minSdk = JELLY_BEAN_MR2) protected Bundle getApplicationRestrictions(String packageName) { Bundle bundle = applicationRestrictions.get(packageName); return bundle != null ? bundle : new Bundle(); }public final boolean isDefault() { return mcc == 0 && mnc == 0 && isZeroes(language) && isZeroes(country) && orientation == 0 && touchscreen == 0 && density == 0 && keyboard == 0 && navigation == 0 && inputFlags == 0 && screenWidth == 0 && screenHeight == 0 && sdkVersion == 0 && minorVersion == 0 && screenLayout == 0 && uiMode == 0 && smallestScreenWidthDp == 0 && screenWidthDp == 0 && screenHeightDp == 0 && isZeroes(localeScript) && isZeroes(localeVariant) && screenLayout2 == 0 && colorMode == 0 ; }int diff(final ResTable_config o) { int diffs = 0; if (mcc != o.mcc) diffs |= CONFIG_MCC; if (mnc != o.mnc) diffs |= CONFIG_MNC; if (orientation != o.orientation) diffs |= CONFIG_ORIENTATION; if (density != o.density) diffs |= CONFIG_DENSITY; if (touchscreen != o.touchscreen) diffs |= CONFIG_TOUCHSCREEN; if (((inputFlags^o.inputFlags)&(MASK_KEYSHIDDEN|MASK_NAVHIDDEN)) != 0) diffs |= CONFIG_KEYBOARD_HIDDEN; if (keyboard != o.keyboard) diffs |= CONFIG_KEYBOARD; if (navigation != o.navigation) diffs |= CONFIG_NAVIGATION; if (screenSize() != o.screenSize()) diffs |= CONFIG_SCREEN_SIZE; if (version() != o.version()) diffs |= CONFIG_VERSION; if ((screenLayout & MASK_LAYOUTDIR) != (o.screenLayout & MASK_LAYOUTDIR)) diffs |= CONFIG_LAYOUTDIR; if ((screenLayout & ~MASK_LAYOUTDIR) != (o.screenLayout & ~MASK_LAYOUTDIR)) diffs |= CONFIG_SCREEN_LAYOUT; if ((screenLayout2 & MASK_SCREENROUND) != (o.screenLayout2 & MASK_SCREENROUND)) diffs |= CONFIG_SCREEN_ROUND; if ((colorMode & MASK_WIDE_COLOR_GAMUT) != (o.colorMode & MASK_WIDE_COLOR_GAMUT)) diffs |= CONFIG_COLOR_MODE; if ((colorMode & MASK_HDR) != (o.colorMode & MASK_HDR)) diffs |= CONFIG_COLOR_MODE; if (uiMode != o.uiMode) diffs |= CONFIG_UI_MODE; if (smallestScreenWidthDp != o.smallestScreenWidthDp) diffs |= CONFIG_SMALLEST_SCREEN_SIZE; if (screenSizeDp() != o.screenSizeDp()) diffs |= CONFIG_SCREEN_SIZE; int diff = compareLocales(this, o); if (isTruthy(diff)) diffs |= CONFIG_LOCALE; return diffs; }static ResTable_config createConfig(ByteBuffer buffer) { int startPosition = buffer.position(); // The starting buffer position to calculate bytes read. int size = buffer.getInt(); int mcc = buffer.getShort() & 0xFFFF; int mnc = buffer.getShort() & 0xFFFF; byte[] language = new byte[2]; buffer.get(language); byte[] region = new byte[2]; buffer.get(region); int orientation = UnsignedBytes.toInt(buffer.get()); int touchscreen = UnsignedBytes.toInt(buffer.get()); int density = buffer.getShort() & 0xFFFF; int keyboard = UnsignedBytes.toInt(buffer.get()); int navigation = UnsignedBytes.toInt(buffer.get()); int inputFlags = UnsignedBytes.toInt(buffer.get()); buffer.get(); // 1 byte of padding int screenWidth = buffer.getShort() & 0xFFFF; int screenHeight = buffer.getShort() & 0xFFFF; int sdkVersion = buffer.getShort() & 0xFFFF; int minorVersion = buffer.getShort() & 0xFFFF; // At this point, the configuration's size needs to be taken into account as not all // configurations have all values. int screenLayout = 0; int uiMode = 0; int smallestScreenWidthDp = 0; int screenWidthDp = 0; int screenHeightDp = 0; byte[] localeScript = new byte[4]; byte[] localeVariant = new byte[8]; byte screenLayout2 = 0; byte screenConfigPad1 = 0; short screenConfigPad2 = 0; if (size >= SCREEN_CONFIG_MIN_SIZE) { screenLayout = UnsignedBytes.toInt(buffer.get()); uiMode = UnsignedBytes.toInt(buffer.get()); smallestScreenWidthDp = buffer.getShort() & 0xFFFF; } if (size >= SCREEN_DP_MIN_SIZE) { screenWidthDp = buffer.getShort() & 0xFFFF; screenHeightDp = buffer.getShort() & 0xFFFF; } if (size >= LOCALE_MIN_SIZE) { buffer.get(localeScript); buffer.get(localeVariant); } if (size >= SCREEN_CONFIG_EXTENSION_MIN_SIZE) { screenLayout2 = (byte) UnsignedBytes.toInt(buffer.get()); screenConfigPad1 = buffer.get(); // Reserved padding screenConfigPad2 = buffer.getShort(); // More reserved padding } // After parsing everything that's known, account for anything that's unknown. int bytesRead = buffer.position() - startPosition; byte[] unknown = new byte[size - bytesRead]; buffer.get(unknown); return new ResTable_config(size, mcc, mnc, language, region, orientation, touchscreen, density, keyboard, navigation, inputFlags, screenWidth, screenHeight, sdkVersion, minorVersion, screenLayout, uiMode, smallestScreenWidthDp, screenWidthDp, screenHeightDp, localeScript, localeVariant, screenLayout2, screenConfigPad1, screenConfigPad2, unknown); }private void getPointAtLength( int type, float[] coords, float lastX, float lastY, float t, float[] point) { if (type == PathIterator.SEG_LINETO) { point[0] = lastX + (coords[0] - lastX) * t; point[1] = lastY + (coords[1] - lastY) * t; // Return here, since we do not need a shape to estimate return; } float[] curve = new float[8]; int lastPointIndex = (getNumberOfPoints(type) - 1) * 2; System.arraycopy(coords, 0, curve, 2, coords.length); curve[0] = lastX; curve[1] = lastY; if (type == PathIterator.SEG_CUBICTO) { cubicCurveSegment(curve, 0f, t); } else { quadCurveSegment(curve, 0f, t); } point[0] = curve[2 + lastPointIndex]; point[1] = curve[2 + lastPointIndex + 1]; }private static void getShapeEndPoint(int type, float[] coords, float[] point) { // start index of the end point for the segment type int pointIndex = (getNumberOfPoints(type) - 1) * 2; point[0] = coords[pointIndex]; point[1] = coords[pointIndex + 1]; }public boolean isExported() { boolean defaultValue = !intentFilters.isEmpty(); return (attributes.containsKey(EXPORTED) ? Boolean.parseBoolean(attributes.get(EXPORTED)) : defaultValue); }public void expectLogMessage(int level, String tag, String message) { checkTag(tag); expectedLogs.add(new LogItem(level, tag, message, null)); }public void setCallState(int callState, String incomingPhoneNumber) { if (callState != CALL_STATE_RINGING) { incomingPhoneNumber = null; } this.callState = callState; this.incomingPhoneNumber = incomingPhoneNumber; for (PhoneStateListener listener : getListenersForFlags(LISTEN_CALL_STATE)) { listener.onCallStateChanged(callState, incomingPhoneNumber); } }@SuppressWarnings("unchecked") public ActivityController recreate() { Stage originalStage = ActivityLifecycleMonitorRegistry.getInstance().getLifecycleStageOf(component); switch (originalStage) { case PRE_ON_CREATE: create(); // fall through case CREATED: case RESTARTED: start(); postCreate(null); // fall through case STARTED: resume(); // fall through case RESUMED: pause(); // fall through case PAUSED: stop(); // fall through case STOPPED: break; default: throw new IllegalStateException("Cannot recreate activity since it's destroyed already"); } // Activity#mChangingConfigurations flag should be set prior to Activity recreation process // starts. ActivityThread does set it on real device but here we simulate the Activity // recreation process on behalf of ActivityThread so set the flag here. Note we don't need to // reset the flag to false because this Activity instance is going to be destroyed and disposed. // https://android.googlesource.com/platform/frameworks/base/+/55418eada51d4f5e6532ae9517af66c50 // ea495c4/core/java/android/app/ActivityThread.java#4806 ReflectionHelpers.setField(component, "mChangingConfigurations", true); Bundle outState = new Bundle(); saveInstanceState(outState); Object lastNonConfigurationInstances = ReflectionHelpers.callInstanceMethod(component, "retainNonConfigurationInstances"); destroy(); component = (T) ReflectionHelpers.callConstructor(component.getClass()); _component_ = reflector(_Activity_.class, component); attached = false; attach(lastNonConfigurationInstances); create(outState); start(); restoreInstanceState(outState); postCreate(outState); resume(); postResume(); visible(); windowFocusChanged(true); // Move back to the original stage. If the original stage was transient stage, it will bring it // to resumed state to match the on device behavior. switch (originalStage) { case PAUSED: pause(); return this; case STOPPED: pause(); stop(); return this; default: return this; } }public ActivityController setup(Bundle savedInstanceState) { return create(savedInstanceState) .start() .restoreInstanceState(savedInstanceState) .postCreate(savedInstanceState) .resume() .visible(); }public static int getMode(String path) { if (path == null) { return 0; } File file = new File(path); if (file.isDirectory()) { return S_IFDIR_VALUE; } if (file.isFile()) { return S_IFREG_VALUE; } if (!canonicalize(path).equals(path)) { return S_IFLNK_VALUE; } return 0; }public void pushDefaultReturnValueToStack(Type type) { if (type.equals(Type.BOOLEAN_TYPE)) { push(false); } else if (type.equals(Type.INT_TYPE) || type.equals(Type.SHORT_TYPE) || type.equals(Type.BYTE_TYPE) || type.equals(Type.CHAR_TYPE)) { push(0); } else if (type.equals(Type.LONG_TYPE)) { push(0L); } else if (type.equals(Type.FLOAT_TYPE)) { push(0f); } else if (type.equals(Type.DOUBLE_TYPE)) { push(0d); } else if (type.getSort() == ARRAY || type.getSort() == OBJECT) { loadNull(); } }public void addChild(AccessibilityNodeInfo child) { if (children == null) { children = new ArrayList<>(); } children.add(child); ShadowAccessibilityNodeInfo shadowAccessibilityNodeInfo = Shadow.extract(child); shadowAccessibilityNodeInfo.parent = realAccessibilityNodeInfo; }public void setTraversalBefore(AccessibilityNodeInfo info) { if (this.traversalBefore != null) { this.traversalBefore.recycle(); } this.traversalBefore = obtain(info); }public void setTraversalAfter(AccessibilityNodeInfo info) { if (this.traversalAfter != null) { this.traversalAfter.recycle(); } this.traversalAfter = obtain(info); }protected void makeMethodPrivate(MethodNode method) { method.access = (method.access | Opcodes.ACC_PRIVATE) & ~(Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED); }protected void makeMethodPublic(MethodNode method) { method.access = (method.access | Opcodes.ACC_PUBLIC) & ~(Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE); }private void makeClassPublic(ClassNode clazz) { clazz.access = (clazz.access | Opcodes.ACC_PUBLIC) & ~(Opcodes.ACC_PROTECTED | Opcodes.ACC_PRIVATE); }private boolean isGregorianCalendarBooleanConstructor(MethodInsnNode targetMethod) { return targetMethod.owner.equals("java/util/GregorianCalendar") && targetMethod.name.equals("") && targetMethod.desc.equals("(Z)V"); }private void rewriteMethodBody(MutableClass mutableClass, MethodNode callingMethod) { ListIterator instructions = callingMethod.instructions.iterator(); while (instructions.hasNext()) { AbstractInsnNode node = instructions.next(); switch (node.getOpcode()) { case Opcodes.NEW: TypeInsnNode newInsnNode = (TypeInsnNode) node; newInsnNode.desc = mutableClass.config.mappedTypeName(newInsnNode.desc); break; case Opcodes.GETFIELD: /* falls through */ case Opcodes.PUTFIELD: /* falls through */ case Opcodes.GETSTATIC: /* falls through */ case Opcodes.PUTSTATIC: FieldInsnNode fieldInsnNode = (FieldInsnNode) node; fieldInsnNode.desc = mutableClass.config.mappedTypeName(fieldInsnNode.desc); // todo test break; case Opcodes.INVOKESTATIC: /* falls through */ case Opcodes.INVOKEINTERFACE: /* falls through */ case Opcodes.INVOKESPECIAL: /* falls through */ case Opcodes.INVOKEVIRTUAL: MethodInsnNode targetMethod = (MethodInsnNode) node; targetMethod.desc = mutableClass.config.remapParams(targetMethod.desc); if (isGregorianCalendarBooleanConstructor(targetMethod)) { replaceGregorianCalendarBooleanConstructor(instructions, targetMethod); } else if (mutableClass.config.shouldIntercept(targetMethod)) { interceptInvokeVirtualMethod(mutableClass, instructions, targetMethod); } break; case Opcodes.INVOKEDYNAMIC: /* no unusual behavior */ break; default: break; } } }protected void instrumentNativeMethod(MutableClass mutableClass, MethodNode method) { method.access = method.access & ~Opcodes.ACC_NATIVE; RobolectricGeneratorAdapter generator = new RobolectricGeneratorAdapter(method); Type returnType = generator.getReturnType(); generator.pushDefaultReturnValueToStack(returnType); generator.returnValue(); }@Deprecated public static String addSmallestScreenWidth(String qualifiers, int smallestScreenWidth) { int qualifiersSmallestScreenWidth = Qualifiers.getSmallestScreenWidth(qualifiers); if (qualifiersSmallestScreenWidth == -1) { if (qualifiers.length() > 0) { qualifiers += "-"; } qualifiers += "sw" + smallestScreenWidth + "dp"; } return qualifiers; }public static void setWifiOn(boolean isOn) { Settings.Global.putInt( RuntimeEnvironment.application.getContentResolver(), Settings.Global.WIFI_ON, isOn ? 1 : 0); Settings.System.putInt( RuntimeEnvironment.application.getContentResolver(), Settings.System.WIFI_ON, isOn ? 1 : 0); }private void addMissingStyleableAttributes(PackageResourceTable resourceTable, Class rClass) { for (Class innerClass : rClass.getClasses()) { if (innerClass.getSimpleName().equals("styleable")) { String styleableName = null; // Current styleable name int[] styleableArray = null; // Current styleable value array or references for (Field field : innerClass.getDeclaredFields()) { if (field.getType().equals(int[].class) && Modifier.isStatic(field.getModifiers())) { styleableName = field.getName(); try { styleableArray = (int[]) (field.get(null)); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } else if (field.getType().equals(Integer.TYPE) && Modifier.isStatic(field.getModifiers())) { String attributeName = field.getName().substring(styleableName.length() + 1); try { int styleableIndex = field.getInt(null); int attributeResId = styleableArray[styleableIndex]; resourceTable.addResource(attributeResId, "attr", attributeName); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } } } }public PackageResourceTable newResourceTable(String packageName, ResourcePath... resourcePaths) { return PerfStatsCollector.getInstance() .measure( "load legacy app resources", () -> { PackageResourceTable resourceTable = new PackageResourceTable(packageName); for (ResourcePath resourcePath : resourcePaths) { if (resourcePath.getRClass() != null) { addRClassValues(resourceTable, resourcePath.getRClass()); } } for (ResourcePath resourcePath : resourcePaths) { parseResourceFiles(resourcePath, resourceTable); } return resourceTable; }); }public PackageResourceTable newFrameworkResourceTable(ResourcePath resourcePath) { return PerfStatsCollector.getInstance() .measure( "load legacy framework resources", () -> { PackageResourceTable resourceTable = new PackageResourceTable("android"); if (resourcePath.getRClass() != null) { addRClassValues(resourceTable, resourcePath.getRClass()); addMissingStyleableAttributes(resourceTable, resourcePath.getRClass()); } if (resourcePath.getInternalRClass() != null) { addRClassValues(resourceTable, resourcePath.getInternalRClass()); addMissingStyleableAttributes(resourceTable, resourcePath.getInternalRClass()); } parseResourceFiles(resourcePath, resourceTable); return resourceTable; }); }public static Element getSelectKey(IntrospectedColumn introspectedColumn, GeneratedKey generatedKey) { return getSelectKey(introspectedColumn, generatedKey, null); }@Override public String getFullyQualifiedName() { String fullyQualifiedName = super.getFullyQualifiedName(); String before = fullyQualifiedName.substring(0, fullyQualifiedName.lastIndexOf(".")); String end = fullyQualifiedName.substring(fullyQualifiedName.lastIndexOf(".")); return before + "." + outerType + end; }@Override public void addComment(XmlElement xmlElement) { Map map = new HashMap<>(); map.put("mgb", MergeConstants.NEW_ELEMENT_TAG); map.put("xmlElement", xmlElement); // 添加评论 addXmlElementComment(xmlElement, map, EnumNode.ADD_COMMENT); }@Override public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) { Map map = new HashMap<>(); map.put("mgb", MergeConstants.NEW_ELEMENT_TAG); map.put("method", method); map.put("introspectedTable", introspectedTable); // 添加评论 addJavaElementComment(method, map, EnumNode.ADD_GENERAL_METHOD_COMMENT); }@Override public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { Map map = new HashMap<>(); map.put("mgb", MergeConstants.NEW_ELEMENT_TAG); map.put("method", method); map.put("introspectedTable", introspectedTable); map.put("introspectedColumn", introspectedColumn); // 添加评论 addJavaElementComment(method, map, EnumNode.ADD_GETTER_COMMENT); }@Override public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) { Map map = new HashMap<>(); map.put("mgb", MergeConstants.NEW_ELEMENT_TAG); map.put("innerEnum", innerEnum); map.put("introspectedTable", introspectedTable); // 添加评论 addJavaElementComment(innerEnum, map, EnumNode.ADD_ENUM_COMMENT); }@Override public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { Map map = new HashMap<>(); map.put("mgb", MergeConstants.NEW_ELEMENT_TAG); map.put("topLevelClass", topLevelClass); map.put("introspectedTable", introspectedTable); // 添加评论 addJavaElementComment(topLevelClass, map, EnumNode.ADD_MODEL_CLASS_COMMENT); }@Override public void addConfigurationProperties(Properties properties) { suppressDate = isTrue(properties .getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE)); suppressAllComments = isTrue(properties .getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS)); }public void setLabelColors(int colorNormal, int colorPressed, int colorRipple) { Label label = getLabelView(); int left = label.getPaddingLeft(); int top = label.getPaddingTop(); int right = label.getPaddingRight(); int bottom = label.getPaddingBottom(); label.setColors(colorNormal, colorPressed, colorRipple); label.updateBackground(); label.setPadding(left, top, right, bottom); }@TargetApi(Build.VERSION_CODES.LOLLIPOP) public void setElevationCompat(float elevation) { mShadowColor = 0x26000000; mShadowRadius = Math.round(elevation / 2); mShadowXOffset = 0; mShadowYOffset = Math.round(mFabSize == SIZE_NORMAL ? elevation : elevation / 2); if (Util.hasLollipop()) { super.setElevation(elevation); mUsingElevationCompat = true; mShowShadow = false; updateBackground(); ViewGroup.LayoutParams layoutParams = getLayoutParams(); if (layoutParams != null) { setLayoutParams(layoutParams); } } else { mShowShadow = true; updateBackground(); } }public void setAnimated(boolean animated) { mIsAnimated = animated; mOpenAnimatorSet.setDuration(animated ? ANIMATION_DURATION : 0); mCloseAnimatorSet.setDuration(animated ? ANIMATION_DURATION : 0); }public static long findInstanceLengthForTrial(FileDownloadConnection connection) { long length = findInstanceLengthFromContentRange(connection); if (length < 0) { length = TOTAL_VALUE_IN_CHUNKED_RESOURCE; FileDownloadLog.w(FileDownloadUtils.class, "don't get instance length from" + "Content-Range header"); } // the response of HEAD method is not very canonical sometimes(it depends on server // implementation) // so that it's uncertain the content-length is the same as the response of GET method if // content-length=0, so we have to filter this case in here. if (length == 0 && FileDownloadProperties.getImpl().trialConnectionHeadMethod) { length = TOTAL_VALUE_IN_CHUNKED_RESOURCE; } return length; }public static boolean isAcceptRange(int responseCode, FileDownloadConnection connection) { if (responseCode == HttpURLConnection.HTTP_PARTIAL || responseCode == FileDownloadConnection.RESPONSE_CODE_FROM_OFFSET) return true; final String acceptRanges = connection.getResponseHeaderField("Accept-Ranges"); return "bytes".equals(acceptRanges); }public void resume() { synchronized (finishCallback) { if (!paused) { FileDownloadLog.w(this, "require resume this queue(remain %d), but it is" + " still running", mTasks.size()); return; } paused = false; mTasks.addAll(pausedList); pausedList.clear(); if (workingTask == null) { sendNext(); } else { workingTask.addFinishListener(finishCallback); workingTask.start(); } } }public void pause() { synchronized (finishCallback) { if (paused) { FileDownloadLog.w(this, "require pause this queue(remain %d), but " + "it has already been paused", mTasks.size()); return; } paused = true; mTasks.drainTo(pausedList); if (workingTask != null) { workingTask.removeFinishListener(finishCallback); workingTask.pause(); } } }void addUnchecked(final BaseDownloadTask.IRunningTask task) { if (task.isMarkedAdded2List()) { return; } synchronized (mList) { if (mList.contains(task)) { FileDownloadLog.w(this, "already has %s", task); } else { task.markAdded2List(); mList.add(task); if (FileDownloadLog.NEED_LOG) { FileDownloadLog.v(this, "add list in all %s %d %d", task, task.getOrigin().getStatus(), mList.size()); } } } }void divertAndIgnoreDuplicate( @SuppressWarnings("SameParameterValue") final List destination) { synchronized (mList) { for (BaseDownloadTask.IRunningTask iRunningTask : mList) { if (!destination.contains(iRunningTask)) { destination.add(iRunningTask); } } mList.clear(); } }public void start() { for (BaseDownloadTask task : tasks) { task.setListener(target); if (autoRetryTimes != null) { task.setAutoRetryTimes(autoRetryTimes); } if (syncCallback != null) { task.setSyncCallback(syncCallback); } if (isForceReDownload != null) { task.setForceReDownload(isForceReDownload); } if (callbackProgressTimes != null) { task.setCallbackProgressTimes(callbackProgressTimes); } if (callbackProgressMinIntervalMillis != null) { task.setCallbackProgressMinInterval(callbackProgressMinIntervalMillis); } if (tag != null) { task.setTag(tag); } if (taskFinishListenerList != null) { for (BaseDownloadTask.FinishListener finishListener : taskFinishListenerList) { task.addFinishListener(finishListener); } } if (this.directory != null) { task.setPath(this.directory, true); } if (this.isWifiRequired != null) { task.setWifiRequired(this.isWifiRequired); } task.asInQueueTask().enqueue(); } FileDownloader.getImpl().start(target, isSerial); }public void pauseAll() { List list = mThreadPool.getAllExactRunningDownloadIds(); if (FileDownloadLog.NEED_LOG) { FileDownloadLog.d(this, "pause all tasks %d", list.size()); } for (Integer id : list) { pause(id); } }public boolean setMaxNetworkThreadCount(final int count) { if (!FileDownloadList.getImpl().isEmpty()) { FileDownloadLog.w(this, "Can't change the max network thread count, because there " + "are actively executing tasks in FileDownloader, please try again after all" + " actively executing tasks are completed or invoking FileDownloader#pauseAll" + " directly."); return false; } return FileDownloadServiceProxy.getImpl().setMaxNetworkThreadCount(count); }public boolean unBindServiceIfIdle() { // check idle if (!isServiceConnected()) { return false; } if (FileDownloadList.getImpl().isEmpty() && FileDownloadServiceProxy.getImpl().isIdle()) { unBindService(); return true; } return false; }public long getSoFar(final int downloadId) { BaseDownloadTask.IRunningTask task = FileDownloadList.getImpl().get(downloadId); if (task == null) { return FileDownloadServiceProxy.getImpl().getSofar(downloadId); } return task.getOrigin().getLargeFileSoFarBytes(); }public void pauseAll() { FileDownloadTaskLauncher.getImpl().expireAll(); final BaseDownloadTask.IRunningTask[] downloadList = FileDownloadList.getImpl().copy(); for (BaseDownloadTask.IRunningTask task : downloadList) { task.getOrigin().pause(); } // double check, for case: File Download progress alive but ui progress has died and relived // so FileDownloadList not always contain all running task exactly. if (FileDownloadServiceProxy.getImpl().isConnected()) { FileDownloadServiceProxy.getImpl().pauseAllTasks(); } else { PauseAllMarker.createMarker(); } }public boolean start(final FileDownloadListener listener, final boolean isSerial) { if (listener == null) { FileDownloadLog.w(this, "Tasks with the listener can't start, because the listener " + "provided is null: [null, %B]", isSerial); return false; } return isSerial ? getQueuesHandler().startQueueSerial(listener) : getQueuesHandler().startQueueParallel(listener); }void log(SignalType signalType, Object signalValue) { String line = fuseable ? LOG_TEMPLATE_FUSEABLE : LOG_TEMPLATE; if (operatorLine != null) { line = line + " " + operatorLine; } if (level == Level.FINEST) { log.trace(line, signalType, signalValue); } else if (level == Level.FINE) { log.debug(line, signalType, signalValue); } else if (level == Level.INFO) { log.info(line, signalType, signalValue); } else if (level == Level.WARNING) { log.warn(line, signalType, signalValue); } else if (level == Level.SEVERE) { log.error(line, signalType, signalValue); } }@Nullable public static Throwable terminate(AtomicReferenceFieldUpdater field, T instance) { Throwable current = field.get(instance); if (current != TERMINATED) { current = field.getAndSet(instance, TERMINATED); } return current; }final ParallelFlux concatMapDelayError(Function> mapper, boolean delayUntilEnd, int prefetch) { return concatMap(mapper, prefetch, delayUntilEnd ? ErrorMode.END: ErrorMode.BOUNDARY); }final ParallelFlux concatMap(Function> mapper, int prefetch, ErrorMode errorMode) { return onAssembly(new ParallelConcatMap<>(this, mapper, Queues.get(prefetch), prefetch, errorMode)); }protected final boolean validate(Subscriber[] subscribers) { int p = parallelism(); if (subscribers.length != p) { IllegalArgumentException iae = new IllegalArgumentException("parallelism = " + "" + p + ", subscribers = " + subscribers.length); for (Subscriber s : subscribers) { Operators.error(s, iae); } return false; } return true; }public final Flux sequential(int prefetch) { return Flux.onAssembly(new ParallelMergeSequential<>(this, prefetch, Queues.get(prefetch))); }public final ParallelFlux flatMap(Function> mapper, boolean delayError, int maxConcurrency, int prefetch) { return onAssembly(new ParallelFlatMap<>(this, mapper, delayError, maxConcurrency, Queues.get(maxConcurrency), prefetch, Queues.get(prefetch))); }public final ParallelFlux doOnRequest(LongConsumer onRequest) { Objects.requireNonNull(onRequest, "onRequest"); return doOnSignal(this, null, null, null, null, null, null, onRequest, null); }public final ParallelFlux doOnError(Consumer onError) { Objects.requireNonNull(onError, "onError"); return doOnSignal(this, null, null, onError, null, null, null, null, null); }public final ParallelFlux doOnComplete(Runnable onComplete) { Objects.requireNonNull(onComplete, "onComplete"); return doOnSignal(this, null, null, null, onComplete, null, null, null, null); }public final ParallelFlux doOnCancel(Runnable onCancel) { Objects.requireNonNull(onCancel, "onCancel"); return doOnSignal(this, null, null, null, null, null, null, null, onCancel); }public final ParallelFlux concatMap(Function> mapper) { return concatMap(mapper, 2, ErrorMode.IMMEDIATE); }public final ParallelFlux collect(Supplier collectionSupplier, BiConsumer collector) { return onAssembly(new ParallelCollect<>(this, collectionSupplier, collector)); }public final U as(Function, U> converter) { return converter.apply(this); }@SuppressWarnings("unchecked") static boolean trySubscribeScalarMap(Publisher source, CoreSubscriber s, Function> mapper, boolean fuseableExpected) { if (source instanceof Callable) { T t; try { t = ((Callable) source).call(); } catch (Throwable e) { Operators.error(s, Operators.onOperatorError(e, s.currentContext())); return true; } if (t == null) { Operators.complete(s); return true; } Publisher p; try { p = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null Publisher"); } catch (Throwable e) { Operators.error(s, Operators.onOperatorError(null, e, t, s.currentContext())); return true; } if (p instanceof Callable) { R v; try { v = ((Callable) p).call(); } catch (Throwable e) { Operators.error(s, Operators.onOperatorError(null, e, t, s.currentContext())); return true; } if (v != null) { s.onSubscribe(Operators.scalarSubscription(s, v)); } else { Operators.complete(s); } } else { if (!fuseableExpected || p instanceof Fuseable) { p.subscribe(s); } else { p.subscribe(new FluxHide.SuppressFuseableSubscriber<>(s)); } } return true; } return false; }static void drainMaxLoop(Queue q, Subscriber a, boolean delayError, Disposable dispose, QueueDrainSubscriber qd) { int missed = 1; for (;;) { for (;;) { boolean d = qd.done(); Q v = q.poll(); boolean empty = v == null; if (checkTerminated(d, empty, a, delayError, q, qd)) { if (dispose != null) { dispose.dispose(); } return; } if (empty) { break; } long r = qd.requested(); if (r != 0L) { if (qd.accept(a, v)) { if (r != Long.MAX_VALUE) { qd.produced(1); } } } else { q.clear(); if (dispose != null) { dispose.dispose(); } a.onError(Exceptions.failWithOverflow("Could not emit value due to lack of requests.")); return; } } missed = qd.leave(-missed); if (missed == 0) { break; } } }@SuppressWarnings("unchecked") MonoDelayUntil copyWithNewTriggerGenerator(boolean delayError, Function> triggerGenerator) { Objects.requireNonNull(triggerGenerator, "triggerGenerator"); Function>[] oldTriggers = this.otherGenerators; Function>[] newTriggers = new Function[oldTriggers.length + 1]; System.arraycopy(oldTriggers, 0, newTriggers, 0, oldTriggers.length); newTriggers[oldTriggers.length] = triggerGenerator; return new MonoDelayUntil<>(this.source, newTriggers); }static final Map, ? extends Publisher>> getOnEachOperatorHooks() { return Collections.unmodifiableMap(onEachOperatorHooks); }public final Mono onErrorResume(Function> fallback) { return onAssembly(new MonoOnErrorResume<>(this, fallback)); }public final Mono or(Mono other) { if (this instanceof MonoFirst) { MonoFirst a = (MonoFirst) this; Mono result = a.orAdditionalSource(other); if (result != null) { return result; } } return first(this, other); }public final Mono defaultIfEmpty(T defaultV) { if (this instanceof Fuseable.ScalarCallable) { try { T v = block(); if (v == null) { return Mono.just(defaultV); } } catch (Throwable e) { //leave MonoError returns as this } return this; } return onAssembly(new MonoDefaultIfEmpty<>(this, defaultV)); }public final Mono and(Publisher other) { if (this instanceof MonoWhen) { @SuppressWarnings("unchecked") MonoWhen o = (MonoWhen) this; Mono result = o.whenAdditionalSource(other); if (result != null) { return result; } } return when(this, other); }public static WaitStrategy phasedOffSleep(long spinTimeout, long yieldTimeout, TimeUnit units) { return phasedOff(spinTimeout, yieldTimeout, units, parking(0)); } MonoIgnoreThen shift(Mono newLast) { Objects.requireNonNull(newLast, "newLast"); Publisher[] a = ignore; int n = a.length; Publisher[] b = new Publisher[n + 1]; System.arraycopy(a, 0, b, 0, n); b[n] = last; return new MonoIgnoreThen<>(b, newLast); }public static Subscription scalarSubscription(CoreSubscriber subscriber, T value){ return new ScalarSubscription<>(subscriber, value); }public static long produced(AtomicLongFieldUpdater updater, T instance, long toSub) { long r, u; do { r = updater.get(instance); if (r == 0 || r == Long.MAX_VALUE) { return r; } u = subOrZero(r, toSub); } while (!updater.compareAndSet(instance, r, u)); return u; }public static void error(Subscriber s, Throwable e) { s.onSubscribe(EmptySubscription.INSTANCE); s.onError(e); }@SuppressWarnings("unchecked") @Nullable public static QueueSubscription as(Subscription s) { if (s instanceof QueueSubscription) { return (QueueSubscription) s; } return null; }static long getAndSub(RingBuffer.Sequence sequence, long toSub) { long r, u; do { r = sequence.getAsLong(); if (r == 0 || r == Long.MAX_VALUE) { return r; } u = Operators.subOrZero(r, toSub); } while (!sequence.compareAndSet(r, u)); return r; }static Mono convertToMono(Callable supplier) { if (supplier instanceof Fuseable.ScalarCallable) { Fuseable.ScalarCallable scalarCallable = (Fuseable.ScalarCallable) supplier; T v; try { v = scalarCallable.call(); } catch (Exception e) { return Mono.error(e); } if (v == null) { return Mono.empty(); } return Mono.just(v); } return Mono.onAssembly(new MonoCallable<>(supplier)); }public final Flux repeat(long numRepeat, BooleanSupplier predicate) { if (numRepeat < 0L) { throw new IllegalArgumentException("numRepeat >= 0 required"); } if (numRepeat == 0) { return this; } return defer( () -> repeat(countingBooleanSupplier(predicate, numRepeat))); }public final Flux onErrorResume(Function> fallback) { return onAssembly(new FluxOnErrorResume<>(this, fallback)); }public final Mono elementAt(int index, T defaultValue) { return Mono.onAssembly(new MonoElementAt<>(this, index, defaultValue)); }@Nullable final T blockingGet(long timeout, TimeUnit unit) { if (Schedulers.isInNonBlockingThread()) { throw new IllegalStateException("block()/blockFirst()/blockLast() are blocking, which is not supported in thread " + Thread.currentThread().getName()); } if (getCount() != 0) { try { if (!await(timeout, unit)) { dispose(); throw new IllegalStateException("Timeout on blocking read for " + timeout + " " + unit); } } catch (InterruptedException ex) { dispose(); RuntimeException re = Exceptions.propagate(ex); //this is ok, as re is always a new non-singleton instance re.addSuppressed(new Exception("#block has been interrupted")); throw re; } } Throwable e = error; if (e != null) { RuntimeException re = Exceptions.propagate(e); //this is ok, as re is always a new non-singleton instance re.addSuppressed(new Exception("#block terminated with an error")); throw re; } return value; }static boolean postCompleteDrain(long n, Subscriber actual, Queue queue, AtomicLongFieldUpdater field, F instance, BooleanSupplier isCancelled) { // TODO enable fast-path // if (n == -1 || n == Long.MAX_VALUE) { // for (;;) { // if (isDisposed.getAsBoolean()) { // break; // } // // T v = queue.poll(); // // if (v == null) { // actual.onComplete(); // break; // } // // actual.onNext(v); // } // // return true; // } long e = n & COMPLETED_MASK; for (; ; ) { while (e != n) { if (isCancelled.getAsBoolean()) { return true; } T t = queue.poll(); if (t == null) { actual.onComplete(); return true; } actual.onNext(t); e++; } if (isCancelled.getAsBoolean()) { return true; } if (queue.isEmpty()) { actual.onComplete(); return true; } n = field.get(instance); if (n == e) { n = field.addAndGet(instance, -(e & REQUESTED_MASK)); if ((n & REQUESTED_MASK) == 0L) { return false; } e = n & COMPLETED_MASK; } } }protected String getMessageFor(ThrowableFailureEvent event, Bundle arguments) { int msgResId = config.getMessageIdForThrowable(event.throwable); return config.resources.getString(msgResId); }protected String getTitleFor(ThrowableFailureEvent event, Bundle arguments) { return config.resources.getString(config.defaultTitleId); }protected T prepareErrorFragment(ThrowableFailureEvent event, boolean finishAfterDialog, Bundle argumentsForErrorDialog) { if (event.isSuppressErrorUi()) { // Show nothing by default return null; } Bundle bundle; if (argumentsForErrorDialog != null) { bundle = (Bundle) argumentsForErrorDialog.clone(); } else { bundle = new Bundle(); } if (!bundle.containsKey(ErrorDialogManager.KEY_TITLE)) { String title = getTitleFor(event, bundle); bundle.putString(ErrorDialogManager.KEY_TITLE, title); } if (!bundle.containsKey(ErrorDialogManager.KEY_MESSAGE)) { String message = getMessageFor(event, bundle); bundle.putString(ErrorDialogManager.KEY_MESSAGE, message); } if (!bundle.containsKey(ErrorDialogManager.KEY_FINISH_AFTER_DIALOG)) { bundle.putBoolean(ErrorDialogManager.KEY_FINISH_AFTER_DIALOG, finishAfterDialog); } if (!bundle.containsKey(ErrorDialogManager.KEY_EVENT_TYPE_ON_CLOSE) && config.defaultEventTypeOnDialogClosed != null) { bundle.putSerializable(ErrorDialogManager.KEY_EVENT_TYPE_ON_CLOSE, config.defaultEventTypeOnDialogClosed); } if (!bundle.containsKey(ErrorDialogManager.KEY_ICON_ID) && config.defaultDialogIconId != 0) { bundle.putInt(ErrorDialogManager.KEY_ICON_ID, config.defaultDialogIconId); } return createErrorFragment(event, bundle); }public static void attachTo(Activity activity, boolean finishAfterDialog, Bundle argumentsForErrorDialog) { Object executionScope = activity.getClass(); attachTo(activity, executionScope, finishAfterDialog, argumentsForErrorDialog); }public EventBusBuilder addIndex(SubscriberInfoIndex index) { if (subscriberInfoIndexes == null) { subscriberInfoIndexes = new ArrayList<>(); } subscriberInfoIndexes.add(index); return this; }static void addInterfaces(List> eventTypes, Class[] interfaces) { for (Class interfaceClass : interfaces) { if (!eventTypes.contains(interfaceClass)) { eventTypes.add(interfaceClass); addInterfaces(eventTypes, interfaceClass.getInterfaces()); } } }private static List> lookupAllEventTypes(Class eventClass) { synchronized (eventTypesCache) { List> eventTypes = eventTypesCache.get(eventClass); if (eventTypes == null) { eventTypes = new ArrayList<>(); Class clazz = eventClass; while (clazz != null) { eventTypes.add(clazz); addInterfaces(eventTypes, clazz.getInterfaces()); clazz = clazz.getSuperclass(); } eventTypesCache.put(eventClass, eventTypes); } return eventTypes; } }public boolean removeStickyEvent(Object event) { synchronized (stickyEvents) { Class eventType = event.getClass(); Object existingEvent = stickyEvents.get(eventType); if (event.equals(existingEvent)) { stickyEvents.remove(eventType); return true; } else { return false; } } }public T removeStickyEvent(Class eventType) { synchronized (stickyEvents) { return eventType.cast(stickyEvents.remove(eventType)); } }public T getStickyEvent(Class eventType) { synchronized (stickyEvents) { return eventType.cast(stickyEvents.get(eventType)); } }public void post(Object event) { PostingThreadState postingState = currentPostingThreadState.get(); List eventQueue = postingState.eventQueue; eventQueue.add(event); if (!postingState.isPosting) { postingState.isMainThread = isMainThread(); postingState.isPosting = true; if (postingState.canceled) { throw new EventBusException("Internal error. Abort state was not reset"); } try { while (!eventQueue.isEmpty()) { postSingleEvent(eventQueue.remove(0), postingState); } } finally { postingState.isPosting = false; postingState.isMainThread = false; } } }public synchronized void unregister(Object subscriber) { List> subscribedTypes = typesBySubscriber.get(subscriber); if (subscribedTypes != null) { for (Class eventType : subscribedTypes) { unsubscribeByEventType(subscriber, eventType); } typesBySubscriber.remove(subscriber); } else { logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass()); } }private void unsubscribeByEventType(Object subscriber, Class eventType) { List subscriptions = subscriptionsByEventType.get(eventType); if (subscriptions != null) { int size = subscriptions.size(); for (int i = 0; i < size; i++) { Subscription subscription = subscriptions.get(i); if (subscription.subscriber == subscriber) { subscription.active = false; subscriptions.remove(i); i--; size--; } } } }private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) { Class eventType = subscriberMethod.eventType; Subscription newSubscription = new Subscription(subscriber, subscriberMethod); CopyOnWriteArrayList subscriptions = subscriptionsByEventType.get(eventType); if (subscriptions == null) { subscriptions = new CopyOnWriteArrayList<>(); subscriptionsByEventType.put(eventType, subscriptions); } else { if (subscriptions.contains(newSubscription)) { throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event " + eventType); } } int size = subscriptions.size(); for (int i = 0; i <= size; i++) { if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) { subscriptions.add(i, newSubscription); break; } } List> subscribedEvents = typesBySubscriber.get(subscriber); if (subscribedEvents == null) { subscribedEvents = new ArrayList<>(); typesBySubscriber.put(subscriber, subscribedEvents); } subscribedEvents.add(eventType); if (subscriberMethod.sticky) { if (eventInheritance) { // Existing sticky events of all subclasses of eventType have to be considered. // Note: Iterating over all events may be inefficient with lots of sticky events, // thus data structure should be changed to allow a more efficient lookup // (e.g. an additional map storing sub classes of super classes: Class -> List). Set, Object>> entries = stickyEvents.entrySet(); for (Map.Entry, Object> entry : entries) { Class candidateEventType = entry.getKey(); if (eventType.isAssignableFrom(candidateEventType)) { Object stickyEvent = entry.getValue(); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } } else { Object stickyEvent = stickyEvents.get(eventType); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } }public static EventBus getDefault() { EventBus instance = defaultInstance; if (instance == null) { synchronized (EventBus.class) { instance = EventBus.defaultInstance; if (instance == null) { instance = EventBus.defaultInstance = new EventBus(); } } } return instance; }private void checkForSubscribersToSkip(Messager messager, String myPackage) { for (TypeElement skipCandidate : methodsByClass.keySet()) { TypeElement subscriberClass = skipCandidate; while (subscriberClass != null) { if (!isVisible(myPackage, subscriberClass)) { boolean added = classesToSkip.add(skipCandidate); if (added) { String msg; if (subscriberClass.equals(skipCandidate)) { msg = "Falling back to reflection because class is not public"; } else { msg = "Falling back to reflection because " + skipCandidate + " has a non-public super class"; } messager.printMessage(Diagnostic.Kind.NOTE, msg, subscriberClass); } break; } List methods = methodsByClass.get(subscriberClass); if (methods != null) { for (ExecutableElement method : methods) { String skipReason = null; VariableElement param = method.getParameters().get(0); TypeMirror typeMirror = getParamTypeMirror(param, messager); if (!(typeMirror instanceof DeclaredType) || !(((DeclaredType) typeMirror).asElement() instanceof TypeElement)) { skipReason = "event type cannot be processed"; } if (skipReason == null) { TypeElement eventTypeElement = (TypeElement) ((DeclaredType) typeMirror).asElement(); if (!isVisible(myPackage, eventTypeElement)) { skipReason = "event type is not public"; } } if (skipReason != null) { boolean added = classesToSkip.add(skipCandidate); if (added) { String msg = "Falling back to reflection because " + skipReason; if (!subscriberClass.equals(skipCandidate)) { msg += " (found in super class for " + skipCandidate + ")"; } messager.printMessage(Diagnostic.Kind.NOTE, msg, param); } break; } } } subscriberClass = getSuperclass(subscriberClass); } } }public Integer mapThrowable(final Throwable throwable) { Throwable throwableToCheck = throwable; int depthToGo = 20; while (true) { Integer resId = mapThrowableFlat(throwableToCheck); if (resId != null) { return resId; } else { throwableToCheck = throwableToCheck.getCause(); depthToGo--; if (depthToGo <= 0 || throwableToCheck == throwable || throwableToCheck == null) { Log.d("EventBus", "No specific message resource ID found for " + throwable); // return config.defaultErrorMsgId; return null; } } } }public static ConnectionInformation fromConnection(Connection connection) { final ConnectionInformation connectionInformation = new ConnectionInformation(); connectionInformation.connection = connection; return connectionInformation; }public static URL locateOnClassPath(String filename) { URL result; // first try to load from context class loader result = Thread.currentThread().getContextClassLoader().getResource(filename); // next try the current class loader which loaded p6spy if (result == null) { result = P6Util.class.getClassLoader().getResource(filename); } // finally try the system class loader if (result == null) { result = ClassLoader.getSystemResource(filename); } return result; }public String appMapString() { if (hasGroup()) { String appMap = Optional.ofNullable(this.fields.get(TracingConstants.APP_MAP)).orElse(""); log.debug("App map: {}", appMap); return appMap; } raiseNonGroupException(); return "{}"; }@Bean @ConditionalOnClass(name = "org.springframework.data.redis.connection.RedisConnectionFactory") public RedisTemplate functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) { JdkSerializationRedisSerializer serializationRedisSerializer = new JdkSerializationRedisSerializer(); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); RedisTemplate redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(stringRedisSerializer); redisTemplate.setHashKeySerializer(stringRedisSerializer); redisTemplate.setHashValueSerializer(serializationRedisSerializer); redisTemplate.setValueSerializer(serializationRedisSerializer); redisTemplate.setConnectionFactory(redisConnectionFactory); return redisTemplate; }private void saveUndoLog(String groupId, String unitId, int sqlType, TableRecordList recordList) throws TxcLogicException { UndoLogDO undoLogDO = new UndoLogDO(); undoLogDO.setRollbackInfo(SqlUtils.objectToBlob(recordList)); undoLogDO.setUnitId(unitId); undoLogDO.setGroupId(groupId); undoLogDO.setSqlType(sqlType); try { txcLogHelper.saveUndoLog(undoLogDO); } catch (SQLException e) { throw new TxcLogicException(e); } }private void lockDataLine(String groupId, String unitId, Set lockIdSet, boolean isXLock) throws TxcLogicException { try { if (!reliableMessenger.acquireLocks(groupId, lockIdSet, isXLock ? DTXLocks.X_LOCK : DTXLocks.S_LOCK)) { throw new TxcLogicException("resource is locked! place try again later."); } globalContext.addTxcLockId(groupId, unitId, lockIdSet); } catch (RpcException e) { throw new TxcLogicException("can't contact to any TM for lock info. default error."); } }public static T blobToObject(byte[] blob, Class type) { try { return SerializerContext.getInstance().deSerialize(blob, type); } catch (SerializerException e) { throw new IllegalStateException(e); } }public static byte[] objectToBlob(Object o) { try { return SerializerContext.getInstance().serialize(o); } catch (SerializerException e) { throw new RuntimeException(e); } }public void setParameterValue(final String name, final Object value) { namedParameterValues.put(name, new Value(value)); }@Override public String getSqlWithValues() { if( namedParameterValues.size() == 0 ) { return super.getSqlWithValues(); } /* If named parameters were used, it is no longer possible to simply replace the placeholders in the original statement with the values of the bind variables. The only way it could be done is if the names could be resolved by to the ordinal positions which is not possible on all databases. New log format: name:value, name:value Example: {? = call test_proc(?,?)} param1:value1, param2:value2, param3:value3 In the event that ordinal and named parameters are both used, the original position will be used as the name. Example: {? = call test_proc(?,?)} 1:value1, 3:value3, param2:value2 */ final StringBuilder result = new StringBuilder(); final String statementQuery = getStatementQuery(); // first append the original statement result.append(statementQuery); result.append(" "); StringBuilder parameters = new StringBuilder(); // add parameters set with ordinal positions for( Map.Entry entry : getParameterValues().entrySet() ) { appendParameter(parameters, entry.getKey().toString(), entry.getValue()); } // add named parameters for( Map.Entry entry : namedParameterValues.entrySet() ) { appendParameter(parameters, entry.getKey(), entry.getValue()); } result.append(parameters); return result.toString(); }public NetworkBuilder expectedEdgeCount(int expectedEdgeCount) { this.expectedEdgeCount = Optional.of(checkNonNegative(expectedEdgeCount)); return this; }public NetworkBuilder expectedNodeCount(int expectedNodeCount) { this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount)); return this; }void removeEntryValueHashKnown(int entry, int valueHash) { removeEntry(entry, Hashing.smearedHash(keys[entry]), valueHash); }void removeEntryKeyHashKnown(int entry, int keyHash) { removeEntry(entry, keyHash, Hashing.smearedHash(values[entry])); }private void removeEntry(int entry, int keyHash, int valueHash) { checkArgument(entry != ABSENT); deleteFromTableKToV(entry, keyHash); deleteFromTableVToK(entry, valueHash); int oldPredecessor = prevInInsertionOrder[entry]; int oldSuccessor = nextInInsertionOrder[entry]; setSucceeds(oldPredecessor, oldSuccessor); moveEntryToIndex(size - 1, entry); keys[size - 1] = null; values[size - 1] = null; size--; modCount++; }private void deleteFromTableVToK(int entry, int valueHash) { checkArgument(entry != ABSENT); int valueBucket = bucket(valueHash); if (hashTableVToK[valueBucket] == entry) { hashTableVToK[valueBucket] = nextInBucketVToK[entry]; nextInBucketVToK[entry] = ABSENT; return; } int prevInBucket = hashTableVToK[valueBucket]; for (int entryInBucket = nextInBucketVToK[prevInBucket]; entryInBucket != ABSENT; entryInBucket = nextInBucketVToK[entryInBucket]) { if (entryInBucket == entry) { nextInBucketVToK[prevInBucket] = nextInBucketVToK[entry]; nextInBucketVToK[entry] = ABSENT; return; } prevInBucket = entryInBucket; } throw new AssertionError("Expected to find entry with value " + values[entry]); }private void deleteFromTableKToV(int entry, int keyHash) { checkArgument(entry != ABSENT); int keyBucket = bucket(keyHash); if (hashTableKToV[keyBucket] == entry) { hashTableKToV[keyBucket] = nextInBucketKToV[entry]; nextInBucketKToV[entry] = ABSENT; return; } int prevInBucket = hashTableKToV[keyBucket]; for (int entryInBucket = nextInBucketKToV[prevInBucket]; entryInBucket != ABSENT; entryInBucket = nextInBucketKToV[entryInBucket]) { if (entryInBucket == entry) { nextInBucketKToV[prevInBucket] = nextInBucketKToV[entry]; nextInBucketKToV[entry] = ABSENT; return; } prevInBucket = entryInBucket; } throw new AssertionError("Expected to find entry with key " + keys[entry]); }private void insertIntoTableVToK(int entry, int valueHash) { checkArgument(entry != ABSENT); int valueBucket = bucket(valueHash); nextInBucketVToK[entry] = hashTableVToK[valueBucket]; hashTableVToK[valueBucket] = entry; }private void insertIntoTableKToV(int entry, int keyHash) { checkArgument(entry != ABSENT); int keyBucket = bucket(keyHash); nextInBucketKToV[entry] = hashTableKToV[keyBucket]; hashTableKToV[keyBucket] = entry; }private void ensureCapacity(int minCapacity) { if (nextInBucketKToV.length < minCapacity) { int oldCapacity = nextInBucketKToV.length; int newCapacity = ImmutableCollection.Builder.expandedCapacity(oldCapacity, minCapacity); keys = Arrays.copyOf(keys, newCapacity); values = Arrays.copyOf(values, newCapacity); nextInBucketKToV = expandAndFillWithAbsent(nextInBucketKToV, newCapacity); nextInBucketVToK = expandAndFillWithAbsent(nextInBucketVToK, newCapacity); prevInInsertionOrder = expandAndFillWithAbsent(prevInInsertionOrder, newCapacity); nextInInsertionOrder = expandAndFillWithAbsent(nextInInsertionOrder, newCapacity); } if (hashTableKToV.length < minCapacity) { int newTableSize = Hashing.closedTableSize(minCapacity, 1.0); hashTableKToV = createFilledWithAbsent(newTableSize); hashTableVToK = createFilledWithAbsent(newTableSize); for (int entryToRehash = 0; entryToRehash < size; entryToRehash++) { int keyHash = Hashing.smearedHash(keys[entryToRehash]); int keyBucket = bucket(keyHash); nextInBucketKToV[entryToRehash] = hashTableKToV[keyBucket]; hashTableKToV[keyBucket] = entryToRehash; int valueHash = Hashing.smearedHash(values[entryToRehash]); int valueBucket = bucket(valueHash); nextInBucketVToK[entryToRehash] = hashTableVToK[valueBucket]; hashTableVToK[valueBucket] = entryToRehash; } } }protected static int codePointAt(CharSequence seq, int index, int end) { checkNotNull(seq); if (index < end) { char c1 = seq.charAt(index++); if (c1 < Character.MIN_HIGH_SURROGATE || c1 > Character.MAX_LOW_SURROGATE) { // Fast path (first test is probably all we need to do) return c1; } else if (c1 <= Character.MAX_HIGH_SURROGATE) { // If the high surrogate was the last character, return its inverse if (index == end) { return -c1; } // Otherwise look for the low surrogate following it char c2 = seq.charAt(index); if (Character.isLowSurrogate(c2)) { return Character.toCodePoint(c1, c2); } throw new IllegalArgumentException( "Expected low surrogate but got char '" + c2 + "' with value " + (int) c2 + " at index " + index + " in '" + seq + "'"); } else { throw new IllegalArgumentException( "Unexpected low surrogate character '" + c1 + "' with value " + (int) c1 + " at index " + (index - 1) + " in '" + seq + "'"); } } throw new IndexOutOfBoundsException("Index exceeds specified range"); }final long reserveAndGetWaitLength(int permits, long nowMicros) { long momentAvailable = reserveEarliestAvailable(permits, nowMicros); return max(momentAvailable - nowMicros, 0); }boolean isExpired(ReferenceEntry entry, long now) { checkNotNull(entry); if (expiresAfterAccess() && (now - entry.getAccessTime() >= expireAfterAccessNanos)) { return true; } if (expiresAfterWrite() && (now - entry.getWriteTime() >= expireAfterWriteNanos)) { return true; } return false; }@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value static ValueReference unset() { return (ValueReference) UNSET; }public static Function forPredicate(Predicate predicate) { return new PredicateFunction(predicate); }@SuppressWarnings("unchecked") public static Function identity() { return (Function) IdentityFunction.INSTANCE; }@Beta public static ImmutableBiMap copyOf( Iterable> entries) { int estimatedSize = (entries instanceof Collection) ? ((Collection) entries).size() : ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY; return new Builder(estimatedSize).putAll(entries).build(); }public static ImmutableBiMap of(K k1, V v1) { checkEntryNotNull(k1, v1); return new RegularImmutableBiMap<>(new Object[] {k1, v1}, 1); }public void add(double x, double y) { // We extend the recursive expression for the one-variable case at Art of Computer Programming // vol. 2, Knuth, 4.2.2, (16) to the two-variable case. We have two value series x_i and y_i. // We define the arithmetic means X_n = 1/n \sum_{i=1}^n x_i, and Y_n = 1/n \sum_{i=1}^n y_i. // We also define the sum of the products of the differences from the means // C_n = \sum_{i=1}^n x_i y_i - n X_n Y_n // for all n >= 1. Then for all n > 1: // C_{n-1} = \sum_{i=1}^{n-1} x_i y_i - (n-1) X_{n-1} Y_{n-1} // C_n - C_{n-1} = x_n y_n - n X_n Y_n + (n-1) X_{n-1} Y_{n-1} // = x_n y_n - X_n [ y_n + (n-1) Y_{n-1} ] + [ n X_n - x_n ] Y_{n-1} // = x_n y_n - X_n y_n - x_n Y_{n-1} + X_n Y_{n-1} // = (x_n - X_n) (y_n - Y_{n-1}) xStats.add(x); if (isFinite(x) && isFinite(y)) { if (xStats.count() > 1) { sumOfProductsOfDeltas += (x - xStats.mean()) * (y - yStats.mean()); } } else { sumOfProductsOfDeltas = NaN; } yStats.add(y); }private static UnicodeEscaper wrap(final CharEscaper escaper) { return new UnicodeEscaper() { @Override protected char[] escape(int cp) { // If a code point maps to a single character, just escape that. if (cp < Character.MIN_SUPPLEMENTARY_CODE_POINT) { return escaper.escape((char) cp); } // Convert the code point to a surrogate pair and escape them both. // Note: This code path is horribly slow and typically allocates 4 new // char[] each time it is invoked. However this avoids any // synchronization issues and makes the escaper thread safe. char[] surrogateChars = new char[2]; Character.toChars(cp, surrogateChars, 0); char[] hiChars = escaper.escape(surrogateChars[0]); char[] loChars = escaper.escape(surrogateChars[1]); // If either hiChars or lowChars are non-null, the CharEscaper is trying // to escape the characters of a surrogate pair separately. This is // uncommon and applies only to escapers that assume UCS-2 rather than // UTF-16. See: http://en.wikipedia.org/wiki/UTF-16/UCS-2 if (hiChars == null && loChars == null) { // We expect this to be the common code path for most escapers. return null; } // Combine the characters and/or escaped sequences into a single array. int hiCount = hiChars != null ? hiChars.length : 1; int loCount = loChars != null ? loChars.length : 1; char[] output = new char[hiCount + loCount]; if (hiChars != null) { // TODO: Is this faster than System.arraycopy() for small arrays? for (int n = 0; n < hiChars.length; ++n) { output[n] = hiChars[n]; } } else { output[0] = surrogateChars[0]; } if (loChars != null) { for (int n = 0; n < loChars.length; ++n) { output[hiCount + n] = loChars[n]; } } else { output[hiCount] = surrogateChars[1]; } return output; } }; }static ImmutableMapEntry makeImmutable(Entry entry) { return makeImmutable(entry, entry.getKey(), entry.getValue()); }static ImmutableMapEntry makeImmutable(Entry entry, K key, V value) { boolean reusable = entry instanceof ImmutableMapEntry && ((ImmutableMapEntry) entry).isReusable(); return reusable ? (ImmutableMapEntry) entry : new ImmutableMapEntry(key, value); }@Override public ImmutableRangeSet subRangeSet(Range range) { if (!isEmpty()) { Range span = span(); if (range.encloses(span)) { return this; } else if (range.isConnected(span)) { return new ImmutableRangeSet(intersectRanges(range)); } } return of(); }private void aboutToAcquire(CycleDetectingLock lock) { if (!lock.isAcquiredByCurrentThread()) { ArrayList acquiredLockList = acquiredLocks.get(); LockGraphNode node = lock.getLockGraphNode(); node.checkAcquiredLocks(policy, acquiredLockList); acquiredLockList.add(node); } }public static ImmutableTypeToInstanceMap of() { return new ImmutableTypeToInstanceMap(ImmutableMap., B>of()); }static ImmutableSet unsafeDelegate(Set delegate) { switch (delegate.size()) { case 0: return of(); case 1: return new SingletonImmutableSet(delegate.iterator().next()); default: return new RegularImmutableSet(delegate); } }GeneralRange reverse() { GeneralRange result = reverse; if (result == null) { result = new GeneralRange( Ordering.from(comparator).reverse(), hasUpperBound, getUpperEndpoint(), getUpperBoundType(), hasLowerBound, getLowerEndpoint(), getLowerBoundType()); result.reverse = this; return this.reverse = result; } return result; }static GeneralRange all(Comparator comparator) { return new GeneralRange(comparator, false, null, OPEN, false, null, OPEN); }private static String[] getHostAndPortFromBracketedHost(String hostPortString) { int colonIndex = 0; int closeBracketIndex = 0; checkArgument( hostPortString.charAt(0) == '[', "Bracketed host-port string must start with a bracket: %s", hostPortString); colonIndex = hostPortString.indexOf(':'); closeBracketIndex = hostPortString.lastIndexOf(']'); checkArgument( colonIndex > -1 && closeBracketIndex > colonIndex, "Invalid bracketed host/port: %s", hostPortString); String host = hostPortString.substring(1, closeBracketIndex); if (closeBracketIndex + 1 == hostPortString.length()) { return new String[] {host, ""}; } else { checkArgument( hostPortString.charAt(closeBracketIndex + 1) == ':', "Only a colon may follow a close bracket: %s", hostPortString); for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) { checkArgument( Character.isDigit(hostPortString.charAt(i)), "Port must be numeric: %s", hostPortString); } return new String[] {host, hostPortString.substring(closeBracketIndex + 2)}; } }public static HostAndPort fromString(String hostPortString) { checkNotNull(hostPortString); String host; String portString = null; boolean hasBracketlessColons = false; if (hostPortString.startsWith("[")) { String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString); host = hostAndPort[0]; portString = hostAndPort[1]; } else { int colonPos = hostPortString.indexOf(':'); if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) { // Exactly 1 colon. Split into host:port. host = hostPortString.substring(0, colonPos); portString = hostPortString.substring(colonPos + 1); } else { // 0 or 2+ colons. Bare hostname or IPv6 literal. host = hostPortString; hasBracketlessColons = (colonPos >= 0); } } int port = NO_PORT; if (!Strings.isNullOrEmpty(portString)) { // Try to parse the whole port string as a number. // JDK7 accepts leading plus signs. We don't want to. checkArgument(!portString.startsWith("+"), "Unparseable port number: %s", hostPortString); try { port = Integer.parseInt(portString); } catch (NumberFormatException e) { throw new IllegalArgumentException("Unparseable port number: " + hostPortString); } checkArgument(isValidPort(port), "Port number out of range: %s", hostPortString); } return new HostAndPort(host, port, hasBracketlessColons); }public static HostAndPort fromHost(String host) { HostAndPort parsedHost = fromString(host); checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host); return parsedHost; }public static HostAndPort fromParts(String host, int port) { checkArgument(isValidPort(port), "Port out of range: %s", port); HostAndPort parsedHost = fromString(host); checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host); return new HostAndPort(parsedHost.host, port, parsedHost.hasBracketlessColons); }public ThreadFactoryBuilder setPriority(int priority) { // Thread#setPriority() already checks for validity. These error messages // are nicer though and will fail-fast. checkArgument( priority >= Thread.MIN_PRIORITY, "Thread priority (%s) must be >= %s", priority, Thread.MIN_PRIORITY); checkArgument( priority <= Thread.MAX_PRIORITY, "Thread priority (%s) must be <= %s", priority, Thread.MAX_PRIORITY); this.priority = priority; return this; }@J2ObjCIncompatible @GwtIncompatible // java.time.Duration @SuppressWarnings("GoodTime") // java.time.Duration decomposition public CacheBuilder expireAfterWrite(java.time.Duration duration) { return expireAfterWrite(duration.toNanos(), TimeUnit.NANOSECONDS); }private static boolean addCausalChain(Set seen, Throwable t) { for (; t != null; t = t.getCause()) { boolean firstTimeSeen = seen.add(t); if (!firstTimeSeen) { /* * We've seen this, so we've seen its causes, too. No need to re-add them. (There's one case * where this isn't true, but we ignore it: If we record an exception, then someone calls * initCause() on it, and then we examine it again, we'll conclude that we've seen the whole * chain before when it fact we haven't. But this should be rare.) */ return false; } } return true; }public static TreeMultiset create(Iterable elements) { TreeMultiset multiset = create(); Iterables.addAll(multiset, elements); return multiset; }@Beta public static Table transformValues( Table fromTable, Function function) { return new TransformedTable<>(fromTable, function); }@Override public void execute(final Runnable task) { checkNotNull(task); final Runnable submittedTask; final long oldRunCount; synchronized (queue) { // If the worker is already running (or execute() on the delegate returned successfully, and // the worker has yet to start) then we don't need to start the worker. if (workerRunningState == RUNNING || workerRunningState == QUEUED) { queue.add(task); return; } oldRunCount = workerRunCount; // If the worker is not yet running, the delegate Executor might reject our attempt to start // it. To preserve FIFO order and failure atomicity of rejected execution when the same // Runnable is executed more than once, allocate a wrapper that we know is safe to remove by // object identity. // A data structure that returned a removal handle from add() would allow eliminating this // allocation. submittedTask = new Runnable() { @Override public void run() { task.run(); } }; queue.add(submittedTask); workerRunningState = QUEUING; } try { executor.execute(worker); } catch (RuntimeException | Error t) { synchronized (queue) { boolean removed = (workerRunningState == IDLE || workerRunningState == QUEUING) && queue.removeLastOccurrence(submittedTask); // If the delegate is directExecutor(), the submitted runnable could have thrown a REE. But // that's handled by the log check that catches RuntimeExceptions in the queue worker. if (!(t instanceof RejectedExecutionException) || removed) { throw t; } } return; } /* * This is an unsynchronized read! After the read, the function returns immediately or acquires * the lock to check again. Since an IDLE state was observed inside the preceding synchronized * block, and reference field assignment is atomic, this may save reacquiring the lock when * another thread or the worker task has cleared the count and set the state. * *

When {@link #executor} is a directExecutor(), the value written to * {@code workerRunningState} will be available synchronously, and behaviour will be * deterministic. */ @SuppressWarnings("GuardedBy") boolean alreadyMarkedQueued = workerRunningState != QUEUING; if (alreadyMarkedQueued) { return; } synchronized (queue) { if (workerRunCount == oldRunCount && workerRunningState == QUEUING) { workerRunningState = QUEUED; } } }@GwtIncompatible // reflection public V[][] toArray(Class valueClass) { @SuppressWarnings("unchecked") // TODO: safe? V[][] copy = (V[][]) Array.newInstance(valueClass, rowList.size(), columnList.size()); for (int i = 0; i < rowList.size(); i++) { System.arraycopy(array[i], 0, copy[i], 0, array[i].length); } return copy; }void setDelegates(Map forward, Map backward) { checkState(delegate == null); checkState(inverse == null); checkArgument(forward.isEmpty()); checkArgument(backward.isEmpty()); checkArgument(forward != backward); delegate = forward; inverse = makeInverse(backward); }@CanIgnoreReturnValue public MapMaker concurrencyLevel(int concurrencyLevel) { checkState( this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s", this.concurrencyLevel); checkArgument(concurrencyLevel > 0); this.concurrencyLevel = concurrencyLevel; return this; }public void post(Object event) { Iterator eventSubscribers = subscribers.getSubscribers(event); if (eventSubscribers.hasNext()) { dispatcher.dispatch(event, eventSubscribers); } else if (!(event instanceof DeadEvent)) { // the event had no subscribers and was not itself a DeadEvent post(new DeadEvent(this, event)); } }public static void copy(URL from, OutputStream to) throws IOException { asByteSource(from).copyTo(to); }public void dispatch() { // iterate by index to avoid concurrent modification exceptions for (int i = 0; i < listeners.size(); i++) { listeners.get(i).dispatch(); } }private static Class loadFinalizer(FinalizerLoader... loaders) { for (FinalizerLoader loader : loaders) { Class finalizer = loader.loadFinalizer(); if (finalizer != null) { return finalizer; } } throw new AssertionError(); }public long sum() { long sum = 0L; for (AtomicLong value : map.values()) { sum = sum + value.get(); } return sum; }@SuppressWarnings("unchecked") public static ImmutableSetMultimap instantiate(SerializationStreamReader reader) throws SerializationException { Comparator valueComparator = (Comparator) reader.readObject(); ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder(); if (valueComparator != null) { builder.orderValuesBy(valueComparator); } return (ImmutableSetMultimap) Multimap_CustomFieldSerializerBase.instantiate(reader, builder); }static ImmutableSortedSet unsafeDelegateSortedSet( SortedSet delegate, boolean isSubset) { return delegate.isEmpty() ? emptySet(delegate.comparator()) : new RegularImmutableSortedSet(delegate, isSubset); }protected void update(ByteBuffer b) { if (b.hasArray()) { update(b.array(), b.arrayOffset() + b.position(), b.remaining()); b.position(b.limit()); } else { for (int remaining = b.remaining(); remaining > 0; remaining--) { update(b.get()); } } }protected @Nullable String pendingToString() { Object localValue = value; if (localValue instanceof SetFuture) { return "setFuture=[" + userObjectToString(((SetFuture) localValue).future) + "]"; } else if (this instanceof ScheduledFuture) { return "remaining delay=[" + ((ScheduledFuture) this).getDelay(TimeUnit.MILLISECONDS) + " ms]"; } return null; }static ImmutableMap indexMap(Collection list) { ImmutableMap.Builder builder = new ImmutableMap.Builder<>(list.size()); int i = 0; for (E e : list) { builder.put(e, i++); } return builder.build(); }static Function, Entry> asEntryToEntryFunction( final EntryTransformer transformer) { checkNotNull(transformer); return new Function, Entry>() { @Override public Entry apply(final Entry entry) { return transformEntry(transformer, entry); } }; }static Entry transformEntry( final EntryTransformer transformer, final Entry entry) { checkNotNull(transformer); checkNotNull(entry); return new AbstractMapEntry() { @Override public K getKey() { return entry.getKey(); } @Override public V2 getValue() { return transformer.transformEntry(entry.getKey(), entry.getValue()); } }; }static EntryTransformer asEntryTransformer( final Function function) { checkNotNull(function); return new EntryTransformer() { @Override public V2 transformEntry(K key, V1 value) { return function.apply(value); } }; }@CanIgnoreReturnValue private boolean finishLine(boolean sawNewline) throws IOException { String separator = sawReturn ? (sawNewline ? "\r\n" : "\r") : (sawNewline ? "\n" : ""); handleLine(line.toString(), separator); line = new StringBuilder(); sawReturn = false; return sawNewline; }@Override public ImmutableSet> entrySet() { ImmutableSet> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; }@Deprecated public static ImmutableSortedMap.Builder builderWithExpectedSize(int expectedSize) { throw new UnsupportedOperationException(); }static ImmutableList asImmutableList(Object[] elements, int length) { switch (length) { case 0: return of(); case 1: return of((E) elements[0]); default: if (length < elements.length) { elements = Arrays.copyOf(elements, length); } return new RegularImmutableList(elements); } }private static WildcardType canonicalizeWildcardType( TypeVariable declaration, WildcardType type) { Type[] declared = declaration.getBounds(); List upperBounds = new ArrayList<>(); for (Type bound : type.getUpperBounds()) { if (!any(declared).isSubtypeOf(bound)) { upperBounds.add(canonicalizeWildcardsInType(bound)); } } return new Types.WildcardTypeImpl(type.getLowerBounds(), upperBounds.toArray(new Type[0])); }@GwtIncompatible // java.lang.reflect @NullableDecl private static Object getJLA() { try { /* * We load sun.misc.* classes using reflection since Android doesn't support these classes and * would result in compilation failure if we directly refer to these classes. */ Class sharedSecrets = Class.forName(SHARED_SECRETS_CLASSNAME, false, null); Method langAccess = sharedSecrets.getMethod("getJavaLangAccess"); return langAccess.invoke(null); } catch (ThreadDeath death) { throw death; } catch (Throwable t) { /* * This is not one of AppEngine's allowed classes, so even in Sun JDKs, this can fail with * a NoClassDefFoundError. Other apps might deny access to sun.misc packages. */ return null; } }@CanIgnoreReturnValue static Object checkElementNotNull(Object element, int index) { if (element == null) { throw new NullPointerException("at index " + index); } return element; }static T[] toArrayImpl(Collection c, T[] array) { int size = c.size(); if (array.length < size) { array = newArray(array, size); } fillArray(c, array); if (array.length > size) { array[size] = null; } return array; }@GwtIncompatible // Array.newInstance(Class, int) public static T[] concat(T[] first, T[] second, Class type) { T[] result = newArray(type, first.length + second.length); System.arraycopy(first, 0, result, 0, first.length); System.arraycopy(second, 0, result, first.length, second.length); return result; }@Beta public static Builder builderWithExpectedSize(int expectedSize) { checkNonnegative(expectedSize, "expectedSize"); return new ImmutableList.Builder(expectedSize); }static ImmutableList asImmutableList(Object[] elements, int length) { if (length == 0) { return of(); } return new RegularImmutableList(elements, length); }static ImmutableList asImmutableList(Object[] elements) { return asImmutableList(elements, elements.length); }public static > ImmutableList sortedCopyOf( Iterable elements) { Comparable[] array = Iterables.toArray(elements, new Comparable[0]); checkElementsNotNull((Object[]) array); Arrays.sort(array); return asImmutableList(array); }private Multimap, Subscriber> findAllSubscribers(Object listener) { Multimap, Subscriber> methodsInListener = HashMultimap.create(); Class clazz = listener.getClass(); for (Method method : getAnnotatedMethods(clazz)) { Class[] parameterTypes = method.getParameterTypes(); Class eventType = parameterTypes[0]; methodsInListener.put(eventType, Subscriber.create(bus, listener, method)); } return methodsInListener; }Iterator getSubscribers(Object event) { ImmutableSet> eventTypes = flattenHierarchy(event.getClass()); List> subscriberIterators = Lists.newArrayListWithCapacity(eventTypes.size()); for (Class eventType : eventTypes) { CopyOnWriteArraySet eventSubscribers = subscribers.get(eventType); if (eventSubscribers != null) { // eager no-copy snapshot subscriberIterators.add(eventSubscribers.iterator()); } } return Iterators.concat(subscriberIterators.iterator()); }void unregister(Object listener) { Multimap, Subscriber> listenerMethods = findAllSubscribers(listener); for (Entry, Collection> entry : listenerMethods.asMap().entrySet()) { Class eventType = entry.getKey(); Collection listenerMethodsForType = entry.getValue(); CopyOnWriteArraySet currentSubscribers = subscribers.get(eventType); if (currentSubscribers == null || !currentSubscribers.removeAll(listenerMethodsForType)) { // if removeAll returns true, all we really know is that at least one subscriber was // removed... however, barring something very strange we can assume that if at least one // subscriber was removed, all subscribers on listener for that event type were... after // all, the definition of subscribers on a particular class is totally static throw new IllegalArgumentException( "missing event subscriber for an annotated method. Is " + listener + " registered?"); } // don't try to remove the set if it's empty; that can't be done safely without a lock // anyway, if the set is empty it'll just be wrapping an array of length 0 } }private Range coalescedRange(Range range, V value) { Range coalescedRange = range; Entry, RangeMapEntry> lowerEntry = entriesByLowerBound.lowerEntry(range.lowerBound); coalescedRange = coalesce(coalescedRange, value, lowerEntry); Entry, RangeMapEntry> higherEntry = entriesByLowerBound.floorEntry(range.upperBound); coalescedRange = coalesce(coalescedRange, value, higherEntry); return coalescedRange; }static ImmutableList unsafeDelegateList(List list) { switch (list.size()) { case 0: return of(); case 1: return of(list.get(0)); default: @SuppressWarnings("unchecked") List castedList = (List) list; return new RegularImmutableList(castedList); } }Segment segmentFor(int hash) { // TODO(fry): Lazily create segments? return segments[(hash >>> segmentShift) & segmentMask]; }static int rehash(int h) { // Spread bits to regularize both segment and index locations, // using variant of single-word Wang/Jenkins hash. // TODO(kevinb): use Hashing/move this to Hashing? h += (h << 15) ^ 0xffffcd7d; h ^= (h >>> 10); h += (h << 3); h ^= (h >>> 6); h += (h << 2) + (h << 14); return h ^ (h >>> 16); }private static void throwDeleteFailed(Path path, Collection exceptions) throws FileSystemException { // TODO(cgdecker): Should there be a custom exception type for this? // Also, should we try to include the Path of each file we may have failed to delete rather // than just the exceptions that occurred? FileSystemException deleteFailed = new FileSystemException( path.toString(), null, "failed to delete one or more files; see suppressed exceptions for details"); for (IOException e : exceptions) { deleteFailed.addSuppressed(e); } throw deleteFailed; }private static void checkAllowsInsecure(Path path, RecursiveDeleteOption[] options) throws InsecureRecursiveDeleteException { if (!Arrays.asList(options).contains(RecursiveDeleteOption.ALLOW_INSECURE)) { throw new InsecureRecursiveDeleteException(path.toString()); } }private static @Nullable Path getParentPath(Path path) { Path parent = path.getParent(); // Paths that have a parent: if (parent != null) { // "/foo" ("/") // "foo/bar" ("foo") // "C:\foo" ("C:\") // "\foo" ("\" - current drive for process on Windows) // "C:foo" ("C:" - working dir of drive C on Windows) return parent; } // Paths that don't have a parent: if (path.getNameCount() == 0) { // "/", "C:\", "\" (no parent) // "" (undefined, though typically parent of working dir) // "C:" (parent of working dir of drive C on Windows) // // For working dir paths ("" and "C:"), return null because: // A) it's not specified that "" is the path to the working directory. // B) if we're getting this path for recursive delete, it's typically not possible to // delete the working dir with a relative path anyway, so it's ok to fail. // C) if we're getting it for opening a new SecureDirectoryStream, there's no need to get // the parent path anyway since we can safely open a DirectoryStream to the path without // worrying about a symlink. return null; } else { // "foo" (working dir) return path.getFileSystem().getPath("."); } }@SuppressWarnings("GoodTime") // reading system time without TimeSource public static void touch(Path path) throws IOException { checkNotNull(path); try { Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis())); } catch (NoSuchFileException e) { try { Files.createFile(path); } catch (FileAlreadyExistsException ignore) { // The file didn't exist when we called setLastModifiedTime, but it did when we called // createFile, so something else created the file in between. The end result is // what we wanted: a new file that probably has its last modified time set to approximately // now. Or it could have an arbitrary last modified time set by the creator, but that's no // different than if another process set its last modified time to something else after we // created it here. } } }public static boolean equal(Path path1, Path path2) throws IOException { checkNotNull(path1); checkNotNull(path2); if (Files.isSameFile(path1, path2)) { return true; } /* * Some operating systems may return zero as the length for files denoting system-dependent * entities such as devices or pipes, in which case we must fall back on comparing the bytes * directly. */ ByteSource source1 = asByteSource(path1); ByteSource source2 = asByteSource(path2); long len1 = source1.sizeIfKnown().or(0L); long len2 = source2.sizeIfKnown().or(0L); if (len1 != 0 && len2 != 0 && len1 != len2) { return false; } return source1.contentEquals(source2); }private static boolean isDirectory( SecureDirectoryStream dir, Path name, LinkOption... options) throws IOException { return dir.getFileAttributeView(name, BasicFileAttributeView.class, options) .readAttributes() .isDirectory(); }public static ImmutableList listFiles(Path dir) throws IOException { try (DirectoryStream stream = Files.newDirectoryStream(dir)) { return ImmutableList.copyOf(stream); } catch (DirectoryIteratorException e) { throw e.getCause(); } }@GuardedBy("monitor") private void checkCurrentState(State expected) { State actual = state(); if (actual != expected) { if (actual == FAILED) { // Handle this specially so that we can include the failureCause, if there is one. throw new IllegalStateException( "Expected the service " + this + " to be " + expected + ", but the service has FAILED", failureCause()); } throw new IllegalStateException( "Expected the service " + this + " to be " + expected + ", but was " + actual); } }private static void weakHashLength32WithSeeds( byte[] bytes, int offset, long seedA, long seedB, long[] output) { long part1 = load64(bytes, offset); long part2 = load64(bytes, offset + 8); long part3 = load64(bytes, offset + 16); long part4 = load64(bytes, offset + 24); seedA += part1; seedB = rotateRight(seedB + seedA + part4, 21); long c = seedA; seedA += part2; seedA += part3; seedB += rotateRight(seedA, 44); output[0] = seedA + part4; output[1] = seedB + c; }@SuppressWarnings("unchecked") public static ImmutableSortedMap copyOfSorted(SortedMap map) { Comparator comparator = map.comparator(); if (comparator == null) { // If map has a null comparator, the keys should have a natural ordering, // even though K doesn't explicitly implement Comparable. comparator = (Comparator) NATURAL_ORDER; } if (map instanceof ImmutableSortedMap) { // TODO(kevinb): Prove that this cast is safe, even though // Collections.unmodifiableSortedMap requires the same key type. @SuppressWarnings("unchecked") ImmutableSortedMap kvMap = (ImmutableSortedMap) map; if (!kvMap.isPartialView()) { return kvMap; } } return fromEntries(comparator, true, map.entrySet()); }@SuppressWarnings("unchecked") public static , V> ImmutableSortedMap of( K k1, V v1, K k2, V v2) { return ofEntries(entryOf(k1, v1), entryOf(k2, v2)); }public static , V> ImmutableSortedMap of(K k1, V v1) { return of(Ordering.natural(), k1, v1); }@SuppressWarnings("unchecked") // unsafe, comparator() returns a comparator on the specified type // TODO(kevinb): evaluate whether or not of().comparator() should return null public static ImmutableSortedMap of() { return (ImmutableSortedMap) NATURAL_EMPTY_MAP; }public static void startFinalizer( Class finalizableReferenceClass, ReferenceQueue queue, PhantomReference frqReference) { /* * We use FinalizableReference.class for two things: * * 1) To invoke FinalizableReference.finalizeReferent() * * 2) To detect when FinalizableReference's class loader has to be garbage collected, at which * point, Finalizer can stop running */ if (!finalizableReferenceClass.getName().equals(FINALIZABLE_REFERENCE)) { throw new IllegalArgumentException("Expected " + FINALIZABLE_REFERENCE + "."); } Finalizer finalizer = new Finalizer(finalizableReferenceClass, queue, frqReference); String threadName = Finalizer.class.getName(); Thread thread = null; if (bigThreadConstructor != null) { try { boolean inheritThreadLocals = false; long defaultStackSize = 0; thread = bigThreadConstructor.newInstance( (ThreadGroup) null, finalizer, threadName, defaultStackSize, inheritThreadLocals); } catch (Throwable t) { logger.log( Level.INFO, "Failed to create a thread without inherited thread-local values", t); } } if (thread == null) { thread = new Thread((ThreadGroup) null, finalizer, threadName); } thread.setDaemon(true); try { if (inheritableThreadLocals != null) { inheritableThreadLocals.set(thread, null); } } catch (Throwable t) { logger.log( Level.INFO, "Failed to clear thread local values inherited by reference finalizer thread.", t); } thread.start(); }public static Comparator> lexicographical(Comparator comparator) { return new LexicographicalOrdering(checkNotNull(comparator)); }public ValueGraphBuilder expectedNodeCount(int expectedNodeCount) { this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount)); return this; }public static > ImmutableSortedSet of(E element) { return new RegularImmutableSortedSet(ImmutableList.of(element), Ordering.natural()); }public static HashFunction concatenating( HashFunction first, HashFunction second, HashFunction... rest) { // We can't use Lists.asList() here because there's no hash->collect dependency List list = new ArrayList<>(); list.add(first); list.add(second); list.addAll(Arrays.asList(rest)); return new ConcatenatedHashFunction(list.toArray(new HashFunction[0])); }public static , V> ImmutableRangeMap of(Range range, V value) { return new ImmutableRangeMap<>(ImmutableList.of(range), ImmutableList.of(value)); }@SuppressWarnings("unchecked") public static , V> ImmutableRangeMap of() { return (ImmutableRangeMap) EMPTY; }public boolean contentEquals(ByteSource other) throws IOException { checkNotNull(other); byte[] buf1 = createBuffer(); byte[] buf2 = createBuffer(); Closer closer = Closer.create(); try { InputStream in1 = closer.register(openStream()); InputStream in2 = closer.register(other.openStream()); while (true) { int read1 = ByteStreams.read(in1, buf1, 0, buf1.length); int read2 = ByteStreams.read(in2, buf2, 0, buf2.length); if (read1 != read2 || !Arrays.equals(buf1, buf2)) { return false; } else if (read1 != buf1.length) { return true; } } } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }public HashCode hash(HashFunction hashFunction) throws IOException { Hasher hasher = hashFunction.newHasher(); copyTo(Funnels.asOutputStream(hasher)); return hasher.hash(); }public byte[] read() throws IOException { Closer closer = Closer.create(); try { InputStream in = closer.register(openStream()); Optional size = sizeIfKnown(); return size.isPresent() ? ByteStreams.toByteArray(in, size.get()) : ByteStreams.toByteArray(in); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }private long countBySkipping(InputStream in) throws IOException { long count = 0; long skipped; while ((skipped = skipUpTo(in, Integer.MAX_VALUE)) > 0) { count += skipped; } return count; }@Override public ImmutableCollection> entries() { return (ImmutableCollection>) super.entries(); }public static ImmutableMultimap of(K k1, V v1, K k2, V v2) { return ImmutableListMultimap.of(k1, v1, k2, v2); }@GwtIncompatible // Array.newArray(Class, int) public final E[] toArray(Class type) { return Iterables.toArray(getDelegate(), type); }@Beta public static FluentIterable of() { return FluentIterable.from(ImmutableList.of()); }private static FluentIterable concatNoDefensiveCopy( final Iterable... inputs) { for (Iterable input : inputs) { checkNotNull(input); } return new FluentIterable() { @Override public Iterator iterator() { return Iterators.concat( /* lazily generate the iterators on each input only as needed */ new AbstractIndexedListIterator>(inputs.length) { @Override public Iterator get(int i) { return inputs[i].iterator(); } }); } }; }private void removeValuesForKey(Object key) { Collection collection = Maps.safeRemove(map, key); if (collection != null) { int count = collection.size(); collection.clear(); totalSize -= count; } }final void setMap(Map> map) { this.map = map; totalSize = 0; for (Collection values : map.values()) { checkArgument(!values.isEmpty()); totalSize += values.size(); } }static TypeResolver invariantly(Type contextType) { Type invariantContext = WildcardCapturer.INSTANCE.capture(contextType); return new TypeResolver().where(TypeMappingIntrospector.getTypeMappings(invariantContext)); }static StringBuilder newStringBuilderForCollection(int size) { checkNonnegative(size, "size"); return new StringBuilder((int) Math.min(size * 8L, Ints.MAX_POWER_OF_TWO)); }@Deprecated public final FluentIterable preOrderTraversal(final T root) { checkNotNull(root); return new FluentIterable() { @Override public UnmodifiableIterator iterator() { return preOrderIterator(root); } @Override public void forEach(Consumer action) { checkNotNull(action); new Consumer() { @Override public void accept(T t) { action.accept(t); children(t).forEach(this); } }.accept(root); } }; }private static boolean retainOccurrencesImpl( Multiset multisetToModify, Multiset occurrencesToRetain) { checkNotNull(multisetToModify); checkNotNull(occurrencesToRetain); // Avoiding ConcurrentModificationExceptions is tricky. Iterator> entryIterator = multisetToModify.entrySet().iterator(); boolean changed = false; while (entryIterator.hasNext()) { Entry entry = entryIterator.next(); int retainCount = occurrencesToRetain.count(entry.getElement()); if (retainCount == 0) { entryIterator.remove(); changed = true; } else if (retainCount < entry.getCount()) { multisetToModify.setCount(entry.getElement(), retainCount); changed = true; } } return changed; }public static > Builder reverseOrder() { return new Builder(Ordering.natural().reverse()); }public static > ImmutableSortedMultiset of(E element) { RegularImmutableSortedSet elementSet = (RegularImmutableSortedSet) ImmutableSortedSet.of(element); long[] cumulativeCounts = {0, 1}; return new RegularImmutableSortedMultiset(elementSet, cumulativeCounts, 0, 1); }static RegularImmutableTable forOrderedComponents( ImmutableList> cellList, ImmutableSet rowSpace, ImmutableSet columnSpace) { // use a dense table if more than half of the cells have values // TODO(gak): tune this condition based on empirical evidence return (cellList.size() > (((long) rowSpace.size() * columnSpace.size()) / 2)) ? new DenseImmutableTable(cellList, rowSpace, columnSpace) : new SparseImmutableTable(cellList, rowSpace, columnSpace); }@SuppressWarnings("unchecked") // implementation is "fully variant" public static Converter identity() { return (IdentityConverter) IdentityConverter.INSTANCE; }public static ImmutableTable copyOf( Table table) { if (table instanceof ImmutableTable) { @SuppressWarnings("unchecked") ImmutableTable parameterizedTable = (ImmutableTable) table; return parameterizedTable; } else { return copyOf(table.cellSet()); } }public static ImmutableTable of(R rowKey, C columnKey, V value) { return new SingletonImmutableTable<>(rowKey, columnKey, value); }@SuppressWarnings("unchecked") public static ImmutableTable of() { return (ImmutableTable) SparseImmutableTable.EMPTY; }@VisibleForTesting static int chooseTableSize(int setSize) { setSize = Math.max(setSize, 2); // Correct the size for open addressing to match desired load factor. if (setSize < CUTOFF) { // Round up to the next highest power of 2. int tableSize = Integer.highestOneBit(setSize - 1) << 1; while (tableSize * DESIRED_LOAD_FACTOR < setSize) { tableSize <<= 1; } return tableSize; } // The table can't be completely full or we'll get infinite reprobes checkArgument(setSize < MAX_TABLE_SIZE, "collection too large"); return MAX_TABLE_SIZE; }static Object[] rebuildHashTable(int newTableSize, Object[] elements, int n) { Object[] hashTable = new Object[newTableSize]; int mask = hashTable.length - 1; for (int i = 0; i < n; i++) { Object e = elements[i]; int j0 = Hashing.smear(e.hashCode()); for (int j = j0; ; j++) { int index = j & mask; if (hashTable[index] == null) { hashTable[index] = e; break; } } } return hashTable; }static double calculateNewMeanNonFinite(double previousMean, double value) { /* * Desired behaviour is to match the results of applying the naive mean formula. In particular, * the update formula can subtract infinities in cases where the naive formula would add them. * * Consequently: * 1. If the previous mean is finite and the new value is non-finite then the new mean is that * value (whether it is NaN or infinity). * 2. If the new value is finite and the previous mean is non-finite then the mean is unchanged * (whether it is NaN or infinity). * 3. If both the previous mean and the new value are non-finite and... * 3a. ...either or both is NaN (so mean != value) then the new mean is NaN. * 3b. ...they are both the same infinities (so mean == value) then the mean is unchanged. * 3c. ...they are different infinities (so mean != value) then the new mean is NaN. */ if (isFinite(previousMean)) { // This is case 1. return value; } else if (isFinite(value) || previousMean == value) { // This is case 2. or 3b. return previousMean; } else { // This is case 3a. or 3c. return NaN; } }public void add(double value) { if (count == 0) { count = 1; mean = value; min = value; max = value; if (!isFinite(value)) { sumOfSquaresOfDeltas = NaN; } } else { count++; if (isFinite(value) && isFinite(mean)) { // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) and (16) double delta = value - mean; mean += delta / count; sumOfSquaresOfDeltas += delta * (value - mean); } else { mean = calculateNewMeanNonFinite(mean, value); sumOfSquaresOfDeltas = NaN; } min = Math.min(min, value); max = Math.max(max, value); } }void allocArrays() { Preconditions.checkState(needsAllocArrays(), "Arrays already allocated"); int expectedSize = modCount; int buckets = Hashing.closedTableSize(expectedSize, LOAD_FACTOR); this.table = newTable(buckets); this.entries = newEntries(expectedSize); this.keys = new Object[expectedSize]; this.values = new Object[expectedSize]; }public Cache build() { checkWeightWithWeigher(); checkNonLoadingCache(); return new LocalCache.LocalManualCache<>(this); }public CacheBuilder concurrencyLevel(int concurrencyLevel) { checkState( this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s", this.concurrencyLevel); checkArgument(concurrencyLevel > 0); this.concurrencyLevel = concurrencyLevel; return this; }private static char[] growBuffer(char[] dest, int index, int size) { if (size < 0) { // overflow - should be OutOfMemoryError but GWT/j2cl don't support it throw new AssertionError("Cannot increase internal buffer any further"); } char[] copy = new char[size]; if (index > 0) { System.arraycopy(dest, 0, copy, 0, index); } return copy; }@Override public String escape(String string) { checkNotNull(string); // GWT specific check (do not optimize) // Inlineable fast-path loop which hands off to escapeSlow() only if needed int length = string.length(); for (int index = 0; index < length; index++) { if (escape(string.charAt(index)) != null) { return escapeSlow(string, index); } } return string; }static boolean removeAllImpl(Set set, Iterator iterator) { boolean changed = false; while (iterator.hasNext()) { changed |= set.remove(iterator.next()); } return changed; }final Type capture() { Type superclass = getClass().getGenericSuperclass(); checkArgument(superclass instanceof ParameterizedType, "%s isn't parameterized", superclass); return ((ParameterizedType) superclass).getActualTypeArguments()[0]; }public static MediaType parse(String input) { checkNotNull(input); Tokenizer tokenizer = new Tokenizer(input); try { String type = tokenizer.consumeToken(TOKEN_MATCHER); tokenizer.consumeCharacter('/'); String subtype = tokenizer.consumeToken(TOKEN_MATCHER); ImmutableListMultimap.Builder parameters = ImmutableListMultimap.builder(); while (tokenizer.hasMore()) { tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE); tokenizer.consumeCharacter(';'); tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE); String attribute = tokenizer.consumeToken(TOKEN_MATCHER); tokenizer.consumeCharacter('='); final String value; if ('"' == tokenizer.previewChar()) { tokenizer.consumeCharacter('"'); StringBuilder valueBuilder = new StringBuilder(); while ('"' != tokenizer.previewChar()) { if ('\\' == tokenizer.previewChar()) { tokenizer.consumeCharacter('\\'); valueBuilder.append(tokenizer.consumeCharacter(ascii())); } else { valueBuilder.append(tokenizer.consumeToken(QUOTED_TEXT_MATCHER)); } } value = valueBuilder.toString(); tokenizer.consumeCharacter('"'); } else { value = tokenizer.consumeToken(TOKEN_MATCHER); } parameters.put(attribute, value); } return create(type, subtype, parameters.build()); } catch (IllegalStateException e) { throw new IllegalArgumentException("Could not parse '" + input + "'", e); } }public static MediaType create(String type, String subtype) { MediaType mediaType = create(type, subtype, ImmutableListMultimap.of()); mediaType.parsedCharset = Optional.absent(); return mediaType; }static int load32(byte[] source, int offset) { // TODO(user): Measure the benefit of delegating this to LittleEndianBytes also. return (source[offset] & 0xFF) | ((source[offset + 1] & 0xFF) << 8) | ((source[offset + 2] & 0xFF) << 16) | ((source[offset + 3] & 0xFF) << 24); }static void store64(byte[] sink, int offset, long value) { // We don't want to assert in production code. assert offset >= 0 && offset + 8 <= sink.length; // Delegates to the fast (unsafe)version or the fallback. byteArray.putLongLittleEndian(sink, offset, value); }static long load64Safely(byte[] input, int offset, int length) { long result = 0; // Due to the way we shift, we can stop iterating once we've run out of data, the rest // of the result already being filled with zeros. // This loop is critical to performance, so please check HashBenchmark if altering it. int limit = Math.min(length, 8); for (int i = 0; i < limit; i++) { // Shift value left while iterating logically through the array. result |= (input[offset + i] & 0xFFL) << (i * 8); } return result; }public void execute() { // Lock while we update our state so the add method above will finish adding any listeners // before we start to run them. RunnableExecutorPair list; synchronized (this) { if (executed) { return; } executed = true; list = runnables; runnables = null; // allow GC to free listeners even if this stays around for a while. } // If we succeeded then list holds all the runnables we to execute. The pairs in the stack are // in the opposite order from how they were added so we need to reverse the list to fulfill our // contract. // This is somewhat annoying, but turns out to be very fast in practice. Alternatively, we could // drop the contract on the method that enforces this queue like behavior since depending on it // is likely to be a bug anyway. // N.B. All writes to the list and the next pointers must have happened before the above // synchronized block, so we can iterate the list without the lock held here. RunnableExecutorPair reversedList = null; while (list != null) { RunnableExecutorPair tmp = list; list = list.next; tmp.next = reversedList; reversedList = tmp; } while (reversedList != null) { executeListener(reversedList.runnable, reversedList.executor); reversedList = reversedList.next; } }public void write(CharSequence charSequence) throws IOException { checkNotNull(charSequence); Closer closer = Closer.create(); try { Writer out = closer.register(openStream()); out.append(charSequence); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }@Beta @CanIgnoreReturnValue @GwtIncompatible // concurrency @SuppressWarnings("GoodTime") // should accept a java.time.Duration public static boolean shutdownAndAwaitTermination( ExecutorService service, long timeout, TimeUnit unit) { long halfTimeoutNanos = unit.toNanos(timeout) / 2; // Disable new tasks from being submitted service.shutdown(); try { // Wait for half the duration of the timeout for existing tasks to terminate if (!service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS)) { // Cancel currently executing tasks service.shutdownNow(); // Wait the other half of the timeout for tasks to respond to being cancelled service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS); } } catch (InterruptedException ie) { // Preserve interrupt status Thread.currentThread().interrupt(); // (Re-)Cancel if current thread also interrupted service.shutdownNow(); } return service.isTerminated(); }@GuardedBy("lock") private boolean awaitNanos(Guard guard, long nanos, boolean signalBeforeWaiting) throws InterruptedException { boolean firstTime = true; try { do { if (nanos <= 0L) { return false; } if (firstTime) { if (signalBeforeWaiting) { signalNextWaiter(); } beginWaitingFor(guard); firstTime = false; } nanos = guard.condition.awaitNanos(nanos); } while (!guard.isSatisfied()); return true; } finally { if (!firstTime) { endWaitingFor(guard); } } }@GuardedBy("lock") private void endWaitingFor(Guard guard) { int waiters = --guard.waiterCount; if (waiters == 0) { // unlink guard from activeGuards for (Guard p = activeGuards, pred = null; ; pred = p, p = p.next) { if (p == guard) { if (pred == null) { activeGuards = p.next; } else { pred.next = p.next; } p.next = null; // help GC break; } } } }@GuardedBy("lock") private void beginWaitingFor(Guard guard) { int waiters = guard.waiterCount++; if (waiters == 0) { // push guard onto activeGuards guard.next = activeGuards; activeGuards = guard; } }@GuardedBy("lock") private void signalAllWaiters() { for (Guard guard = activeGuards; guard != null; guard = guard.next) { guard.condition.signalAll(); } }@GuardedBy("lock") private void signalNextWaiter() { for (Guard guard = activeGuards; guard != null; guard = guard.next) { if (isSatisfied(guard)) { guard.condition.signal(); break; } } }public int getWaitQueueLength(Guard guard) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } lock.lock(); try { return guard.waiterCount; } finally { lock.unlock(); } }@SuppressWarnings("GoodTime") // should accept a java.time.Duration public boolean waitForUninterruptibly(Guard guard, long time, TimeUnit unit) { final long timeoutNanos = toSafeNanos(time, unit); if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } if (guard.isSatisfied()) { return true; } boolean signalBeforeWaiting = true; final long startTime = initNanoTime(timeoutNanos); boolean interrupted = Thread.interrupted(); try { for (long remainingNanos = timeoutNanos; ; ) { try { return awaitNanos(guard, remainingNanos, signalBeforeWaiting); } catch (InterruptedException interrupt) { interrupted = true; if (guard.isSatisfied()) { return true; } signalBeforeWaiting = false; remainingNanos = remainingNanos(startTime, timeoutNanos); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }public void waitForUninterruptibly(Guard guard) { if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } if (!guard.isSatisfied()) { awaitUninterruptibly(guard, true); } }public void waitFor(Guard guard) throws InterruptedException { if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } if (!guard.isSatisfied()) { await(guard, true); } }public boolean tryEnterIf(Guard guard) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; if (!lock.tryLock()) { return false; } boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } }public boolean enterIfInterruptibly(Guard guard) throws InterruptedException { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; lock.lockInterruptibly(); boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } }@SuppressWarnings("GoodTime") // should accept a java.time.Duration public boolean enterIf(Guard guard, long time, TimeUnit unit) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } if (!enter(time, unit)) { return false; } boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } }public boolean enterIf(Guard guard) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; lock.lock(); boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } }public void enterWhenUninterruptibly(Guard guard) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); lock.lock(); boolean satisfied = false; try { if (!guard.isSatisfied()) { awaitUninterruptibly(guard, signalBeforeWaiting); } satisfied = true; } finally { if (!satisfied) { leave(); } } }@SuppressWarnings("GoodTime") // should accept a java.time.Duration public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException { final long timeoutNanos = toSafeNanos(time, unit); if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; boolean reentrant = lock.isHeldByCurrentThread(); long startTime = 0L; locked: { if (!fair) { // Check interrupt status to get behavior consistent with fair case. if (Thread.interrupted()) { throw new InterruptedException(); } if (lock.tryLock()) { break locked; } } startTime = initNanoTime(timeoutNanos); if (!lock.tryLock(time, unit)) { return false; } } boolean satisfied = false; boolean threw = true; try { satisfied = guard.isSatisfied() || awaitNanos( guard, (startTime == 0L) ? timeoutNanos : remainingNanos(startTime, timeoutNanos), reentrant); threw = false; return satisfied; } finally { if (!satisfied) { try { // Don't need to signal if timed out, but do if interrupted if (threw && !reentrant) { signalNextWaiter(); } } finally { lock.unlock(); } } } }public void enterWhen(Guard guard) throws InterruptedException { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); lock.lockInterruptibly(); boolean satisfied = false; try { if (!guard.isSatisfied()) { await(guard, signalBeforeWaiting); } satisfied = true; } finally { if (!satisfied) { leave(); } } }@SuppressWarnings("GoodTime") // should accept a java.time.Duration public boolean enterInterruptibly(long time, TimeUnit unit) throws InterruptedException { return lock.tryLock(time, unit); }@SuppressWarnings("GoodTime") // should accept a java.time.Duration public boolean enter(long time, TimeUnit unit) { final long timeoutNanos = toSafeNanos(time, unit); final ReentrantLock lock = this.lock; if (!fair && lock.tryLock()) { return true; } boolean interrupted = Thread.interrupted(); try { final long startTime = System.nanoTime(); for (long remainingNanos = timeoutNanos; ; ) { try { return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS); } catch (InterruptedException interrupt) { interrupted = true; remainingNanos = remainingNanos(startTime, timeoutNanos); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }public static > ElementOrder natural() { return new ElementOrder(Type.SORTED, Ordering.natural()); }private static HashCode fmix(int h1, int length) { h1 ^= length; h1 ^= h1 >>> 16; h1 *= 0x85ebca6b; h1 ^= h1 >>> 13; h1 *= 0xc2b2ae35; h1 ^= h1 >>> 16; return HashCode.fromInt(h1); }private int calculateNewCapacity() { int oldCapacity = queue.length; int newCapacity = (oldCapacity < 64) ? (oldCapacity + 1) * 2 : IntMath.checkedMultiply(oldCapacity / 2, 3); return capAtMaximumSize(newCapacity, maximumSize); }public static > MinMaxPriorityQueue create( Iterable initialContents) { return new Builder(Ordering.natural()).create(initialContents); }@CanIgnoreReturnValue @Deprecated @Override public V forcePut(K key, V value) { throw new UnsupportedOperationException(); }@Beta public static Builder builderWithExpectedSize(int expectedSize) { checkNonnegative(expectedSize, "expectedSize"); return new Builder<>(expectedSize); }@Beta @Deprecated public static String readFirstLine(File file, Charset charset) throws IOException { return asCharSource(file, charset).readFirstLine(); }@Beta @SuppressWarnings("GoodTime") // reading system time without TimeSource public static void touch(File file) throws IOException { checkNotNull(file); if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) { throw new IOException("Unable to update modification time of " + file); } }@Beta public static void copy(File from, File to) throws IOException { checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to); asByteSource(from).copyTo(asByteSink(to)); }@Beta public static void copy(File from, OutputStream to) throws IOException { asByteSource(from).copyTo(to); }@Beta public static void write(byte[] from, File to) throws IOException { asByteSink(to).write(from); }@Beta public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException { checkNotNull(file); checkNotNull(charset); return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset)); }public static InetAddress decrement(InetAddress address) { byte[] addr = address.getAddress(); int i = addr.length - 1; while (i >= 0 && addr[i] == (byte) 0x00) { addr[i] = (byte) 0xff; i--; } checkArgument(i >= 0, "Decrementing %s would wrap.", address); addr[i]--; return bytesToInetAddress(addr); }public static boolean isMappedIPv4Address(String ipString) { byte[] bytes = ipStringToBytes(ipString); if (bytes != null && bytes.length == 16) { for (int i = 0; i < 10; i++) { if (bytes[i] != 0) { return false; } } for (int i = 10; i < 12; i++) { if (bytes[i] != (byte) 0xff) { return false; } } return true; } return false; }public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) { if (isCompatIPv4Address(ip)) { return getCompatIPv4Address(ip); } if (is6to4Address(ip)) { return get6to4IPv4Address(ip); } if (isTeredoAddress(ip)) { return getTeredoInfo(ip).getClient(); } throw formatIllegalArgumentException("'%s' has no embedded IPv4 address.", toAddrString(ip)); }public static Inet4Address getIsatapIPv4Address(Inet6Address ip) { checkArgument(isIsatapAddress(ip), "Address '%s' is not an ISATAP address.", toAddrString(ip)); return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16)); }public static boolean isIsatapAddress(Inet6Address ip) { // If it's a Teredo address with the right port (41217, or 0xa101) // which would be encoded as 0x5efe then it can't be an ISATAP address. if (isTeredoAddress(ip)) { return false; } byte[] bytes = ip.getAddress(); if ((bytes[8] | (byte) 0x03) != (byte) 0x03) { // Verify that high byte of the 64 bit identifier is zero, modulo // the U/L and G bits, with which we are not concerned. return false; } return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e) && (bytes[11] == (byte) 0xfe); }public static boolean isTeredoAddress(Inet6Address ip) { byte[] bytes = ip.getAddress(); return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x01) && (bytes[2] == 0) && (bytes[3] == 0); }public static Inet4Address getCompatIPv4Address(Inet6Address ip) { checkArgument( isCompatIPv4Address(ip), "Address '%s' is not IPv4-compatible.", toAddrString(ip)); return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16)); }public static boolean isCompatIPv4Address(Inet6Address ip) { if (!ip.isIPv4CompatibleAddress()) { return false; } byte[] bytes = ip.getAddress(); if ((bytes[12] == 0) && (bytes[13] == 0) && (bytes[14] == 0) && ((bytes[15] == 0) || (bytes[15] == 1))) { return false; } return true; }public static InetAddress forUriString(String hostAddr) { InetAddress addr = forUriStringNoThrow(hostAddr); if (addr == null) { throw formatIllegalArgumentException("Not a valid URI IP literal: '%s'", hostAddr); } return addr; }private static String hextetsToIPv6String(int[] hextets) { // While scanning the array, handle these state transitions: // start->num => "num" start->gap => "::" // num->num => ":num" num->gap => "::" // gap->num => "num" gap->gap => "" StringBuilder buf = new StringBuilder(39); boolean lastWasNumber = false; for (int i = 0; i < hextets.length; i++) { boolean thisIsNumber = hextets[i] >= 0; if (thisIsNumber) { if (lastWasNumber) { buf.append(':'); } buf.append(Integer.toHexString(hextets[i])); } else { if (i == 0 || lastWasNumber) { buf.append("::"); } } lastWasNumber = thisIsNumber; } return buf.toString(); }private static void compressLongestRunOfZeroes(int[] hextets) { int bestRunStart = -1; int bestRunLength = -1; int runStart = -1; for (int i = 0; i < hextets.length + 1; i++) { if (i < hextets.length && hextets[i] == 0) { if (runStart < 0) { runStart = i; } } else if (runStart >= 0) { int runLength = i - runStart; if (runLength > bestRunLength) { bestRunStart = runStart; bestRunLength = runLength; } runStart = -1; } } if (bestRunLength >= 2) { Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1); } }private static InetAddress bytesToInetAddress(byte[] addr) { try { return InetAddress.getByAddress(addr); } catch (UnknownHostException e) { throw new AssertionError(e); } }private void resizeMeMaybe(int newSize) { int entriesSize = entries.length; if (newSize > entriesSize) { int newCapacity = entriesSize + Math.max(1, entriesSize >>> 1); if (newCapacity < 0) { newCapacity = Integer.MAX_VALUE; } if (newCapacity != entriesSize) { resizeEntries(newCapacity); } } }@CanIgnoreReturnValue @Override public int add(E element, int occurrences) { checkNotNull(element); if (occurrences == 0) { return count(element); } CollectPreconditions.checkPositive(occurrences, "occurences"); while (true) { AtomicInteger existingCounter = Maps.safeGet(countMap, element); if (existingCounter == null) { existingCounter = countMap.putIfAbsent(element, new AtomicInteger(occurrences)); if (existingCounter == null) { return 0; } // existingCounter != null: fall through to operate against the existing AtomicInteger } while (true) { int oldValue = existingCounter.get(); if (oldValue != 0) { try { int newValue = IntMath.checkedAdd(oldValue, occurrences); if (existingCounter.compareAndSet(oldValue, newValue)) { // newValue can't == 0, so no need to check & remove return oldValue; } } catch (ArithmeticException overflow) { throw new IllegalArgumentException( "Overflow adding " + occurrences + " occurrences to a count of " + oldValue); } } else { // In the case of a concurrent remove, we might observe a zero value, which means another // thread is about to remove (element, existingCounter) from the map. Rather than wait, // we can just do that work here. AtomicInteger newCounter = new AtomicInteger(occurrences); if ((countMap.putIfAbsent(element, newCounter) == null) || countMap.replace(element, existingCounter, newCounter)) { return 0; } break; } } // If we're still here, there was a race, so just try again. } }@CanIgnoreReturnValue public Stopwatch start() { checkState(!isRunning, "This stopwatch is already running."); isRunning = true; startTick = ticker.read(); return this; }static FieldSetter getFieldSetter(final Class clazz, String fieldName) { try { Field field = clazz.getDeclaredField(fieldName); return new FieldSetter(field); } catch (NoSuchFieldException e) { throw new AssertionError(e); // programmer error } }static void writeMultiset(Multiset multiset, ObjectOutputStream stream) throws IOException { int entryCount = multiset.entrySet().size(); stream.writeInt(entryCount); for (Multiset.Entry entry : multiset.entrySet()) { stream.writeObject(entry.getElement()); stream.writeInt(entry.getCount()); } }static void writeMap(Map map, ObjectOutputStream stream) throws IOException { stream.writeInt(map.size()); for (Map.Entry entry : map.entrySet()) { stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } }@Override @CanIgnoreReturnValue public int read(byte[] bytes, int off, int len) throws IOException { int numOfBytesRead = in.read(bytes, off, len); if (numOfBytesRead != -1) { hasher.putBytes(bytes, off, numOfBytesRead); } return numOfBytesRead; }@Override @CanIgnoreReturnValue public int read() throws IOException { int b = in.read(); if (b != -1) { hasher.putByte((byte) b); } return b; }public ImmutableIntArray subArray(int startIndex, int endIndex) { Preconditions.checkPositionIndexes(startIndex, endIndex, length()); return startIndex == endIndex ? EMPTY : new ImmutableIntArray(array, start + startIndex, start + endIndex); }public static ImmutableIntArray of(int first, int... rest) { checkArgument( rest.length <= Integer.MAX_VALUE - 1, "the total number of elements must fit in an int"); int[] array = new int[rest.length + 1]; array[0] = first; System.arraycopy(rest, 0, array, 1, rest.length); return new ImmutableIntArray(array); }public Joiner skipNulls() { return new Joiner(this) { @Override public A appendTo(A appendable, Iterator parts) throws IOException { checkNotNull(appendable, "appendable"); checkNotNull(parts, "parts"); while (parts.hasNext()) { Object part = parts.next(); if (part != null) { appendable.append(Joiner.this.toString(part)); break; } } while (parts.hasNext()) { Object part = parts.next(); if (part != null) { appendable.append(separator); appendable.append(Joiner.this.toString(part)); } } return appendable; } @Override public Joiner useForNull(String nullText) { throw new UnsupportedOperationException("already specified skipNulls"); } @Override public MapJoiner withKeyValueSeparator(String kvs) { throw new UnsupportedOperationException("can't use .skipNulls() with maps"); } }; }CacheBuilder toCacheBuilder() { CacheBuilder builder = CacheBuilder.newBuilder(); if (initialCapacity != null) { builder.initialCapacity(initialCapacity); } if (maximumSize != null) { builder.maximumSize(maximumSize); } if (maximumWeight != null) { builder.maximumWeight(maximumWeight); } if (concurrencyLevel != null) { builder.concurrencyLevel(concurrencyLevel); } if (keyStrength != null) { switch (keyStrength) { case WEAK: builder.weakKeys(); break; default: throw new AssertionError(); } } if (valueStrength != null) { switch (valueStrength) { case SOFT: builder.softValues(); break; case WEAK: builder.weakValues(); break; default: throw new AssertionError(); } } if (recordStats != null && recordStats) { builder.recordStats(); } if (writeExpirationTimeUnit != null) { builder.expireAfterWrite(writeExpirationDuration, writeExpirationTimeUnit); } if (accessExpirationTimeUnit != null) { builder.expireAfterAccess(accessExpirationDuration, accessExpirationTimeUnit); } if (refreshTimeUnit != null) { builder.refreshAfterWrite(refreshDuration, refreshTimeUnit); } return builder; }public static CacheBuilderSpec parse(String cacheBuilderSpecification) { CacheBuilderSpec spec = new CacheBuilderSpec(cacheBuilderSpecification); if (!cacheBuilderSpecification.isEmpty()) { for (String keyValuePair : KEYS_SPLITTER.split(cacheBuilderSpecification)) { List keyAndValue = ImmutableList.copyOf(KEY_VALUE_SPLITTER.split(keyValuePair)); checkArgument(!keyAndValue.isEmpty(), "blank key-value pair"); checkArgument( keyAndValue.size() <= 2, "key-value pair %s with more than one equals sign", keyValuePair); // Find the ValueParser for the current key. String key = keyAndValue.get(0); ValueParser valueParser = VALUE_PARSERS.get(key); checkArgument(valueParser != null, "unknown key %s", key); String value = keyAndValue.size() == 1 ? null : keyAndValue.get(1); valueParser.parse(spec, key, value); } } return spec; }public void write(byte[] bytes) throws IOException { checkNotNull(bytes); Closer closer = Closer.create(); try { OutputStream out = closer.register(openStream()); out.write(bytes); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }static void clear(Iterator iterator) { checkNotNull(iterator); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } }static Iterator concatNoDefensiveCopy(Iterator... inputs) { for (Iterator input : checkNotNull(inputs)) { checkNotNull(input); } return concat(consumingForArray(inputs)); }private static Iterator consumingForArray(final T... elements) { return new UnmodifiableIterator() { int index = 0; @Override public boolean hasNext() { return index < elements.length; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } T result = elements[index]; elements[index] = null; index++; return result; } }; }static Function, Iterator> toIterator() { return new Function, Iterator>() { @Override public Iterator apply(Iterable iterable) { return iterable.iterator(); } }; }public static boolean isEmpty(Iterable iterable) { if (iterable instanceof Collection) { return ((Collection) iterable).isEmpty(); } return !iterable.iterator().hasNext(); }@GwtIncompatible // Array.newInstance(Class, int) public static T[] toArray(Iterable iterable, Class type) { return toArray(iterable, ObjectArrays.newArray(type, 0)); }private void startDraining(boolean overflow) { byteBuffer.flip(); if (overflow && byteBuffer.remaining() == 0) { byteBuffer = ByteBuffer.allocate(byteBuffer.capacity() * 2); } else { draining = true; } }private void readMoreChars() throws IOException { // Possibilities: // 1) array has space available on right hand side (between limit and capacity) // 2) array has space available on left hand side (before position) // 3) array has no space available // // In case 2 we shift the existing chars to the left, and in case 3 we create a bigger // array, then they both become case 1. if (availableCapacity(charBuffer) == 0) { if (charBuffer.position() > 0) { // (2) There is room in the buffer. Move existing bytes to the beginning. charBuffer.compact().flip(); } else { // (3) Entire buffer is full, need bigger buffer. charBuffer = grow(charBuffer); } } // (1) Read more characters into free space at end of array. int limit = charBuffer.limit(); int numChars = reader.read(charBuffer.array(), limit, availableCapacity(charBuffer)); if (numChars == -1) { endOfInput = true; } else { charBuffer.limit(limit + numChars); } }private static CharBuffer grow(CharBuffer buf) { char[] copy = Arrays.copyOf(buf.array(), buf.capacity() * 2); CharBuffer bigger = CharBuffer.wrap(copy); bigger.position(buf.position()); bigger.limit(buf.limit()); return bigger; }@Override public int read(byte[] b, int off, int len) throws IOException { // Obey InputStream contract. checkPositionIndexes(off, off + len, b.length); if (len == 0) { return 0; } // The rest of this method implements the process described by the CharsetEncoder javadoc. int totalBytesRead = 0; boolean doneEncoding = endOfInput; DRAINING: while (true) { // We stay in draining mode until there are no bytes left in the output buffer. Then we go // back to encoding/flushing. if (draining) { totalBytesRead += drain(b, off + totalBytesRead, len - totalBytesRead); if (totalBytesRead == len || doneFlushing) { return (totalBytesRead > 0) ? totalBytesRead : -1; } draining = false; byteBuffer.clear(); } while (true) { // We call encode until there is no more input. The last call to encode will have endOfInput // == true. Then there is a final call to flush. CoderResult result; if (doneFlushing) { result = CoderResult.UNDERFLOW; } else if (doneEncoding) { result = encoder.flush(byteBuffer); } else { result = encoder.encode(charBuffer, byteBuffer, endOfInput); } if (result.isOverflow()) { // Not enough room in output buffer--drain it, creating a bigger buffer if necessary. startDraining(true); continue DRAINING; } else if (result.isUnderflow()) { // If encoder underflows, it means either: // a) the final flush() succeeded; next drain (then done) // b) we encoded all of the input; next flush // c) we ran of out input to encode; next read more input if (doneEncoding) { // (a) doneFlushing = true; startDraining(false); continue DRAINING; } else if (endOfInput) { // (b) doneEncoding = true; } else { // (c) readMoreChars(); } } else if (result.isError()) { // Only reach here if a CharsetEncoder with non-REPLACE settings is used. result.throwException(); return 0; // Not called. } } } }public ImmutableList readLines() throws IOException { Closer closer = Closer.create(); try { BufferedReader reader = closer.register(openBufferedStream()); List result = Lists.newArrayList(); String line; while ((line = reader.readLine()) != null) { result.add(line); } return ImmutableList.copyOf(result); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }public String read() throws IOException { Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return CharStreams.toString(reader); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }@CanIgnoreReturnValue public long copyTo(CharSink sink) throws IOException { checkNotNull(sink); Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); Writer writer = closer.register(sink.openStream()); return CharStreams.copy(reader, writer); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }�X]�* =����L�y6�r34 � ��[eU��1�6"�&�')�)�*B+�,.�.2�:e;+<==�>@�BD�F�INOlQ�U�VGXHY�c�g�hFj�j2m�w�{�~��%���F���!� � �����������زݶ��8�������������Y�i���3����$�X���������@�����z #�T����*�-�.�/�0�1�6�8z=o?�A�CjE/F.GiH�J[T�V([�\`]�`xa8b�ck�k5lSmn�nAo�o�p=q%su}�~D��ц̋t���=���}�9��������J�������;�1���u���������̥��������[���n�e�_�����_�8�?�/�������E���O�n�2�C�J���D�k��� ����������"�i�<����������������8�����g��E�r�(�����:�;������������3 4 # � ����Z����P"$'%M&5'�'()�)�*K+�+�,#-�-u./�/\0�2H3H4Z6�6 9�<DFE�FrIsJDK�K�MTN�OQ\R9S�UlX�[�\^4_�`�a�bed�f�gbh'i�i�jl7m�m�n�p�q s^t_u\v�v/y/{�{�|�}�~4���!�X��������E�ŽA������X�H� �T�o�����}�����آ$�P�����\�>�[�'�T�q�6���������I���e�O�����3���e�T���5� �����7���w�%�I�3�������B������R������r�6������b�R���)�h��9���c^�}��ע�x �v���)ɍ�nw�Ѩ�4�l_њ����4~F? +�VZ�&U�S��̩�����o�<��_n�7�dؤ�Zn��Yw*��tt �BF3h���8�4~ǰF��+ӄSn���(D�an&��gDŽs�&���W� ����u?���{�:'p<�$;���?�\j��vh8r֡(��zՠl.�;�PJ�ɑ@�XS|��*� `ߒ �腹Ebc�@VW~\�@r���k��rQ9 A8�-�r�P/j�w��(�?b�GsxK1��N�rJ�64�e�P�����Hg�?��Qt�ө�N��� �~O�,�>���p�A�gIK�@�j�[�z��&��@��gɜ�;�ewj,�N��private void writeHandlingTasks(final RegisteredSocket socket, final WriteOperation op) throws IOException { while (true) { try { socket.tlsChannel.write(op.bufferSet.array, op.bufferSet.offset, op.bufferSet.length); return; } catch (NeedsTaskException e) { warnAboutNeedTask(); e.getTask().run(); } } }public BsonRegularExpression getRegularExpression(final Object key, final BsonRegularExpression defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asRegularExpression(); }public BsonBinary getBinary(final Object key, final BsonBinary defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asBinary(); }public BsonObjectId getObjectId(final Object key, final BsonObjectId defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asObjectId(); }public BsonTimestamp getTimestamp(final Object key, final BsonTimestamp defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asTimestamp(); }public BsonDateTime getDateTime(final Object key, final BsonDateTime defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asDateTime(); }public BsonString getString(final Object key, final BsonString defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asString(); }public BsonBoolean getBoolean(final Object key, final BsonBoolean defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asBoolean(); }public BsonDouble getDouble(final Object key, final BsonDouble defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asDouble(); }public BsonDecimal128 getDecimal128(final Object key, final BsonDecimal128 defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asDecimal128(); }public BsonInt64 getInt64(final Object key, final BsonInt64 defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asInt64(); }public BsonInt32 getInt32(final Object key, final BsonInt32 defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asInt32(); }public BsonNumber getNumber(final Object key, final BsonNumber defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asNumber(); }public BsonArray getArray(final Object key, final BsonArray defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asArray(); }public BsonDocument getDocument(final Object key, final BsonDocument defaultValue) { if (!containsKey(key)) { return defaultValue; } return get(key).asDocument(); }public BsonValue get(final Object key, final BsonValue defaultValue) { BsonValue value = get(key); return value != null ? value : defaultValue; }public List getIndexNames() { List indexNames = new ArrayList(requests.size()); for (IndexRequest request : requests) { if (request.getName() != null) { indexNames.add(request.getName()); } else { indexNames.add(IndexHelper.generateIndexName(request.getKeys())); } } return indexNames; }public static Bson geoHaystack(final String fieldName, final Bson additional) { notNull("fieldName", fieldName); return compoundIndex(new BsonDocument(fieldName, new BsonString("geoHaystack")), additional); }public Object copy() { // copy field values into new object BasicDBObject newCopy = new BasicDBObject(this.toMap()); // need to clone the sub obj for (final String field : keySet()) { Object val = get(field); if (val instanceof BasicDBObject) { newCopy.put(field, ((BasicDBObject) val).copy()); } else if (val instanceof BasicDBList) { newCopy.put(field, ((BasicDBList) val).copy()); } } return newCopy; }public BulkWriteResult execute() { isTrue("already executed", !closed); closed = true; return collection.executeBulkWriteOperation(ordered, bypassDocumentValidation, requests); }public BulkWriteRequestBuilder find(final DBObject query) { isTrue("already executed", !closed); return new BulkWriteRequestBuilder(this, query, collection.getDefaultDBObjectCodec(), collection.getObjectCodec()); }public void insert(final DBObject document) { isTrue("already executed", !closed); if (document.get(ID_FIELD_NAME) == null) { document.put(ID_FIELD_NAME, new ObjectId()); } addRequest(new InsertRequest(document, collection.getObjectCodec())); }@Deprecated public static Majority majorityWriteConcern(final int wtimeout, final boolean fsync, final boolean j) { return new Majority(wtimeout, fsync, j); }public WriteConcern withWTimeout(final long wTimeout, final TimeUnit timeUnit) { notNull("timeUnit", timeUnit); long newWTimeOutMS = TimeUnit.MILLISECONDS.convert(wTimeout, timeUnit); isTrueArgument("wTimeout >= 0", wTimeout >= 0); isTrueArgument("wTimeout <= " + Integer.MAX_VALUE + " ms", newWTimeOutMS <= Integer.MAX_VALUE); return new WriteConcern(w, (int) newWTimeOutMS, fsync, journal); }public WriteConcern withW(final String w) { notNull("w", w); return new WriteConcern(w, wTimeoutMS, fsync, journal); }public WriteConcern withW(final int w) { return new WriteConcern(Integer.valueOf(w), wTimeoutMS, fsync, journal); }public boolean isAcknowledged() { if (w instanceof Integer) { return (Integer) w > 0 || (journal != null && journal) || (fsync != null && fsync); } return true; }public BsonDocument asDocument() { BsonDocument document = new BsonDocument(); addW(document); addWTimeout(document); addFSync(document); addJ(document); return document; }@Nullable public Integer getWTimeout(final TimeUnit timeUnit) { notNull("timeUnit", timeUnit); return wTimeoutMS == null ? null : (int) timeUnit.convert(wTimeoutMS, TimeUnit.MILLISECONDS); }public ClientSession startSession(final ClientSessionOptions options) { ClientSession clientSession = createClientSession(notNull("options", options)); if (clientSession == null) { throw new MongoClientException("Sessions are not supported by the MongoDB cluster to which this client is connected"); } return clientSession; }@Nullable public MongoCredential getCredential() { if (getCredentialsList().size() > 1) { throw new IllegalStateException("Instance constructed with more than one MongoCredential"); } else if (getCredentialsList().isEmpty()) { return null; } else { return getCredentialsList().get(0); } }@SuppressWarnings("unchecked") private static Object canonicalize(final Object from) { if (from instanceof BSONObject && !(from instanceof BasicBSONList)) { return canonicalizeBSONObject((BSONObject) from); } else if (from instanceof List) { return canonicalizeList((List) from); } else if (from instanceof Map) { return canonicalizeMap((Map) from); } else { return from; } }public Date getDate(final String field, final Date def) { Object foo = get(field); return (foo != null) ? (Date) foo : def; }public ObjectId getObjectId(final String field, final ObjectId def) { Object foo = get(field); return (foo != null) ? (ObjectId) foo : def; }public boolean getBoolean(final String key, final boolean def) { Object foo = get(key); if (foo == null) { return def; } if (foo instanceof Number) { return ((Number) foo).intValue() > 0; } if (foo instanceof Boolean) { return (Boolean) foo; } throw new IllegalArgumentException("can't coerce to bool:" + foo.getClass()); }public String getString(final String key) { Object foo = get(key); if (foo == null) { return null; } return foo.toString(); }@Override public void compress(final List source, final BsonOutput target) { int uncompressedSize = getUncompressedSize(source); byte[] singleByteArraySource = new byte[uncompressedSize]; copy(source, singleByteArraySource); try { byte[] out = new byte[Snappy.maxCompressedLength(uncompressedSize)]; int compressedSize = Snappy.compress(singleByteArraySource, 0, singleByteArraySource.length, out, 0); target.writeBytes(out, 0, compressedSize); } catch (IOException e) { throw new MongoInternalException("Unexpected IOException", e); } }public BsonDocument asDocument() { BsonDocument readConcern = new BsonDocument(); if (level != null) { readConcern.put("level", new BsonString(level.getValue())); } return readConcern; }public void encodeWithChildContext(final Encoder encoder, final BsonWriter writer, final T value) { encoder.encode(writer, value, DEFAULT_CONTEXT); }public String getFirstKey() { return findInDocument(new Finder() { @Override public String find(final BsonReader bsonReader) { return bsonReader.readName(); } @Override public String notFound() { throw new NoSuchElementException(); } }); }@Deprecated @SuppressWarnings("unchecked") public List getAliases() { if (extraElements != null && extraElements.containsKey("aliases")) { return (List) extraElements.get("aliases"); } else { throw new MongoGridFSException("No aliases data for this GridFS file"); } }@Deprecated public String getContentType() { if (extraElements != null && extraElements.containsKey("contentType")) { return extraElements.getString("contentType"); } else { throw new MongoGridFSException("No contentType data for this GridFS file"); } }public static UpdateResult acknowledged(final long matchedCount, @Nullable final Long modifiedCount, @Nullable final BsonValue upsertedId) { return new AcknowledgedUpdateResult(matchedCount, modifiedCount, upsertedId); }public String getShortDescription() { return "{" + (hosts.isEmpty() ? "" : "hosts=" + hosts) + (srvHost == null ? "" : ", srvHost=" + srvHost) + ", mode=" + mode + ", requiredClusterType=" + requiredClusterType + ", serverSelectionTimeout='" + serverSelectionTimeoutMS + " ms" + '\'' + ", maxWaitQueueSize=" + maxWaitQueueSize + (requiredReplicaSetName == null ? "" : ", requiredReplicaSetName='" + requiredReplicaSetName + '\'') + (description == null ? "" : ", description='" + description + '\'') + '}'; }public DBObject toDBObject() { BasicDBObject cmd = new BasicDBObject(); cmd.put("mapreduce", mapReduce); cmd.put("map", map); cmd.put("reduce", reduce); if (verbose != null) { cmd.put("verbose", verbose); } BasicDBObject out = new BasicDBObject(); switch (outputType) { case INLINE: out.put("inline", 1); break; case REPLACE: out.put("replace", outputCollection); break; case MERGE: out.put("merge", outputCollection); break; case REDUCE: out.put("reduce", outputCollection); break; default: throw new IllegalArgumentException("Unexpected output type"); } if (outputDB != null) { out.put("db", outputDB); } cmd.put("out", out); if (query != null) { cmd.put("query", query); } if (finalize != null) { cmd.put("finalize", finalize); } if (sort != null) { cmd.put("sort", sort); } if (limit > 0) { cmd.put("limit", limit); } if (scope != null) { cmd.put("scope", scope); } if (jsMode != null) { cmd.put("jsMode", jsMode); } if (maxTimeMS != 0) { cmd.put("maxTimeMS", maxTimeMS); } return cmd; }@SuppressWarnings("deprecation") public static byte getType(final Object object) { if (object == null) { return NULL; } if (object instanceof Integer || object instanceof Short || object instanceof Byte || object instanceof AtomicInteger) { return NUMBER_INT; } if (object instanceof Long || object instanceof AtomicLong) { return NUMBER_LONG; } if (object instanceof Number) { return NUMBER; } if (object instanceof String) { return STRING; } if (object instanceof java.util.List) { return ARRAY; } if (object instanceof byte[]) { return BINARY; } if (object instanceof ObjectId) { return OID; } if (object instanceof Boolean) { return BOOLEAN; } if (object instanceof java.util.Date) { return DATE; } if (object instanceof BSONTimestamp) { return TIMESTAMP; } if (object instanceof java.util.regex.Pattern) { return REGEX; } if (object instanceof DBObject || object instanceof DBRef) { return OBJECT; } if (object instanceof CodeWScope) { return CODE_W_SCOPE; } if (object instanceof Code) { return CODE; } return -1; }public static void enableSni(final String host, final SSLParameters sslParameters) { if (SNI_SSL_HELPER != null) { SNI_SSL_HELPER.enableSni(host, sslParameters); } }public static synchronized void close() { if (mongoEmbeddedLibrary != null) { try { mongoEmbeddedLibrary.close(); } catch (Exception e) { throw new MongoClientEmbeddedException(format("Could not close the mongo embedded library.%n" + "Please ensure that any MongoClient instances have been closed first.%n" + "Server error message: %s", e.getMessage()), e); } mongoEmbeddedLibrary = null; } }public static synchronized MongoClient create(final MongoClientSettings mongoClientSettings) { if (mongoEmbeddedLibrary == null) { throw new MongoClientEmbeddedException("The mongo embedded library must be initialized first."); } try { Cluster cluster = new EmbeddedCluster(mongoEmbeddedLibrary, mongoClientSettings); return new MongoClientImpl(cluster, mongoClientSettings.getWrappedMongoClientSettings(), null); } catch (Exception e) { throw new MongoClientEmbeddedException(format("Could not create a new embedded cluster.%n" + "Please ensure any existing MongoClients are fully closed before trying to create a new one.%n" + "Server error message: %s", e.getMessage()), e); } }public static synchronized void init(final MongoEmbeddedSettings mongoEmbeddedSettings) { if (mongoEmbeddedLibrary != null) { throw new MongoClientEmbeddedException("The mongo embedded library has already been initialized"); } try { mongoEmbeddedLibrary = MongoEmbeddedCAPI.create(mongoEmbeddedSettings.getYamlConfig(), mongoEmbeddedSettings.getLogLevel().toCapiLogLevel(), mongoEmbeddedSettings.getLibraryPath()); } catch (Exception e) { throw new MongoClientEmbeddedException(format("The mongo embedded library could not be initialized%n" + "Server error message: %s", e.getMessage()), e); } }@Override public MapReduceStatistics execute(final WriteBinding binding) { return withConnection(binding, new OperationHelper.CallableWithConnection() { @Override public MapReduceStatistics call(final Connection connection) { validateCollation(connection, collation); return executeCommand(binding, namespace.getDatabaseName(), getCommand(connection.getDescription()), connection, transformer()); } }); }public BulkUpdateRequestBuilder arrayFilters(final List arrayFilters) { return new BulkUpdateRequestBuilder(bulkWriteOperation, query, false, codec, replacementCodec, collation, arrayFilters); }public BulkUpdateRequestBuilder upsert() { return new BulkUpdateRequestBuilder(bulkWriteOperation, query, true, codec, replacementCodec, collation, null); }@Override public BulkWriteResult execute(final WriteBinding binding) { return withReleasableConnection(binding, new CallableWithConnectionAndSource() { @Override public BulkWriteResult call(final ConnectionSource connectionSource, final Connection connection) { validateWriteRequestsAndReleaseConnectionIfError(connection); if (getWriteConcern().isAcknowledged() || serverIsAtLeastVersionThreeDotSix(connection.getDescription())) { BulkWriteBatch bulkWriteBatch = BulkWriteBatch.createBulkWriteBatch(namespace, connectionSource.getServerDescription(), connection.getDescription(), ordered, writeConcern, bypassDocumentValidation, retryWrites, writeRequests, binding.getSessionContext()); return executeBulkWriteBatch(binding, connection, bulkWriteBatch); } else { return executeLegacyBatches(connection); } } }); }@Override public void encode(final BsonWriter writer, final DBObject document, final EncoderContext encoderContext) { BasicOutputBuffer buffer = new BasicOutputBuffer(); try { encoder.writeObject(buffer, document); BsonBinaryReader reader = new BsonBinaryReader(new ByteBufferBsonInput(new ByteBufNIO(wrap(buffer.toByteArray())))); try { writer.pipe(reader); } finally { reader.close(); } } finally { buffer.close(); } }@SuppressWarnings("unchecked") public static T convertToType(final Class clazz, final Object value, final String errorMessage) { if (!clazz.isAssignableFrom(value.getClass())) { throw new IllegalArgumentException(errorMessage); } return (T) value; }public DBCollectionFindOptions copy() { DBCollectionFindOptions copiedOptions = new DBCollectionFindOptions(); copiedOptions.batchSize(batchSize); copiedOptions.limit(limit); copiedOptions.modifiers(modifiers); copiedOptions.projection(projection); copiedOptions.maxTime(maxTimeMS, TimeUnit.MILLISECONDS); copiedOptions.maxAwaitTime(maxAwaitTimeMS, TimeUnit.MILLISECONDS); copiedOptions.skip(skip); copiedOptions.sort(sort); copiedOptions.cursorType(cursorType); copiedOptions.noCursorTimeout(noCursorTimeout); copiedOptions.oplogReplay(oplogReplay); copiedOptions.partial(partial); copiedOptions.readPreference(readPreference); copiedOptions.readConcern(readConcern); copiedOptions.collation(collation); copiedOptions.comment(comment); copiedOptions.hint(hint); copiedOptions.max(max); copiedOptions.min(min); copiedOptions.returnKey(returnKey); copiedOptions.showRecordId(showRecordId); return copiedOptions; }public IndexRequest sphereVersion(final Integer sphereVersion) { if (sphereVersion != null) { isTrueArgument("sphereIndexVersion must be 1, 2 or 3", VALID_SPHERE_INDEX_VERSIONS.contains(sphereVersion)); } this.sphereVersion = sphereVersion; return this; }public IndexRequest textVersion(final Integer textVersion) { if (textVersion != null) { isTrueArgument("textVersion must be 1, 2 or 3", VALID_TEXT_INDEX_VERSIONS.contains(textVersion)); } this.textVersion = textVersion; return this; }public static String regexFlags(final int flags) { int processedFlags = flags; StringBuilder buf = new StringBuilder(); for (int i = 0; i < FLAG_LOOKUP.length; i++) { if ((processedFlags & FLAG_LOOKUP[i]) > 0) { buf.append((char) i); processedFlags -= FLAG_LOOKUP[i]; } } if (processedFlags > 0) { throw new IllegalArgumentException("Some flags could not be recognized."); } return buf.toString(); }public static int regexFlag(final char c) { int flag = FLAG_LOOKUP[c]; if (flag == 0) { throw new IllegalArgumentException(String.format("Unrecognized flag [%c]", c)); } return flag; }public static int regexFlags(final String s) { int flags = 0; if (s == null) { return flags; } for (final char f : s.toLowerCase().toCharArray()) { flags |= regexFlag(f); } return flags; }public static Bson near(final String fieldName, final double x, final double y, @Nullable final Double maxDistance, @Nullable final Double minDistance) { return createNearFilterDocument(fieldName, x, y, maxDistance, minDistance, "$near"); }public static Bson near(final String fieldName, final Point geometry, @Nullable final Double maxDistance, @Nullable final Double minDistance) { return new GeometryOperatorFilter("$near", fieldName, geometry, maxDistance, minDistance); }public static Bson geoWithinCenter(final String fieldName, final double x, final double y, final double radius) { BsonDocument center = new BsonDocument("$center", new BsonArray(Arrays.asList(new BsonArray(asList(new BsonDouble(x), new BsonDouble(y))), new BsonDouble(radius)))); return new OperatorFilter("$geoWithin", fieldName, center); }public static Bson geoWithinPolygon(final String fieldName, final List> points) { BsonArray pointsArray = new BsonArray(); for (List point : points) { pointsArray.add(new BsonArray(asList(new BsonDouble(point.get(0)), new BsonDouble(point.get(1))))); } BsonDocument polygon = new BsonDocument("$polygon", pointsArray); return new OperatorFilter("$geoWithin", fieldName, polygon); }public static Bson geoWithinBox(final String fieldName, final double lowerLeftX, final double lowerLeftY, final double upperRightX, final double upperRightY) { BsonDocument box = new BsonDocument("$box", new BsonArray(asList(new BsonArray(asList(new BsonDouble(lowerLeftX), new BsonDouble(lowerLeftY))), new BsonArray(asList(new BsonDouble(upperRightX), new BsonDouble(upperRightY)))))); return new OperatorFilter("$geoWithin", fieldName, box); }public static Bson elemMatch(final String fieldName, final Bson filter) { return new Bson() { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { return new BsonDocument(fieldName, new BsonDocument("$elemMatch", filter.toBsonDocument(documentClass, codecRegistry))); } }; }public static Bson text(final String search, final TextSearchOptions textSearchOptions) { notNull("search", search); notNull("textSearchOptions", textSearchOptions); return new TextFilter(search, textSearchOptions); }@Deprecated public static Bson text(final String search, final String language) { notNull("search", search); return text(search, new TextSearchOptions().language(language)); }public static Bson exists(final String fieldName, final boolean exists) { return new OperatorFilter("$exists", fieldName, BsonBoolean.valueOf(exists)); }public static Bson nor(final Iterable filters) { return new OrNorFilter(OrNorFilter.Operator.NOR, filters); }public static Bson or(final Iterable filters) { return new OrNorFilter(OrNorFilter.Operator.OR, filters); }public static Bson lte(final String fieldName, final TItem value) { return new OperatorFilter("$lte", fieldName, value); }public static Bson gte(final String fieldName, final TItem value) { return new OperatorFilter("$gte", fieldName, value); }public static Bson lt(final String fieldName, final TItem value) { return new OperatorFilter("$lt", fieldName, value); }public static Bson gt(final String fieldName, final TItem value) { return new OperatorFilter("$gt", fieldName, value); }public static Bson ne(final String fieldName, @Nullable final TItem value) { return new OperatorFilter("$ne", fieldName, value); }public List getSocketAddresses() { try { InetAddress[] inetAddresses = InetAddress.getAllByName(host); List inetSocketAddressList = new ArrayList(); for (InetAddress inetAddress : inetAddresses) { inetSocketAddressList.add(new InetSocketAddress(inetAddress, port)); } return inetSocketAddressList; } catch (UnknownHostException e) { throw new MongoSocketException(e.getMessage(), this, e); } }public InetSocketAddress getSocketAddress() { try { return new InetSocketAddress(InetAddress.getByName(host), port); } catch (UnknownHostException e) { throw new MongoSocketException(e.getMessage(), this, e); } }public static BulkWriteResult unacknowledged() { return new BulkWriteResult() { @Override public boolean wasAcknowledged() { return false; } @Override public int getInsertedCount() { throw getUnacknowledgedWriteException(); } @Override public int getMatchedCount() { throw getUnacknowledgedWriteException(); } @Override public int getDeletedCount() { throw getUnacknowledgedWriteException(); } @Override @Deprecated public boolean isModifiedCountAvailable() { throw getUnacknowledgedWriteException(); } @Override public int getModifiedCount() { throw getUnacknowledgedWriteException(); } @Override public List getUpserts() { throw getUnacknowledgedWriteException(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BulkWriteResult that = (BulkWriteResult) o; return !that.wasAcknowledged(); } @Override public int hashCode() { return 0; } @Override public String toString() { return "UnacknowledgedBulkWriteResult{}"; } private UnsupportedOperationException getUnacknowledgedWriteException() { return new UnsupportedOperationException("Cannot get information about an unacknowledged write"); } }; }protected void putDBRef(final String name, final DBRef ref) { BasicDBObject dbRefDocument = new BasicDBObject("$ref", ref.getCollectionName()).append("$id", ref.getId()); if (ref.getDatabaseName() != null) { dbRefDocument.put("$db", ref.getDatabaseName()); } putObject(name, dbRefDocument); }protected void _put(final String name, final Object value) { cur().put(name, !BSON.hasDecodeHooks() ? value : BSON.applyDecodingHooks(value)); }ReadConcern getReadConcern() { ReadConcern readConcern = findOptions.getReadConcern(); if (readConcern != null) { return readConcern; } return collection.getReadConcern(); }public ReadPreference getReadPreference() { ReadPreference readPreference = findOptions.getReadPreference(); if (readPreference != null) { return readPreference; } return collection.getReadPreference(); }@Nullable public DBObject one() { DBCursor findOneCursor = copy().limit(-1); try { return findOneCursor.hasNext() ? findOneCursor.next() : null; } finally { findOneCursor.close(); } }public List toArray(final int max) { checkIteratorOrArray(IteratorOrArray.ARRAY); fillArray(max - 1); return all; }@Nullable public DBObject tryNext() { if (cursor == null) { FindOperation operation = getQueryOperation(decoder); if (!operation.getCursorType().isTailable()) { throw new IllegalArgumentException("Can only be used with a tailable cursor"); } initializeCursor(operation); } DBObject next = cursor.tryNext(); setServerCursorOnFinalizer(cursor.getServerCursor()); return currentObject(next); }@Override public boolean hasNext() { if (closed) { throw new IllegalStateException("Cursor has been closed"); } if (cursor == null) { FindOperation operation = getQueryOperation(decoder); if (operation.getCursorType() == CursorType.Tailable) { operation.cursorType(CursorType.TailableAwait); } initializeCursor(operation); } boolean hasNext = cursor.hasNext(); setServerCursorOnFinalizer(cursor.getServerCursor()); return hasNext; }public DBCursor copy() { return new DBCursor(collection, filter, findOptions, executor, decoderFactory, decoder, retryReads); }protected DBObject createChunk(final Object id, final int currentChunkNumber, final byte[] writeBuffer) { return new BasicDBObject("files_id", id) .append("n", currentChunkNumber) .append("data", writeBuffer); }protected void backpatchMessageLength(final int startPosition, final BsonOutput bsonOutput) { int messageLength = bsonOutput.getPosition() - startPosition; bsonOutput.writeInt32(bsonOutput.getPosition() - messageLength, messageLength); }protected void addCollectibleDocument(final BsonDocument document, final BsonOutput bsonOutput, final FieldNameValidator validator) { addDocument(document, getCodec(document), EncoderContext.builder().isEncodingCollectibleDocument(true).build(), bsonOutput, validator, settings.getMaxDocumentSize(), null); }protected void addDocument(final BsonDocument document, final BsonOutput bsonOutput, final FieldNameValidator validator) { addDocument(document, getCodec(document), EncoderContext.builder().build(), bsonOutput, validator, settings.getMaxDocumentSize() + DOCUMENT_HEADROOM, null); }protected void writeMessagePrologue(final BsonOutput bsonOutput) { bsonOutput.writeInt32(0); // length: will set this later bsonOutput.writeInt32(id); bsonOutput.writeInt32(0); // response to bsonOutput.writeInt32(opCode.getValue()); }public void encode(final BsonOutput bsonOutput, final SessionContext sessionContext) { notNull("sessionContext", sessionContext); int messageStartPosition = bsonOutput.getPosition(); writeMessagePrologue(bsonOutput); EncodingMetadata encodingMetadata = encodeMessageBodyWithMetadata(bsonOutput, sessionContext); backpatchMessageLength(messageStartPosition, bsonOutput); this.encodingMetadata = encodingMetadata; }public UpdateRequest multi(final boolean isMulti) { if (isMulti && updateType == Type.REPLACE) { throw new IllegalArgumentException("Replacements can not be multi"); } this.isMulti = isMulti; return this; }@SuppressWarnings("rawtypes") void addObjectSerializer(final Class c, final ObjectSerializer serializer) { _serializers.put(c, serializer); }public byte[] toByteArray() { try { ByteArrayOutputStream bout = new ByteArrayOutputStream(size()); pipe(bout); return bout.toByteArray(); } catch (IOException ioe) { throw new RuntimeException("should be impossible", ioe); } }@SuppressWarnings("unchecked") @Nullable public T getMechanismProperty(final String key, @Nullable final T defaultValue) { notNull("key", key); T value = (T) mechanismProperties.get(key.toLowerCase()); return (value == null) ? defaultValue : value; }public MongoCredential withMechanism(final AuthenticationMechanism mechanism) { if (this.mechanism != null) { throw new IllegalArgumentException("Mechanism already set"); } return new MongoCredential(mechanism, userName, source, password, mechanismProperties); }public MongoCredential withMechanismProperty(final String key, final T value) { return new MongoCredential(this, key, value); }public static MongoCredential createPlainCredential(final String userName, final String source, final char[] password) { return new MongoCredential(PLAIN, userName, source, password); }public static MongoCredential createScramSha256Credential(final String userName, final String source, final char[] password) { return new MongoCredential(SCRAM_SHA_256, userName, source, password); }public static MongoCredential createCredential(final String userName, final String database, final char[] password) { return new MongoCredential(null, userName, database, password); }public String getShortDescription() { StringBuilder serverDescriptions = new StringBuilder(); String delimiter = ""; for (final ServerDescription cur : this.serverDescriptions) { serverDescriptions.append(delimiter).append(cur.getShortDescription()); delimiter = ", "; } if (srvResolutionException == null) { return format("{type=%s, servers=[%s]", type, serverDescriptions); } else { return format("{type=%s, srvResolutionException=%s, servers=[%s]", type, srvResolutionException, serverDescriptions); } }@Deprecated public List getAnyPrimaryOrSecondary(final TagSet tagSet) { return getServersByPredicate(new Predicate() { public boolean apply(final ServerDescription serverDescription) { return (serverDescription.isPrimary() || serverDescription.isSecondary()) && serverDescription.hasTags(tagSet); } }); }@Deprecated public List getAnyPrimaryOrSecondary() { return getServersByPredicate(new Predicate() { public boolean apply(final ServerDescription serverDescription) { return serverDescription.isPrimary() || serverDescription.isSecondary(); } }); }@Deprecated public List getAny() { return getServersByPredicate(new Predicate() { public boolean apply(final ServerDescription serverDescription) { return serverDescription.isOk(); } }); }@Deprecated public List getSecondaries(final TagSet tagSet) { return getServersByPredicate(new Predicate() { public boolean apply(final ServerDescription serverDescription) { return serverDescription.isSecondary() && serverDescription.hasTags(tagSet); } }); }@Deprecated public List getSecondaries() { return getServersByPredicate(new Predicate() { public boolean apply(final ServerDescription serverDescription) { return serverDescription.isSecondary(); } }); }@Deprecated public List getPrimaries() { return getServersByPredicate(new Predicate() { public boolean apply(final ServerDescription serverDescription) { return serverDescription.isPrimary(); } }); }@Deprecated public ServerDescription getByServerAddress(final ServerAddress serverAddress) { for (final ServerDescription cur : serverDescriptions) { if (cur.isOk() && cur.getAddress().equals(serverAddress)) { return cur; } } return null; }@Deprecated public Set getAll() { Set serverDescriptionSet = new TreeSet(new Comparator() { @Override public int compare(final ServerDescription o1, final ServerDescription o2) { int val = o1.getAddress().getHost().compareTo(o2.getAddress().getHost()); if (val != 0) { return val; } return integerCompare(o1.getAddress().getPort(), o2.getAddress().getPort()); } private int integerCompare(final int p1, final int p2) { return (p1 < p2) ? -1 : ((p1 == p2) ? 0 : 1); } }); serverDescriptionSet.addAll(serverDescriptions); return Collections.unmodifiableSet(serverDescriptionSet); }public Integer getLogicalSessionTimeoutMinutes() { Integer retVal = null; for (ServerDescription cur : getServersByPredicate(new Predicate() { @Override public boolean apply(final ServerDescription serverDescription) { return serverDescription.isPrimary() || serverDescription.isSecondary(); } })) { if (cur.getLogicalSessionTimeoutMinutes() == null) { return null; } if (retVal == null) { retVal = cur.getLogicalSessionTimeoutMinutes(); } else { retVal = Math.min(retVal, cur.getLogicalSessionTimeoutMinutes()); } } return retVal; }public DBObject toDBObject() { DBObject args = new BasicDBObject("ns", collectionName).append("cond", condition) .append("$reduce", reduce) .append("initial", initial); if (keys != null) { args.put("key", keys); } if (keyf != null) { args.put("$keyf", keyf); } if (finalize != null) { args.put("finalize", finalize); } return new BasicDBObject("group", args); }@Nullable public Long getExpireAfter(final TimeUnit timeUnit) { if (expireAfterSeconds == null) { return null; } return timeUnit.convert(expireAfterSeconds, TimeUnit.SECONDS); }@Override @SuppressWarnings("unchecked") public MapReduceBatchCursor execute(final ReadBinding binding) { return executeCommand(binding, namespace.getDatabaseName(), getCommandCreator(binding.getSessionContext()), CommandResultDocumentCodec.create(decoder, "results"), transformer(), false); }@SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) public String toJson() { StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings()); Codec codec = getRegistry().get(getClass()); codec.encode(writer, this, EncoderContext.builder().build()); return stringWriter.toString(); }private static List> computeAncestry(final Class c) { List> result = new ArrayList>(); result.add(Object.class); computeAncestry(c, result); Collections.reverse(result); return unmodifiableList(new ArrayList>(result)); }public ConnectionId withServerValue(final int serverValue) { isTrue("server value is null", this.serverValue == null); return new ConnectionId(serverId, localValue, serverValue); }public BsonNumber asNumber() { if (getBsonType() != BsonType.INT32 && getBsonType() != BsonType.INT64 && getBsonType() != BsonType.DOUBLE) { throw new BsonInvalidOperationException(format("Value expected to be of a numerical BSON type is of unexpected type %s", getBsonType())); } return (BsonNumber) this; }@Deprecated public DBObject unlock() { return DBObjects.toDBObject(createOperationExecutor().execute(new FsyncUnlockOperation(), readPreference, readConcern)); }@Deprecated public CommandResult fsyncAndLock() { DBObject command = new BasicDBObject("fsync", 1); command.put("lock", 1); return getDB(ADMIN_DATABASE_NAME).command(command); }@Deprecated public CommandResult fsync(final boolean async) { DBObject command = new BasicDBObject("fsync", 1); if (async) { command.put("async", 1); } return getDB(ADMIN_DATABASE_NAME).command(command); }@Deprecated public List getDatabaseNames() { return new MongoIterableImpl(null, createOperationExecutor(), ReadConcern.DEFAULT, primary(), options.getRetryReads()) { @Override public ReadOperation> asReadOperation() { return new ListDatabasesOperation(MongoClient.getCommandCodec()); } }.map(new Function() { @Override public String apply(final DBObject result) { return (String) result.get("name"); } }).into(new ArrayList()); }@SuppressWarnings("deprecation") @Deprecated @Nullable public ReplicaSetStatus getReplicaSetStatus() { ClusterDescription clusterDescription = getClusterDescription(); return clusterDescription.getType() == REPLICA_SET && clusterDescription.getConnectionMode() == MULTIPLE ? new ReplicaSetStatus(delegate.getCluster()) : null; // this is intended behavior in 2.x }@Deprecated @SuppressWarnings("deprecation") @Nullable public ServerAddress getAddress() { ClusterDescription description = getClusterDescription(); if (description.getPrimaries().isEmpty()) { return null; } return description.getPrimaries().get(0).getAddress(); }public static String encode(final byte[] in) { int modulus = 0; int bitWorkArea = 0; int numEncodedBytes = (in.length / BYTES_PER_UNENCODED_BLOCK) * BYTES_PER_ENCODED_BLOCK + ((in.length % BYTES_PER_UNENCODED_BLOCK == 0) ? 0 : 4); byte[] buffer = new byte[numEncodedBytes]; int pos = 0; for (int b : in) { modulus = (modulus + 1) % BYTES_PER_UNENCODED_BLOCK; if (b < 0) { b += 256; } bitWorkArea = (bitWorkArea << 8) + b; // BITS_PER_BYTE if (0 == modulus) { // 3 bytes = 24 bits = 4 * 6 bits to extract buffer[pos++] = ENCODE_TABLE[(bitWorkArea >> 18) & SIX_BIT_MASK]; buffer[pos++] = ENCODE_TABLE[(bitWorkArea >> 12) & SIX_BIT_MASK]; buffer[pos++] = ENCODE_TABLE[(bitWorkArea >> 6) & SIX_BIT_MASK]; buffer[pos++] = ENCODE_TABLE[bitWorkArea & SIX_BIT_MASK]; } } switch (modulus) { // 0-2 case 1: // 8 bits = 6 + 2 buffer[pos++] = ENCODE_TABLE[(bitWorkArea >> 2) & SIX_BIT_MASK]; // top 6 bits buffer[pos++] = ENCODE_TABLE[(bitWorkArea << 4) & SIX_BIT_MASK]; // remaining 2 buffer[pos++] = PAD; buffer[pos] = PAD; // Last entry no need to ++ break; case 2: // 16 bits = 6 + 6 + 4 buffer[pos++] = ENCODE_TABLE[(bitWorkArea >> 10) & SIX_BIT_MASK]; buffer[pos++] = ENCODE_TABLE[(bitWorkArea >> 4) & SIX_BIT_MASK]; buffer[pos++] = ENCODE_TABLE[(bitWorkArea << 2) & SIX_BIT_MASK]; buffer[pos] = PAD; // Last entry no need to ++ break; default: break; } return byteArrayToString(buffer); }public static byte[] decode(final String s) { int delta = s.endsWith("==") ? 2 : s.endsWith("=") ? 1 : 0; byte[] buffer = new byte[s.length() * BYTES_PER_UNENCODED_BLOCK / BYTES_PER_ENCODED_BLOCK - delta]; int mask = 0xFF; int pos = 0; for (int i = 0; i < s.length(); i += BYTES_PER_ENCODED_BLOCK) { int c0 = DECODE_TABLE[s.charAt(i)]; int c1 = DECODE_TABLE[s.charAt(i + 1)]; buffer[pos++] = (byte) (((c0 << 2) | (c1 >> 4)) & mask); if (pos >= buffer.length) { return buffer; } int c2 = DECODE_TABLE[s.charAt(i + 2)]; buffer[pos++] = (byte) (((c1 << 4) | (c2 >> 2)) & mask); if (pos >= buffer.length) { return buffer; } int c3 = DECODE_TABLE[s.charAt(i + 3)]; buffer[pos++] = (byte) (((c2 << 6) | c3) & mask); } return buffer; }@Deprecated public static ReplaceOptions createReplaceOptions(final UpdateOptions updateOptions) { notNull("updateOptions", updateOptions); List arrayFilters = updateOptions.getArrayFilters(); isTrue("ArrayFilters should be empty.", arrayFilters == null || arrayFilters.isEmpty()); return new ReplaceOptions() .bypassDocumentValidation(updateOptions.getBypassDocumentValidation()) .collation(updateOptions.getCollation()) .upsert(updateOptions.isUpsert()); }public static List> getAncestry(final Class clazz) { return ClassAncestry.getAncestry(clazz); }private void incrementGenerationOnSocketException(final InternalConnection connection, final Throwable t) { if (t instanceof MongoSocketException && !(t instanceof MongoSocketReadTimeoutException)) { if (LOGGER.isWarnEnabled()) { LOGGER.warn(format("Got socket exception on connection [%s] to %s. All connections to %s will be closed.", getId(connection), serverId.getAddress(), serverId.getAddress())); } invalidate(); } }protected void writeQueryPrologue(final BsonOutput bsonOutput) { bsonOutput.writeInt32(getCursorFlag()); bsonOutput.writeCString(getCollectionName()); bsonOutput.writeInt32(skip); bsonOutput.writeInt32(numberToReturn); }public static Bson pullAll(final String fieldName, final List values) { return new PullAllUpdate(fieldName, values); }public static Bson pullByFilter(final Bson filter) { return new Bson() { @Override public BsonDocument toBsonDocument(final Class tDocumentClass, final CodecRegistry codecRegistry) { BsonDocumentWriter writer = new BsonDocumentWriter(new BsonDocument()); writer.writeStartDocument(); writer.writeName("$pull"); encodeValue(writer, filter, codecRegistry); writer.writeEndDocument(); return writer.getDocument(); } }; }public static Bson pull(final String fieldName, @Nullable final TItem value) { return new SimpleUpdate(fieldName, value, "$pull"); }public static Bson pushEach(final String fieldName, final List values) { return new PushUpdate(fieldName, values, new PushOptions()); }public static Bson push(final String fieldName, @Nullable final TItem value) { return new SimpleUpdate(fieldName, value, "$push"); }public static Bson addEachToSet(final String fieldName, final List values) { return new WithEachUpdate(fieldName, values, "$addToSet"); }public static Bson addToSet(final String fieldName, @Nullable final TItem value) { return new SimpleUpdate(fieldName, value, "$addToSet"); }public static Bson max(final String fieldName, final TItem value) { return new SimpleUpdate(fieldName, value, "$max"); }public static Bson min(final String fieldName, final TItem value) { return new SimpleUpdate(fieldName, value, "$min"); }public static Bson mul(final String fieldName, final Number number) { notNull("number", number); return new SimpleUpdate(fieldName, number, "$mul"); }public static Bson inc(final String fieldName, final Number number) { notNull("number", number); return new SimpleUpdate(fieldName, number, "$inc"); }public static Bson rename(final String fieldName, final String newFieldName) { notNull("newFieldName", newFieldName); return new SimpleUpdate(fieldName, newFieldName, "$rename"); }public static Bson setOnInsert(final String fieldName, @Nullable final TItem value) { return new SimpleUpdate(fieldName, value, "$setOnInsert"); }public static Bson set(final String fieldName, @Nullable final TItem value) { return new SimpleUpdate(fieldName, value, "$set"); }protected Class getInternalClass(final String path) { return objectFactory.getClassForPath(asList(path.split("\\."))); }public void setInternalClass(final String path, final Class aClass) { setObjectFactory(objectFactory.update(aClass, asList(path.split("\\.")))); }public boolean isCapped() { CommandResult commandResult = getStats(); Object cappedField = commandResult.get("capped"); return cappedField != null && (cappedField.equals(1) || cappedField.equals(true)); }public void dropIndex(final String indexName) { try { executor.execute(new DropIndexOperation(getNamespace(), indexName, getWriteConcern()), getReadConcern()); } catch (MongoWriteConcernException e) { throw createWriteConcernException(e); } }public void dropIndex(final DBObject index) { try { executor.execute(new DropIndexOperation(getNamespace(), wrap(index), getWriteConcern()), getReadConcern()); } catch (MongoWriteConcernException e) { throw createWriteConcernException(e); } }public List getIndexInfo() { return new MongoIterableImpl(null, executor, ReadConcern.DEFAULT, primary(), retryReads) { @Override public ReadOperation> asReadOperation() { return new ListIndexesOperation(getNamespace(), getDefaultDBObjectCodec()).retryReads(retryReads); } }.into(new ArrayList()); }public synchronized void setDBEncoderFactory(@Nullable final DBEncoderFactory factory) { this.encoderFactory = factory; //Are we are using default factory? // If yes then we can use CollectibleDBObjectCodec directly, otherwise it will be wrapped. Encoder encoder = (factory == null || factory == DefaultDBEncoder.FACTORY) ? getDefaultDBObjectCodec() : new DBEncoderFactoryAdapter(encoderFactory); this.objectCodec = new CompoundDBObjectCodec(encoder, objectCodec.getDecoder()); }public synchronized void setDBDecoderFactory(@Nullable final DBDecoderFactory factory) { this.decoderFactory = factory; //Are we are using default factory? // If yes then we can use CollectibleDBObjectCodec directly, otherwise it will be wrapped. Decoder decoder = (factory == null || factory == DefaultDBDecoder.FACTORY) ? getDefaultDBObjectCodec() : new DBDecoderAdapter(factory.create(), this, getBufferPool()); this.objectCodec = new CompoundDBObjectCodec(objectCodec.getEncoder(), decoder); }@Nullable public DBObject findAndRemove(@Nullable final DBObject query) { return findAndModify(query, null, null, true, null, false, false); }public void createIndex(final DBObject keys, final DBObject options) { try { executor.execute(createIndexOperation(keys, options), getReadConcern()); } catch (MongoWriteConcernException e) { throw createWriteConcernException(e); } }public void createIndex(final DBObject keys, @Nullable final String name, final boolean unique) { DBObject options = new BasicDBObject(); if (name != null && name.length() > 0) { options.put("name", name); } if (unique) { options.put("unique", Boolean.TRUE); } createIndex(keys, options); }public CommandResult explainAggregate(final List pipeline, final AggregationOptions options) { AggregateOperation operation = new AggregateOperation(getNamespace(), preparePipeline(pipeline), new BsonDocumentCodec()) .maxTime(options.getMaxTime(MILLISECONDS), MILLISECONDS) .allowDiskUse(options.getAllowDiskUse()) .collation(options.getCollation()) .retryReads(retryReads); return new CommandResult(executor.execute(operation.asExplainableOperation(ExplainVerbosity.QUERY_PLANNER), primaryPreferred(), getReadConcern())); }public MapReduceOutput mapReduce(final String map, final String reduce, final String outputTarget, final MapReduceCommand.OutputType outputType, final DBObject query, final ReadPreference readPreference) { MapReduceCommand command = new MapReduceCommand(this, map, reduce, outputTarget, outputType, query); command.setReadPreference(readPreference); return mapReduce(command); }public DBCollection rename(final String newName, final boolean dropTarget) { try { executor.execute(new RenameCollectionOperation(getNamespace(), new MongoNamespace(getNamespace().getDatabaseName(), newName), getWriteConcern()) .dropTarget(dropTarget), getReadConcern()); return getDB().getCollection(newName); } catch (MongoWriteConcernException e) { throw createWriteConcernException(e); } }@Nullable public DBObject findOne(final Object id, final DBObject projection) { return findOne(new BasicDBObject("_id", id), new DBCollectionFindOptions().projection(projection)); }public WriteResult update(final DBObject query, final DBObject update, final DBCollectionUpdateOptions options) { notNull("query", query); notNull("update", update); notNull("options", options); WriteConcern writeConcern = options.getWriteConcern() != null ? options.getWriteConcern() : getWriteConcern(); com.mongodb.bulk.WriteRequest.Type updateType = !update.keySet().isEmpty() && update.keySet().iterator().next().startsWith("$") ? com.mongodb.bulk.WriteRequest.Type.UPDATE : com.mongodb.bulk.WriteRequest.Type.REPLACE; UpdateRequest updateRequest = new UpdateRequest(wrap(query), wrap(update, options.getEncoder()), updateType) .upsert(options.isUpsert()).multi(options.isMulti()) .collation(options.getCollation()) .arrayFilters(wrapAllowNull(options.getArrayFilters(), options.getEncoder())); return executeWriteOperation(new UpdateOperation(getNamespace(), true, writeConcern, retryWrites, singletonList(updateRequest)).bypassDocumentValidation(options.getBypassDocumentValidation())); }public WriteResult insert(final DBObject document, final WriteConcern writeConcern) { return insert(asList(document), writeConcern); }public Codec get(final Class clazz) { if (hasCycles(clazz)) { return new LazyCodec(registry, clazz); } else { return registry.get(new ChildCodecRegistry(this, clazz)); } }ReadPreference getCommandReadPreference(final DBObject command, @Nullable final ReadPreference requestedPreference) { String comString = command.keySet().iterator().next().toLowerCase(); boolean primaryRequired = !OBEDIENT_COMMANDS.contains(comString); if (primaryRequired) { return ReadPreference.primary(); } else if (requestedPreference == null) { return ReadPreference.primary(); } else { return requestedPreference; } }@Deprecated public WriteResult removeUser(final String userName) { try { executor.execute(new com.mongodb.operation.DropUserOperation(getName(), userName, getWriteConcern()), getReadConcern()); return new WriteResult(1, true, null); } catch (MongoWriteConcernException e) { throw createWriteConcernException(e); } }@Deprecated public CommandResult getStats() { BsonDocument commandDocument = new BsonDocument("dbStats", new BsonInt32(1)).append("scale", new BsonInt32(1)); return executeCommand(commandDocument); }@Deprecated public CommandResult doEval(final String code, final Object... args) { DBObject commandDocument = new BasicDBObject("$eval", code).append("args", asList(args)); return executeCommand(wrap(commandDocument)); }public boolean collectionExists(final String collectionName) { Set collectionNames = getCollectionNames(); for (final String name : collectionNames) { if (name.equalsIgnoreCase(collectionName)) { return true; } } return false; }public CommandResult command(final DBObject command, final ReadPreference readPreference) { return command(command, readPreference, null); }public CommandResult command(final DBObject command, final ReadPreference readPreference, @Nullable final DBEncoder encoder) { try { return executeCommand(wrap(command, encoder), getCommandReadPreference(command, readPreference)); } catch (MongoCommandException ex) { return new CommandResult(ex.getResponse(), ex.getServerAddress()); } }public Set getCollectionNames() { List collectionNames = new MongoIterableImpl(null, executor, ReadConcern.DEFAULT, primary(), mongo.getMongoClientOptions().getRetryReads()) { @Override public ReadOperation> asReadOperation() { return new ListCollectionsOperation(name, commandCodec) .nameOnly(true); } }.map(new Function() { @Override public String apply(final DBObject result) { return (String) result.get("name"); } }).into(new ArrayList()); Collections.sort(collectionNames); return new LinkedHashSet(collectionNames); }public void dropDatabase() { try { getExecutor().execute(new DropDatabaseOperation(getName(), getWriteConcern()), getReadConcern()); } catch (MongoWriteConcernException e) { throw createWriteConcernException(e); } }public DBCollection getCollection(final String name) { DBCollection collection = collectionCache.get(name); if (collection != null) { return collection; } collection = new DBCollection(name, this, executor); if (mongo.getMongoClientOptions().getDbDecoderFactory() != DefaultDBDecoder.FACTORY) { collection.setDBDecoderFactory(mongo.getMongoClientOptions().getDbDecoderFactory()); } if (mongo.getMongoClientOptions().getDbEncoderFactory() != DefaultDBEncoder.FACTORY) { collection.setDBEncoderFactory(mongo.getMongoClientOptions().getDbEncoderFactory()); } DBCollection old = collectionCache.putIfAbsent(name, collection); return old != null ? old : collection; }public static ClassModelBuilder builder(final Class type) { return new ClassModelBuilder(type); }public Object copy() { // copy field values into new object BasicDBList newobj = new BasicDBList(); // need to clone the sub obj for (int i = 0; i < size(); ++i) { Object val = get(i); if (val instanceof BasicDBObject) { val = ((BasicDBObject) val).copy(); } else if (val instanceof BasicDBList) { val = ((BasicDBList) val).copy(); } newobj.add(val); } return newobj; }public static MongoClient create(final ConnectionString connectionString, @Nullable final MongoDriverInformation mongoDriverInformation) { return create(MongoClientSettings.builder().applyConnectionString(connectionString).build(), mongoDriverInformation, connectionString.getStreamType()); }private ClusterableServer getRandomServer(final List serverDescriptions) { while (!serverDescriptions.isEmpty()) { int serverPos = getRandom().nextInt(serverDescriptions.size()); ClusterableServer server = getServer(serverDescriptions.get(serverPos).getAddress()); if (server != null) { return server; } else { serverDescriptions.remove(serverPos); } } return null; }@Deprecated public List getCredentialList() { return credential != null ? singletonList(credential) : Collections.emptyList(); }public static long readLong(final InputStream inputStream, final byte[] buffer) throws IOException { readFully(inputStream, buffer, 8); return readLong(buffer); }public static int readIntBE(final byte[] buffer, final int offset) { int x = 0; x |= (0xFF & buffer[offset + 0]) << 24; x |= (0xFF & buffer[offset + 1]) << 16; x |= (0xFF & buffer[offset + 2]) << 8; x |= (0xFF & buffer[offset + 3]) << 0; return x; }public static int readInt(final byte[] buffer, final int offset) { int x = 0; x |= (0xFF & buffer[offset + 0]) << 0; x |= (0xFF & buffer[offset + 1]) << 8; x |= (0xFF & buffer[offset + 2]) << 16; x |= (0xFF & buffer[offset + 3]) << 24; return x; }public static int readInt(final InputStream inputStream, final byte[] buffer) throws IOException { readFully(inputStream, buffer, 4); return readInt(buffer); }public static void readFully(final InputStream inputStream, final byte[] buffer, final int offset, final int length) throws IOException { if (buffer.length < length + offset) { throw new IllegalArgumentException("Buffer is too small"); } int arrayOffset = offset; int bytesToRead = length; while (bytesToRead > 0) { int bytesRead = inputStream.read(buffer, arrayOffset, bytesToRead); if (bytesRead < 0) { throw new EOFException(); } bytesToRead -= bytesRead; arrayOffset += bytesRead; } }public static TaggableReadPreference valueOf(final String name, final List tagSetList, final long maxStaleness, final TimeUnit timeUnit) { return valueOf(name, tagSetList, (Long) maxStaleness, timeUnit); }public static TaggableReadPreference valueOf(final String name, final List tagSetList) { return valueOf(name, tagSetList, null, MILLISECONDS); }public static ReadPreference valueOf(final String name) { notNull("name", name); String nameToCheck = name.toLowerCase(); if (nameToCheck.equals(PRIMARY.getName().toLowerCase())) { return PRIMARY; } if (nameToCheck.equals(SECONDARY.getName().toLowerCase())) { return SECONDARY; } if (nameToCheck.equals(SECONDARY_PREFERRED.getName().toLowerCase())) { return SECONDARY_PREFERRED; } if (nameToCheck.equals(PRIMARY_PREFERRED.getName().toLowerCase())) { return PRIMARY_PREFERRED; } if (nameToCheck.equals(NEAREST.getName().toLowerCase())) { return NEAREST; } throw new IllegalArgumentException("No match for read preference of " + name); }public static TaggableReadPreference nearest(final List tagSetList, final long maxStaleness, final TimeUnit timeUnit) { return new NearestReadPreference(tagSetList, maxStaleness, timeUnit); }public static TaggableReadPreference primaryPreferred(final List tagSetList, final long maxStaleness, final TimeUnit timeUnit) { return new PrimaryPreferredReadPreference(tagSetList, maxStaleness, timeUnit); }public static TaggableReadPreference nearest(final TagSet tagSet, final long maxStaleness, final TimeUnit timeUnit) { return new NearestReadPreference(singletonList(tagSet), maxStaleness, timeUnit); }public static TaggableReadPreference secondaryPreferred(final TagSet tagSet, final long maxStaleness, final TimeUnit timeUnit) { return new SecondaryPreferredReadPreference(singletonList(tagSet), maxStaleness, timeUnit); }public static TaggableReadPreference secondary(final TagSet tagSet, final long maxStaleness, final TimeUnit timeUnit) { return new SecondaryReadPreference(singletonList(tagSet), maxStaleness, timeUnit); }public static TaggableReadPreference primaryPreferred(final TagSet tagSet, final long maxStaleness, final TimeUnit timeUnit) { return new PrimaryPreferredReadPreference(singletonList(tagSet), maxStaleness, timeUnit); }public static ReadPreference nearest(final long maxStaleness, final TimeUnit timeUnit) { return new NearestReadPreference(Collections.emptyList(), maxStaleness, timeUnit); }public static ReadPreference secondaryPreferred(final long maxStaleness, final TimeUnit timeUnit) { return new SecondaryPreferredReadPreference(Collections.emptyList(), maxStaleness, timeUnit); }public static ReadPreference secondary(final long maxStaleness, final TimeUnit timeUnit) { return new SecondaryReadPreference(Collections.emptyList(), maxStaleness, timeUnit); }public static ReadPreference primaryPreferred(final long maxStaleness, final TimeUnit timeUnit) { return new PrimaryPreferredReadPreference(Collections.emptyList(), maxStaleness, timeUnit); }public final List choose(final ClusterDescription clusterDescription) { switch (clusterDescription.getType()) { case REPLICA_SET: return chooseForReplicaSet(clusterDescription); case SHARDED: case STANDALONE: return chooseForNonReplicaSet(clusterDescription); case UNKNOWN: return Collections.emptyList(); default: throw new UnsupportedOperationException("Unsupported cluster type: " + clusterDescription.getType()); } }@Deprecated @Override public BsonDocument execute(final WriteBinding binding) { return withConnection(binding, new CallableWithConnection() { @Override public BsonDocument call(final Connection connection) { if (serverIsAtLeastVersionThreeDotTwo(connection.getDescription())) { return executeCommand(binding, "admin", FSYNC_UNLOCK_COMMAND, connection); } else { return queryUnlock(connection); } } }); }Node replace(E newElement) { for (;;) { Node b = getPrev(); Node f = getNext(); if (b == null || f == null || f.isMarker()) return null; Node x = new Node(newElement, f, b); if (casNext(f, new Node(x))) { b.successor(); // to relink b x.successor(); // to relink f return x; } } }boolean delete() { Node b = getPrev(); Node f = getNext(); if (b != null && f != null && !f.isMarker() && casNext(f, new Node(f))) { if (b.casNext(this, f)) f.setPrev(b); return true; } return false; }Node prepend(E element) { for (;;) { Node b = predecessor(); if (b == null) return null; Node x = new Node(element, this, b); if (b.casNext(this, x)) { setPrev(x); // optimistically link return x; } } }Node append(E element) { for (;;) { Node f = getNext(); if (f == null || f.isMarker()) return null; Node x = new Node(element, f, this); if (casNext(f, x)) { f.setPrev(x); // optimistically link return x; } } }Node back() { Node f = predecessor(); return (f == null || f.isSpecial()) ? null : f; }Node forward() { Node f = successor(); return (f == null || f.isSpecial()) ? null : f; }Node predecessor() { Node n = this; for (;;) { Node b = n.getPrev(); if (b == null) return n.findPredecessorOf(this); Node s = b.getNext(); if (s == this) return b; if (s == null || !s.isMarker()) { Node p = b.findPredecessorOf(this); if (p != null) return p; } n = b; } }Node successor() { Node f = nextNonmarker(); for (;;) { if (f == null) return null; if (!f.isDeleted()) { if (f.getPrev() != this && !isDeleted()) f.setPrev(this); // relink f's prev return f; } Node s = f.nextNonmarker(); if (f == getNext()) casNext(f, s); // unlink f f = s; } }private Node nextNonmarker() { Node f = getNext(); return (f == null || !f.isMarker()) ? f : f.getNext(); }private boolean casNext(Node cmp, Node val) { return compareAndSet(cmp, val); }public MongoBulkWriteException getError() { return hasErrors() ? new MongoBulkWriteException(createResult(), new ArrayList(writeErrors), writeConcernErrors.isEmpty() ? null : writeConcernErrors.get(writeConcernErrors.size() - 1), serverAddress) : null; }public void addErrorResult(final List writeErrors, final WriteConcernError writeConcernError, final IndexMap indexMap) { mergeWriteErrors(writeErrors, indexMap); mergeWriteConcernError(writeConcernError); }public void addWriteErrorResult(final BulkWriteError writeError, final IndexMap indexMap) { notNull("writeError", writeError); mergeWriteErrors(asList(writeError), indexMap); }public void addErrorResult(final MongoBulkWriteException exception, final IndexMap indexMap) { addResult(exception.getWriteResult(), indexMap); mergeWriteErrors(exception.getWriteErrors(), indexMap); mergeWriteConcernError(exception.getWriteConcernError()); }public void addResult(final BulkWriteResult result, final IndexMap indexMap) { insertedCount += result.getInsertedCount(); matchedCount += result.getMatchedCount(); deletedCount += result.getDeletedCount(); modifiedCount += result.getModifiedCount(); mergeUpserts(result.getUpserts(), indexMap); }public BasicDBObjectBuilder push(final String key) { BasicDBObject o = new BasicDBObject(); _cur().put(key, o); _stack.addLast(o); return this; }@SuppressWarnings("unchecked") public static BasicDBObjectBuilder start(final Map documentAsMap) { BasicDBObjectBuilder builder = new BasicDBObjectBuilder(); Iterator i = documentAsMap.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = i.next(); builder.add(entry.getKey().toString(), entry.getValue()); } return builder; }public String getShortDescription() { return "{" + "address=" + address + ", type=" + type + (!tagSet.iterator().hasNext() ? "" : ", " + tagSet) + (state == CONNECTED ? (", roundTripTime=" + getRoundTripFormattedInMilliseconds() + " ms") : "") + ", state=" + state + (exception == null ? "" : ", exception=" + translateExceptionToString()) + '}'; }public String toHexString() { char[] chars = new char[OBJECT_ID_LENGTH * 2]; int i = 0; for (byte b : toByteArray()) { chars[i++] = HEX_CHARS[b >> 4 & 0xF]; chars[i++] = HEX_CHARS[b & 0xF]; } return new String(chars); }public void putToByteBuffer(final ByteBuffer buffer) { notNull("buffer", buffer); isTrueArgument("buffer.remaining() >=12", buffer.remaining() >= OBJECT_ID_LENGTH); buffer.put(int3(timestamp)); buffer.put(int2(timestamp)); buffer.put(int1(timestamp)); buffer.put(int0(timestamp)); buffer.put(int2(randomValue1)); buffer.put(int1(randomValue1)); buffer.put(int0(randomValue1)); buffer.put(short1(randomValue2)); buffer.put(short0(randomValue2)); buffer.put(int2(counter)); buffer.put(int1(counter)); buffer.put(int0(counter)); }public byte[] toByteArray() { ByteBuffer buffer = ByteBuffer.allocate(OBJECT_ID_LENGTH); putToByteBuffer(buffer); return buffer.array(); // using .allocate ensures there is a backing array that can be returned }protected void pipeExtraElements(final List extraElements) { notNull("extraElements", extraElements); for (BsonElement cur : extraElements) { writeName(cur.getName()); pipeValue(cur.getValue()); } }public void pipe(final BsonReader reader, final List extraElements) { notNull("reader", reader); notNull("extraElements", extraElements); pipeDocument(reader, extraElements); }protected boolean checkState(final State[] validStates) { for (final State cur : validStates) { if (cur == getState()) { return true; } } return false; }public T decodeWithChildContext(final Decoder decoder, final BsonReader reader) { return decoder.decode(reader, DEFAULT_CONTEXT); }public static long parse(final String string) { if (string.length() == 0) { throw new NumberFormatException("empty string"); } int radix = 10; int maxSafePos = MAX_SAFE_DIGITS[radix] - 1; long value = 0; for (int pos = 0; pos < string.length(); pos++) { int digit = Character.digit(string.charAt(pos), radix); if (digit == -1) { throw new NumberFormatException(string); } if (pos > maxSafePos && overflowInParse(value, digit, radix)) { throw new NumberFormatException("Too large for unsigned long: " + string); } value = (value * radix) + digit; } return value; }private int calculateBatchSize() { Integer batchSize = mongoIterable.getBatchSize(); if (batchSize != null) { return batchSize; } long requested = getRequested(); if (requested <= 1) { return 2; } else if (requested < Integer.MAX_VALUE) { return (int) requested; } else { return Integer.MAX_VALUE; } }public Codec get(final BsonType bsonType) { Codec codec = codecs[bsonType.getValue()]; if (codec == null) { Class clazz = bsonTypeClassMap.get(bsonType); if (clazz == null) { throw new CodecConfigurationException(format("No class mapped for BSON type %s.", bsonType)); } else { throw new CodecConfigurationException(format("Can't find a codec for %s.", clazz)); } } return codec; }@Deprecated public void validate() { if (fs == null) { throw new MongoException("no fs"); } if (md5 == null) { throw new MongoException("no md5 stored"); } DBObject cmd = new BasicDBObject("filemd5", id); cmd.put("root", fs.getBucketName()); DBObject res = fs.getDB().command(cmd); if (res != null && res.containsField("md5")) { String m = res.get("md5").toString(); if (m.equals(md5)) { return; } throw new MongoException("md5 differ. mine [" + md5 + "] theirs [" + m + "]"); } // no md5 from the server throw new MongoException("no md5 returned from server: " + res); }public static String generateIndexName(final BsonDocument index) { StringBuilder indexName = new StringBuilder(); for (final String keyNames : index.keySet()) { if (indexName.length() != 0) { indexName.append('_'); } indexName.append(keyNames).append('_'); BsonValue ascOrDescValue = index.get(keyNames); if (ascOrDescValue instanceof BsonNumber) { indexName.append(((BsonNumber) ascOrDescValue).intValue()); } else if (ascOrDescValue instanceof BsonString) { indexName.append(((BsonString) ascOrDescValue).getValue().replace(' ', '_')); } } return indexName.toString(); }public static List getIndexNames(final List indexes, final CodecRegistry codecRegistry) { List indexNames = new ArrayList(indexes.size()); for (IndexModel index : indexes) { String name = index.getOptions().getName(); if (name != null) { indexNames.add(name); } else { indexNames.add(IndexHelper.generateIndexName(index.getKeys().toBsonDocument(BsonDocument.class, codecRegistry))); } } return indexNames; }public PropertyModelBuilder readAnnotations(final List annotations) { this.readAnnotations = unmodifiableList(notNull("annotations", annotations)); return this; }@Nullable public String getErrorMessage() { Object foo = get("errmsg"); if (foo == null) { return null; } return foo.toString(); }public boolean ok() { Object okValue = get("ok"); if (okValue instanceof Boolean) { return (Boolean) okValue; } else if (okValue instanceof Number) { return ((Number) okValue).intValue() == 1; } else { return false; } }private void applyMajorityWriteConcernToTransactionOptions() { if (transactionOptions != null) { WriteConcern writeConcern = transactionOptions.getWriteConcern(); if (writeConcern != null) { transactionOptions = TransactionOptions.merge(TransactionOptions.builder() .writeConcern(writeConcern.withW("majority")).build(), transactionOptions); } else { transactionOptions = TransactionOptions.merge(TransactionOptions.builder() .writeConcern(WriteConcern.MAJORITY).build(), transactionOptions); } } else { transactionOptions = TransactionOptions.builder().writeConcern(WriteConcern.MAJORITY).build(); } }public QueryBuilder put(final String key) { _currentKey = key; if (_query.get(key) == null) { _query.put(_currentKey, new NullObject()); } return this; }@SuppressWarnings("deprecation") public int getMaxBsonObjectSize() { List primaries = getClusterDescription().getPrimaries(); return primaries.isEmpty() ? ServerDescription.getDefaultMaxDocumentSize() : primaries.get(0).getMaxDocumentSize(); }public boolean isMaster(final ServerAddress serverAddress) { ServerAddress masterServerAddress = getMaster(); return masterServerAddress != null && masterServerAddress.equals(serverAddress); }@SuppressWarnings("deprecation") @Nullable public ServerAddress getMaster() { List primaries = getClusterDescription().getPrimaries(); return primaries.isEmpty() ? null : primaries.get(0).getAddress(); }@SuppressWarnings("deprecation") @Nullable public String getName() { List any = getClusterDescription().getAnyPrimaryOrSecondary(); return any.isEmpty() ? null : any.get(0).getSetName(); }public MongoCompressor withProperty(final String key, final T value) { return new MongoCompressor(this, key, value); }public long getMaxTime(final TimeUnit timeUnit) { notNull("timeUnit", timeUnit); return timeUnit.convert(maxTimeMS, TimeUnit.MILLISECONDS); }public static Builder builder(final Class type) { return new Builder(notNull("type", type)); }public Object get(final String key) { int i = _getInt(key); if (i < 0) { return null; } if (i >= size()) { return null; } return get(i); }@Override public Object put(final String key, final Object v) { return put(_getInt(key), v); }public void remove(final DBObject query) { if (query == null) { throw new IllegalArgumentException("query can not be null"); } for (final GridFSDBFile f : find(query)) { f.remove(); } }public void remove(final ObjectId id) { if (id == null) { throw new IllegalArgumentException("file id can not be null"); } filesCollection.remove(new BasicDBObject("_id", id)); chunksCollection.remove(new BasicDBObject("files_id", id)); }public List find(final DBObject query, final DBObject sort) { List files = new ArrayList(); DBCursor cursor = filesCollection.find(query); if (sort != null) { cursor.sort(sort); } try { while (cursor.hasNext()) { files.add(injectGridFSInstance(cursor.next())); } } finally { cursor.close(); } return Collections.unmodifiableList(files); }public List find(final String filename, final DBObject sort) { return find(new BasicDBObject("filename", filename), sort); }public DBCursor getFileList(final DBObject query, final DBObject sort) { return filesCollection.find(query).sort(sort); }static Matrix parseTransform(String s) { //Log.d(TAG, s); Matrix matrix = new Matrix(); while (true) { parseTransformItem(s, matrix); int rparen = s.indexOf(")"); if (rparen > 0 && s.length() > rparen + 1) { s = s.substring(rparen + 1).replaceFirst("[\\s,]*", ""); } else { break; } } return matrix; }public static void notEmpty(String string, String msg) { if (string == null || string.length() == 0) throw new IllegalArgumentException(msg); }public static void noNullElements(Object[] objects, String msg) { for (Object obj : objects) if (obj == null) throw new IllegalArgumentException(msg); }public String consumeToAny(final char... chars) { bufferUp(); final int start = bufPos; final int remaining = bufLength; final char[] val = charBuf; OUTER: while (bufPos < remaining) { for (char c : chars) { if (val[bufPos] == c) break OUTER; } bufPos++; } return bufPos > start ? cacheString(charBuf, stringCache, start, bufPos - start) : ""; }@SuppressWarnings("resource") public static synchronized void initialize(AsyncHttpClientConfig cfg) { if (!_client.compareAndSet(null, new AsyncHttpClient(cfg))) { throw new RuntimeException("async http client concurrently initialized"); } }public static synchronized AsyncHttpClient getNingClient() { if (_client.get() == null) { initialize(new AsyncHttpClientConfig.Builder().build()); } return _client.get(); }private boolean tryAcquirePermit(String planClass) { return _concurrentPlans.tryAcquire() && (_planBasedRateLimiter == null || _planBasedRateLimiter.tryAcquire(planClass)); }private Task release() { return PlanLocal.get(getPlanLocalKey(), LockInternal.class).flatMap(lockInternal -> { // should never be null. if (lockInternal == null) { LOG.error("LockInternal is null when releasing lock: ", _lockPath); } else { lockInternal._lockCount--; if (lockInternal._lockCount == 0) { return PlanLocal.remove(getPlanLocalKey()) .flatMap(unused -> _zkClient.delete(lockInternal._lockNode, -1) .recover(e -> { _zkClient.deleteNode(lockInternal._lockNode); return null; }) ); } } return Task.value(null); }); }private Task acquire(long deadline) { final String uuid = UUID.randomUUID().toString(); return /* Step 1: create znode with a pathname of "_locknode_/guid-lock-" * and the sequence and ephemeral flags set. */ safeCreateLockNode(uuid, deadline, false) .onFailure(e -> _zkClient.deleteNodeHasUUID(_lockPath, uuid)) .flatMap(lockNode -> tryAcquire(lockNode, deadline) .withTimeout(deadline - System.currentTimeMillis(), TimeUnit.MILLISECONDS) .onFailure(e -> _zkClient.deleteNode(lockNode))); }@Deprecated public ParSeqRestliClientBuilder setRestClient(RestClient client) { ArgumentUtil.requireNotNull(client, "client"); _client = client; return this; }private static Exception failCoercion(final Object object, final Class targetType) { return new Exception("Could not convert object to " + targetType.getSimpleName() + ". Object is instance of: " + object.getClass().getName() + ", value: " + object.toString()); }private Promise run(Context context) { _startedAt = System.currentTimeMillis(); Task task = wrap(0); context.run(task); return task; }private void retry(int attempt, Throwable error, ErrorClassification errorClassification, Context recoveryContext, SettablePromise recoveryResult) { long backoffTime = _policy.getBackoffPolicy().nextBackoff(attempt, error); if (errorClassification == ErrorClassification.UNRECOVERABLE) { // For fatal errors there are no retries. LOGGER.debug(String.format("Attempt %s of %s interrupted: %s", attempt, _name, error.getMessage())); recoveryResult.fail(error); } else if (_policy.getTerminationPolicy().shouldTerminate(attempt, System.currentTimeMillis() - _startedAt + backoffTime)) { // Retry policy commands that no more retries should be done. LOGGER.debug(String.format("Too many exceptions after attempt %s of %s, aborting: %s", attempt, _name, error.getMessage())); recoveryResult.fail(error); } else { // Schedule a new retry task after a computed backoff timeout. LOGGER.debug(String.format("Attempt %s of %s failed and will be retried after %s millis: %s", attempt, _name, backoffTime, error.getMessage())); Task retryTask = wrap(attempt); Promises.propagateResult(retryTask, recoveryResult); recoveryContext.createTimer(backoffTime, TimeUnit.MILLISECONDS, retryTask); } }private Task wrap(int attempt) { Task retryTask = Task.async(_policy.getName() + ", attempt " + attempt, context -> { final SettablePromise result = Promises.settable(); Task task = _taskFunction.apply(attempt); final Task recovery = Task.async(_name + " recovery", recoveryContext -> { final SettablePromise recoveryResult = Promises.settable(); if (task.isFailed()) { // Failed task will cause retry to be scheduled. ErrorClassification errorClassification = _policy.getErrorClassifier().apply(task.getError()); retry(attempt + 1, task.getError(), errorClassification, recoveryContext, recoveryResult); } else { recoveryResult.done(task.get()); } return recoveryResult; }); // Recovery task should run immediately after the original task to process its error. recovery.setPriority(Priority.MAX_PRIORITY); recovery.getShallowTraceBuilder().setSystemHidden(true); Promises.propagateResult(recovery, result); context.after(task).run(recovery); context.run(task); return result; }); retryTask.getShallowTraceBuilder().setTaskType(TaskType.RETRY.getName()); return retryTask; }public static Task withRetryPolicy(String name, RetryPolicy policy, Function1> taskFunction) { RetriableTask retriableTask = new RetriableTask<>(name, policy, taskFunction); Task retryTaskWrapper = Task.async(name + " retriableTask", retriableTask::run); retryTaskWrapper.getShallowTraceBuilder().setTaskType(TaskType.WITH_RETRY.getName()); return retryTaskWrapper; }private void checkForStall(long currentTime) { long delta = currentTime - _lastMonitoringStep; if (delta < _shortestObservedDelta) { _shortestObservedDelta = delta; } long stall = Math.max(0, delta - _shortestObservedDelta); if (stall > _minStallNano) { _stalls.put(_lastMonitoringStep, stall); if (_stalls.size() > _stallsHistorySize) { _stalls.pollFirstEntry(); } } }private void monitor() { _lastMonitoringStep = _clock.nanoTime(); _nextAllowedLogging = _lastMonitoringStep; while(!_stopped) { try { _clock.sleepNano(_checkIntervalNano); } catch (InterruptedException e) { break; } monitorStep(); } }private void appendTaskStackTrace(final Throwable error) { StackTraceElement[] taskStackTrace = _taskStackTraceHolder != null ? _taskStackTraceHolder.getStackTrace() : null; // At a minimum, any stack trace should have at least 3 stack frames (caller + BaseTask + getStackTrace). // So if there are less than 3 stack frames available then there's something fishy and it's better to ignore them. if (!ParSeqGlobalConfiguration.isCrossThreadStackTracesEnabled() || error == null || taskStackTrace == null || taskStackTrace.length <= 2) { return; } StackTraceElement[] errorStackTrace = error.getStackTrace(); if (errorStackTrace.length <= 2) { return; } // Skip stack frames up to the BaseTask (useless java.util.concurrent stuff) int skipErrorFrames = 1; while (skipErrorFrames < errorStackTrace.length) { int index = errorStackTrace.length - 1 - skipErrorFrames; if (!errorStackTrace[index].getClassName().equals(CANONICAL_NAME) && errorStackTrace[index + 1].getClassName().equals(CANONICAL_NAME)) { break; } skipErrorFrames++; } // Safeguard against accidentally removing entire stack trace if (skipErrorFrames == errorStackTrace.length) { skipErrorFrames = 0; } // Skip stack frames up to the BaseTask (useless Thread.getStackTrace stuff) int skipTaskFrames = 1; while (skipTaskFrames < taskStackTrace.length) { if (!taskStackTrace[skipTaskFrames].getClassName().equals(CANONICAL_NAME) && taskStackTrace[skipTaskFrames - 1].getClassName().equals(CANONICAL_NAME)) { break; } skipTaskFrames++; } // Safeguard against accidentally removing entire stack trace if (skipTaskFrames == taskStackTrace.length) { skipTaskFrames = 0; } int combinedLength = errorStackTrace.length - skipErrorFrames + taskStackTrace.length - skipTaskFrames; if (combinedLength <= 0) { return; } StackTraceElement[] concatenatedStackTrace = new StackTraceElement[combinedLength + 1]; System.arraycopy(errorStackTrace, 0, concatenatedStackTrace, 0, errorStackTrace.length - skipErrorFrames); concatenatedStackTrace[errorStackTrace.length - skipErrorFrames] = new StackTraceElement("********** Task \"" + getName() + "\" (above) was instantiated as following (below): **********", "",null, 0); System.arraycopy(taskStackTrace, skipTaskFrames, concatenatedStackTrace, errorStackTrace.length - skipErrorFrames + 1, taskStackTrace.length - skipTaskFrames); error.setStackTrace(concatenatedStackTrace); }public static String findNodeWithNextLowestSN(List children, String node) { List sortedChildren = children.stream() .sorted((String o1, String o2) -> Long.compare(getSequenceNumber(o1), getSequenceNumber(o2))) .collect(Collectors.toList()); int index = sortedChildren.indexOf(node); if (index > 0) { return sortedChildren.get(index-1); } else if (index == 0) { return node; } else { return null; } }@Deprecated public static Task timeoutWithError(final long time, final TimeUnit unit, final Task task) { return task.withTimeout(time, unit); }@Deprecated public static Task withSideEffect(final Task parent, final Task sideEffect) { return parent.withSideEffect(t -> sideEffect); }Task> createConnectionsSummaries(int id) { return fetchPerson(id).flatMap("createConnectionsSummaries", person -> createConnectionsSummaries(person.getConnections())); }Task createResponsiveSummary(int id) { return fetchPerson(id).withTimeout(100, TimeUnit.MILLISECONDS).map(this::shortSummary).recover(e -> "Member " + id); }Task createResilientSummary(int id) { return fetchPerson(id).map(this::shortSummary).recover(e -> "Member " + id); }public static void propagateResult(final Promise source, final Settable dest) { source.addListener(new TransformingPromiseListener(dest, PromiseTransformer.identity())); }@SuppressWarnings("unchecked") public static Promise value(final T value) { if (value == null) { if (VOID == null) { return new ResolvedValue(value); } else { return (Promise) VOID; } } return new ResolvedValue(value); }public EngineBuilder setEngineProperty(String key, Object value) { _properties.put(key, value); return this; }public static FusionTask create(final String name, final Task task, final PromisePropagator propagator) { return new FusionTask(name, task, propagator); }private Consumer3, Settable> compose( final Consumer3, Settable> predecessor, final Consumer3, Settable> propagator) { return (traceContext, src, dst) -> { /* * At this point we know that transformation chain's length > 1. * This code is executed during task execution, not when task is constructed. */ traceContext.createSurrogate(); predecessor.accept(traceContext, src, new Settable() { @Override public void done(R value) throws PromiseResolvedException { try { /* Track start time of the transformation. End time is tracked by closure created by completing() */ getEffectiveShallowTraceBuilder(traceContext).setStartNanos(System.nanoTime()); propagator.accept(traceContext, Promises.value(value), dst); } catch (Exception e) { /* This can only happen if there is an internal problem. Propagators should not throw any exceptions. */ LOGGER.error("ParSeq ingternal error. An exception was thrown by propagator", e); } } @Override public void fail(Throwable error) throws PromiseResolvedException { try { /* Track start time of the transformation. End time is tracked by closure created by completing() */ getEffectiveShallowTraceBuilder(traceContext).setStartNanos(System.nanoTime()); propagator.accept(traceContext, Promises.error(error), dst); } catch (Exception e) { /* This can only happen if there is an internal problem. Propagators should not throw any exceptions. */ LOGGER.error("ParSeq ingternal error. An exception was thrown by propagator.", e); } } }); }; }private static ParSeqRestliClientConfig createDefaultConfig() { ParSeqRestliClientConfigBuilder builder = new ParSeqRestliClientConfigBuilder(); builder.addTimeoutMs("*.*/*.*", DEFAULT_TIMEOUT); builder.addBatchingEnabled("*.*/*.*", DEFAULT_BATCHING_ENABLED); builder.addMaxBatchSize("*.*/*.*", DEFAULT_MAX_BATCH_SIZE); return builder.build(); }public synchronized T harvest(Function consumer) { initializeRecorder(); _recycle = _recorder.getIntervalHistogram(_recycle); return consumer.apply(_recycle); }public String getBatchName(G group, Batch batch) { return "batch(keys: " + batch.keySize() + ", size: " + batch.batchSize() + ")"; }public Task batchable(final String desc, final K key) { Task batchableTask = Task.async(desc, ctx -> { final BatchPromise result = new BatchPromise<>(); final Long planId = ctx.getPlanId(); final GroupBatchBuilder builder = _batches.computeIfAbsent(planId, k -> new GroupBatchBuilder()); final G group = classify(key); Batch fullBatch = builder.add(group, key, ctx.getShallowTraceBuilder(), result); if (fullBatch != null) { try { ctx.run(taskForBatch(group, fullBatch, true)); } catch (Throwable t) { //we don't care if some of promises have already been completed //all we care is that all remaining promises have been failed fullBatch.failAll(t); } } return result; }); batchableTask.getShallowTraceBuilder().setTaskType("batched"); return batchableTask; }public static Trace single(ShallowTrace shallowTrace) { return single(shallowTrace, TraceBuilder.UNKNOWN_PLAN_CLASS, TraceBuilder.UNKNOWN_PLAN_ID); }private String writeGenericFailureInfo(final Exec.Result result) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("graphviz process returned: ").append(result.getStatus()).append("\n").append("stdout:\n"); Files.lines(result.getStdout()).forEach(sb::append); sb.append("stderr:\n"); Files.lines(result.getStderr()).forEach(sb::append); return sb.toString(); }private Task createNewBuildTask(final String hash, final InputStream body) { LOG.info("building: " + hash); final Task createDotFile = Task.action("createDotFile", () -> Files.copy(body, pathToCacheFile(hash, "dot"), StandardCopyOption.REPLACE_EXISTING)); // Task that runs a graphviz command. // We give process TIMEOUT_MS time to finish, after that // it will be forcefully killed. final Task graphviz = _exec .command("graphviz", _timeoutMs, TimeUnit.MILLISECONDS, _dotLocation, "-T" + Constants.OUTPUT_TYPE, "-Grankdir=LR", "-Gnewrank=true", "-Gbgcolor=transparent", pathToCacheFile(hash, "dot").toString(), "-o", pathToCacheFile(hash, Constants.OUTPUT_TYPE).toString()); // Since Exec utility allows only certain number of processes // to run in parallel and rest is enqueued, we also specify // timeout on a task level equal to 2 * graphviz timeout. final Task graphvizWithTimeout = graphviz.withTimeout(_timeoutMs * 2, TimeUnit.MILLISECONDS); return createDotFile.andThen(graphvizWithTimeout); }private Task getBuildTask(final String hash, final InputStream body) { Task existing = _inFlightBuildTasks.get(hash); if (existing != null) { LOG.info("using in flight shareable: " + hash); return existing.shareable(); } else { Task newBuildTask = createNewBuildTask(hash, body); existing = _inFlightBuildTasks.putIfAbsent(hash, newBuildTask); if (existing != null) { LOG.info("using in flight shareable: " + hash); return existing.shareable(); } else { return newBuildTask; } } }public Task build(final String hash, final InputStream body) throws IOException { if (hash == null) { // Missing hash String content = "Missing hash."; LOG.info(content); return Task.value(new HttpResponse(HttpServletResponse.SC_BAD_REQUEST, content)); } else { // Have cache if (_hashManager.contains(hash)) { LOG.info("hash found in cache: " + hash); return Task.value(new HttpResponse(HttpServletResponse.SC_OK, "")); } else { if (body == null) { // Missing body String content = "Missing body."; LOG.info(content); return Task.value(new HttpResponse(HttpServletResponse.SC_BAD_REQUEST, content)); } else if (_dotLocation == null) { // Missing dot String content = "Missing dot."; LOG.info(content); return Task.value(new HttpResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, content)); } else { // Build task final Task buildTask = getBuildTask(hash, body); return buildTask.transform("result", result -> { Integer status = null; String content = null; if (result.isFailed()) { // Task fail status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; content = result.getError().toString(); } else { // Task success switch (result.get().getStatus()) { // Success case 0: _hashManager.add(hash); status = HttpServletResponse.SC_OK; content = ""; break; // Timeout case 137: status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; content = "graphviz process was killed because it did not finish within " + _timeoutMs + "ms"; break; // Unknown default: status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; content = writeGenericFailureInfo(result.get()); break; } } // Clean up cache _inFlightBuildTasks.remove(hash, buildTask); return Success.of(new HttpResponse(status, content)); }); } } } }private Task> createTaskWithTimeout(final String name, final Request request, final RequestContext requestContext, RequestConfig config) { ConfigValue timeout = config.getTimeoutMs(); Task> requestTask; if (RequestGroup.isBatchable(request, config)) { requestTask = createBatchableTask(name, request, requestContext, config); } else { requestTask = Task.async(name, () -> sendRequest(request, requestContext)); } if (!needApplyTaskTimeout(requestContext, timeout)) { return requestTask; } else { return withTimeout(requestTask, timeout); } }private boolean needApplyTaskTimeout(RequestContext requestContext, ConfigValue timeout) { // return false if no timeout configured or per-request timeout already specified in request context return timeout.getValue() != null && timeout.getValue() > 0 && !hasRequestContextTimeout(requestContext); }private boolean hasRequestContextTimeout(RequestContext requestContext) { Object requestTimeout = requestContext.getLocalAttr(R2Constants.REQUEST_TIMEOUT); return (requestTimeout instanceof Number) && (((Number)requestTimeout).intValue() > 0); }static String generateTaskName(final Request request) { return request.getBaseUriTemplate() + " " + OperationNameGenerator.generate(request.getMethod(), request.getMethodName()); }public long getProblemScale(Solution_ solution) { long problemScale = 0L; for (Iterator it = extractAllEntitiesIterator(solution); it.hasNext(); ) { Object entity = it.next(); EntityDescriptor entityDescriptor = findEntityDescriptorOrFail(entity.getClass()); problemScale += entityDescriptor.getProblemScale(solution, entity); } return problemScale; }public void checkIfProblemFactsExist() { if (problemFactCollectionMemberAccessorMap.isEmpty() && problemFactMemberAccessorMap.isEmpty()) { throw new IllegalStateException("The solutionClass (" + solutionClass + ") must have at least 1 member with a " + ProblemFactCollectionProperty.class.getSimpleName() + " annotation or a " + ProblemFactProperty.class.getSimpleName() + " annotation" + " when used with Drools score calculation."); } }public long calculateStandardDeviationSquaredFemtos() { long totalFemtos = 0L; for (AssetClassAllocation a : assetClassAllocationList) { for (AssetClassAllocation b : assetClassAllocationList) { if (a == b) { totalFemtos += a.getQuantifiedStandardDeviationRiskMicros() * b.getQuantifiedStandardDeviationRiskMicros() * 1000L; } else { // Matches twice: once for (A, B) and once for (B, A) long correlationMillis = a.getAssetClass().getCorrelationMillisMap().get(b.getAssetClass()); totalFemtos += a.getQuantifiedStandardDeviationRiskMicros() * b.getQuantifiedStandardDeviationRiskMicros() * correlationMillis; } } } return totalFemtos; }public static String cleanPath(final URL url) { String path = url.getPath(); try { path = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { /**/ } if (path.startsWith("jar:")) { path = path.substring("jar:".length()); } if (path.startsWith("file:")) { path = path.substring("file:".length()); } if (path.endsWith("!/")) { path = path.substring(0, path.lastIndexOf("!/")) + "/"; } return path; }public void addSoftConstraintMatch(RuleContext kcontext, BigDecimal softWeight) { softScore = softScore.add(softWeight); registerConstraintMatch(kcontext, () -> softScore = softScore.subtract(softWeight), () -> HardMediumSoftBigDecimalScore.of(BigDecimal.ZERO, BigDecimal.ZERO, softWeight)); }public void addMediumConstraintMatch(RuleContext kcontext, BigDecimal mediumWeight) { mediumScore = mediumScore.add(mediumWeight); registerConstraintMatch(kcontext, () -> mediumScore = mediumScore.subtract(mediumWeight), () -> HardMediumSoftBigDecimalScore.of(BigDecimal.ZERO, mediumWeight, BigDecimal.ZERO)); }public void addHardConstraintMatch(RuleContext kcontext, BigDecimal hardWeight) { hardScore = hardScore.add(hardWeight); registerConstraintMatch(kcontext, () -> hardScore = hardScore.subtract(hardWeight), () -> HardMediumSoftBigDecimalScore.of(hardWeight, BigDecimal.ZERO, BigDecimal.ZERO)); }public static boolean isGetterMethod(Method method) { if (method.getParameterTypes().length != 0) { return false; } String methodName = method.getName(); if (methodName.startsWith(PROPERTY_ACCESSOR_PREFIX_GET) && method.getReturnType() != void.class) { return true; } else if (methodName.startsWith(PROPERTY_ACCESSOR_PREFIX_IS) && method.getReturnType() == boolean.class) { return true; } return false; }public static String getGetterPropertyName(Member member) { if (member instanceof Field) { return member.getName(); } else if (member instanceof Method) { String methodName = member.getName(); for (String prefix : PROPERTY_ACCESSOR_PREFIXES) { if (methodName.startsWith(prefix)) { return decapitalizePropertyName(methodName.substring(prefix.length())); } } } return null; }public static void main(String[] args) { CloudBalancingGenerator generator = new CloudBalancingGenerator(); generator.writeCloudBalance(2, 6); generator.writeCloudBalance(3, 9); generator.writeCloudBalance(4, 12); // generator.writeCloudBalance(5, 15); // generator.writeCloudBalance(6, 18); // generator.writeCloudBalance(7, 21); // generator.writeCloudBalance(8, 24); // generator.writeCloudBalance(9, 27); // generator.writeCloudBalance(10, 30); // generator.writeCloudBalance(11, 33); // generator.writeCloudBalance(12, 36); // generator.writeCloudBalance(13, 39); // generator.writeCloudBalance(14, 42); // generator.writeCloudBalance(15, 45); // generator.writeCloudBalance(16, 48); // generator.writeCloudBalance(17, 51); // generator.writeCloudBalance(18, 54); // generator.writeCloudBalance(19, 57); // generator.writeCloudBalance(20, 60); generator.writeCloudBalance(100, 300); generator.writeCloudBalance(200, 600); generator.writeCloudBalance(400, 1200); generator.writeCloudBalance(800, 2400); generator.writeCloudBalance(1600, 4800); }@Override public V computeIfAbsent(K key, Function mappingFunction) { // This might look like a Double Checked Idiom (which is broken), but it is not // because value is not a global variable V value = get(key); if (value != null) { return value; } return super.computeIfAbsent(key, mappingFunction); }public double getAngle(Location location) { // Euclidean distance (Pythagorean theorem) - not correct when the surface is a sphere double latitudeDifference = location.latitude - latitude; double longitudeDifference = location.longitude - longitude; return Math.atan2(latitudeDifference, longitudeDifference); }@Override public PollResult poll(boolean initial, Object checkPoint) throws IOException { if (configUrls == null || configUrls.length == 0) { return PollResult.createFull(null); } Map map = new HashMap(); for (URL url: configUrls) { InputStream fin = url.openStream(); Properties props = ConfigurationUtils.loadPropertiesFromInputStream(fin); for (Entry entry: props.entrySet()) { map.put((String) entry.getKey(), entry.getValue()); } } return PollResult.createFull(map); }public static void loadProperties(Properties properties) { if (instance == null) { instance = getConfigInstance(); } ConfigurationUtils.loadProperties(properties, instance); }public static void loadPropertiesFromConfiguration(AbstractConfiguration config) { if (instance == null) { instance = getConfigInstance(); } if (instance instanceof AggregatedConfiguration) { ((AggregatedConfiguration) instance).addConfiguration(config); } else { Properties props = ConfigurationUtils.getProperties(config); ConfigurationUtils.loadProperties(props, instance); } }public static void loadCascadedPropertiesFromResources(String configName) throws IOException { Properties props = loadCascadedProperties(configName); if (instance instanceof AggregatedConfiguration) { ConcurrentMapConfiguration config = new ConcurrentMapConfiguration(); config.loadProperties(props); ((AggregatedConfiguration) instance).addConfiguration(config, configName); } else { ConfigurationUtils.loadProperties(props, instance); } }@Override public String[] getStringArray(String key) { List list = getList(key); // transform property values into strings String[] tokens = new String[list.size()]; for (int i = 0; i < tokens.length; i++) { tokens[i] = String.valueOf(list.get(i)); } return tokens; }@Override public List getList(String key, List defaultValue) { List list = new ArrayList(); // add all elements from the first configuration containing the requested key Iterator it = configList.iterator(); if (overrideProperties.containsKey(key)) { appendListProperty(list, overrideProperties, key); } while (it.hasNext() && list.isEmpty()) { Configuration config = it.next(); if ((config != containerConfiguration || containerConfigurationChanged) && config.containsKey(key)) { appendListProperty(list, config, key); } } // add all elements from the in memory configuration if (list.isEmpty()) { appendListProperty(list, containerConfiguration, key); } if (list.isEmpty()) { return defaultValue; } ListIterator lit = list.listIterator(); while (lit.hasNext()) { lit.set(interpolate(lit.next())); } return list; }@Override public boolean containsKey(String key) { if (overrideProperties.containsKey(key)) { return true; } for (Configuration config : configList) { if (config.containsKey(key)) { return true; } } return false; }@Override public Iterator getKeys(String prefix) { Set keys = new LinkedHashSet(); for (Iterator it = overrideProperties.getKeys(prefix); it.hasNext();) { keys.add(it.next()); } for (Configuration config : configList) { for (Iterator it = config.getKeys(prefix); it.hasNext();) { keys.add(it.next()); } } return keys.iterator(); }public Iterator getKeys() throws ConcurrentModificationException { Set keys = new LinkedHashSet(); for (Iterator it = overrideProperties.getKeys(); it.hasNext();) { keys.add(it.next()); } for (Configuration config : configList) { for (Iterator it = config.getKeys(); it.hasNext();) { try { keys.add(it.next()); } catch (ConcurrentModificationException e) { logger.error("unexpected exception when iterating the keys for configuration " + config + " with name " + getNameForConfiguration(config)); throw e; } } } return keys.iterator(); }public Configuration removeConfiguration(String name) { Configuration conf = getConfiguration(name); if (conf != null && !conf.equals(containerConfiguration)) { configList.remove(conf); namedConfigurations.remove(name); } else if (conf != null && conf.equals(containerConfiguration)) { throw new IllegalArgumentException("Can't remove container configuration"); } return conf; }public boolean removeConfiguration(Configuration config) { // Make sure that you can't remove the inMemoryConfiguration from // the CompositeConfiguration object if (!config.equals(containerConfiguration)) { String configName = getNameForConfiguration(config); if (configName != null) { namedConfigurations.remove(configName); } return configList.remove(config); } else { throw new IllegalArgumentException("Can't remove container configuration"); } }public void addConfigurationAtIndex(AbstractConfiguration config, String name, int index) throws IndexOutOfBoundsException { if (!configList.contains(config)) { checkIndex(index); configList.add(index, config); if (name != null) { namedConfigurations.put(name, config); } config.addConfigurationListener(eventPropagater); fireEvent(EVENT_CONFIGURATION_SOURCE_CHANGED, null, null, false); } else { logger.warn(config + " is not added as it already exits"); } }protected synchronized void initialLoad(final PolledConfigurationSource source, final Configuration config) { PollResult result = null; try { result = source.poll(true, null); checkPoint = result.getCheckPoint(); fireEvent(EventType.POLL_SUCCESS, result, null); } catch (Throwable e) { throw new RuntimeException("Unable to load Properties source from " + source, e); } try { populateProperties(result, config); } catch (Throwable e) { throw new RuntimeException("Unable to load Properties", e); } }public Properties getProperties() { Properties p = new Properties(); for (Iterator i = getKeys(); i.hasNext();) { String name = (String) i.next(); String value = getString(name); p.put(name, value); } return p; }@Override public void clear() { fireEvent(EVENT_CLEAR, null, null, true); map.clear(); fireEvent(EVENT_CLEAR, null, null, false); }void deleteProperty(final String key, final Configuration config) { if (config.containsKey(key)) { logger.debug("deleting property key [" + key + "]"); config.clearProperty(key); } }void addOrChangeProperty(final String name, final Object newValue, final Configuration config) { // We do not want to abort the operation due to failed validation on one property try { if (!config.containsKey(name)) { logger.debug("adding property key [{}], value [{}]", name, newValue); config.addProperty(name, newValue); } else { Object oldValue = config.getProperty(name); if (newValue != null) { Object newValueArray; if (oldValue instanceof CopyOnWriteArrayList && AbstractConfiguration.getDefaultListDelimiter() != '\0'){ newValueArray = new CopyOnWriteArrayList(); Iterable stringiterator = Splitter.on(AbstractConfiguration.getDefaultListDelimiter()).omitEmptyStrings().trimResults().split((String)newValue); for(String s :stringiterator){ ((CopyOnWriteArrayList) newValueArray).add(s); } } else { newValueArray = newValue; } if (!newValueArray.equals(oldValue)) { logger.debug("updating property key [{}], value [{}]", name, newValue); config.setProperty(name, newValue); } } else if (oldValue != null) { logger.debug("nulling out property key [{}]", name); config.setProperty(name, null); } } } catch (ValidationException e) { logger.warn("Validation failed for property " + name, e); } }public void updateProperties(final WatchedUpdateResult result, final Configuration config, final boolean ignoreDeletesFromSource) { if (result == null || !result.hasChanges()) { return; } logger.debug("incremental result? [{}]", result.isIncremental()); logger.debug("ignored deletes from source? [{}]", ignoreDeletesFromSource); if (!result.isIncremental()) { Map props = result.getComplete(); if (props == null) { return; } for (Entry entry : props.entrySet()) { addOrChangeProperty(entry.getKey(), entry.getValue(), config); } Set existingKeys = new HashSet(); for (Iterator i = config.getKeys(); i.hasNext();) { existingKeys.add(i.next()); } if (!ignoreDeletesFromSource) { for (String key : existingKeys) { if (!props.containsKey(key)) { deleteProperty(key, config); } } } } else { Map props = result.getAdded(); if (props != null) { for (Entry entry : props.entrySet()) { addOrChangeProperty(entry.getKey(), entry.getValue(), config); } } props = result.getChanged(); if (props != null) { for (Entry entry : props.entrySet()) { addOrChangeProperty(entry.getKey(), entry.getValue(), config); } } if (!ignoreDeletesFromSource) { props = result.getDeleted(); if (props != null) { for (String name : props.keySet()) { deleteProperty(name, config); } } } } }@Override public void addProperty(String name, Object value) { if (containsKey(name)) { // clear without triggering an event clearPropertyDirect(name); } super.addProperty(name, value); }public static Properties loadPropertiesFromInputStream(InputStream fin) throws IOException { Properties props = new Properties(); InputStreamReader reader = new InputStreamReader(fin, "UTF-8"); try { props.load(reader); return props; } finally { if (reader != null) { reader.close(); } if (fin != null) { fin.close(); } } }public static HttpVerbUriRegexPropertyValue getVerbUriRegex(String propValue) { HttpVerbUriRegexPropertyValue returnValue = null; if (propValue != null) { propValue = propValue.trim(); int methodSeparatorIndex = propValue.indexOf(METHOD_SEPARATOR); String uriRegex = propValue; // to begin with Verb verb = Verb.ANY_VERB; if (methodSeparatorIndex != -1) { // user may have supplied a verb verb = getVerb(propValue.substring(0, methodSeparatorIndex)); if (verb != Verb.ANY_VERB) { // update uriRegex uriRegex = propValue.substring(methodSeparatorIndex + 1); } } returnValue = new HttpVerbUriRegexPropertyValue(verb, uriRegex); } return returnValue; }@Override public void removeAllCallbacks() { final Set callbacksToRemove = new HashSet(callbacks); for (Runnable callback : callbacksToRemove) { prop.removeCallback(callback); } callbacks.removeAll(callbacksToRemove); }@Override public void addCallback(Runnable callback) { if (callback != null) { prop.addCallback(callback); callbacks.add(callback); } }private static boolean updateAllProperties() { boolean changed = false; for (DynamicProperty prop : ALL_PROPS.values()) { if (prop.updateValue()) { prop.notifyCallbacks(); changed = true; } } return changed; }public static DynamicProperty getInstance(String propName) { // This is to ensure that a configuration source is registered with // DynamicProperty if (dynamicPropertySupportImpl == null) { DynamicPropertyFactory.getInstance(); } DynamicProperty prop = ALL_PROPS.get(propName); if (prop == null) { prop = new DynamicProperty(propName); DynamicProperty oldProp = ALL_PROPS.putIfAbsent(propName, prop); if (oldProp != null) { prop = oldProp; } } return prop; }@Override protected Map loadPropertiesFromTable(String table) { Map propertyMap = new HashMap(); Map lastKeysEvaluated = null; do { ScanRequest scanRequest = new ScanRequest() .withTableName(table) .withExclusiveStartKey(lastKeysEvaluated); ScanResult result = dbScanWithThroughputBackOff(scanRequest); for (Map item : result.getItems()) { String keyVal = item.get(keyAttributeName.get()).getS(); //Need to deal with the fact that these attributes might not exist DeploymentContext.ContextKey contextKey = item.containsKey(contextKeyAttributeName.get()) ? DeploymentContext.ContextKey.valueOf(item.get(contextKeyAttributeName.get()).getS()) : null; String contextVal = item.containsKey(contextValueAttributeName.get()) ? item.get(contextValueAttributeName.get()).getS() : null; String key = keyVal + ";" + contextKey + ";" + contextVal; propertyMap.put(key, new PropertyWithDeploymentContext( contextKey, contextVal, keyVal, item.get(valueAttributeName.get()).getS() )); } lastKeysEvaluated = result.getLastEvaluatedKey(); } while (lastKeysEvaluated != null); return propertyMap; }public DynamicDoubleProperty getDoubleProperty(String propName, double defaultValue, final Runnable propertyChangeCallback) { checkAndWarn(propName); DynamicDoubleProperty property = new DynamicDoubleProperty(propName, defaultValue); addCallback(propertyChangeCallback, property); return property; }public DynamicFloatProperty getFloatProperty(String propName, float defaultValue, final Runnable propertyChangeCallback) { checkAndWarn(propName); DynamicFloatProperty property = new DynamicFloatProperty(propName, defaultValue); addCallback(propertyChangeCallback, property); return property; }public DynamicBooleanProperty getBooleanProperty(String propName, boolean defaultValue, final Runnable propertyChangeCallback) { checkAndWarn(propName); DynamicBooleanProperty property = new DynamicBooleanProperty(propName, defaultValue); addCallback(propertyChangeCallback, property); return property; }public DynamicLongProperty getLongProperty(String propName, long defaultValue, final Runnable propertyChangeCallback) { checkAndWarn(propName); DynamicLongProperty property = new DynamicLongProperty(propName, defaultValue); addCallback(propertyChangeCallback, property); return property; }public DynamicIntProperty getIntProperty(String propName, int defaultValue, final Runnable propertyChangeCallback) { checkAndWarn(propName); DynamicIntProperty property = new DynamicIntProperty(propName, defaultValue); addCallback(propertyChangeCallback, property); return property; }public static void setAppConfFolder(File appConfFolderFromConfig, String baseConfigFileName) { WebApplicationProperties.appConfFolder = appConfFolderFromConfig; WebApplicationProperties.baseConfigFileName = baseConfigFileName; }public void start() throws Exception { // create the watcher for future configuration updatess pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() { public void childEvent(CuratorFramework aClient, PathChildrenCacheEvent event) throws Exception { Type eventType = event.getType(); ChildData data = event.getData(); String path = null; if (data != null) { path = data.getPath(); // scrub configRootPath out of the key name String key = removeRootPath(path); byte[] value = data.getData(); String stringValue = new String(value, charset); logger.debug("received update to pathName [{}], eventType [{}]", path, eventType); logger.debug("key [{}], and value [{}]", key, stringValue); // fire event to all listeners Map added = null; Map changed = null; Map deleted = null; if (eventType == Type.CHILD_ADDED) { added = new HashMap(1); added.put(key, stringValue); } else if (eventType == Type.CHILD_UPDATED) { changed = new HashMap(1); changed.put(key, stringValue); } else if (eventType == Type.CHILD_REMOVED) { deleted = new HashMap(1); deleted.put(key, stringValue); } WatchedUpdateResult result = WatchedUpdateResult.createIncremental(added, changed, deleted); fireEvent(result); } } }); // passing true to trigger an initial rebuild upon starting. (blocking call) pathChildrenCache.start(true); }public synchronized void startPolling(PolledConfigurationSource source, AbstractPollingScheduler scheduler) { this.scheduler = scheduler; this.source = source; init(source, scheduler); scheduler.startPolling(source, this); }private boolean isClosed() { if (!verifyReader) { return false; } try { br.mark(READ_AHEAD_LIMIT); int nextByte = br.read(); br.reset(); // resets stream position, possible because its buffered return nextByte == -1; // read() returns -1 at end of stream } catch (IOException e) { return true; } }protected String getNextLine() throws IOException { if (isClosed()) { hasNext = false; return null; } if (!this.linesSkiped) { for (int i = 0; i < skipLines; i++) { lineReader.readLine(); linesRead++; } this.linesSkiped = true; } String nextLine = lineReader.readLine(); if (nextLine == null) { hasNext = false; } else { linesRead++; } return hasNext ? nextLine : null; }public String[] readNext() throws IOException { String[] result = null; do { String nextLine = getNextLine(); if (!hasNext) { return validateResult(result); } String[] r = parser.parseLineMulti(nextLine); if (r.length > 0) { if (result == null) { result = r; } else { result = combineResultsFromMultipleReads(result, r); } } } while (parser.isPending()); return validateResult(result); }protected String[] getDatabaseSchemaNames(Database database) throws SQLException, DatabaseException { List returnList = new ArrayList<>(); ResultSet schemas = null; try { schemas = ((JdbcConnection) database.getConnection()).getMetaData().getSchemas(); while (schemas.next()) { returnList.add(JdbcUtils.getValueForColumn(schemas, "TABLE_SCHEM", database)); } } finally { if (schemas != null) { schemas.close(); } } return returnList.toArray(new String[returnList.size()]); }private static char[] encodeHex(byte[] data) { int l = data.length; char[] out = new char[l << 1]; // two characters form the hex value. for (int i = 0, j = 0; i < l; i++) { out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4]; out[j++] = DIGITS_LOWER[0x0F & data[i]]; } return out; }public static String addSchemaToText(String procedureText, String schemaName, String keywordBeforeName, Database database) { if (schemaName == null) { return procedureText; } if ((StringUtil.trimToNull(schemaName) != null) && LiquibaseConfiguration.getInstance().getProperty(ChangeLogParserCofiguration.class, ChangeLogParserCofiguration.USE_PROCEDURE_SCHEMA).getValue(Boolean.class)) { StringClauses parsedSql = SqlParser.parse(procedureText, true, true); StringClauses.ClauseIterator clauseIterator = parsedSql.getClauseIterator(); Object next = "START"; while ((next != null) && !next.toString().equalsIgnoreCase(keywordBeforeName) && clauseIterator.hasNext()) { if (!"PACKAGE".equalsIgnoreCase(keywordBeforeName) && "PACKAGE".equalsIgnoreCase((String) next)) { return procedureText; } next = clauseIterator.nextNonWhitespace(); } if ((next != null) && clauseIterator.hasNext()) { Object procNameClause = clauseIterator.nextNonWhitespace(); if (procNameClause instanceof String) { String[] nameParts = ((String) procNameClause).split("\\."); String finalName; if (nameParts.length == 1) { finalName = database.escapeObjectName(schemaName, Schema.class) + "." + nameParts[0]; } else if (nameParts.length == 2) { finalName = database.escapeObjectName(schemaName, Schema.class) + "." + nameParts[1]; } else if (nameParts.length == 3) { finalName = nameParts[0] + "." + database.escapeObjectName(schemaName, Schema.class) + "." + nameParts[2]; } else { finalName = (String) procNameClause; //just go with what was there } clauseIterator.replace(finalName); } procedureText = parsedSql.toString(); } } return procedureText; }public static void surroundWithSchemaSets(List sql, String schemaName, Database database) { if ((StringUtil.trimToNull(schemaName) != null) && !LiquibaseConfiguration.getInstance().getProperty(ChangeLogParserCofiguration.class, ChangeLogParserCofiguration.USE_PROCEDURE_SCHEMA).getValue(Boolean.class)) { String defaultSchema = database.getDefaultSchemaName(); if (database instanceof OracleDatabase) { sql.add(0, new UnparsedSql("ALTER SESSION SET CURRENT_SCHEMA=" + database.escapeObjectName(schemaName, Schema.class))); sql.add(new UnparsedSql("ALTER SESSION SET CURRENT_SCHEMA=" + database.escapeObjectName(defaultSchema, Schema.class))); } else if (database instanceof AbstractDb2Database) { sql.add(0, new UnparsedSql("SET CURRENT SCHEMA " + schemaName)); sql.add(new UnparsedSql("SET CURRENT SCHEMA " + defaultSchema)); } } }public static String getLocalHostName() throws UnknownHostException, SocketException { try { return getLocalHost().getHostName(); } catch (Exception e) { Scope.getCurrentScope().getLog(NetUtil.class).fine(LogType.LOG, "Error getting hostname", e); return "unknown"; } }public static String getLocalHostAddress() throws UnknownHostException, SocketException { try { return getLocalHost().getHostAddress(); } catch (Exception e) { Scope.getCurrentScope().getLog(NetUtil.class).fine(LogType.LOG, "Error getting hostname", e); return "unknown"; } }public SqlVisitor create(String tagName) { Class aClass = tagToClassMap.get(tagName); if (aClass == null) { return null; } try { return (SqlVisitor) aClass.getConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException(e); } }boolean isSybaseProductName(String dbProductName) { return PRODUCT_NAME.equals(dbProductName) || "Sybase SQL Server".equals(dbProductName) || "sql server".equals(dbProductName) || "ASE".equals(dbProductName); }public static void notNull(Object object, String failMessage) throws UnexpectedLiquibaseException { if (object == null) { fail(failMessage); } }public Element createNode(String nodeNamespace, String nodeName, String nodeContent) { Element element = currentChangeLogFileDOM.createElementNS(nodeNamespace, nodeName); element.setTextContent(nodeContent); return element; }protected String checkString(String text) throws UnexpectedLiquibaseException { if (null == text || text.isEmpty()) { return text; } final int len = text.length(); char current; int codePoint; for (int i = 0; i < len; i++) { current = text.charAt(i); if (Character.isHighSurrogate(current) && i + 1 < len && Character.isLowSurrogate(text.charAt(i + 1))) { codePoint = text.codePointAt(i++); } else { codePoint = current; } if ((codePoint == '\n') || (codePoint == '\r') || (codePoint == '\t') || (codePoint == 0xB) || (codePoint == 0xC) || ((codePoint >= 0x20) && (codePoint <= 0x7E)) || ((codePoint >= 0xA0) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)) ) { //ok } else { throw new UnexpectedLiquibaseException(INVALID_STRING_ENCODING_MESSAGE); } } return text; }@Override public int getMaxFractionalDigitsForTimestamp() { if (getConnection() == null) { // if no connection is there we cannot do anything... Scope.getCurrentScope().getLog(getClass()).warning( LogType.LOG, "No database connection available - specified" + " DATETIME/TIMESTAMP precision will be tried"); return DEFAULT_MAX_TIMESTAMP_FRACTIONAL_DIGITS; } return DEFAULT_MAX_TIMESTAMP_FRACTIONAL_DIGITS; }protected List filterRollbackVisitors(final List visitors) { final List rollbackVisitors = new ArrayList<>(); if (visitors != null) { for (SqlVisitor visitor : visitors) { if (visitor.isApplyToRollback()) { rollbackVisitors.add(visitor); } } } return rollbackVisitors; }@Override public boolean isSafeToRunUpdate() throws DatabaseException { DatabaseConnection connection = getConnection(); if (connection == null) { return true; } String url = connection.getURL(); if (url == null) { return false; } return (url.contains("localhost")) || (url.contains("127.0.0.1")); }protected String getConnectionSchemaName() { if (connection == null) { return null; } if (connection instanceof OfflineConnection) { return ((OfflineConnection) connection).getSchema(); } try { SqlStatement currentSchemaStatement = getConnectionSchemaNameCallStatement(); return ExecutorService.getInstance().getExecutor(this). queryForObject(currentSchemaStatement, String.class); } catch (Exception e) { Scope.getCurrentScope().getLog(getClass()).info(LogType.LOG, "Error getting default schema", e); } return null; }@Override public boolean promptForNonLocalDatabase(Database database) throws DatabaseException { return JOptionPane.showConfirmDialog(null, "You are running a database migration against a non-local database." + StreamUtil.getLineSeparator() + "Database URL is: " + database.getConnection().getURL() + StreamUtil.getLineSeparator() + "Username is: " + database.getConnection().getConnectionUserName() + StreamUtil.getLineSeparator() + StreamUtil.getLineSeparator() + "Are you sure you want to do this?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION; }public Change create(String name) { Change plugin = getPlugin(name); if (plugin == null) { return null; } try { return plugin.getClass().getConstructor().newInstance(); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } }public SortedSet getDefinedChanges() { SortedSet names = new TreeSet<>(); for (Change change : findAllInstances()) { names.add(getChangeMetaData(change).getName()); } return Collections.unmodifiableSortedSet(names); }public void unregister(String name) { for (Change change : new ArrayList<>(findAllInstances())) { if (getChangeMetaData(change).getName().equals(name)) { this.removeInstance(change); } } }public ColumnConfig setDefaultValueBoolean(String defaultValueBoolean) { defaultValueBoolean = StringUtil.trimToNull(defaultValueBoolean); if ((defaultValueBoolean == null) || "null".equalsIgnoreCase(defaultValueBoolean)) { this.defaultValueBoolean = null; } else { if ("true".equalsIgnoreCase(defaultValueBoolean) || "1".equals(defaultValueBoolean)) { this.defaultValueBoolean = true; } else if ("false".equalsIgnoreCase(defaultValueBoolean) || "0".equals(defaultValueBoolean)) { this.defaultValueBoolean = false; } else { this.defaultValueComputed = new DatabaseFunction(defaultValueBoolean); } } return this; }public ColumnConfig setValueBoolean(String valueBoolean) { valueBoolean = StringUtil.trimToNull(valueBoolean); if ((valueBoolean == null) || "null".equalsIgnoreCase(valueBoolean)) { this.valueBoolean = null; } else { if ("true".equalsIgnoreCase(valueBoolean) || "1".equals(valueBoolean)) { this.valueBoolean = true; } else if ("false".equalsIgnoreCase(valueBoolean) || "0".equals(valueBoolean)) { this.valueBoolean = false; } else { this.valueComputed = new DatabaseFunction(valueBoolean); } } return this; }public ColumnConfig setValueNumeric(String valueNumeric) { if ((valueNumeric == null) || "null".equalsIgnoreCase(valueNumeric)) { this.valueNumeric = null; } else { String saved = valueNumeric; if (valueNumeric.startsWith("(")) { valueNumeric = valueNumeric.replaceFirst("^\\(", ""); valueNumeric = valueNumeric.replaceFirst("\\)$", ""); } try { this.valueNumeric = ValueNumeric.of(Locale.US, valueNumeric); } catch (ParseException e) { this.valueComputed = new DatabaseFunction(saved); } } return this; }@Override public String escapeObjectName(String objectName, Class objectType) { if ((quotingStrategy == ObjectQuotingStrategy.LEGACY) && hasMixedCase(objectName)) { return "\"" + objectName + "\""; } else if (objectType != null && LiquibaseColumn.class.isAssignableFrom(objectType)) { return (objectName != null && !objectName.isEmpty()) ? objectName.trim() : objectName; } return super.escapeObjectName(objectName, objectType); }public List getChangeSetsToRun() { ArrayList returnList = new ArrayList<>(); for (ChangeSetStatus status : changeSetStatuses.values()) { if (status.getWillRun()) { returnList.add(status); } } return returnList; }public static boolean supportsDefaultValueComputed(String columnType, String defaultValue) { HashSet possibleComputedValues = SUPPORTED_DEFAULT_VALUE_COMPUTED_MAP.get(columnType); return (possibleComputedValues != null) && possibleComputedValues.contains(defaultValue.toLowerCase()); }protected int getSize() { if (getParameters().length == 0) { return -1; } if (getParameters()[0] instanceof String) { return Integer.parseInt((String) getParameters()[0]); } if (getParameters()[0] instanceof Number) { return ((Number) getParameters()[0]).intValue(); } return -1; }public void setColumnMapping(String... columnMapping) { this.columnMapping = (columnMapping != null) ? columnMapping.clone() : new String[]{}; resetIndexMap(); createIndexLookup(this.columnMapping); }@Override public String getColumnName(int col) { return (col < columnMapping.length) ? columnMapping[col] : null; }protected Map loadDescriptorMap() throws IntrospectionException { Map map = new HashMap<>(); PropertyDescriptor[] descriptors; descriptors = loadDescriptors(getType()); for (PropertyDescriptor descriptor : descriptors) { map.put(descriptor.getName().toUpperCase().trim(), descriptor); } return map; }protected boolean matches(String name, PropertyDescriptor desc) { return desc.getName().equals(name.trim()); }protected BeanField findField(String name) { if (null == fieldMap) { fieldMap = loadFieldMap(); //lazy load fields } return fieldMap.get(name.toUpperCase().trim()); }protected PropertyDescriptor findDescriptor(String name) throws IntrospectionException { if (null == descriptorMap) { descriptorMap = loadDescriptorMap(); //lazy load descriptors } return descriptorMap.get(name.toUpperCase().trim()); }public String getColumnName(int col) { return ((null != header) && (col < header.length)) ? header[col] : null; }@Override public BeanField findField(int col) { String columnName = getColumnName(col); return (StringUtil.trimToNull(columnName) != null) ? findField(columnName) : null; }@Override public PropertyDescriptor findDescriptor(int col) throws IntrospectionException { String columnName = getColumnName(col); return (StringUtil.trimToNull(columnName) != null) ? findDescriptor(columnName) : null; }@Override public Integer getColumnIndex(String name) { if (null == header) { throw new IllegalStateException("The header row hasn't been read yet."); } createIndexLookup(header); return indexLookup.get(name); }protected void createIndexLookup(String[] values) { if (indexLookup.isEmpty()) { for (int i = 0; i < values.length; i++) { indexLookup.put(values[i], i); } } }private static String doGetFullPath(String filename, boolean includeSeparator) { if (filename == null) { return null; } int prefix = getPrefixLength(filename); if (prefix < 0) { return null; } if (prefix >= filename.length()) { if (includeSeparator) { return getPrefix(filename); // add end slash if necessary } else { return filename; } } int index = indexOfLastSeparator(filename); if (index < 0) { return filename.substring(0, prefix); } int end = index + (includeSeparator ? 1 : 0); return filename.substring(0, end); }@Override public Set getSerializableFields() { return Scope.getCurrentScope().getSingleton(ChangeFactory.class).getChangeMetaData(this).getParameters().keySet(); }private String convertToString(Object newValue, Database database) { String sqlString; if (newValue == null || newValue.toString().equals("") || newValue.toString().equalsIgnoreCase("NULL")) { sqlString = "NULL::INTEGER"; } else if (newValue instanceof String && !looksLikeFunctionCall(((String) newValue), database)) { sqlString = "'" + database.escapeStringForDatabase(newValue.toString()) + "'"; } else if (newValue instanceof Date) { sqlString = database.getDateLiteral(((Date) newValue)); } else if (newValue instanceof Boolean) { if (((Boolean) newValue)) { sqlString = DataTypeFactory.getInstance().getTrueBooleanValue(database); } else { sqlString = DataTypeFactory.getInstance().getFalseBooleanValue(database); } } else { sqlString = newValue.toString(); } return sqlString; }public Map getRequiredParameters(Database database) { Map returnMap = new HashMap<>(); for (ChangeParameterMetaData metaData : parameters.values()) { if (metaData.isRequiredFor(database)) { returnMap.put(metaData.getParameterName(), metaData); } } return returnMap; }public Map getSetParameters(Change change) { Map returnMap = new HashMap<>(); for (Map.Entry entry : getParameters().entrySet()) { if (entry.getValue().getCurrentValue(change) != null) { returnMap.put(entry.getKey(), entry.getValue()); } } return Collections.unmodifiableMap(returnMap); }private String getUniqueConstraintsSqlInformix(InformixDatabase database, Schema schema, String name) { StringBuffer sqlBuf = new StringBuffer(); sqlBuf.append("SELECT * FROM (\n"); // Yes, I am serious about this. It appears there are neither CTE/WITH clauses nor PIVOT/UNPIVOT operators // in Informix SQL. for (int i=1; i<=16; i++) { if (i>1) sqlBuf.append("UNION ALL\n"); sqlBuf.append( String.format(" SELECT\n" + " CONS.owner,\n" + " CONS.constrname AS constraint_name,\n" + " COL.colname AS column_name,\n" + " CONS.constrtype,\n" + " %d AS column_index\n" + " FROM informix.sysconstraints CONS\n" + " JOIN informix.sysindexes IDX ON CONS.idxname = IDX.idxname\n" + " JOIN informix.syscolumns COL ON COL.tabid = CONS.tabid AND COL.colno = IDX.part%d\n", i, i ) ); } // Finish the subquery and filter on the U(NIQUE) constraint type sqlBuf.append( " ) SUBQ\n" + "WHERE constrtype='U' \n"); String catalogName = database.correctObjectName(schema.getCatalogName(), Catalog.class); String constraintName = database.correctObjectName(name, UniqueConstraint.class); // If possible, filter for catalog name and/or constraint name if (catalogName != null) { sqlBuf.append("AND owner='" + catalogName + "'\n"); } if (constraintName != null) { sqlBuf.append("AND constraint_name='" + constraintName + "'"); } // For correct processing, it is important that we get all columns in order. sqlBuf.append("ORDER BY owner, constraint_name, column_index"); // Return the query return sqlBuf.toString(); }private void setValidateOptionIfAvailable(Database database, UniqueConstraint uniqueConstraint, Map columnsMetadata) { if (!(database instanceof OracleDatabase)) { return; } final Object constraintValidate = columnsMetadata.get("CONSTRAINT_VALIDATE"); final String VALIDATE = "VALIDATED"; if (constraintValidate!=null && !constraintValidate.toString().trim().isEmpty()) { uniqueConstraint.setShouldValidate(VALIDATE.equals(cleanNameFromDatabase(constraintValidate.toString().trim(), database))); } }public Object getValue(String key, DatabaseChangeLog changeLog) { ChangeLogParameter parameter = findParameter(key, changeLog); return (parameter != null) ? parameter.getValue() : null; }public static boolean isNowOrTodayFormat(String value) { boolean ret = false; if (value != null) { String lowerValue = value.toLowerCase(); if (lowerValue.length() >= NOW_LENGTH && lowerValue.startsWith(NOW)) { ret = true; } else if (lowerValue.length() >= TODAY_LENGTH && lowerValue.startsWith(TODAY)) { ret = true; } } return ret; }public Precondition create(String tagName) { Class aClass = preconditions.get(tagName); if (aClass == null) { return null; } try { return (Precondition) aClass.getConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException(e); } }@Override public void tag(final String tagString) throws DatabaseException { Database database = getDatabase(); Executor executor = ExecutorService.getInstance().getExecutor(database); int totalRows = ExecutorService.getInstance().getExecutor(database).queryForInt(new SelectFromDatabaseChangeLogStatement(new ColumnConfig().setName("COUNT(*)", true))); if (totalRows == 0) { ChangeSet emptyChangeSet = new ChangeSet(String.valueOf(new Date().getTime()), "liquibase", false,false, "liquibase-internal", null, null, getDatabase().getObjectQuotingStrategy(), null); this.setExecType(emptyChangeSet, ChangeSet.ExecType.EXECUTED); } executor.execute(new TagDatabaseStatement(tagString)); getDatabase().commit(); if (this.ranChangeSetList != null) { ranChangeSetList.get(ranChangeSetList.size() - 1).setTag(tagString); } }public T getSingleton(Class type) { if (getParent() != null) { return getParent().getSingleton(type); } String key = type.getName(); T singleton = get(key, type); if (singleton == null) { try { try { Constructor constructor = type.getDeclaredConstructor(Scope.class); constructor.setAccessible(true); singleton = constructor.newInstance(this); } catch (NoSuchMethodException e) { //try without scope Constructor constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); singleton = constructor.newInstance(); } } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } values.put(key, singleton); } return singleton; }public Column getColumn(String columnName) { for (Column column : getColumns()) { if (column.getName().equalsIgnoreCase(columnName)) { return column; } } return null; }protected boolean isCompressedFile(Path path) { return path != null && (path.toString().startsWith("jar:") || path.toString().toLowerCase().endsWith(".jar") || path.toString().toLowerCase().endsWith(".zip")); }public boolean isAutoIncrement() { return "serial".equals(type.toLowerCase(Locale.US)) || "bigserial".equals(type.toLowerCase(Locale.US)) || "smallserial" .equals(type.toLowerCase(Locale.US)); }@Override public void close() throws IOException { for (InputStream stream : this) { try { stream.close(); } catch (IOException e) { Scope.getCurrentScope().getLog(getClass()).severe("Error closing stream. Logging error and continuing", e); } } }public Object getChildValue(String namespace, String nodename) throws ParsedNodeException { ParsedNode child = getChild(namespace, nodename); if (child == null) { return null; } return child.getValue(); }public T getChildValue(String namespace, String nodename, Class type) throws ParsedNodeException { Object rawValue = getChildValue(namespace, nodename); if (rawValue == null) { return null; } return convertObject(rawValue, type); }public ParsedNode getChild(String namespace, String name) throws ParsedNodeException { ParsedNode returnNode = null; for (ParsedNode node : children) { if (nodeMatches(node, namespace, name)) { if (returnNode != null) { throw new ParsedNodeException("Multiple nodes match "+namespace+"/"+name); } returnNode = node; } } return returnNode; }public T getValue(Class type) throws ParsedNodeException { return convertObject(value, type); }public ParsedNode setValue(Object value) throws ParsedNodeException { if (value instanceof ParsedNode) { this.addChild((ParsedNode) value); } else if (value instanceof Collection) { List newValue = new ArrayList(); for (Object obj : ((Collection) value)) { if (obj instanceof Map) { addChildren((Map) obj); } else if (obj instanceof ParsedNode) { addChild(((ParsedNode) obj)); } else { newValue.add(obj); } } if (newValue.isEmpty()) { //do nothing } else if (newValue.size() == 1) { this.value = newValue.get(0); } else { this.value = newValue; } } else if (value instanceof Map) { addChildren(((Map) value)); } else { this.value = value; } return this; }public List getChildren(String namespace, String nodename) { List returnList = new ArrayList<>(); for (ParsedNode node : children) { if (nodeMatches(node, namespace, nodename)) { returnList.add(node); } } return Collections.unmodifiableList(returnList); }protected boolean isNextCharacterEscapable(String nextLine, boolean inQuotes, int i) { return inQuotes // we are in quotes, therefore there can be escaped quotes in here. && (nextLine.length() > (i + 1)) // there is indeed another character to check. && isCharacterEscapable(nextLine.charAt(i + 1)); }private boolean isNextCharacterEscapedQuote(String nextLine, boolean inQuotes, int i) { return inQuotes // we are in quotes, therefore there can be escaped quotes in here. && (nextLine.length() > (i + 1)) // there is indeed another character to check. && isCharacterQuoteCharacter(nextLine.charAt(i + 1)); }private int appendNextCharacterAndAdvanceLoop(String line, StringBuilder sb, int i) { sb.append(line.charAt(i + 1)); i++; return i; }protected void closeDatabase(Database database) { try { if(database != null) { database.close(); } } catch (DatabaseException e) { log("Error closing the database connection.", e, Project.MSG_WARN); } }private ResourceAccessor createResourceAccessor(ClassLoader classLoader) { List resourceAccessors = new ArrayList(); resourceAccessors.add(new FileSystemResourceAccessor(Paths.get(".").toAbsolutePath().getRoot().toFile())); resourceAccessors.add(new ClassLoaderResourceAccessor(classLoader)); String changeLogDirectory = getChangeLogDirectory(); if (changeLogDirectory != null) { changeLogDirectory = changeLogDirectory.trim().replace('\\', '/'); //convert to standard / if using absolute path on windows resourceAccessors.add(new FileSystemResourceAccessor(new File(changeLogDirectory))); } return new CompositeResourceAccessor(resourceAccessors.toArray(new ResourceAccessor[0])); }public boolean matches(Contexts runtimeContexts) { if ((runtimeContexts == null) || runtimeContexts.isEmpty()) { return true; } if (this.contexts.isEmpty()) { return true; } for (String expression : this.contexts) { if (matches(expression, runtimeContexts)) { return true; } } return false; }protected List getAlternatePaths(String path) { List alternatePaths = new ArrayList<>(); if (path.startsWith("/")) { //People are often confused about leading slashes in resource paths... alternatePaths.add(path.substring(1)); } return alternatePaths; }public static Field getDeclaredField(Class clazz, String fieldName) throws NoSuchFieldException { Field f = getField(clazz, fieldName); if (f == null) { // Try the parent class Class parent = clazz.getSuperclass(); if (parent != null) { return getDeclaredField(parent, fieldName); } else { throw new NoSuchFieldException("The field '" + fieldName + "' could not be " + "found in the class of any of its parent " + "classes."); } } else { return f; } }private static void addArtifact(Set urls, Artifact artifact, Log log, boolean verbose) throws MalformedURLException { File f = artifact.getFile(); if (f == null) { log.warn("Artifact with no actual file, '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + "'"); } else { addFile(urls, f, log, verbose); } // if (f != null) { // URL fileURL = f.toURI().toURL(); // if (verbose) { // log.info(" artifact: " + fileURL); // } // urls.add(fileURL); // } else { // log.warning("Artifact with no actual file, '" + artifact.getGroupId() // + ":" + artifact.getArtifactId() + "'"); // } }public boolean generateStatementsVolatile(SqlStatement statement, Database database) { for (SqlGenerator generator : getGenerators(statement, database)) { if (generator.generateStatementsIsVolatile(database)) { return true; } } return false; }private String getConcatSql(List values) { if (values.size() == 1) { return values.get(0); } else { return START_CONCAT + values.get(0) + SEP_CONCAT + getConcatSql(values.subList(1, values.size())) + END_CONCAT; } }public boolean supportsBooleanDataType() { if (getConnection() == null) return false; /// assume not; try { final Integer fixPack = getDb2FixPack(); if (fixPack == null) throw new DatabaseException("Error getting fix pack number"); return getDatabaseMajorVersion() > 11 || getDatabaseMajorVersion() == 11 && getDatabaseMinorVersion() >= 1 && fixPack.intValue() >= 1; } catch (final DatabaseException e) { return false; // assume not } }protected boolean isCurrentDateTimeFunction(String string, Database database) { return string.toLowerCase(Locale.US).startsWith("current_timestamp") || string.toLowerCase(Locale.US).startsWith(DatabaseFunction.CURRENT_DATE_TIME_PLACE_HOLDER) || database.getCurrentDateTimeFunction().toLowerCase(Locale.US).equals(string.toLowerCase(Locale.US)); }public String objectToSql(Object value, Database database) { if ((value == null) || "null".equals(value.toString().toLowerCase(Locale.US))) { return null; } else if (value instanceof DatabaseFunction) { return functionToSql((DatabaseFunction) value, database); } else if (value instanceof Number) { return numberToSql((Number) value, database); } return otherToSql(value, database); }public DatabaseDataType toDatabaseDataType(Database database) { if (database instanceof MSSQLDatabase) { String name = database.escapeDataTypeName(getName()); int dataTypeMaxParameters = database.getDataTypeMaxParameters(getName()); Object[] parameters = getParameters(); if (dataTypeMaxParameters < parameters.length) { parameters = Arrays.copyOfRange(parameters, 0, dataTypeMaxParameters); } return new DatabaseDataType(name, parameters); } DatabaseDataType type = new DatabaseDataType(name.toUpperCase(Locale.US), getParameters()); type.addAdditionalInformation(additionalInformation); return type; }public boolean validate(Database database) { int maxParameters = this.getMaxParameters(database); int minParameters = this.getMinParameters(database); if (parameters.size() > maxParameters) { throw new UnexpectedLiquibaseException("Type "+getClass()+" doesn't support "+ maxParameters+" parameters"); } if (parameters.size() < minParameters) { throw new UnexpectedLiquibaseException("Type "+getClass()+" requires "+ minParameters+" parameters"); } return true; }public List getInternalDatabases() { List returnList = new ArrayList<>(); for (SortedSet set : internalDatabases.values()) { returnList.add(set.iterator().next()); } return returnList; }public List getImplementedDatabases() { List returnList = new ArrayList<>(); for (SortedSet set : implementedDatabases.values()) { returnList.add(set.iterator().next()); } return returnList; }public void print(PrintStream out, ChangeLogSerializer changeLogSerializer) throws ParserConfigurationException, IOException, DatabaseException { List changeSets = generateChangeSets(); changeLogSerializer.write(changeSets, out); out.flush(); }public StringClauses getSubclause(String exitingKey) { exitingKey = StringUtil.trimToEmpty(exitingKey).toLowerCase(); Object clauses = getImpl(exitingKey); if (clauses == null) { return null; } if (clauses instanceof String) { return new StringClauses().append((String) clauses); } return (StringClauses) clauses; }public String get(String exitingKey) { exitingKey = StringUtil.trimToEmpty(exitingKey).toLowerCase(); Object clauses = getImpl(exitingKey); if (clauses == null) { return null; } return clauses.toString(); }public StringClauses insertAfter(String existingKey, String newKey, String newValue) { return insertAfterImpl(existingKey, newKey, newValue); }public StringClauses insertBefore(String existingKey, String newKey, String newValue) throws IllegalArgumentException { return insertBeforeImpl(existingKey, newKey, newValue); }public StringClauses prepend(String key, String clause) { return prependImpl(key, StringUtil.trimToEmpty(clause)); }public StringClauses append(String key, StringClauses subclauses) { Validate.notNull(StringUtil.trimToNull(key), "key must be a non-null, non-empty value"); key = StringUtil.trimToEmpty(key).toLowerCase(); if (clauses.containsKey(key)) { throw new IllegalArgumentException("Cannot add clause with key '" + key + "' because it is already defined"); } clauses.put(key, subclauses); return this; }public StringClauses append(String key, String clause) { Validate.notNull(StringUtil.trimToNull(key), "key must be a non-null, non-empty value"); key = StringUtil.trimToEmpty(key).toLowerCase(); clause = StringUtil.trimToEmpty(clause); if (clauses.containsKey(key)) { throw new IllegalArgumentException("Cannot add clause with key '" + key + "' because it is already defined"); } clauses.put(key, clause.trim()); return this; }protected String[] getDatabaseCatalogNames(Database database) throws SQLException, DatabaseException { List returnList = new ArrayList<>(); ResultSet catalogs = null; try { if (((AbstractJdbcDatabase) database).jdbcCallsCatalogsSchemas()) { catalogs = ((JdbcConnection) database.getConnection()).getMetaData().getSchemas(); } else { catalogs = ((JdbcConnection) database.getConnection()).getMetaData().getCatalogs(); } while (catalogs.next()) { if (((AbstractJdbcDatabase) database).jdbcCallsCatalogsSchemas()) { returnList.add(catalogs.getString("TABLE_SCHEM")); } else { returnList.add(catalogs.getString("TABLE_CAT")); } } } finally { if (catalogs != null) { try { catalogs.close(); } catch (SQLException ignore) { } } } return returnList.toArray(new String[returnList.size()]); }public static String concatConsistentCase(String baseString, String addition) { boolean hasLowerCase = hasLowerCase(baseString); boolean hasUpperCase = hasUpperCase(baseString); if ((hasLowerCase && hasUpperCase) || (!hasLowerCase && !hasUpperCase)) { //mixed case || no letters return baseString + addition; } else if (hasLowerCase) { return baseString + addition.toLowerCase(); } else { return baseString + addition.toUpperCase(); } }public static String stripSqlCommentsAndWhitespacesFromTheEnd(String sqlString) { if (isEmpty(sqlString)) { return sqlString; } StringBuilder str = new StringBuilder(sqlString); boolean strModified = true; while (strModified) { strModified = false; // first check for last block comment // since line comments could be inside block comments, we want to // remove them first. String lastBlockComment = getLastBlockComment(str.toString()); if (isNotEmpty(lastBlockComment)) { str.setLength(str.length() - lastBlockComment.length()); // we just modified the end of the string, // do another loop to check for next block or line comments strModified = true; } // now check for the line comments String lastLineComment = getLastLineComment(str.toString()); if (isNotEmpty(lastLineComment)) { str.setLength(str.length() - lastLineComment.length()); // we just modified the end of the string, // do another loop to check for next block or line comments strModified = true; } } return trimRight(str.toString()); }public static String randomIdentifer(int len) { final String AB = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; StringBuilder sb = new StringBuilder( len ); for (int i = 0; i < len; i++) sb.append( AB.charAt( rnd.nextInt(AB.length()) ) ); return sb.toString(); }public static String leftPad(String value, int length) { value = StringUtil.trimToEmpty(value); if (value.length() >= length) { return value; } return StringUtil.repeat(" ", length - value.length()) + value; }public static String pad(String value, int length) { value = StringUtil.trimToEmpty(value); if (value.length() >= length) { return value; } return value + StringUtil.repeat(" ", length - value.length()); }public static String[] splitSQL(String multiLineSQL, String endDelimiter) { return processMutliLineSQL(multiLineSQL, false, true, endDelimiter); }private static void cleanDirectory(final File directory) throws IOException { if ( !directory.exists() ) { return; } if ( !directory.isDirectory() ) { return; } IOException exception = null; final File[] files = directory.listFiles(); if (files != null) { for (final File file : files) { try { cleanDirectory(file); if (!file.delete()) { throw new IOException("Cannot delete "+file.getAbsolutePath()); } } catch (final IOException ioe) { exception = ioe; } } } if ( null != exception ) { throw exception; } }private List generateChildren(Database database) { // Make a new list List childDropChanges = new ArrayList<>(); try { SnapshotControl control = new SnapshotControl(database); control.getTypesToInclude().add(ForeignKey.class); CatalogAndSchema catalogAndSchema = new CatalogAndSchema(getBaseTableCatalogName(), getBaseTableSchemaName()); catalogAndSchema = catalogAndSchema.standardize(database); Table target = SnapshotGeneratorFactory.getInstance().createSnapshot( new Table(catalogAndSchema.getCatalogName(), catalogAndSchema.getSchemaName(), database.correctObjectName(getBaseTableName(), Table.class)) , database); List results = ((target == null) ? null : target.getOutgoingForeignKeys()); Set handledConstraints = new HashSet<>(); if ((results != null) && (!results.isEmpty())) { for (ForeignKey fk : results) { Table baseTable = fk.getForeignKeyTable(); String constraintName = fk.getName(); if (DatabaseObjectComparatorFactory.getInstance().isSameObject( baseTable, target, null, database )) { if( !handledConstraints.contains(constraintName)) { DropForeignKeyConstraintChange dropForeignKeyConstraintChange = new DropForeignKeyConstraintChange(); dropForeignKeyConstraintChange.setBaseTableSchemaName(getBaseTableSchemaName()); dropForeignKeyConstraintChange.setBaseTableName(baseTableName); dropForeignKeyConstraintChange.setConstraintName(constraintName); childDropChanges.add(dropForeignKeyConstraintChange); handledConstraints.add(constraintName); } } else { throw new UnexpectedLiquibaseException( "Expected to return only foreign keys for base table name: " + getBaseTableName() + " and got results for table: " + baseTableName); } } } return childDropChanges; } catch (DatabaseException | InvalidExampleException e) { throw new UnexpectedLiquibaseException("Failed to find foreign keys for table: " + getBaseTableName(), e); } }public T createSnapshot(T example, Database database) throws DatabaseException, InvalidExampleException { return createSnapshot(example, database, new SnapshotControl(database)); }public DatabaseSnapshot createSnapshot(DatabaseObject[] examples, Database database, SnapshotControl snapshotControl) throws DatabaseException, InvalidExampleException { DatabaseConnection conn = database.getConnection(); if (conn == null) { return new EmptyDatabaseSnapshot(database, snapshotControl); } if (conn instanceof OfflineConnection) { DatabaseSnapshot snapshot = ((OfflineConnection) conn).getSnapshot(examples); if (snapshot == null) { throw new DatabaseException("No snapshotFile parameter specified for offline database"); } return snapshot; } return new JdbcDatabaseSnapshot(examples, database, snapshotControl); }public boolean has(DatabaseObject example, Database database) throws DatabaseException, InvalidExampleException { // @todo I have seen duplicates in types - maybe convert the List into a Set? Need to understand it more thoroughly. List> types = new ArrayList<>(getContainerTypes(example.getClass(), database)); types.add(example.getClass()); /* * Does the query concern the DATABASECHANGELOG / DATABASECHANGELOGLOCK table? If so, we do a quick & dirty * SELECT COUNT(*) on that table. If that works, we count that as confirmation of existence. */ // @todo Actually, there may be extreme cases (distorted table statistics etc.) where a COUNT(*) might not be so cheap. Maybe SELECT a dummy constant is the better way? if ((example instanceof Table) && (example.getName().equals(database.getDatabaseChangeLogTableName()) || example.getName().equals(database.getDatabaseChangeLogLockTableName()))) { try { ExecutorService.getInstance().getExecutor(database).queryForInt( new RawSqlStatement("SELECT COUNT(*) FROM " + database.escapeObjectName(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), example.getName(), Table.class))); return true; } catch (DatabaseException e) { if (database instanceof PostgresDatabase) { // throws "current transaction is aborted" unless we roll back the connection database.rollback(); } return false; } } /* * If the query is about another object, try to create a snapshot of the of the object (or used the cached * snapshot. If that works, we count that as confirmation of existence. */ SnapshotControl snapshotControl = (new SnapshotControl(database, false, types.toArray(new Class[types.size()]))); snapshotControl.setWarnIfObjectNotFound(false); if (createSnapshot(example, database,snapshotControl) != null) { return true; } CatalogAndSchema catalogAndSchema; if (example.getSchema() == null) { catalogAndSchema = database.getDefaultSchema(); } else { catalogAndSchema = example.getSchema().toCatalogAndSchema(); } DatabaseSnapshot snapshot = createSnapshot(catalogAndSchema, database, new SnapshotControl(database, false, example.getClass()).setWarnIfObjectNotFound(false) ); for (DatabaseObject obj : snapshot.get(example.getClass())) { if (DatabaseObjectComparatorFactory.getInstance().isSameObject(example, obj, null, database)) { return true; } } return false; }public boolean matches(Labels runtimeLabels) { if ((runtimeLabels == null) || runtimeLabels.isEmpty()) { return true; } if (this.labels.isEmpty()) { return true; } for (String expression : this.labels) { if (matches(expression, runtimeLabels)) { return true; } } return false; }public static Integer readInteger(String value) { if (value == null) { return null; } return Integer.valueOf(value); }private String getCommandParam(String paramName, String defaultValue) throws CommandLineParsingException { for (String param : commandParams) { if (!param.contains("=")) { continue; } String[] splitArg = splitArg(param); String attributeName = splitArg[0]; String value = splitArg[1]; if (attributeName.equalsIgnoreCase(paramName)) { return value; } } return defaultValue; }protected void parseOptions(String[] paramArgs) throws CommandLineParsingException { String[] args = fixupArgs(paramArgs); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase(COMMANDS.MIGRATE)) { this.command = COMMANDS.UPDATE; } else if (this.command.equalsIgnoreCase(COMMANDS.MIGRATE_SQL)) { this.command = COMMANDS.UPDATE_SQL; } seenCommand = true; } else if (seenCommand) { // ChangeLog parameter: if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); if (arg.startsWith("--")) { parseOptionArgument(arg); } } } else if (arg.startsWith("--")) { parseOptionArgument(arg); } else { throw new CommandLineParsingException( String.format(coreBundle.getString("unexpected.value"), arg)); } } // Now apply default values from the default property files. We waited with this until this point // since command line parameters might have changed the location where we will look for them. parseDefaultPropertyFiles(); }protected void printHelp(PrintStream stream) { String helpText = commandLineHelpBundle.getString("commandline-helptext"); stream.println(helpText); }protected void printHelp(List errorMessages, PrintStream stream) { stream.println(coreBundle.getString("errors")); for (String message : errorMessages) { stream.println(" " + message); } stream.println(); }protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); if (props.containsKey("strict")) { strict = Boolean.valueOf(props.getProperty("strict")); } for (Map.Entry entry : props.entrySet()) { try { if ("promptOnNonLocalDatabase".equals(entry.getKey())) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue ()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (NoSuchFieldException ignored) { if (strict) { throw new CommandLineParsingException( String.format(coreBundle.getString("parameter.unknown"), entry.getKey()) ); } else { Scope.getCurrentScope().getLog(getClass()).warning( LogType.LOG, String.format(coreBundle.getString("parameter.ignored"), entry.getKey()) ); } } catch (IllegalAccessException e) { throw new UnexpectedLiquibaseException( String.format(coreBundle.getString("parameter.unknown"), entry.getKey()) ); } } }private void checkForMalformedCommandParameters(final List messages) { if (commandParams.isEmpty()) { return; } final int CHANGESET_MINIMUM_IDENTIFIER_PARTS = 3; if (COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(command)) { for (final String param : commandParams) { if ((param != null) && !param.startsWith("-")) { final String[] parts = param.split("::"); if (parts.length < CHANGESET_MINIMUM_IDENTIFIER_PARTS) { messages.add(coreBundle.getString("changeset.identifier.must.have.form.filepath.id.author")); break; } } } } else if (COMMANDS.DIFF_CHANGELOG.equalsIgnoreCase(command) && (diffTypes != null) && diffTypes.toLowerCase ().contains("data")) { messages.add(String.format(coreBundle.getString("including.data.diffchangelog.has.no.effect"), OPTIONS.DIFF_TYPES, COMMANDS.GENERATE_CHANGELOG )); } }private void checkForMissingCommandParameters(final List messages) { if ((commandParams.isEmpty() || commandParams.iterator().next().startsWith("-")) && (COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(command))) { messages.add(coreBundle.getString("changeset.identifier.missing")); } }protected List checkSetup() { List messages = new ArrayList<>(); if (command == null) { messages.add(coreBundle.getString("command.not.passed")); } else if (!isCommand(command)) { messages.add(String.format(coreBundle.getString("command.unknown"), command)); } else { if (StringUtil.trimToNull(url) == null) { messages.add(String.format(coreBundle.getString("option.required"), "--" + OPTIONS.URL)); } if (isChangeLogRequired(command) && (StringUtil.trimToNull(changeLogFile) == null)) { messages.add(String.format(coreBundle.getString("option.required"), "--" + OPTIONS.CHANGELOG_FILE)); } if (isNoArgCommand(command) && !commandParams.isEmpty()) { messages.add(coreBundle.getString(ERRORMSG_UNEXPECTED_PARAMETERS) + commandParams); } else { validateCommandParameters(messages); } } return messages; }protected String[] fixupArgs(String[] args) { List fixedArgs = new ArrayList<>(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) { String nextArg = null; if ((i + 1) < args.length) { nextArg = args[i + 1]; } if ((nextArg != null) && !nextArg.startsWith("--") && !isCommand(nextArg)) { arg = arg + "=" + nextArg; i++; } } // Sometimes, commas are still escaped as \, at this point, fix it: arg = arg.replace("\\,", ","); fixedArgs.add(arg); } return fixedArgs.toArray(new String[fixedArgs.size()]); }private void parseDefaultPropertyFileFromResource(File potentialPropertyFile) throws IOException, CommandLineParsingException { try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream (potentialPropertyFile.getAbsolutePath())) { if (resourceAsStream != null) { parsePropertiesFile(resourceAsStream); } } }private static File extract(JarFile jar, JarEntry entry) throws IOException { // expand to temp dir and add to list File tempFile = File.createTempFile("liquibase.tmp", null); // read from jar and write to the tempJar file try ( BufferedInputStream inStream = new BufferedInputStream(jar.getInputStream(entry)); BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(tempFile)) ) { int status; while ((status = inStream.read()) != -1) { outStream.write(status); } } return tempFile; }private static boolean isNoArgCommand(String arg) { return COMMANDS.MIGRATE.equals(arg) || COMMANDS.MIGRATE_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE.equalsIgnoreCase(arg) || COMMANDS.UPDATE_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TESTING_ROLLBACK.equalsIgnoreCase(arg) || COMMANDS.LIST_LOCKS.equalsIgnoreCase(arg) || COMMANDS.DROP_ALL.equalsIgnoreCase(arg) || COMMANDS.RELEASE_LOCKS.equalsIgnoreCase(arg) || COMMANDS.VALIDATE.equalsIgnoreCase(arg) || COMMANDS.HELP.equalsIgnoreCase(arg) || COMMANDS.CLEAR_CHECKSUMS.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC_SQL.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN_SQL.equalsIgnoreCase(arg); }private static boolean isCommand(String arg) { return COMMANDS.MIGRATE.equals(arg) || COMMANDS.MIGRATE_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE.equalsIgnoreCase(arg) || COMMANDS.UPDATE_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_COUNT.equalsIgnoreCase(arg) || COMMANDS.UPDATE_COUNT_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TO_TAG.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TO_TAG_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_TO_DATE.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_COUNT.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_TO_DATE_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_COUNT_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_COUNT_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_TO_TAG_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TESTING_ROLLBACK.equalsIgnoreCase(arg) || COMMANDS.TAG.equalsIgnoreCase(arg) || COMMANDS.TAG_EXISTS.equalsIgnoreCase(arg) || COMMANDS.LIST_LOCKS.equalsIgnoreCase(arg) || COMMANDS.DROP_ALL.equalsIgnoreCase(arg) || COMMANDS.RELEASE_LOCKS.equalsIgnoreCase(arg) || COMMANDS.STATUS.equalsIgnoreCase(arg) || COMMANDS.UNEXPECTED_CHANGESETS.equalsIgnoreCase(arg) || COMMANDS.VALIDATE.equalsIgnoreCase(arg) || COMMANDS.HELP.equalsIgnoreCase(arg) || COMMANDS.DIFF.equalsIgnoreCase(arg) || COMMANDS.DIFF_CHANGELOG.equalsIgnoreCase(arg) || COMMANDS.GENERATE_CHANGELOG.equalsIgnoreCase(arg) || COMMANDS.SNAPSHOT.equalsIgnoreCase(arg) || COMMANDS.SNAPSHOT_REFERENCE.equalsIgnoreCase(arg) || COMMANDS.EXECUTE_SQL.equalsIgnoreCase(arg) || COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(arg) || COMMANDS.CLEAR_CHECKSUMS.equalsIgnoreCase(arg) || COMMANDS.DB_DOC.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC_SQL.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN_SQL.equalsIgnoreCase(arg); }@SuppressWarnings("squid:S109") private static String[] splitArg(String arg) throws CommandLineParsingException { String[] splitArg = arg.split("=", 2); if (splitArg.length < 2) { throw new CommandLineParsingException( String.format(coreBundle.getString("could.not.parse.expression"), arg) ); } splitArg[0] = splitArg[0].replaceFirst("--", ""); return splitArg; }public static void main(String[] args) { int errorLevel = 0; try { errorLevel = run(args); } catch (Throwable e) { System.exit(-1); } System.exit(errorLevel); }protected Object convertValue(String value, PropertyDescriptor prop) throws ReflectiveOperationException { PropertyEditor editor = getPropertyEditor(prop); Object obj = value; if (null != editor) { editor.setAsText(value); obj = editor.getValue(); } return obj; }protected String checkForTrim(String s, PropertyDescriptor prop) { return trimmableProperty(prop) ? s.trim() : s; }@Override public void afterPropertiesSet() throws LiquibaseException { ConfigurationProperty shouldRunProperty = LiquibaseConfiguration.getInstance() .getProperty(GlobalConfiguration.class, GlobalConfiguration.SHOULD_RUN); if (!shouldRunProperty.getValue(Boolean.class)) { Scope.getCurrentScope().getLog(getClass()).info(LogType.LOG, "Liquibase did not run because " + LiquibaseConfiguration .getInstance().describeValueLookupLogic(shouldRunProperty) + " was set to false"); return; } if (!shouldRun) { Scope.getCurrentScope().getLog(getClass()).info(LogType.LOG, "Liquibase did not run because 'shouldRun' " + "property was set " + "to false on " + getBeanName() + " Liquibase Spring bean."); return; } Connection c = null; Liquibase liquibase = null; try { c = getDataSource().getConnection(); liquibase = createLiquibase(c); generateRollbackFile(liquibase); performUpdate(liquibase); } catch (SQLException e) { throw new DatabaseException(e); } finally { Database database = null; if (liquibase != null) { database = liquibase.getDatabase(); } if (database != null) { database.close(); } } }public boolean addType(Class type, Database database) { boolean added = this.types.add(type); if (added) { for (Class container : SnapshotGeneratorFactory.getInstance().getContainerTypes(type, database)) { addType(container, database); } } return added; }private void setValidateOptionIfAvailable(Database database, ForeignKey foreignKey, CachedRow cachedRow) { if (!(database instanceof OracleDatabase)) { return; } final String constraintValidate = cachedRow.getString("FK_VALIDATE"); final String VALIDATE = "VALIDATED"; if (constraintValidate!=null && !constraintValidate.isEmpty()) { foreignKey.setShouldValidate(VALIDATE.equals(cleanNameFromDatabase(constraintValidate.trim(), database))); } }public static boolean nameMatches(DatabaseObject databaseObject1, DatabaseObject databaseObject2, Database accordingTo) { String object1Name = accordingTo.correctObjectName(databaseObject1.getName(), databaseObject1.getClass()); String object2Name = accordingTo.correctObjectName(databaseObject2.getName(), databaseObject2.getClass()); if ((object1Name == null) && (object2Name == null)) { return true; } if ((object1Name == null) || (object2Name == null)) { return false; } if (accordingTo.isCaseSensitive()) { return object1Name.equals(object2Name); } else { return object1Name.equalsIgnoreCase(object2Name); } }public static void initializeDatabase(String username, String defaultCatalogName, String defaultSchemaName, Database database) throws DatabaseException { if (((defaultCatalogName != null) || (defaultSchemaName != null)) && !(database.getConnection() instanceof OfflineConnection)) { if (database instanceof OracleDatabase) { String schema = defaultCatalogName; if (schema == null) { schema = defaultSchemaName; } ExecutorService.getInstance().getExecutor(database).execute( new RawSqlStatement("ALTER SESSION SET CURRENT_SCHEMA=" + database.escapeObjectName(schema, Schema.class))); } else if (database instanceof PostgresDatabase && defaultSchemaName != null) { ExecutorService.getInstance().getExecutor(database).execute(new RawSqlStatement("SET SEARCH_PATH TO " + database.escapeObjectName(defaultSchemaName, Schema.class))); } else if (database instanceof AbstractDb2Database) { String schema = defaultCatalogName; if (schema == null) { schema = defaultSchemaName; } ExecutorService.getInstance().getExecutor(database).execute(new RawSqlStatement("SET CURRENT SCHEMA " + schema)); } else if (database instanceof MySQLDatabase) { String schema = defaultCatalogName; if (schema == null) { schema = defaultSchemaName; } ExecutorService.getInstance().getExecutor(database).execute(new RawSqlStatement("USE " + schema)); } } }public void init(ConfigurationValueProvider... configurationValueProviders) { if (configurationValueProviders == null) { configurationValueProviders = new ConfigurationValueProvider[0]; } this.configurationValueProviders = configurationValueProviders; this.reset(); }public static String getValueForColumn(ResultSet rs, String columnNameToCheck, Database database) throws SQLException { ResultSetMetaData metadata = rs.getMetaData(); int numberOfColumns = metadata.getColumnCount(); String correctedColumnName = database.correctObjectName(columnNameToCheck, Column.class); // get the column names; column indexes start from 1 for (int i = 1; i < (numberOfColumns + 1); i++) { String columnName = metadata.getColumnLabel(i); // Get the name of the column's table name if (correctedColumnName.equalsIgnoreCase(columnName)) { return rs.getString(columnName); } } return null; }public boolean isFilteredBy(Class filterType) { if (!willRun) { return false; } if (filterResults == null) { return false; } for (ChangeSetFilterResult result : filterResults) { if (result.getFilter().equals(filterType)) { return true; } } return false; }public static String getSimplePathForResources(String entryName, String path) { String[] components = path.split("!"); if (components.length == 3) { if (components[1].endsWith(".jar")) { return components[2].substring(1); } else { return entryName.replaceFirst(components[1], "").substring(1); } } return entryName; }CDILiquibaseConfig fileLocked(final String id, Callable action) throws Exception { log.info(LogType.LOG, String.format("[id = %s] JVM lock acquired, acquiring file lock", id)); String lockPath = String.format("%s/schema.liquibase.lock", ROOT_PATH); File lockFile = new File(lockPath); if (!lockFile.exists() && lockFile.createNewFile()) { log.info(LogType.LOG, String.format("[id = %s] Created lock file [path='%s'].", id, lockPath)); } log.info(LogType.LOG, String.format("[id = %s] Trying to acquire the file lock [file='%s']...", id, lockPath)); CDILiquibaseConfig actionResult = null; FileLock lock = null; try ( FileOutputStream fileStream = new FileOutputStream(lockPath); FileChannel fileChannel = fileStream.getChannel(); ) { while (null == lock) { try { lock = fileChannel.tryLock(); } catch (OverlappingFileLockException e) { log.fine(LogType.LOG, String.format("[id = %s] Lock already acquired, waiting for the lock...", id)); } if (null == lock) { log.fine(LogType.LOG, String.format("[id = %s] Waiting for the lock...", id)); Thread.sleep(FILE_LOCK_TIMEOUT); } } log.info(LogType.LOG, String.format("[id = %s] File lock acquired, running liquibase...", id)); actionResult = action.call(); lock.release(); } catch (Exception e) { log.warning(LogType.LOG, e.getMessage(), e); } return actionResult; }public CDILiquibaseConfig createCDILiquibaseConfig() { final String id = UUID.randomUUID().toString(); log.fine(LogType.LOG, String.format("[id = %s] createConfig(). Date: '%s'", id, new Date())); final InputStream is = SchemesCDIConfigBuilder.class.getResourceAsStream(SCHEMA_NAME); try { return jvmLocked(id, new Callable() { public CDILiquibaseConfig call() throws Exception { return createCDILiquibaseConfig(id, is); } }); } catch (Exception ex) { log.warning(LogType.LOG, String.format("[id = %s] Unable to initialize liquibase where '%s'.", id, ex.getMessage()), ex); return null; } finally { try { is.close(); } catch (IOException ioe) { log.warning(LogType.LOG, String.format("[id = %s] IOException during closing an input stream '%s'.", id, ioe.getMessage()), ioe); } } }public List getOutgoingForeignKeys() { List fkList = getAttribute("outgoingForeignKeys", List.class); return ((fkList == null) ? new ArrayList(0) : fkList); }protected Object undoCollection(Object potentialCollection, Object otherObject) { if ((potentialCollection != null) && (otherObject != null) && (potentialCollection instanceof Collection) && !(otherObject instanceof Collection)) { if ((((Collection) potentialCollection).size() == 1) && ((Collection) potentialCollection).iterator() .next().getClass().equals(otherObject.getClass())) { potentialCollection = ((Collection) potentialCollection).iterator().next(); } } return potentialCollection; }private static Method[] getMethods(Object object) { Method[] methods = methodCache.get(object.getClass()); if (methods == null) { methods = object.getClass().getMethods(); methodCache.put(object.getClass(), methods); } return methods; }private static Method getWriteMethod(Object object, String propertyName) { String methodName = "set" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1); Method[] methods = getMethods(object); for (Method method : methods) { if (method.getName().equals(methodName) && (method.getParameterTypes().length == 1)) { return method; } } return null; }private static Method getReadMethod(Object object, String propertyName) { String getMethodName = "get" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1); String isMethodName = "is" + propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1); Method[] methods = getMethods(object); for (Method method : methods) { if ((method.getName().equals(getMethodName) || method.getName().equals(isMethodName)) && (method .getParameterTypes().length == 0)) { return method; } } return null; }public static void setProperty(Object object, String propertyName, String propertyValue) { Method method = getWriteMethod(object, propertyName); if (method == null) { throw new UnexpectedLiquibaseException ( String.format("Property [%s] was not found for object type [%s]", propertyName, object.getClass().getName() )); } Class parameterType = method.getParameterTypes()[0]; Object finalValue = propertyValue; if (parameterType.equals(Boolean.class) || parameterType.equals(boolean.class)) { finalValue = Boolean.valueOf(propertyValue); } else if (parameterType.equals(Integer.class)) { finalValue = Integer.valueOf(propertyValue); } else if (parameterType.equals(Long.class)) { finalValue = Long.valueOf(propertyValue); } else if (parameterType.equals(BigInteger.class)) { finalValue = new BigInteger(propertyValue); } else if (parameterType.equals(BigDecimal.class)) { finalValue = new BigDecimal(propertyValue); } else if (parameterType.equals(DatabaseFunction.class)) { finalValue = new DatabaseFunction(propertyValue); } else if (parameterType.equals(SequenceNextValueFunction.class)) { finalValue = new SequenceNextValueFunction(propertyValue); } else if (parameterType.equals(SequenceCurrentValueFunction.class)) { finalValue = new SequenceCurrentValueFunction(propertyValue); } else if (Enum.class.isAssignableFrom(parameterType)) { finalValue = Enum.valueOf((Class) parameterType, propertyValue); } try { method.invoke(object, finalValue); } catch (IllegalAccessException | InvocationTargetException e) { throw new UnexpectedLiquibaseException(e); } catch (IllegalArgumentException e) { throw new UnexpectedLiquibaseException("Cannot call " + method.toString() + " with value of type " + finalValue.getClass().getName()); } }public static boolean hasProperty(Object object, String propertyName) { return hasReadProperty(object, propertyName) && hasWriteProperty(object, propertyName); }public static Class getPropertyType(Object object, String propertyName) { Method readMethod = getReadMethod(object, propertyName); if (readMethod == null) { return null; } return readMethod.getReturnType(); }protected void addIfMatching(PackageScanFilter test, String fqn, Set> classes) { try { String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.'); Set set = getClassLoaders(); boolean found = false; for (ClassLoader classLoader : set) { log.fine(LogType.LOG, "Testing that class " + externalName + " matches criteria [" + test + "] using classloader:" + classLoader); try { Class type = classLoader.loadClass(externalName); log.fine(LogType.LOG, "Loaded the class: " + type + " in classloader: " + classLoader); if (test.matches(type)) { log.fine(LogType.LOG, "Found class: " + type + " which matches the filter in classloader: " + classLoader); classes.add(type); } found = true; break; } catch (ClassNotFoundException e) { log.fine(LogType.LOG, "Cannot find class '" + fqn + "' in classloader: " + classLoader + ". Reason: " + e, e); } catch (LinkageError e) { log.fine(LogType.LOG, "Cannot find the class definition '" + fqn + "' in classloader: " + classLoader + ". Reason: " + e, e); } catch (Exception e) { log.severe(LogType.LOG, "Cannot load class '"+fqn+"' in classloader: "+classLoader+". Reason: "+e, e); } } if (!found) { // use debug to avoid being noisy in logs log.fine(LogType.LOG, "Cannot find class '" + fqn + "' in any classloaders: " + set); } } catch (Exception e) { log.warning(LogType.LOG, "Cannot examine class '" + fqn + "' due to a " + e.getClass().getName() + " with message: " + e.getMessage(), e); } }protected void loadImplementationsInJar( String parentPackage, InputStream parentFileStream, ClassLoader loader, String parentFileName, String grandparentFileName) throws IOException { Set classFiles = classFilesByLocation.get(parentFileName); if (classFiles == null) { classFiles = new HashSet(); classFilesByLocation.put(parentFileName, classFiles); Set grandparentClassFiles = classFilesByLocation.get(grandparentFileName); if (grandparentClassFiles == null) { grandparentClassFiles = new HashSet(); classFilesByLocation.put(grandparentFileName, grandparentClassFiles); } JarInputStream jarStream; if (parentFileStream instanceof JarInputStream) { jarStream = (JarInputStream) parentFileStream; } else { jarStream = new JarInputStream(parentFileStream); } JarEntry entry; while ((entry = jarStream.getNextJarEntry()) != null) { String name = entry.getName(); if (name != null) { if (name.endsWith(".jar")) { //in a nested jar log.fine(LogType.LOG, "Found nested jar " + name); // To avoid needing to unzip 'parentFile' in its entirety, as that // may take a very long time (see CORE-2115) or not even be possible // (see CORE-2595), we load the nested JAR from the classloader and // read it as a zip. // // It is safe to assume that the nested JAR is readable by the classloader // as a resource stream, because we have reached this point by scanning // through packages located from `classloader` by using `getResource`. // If loading this nested JAR as a resource fails, then certainly loading // classes from inside it with `classloader` would fail and we are safe // to exclude it form the PackageScan. InputStream nestedJarResourceStream = loader.getResourceAsStream(name); if (nestedJarResourceStream != null) { JarInputStream nestedJarStream = new JarInputStream(nestedJarResourceStream); try { loadImplementationsInJar( parentPackage, nestedJarStream, loader, parentFileName + "!" + name, parentFileName); } finally { nestedJarStream.close(); } } } else if (!entry.isDirectory() && name.endsWith(".class")) { classFiles.add(name.trim()); grandparentClassFiles.add(name.trim()); } } } } for (String name : classFiles) { if (name.contains(parentPackage)) { loadClass(name, loader); } } }protected PropertyEditor getPropertyEditor(PropertyDescriptor desc) throws ReflectiveOperationException { Class cls = desc.getPropertyEditorClass(); if (null != cls) { return (PropertyEditor) cls.getConstructor().newInstance(); } return getPropertyEditorValue(desc.getPropertyType()); }protected T processLine(MappingStrategy mapper, String[] line) throws ReflectiveOperationException, IntrospectionException { T bean = mapper.createBean(); for (int col = 0; col < line.length; col++) { if (mapper.isAnnotationDriven()) { processField(mapper, line, bean, col); } else { processProperty(mapper, line, bean, col); } } return bean; }public List parse(MappingStrategy mapper, Reader reader) { return parse(mapper, new CSVReader(reader)); }public void clearCheckSums() throws LiquibaseException { LOG.info(LogType.LOG, "Clearing database change log checksums"); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); UpdateStatement updateStatement = new UpdateStatement( getDatabase().getLiquibaseCatalogName(), getDatabase().getLiquibaseSchemaName(), getDatabase().getDatabaseChangeLogTableName() ); updateStatement.addNewColumnValue("MD5SUM", null); ExecutorService.getInstance().getExecutor(database).execute(updateStatement); getDatabase().commit(); } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } } resetServices(); }public List getChangeSetStatuses(Contexts contexts, LabelExpression labelExpression, boolean checkLiquibaseTables) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); DatabaseChangeLog changeLog = getDatabaseChangeLog(); if (checkLiquibaseTables) { checkLiquibaseTables(true, changeLog, contexts, labelExpression); } changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = getStandardChangelogIterator(contexts, labelExpression, changeLog); StatusVisitor visitor = new StatusVisitor(database); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression)); return visitor.getStatuses(); }public DatabaseChangeLogLock[] listLocks() throws LiquibaseException { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); return LockServiceFactory.getInstance().getLockService(database).listLocks(); }public void tag(String tagString) throws LiquibaseException { LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId(); checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); getDatabase().tag(tagString); } finally { try { lockService.releaseLock(); } catch (LockException e) { LOG.severe(LogType.LOG, MSG_COULD_NOT_RELEASE_LOCK, e); } } }private boolean applyIsComputedExpressionHeuristic(ColumnConfig column, Database database) { String expr = column.getName(); /* * https://firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-structure-identifiers.html * says the following about what makes a valid identifier in Firebird: * - At most 31 chars * - Starts with a 7-bit character * - After that, letters, digits, underscores or dollar signs are valid characters */ String regex = "^(?i)[ABCDEFGHIJKLMNOPQRSTUVWXYZ]" // Starting character + "[ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$]{0,30}$"; // following characters if (!expr.matches(regex)) return true; /* At this point, we know that expr at least has the form of an identifier. If it is a function, it must * be in the list of database functions. */ if (database.isFunction(expr)) return true; else return false; }@Override public Sql[] generateSql(CreateIndexStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { /* * According to https://firebirdsql.org/refdocs/langrefupd20-create-table.html#langrefupd20-ct-using-index , * Firebird automatically creates indexes for PRIMARY KEY, UNIQUE KEY and FOREIGN KEY constraints, * so we should not duplicate that functionality (=we should not issue CREATE INDEX statements for them) */ List associatedWith = StringUtil.splitAndTrim(statement.getAssociatedWith(), ","); if ((associatedWith != null) && (associatedWith.contains(Index.MARK_PRIMARY_KEY) || associatedWith.contains (Index.MARK_UNIQUE_CONSTRAINT) || associatedWith.contains(Index.MARK_FOREIGN_KEY))) { return new Sql[0]; } StringBuffer buffer = new StringBuffer(); buffer.append("CREATE "); // If the statement wants a UNIQUE index, issue a CREATE UNIQUE ... INDEX statement. if ((statement.isUnique() != null) && statement.isUnique()) { buffer.append("UNIQUE "); } /* * Examine the direction (ASCending or DESCending) of all columns of the planned index. If _all_ of them * are DESC, issue a CREATE DESCENDING INDEX statement. If all of them are ASC, we do not need to do anything * special (ASCENDING is the default). However, since Firebird does not seem to support mixed ASC/DESC * columns within a single index, we must error out. * * The syntax we want to create is this: * CREATE [UNIQUE] [ASC[ENDING] | DESC[ENDING]] INDEX index_name ON table_name * {(col [, col …]) | COMPUTED BY ()}; */ ColumnAnalysisResult result = analyseColumns(statement, database); if (result.isFoundDescColumns()) buffer.append("DESCENDING "); buffer.append("INDEX "); if (statement.getIndexName() != null) { String indexSchema = statement.getTableSchemaName(); buffer.append(database.escapeIndexName(statement.getTableCatalogName(), indexSchema, statement.getIndexName())).append(" "); } buffer.append("ON "); // append table name buffer.append(database.escapeTableName(statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName())); if (result.getNumComputedCols() > 0) buffer.append("COMPUTED BY "); buffer.append(String.format("(%s)", result.getColumnExpression())); return new Sql[]{new UnparsedSql(buffer.toString(), getAffectedIndex(statement))}; }public ConfigurationProperty setDefaultValue(Object defaultValue) { if ((defaultValue != null) && !type.isAssignableFrom(defaultValue.getClass())) { if ((type == Long.class) && (defaultValue instanceof Integer)) { return setDefaultValue(((Integer) defaultValue).longValue()); } throw new UnexpectedLiquibaseException("Property "+name+" on is of type "+type.getSimpleName()+", not "+defaultValue.getClass().getSimpleName()); } this.defaultValue = defaultValue; return this; }public ConfigurationProperty addAlias(String... aliases) { if (aliases != null) { this.aliases.addAll(Arrays.asList(aliases)); } return this; }public void setValue(Object value) { if ((value != null) && !type.isAssignableFrom(value.getClass())) { throw new UnexpectedLiquibaseException("Property "+name+" on is of type "+type.getSimpleName()+", not "+value.getClass().getSimpleName()); } this.value = value; wasOverridden = true; }public T getValue(Class type) { if (!this.type.isAssignableFrom(type)) { throw new UnexpectedLiquibaseException("Property "+name+" on is of type "+this.type.getSimpleName()+", not "+type.getSimpleName()); } return (T) value; }protected Object valueOf(Object value) { if (value == null) { return value; } else if (type.isAssignableFrom(value.getClass())) { return value; } else if (value instanceof String) { if (type.equals(Boolean.class)) { return Boolean.valueOf((String) value); } else if (type.equals(Integer.class)) { return Integer.valueOf((String) value); } else if (type.equals(BigDecimal.class)) { return new BigDecimal((String) value); } else if (type.equals(Long.class)) { return Long.valueOf((String) value); } else if (type.equals(List.class)) { return StringUtil.splitAndTrim((String) value, ","); } else { throw new UnexpectedLiquibaseException("Cannot parse property "+value.getClass().getSimpleName()+" to a "+type.getSimpleName()); } } else { throw new UnexpectedLiquibaseException("Could not convert "+value.getClass().getSimpleName()+" to a "+type.getSimpleName()); } }private void executeUpdate(ServletContext servletContext, InitialContext ic) throws NamingException, SQLException, LiquibaseException { setDataSource((String) servletValueContainer.getValue(LIQUIBASE_DATASOURCE)); if (getDataSource() == null) { throw new RuntimeException("Cannot run Liquibase, " + LIQUIBASE_DATASOURCE + " is not set"); } setChangeLogFile((String) servletValueContainer.getValue(LIQUIBASE_CHANGELOG)); if (getChangeLogFile() == null) { throw new RuntimeException("Cannot run Liquibase, " + LIQUIBASE_CHANGELOG + " is not set"); } setContexts((String) servletValueContainer.getValue(LIQUIBASE_CONTEXTS)); setLabels((String) servletValueContainer.getValue(LIQUIBASE_LABELS)); this.defaultSchema = StringUtil.trimToNull((String) servletValueContainer.getValue(LIQUIBASE_SCHEMA_DEFAULT)); Connection connection = null; Database database = null; try { DataSource dataSource = (DataSource) ic.lookup(this.dataSourceName); connection = dataSource.getConnection(); Thread currentThread = Thread.currentThread(); ClassLoader contextClassLoader = currentThread.getContextClassLoader(); ResourceAccessor threadClFO = new ClassLoaderResourceAccessor(contextClassLoader); ResourceAccessor clFO = new ClassLoaderResourceAccessor(); ResourceAccessor fsFO = new FileSystemResourceAccessor(); database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection)); database.setDefaultSchemaName(getDefaultSchema()); Liquibase liquibase = new Liquibase(getChangeLogFile(), new CompositeResourceAccessor(clFO, fsFO, threadClFO), database); @SuppressWarnings("unchecked") Enumeration initParameters = servletContext.getInitParameterNames(); while (initParameters.hasMoreElements()) { String name = initParameters.nextElement().trim(); if (name.startsWith(LIQUIBASE_PARAMETER + ".")) { liquibase.setChangeLogParameter(name.substring(LIQUIBASE_PARAMETER.length() + 1), servletValueContainer.getValue(name)); } } liquibase.update(new Contexts(getContexts()), new LabelExpression(getLabels())); } finally { if (database != null) { database.close(); } else if (connection != null) { connection.close(); } } }private void processCharacter(StringBuilder sb, char nextChar) { if ((escapechar != NO_ESCAPE_CHARACTER) && checkCharactersToEscape(nextChar)) { sb.append(escapechar).append(nextChar); } else { sb.append(nextChar); } }protected StringBuilder processLine(String nextElement) { StringBuilder sb = new StringBuilder(nextElement.length() * 2); // this is for the worse case where all elements have to be escaped. for (int j = 0; j < nextElement.length(); j++) { char nextChar = nextElement.charAt(j); processCharacter(sb, nextChar); } return sb; }protected boolean stringContainsSpecialCharacters(String line) { return (line.indexOf(quotechar) != -1) || (line.indexOf(escapechar) != -1) || (line.indexOf(separator) != -1) || line.contains(DEFAULT_LINE_END) || line.contains("\r"); }public void writeNext(String[] nextLine, boolean applyQuotesToAll) { if (nextLine == null) { return; } StringBuilder sb = new StringBuilder(nextLine.length * 2); // This is for the worse case where all elements have to be escaped. for (int i = 0; i < nextLine.length; i++) { if (i != 0) { sb.append(separator); } String nextElement = nextLine[i]; if (nextElement == null) { continue; } Boolean stringContainsSpecialCharacters = stringContainsSpecialCharacters(nextElement); if ((applyQuotesToAll || stringContainsSpecialCharacters) && (quotechar != NO_QUOTE_CHARACTER)) { sb.append(quotechar); } if (stringContainsSpecialCharacters) { sb.append(processLine(nextElement)); } else { sb.append(nextElement); } if ((applyQuotesToAll || stringContainsSpecialCharacters) && (quotechar != NO_QUOTE_CHARACTER)) { sb.append(quotechar); } } sb.append(lineEnd); pw.write(sb.toString()); }private boolean isCurrentFieldValueSpecified(Field f) throws IllegalAccessException { Object currentValue = f.get(this); if (currentValue == null) { return false; } Object defaultValue = getDefaultValue(f); if (defaultValue == null) { return currentValue != null; } else { // There is a default value, check to see if the user has selected something other // than the default return !defaultValue.equals(f.get(this)); } }protected void parsePropertiesFile(InputStream propertiesInputStream) throws MojoExecutionException { if (propertiesInputStream == null) { throw new MojoExecutionException("Properties file InputStream is null."); } Properties props = new Properties(); try { props.load(propertiesInputStream); } catch (IOException e) { throw new MojoExecutionException("Could not load the properties Liquibase file", e); } for (Iterator it = props.keySet().iterator(); it.hasNext(); ) { String key = null; try { key = (String) it.next(); Field field = MavenUtils.getDeclaredField(this.getClass(), key); if (propertyFileWillOverride) { getLog().debug(" properties file setting value: " + field.getName()); setFieldValue(field, props.get(key).toString()); } else { if (!isCurrentFieldValueSpecified(field)) { getLog().debug(" properties file setting value: " + field.getName()); setFieldValue(field, props.get(key).toString()); } } } catch (Exception e) { getLog().info(" '" + key + "' in properties file is not being used by this " + "task."); } } }protected void printSettings(String indent) { if (indent == null) { indent = ""; } getLog().info(indent + "driver: " + driver); getLog().info(indent + "url: " + url); getLog().info(indent + "username: " + username); getLog().info(indent + "password: " + "*****"); getLog().info(indent + "use empty password: " + emptyPassword); getLog().info(indent + "properties file: " + propertyFile); getLog().info(indent + "properties file will override? " + propertyFileWillOverride); getLog().info(indent + "prompt on non-local database? " + promptOnNonLocalDatabase); getLog().info(indent + "clear checksums? " + clearCheckSums); }protected ClassLoader getClassLoaderIncludingProjectClasspath() throws MojoExecutionException { try { List classpathElements = project.getCompileClasspathElements(); classpathElements.add(project.getBuild().getOutputDirectory()); URL urls[] = new URL[classpathElements.size()]; for (int i = 0; i < classpathElements.size(); ++i) { urls[i] = new File((String) classpathElements.get(i)).toURI().toURL(); } return new URLClassLoader(urls, getMavenArtifactClassLoader()); } catch (Exception e) { throw new MojoExecutionException("Failed to create project classloader", e); } }public static CheckSum compute(String valueToChecksum) { return new CheckSum(MD5Util.computeMD5( //remove "Unknown" unicode char 65533 Normalizer.normalize( StringUtil.standardizeLineEndings(valueToChecksum) .replace("\uFFFD", "") , Normalizer.Form.NFC) ), getCurrentVersion()); }public static CheckSum parse(String checksumValue) { if (checksumValue == null) { return null; } // The general layout of a checksum is: // <1 digit: algorithm version number>:<1..n characters alphanumeric checksum> // Example: 7:2cdf9876e74347162401315d34b83746 Matcher matcher = CHECKSUM_PATTERN.matcher(checksumValue); if (matcher.find()) { return new CheckSum(matcher.group(2), Integer.parseInt(matcher.group(1))); } else { // No version information found return new CheckSum(checksumValue, 1); } }public String getAbsolutePath(String path) { String p = path; File f = new File(p); if (!f.isAbsolute()) { String basePath = FilenameUtils.getFullPath(changeSet.getChangeLog().getPhysicalFilePath()); p = FilenameUtils.normalize(basePath + p); } return p; }protected void attachParams(List cols, PreparedStatement stmt) throws SQLException, DatabaseException { int i = 1; // index starts from 1 for (ColumnConfig col : cols) { LOG.fine(LogType.LOG, "Applying column parameter = " + i + " for column " + col.getName()); applyColumnParameter(stmt, i, col); i++; } }private Boolean getGlobalParam(Map property) { Boolean global = null; Object globalObj = property.get("global"); if (globalObj == null) { // default behaviour before liquibase 3.4 global = true; } else { global = (Boolean) globalObj; } return global; }public static Set createIfNull(Set currentValue) { if (currentValue == null) { return new HashSet<>(); } else { return currentValue; } }public static T[] createIfNull(T[] arguments) { if (arguments == null) { return (T[]) new Object[0]; } else { return arguments; } }public void setValue(Change change, Object value) { if ((value instanceof String) && (!"string".equals(dataType))) { try { switch (dataType) { case "bigInteger": value = new BigInteger((String) value); break; case "databaseFunction": value = new DatabaseFunction((String) value); break; default: throw new UnexpectedLiquibaseException("Unknown data type: " + dataType); } } catch (Exception e) { throw new UnexpectedLiquibaseException("Cannot convert string value '" + value + "' to " + dataType + ": " + e.getMessage()); } } try { for (PropertyDescriptor descriptor : PropertyUtils.getInstance().getDescriptors(change.getClass())) { if (descriptor.getDisplayName().equals(this.parameterName)) { Method writeMethod = descriptor.getWriteMethod(); if (writeMethod == null) { throw new UnexpectedLiquibaseException("Could not find writeMethod for " + this.parameterName); } Class expectedWriteType = writeMethod.getParameterTypes()[0]; if ((value != null) && !expectedWriteType.isAssignableFrom(value.getClass())) { if (expectedWriteType.equals(String.class)) { value = value.toString(); } else { throw new UnexpectedLiquibaseException( "Could not convert " + value.getClass().getName() + " to " + expectedWriteType.getName() ); } } writeMethod.invoke(change, value); } } } catch (Exception e) { throw new UnexpectedLiquibaseException("Error setting " + this.parameterName + " to " + value, e); } }public Object getCurrentValue(Change change) { try { for (PropertyDescriptor descriptor : PropertyUtils.getInstance().getDescriptors(change.getClass())) { if (descriptor.getDisplayName().equals(this.parameterName)) { Method readMethod = descriptor.getReadMethod(); if (readMethod == null) { readMethod = change.getClass().getMethod( "is" + StringUtil.upperCaseFirst(descriptor.getName()) ); } return readMethod.invoke(change); } } throw new RuntimeException("Could not find readMethod for " + this.parameterName); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } }String convertCase(String str) { if (str == null) { return null; } return isSensitive ? str : str.toLowerCase(); }public static IOCase forName(String name) { if (IOCase.SENSITIVE.name.equals(name)){ return IOCase.SENSITIVE; } if (IOCase.INSENSITIVE.name.equals(name)){ return IOCase.INSENSITIVE; } if (IOCase.SYSTEM.name.equals(name)){ return IOCase.SYSTEM; } throw new IllegalArgumentException("Invalid IOCase name: " + name); }@Override public void init(ConfigurationValueProvider... configurationValueProviders) { if (configurationValueProviders != null) { for (ConfigurationProperty property : getContainer().properties.values()) { property.init(configurationValueProviders); } } }@Override public T getValue(String propertyName, Class returnType) { return getContainer().getValue(propertyName, returnType); }public void setColumnMapping(Map columnMapping) { this.columnMapping.clear(); for (Map.Entry entry : columnMapping.entrySet()) { this.columnMapping.put(entry.getKey().toUpperCase(), entry.getValue()); } }@Override public String getColumnName(int col) { return (col < header.length) ? columnMapping.get(header[col].toUpperCase()) : null; }private void enlarge(final int size) { int length1 = 2 * data.length; int length2 = length + size; byte[] newData = new byte[length1 > length2 ? length1 : length2]; System.arraycopy(data, 0, newData, 0, length); data = newData; }public ByteVector putByteArray(final byte[] b, final int off, final int len) { if (length + len > data.length) { enlarge(len); } if (b != null) { System.arraycopy(b, off, data, length, len); } length += len; return this; }public ByteVector putUTF8(final String s) { int charLength = s.length(); if (charLength > 65535) { throw new IllegalArgumentException(); } int len = length; if (len + 2 + charLength > data.length) { enlarge(2 + charLength); } byte[] data = this.data; // optimistic algorithm: instead of computing the byte length and then // serializing the string (which requires two loops), we assume the byte // length is equal to char length (which is the most frequent case), and // we start serializing the string right away. During the serialization, // if we find that this assumption is wrong, we continue with the // general method. data[len++] = (byte) (charLength >>> 8); data[len++] = (byte) charLength; for (int i = 0; i < charLength; ++i) { char c = s.charAt(i); if (c >= '\001' && c <= '\177') { data[len++] = (byte) c; } else { length = len; return encodeUTF8(s, i, 65535); } } length = len; return this; }public ByteVector putLong(final long l) { int length = this.length; if (length + 8 > data.length) { enlarge(8); } byte[] data = this.data; int i = (int) (l >>> 32); data[length++] = (byte) (i >>> 24); data[length++] = (byte) (i >>> 16); data[length++] = (byte) (i >>> 8); data[length++] = (byte) i; i = (int) l; data[length++] = (byte) (i >>> 24); data[length++] = (byte) (i >>> 16); data[length++] = (byte) (i >>> 8); data[length++] = (byte) i; this.length = length; return this; }public ByteVector putInt(final int i) { int length = this.length; if (length + 4 > data.length) { enlarge(4); } byte[] data = this.data; data[length++] = (byte) (i >>> 24); data[length++] = (byte) (i >>> 16); data[length++] = (byte) (i >>> 8); data[length++] = (byte) i; this.length = length; return this; }ByteVector put12(final int b, final int s) { int length = this.length; if (length + 3 > data.length) { enlarge(3); } byte[] data = this.data; data[length++] = (byte) b; data[length++] = (byte) (s >>> 8); data[length++] = (byte) s; this.length = length; return this; }public ByteVector putShort(final int s) { int length = this.length; if (length + 2 > data.length) { enlarge(2); } byte[] data = this.data; data[length++] = (byte) (s >>> 8); data[length++] = (byte) s; this.length = length; return this; }ByteVector put11(final int b1, final int b2) { int length = this.length; if (length + 2 > data.length) { enlarge(2); } byte[] data = this.data; data[length++] = (byte) b1; data[length++] = (byte) b2; this.length = length; return this; }public ByteVector putByte(final int b) { int length = this.length; if (length + 1 > data.length) { enlarge(1); } data[length++] = (byte) b; this.length = length; return this; }public int getOpcode(final int opcode) { if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) { // the offset for IALOAD or IASTORE is in byte 1 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF00) >> 8 : 4); } else { // the offset for other instructions is in byte 2 of 'off' for // primitive types (buf == null) return opcode + (buf == null ? (off & 0xFF0000) >> 16 : 4); } }public static String getDescriptor(final Class c) { StringBuilder buf = new StringBuilder(); getDescriptor(buf, c); return buf.toString(); }private void getDescriptor(final StringBuilder buf) { if (this.buf == null) { // descriptor is in byte 3 of 'off' for primitive types (buf == // null) buf.append((char) ((off & 0xFF000000) >>> 24)); } else if (sort == OBJECT) { buf.append('L'); buf.append(this.buf, off, len); buf.append(';'); } else { // sort == ARRAY || sort == METHOD buf.append(this.buf, off, len); } }private static Type getType(final char[] buf, final int off) { int len; switch (buf[off]) { case 'V': return VOID_TYPE; case 'Z': return BOOLEAN_TYPE; case 'C': return CHAR_TYPE; case 'B': return BYTE_TYPE; case 'S': return SHORT_TYPE; case 'I': return INT_TYPE; case 'F': return FLOAT_TYPE; case 'J': return LONG_TYPE; case 'D': return DOUBLE_TYPE; case '[': len = 1; while (buf[off + len] == '[') { ++len; } if (buf[off + len] == 'L') { ++len; while (buf[off + len] != ';') { ++len; } } return new Type(ARRAY, buf, off, len + 1); case 'L': len = 1; while (buf[off + len] != ';') { ++len; } return new Type(OBJECT, buf, off + 1, len - 1); // case '(': default: return new Type(METHOD, buf, off, buf.length - off); } }public static int getArgumentsAndReturnSizes(final String desc) { int n = 1; int c = 1; while (true) { char car = desc.charAt(c++); if (car == ')') { car = desc.charAt(c); return n << 2 | (car == 'V' ? 0 : (car == 'D' || car == 'J' ? 2 : 1)); } else if (car == 'L') { while (desc.charAt(c++) != ';') { } n += 1; } else if (car == '[') { while ((car = desc.charAt(c)) == '[') { ++c; } if (car == 'D' || car == 'J') { n -= 1; } } else if (car == 'D' || car == 'J') { n += 2; } else { n += 1; } } }public static Type getReturnType(final String methodDescriptor) { char[] buf = methodDescriptor.toCharArray(); int off = 1; while (true) { char car = buf[off++]; if (car == ')') { return getType(buf, off); } else if (car == 'L') { while (buf[off++] != ';') { } } } }public static Type[] getArgumentTypes(final String methodDescriptor) { char[] buf = methodDescriptor.toCharArray(); int off = 1; int size = 0; while (true) { char car = buf[off++]; if (car == ')') { break; } else if (car == 'L') { while (buf[off++] != ';') { } ++size; } else if (car != '[') { ++size; } } Type[] args = new Type[size]; off = 1; size = 0; while (buf[off] != ')') { args[size] = getType(buf, off); off += args[size].len + (args[size].sort == OBJECT ? 2 : 0); size += 1; } return args; }public static Type getObjectType(final String internalName) { char[] buf = internalName.toCharArray(); return new Type(buf[0] == '[' ? ARRAY : OBJECT, buf, 0, buf.length); }public static int extract(int bs, int low, int high) { bs = bs >> low; int mask = 0; for (int i = 0; i < (high - low); i++) { mask += 1 << i; } return bs & mask; }public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) { if (api < Opcodes.ASM5) { throw new RuntimeException(); } if (cv != null) { return cv.visitTypeAnnotation(typeRef, typePath, desc, visible); } return null; }public AnnotationVisitor visitAnnotation(String desc, boolean visible) { if (cv != null) { return cv.visitAnnotation(desc, visible); } return null; }public void visitOuterClass(String owner, String name, String desc) { if (cv != null) { cv.visitOuterClass(owner, name, desc); } }public void visitSource(String source, String debug) { if (cv != null) { cv.visitSource(source, debug); } }private int init(final ClassWriter cw, final int t) { int s; if (t == UNINITIALIZED_THIS) { s = OBJECT | cw.addType(cw.thisName); } else if ((t & (DIM | BASE_KIND)) == UNINITIALIZED) { String type = cw.typeTable[t & BASE_VALUE].strVal1; s = OBJECT | cw.addType(type); } else { return t; } for (int j = 0; j < initializationCount; ++j) { int u = initializations[j]; int dim = u & DIM; int kind = u & KIND; if (kind == LOCAL) { u = dim + inputLocals[u & VALUE]; } else if (kind == STACK) { u = dim + inputStack[inputStack.length - (u & VALUE)]; } if (t == u) { return s; } } return t; }����˝lQ����`�J W / �1t�A%�*"-�/�0�1U:"@ACRE5H�I�K�LsM�O)QKT�U�V Y�[�]�^=cfd6e�e�f�gyi�j�kGm p�sw1x�z�{@~�F�;���كr�/���2�ӎ���Ð��_�ȗ����"���w�f�*�����ԣ�6�j�O�1���˯��m�F����״���y���������'���!�!������� ���o���e�:����E�����^�1�����E���f������]������S�X�������`�a�8�����^�1���u�N�����x�����y������Q  �e� d!1%Z&�'h./�1�4�:�;�<1>�>�?�@�A�B�C�F�G&I|JdK�L�MLO�O3R-S�T([�\�_�`�a�b�cyd�ewgXj�u�wy�z����k�����W�����b�����V��u��`�E����=��� �����_�������g����q�����|�_�q�X��������Y�`������QjNQ'��� �� /&s)�.�2�7�:F<�=�>%@�@D>E�G�H�I�M=O'Q�Q�V�Y�]�_�`g�ik�k m n�n�op�p�u�v�w�x�y |�|}B~�~��a� �#���ʨ�������1���`���������X�#�7�����'�a�1����v��d� �������k������: � � �A,�@��[8Q�4q| �"�&U)k*<+-�-�.Z0�3m4_5�5�6b729:�;a?BGE�E�GyI�K�LnM�NhPvQfT�UnW^@l7n�nr�r�sEv�~���͋ύʏ���Қ]�ʞ������Ѷ۷��+�.�i�:�žo�����i���y�������g�,�-�L���C��������g��c�7�7�����M��8� �Q�private static void createDisplayPropertyConverters(final List displayProperties, final ComponentContainer formContent, final Binder binder, final PropertyDescriptor[] propertyDescriptors) { for (final String property : displayProperties) { final Class typeOfProperty = getTypeOfProperty(propertyDescriptors, property); if (typeOfProperty != null) { final AbstractField field = new TextField(); field.setReadOnly(true); field.setCaption(property); field.setWidth(ContentSize.FULL_SIZE); formContent.addComponent(field); final Converter converter = getConverterForType(typeOfProperty); if (converter != null) { binder.forField(field).withConverter(converter).bind(property); } else { binder.forField(field).bind(property); } } } }private static AbstractField createField(final String property) { if (StringUtils.containsIgnoreCase(property,HIDDEN_FIELD_NAME)) { return new PasswordField(); } else { return new TextField(); } }private static void addResultForMonth(final GovernmentBodyAnnualOutcomeSummary governmentBodyAnnualOutcomeSummary, final int month, final String value) { if (value != null && value.length() >0 ) { governmentBodyAnnualOutcomeSummary.addData(month,Double.valueOf(value.replaceAll(",", "."))); } }private static Map> createOrgMinistryMap( final Map> data) { final Map> orgMinistryMap = new HashMap<>(); final Set>> entrySet = data.entrySet(); for (final Entry> entry : entrySet) { orgMinistryMap.put(entry.getKey(), entry.getValue().stream().collect(Collectors.groupingBy(t -> t.getOrgNumber().replaceAll("-","") ,Collectors.collectingAndThen( Collectors.toList(), values -> values.get(0).getMinistry())))); } return orgMinistryMap; }private void addBallotData(final DataValueCalculator dataValueCalculator, final DataSeries dataSeries, final SimpleDateFormat simpleDateFormat, final Series series, final Entry> entry) { series.addSeries(new XYseries().setLabel(getPartyName(entry.getKey()))); dataSeries.newSeries(); final List list = entry.getValue(); for (final ViewRiksdagenVoteDataBallotPartySummaryDaily viewRiksdagenVoteDataBallotPartySummaryDaily : list) { if (viewRiksdagenVoteDataBallotPartySummaryDaily != null) { dataSeries.add( simpleDateFormat .format(viewRiksdagenVoteDataBallotPartySummaryDaily.getEmbeddedId().getVoteDate()), dataValueCalculator.getDataValue(viewRiksdagenVoteDataBallotPartySummaryDaily)); } } }private void createPartyBallotChart(final AbstractOrderedLayout content,final DataValueCalculator dataValueCalculator) { final Map> map = getPartyMap(); final DataSeries dataSeries = new DataSeries(); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DD_MMM_YYYY, Locale.ENGLISH); final Series series = new Series(); for (final Entry> entry : map.entrySet()) { if (!"-".equals(entry.getKey())) { addBallotData(dataValueCalculator, dataSeries, simpleDateFormat, series, entry); } } addChart(content,"Party ballot chart", new DCharts().setDataSeries(dataSeries).setOptions(getChartOptions().createOptionsXYDateFloatLegendInsideOneColumn(series)).show(), true); }private static void addPartyData(final DataSeries dataSeries, final SimpleDateFormat simpleDateFormat, final List list, final Function t) { dataSeries.newSeries(); for (final ViewRiksdagenVoteDataBallotPartySummaryDaily viewRiksdagenVoteDataBallotPartySummaryDaily : list) { if (viewRiksdagenVoteDataBallotPartySummaryDaily != null) { dataSeries.add( simpleDateFormat .format(viewRiksdagenVoteDataBallotPartySummaryDaily.getEmbeddedId().getVoteDate()), t.apply(viewRiksdagenVoteDataBallotPartySummaryDaily)); } } }private synchronized void initPartyMap() { if (partyMap == null) { final DataContainer partyBallotSummaryDailyDataContainer = getApplicationManager() .getDataContainer(ViewRiksdagenVoteDataBallotPartySummaryDaily.class); partyMap = partyBallotSummaryDailyDataContainer.getAll().parallelStream().filter(Objects::nonNull) .collect(Collectors.groupingBy(t -> t.getEmbeddedId().getParty())); } }private List getMaxSizeViewRiksdagenVoteDataBallotPartySummaryDaily() { initPartyMap(); final Optional>> first = partyMap.entrySet() .stream().sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size()) ).findFirst(); if (first.isPresent()) { return first.get().getValue(); } else { return new ArrayList<>(); } }private void updateBallot(final String ballotId) { try { configureAuthentication(); updateService.updateVoteDataData(riksdagenApi.getBallot(ballotId)); } catch (final DataFailureException e) { LOGGER.warn("Eror loading riksdagen voteData:" + ballotId + " errorMessage:", e); } finally { clearAuthentication(); } }public String getPagePath() { if (pageReference != null && !pageReference.isEmpty()) { return page + PAGE_SEPARATOR + pageReference; } else { return page; } }@ManyToOne(targetEntity = DocumentProposalData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "PROPOSAL_DOCUMENT_PROPOSAL_C_0") public DocumentProposalData getProposal() { return proposal; }@OneToMany(targetEntity = AssignmentElement.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "UPPDRAG_PERSON_ASSIGNMENT_EL_0") public List getUppdrag() { return this.uppdrag; }@OneToMany(targetEntity = SwedenMunicipalityData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "KOMMUN_SWEDEN_COUNTY_DATA_HJ_0") public List getKommun() { return this.kommun; }public void setResourceTypeMap(final Map> resourceTypeMap) { this.resourceTypeMap = Collections.unmodifiableMap(MapUtils.emptyIfNull(resourceTypeMap)); }public void setStatusMap(final Map> statusMap) { this.statusMap = Collections.unmodifiableMap(MapUtils.emptyIfNull(statusMap)); }public void setList(final List list) { this.list = Collections.unmodifiableList(ListUtils.emptyIfNull(list)); }private static void configureAuthentication(final String role) { final Collection authorities = AuthorityUtils.createAuthorityList(role); final Authentication authentication = new UsernamePasswordAuthenticationToken("service.impl.BootstrapDefaultConfig", "n/a", authorities); SecurityContextHolder.getContext().setAuthentication(authentication); }@OneToMany(targetEntity = SwedenMunicipalityElectionRegionData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "KOMMUNVALKRETS_SWEDEN_MUNICI_0") public List getKommunvalkrets() { return this.kommunvalkrets; }private void createOverviewContent(final VerticalLayout panelContent, final PersonData personData, final ViewRiksdagenPolitician viewRiksdagenPolitician, final String pageId) { LabelFactory.createHeader2Label(panelContent, OVERVIEW); final Link createPoliticianPageLink = getPageLinkFactory().createPoliticianPageLink(personData); panelContent.addComponent(createPoliticianPageLink); final Image image = new Image("", new ExternalResource(personData.getImageUrl192().replace("http://", "https://"))); final HorizontalLayout horizontalLayout = new HorizontalLayout(); horizontalLayout.setSizeFull(); panelContent.addComponent(horizontalLayout); horizontalLayout.addComponent(image); getFormFactory().addFormPanelTextFields(horizontalLayout, viewRiksdagenPolitician, ViewRiksdagenPolitician.class, AS_LIST); final VerticalLayout overviewLayout = new VerticalLayout(); overviewLayout.setSizeFull(); panelContent.addComponent(overviewLayout); panelContent.setExpandRatio(overviewLayout, ContentRatio.LARGE_FORM); getPoliticianMenuItemFactory().createOverviewPage(overviewLayout, pageId); panelContent.setExpandRatio(createPoliticianPageLink, ContentRatio.SMALL); panelContent.setExpandRatio(horizontalLayout, ContentRatio.GRID); }@Override public void createOverviewPage(final VerticalLayout panelContent) { final ResponsiveRow grid = RowUtil.createGridLayout(panelContent); createButtonLink(grid,POLITICAL_WORK_SUMMARY_TEXT,VaadinIcons.GROUP, COMMAND_DATAGRID, "Scoreboard over current member size, political days served and total assignments"); createButtonLink(grid,CURRENT_COMMITTEES_CURRENT_MEMBERS_TEXT,VaadinIcons.GROUP, COMMAND_CURRENT_COMMITTEES_BY_HEADCOUNT, "Chart over current committees and member size"); createButtonLink(grid,CURRENT_PARTIES_ACTIVE_IN_COMMITTEES_CURRENT_ASSIGNMENTS,VaadinIcons.GROUP, COMMAND_COMMITTEES_BY_PARTY, "Chart over current parties active in committees and member size"); createButtonLink(grid,CURRENT_PARTIES_ACTIVE_IN_COMMITTEES_TOTAL_DAYS_SERVED_IN_COMMITTEES,VaadinIcons.GROUP, COMMAND_CURRENT_COMMITTEES_BY_PARTY_DAYS_SERVED, "Chart over current parties active in committees days served"); createButtonLink(grid,ALL_COMMITTEES_TOTAL_MEMBERS,VaadinIcons.GROUP, COMMAND_ALL_COMMITTEES_BY_HEADCOUNT, "Chart over all committees and member size"); createButtonLink(grid,PAGE_VISIT_HISTORY_TEXT, VaadinIcons.GROUP, COMMAND_PAGEVISIT_HISTORY, "View history of page visit for this page."); }@Override public void createCommitteeRankingTopics(final MenuItem committeeMenuItem) { committeeMenuItem.addItem(OVERVIEW_TEXT, VaadinIcons.GROUP, COMMAND_OVERVIEW); final MenuItem listByTopic = committeeMenuItem.addItem(RANKING_LIST_BY_TOPIC_TEXT, VaadinIcons.GROUP, null); final MenuItem listItem = listByTopic.addItem(POLITICAL_WORK_SUMMARY_TEXT,VaadinIcons.GROUP, COMMAND_DATAGRID); listItem.setDescription(CURRENT_AND_PAST_MEMBER_AND_SUMMARY_OF_POLTICIAL_DAYS); final MenuItem chartByTopic = committeeMenuItem.addItem(CHART_BY_TOPIC_TEXT, VaadinIcons.GROUP, null); chartByTopic.addItem(CURRENT_COMMITTEES_CURRENT_MEMBERS_TEXT,VaadinIcons.GROUP, COMMAND_CURRENT_COMMITTEES_BY_HEADCOUNT); chartByTopic.addItem(CURRENT_PARTIES_ACTIVE_IN_COMMITTEES_CURRENT_ASSIGNMENTS,VaadinIcons.GROUP, COMMAND_COMMITTEES_BY_PARTY); chartByTopic.addItem(CURRENT_PARTIES_ACTIVE_IN_COMMITTEES_TOTAL_DAYS_SERVED_IN_COMMITTEES,VaadinIcons.GROUP, COMMAND_CURRENT_COMMITTEES_BY_PARTY_DAYS_SERVED); chartByTopic.addItem(ALL_COMMITTEES_TOTAL_MEMBERS,VaadinIcons.GROUP, COMMAND_ALL_COMMITTEES_BY_HEADCOUNT); committeeMenuItem.addItem(PAGE_VISIT_HISTORY_TEXT, VaadinIcons.GROUP, COMMAND_PAGEVISIT_HISTORY); }@Override public void createCommitteeeRankingMenuBar(final MenuBar menuBar) { initApplicationMenuBar(menuBar); applicationMenuItemFactory.addRankingMenu(menuBar); createCommitteeRankingTopics(menuBar.addItem(COMMITTEE_RANKING_TEXT, null, null)); }@OneToMany(targetEntity = DocumentAttachment.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "DOCUMENT_ATTACHMENT_LIST_DOC_0") public List getDocumentAttachmentList() { return this.documentAttachmentList; }private static SeriesDefaults createDonoutSeriesDefault() { return new SeriesDefaults().setRenderer(SeriesRenderers.DONUT) .setRendererOptions(new DonutRenderer().setSliceMargin(SLICE_MARGIN).setStartAngle(START_ANGLE).setShowDataLabels(true) .setDataLabels(DataLabels.VALUE)); }private static SeriesDefaults createSeriesDefaultPieChart() { return new SeriesDefaults().setRenderer(SeriesRenderers.PIE) .setRendererOptions(new PieRenderer().setShowDataLabels(true)).setShadow(true); }private static Highlighter createHighLighterNorth() { return new Highlighter().setShow(true).setShowTooltip(true).setTooltipAlwaysVisible(true) .setKeepTooltipInsideChart(true).setTooltipLocation(TooltipLocations.NORTH) .setTooltipAxes(TooltipAxes.XY_BAR).setShowMarker(true).setBringSeriesToFront(true); }private static Highlighter createHighLighter() { return new Highlighter().setShow(true).setShowTooltip(true).setTooltipAlwaysVisible(true) .setKeepTooltipInsideChart(true); }private static Legend setLegendStyling(final Legend legend) { legend.setBackground(BACKGROUND_COLOR).setFontFamily(FONT_FAMILY).setTextColor(TEXT_COLOR).setFontSize(LEGEND_FONT_SIZE); return legend; }private static Legend createLegendOutsideOneColumn() { return setLegendStyling(new Legend().setShow(true) .setRendererOptions( new EnhancedLegendRenderer().setSeriesToggle(SeriesToggles.NORMAL).setSeriesToggleReplot(true).setNumberColumns(ONE_COLUMN_NUMBER_OF_COLUMNS).setNumberRows(ONE_COLUMN_NUMBER_OF_ROWS)) .setPlacement(LegendPlacements.OUTSIDE_GRID)); }private static Legend createdLegendEnhancedInsideWest() { return setLegendStyling( new Legend().setShow(true).setPlacement(LegendPlacements.INSIDE_GRID).setLocation(LegendLocations.WEST) .setRenderer(LegendRenderers.ENHANCED).setRendererOptions(new EnhancedLegendRenderer() .setSeriesToggle(SeriesToggles.NORMAL).setSeriesToggleReplot(true).setNumberColumns(LEGEND_COLUMNS).setNumberRows(LEGEND_ROWS))); }private static Legend createdLegendEnhancedInsideNorthWest() { return setLegendStyling(new Legend().setShow(true) .setRendererOptions( new EnhancedLegendRenderer().setSeriesToggle(SeriesToggles.NORMAL).setSeriesToggleReplot(true).setNumberColumns(LEGEND_COLUMNS).setNumberRows(LEGEND_ROWS)) .setPlacement(LegendPlacements.INSIDE_GRID).setLocation(LegendLocations.NORTH_WEST)); }private static Grid createDefaultGrid() { final Grid grid = new Grid(); grid.setBackground(BACKGROUND_COLOR); grid.setGridLineColor(GRIDLINE_COLOR); grid.setBorderColor(BORDER_COLOR); return grid; }private static Axes createAxesXYDateFloat() { return new Axes() .addAxis(new XYaxis().setRenderer(AxisRenderers.DATE) .setTickOptions(new AxisTickRenderer().setFormatString(YEAR_MONTH_DAY_FORMAT).setFontFamily(FONT_FAMILY).setTextColor(TEXT_COLOR).setFontSize(FONT_SIZE)) .setNumberTicks(NUMBER_TICKS_DATE)) .addAxis(new XYaxis(XYaxes.Y).setRenderer(AxisRenderers.LINEAR).setTickOptions(new AxisTickRenderer().setFormatString(FLOAT_FORMAT).setFontFamily(FONT_FAMILY).setTextColor(TEXT_COLOR).setFontSize(FONT_SIZE)).setNumberTicks(NUMBER_TICKS)); }@OneToMany(targetEntity = DocumentDetailData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "DOCUMENT_DETAIL_LIST_DOCUMEN_0") public List getDocumentDetailList() { return this.documentDetailList; }@Id @Column(name = "HJID") @GeneratedValue(strategy = GenerationType.AUTO) public Long getHjid() { return hjid; }@ManyToOne(targetEntity = Topics.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "TOPICS_INDICATOR_ELEMENT_HJID") public Topics getTopics() { return topics; }@Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "SOURCE_VALUE")), @AttributeOverride(name = "id", column = @Column(name = "SOURCE_ID")) }) public Source getSource() { return source; }private static Map createMapFromList(final List all) { final Map map = new ConcurrentHashMap<>(); for (final String documentElement : all) { if (documentElement != null) { map.put(documentElement, documentElement); } } return map; }private void writeCollectionElement(Object o) throws IOException { if (o == null) { out.write("null"); } else if (o instanceof Boolean || o instanceof Double) { writePrimitive(o, false); } else if (o instanceof Long) { writePrimitive(o, writeLongsAsStrings); } else if (o instanceof String) { // Never do an @ref to a String (they are treated as logical primitives and intern'ed on read) writeJsonUtf8String((String) o, out); } else if (neverShowType && MetaUtils.isPrimitive(o.getClass())) { // If neverShowType, then force primitives (and primitive wrappers) // to be output with toString() - prevents {"value":6} for example writePrimitive(o, false); } else { writeImpl(o, true); } }public static boolean ensureJsonPrimitiveKeys(Map map) { for (Object o : map.keySet()) { if (!(o instanceof String)) { return false; } } return true; }protected void traceFields(final Deque stack, final Object obj, final Map> fieldSpecifiers) { // If caller has special Field specifier for a given class // then use it, otherwise use reflection. Collection fields = getFieldsUsingSpecifier(obj.getClass(), fieldSpecifiers); Collection fieldsBySpec = fields; if (fields == null) { // Trace fields using reflection fields = MetaUtils.getDeepDeclaredFields(obj.getClass()).values(); } for (final Field field : fields) { if ((field.getModifiers() & Modifier.TRANSIENT) != 0) { if (fieldsBySpec == null || !fieldsBySpec.contains(field)) { // Skip tracing transient fields EXCEPT when the field is listed explicitly by using the fieldSpecifiers Map. // In that case, the field must be traced, even though it is transient. continue; } } try { final Object o = field.get(obj); if (o != null && !MetaUtils.isLogicalPrimitive(o.getClass())) { // Trace through objects that can reference other objects stack.addFirst(o); } } catch (Exception ignored) { } } }protected void traceReferences(Object root) { if (root == null) { return; } Map> fieldSpecifiers = (Map) args.get(FIELD_SPECIFIERS); final Deque stack = new ArrayDeque(); stack.addFirst(root); final Map visited = objVisited; final Map referenced = objsReferenced; while (!stack.isEmpty()) { final Object obj = stack.removeFirst(); if (!MetaUtils.isLogicalPrimitive(obj.getClass())) { Long id = visited.get(obj); if (id != null) { // Only write an object once. if (id == ZERO) { // 2nd time this object has been seen, so give it a unique ID and mark it referenced id = identity++; visited.put(obj, id); referenced.put(obj, id); } continue; } else { // Initially, mark an object with 0 as the ID, in case it is never referenced, // we don't waste the memory to store a Long instance that is never used. visited.put(obj, ZERO); } } final Class clazz = obj.getClass(); if (clazz.isArray()) { if (!MetaUtils.isLogicalPrimitive(clazz.getComponentType())) { // Speed up: do not traceReferences of primitives, they cannot reference anything final int len = Array.getLength(obj); for (int i = 0; i < len; i++) { final Object o = Array.get(obj, i); if (o != null) { // Slight perf gain (null is legal) stack.addFirst(o); } } } } else if (Map.class.isAssignableFrom(clazz)) { // Speed up - logically walk maps, as opposed to following their internal structure. Map map = (Map) obj; for (final Object item : map.entrySet()) { final Map.Entry entry = (Map.Entry) item; if (entry.getValue() != null) { stack.addFirst(entry.getValue()); } if (entry.getKey() != null) { stack.addFirst(entry.getKey()); } } } else if (Collection.class.isAssignableFrom(clazz)) { for (final Object item : (Collection)obj) { if (item != null) { stack.addFirst(item); } } } else { // Speed up: do not traceReferences of primitives, they cannot reference anything if (!MetaUtils.isLogicalPrimitive(obj.getClass())) { traceFields(stack, obj, fieldSpecifiers); } } } }public void write(Object obj) { traceReferences(obj); objVisited.clear(); try { writeImpl(obj, true); } catch (Exception e) { throw new JsonIoException("Error writing object to JSON:", e); } flush(); objVisited.clear(); objsReferenced.clear(); }private JsonClassWriterBase forceGetCustomWriter(Class c) { JsonClassWriterBase closestWriter = nullWriter; int minDistance = Integer.MAX_VALUE; for (Map.Entry entry : writers.entrySet()) { Class clz = entry.getKey(); if (clz == c) { return entry.getValue(); } int distance = MetaUtils.getDistance(clz, c); if (distance < minDistance) { minDistance = distance; closestWriter = entry.getValue(); } } return closestWriter; }protected boolean writeCustom(Class arrayComponentClass, Object o, boolean showType, Writer output) throws IOException { if (neverShowType) { showType = false; } JsonClassWriterBase closestWriter = getCustomWriter(arrayComponentClass); if (closestWriter == null) { return false; } if (writeOptionalReference(o)) { return true; } boolean referenced = objsReferenced.containsKey(o); if (closestWriter instanceof JsonClassWriter) { JsonClassWriter writer = (JsonClassWriter) closestWriter; if (writer.hasPrimitiveForm()) { if ((!referenced && !showType) || closestWriter instanceof Writers.JsonStringWriter) { if (writer instanceof Writers.DateWriter) { ((Writers.DateWriter)writer).writePrimitiveForm(o, output, args); } else { writer.writePrimitiveForm(o, output); } return true; } } } output.write('{'); tabIn(); if (referenced) { writeId(getId(o)); if (showType) { output.write(','); newLine(); } } if (showType) { writeType(o, output); } if (referenced || showType) { output.write(','); newLine(); } if (closestWriter instanceof JsonClassWriterEx) { ((JsonClassWriterEx)closestWriter).write(o, showType || referenced, output, args); } else { ((JsonClassWriter)closestWriter).write(o, showType || referenced, output); } tabOut(); output.write('}'); return true; }public boolean writeArrayElementIfMatching(Class arrayComponentClass, Object o, boolean showType, Writer output) { if (!o.getClass().isAssignableFrom(arrayComponentClass) || notCustom.contains(o.getClass())) { return false; } try { return writeCustom(arrayComponentClass, o, showType, output); } catch (IOException e) { throw new JsonIoException("Unable to write custom formatted object as array element:", e); } }private void tab(Writer output, int delta) throws IOException { if (!isPrettyPrint) { return; } output.write(NEW_LINE); depth += delta; for (int i=0; i < depth; i++) { output.write(" "); } }public static String formatJson(String json, Map readingArgs, Map writingArgs) { Map args = new HashMap(); if (readingArgs != null) { args.putAll(readingArgs); } args.put(JsonReader.USE_MAPS, true); Object obj = JsonReader.jsonToJava(json, args); args.clear(); if (writingArgs != null) { args.putAll(writingArgs); } args.put(PRETTY_PRINT, true); return objectToJson(obj, args); }public static String objectToJson(Object item, Map optionalArgs) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); JsonWriter writer = new JsonWriter(stream, optionalArgs); writer.write(item); writer.close(); return new String(stream.toByteArray(), "UTF-8"); } catch (Exception e) { throw new JsonIoException("Unable to convert object to JSON", e); } }static String removeLeadingAndTrailingQuotes(String s) { Matcher m = extraQuotes.matcher(s); if (m.find()) { s = m.group(2); } return s; }public static Field getField(Class c, String field) { return getDeepDeclaredFields(c).get(field); }private String readString() throws IOException { final StringBuilder str = strBuf; final StringBuilder hex = hexBuf; str.setLength(0); int state = STRING_START; final FastPushbackReader in = input; while (true) { final int c = in.read(); if (c == -1) { error("EOF reached while reading JSON string"); } if (state == STRING_START) { if (c == '"') { break; } else if (c == '\\') { state = STRING_SLASH; } else { str.appendCodePoint(c); } } else if (state == STRING_SLASH) { switch(c) { case '\\': str.appendCodePoint('\\'); break; case '/': str.appendCodePoint('/'); break; case '"': str.appendCodePoint('"'); break; case '\'': str.appendCodePoint('\''); break; case 'b': str.appendCodePoint('\b'); break; case 'f': str.appendCodePoint('\f'); break; case 'n': str.appendCodePoint('\n'); break; case 'r': str.appendCodePoint('\r'); break; case 't': str.appendCodePoint('\t'); break; case 'u': hex.setLength(0); state = HEX_DIGITS; break; default: error("Invalid character escape sequence specified: " + c); } if (c != 'u') { state = STRING_START; } } else { if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) { hex.appendCodePoint((char) c); if (hex.length() == 4) { int value = Integer.parseInt(hex.toString(), 16); str.appendCodePoint(value); state = STRING_START; } } else { error("Expected hexadecimal digits"); } } } final String s = str.toString(); final String translate = stringCache.get(s); return translate == null ? s : translate; }private Number readNumber(int c) throws IOException { final FastPushbackReader in = input; final StringBuilder number = numBuf; number.setLength(0); number.appendCodePoint(c); boolean isFloat = false; if (JsonReader.isLenient() && (c == '-' || c == 'N' || c == 'I') ) { // Handle negativity. final boolean isNeg = (c == '-'); if (isNeg) { // Advance to next character. c = input.read(); } // Case "-Infinity", "Infinity" or "NaN". if (c == 'I') { // [Out of RFC 4627] accept NaN/Infinity values readToken("infinity"); return (isNeg) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } else if ('N' == c) { // [Out of RFC 4627] accept NaN/Infinity values readToken("nan"); return Double.NaN; } else { // Case this is a number but not "-Infinity", like "-2". We let the normal code process. input.unread('-'); } } while (true) { c = in.read(); if ((c >= '0' && c <= '9') || c == '-' || c == '+') { number.appendCodePoint(c); } else if (c == '.' || c == 'e' || c == 'E') { number.appendCodePoint(c); isFloat = true; } else if (c == -1) { break; } else { in.unread(c); break; } } try { if (isFloat) { // Floating point number needed return Double.parseDouble(number.toString()); } else { return Long.parseLong(number.toString()); } } catch (Exception e) { return (Number) error("Invalid number: " + number, e); } }private Object readArray(JsonObject object) throws IOException { final List array = new ArrayList(); while (true) { final Object o = readValue(object); if (o != EMPTY_ARRAY) { array.add(o); } final int c = skipWhitespaceRead(); if (c == ']') { break; } else if (c != ',') { error("Expected ',' or ']' inside array"); } } return array.toArray(); }public static Class getRawType(final Type t) { if (t instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) t; if (pType.getRawType() instanceof Class) { return (Class) pType.getRawType(); } } return null; }private void storeMissingField(Object target, String missingField, Object value) { missingFields.add(new Missingfields(target, missingField, value)); }public void traverseFields(final Deque> stack, final JsonObject jsonObj) { final Object javaMate = jsonObj.target; final Iterator> i = jsonObj.entrySet().iterator(); final Class cls = javaMate.getClass(); while (i.hasNext()) { Map.Entry e = i.next(); String key = e.getKey(); final Field field = MetaUtils.getField(cls, key); Object rhs = e.getValue(); if (field != null) { assignField(stack, jsonObj, field, rhs); } else if (missingFieldHandler != null) { handleMissingField(stack, jsonObj, rhs, key); }//else no handler so ignor. } }public Object jsonObjectsToJava(JsonObject root) { getArgs().put(USE_MAPS, false); return convertParsedMapsToJava(root); }public static Object jsonToJava(String json, Map optionalArgs) { if (optionalArgs == null) { optionalArgs = new HashMap(); optionalArgs.put(USE_MAPS, false); } if (!optionalArgs.containsKey(USE_MAPS)) { optionalArgs.put(USE_MAPS, false); } JsonReader jr = new JsonReader(json, optionalArgs); Object obj = jr.readObject(); jr.close(); return obj; }public void traverseFields(final Deque> stack, final JsonObject jsonObj) { final Object target = jsonObj.target; for (Map.Entry e : jsonObj.entrySet()) { final String fieldName = e.getKey(); final Field field = (target != null) ? MetaUtils.getField(target.getClass(), fieldName) : null; final Object rhs = e.getValue(); if (rhs == null) { jsonObj.put(fieldName, null); } else if (rhs == JsonParser.EMPTY_OBJECT) { jsonObj.put(fieldName, new JsonObject()); } else if (rhs.getClass().isArray()) { // RHS is an array // Trace the contents of the array (so references inside the array and into the array work) JsonObject jsonArray = new JsonObject(); jsonArray.put("@items", rhs); stack.addFirst(jsonArray); // Assign the array directly to the Map key (field name) jsonObj.put(fieldName, rhs); } else if (rhs instanceof JsonObject) { JsonObject jObj = (JsonObject) rhs; if (field != null && MetaUtils.isLogicalPrimitive(field.getType())) { jObj.put("value", MetaUtils.convert(field.getType(), jObj.get("value"))); continue; } Long refId = jObj.getReferenceId(); if (refId != null) { // Correct field references JsonObject refObject = getReferencedObj(refId); jsonObj.put(fieldName, refObject); // Update Map-of-Maps reference } else { stack.addFirst(jObj); } } else if (field != null) { // The code below is 'upgrading' the RHS values in the passed in JsonObject Map // by using the @type class name (when specified and exists), to coerce the vanilla // JSON values into the proper types defined by the class listed in @type. This is // a cool feature of json-io, that even when reading a map-of-maps JSON file, it will // improve the final types of values in the maps RHS, to be of the field type that // was optionally specified in @type. final Class fieldType = field.getType(); if (MetaUtils.isPrimitive(fieldType) || BigDecimal.class.equals(fieldType) || BigInteger.class.equals(fieldType) || Date.class.equals(fieldType)) { jsonObj.put(fieldName, MetaUtils.convert(fieldType, rhs)); } else if (rhs instanceof String) { if (fieldType != String.class && fieldType != StringBuilder.class && fieldType != StringBuffer.class) { if ("".equals(((String)rhs).trim())) { // Allow "" to null out a non-String field on the inbound JSON jsonObj.put(fieldName, null); } } } } } jsonObj.target = null; // don't waste space (used for typed return, not for Map return) }protected void patchUnresolvedReferences() { Iterator i = unresolvedRefs.iterator(); while (i.hasNext()) { UnresolvedReference ref = (UnresolvedReference) i.next(); Object objToFix = ref.referencingObj.target; JsonObject objReferenced = reader.getObjectsRead().get(ref.refId); if (ref.index >= 0) { // Fix []'s and Collections containing a forward reference. if (objToFix instanceof List) { // Patch up Indexable Collections List list = (List) objToFix; list.set(ref.index, objReferenced.target); } else if (objToFix instanceof Collection) { // Add element (since it was not indexable, add it to collection) Collection col = (Collection) objToFix; col.add(objReferenced.target); } else { Array.set(objToFix, ref.index, objReferenced.target); // patch array element here } } else { // Fix field forward reference Field field = MetaUtils.getField(objToFix.getClass(), ref.field); if (field != null) { try { field.set(objToFix, objReferenced.target); // patch field here } catch (Exception e) { throw new JsonIoException("Error setting field while resolving references '" + field.getName() + "', @ref = " + ref.refId, e); } } } i.remove(); } }private Object getEnum(Class c, JsonObject jsonObj) { try { return Enum.valueOf(c, (String) jsonObj.get("name")); } catch (Exception e) { // In case the enum class has it's own 'name' member variable (shadowing the 'name' variable on Enum) return Enum.valueOf(c, (String) jsonObj.get("java.lang.Enum.name")); } }private void handleMissingFields() { MissingFieldHandler missingFieldHandler = reader.getMissingFieldHandler(); if (missingFieldHandler != null) { for (Missingfields mf : missingFields) { missingFieldHandler.fieldMissing(mf.target, mf.fieldName, mf.value); } }//else no handler so ignore. }@SuppressWarnings("deprecation") public static boolean install(Context context, String destDir, String filename) { String binaryDir = "armeabi"; String abi = Build.CPU_ABI; if (abi.startsWith("armeabi-v7a")) { binaryDir = "armeabi-v7a"; } else if (abi.startsWith("x86")) { binaryDir = "x86"; } /* for different platform */ String assetfilename = binaryDir + File.separator + filename; try { File f = new File(context.getDir(destDir, Context.MODE_PRIVATE), filename); if (f.exists()) { Log.d(TAG, "binary has existed"); return false; } copyAssets(context, assetfilename, f, "0755"); return true; } catch (Exception e) { Log.e(TAG, "installBinary failed: " + e.getMessage()); return false; } }public static void copyAssets(Context context, String assetsFilename, File file, String mode) throws IOException, InterruptedException { AssetManager manager = context.getAssets(); final InputStream is = manager.open(assetsFilename); copyFile(file, is, mode); }private static void copyFile(File file, InputStream is, String mode) throws IOException, InterruptedException { final String abspath = file.getAbsolutePath(); final FileOutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); is.close(); Runtime.getRuntime().exec("chmod " + mode + " " + abspath).waitFor(); }public static void run(final Context context, final Class daemonServiceClazz, final int interval) { new Thread(new Runnable() { @Override public void run() { Command.install(context, BIN_DIR_NAME, DAEMON_BIN_NAME); start(context, daemonServiceClazz, interval); } }).start(); }protected String fetchDatabaseNameFromURL(String url) { URLLocation hostsLocation = fetchDatabaseNameIndexRange(url); return url.substring(hostsLocation.startIndex(), hostsLocation.endIndex()); }public static void registerConnectionParser(String urlPrefix, ConnectionURLParser parser) { if (null == urlPrefix || parser == null) { throw new IllegalArgumentException("urlPrefix and parser can not be null"); } parserRegister.put(urlPrefix.toLowerCase(), parser); }public static ConnectionInfo parser(String url) { if (null == url) { return ConnectionInfo.UNKNOWN_CONNECTION_INFO; } String lowerCaseUrl = url.toLowerCase(); ConnectionURLParser parser = findURLParser(lowerCaseUrl); if (parser == null) { return ConnectionInfo.UNKNOWN_CONNECTION_INFO; } try { return parser.parse(url); } catch (Exception e) { log.log(Level.WARNING, "error occurs when paring jdbc url"); } return ConnectionInfo.UNKNOWN_CONNECTION_INFO; }private int[] fetchDatabaseNameRangeIndexFromURLForH2MemMode(String url) { int fileLabelIndex = url.indexOf(MEMORY_MODE_FLAG); int parameterLabelIndex = url.indexOf(";", fileLabelIndex); if (parameterLabelIndex == -1) { parameterLabelIndex = url.length(); } if (fileLabelIndex != -1) { return new int[]{fileLabelIndex + MEMORY_MODE_FLAG.length() + 1, parameterLabelIndex}; } else { return null; } }private int[] fetchDatabaseNameRangeIndexFromURLForH2FileMode(String url) { int fileLabelIndex = url.indexOf(FILE_MODE_FLAG); int parameterLabelIndex = url.indexOf(";", fileLabelIndex); if (parameterLabelIndex == -1) { parameterLabelIndex = url.length(); } if (fileLabelIndex != -1) { return new int[]{fileLabelIndex + FILE_MODE_FLAG.length() + 1, parameterLabelIndex}; } else { return null; } }public void setMenuBackgroundColor(int colorResId) { backgroundColor = ContextCompat.getColor(getContext(), colorResId); paint.setColor(backgroundColor); invalidate(); }public void close() { updateDimensions(width, height); state = State.CLOSED; showIcons(false); animator[LEFT].setFloatValues(0, button[LEFT]); animator[RIGHT].setFloatValues(width, button[RIGHT]); animator[RADIUS].setFloatValues(0, button[RADIUS]); animator[TOP].setFloatValues(0, button[TOP]); animator[BOTTOM].setFloatValues(height, button[BOTTOM]); animatorSet.cancel(); animatorSet.start(); if (iconClosedDrawable instanceof Animatable) { ((Animatable) iconClosedDrawable).start(); } this.animate() .y(yPosition) .setDuration(animationDuration) .setInterpolator(DECELERATE_INTERPOLATOR) .start(); }public void open() { state = State.OPENED; showIcons(true); animator[LEFT].setFloatValues(button[LEFT], 0); animator[RIGHT].setFloatValues(button[RIGHT], width); animator[RADIUS].setFloatValues(button[RADIUS], 0); animator[TOP].setFloatValues(button[TOP], 0); animator[BOTTOM].setFloatValues(button[BOTTOM], height); animatorSet.cancel(); animatorSet.start(); if (iconOpenedDrawable instanceof Animatable) { ((Animatable) iconOpenedDrawable).start(); } ViewGroup parentView = (ViewGroup) TapBarMenu.this.getParent(); this.animate() .y(menuAnchor == MENU_ANCHOR_BOTTOM ? parentView.getBottom() - height : 0) .setDuration(animationDuration) .setInterpolator(DECELERATE_INTERPOLATOR) .start(); }public void parseNextRun() { if ((this.isLiteral) || (this.iterator.getNumberOfLiteralWords() == 0)) { // no choice, must load next runs this.iterator.discardFirstWords(this.iterator.size()); if (this.iterator.getRunningLength() > 0) { this.endrun += this.iterator .getRunningLength(); this.isLiteral = false; this.value = this.iterator.getRunningBit(); } else if (this.iterator.getNumberOfLiteralWords() > 0) { this.isLiteral = true; this.endrun += this.iterator .getNumberOfLiteralWords(); } else { this.dead = true; } } else { this.isLiteral = true; this.endrun += this.iterator.getNumberOfLiteralWords(); } }public IntIterator unsetIntIterator() { return new IntIterator() { @Override public boolean hasNext() { return this.i >= 0; } @Override public int next() { this.j = this.i; this.i = ImmutableBitSet.this.nextUnsetBit(this.i + 1); return this.j; } private int i = ImmutableBitSet.this.nextUnsetBit(0); private int j; }; }public boolean intersects(BitSet bs) { for (int k = 0; k < Math.min(this.data.limit(), bs.data.length); ++k) { if ((this.data.get(k) & bs.data[k]) != 0) return true; } return false; }public IntIterator intIterator() { return new IntIterator() { @Override public boolean hasNext() { return this.i >= 0; } @Override public int next() { this.j = this.i; this.i = ImmutableBitSet.this.nextSetBit(this.i + 1); return this.j; } private int i = ImmutableBitSet.this.nextSetBit(0); private int j; }; }public boolean empty() { int length = this.data.limit(); for(int k = 0; k < length; ++k) if (this.data.get(k) != 0) return false; return true; }public int cardinality() { int sum = 0; int length = this.data.limit(); for(int k = 0; k < length; ++k) sum += Long.bitCount(this.data.get(k)); return sum; }public BitSet asBitSet() { BitSet bs = new BitSet(this.size()); this.data.rewind(); this.data.get(bs.data, 0, bs.data.length); return bs; }public final void fillWithLiterals(final List container) { for (int k = this.litwlist.nextSetBit(0); k >= 0; k = this.litwlist .nextSetBit(k + 1)) { container.add(this.rw[k]); } }@Override public void addStreamOfLiteralWords(Buffer32 buffer, int start, int number) { for (int i = start; i < start + number; i++) { addLiteralWord(buffer.getWord(i)); } }public static EWAHCompressedBitmap32 xor(final EWAHCompressedBitmap32... bitmaps) { PriorityQueue pq = new PriorityQueue(bitmaps.length, new Comparator() { @Override public int compare(EWAHCompressedBitmap32 a, EWAHCompressedBitmap32 b) { return a.sizeInBytes() - b.sizeInBytes(); } } ); Collections.addAll(pq, bitmaps); if(pq.isEmpty()) return new EWAHCompressedBitmap32(); while (pq.size() > 1) { EWAHCompressedBitmap32 x1 = pq.poll(); EWAHCompressedBitmap32 x2 = pq.poll(); pq.add(x1.xor(x2)); } return pq.poll(); }private int newSizeInWords(int number) { int size = this.actualSizeInWords + number; if (size >= this.buffer.length) { if (size < 32768) size = size * 2; else if (size * 3 / 2 < size) // overflow size = Integer.MAX_VALUE; else size = size * 3 / 2; } return size; }private void resizeBuffer(int number) { int size = newSizeInWords(number); if (size >= this.buffer.length) { long oldBuffer[] = this.buffer; this.buffer = new long[size]; System.arraycopy(oldBuffer, 0, this.buffer, 0, oldBuffer.length); } }public T poll() { T ans = this.a[1]; this.a[1] = this.a[this.lastIndex--]; percolateDown(1); return ans; }public static void materialize(final IteratingRLW i, final BitmapStorage c) { while (true) { if (i.getRunningLength() > 0) { c.addStreamOfEmptyWords(i.getRunningBit(), i.getRunningLength()); } int il = i.getNumberOfLiteralWords(); for (int k = 0; k < il ; ++k) c.addWord(i.getLiteralWordAt(k)); if (!i.next()) break; } }@Override public void addStreamOfLiteralWords(Buffer buffer, int start, int number) { for(int x = start; x < start + number ; ++x) if(buffer.getWord(x)!=0) throw nonEmptyException; }public void handleNonCORS(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws IOException, ServletException { // Let request pass. filterChain.doFilter(request, response); }@NonNull public static Animator[] concatAnimators(@NonNull final Animator[] childAnimators, @NonNull final Animator[] animators, @NonNull final Animator alphaAnimator) { Animator[] allAnimators = new Animator[childAnimators.length + animators.length + 1]; int i; for (i = 0; i < childAnimators.length; ++i) { allAnimators[i] = childAnimators[i]; } for (Animator animator : animators) { allAnimators[i] = animator; ++i; } allAnimators[allAnimators.length - 1] = alphaAnimator; return allAnimators; }@SuppressLint("NewApi") private int calculateAnimationDelay(final int position) { int delay; int lastVisiblePosition = mListViewWrapper.getLastVisiblePosition(); int firstVisiblePosition = mListViewWrapper.getFirstVisiblePosition(); int numberOfItemsOnScreen = lastVisiblePosition - firstVisiblePosition; int numberOfAnimatedItems = position - 1 - mFirstAnimatedPosition; if (numberOfItemsOnScreen + 1 < numberOfAnimatedItems) { delay = mAnimationDelayMillis; if (mListViewWrapper.getListView() instanceof GridView && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { int numColumns = ((GridView) mListViewWrapper.getListView()).getNumColumns(); delay += mAnimationDelayMillis * (position % numColumns); } } else { int delaySinceStart = (position - mFirstAnimatedPosition) * mAnimationDelayMillis; delay = Math.max(0, (int) (-SystemClock.uptimeMillis() + mAnimationStartMillis + mInitialDelayMillis + delaySinceStart)); } return delay; }private void animateView(final int position, @NonNull final View view, @NonNull final Animator[] animators) { if (mAnimationStartMillis == -1) { mAnimationStartMillis = SystemClock.uptimeMillis(); } ViewHelper.setAlpha(view, 0); AnimatorSet set = new AnimatorSet(); set.playTogether(animators); set.setStartDelay(calculateAnimationDelay(position)); set.setDuration(mAnimationDurationMillis); set.start(); mAnimators.put(view.hashCode(), set); }void cancelExistingAnimation(@NonNull final View view) { int hashCode = view.hashCode(); Animator animator = mAnimators.get(hashCode); if (animator != null) { animator.end(); mAnimators.remove(hashCode); } }public void reset() { for (int i = 0; i < mAnimators.size(); i++) { mAnimators.get(mAnimators.keyAt(i)).cancel(); } mAnimators.clear(); mFirstAnimatedPosition = -1; mLastAnimatedPosition = -1; mAnimationStartMillis = -1; mShouldAnimate = true; }private void reset() { if (mVelocityTracker != null) { mVelocityTracker.recycle(); } mVelocityTracker = null; mDownX = 0; mDownY = 0; mCurrentView = null; mSwipingView = null; mCurrentPosition = AdapterView.INVALID_POSITION; mSwiping = false; mCanDismissCurrent = false; }private boolean isDismissable(final int position) { if (mListViewWrapper.getAdapter() == null) { return false; } if (mDismissableManager != null) { long downId = mListViewWrapper.getAdapter().getItemId(position); return mDismissableManager.isDismissable(downId, position); } return true; }@NonNull static Bitmap getBitmapFromView(@NonNull final View v) { Bitmap bitmap = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); v.draw(canvas); return bitmap; }@SuppressWarnings({"MethodMayBeStatic", "UnusedParameters"}) @NonNull protected Animator[] getAdditionalAnimators(@NonNull final View view, @NonNull final ViewGroup parent) { return new Animator[]{}; }@Nullable private View getContentParent(final int position) { View contentParent = null; View parentView = findViewForPosition(position); if (parentView != null) { Object tag = parentView.getTag(); if (tag instanceof ViewHolder) { contentParent = ((ViewHolder) tag).contentParent; } } return contentParent; }public void collapse(final int position) { long itemId = getItemId(position); if (!mExpandedIds.contains(itemId)) { return; } toggle(position); }public void expand(final int position) { long itemId = getItemId(position); if (mExpandedIds.contains(itemId)) { return; } toggle(position); }@Nullable public View getContentView(final int position) { View contentView = null; View parentView = findViewForPosition(position); if (parentView != null) { Object tag = parentView.getTag(); if (tag instanceof ViewHolder) { contentView = ((ViewHolder) tag).contentView; } } return contentView; }@Nullable public View getTitleView(final int position) { View titleView = null; View parentView = findViewForPosition(position); if (parentView != null) { Object tag = parentView.getTag(); if (tag instanceof ViewHolder) { titleView = ((ViewHolder) tag).titleView; } } return titleView; }@NonNull public Collection getActiveIndexes() { Collection result = new HashSet<>(); for (AtomicInteger i : mActiveIndexes) { result.add(i.get()); } return result; }public void removeActiveIndex(final int index) { boolean found = false; for (Iterator iterator = mActiveIndexes.iterator(); iterator.hasNext() && !found; ) { if (iterator.next().get() == index) { iterator.remove(); found = true; } } if (mActiveIndexes.isEmpty()) { insertPending(); } }private void switchViews(final View switchView, final long switchId, final float translationY) { assert mHoverDrawable != null; assert mAdapter != null; assert mMobileView != null; final int switchViewPosition = mWrapper.getPositionForView(switchView); int mobileViewPosition = mWrapper.getPositionForView(mMobileView); ((Swappable) mAdapter).swapItems(switchViewPosition - mWrapper.getHeaderViewsCount(), mobileViewPosition - mWrapper.getHeaderViewsCount()); ((BaseAdapter) mAdapter).notifyDataSetChanged(); mHoverDrawable.shift(switchView.getHeight()); mSwitchViewAnimator.animateSwitchView(switchId, translationY); }private int getPositionForId(final long itemId) { View v = getViewForId(itemId); if (v == null) { return AdapterView.INVALID_POSITION; } else { return mWrapper.getPositionForView(v); } }public boolean addAll(@NonNull final Collection collection) { boolean result = mItems.addAll(collection); notifyDataSetChanged(); return result; }public static void checkThatApplicationSecretIsSet( boolean isProd, String baseDirWithoutTrailingSlash, PropertiesConfiguration defaultConfiguration, Configuration compositeConfiguration) { String applicationSecret = compositeConfiguration.getString(NinjaConstant.applicationSecret); if (applicationSecret == null || applicationSecret.isEmpty()) { // If in production we stop the startup process. It simply does not make // sense to run in production if the secret is not set. if (isProd) { String errorMessage = "Fatal error. Key application.secret not set. Please fix that."; logger.error(errorMessage); throw new RuntimeException(errorMessage); } logger.info("Key application.secret not set. Generating new one and setting in conf/application.conf."); // generate new secret String secret = SecretGenerator.generateSecret(); // set in overall composite configuration => this enables this instance to // start immediately. Otherwise we would have another build cycle. compositeConfiguration.setProperty(NinjaConstant.applicationSecret, secret); // defaultConfiguration is: conf/application.conf (not prefixed) defaultConfiguration.setProperty(NinjaConstant.applicationSecret, secret); try { // STEP 1: Save in source directories: // save to compiled version => in src/main/target/ String pathToApplicationConfInSrcDir = baseDirWithoutTrailingSlash + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator + NinjaProperties.CONF_FILE_LOCATION_BY_CONVENTION; Files.createParentDirs(new File(pathToApplicationConfInSrcDir)); // save to source defaultConfiguration.save(pathToApplicationConfInSrcDir); // STEP 2: Save in classes dir (target/classes or similar). // save in target directory (compiled version aka war aka classes dir) defaultConfiguration.save(); } catch (ConfigurationException e) { logger.error("Error while saving new secret to application.conf.", e); } catch (IOException e) { logger.error("Error while saving new secret to application.conf.", e); } } }public Result doNotCacheContent() { addHeader(CACHE_CONTROL, CACHE_CONTROL_DEFAULT_NOCACHE_VALUE); addHeader(DATE, DateUtil.formatForHttpHeader(System.currentTimeMillis())); addHeader(EXPIRES, DateUtil.formatForHttpHeader(0L)); return this; }public Cookie getCookie(String cookieName) { for (Cookie cookie : getCookies()) { if (cookie.getName().equals(cookieName)) { return cookie; } } return null; }public Result renderRaw(final byte [] bytes) { Renderable renderable = new Renderable() { @Override public void render(Context context, Result result) { if (result.getContentType() == null) { result.contentType(Result.APPLICATION_OCTET_STREAM); } ResponseStreams responseStreams = context .finalizeHeaders(result); try (OutputStream outputStream = responseStreams.getOutputStream()) { outputStream.write(bytes); } catch (IOException ioException) { throw new InternalServerErrorException(ioException); } } }; render(renderable); return this; }@Deprecated public Result renderRaw(final String string) { Renderable renderable = new Renderable() { @Override public void render(Context context, Result result) { if (result.getContentType() == null) { result.contentType(Result.TEXT_PLAIN); } ResponseStreams resultJsonCustom = context .finalizeHeaders(result); try (Writer writer = resultJsonCustom.getWriter()) { writer.write(string); } catch (IOException ioException) { logger.error( "Error rendering raw String via renderRaw(...)", ioException); } } }; render(renderable); return this; }public Result render(String key, Object value) { render(new AbstractMap.SimpleEntry(key, value)); return this; }void checkSerializable(Object value) { if (value != null && !(value instanceof Serializable)) { throw new CacheException( "Cannot cache a non-serializable value of type " + value.getClass().getName(), new NotSerializableException(value.getClass().getName())); } }@SuppressWarnings("unchecked") public T get(String key, Class clazz) { return (T) cache.get(key); }public void add(String key, Object value, String expiration) { checkSerializable(value); cache.add(key, value, TimeUtil.parseDuration(expiration)); }static public String getSourceCodeRelativePathForStackTraceElement(StackTraceElement ste) { String packageName = ste.getClassName(); // e.g. com.fizzed.test.Application$1 for an internal class int pos = packageName.lastIndexOf('.'); if (pos > 0) { packageName = packageName.substring(0, pos); return packageName.replace(".", File.separator) + File.separator + ste.getFileName(); } else { // must be in default package return ste.getFileName(); } }public static boolean doesClassExist(String nameWithPackage, Object instanceToGetClassloaderFrom) { boolean exists = false; try { Class.forName(nameWithPackage, false, instanceToGetClassloaderFrom.getClass().getClassLoader()); exists = true; } catch (ClassNotFoundException e) { exists = false; } return exists; }public static String getRealClassNameLowerCamelCase(Object object) { return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, object.getClass().getSimpleName()); }public static ControllerMethodInvoker build( Method functionalMethod, Method implementationMethod, Injector injector, NinjaProperties ninjaProperties) { // get both the parameters... final Type[] genericParameterTypes = implementationMethod.getGenericParameterTypes(); final MethodParameter[] methodParameters = MethodParameter.convertIntoMethodParameters(genericParameterTypes); // ... and all annotations for the parameters final Annotation[][] paramAnnotations = implementationMethod .getParameterAnnotations(); ArgumentExtractor[] argumentExtractors = new ArgumentExtractor[methodParameters.length]; // now we skip through the parameters and process the annotations for (int i = 0; i < methodParameters.length; i++) { try { argumentExtractors[i] = getArgumentExtractor(methodParameters[i], paramAnnotations[i], injector); } catch (RoutingException e) { throw new RoutingException("Error building argument extractor for parameter " + i + " in method " + implementationMethod.getDeclaringClass().getName() + "." + implementationMethod.getName() + "()", e); } } // Replace a null extractor with a bodyAs extractor, but make sure there's only one int bodyAsFound = -1; for (int i = 0; i < argumentExtractors.length; i++) { if (argumentExtractors[i] == null) { if (bodyAsFound > -1) { throw new RoutingException("Only one parameter may be deserialised as the body " + implementationMethod.getDeclaringClass().getName() + "." + implementationMethod.getName() + "()\n" + "Extracted parameter is type: " + methodParameters[bodyAsFound].parameterClass.getName() + "\n" + "Extra parmeter is type: " + methodParameters[i].parameterClass.getName()); } else { argumentExtractors[i] = new ArgumentExtractors.BodyAsExtractor(methodParameters[i].parameterClass); bodyAsFound = i; } } } // Now that every parameter has an argument extractor we can run validation on the annotated // parameters for (int i = 0; i < argumentExtractors.length; i++) { argumentExtractors[i] = validateArgumentWithExtractor( methodParameters[i], paramAnnotations[i], injector, argumentExtractors[i]); } boolean useStrictArgumentExtractors = determineWhetherToUseStrictArgumentExtractorMode(ninjaProperties); return new ControllerMethodInvoker(functionalMethod, argumentExtractors, useStrictArgumentExtractors); }private String getHttpMethod(Method method) { for (Annotation annotation : method.getAnnotations()) { Class annotationClass = annotation .annotationType(); if (annotationClass.isAnnotationPresent(HttpMethod.class)) { HttpMethod httpMethod = annotationClass .getAnnotation(HttpMethod.class); return httpMethod.value(); } } // default to GET logger.info(String .format("%s.%s does not specify an HTTP method annotation! Defaulting to GET.", method.getClass().getName(), method.getName())); return HttpMethod.GET; }private boolean allowMethod(Method method) { // NinjaProperties-based route exclusions/inclusions if (method.isAnnotationPresent(Requires.class)) { String key = method.getAnnotation(Requires.class).value(); String value = ninjaProperties.get(key); if (value == null) { return false; } } // NinjaMode-based route exclusions/inclusions Set modes = Sets.newTreeSet(); for (Annotation annotation : method.getAnnotations()) { Class annotationClass = annotation .annotationType(); if (annotationClass.isAnnotationPresent(RuntimeMode.class)) { RuntimeMode mode = annotationClass .getAnnotation(RuntimeMode.class); modes.add(mode.value()); } } return modes.isEmpty() || modes.contains(runtimeMode); }private void configureReflections() { Optional basePackage = Optional.ofNullable(ninjaProperties.get(NinjaConstant.APPLICATION_MODULES_BASE_PACKAGE)); if (basePackage.isPresent()) { reflections = new Reflections( basePackage.get() + "." + NinjaConstant.CONTROLLERS_DIR, new MethodAnnotationsScanner()); } else { reflections = new Reflections( NinjaConstant.CONTROLLERS_DIR, new MethodAnnotationsScanner()); } }@SuppressWarnings("unchecked") private Set findControllerMethods() { Set methods = Sets.newLinkedHashSet(); methods.addAll(reflections.getMethodsAnnotatedWith(Path.class)); boolean enableCustomHttpMethods = ninjaProperties.getBooleanWithDefault(NINJA_CUSTOM_HTTP_METHODS, false); if (enableCustomHttpMethods) { Reflections annotationReflections = new Reflections("", new TypeAnnotationsScanner(), new SubTypesScanner()); for (Class httpMethod : annotationReflections.getTypesAnnotatedWith(HttpMethod.class)) { if (httpMethod.isAnnotation()) { methods.addAll(reflections.getMethodsAnnotatedWith((Class) httpMethod)); } } } else { // Only look for standard HTTP methods annotations Reflections annotationReflections = new Reflections("ninja.jaxy", new TypeAnnotationsScanner(), new SubTypesScanner()); for (Class httpMethod : annotationReflections.getTypesAnnotatedWith(HttpMethod.class)) { if (httpMethod.isAnnotation()) { methods.addAll(reflections.getMethodsAnnotatedWith((Class) httpMethod)); } } } return methods; }private void sortMethods() { List methodList = new ArrayList<>(methods); Collections.sort(methodList, new Comparator() { @Override public int compare(Method m1, Method m2) { int o1 = Integer.MAX_VALUE; if (m1.isAnnotationPresent(Order.class)) { Order order = m1.getAnnotation(Order.class); o1 = order.value(); } int o2 = Integer.MAX_VALUE; if (m2.isAnnotationPresent(Order.class)) { Order order = m2.getAnnotation(Order.class); o2 = order.value(); } if (o1 == o2) { // same or unsorted, compare controller+method String s1 = m1.getDeclaringClass().getName() + "." + m1.getName(); String s2 = m2.getDeclaringClass().getName() + "." + m2.getName(); return s1.compareTo(s2); } if (o1 < o2) { return -1; } else { return 1; } } }); methods = new LinkedHashSet<>(methodList); }private void processFoundMethods() { for (Method method : findControllerMethods()) { if (allowMethod(method)) { // add the method to our todo list methods.add(method); // generate the paths for the controller class final Class controllerClass = method.getDeclaringClass(); if (!controllers.containsKey(controllerClass)) { Set paths = collectPaths(controllerClass); controllers.put(controllerClass, paths); } } } }@Override public void init(Router router) { this.router = router; configureReflections(); controllers = Maps.newHashMap(); methods = Sets.newHashSet(); processFoundMethods(); sortMethods(); registerMethods(); }protected String createServerUrl(String scheme, String host, Integer port) { StringBuilder sb = new StringBuilder(); sb.append(scheme); sb.append("://"); sb.append((host != null ? host : "localhost")); if (("http".equals(scheme) && port != 80) || ("https".equals(scheme) && port != 443)) { sb.append(":"); sb.append(port); } return sb.toString(); }@Override final public void run() { // name current thread for improved logging/debugging Thread.currentThread().setName(this.name); try { this.configure(); } catch (Exception e) { logger.error("Unable to configure {}", name, e); System.exit(1); } try { this.start(); } catch (Exception e) { logger.error("Unable to start {}", name, e); System.exit(1); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { shutdown(); } }); try { // do not simply exit main() -- join something (likely server) join(); } catch (Exception e) { logger.warn("Interrupted (most likely JVM is shutting down and this is safe to ignore)"); } }public Route buildRoute(Injector injector) { if (functionalMethod == null) { log.error("Error in route configuration for {}", uri); throw new IllegalStateException("Route missing a controller method"); } // Calculate filters LinkedList> allFilters = new LinkedList<>(); allFilters.addAll(calculateGlobalFilters(this.globalFiltersOptional, injector)); allFilters.addAll(this.localFilters); allFilters.addAll(calculateFiltersForClass(functionalMethod.getDeclaringClass())); FilterWith filterWith = functionalMethod.getAnnotation(FilterWith.class); if (filterWith != null) { allFilters.addAll(Arrays.asList(filterWith.value())); } FilterChain filterChain = buildFilterChain(injector, allFilters); return new Route(httpMethod, uri, functionalMethod, filterChain); }public boolean isValidMimeType(String mimeType) { if (mimeType == null) { return false; } else if (mimeType.indexOf(";") != -1) { return mimetypes.contains(mimeType.split(";")[0]); } else { return mimetypes.contains(mimeType); } }public static NinjaMode determineModeFromSystemPropertiesOrProdIfNotSet() { Optional ninjaModeOptional = determineModeFromSystemProperties(); NinjaMode ninjaMode; if (!ninjaModeOptional.isPresent()) { ninjaMode = NinjaMode.prod; } else { ninjaMode = ninjaModeOptional.get(); } logger.info("Ninja is running in mode {}", ninjaMode.toString()); return ninjaMode; }private void register(Path path) throws IOException { ////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //// USUALLY THIS IS THE DEFAULT WAY TO REGISTER THE EVENTS: ////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WatchKey watchKey = path.register( // watchService, // ENTRY_CREATE, // ENTRY_DELETE, // ENTRY_MODIFY); ////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //// BUT THIS IS DAMN SLOW (at least on a Mac) //// THEREFORE WE USE EVENTS FROM COM.SUN PACKAGES THAT ARE WAY FASTER //// THIS MIGHT BREAK COMPATIBILITY WITH OTHER JDKs //// MORE: http://stackoverflow.com/questions/9588737/is-java-7-watchservice-slow-for-anyone-else ////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! WatchKey watchKey = path.register( watchService, new WatchEvent.Kind[]{ StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE }, SensitivityWatchEventModifier.HIGH); mapOfWatchKeysToPaths.put(watchKey, path); }private final String readNinjaVersion() { // location of the properties file String LOCATION_OF_NINJA_BUILTIN_PROPERTIES = "ninja/ninja-builtin.properties"; // and the key inside the properties file. String NINJA_VERSION_PROPERTY_KEY = "ninja.version"; String ninjaVersion; try (InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(LOCATION_OF_NINJA_BUILTIN_PROPERTIES)){ Properties prop = new Properties(); prop.load(stream); ninjaVersion = prop.getProperty(NINJA_VERSION_PROPERTY_KEY); } catch (Exception e) { //this should not happen. Never. throw new RuntimeErrorException(new Error("Something is wrong with your build. Cannot find resource " + LOCATION_OF_NINJA_BUILTIN_PROPERTIES)); } return ninjaVersion; }public String decrypt(String data) { Objects.requireNonNull(data, "Data to be decrypted"); if (!secretKeySpec.isPresent()) { return data; } // convert base64 encoded string to bytes byte[] decoded = Base64.decodeBase64(data); try { // decrypt bytes Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec.get()); byte[] decrypted = cipher.doFinal(decoded); // convert bytes to string return new String(decrypted, StandardCharsets.UTF_8); } catch (InvalidKeyException ex) { logger.error(getHelperLogMessage(), ex); throw new RuntimeException(ex); } catch (GeneralSecurityException ex) { logger.error("Failed to decrypt data.", ex); return ""; } }public String encrypt(String data) { Objects.requireNonNull(data, "Data to be encrypted"); if (!secretKeySpec.isPresent()) { return data; } try { // encrypt data Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec.get()); byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)); // convert encrypted bytes to string in base64 return Base64.encodeBase64URLSafeString(encrypted); } catch (InvalidKeyException ex) { logger.error(getHelperLogMessage(), ex); throw new RuntimeException(ex); } catch (GeneralSecurityException ex) { logger.error("Failed to encrypt data.", ex); return ""; } }static public Class resolveStandaloneClass() { return resolveStandaloneClass( System.getProperty(Standalone.KEY_NINJA_STANDALONE_CLASS), ForwardingServiceLoader.loadWithSystemServiceLoader(Standalone.class), Standalone.DEFAULT_STANDALONE_CLASS ); }protected List getAllArtifactsComingFromNinjaStandalone( List artifacts) { List resultingArtifacts = new ArrayList<>(); for (Artifact artifact: artifacts) { for (String dependencyTrail: artifact.getDependencyTrail()) { // something like: org.ninjaframework:ninja-standalone:jar:2.5.2 if (dependencyTrail.contains(NinjaMavenPluginConstants.NINJA_STANDALONE_ARTIFACT_ID)) { resultingArtifacts.add(artifact); break; } } } return resultingArtifacts; }protected RunClassInSeparateJvmMachine buildRunClassInSeparateJvmMachine( String name, String classNameWithMainToRun, List classpath, List jvmArguments, File mavenBaseDir) { return new RunClassInSeparateJvmMachine( name, classNameWithMainToRun, classpath, buildJvmArguments(), mavenBaseDir ); }protected static String generateSecret(Random random) { String charsetForSecret = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; StringBuilder stringBuilder = new StringBuilder(64); for (int i = 0; i < 64; i++) { int charToPoPickFromCharset = random.nextInt(charsetForSecret.length()); stringBuilder.append(charsetForSecret.charAt(charToPoPickFromCharset)); } return stringBuilder.toString(); }protected static URL getUrlForStringFromClasspathAsFileOrUrl(String logbackConfigurationFile) { URL url = null; try { url = Resources.getResource(logbackConfigurationFile); } catch (IllegalArgumentException ex) { // doing nothing intentionally.. } if (url == null) { // configuring from file: try { File file = new File(logbackConfigurationFile); if (file.exists()) { url = new File(logbackConfigurationFile).toURI().toURL(); } } catch (MalformedURLException ex) { // doing nothing intentionally.. } } if (url == null) { try { // we assume we got a real http://... url here... url = new URL(logbackConfigurationFile); } catch (MalformedURLException ex) { // doing nothing intentionally.. } } return url; }private Map loadAllMessageFilesForRegisteredLanguages() { Map langToKeyAndValuesMappingMutable = Maps.newHashMap(); // Load default messages: Configuration defaultLanguage = loadLanguageConfiguration("conf/messages.properties"); // Make sure we got the file. // Everything else does not make much sense. if (defaultLanguage == null) { throw new RuntimeException( "Did not find conf/messages.properties. Please add a default language file."); } else { langToKeyAndValuesMappingMutable.put("", defaultLanguage); } // Get the languages from the application configuration. String[] applicationLangs = ninjaProperties .getStringArray(NinjaConstant.applicationLanguages); // If we don't have any languages declared we just return. // We'll use the default messages.properties file. if (applicationLangs == null) { return ImmutableMap.copyOf(langToKeyAndValuesMappingMutable); } // Load each language into the HashMap containing the languages: for (String lang : applicationLangs) { // First step: Load complete language eg. en-US Configuration configuration = loadLanguageConfiguration(String .format("conf/messages_%s.properties", lang)); Configuration configurationLangOnly = null; // If the language has a country code load the default values for // the language, too. For instance missing variables in en-US will // be // Overwritten by the default languages. if (lang.contains("-")) { // get the lang String langOnly = lang.split("-")[0]; // And load the configuraion configurationLangOnly = loadLanguageConfiguration(String .format("conf/messages_%s.properties", langOnly)); } // This is strange. If you defined the language in application.conf // it should be there propably. if (configuration == null) { logger.info( "Did not find conf/messages_{}.properties but it was specified in application.conf. Using default language instead.", lang); } else { // add new language, but combine with default language if stuff // is missing... CompositeConfiguration compositeConfiguration = new CompositeConfiguration(); // Add eg. "en-US" compositeConfiguration.addConfiguration(configuration); // Add eg. "en" if (configurationLangOnly != null) { compositeConfiguration .addConfiguration(configurationLangOnly); } // Add messages.conf (default pack) compositeConfiguration.addConfiguration(defaultLanguage); // and add the composed configuration to the hashmap with the // mapping. langToKeyAndValuesMappingMutable.put(lang, (Configuration) compositeConfiguration); } } return ImmutableMap.copyOf(langToKeyAndValuesMappingMutable); }private PropertiesConfiguration loadLanguageConfiguration(String fileOrUrl) { PropertiesConfiguration configuration = SwissKnife .loadConfigurationInUtf8(fileOrUrl); if (configuration != null && ninjaProperties.isDev()) { // enable runtime reloading of translations in dev mode FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy(); configuration.setReloadingStrategy(strategy); } return configuration; }public Result serveStatic() { Object renderable = new Renderable() { @Override public void render(Context context, Result result) { String fileName = getFileNameFromPathOrReturnRequestPath(context); URL url = getStaticFileFromAssetsDir(fileName); streamOutUrlEntity(url, context, result); } }; return Results.ok().render(renderable); }protected static String _escapeQuotesAndBackslashes(String s) { final StringBuilder buf = new StringBuilder(s); // Walk backwards, looking for quotes or backslashes. // If we see any, insert an extra backslash into the buffer at // the same index. (By walking backwards, the index into the buffer // will remain correct as we change the buffer.) for (int i = s.length()-1; i >= 0; i--) { char c = s.charAt(i); if ((c == '\\') || (c == '"')) { buf.insert(i, '\\'); } // Replace any special characters with escaped versions else if (c == '\n') { buf.deleteCharAt(i); buf.insert(i, "\\n"); } else if (c == '\t') { buf.deleteCharAt(i); buf.insert(i, "\\t"); } else if (c == '\r') { buf.deleteCharAt(i); buf.insert(i, "\\r"); } else if (c == '\b') { buf.deleteCharAt(i); buf.insert(i, "\\b"); } else if (c == '\f') { buf.deleteCharAt(i); buf.insert(i, "\\f"); } } return buf.toString(); }public static List tokenize(String arguments, boolean stringify) { LinkedList argList = new LinkedList<>(); StringBuilder currArg = new StringBuilder(); boolean escaped = false; int state = NO_TOKEN_STATE; // start in the NO_TOKEN_STATE int len = arguments.length(); // Loop over each character in the string for (int i = 0; i < len; i++) { char c = arguments.charAt(i); if (escaped) { // Escaped state: just append the next character to the current arg. escaped = false; currArg.append(c); } else { switch(state) { case SINGLE_QUOTE_STATE: if (c == '\'') { // Seen the close quote; continue this arg until whitespace is seen state = NORMAL_TOKEN_STATE; } else { currArg.append(c); } break; case DOUBLE_QUOTE_STATE: if (c == '"') { // Seen the close quote; continue this arg until whitespace is seen state = NORMAL_TOKEN_STATE; } else if (c == '\\') { // Look ahead, and only escape quotes or backslashes i++; char next = arguments.charAt(i); if (next == '"' || next == '\\') { currArg.append(next); } else { currArg.append(c); currArg.append(next); } } else { currArg.append(c); } break; // case NORMAL_TOKEN_STATE: // if (Character.isWhitespace(c)) { // // Whitespace ends the token; start a new one // argList.add(currArg.toString()); // currArg = new StringBuffer(); // state = NO_TOKEN_STATE; // } // else if (c == '\\') { // // Backslash in a normal token: escape the next character // escaped = true; // } // else if (c == '\'') { // state = SINGLE_QUOTE_STATE; // } // else if (c == '"') { // state = DOUBLE_QUOTE_STATE; // } // else { // currArg.append(c); // } // break; case NO_TOKEN_STATE: case NORMAL_TOKEN_STATE: switch(c) { case '\\': escaped = true; state = NORMAL_TOKEN_STATE; break; case '\'': state = SINGLE_QUOTE_STATE; break; case '"': state = DOUBLE_QUOTE_STATE; break; default: if (!Character.isWhitespace(c)) { currArg.append(c); state = NORMAL_TOKEN_STATE; } else if (state == NORMAL_TOKEN_STATE) { // Whitespace ends the token; start a new one argList.add(currArg.toString()); currArg = new StringBuilder(); state = NO_TOKEN_STATE; } } break; default: throw new IllegalStateException("ArgumentTokenizer state " + state + " is invalid!"); } } } // If we're still escaped, put in the backslash if (escaped) { currArg.append('\\'); argList.add(currArg.toString()); } // Close the last argument if we haven't yet else if (state != NO_TOKEN_STATE) { argList.add(currArg.toString()); } // Format each argument if we've been told to stringify them if (stringify) { for (int i = 0; i < argList.size(); i++) { argList.set(i, "\"" + _escapeQuotesAndBackslashes(argList.get(i)) + "\""); } } return argList; }public static void setDefaultTimeout(Duration defaultTimeout) { if (defaultTimeout == null) { throw new IllegalArgumentException("You must specify a default timeout (was null)."); } defaultWaitConstraint = defaultWaitConstraint.withMaxWaitTime(defaultTimeout); }public static void setDefaultTimeout(long timeout, TimeUnit unit) { defaultWaitConstraint = defaultWaitConstraint.withMaxWaitTime(new Duration(timeout, unit)); }public static ConditionFactory catchUncaughtExceptions() { return new ConditionFactory(null, defaultWaitConstraint, defaultPollInterval, defaultPollDelay, defaultCatchUncaughtExceptions, defaultExceptionIgnorer, defaultConditionEvaluationListener, defaultExecutorLifecycle); }public void untilFalse(final AtomicBoolean atomic) { untilAtomic(atomic, anyOf(is(Boolean.FALSE), is(false))); }public void untilTrue(final AtomicBoolean atomic) { untilAtomic(atomic, anyOf(is(Boolean.TRUE), is(true))); }public ConditionFactory pollExecutorService(ExecutorService executorService) { if (executorService != null && executorService instanceof ScheduledExecutorService) { throw new IllegalArgumentException("Poll executor service cannot be an instance of " + ScheduledExecutorService.class.getName()); } return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, false, exceptionsIgnorer, conditionEvaluationListener, ExecutorLifecycle.withoutCleanup(executorService)); }public ConditionFactory conditionEvaluationListener(ConditionEvaluationListener conditionEvaluationListener) { return new ConditionFactory(alias, timeoutConstraint, pollInterval, pollDelay, catchUncaughtExceptions, exceptionsIgnorer, conditionEvaluationListener, executorLifecycle); }public static Field getFieldAnnotatedWith(Object object, Class annotationType) { return findSingleFieldUsingStrategy(new FieldAnnotationMatcherStrategy(annotationType), object, true, getType(object)); }public static void throwExceptionIfFieldWasNotFound(Class type, String fieldName, Field field) { if (field == null) { throw new FieldNotFoundException("No field was found with name '" + fieldName + "' in class " + type.getName() + "."); } }private static boolean hasFieldProperModifier(Object object, Field field) { return ((object instanceof Class && Modifier.isStatic(field.getModifiers())) || !(object instanceof Class || Modifier .isStatic(field.getModifiers()))); }private static Field findSingleFieldUsingStrategy(FieldMatcherStrategy strategy, Object object, boolean checkHierarchy, Class startClass) { assertObjectInGetInternalStateIsNotNull(object); Field foundField = null; final Class originalStartClass = startClass; while (startClass != null) { final Field[] declaredFields = startClass.getDeclaredFields(); for (Field field : declaredFields) { if (strategy.matches(field) && hasFieldProperModifier(object, field)) { if (foundField != null) { throw new TooManyFieldsFoundException("Two or more fields matching " + strategy + "."); } foundField = field; } } if (foundField != null) { break; } else if (!checkHierarchy) { break; } startClass = startClass.getSuperclass(); } if (foundField == null) { strategy.notFound(originalStartClass, !isClass(object)); return null; } foundField.setAccessible(true); return foundField; }public Duration divide(long amount) { return new Divide().apply(this, unit == null ? FOREVER : new Duration(amount, unit)); }public Duration multiply(long amount) { return new Multiply().apply(this, unit == null ? FOREVER : new Duration(amount, unit)); }private int fib(int value, int current, int previous) { if (value == 0) { return previous; } else if (value == 1) { return current; } return fib(value - 1, current + previous, current); }public Duration next(int pollCount, Duration previousDuration) { return new Duration(fibonacci(offset + pollCount), timeUnit); }public void bindConfigGlobalDefaults(Class configClass, ConfigDefaults configDefaults) { Key key = Key.get(configClass, GlobalDefaults.class); binder.bindConfigDefaults(new ConfigDefaultsHolder<>(key, configDefaults)); }public static Map loadPropertiesFrom(String path) throws IOException { Properties properties = new Properties(); try (InputStream inputStream = new FileInputStream(path)) { properties.load(inputStream); } return fromProperties(properties); }public void addHash(long hash) { instance.insertHash(hash); if (instance instanceof SparseHll) { instance = makeDenseIfNecessary((SparseHll) instance); } }private double computeMaxPathWeight(int node) { if (node == -1 || levels[node] == 0) { return 0; } double leftMaxWeight = computeMaxPathWeight(lefts[node]); double rightMaxWeight = computeMaxPathWeight(rights[node]); return Math.max(leftMaxWeight, rightMaxWeight) + counts[node]; }private int tryRemove(int node) { checkArgument(node != -1, "node is -1"); int left = lefts[node]; int right = rights[node]; if (left == -1 && right == -1) { // leaf, just remove it remove(node); return -1; } if (left != -1 && right != -1) { // node has both children so we can't physically remove it counts[node] = 0; return node; } // node has a single child, so remove it and return the child remove(node); if (left != -1) { return left; } else { return right; } }public List getHistogram(List bucketUpperBounds, MiddleFunction middleFunction) { checkArgument(Ordering.natural().isOrdered(bucketUpperBounds), "buckets must be sorted in increasing order"); ImmutableList.Builder builder = ImmutableList.builder(); PeekingIterator iterator = Iterators.peekingIterator(bucketUpperBounds.iterator()); HistogramBuilderStateHolder holder = new HistogramBuilderStateHolder(); double normalizationFactor = weight(TimeUnit.NANOSECONDS.toSeconds(ticker.read())); postOrderTraversal(root, node -> { while (iterator.hasNext() && iterator.peek() <= upperBound(node)) { double bucketCount = holder.sum - holder.lastSum; Bucket bucket = new Bucket(bucketCount / normalizationFactor, holder.bucketWeightedSum / bucketCount); builder.add(bucket); holder.lastSum = holder.sum; holder.bucketWeightedSum = 0; iterator.next(); } holder.bucketWeightedSum += middleFunction.middle(lowerBound(node), upperBound(node)) * counts[node]; holder.sum += counts[node]; return iterator.hasNext(); }); while (iterator.hasNext()) { double bucketCount = holder.sum - holder.lastSum; Bucket bucket = new Bucket(bucketCount / normalizationFactor, holder.bucketWeightedSum / bucketCount); builder.add(bucket); iterator.next(); } return builder.build(); }public static void addExceptionCallback(ListenableFuture future, Runnable exceptionCallback, Executor executor) { requireNonNull(exceptionCallback, "exceptionCallback is null"); addExceptionCallback(future, t -> exceptionCallback.run(), executor); }public static ListenableFuture toListenableFuture(CompletableFuture completableFuture) { requireNonNull(completableFuture, "completableFuture is null"); SettableFuture future = SettableFuture.create(); propagateCancellation(future, completableFuture, true); completableFuture.whenComplete((value, exception) -> { if (exception != null) { future.setException(exception); } else { future.set(value); } }); return future; }public static CompletableFuture toCompletableFuture(ListenableFuture listenableFuture) { requireNonNull(listenableFuture, "listenableFuture is null"); CompletableFuture future = new CompletableFuture<>(); future.exceptionally(throwable -> { if (throwable instanceof CancellationException) { listenableFuture.cancel(true); } return null; }); FutureCallback callback = new FutureCallback() { @Override public void onSuccess(V result) { future.complete(result); } @Override public void onFailure(Throwable t) { future.completeExceptionally(t); } }; Futures.addCallback(listenableFuture, callback, directExecutor()); return future; }@Deprecated public static CompletableFuture> allAsList(List> futures) { CompletableFuture allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); // Eagerly propagate exceptions, rather than waiting for all the futures to complete first (default behavior) for (CompletableFuture future : futures) { future.whenComplete((v, throwable) -> { if (throwable != null) { allDoneFuture.completeExceptionally(throwable); } }); } return unmodifiableFuture(allDoneFuture.thenApply(v -> futures.stream() .map(CompletableFuture::join) .collect(Collectors.toList()))); }@Deprecated public static CompletableFuture firstCompletedFuture(Iterable> futures, boolean propagateCancel) { requireNonNull(futures, "futures is null"); checkArgument(!isEmpty(futures), "futures is empty"); CompletableFuture future = new CompletableFuture<>(); for (CompletionStage stage : futures) { stage.whenComplete((value, exception) -> { if (exception != null) { future.completeExceptionally(exception); } else { future.complete(value); } }); } if (propagateCancel) { future.exceptionally(throwable -> { if (throwable instanceof CancellationException) { for (CompletionStage sourceFuture : futures) { if (sourceFuture instanceof Future) { ((Future) sourceFuture).cancel(true); } } } return null; }); } return future; }@Deprecated public static CompletableFuture firstCompletedFuture(Iterable> futures) { return firstCompletedFuture(futures, false); }public static ListenableFuture whenAnyComplete(Iterable> futures) { requireNonNull(futures, "futures is null"); checkArgument(!isEmpty(futures), "futures is empty"); ExtendedSettableFuture firstCompletedFuture = ExtendedSettableFuture.create(); for (ListenableFuture future : futures) { firstCompletedFuture.setAsync(future); } return firstCompletedFuture; }public static void checkSuccess(Future future, String errorMessage) { requireNonNull(future, "future is null"); requireNonNull(errorMessage, "errorMessage is null"); checkArgument(future.isDone(), "future not done yet"); try { getFutureValue(future); } catch (RuntimeException e) { throw new IllegalArgumentException(errorMessage, e); } }public static Optional tryGetFutureValue(Future future, int timeout, TimeUnit timeUnit, Class exceptionType) throws E { requireNonNull(future, "future is null"); checkArgument(timeout >= 0, "timeout is negative"); requireNonNull(timeUnit, "timeUnit is null"); requireNonNull(exceptionType, "exceptionType is null"); try { return Optional.ofNullable(future.get(timeout, timeUnit)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("interrupted", e); } catch (ExecutionException e) { Throwable cause = e.getCause() == null ? e : e.getCause(); propagateIfPossible(cause, exceptionType); throw new RuntimeException(cause); } catch (TimeoutException expected) { // expected } return Optional.empty(); }public static Optional tryGetFutureValue(Future future, int timeout, TimeUnit timeUnit) { return tryGetFutureValue(future, timeout, timeUnit, RuntimeException.class); }public static Optional tryGetFutureValue(Future future) { requireNonNull(future, "future is null"); if (!future.isDone()) { return Optional.empty(); } return tryGetFutureValue(future, 0, MILLISECONDS); }public static V getFutureValue(Future future, Class exceptionType) throws E { requireNonNull(future, "future is null"); requireNonNull(exceptionType, "exceptionType is null"); try { return future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("interrupted", e); } catch (ExecutionException e) { Throwable cause = e.getCause() == null ? e : e.getCause(); propagateIfPossible(cause, exceptionType); throw new RuntimeException(cause); } }@Deprecated public static CompletableFuture failedFuture(Throwable throwable) { requireNonNull(throwable, "throwable is null"); CompletableFuture future = new CompletableFuture<>(); future.completeExceptionally(throwable); return future; }@Deprecated public static CompletableFuture unmodifiableFuture(CompletableFuture future, boolean propagateCancel) { requireNonNull(future, "future is null"); Function onCancelFunction; if (propagateCancel) { onCancelFunction = future::cancel; } else { onCancelFunction = mayInterrupt -> false; } UnmodifiableCompletableFuture unmodifiableFuture = new UnmodifiableCompletableFuture<>(onCancelFunction); future.whenComplete((value, exception) -> { if (exception != null) { unmodifiableFuture.internalCompleteExceptionally(exception); } else { unmodifiableFuture.internalComplete(value); } }); return unmodifiableFuture; }@Deprecated public static CompletableFuture unmodifiableFuture(CompletableFuture future) { return unmodifiableFuture(future, false); }public static void propagateCancellation(ListenableFuture source, Future destination, boolean mayInterruptIfRunning) { source.addListener(() -> { if (source.isCancelled()) { destination.cancel(mayInterruptIfRunning); } }, directExecutor()); }public static double computeAlpha(double targetWeight, long targetAgeInSeconds) { checkArgument(targetAgeInSeconds > 0, "targetAgeInSeconds must be > 0"); checkArgument(targetWeight > 0 && targetWeight < 1, "targetWeight must be in range (0, 1)"); return -Math.log(targetWeight) / targetAgeInSeconds; }@SuppressWarnings("UnusedDeclaration") public String dumpDestination(URI uri) { Destination destination = httpClient.getDestination(uri.getScheme(), uri.getHost(), uri.getPort()); if (destination == null) { return null; } return dumpDestination(destination); }@Override public synchronized void flush() throws IOException { super.flush(); String record = this.toString(); reset(); if (record.isEmpty() || record.equals(lineSeparator)) { // avoid empty records return; } logger.info(record); }public static byte[] base64Decode(String encoded) { int padding = 0; for (int i = encoded.length() - 1; encoded.charAt(i) == '='; i--) { padding++; } int length = encoded.length() * 6 / 8 - padding; byte[] bytes = new byte[length]; for (int i = 0, index = 0, n = encoded.length(); i < n; i += 4) { int word = reverseLookup[encoded.charAt(i)] << 18; word += reverseLookup[encoded.charAt(i + 1)] << 12; word += reverseLookup[encoded.charAt(i + 2)] << 6; word += reverseLookup[encoded.charAt(i + 3)]; for (int j = 0; j < 3 && index + j < length; j++) { bytes[index + j] = (byte) (word >> (8 * (2 - j))); } index += 3; } return bytes; }public static String base64Encode(byte[] bytes) { // always sequence of 4 characters for each 3 bytes; padded with '='s as necessary: StringBuilder buf = new StringBuilder(((bytes.length + 2) / 3) * 4); // first, handle complete chunks (fast loop) int i = 0; for (int end = bytes.length - 2; i < end; ) { int chunk = ((bytes[i++] & 0xFF) << 16) | ((bytes[i++] & 0xFF) << 8) | (bytes[i++] & 0xFF); buf.append(lookup[chunk >> 18]); buf.append(lookup[(chunk >> 12) & 0x3F]); buf.append(lookup[(chunk >> 6) & 0x3F]); buf.append(lookup[chunk & 0x3F]); } // then leftovers, if any int len = bytes.length; if (i < len) { // 1 or 2 extra bytes? int chunk = ((bytes[i++] & 0xFF) << 16); buf.append(lookup[chunk >> 18]); if (i < len) { // 2 bytes chunk |= ((bytes[i] & 0xFF) << 8); buf.append(lookup[(chunk >> 12) & 0x3F]); buf.append(lookup[(chunk >> 6) & 0x3F]); } else { // 1 byte buf.append(lookup[(chunk >> 12) & 0x3F]); buf.append('='); } buf.append('='); } return buf.toString(); }public void update(long value, long timestamp) { lockForRegularUsage(); try { final double priority = weight(timestamp - startTime) / random(); final long newCount = count.incrementAndGet(); if (newCount <= reservoirSize) { values.put(priority, value); } else { Double first = values.firstKey(); if (first < priority) { if (values.putIfAbsent(priority, value) == null) { // ensure we always remove an item while (values.remove(first) == null) { first = values.firstKey(); } } } } } finally { unlockForRegularUsage(); } final long now = System.nanoTime(); final long next = nextScaleTime.get(); if (now >= next) { rescale(now, next); } } T build(ConfigurationProvider configurationProvider) { requireNonNull(configurationProvider, "configurationProvider"); registerConfigurationProvider(configurationProvider, Optional.empty()); // check for a prebuilt instance T instance = getCachedInstance(configurationProvider); if (instance != null) { return instance; } ConfigurationBinding configurationBinding = configurationProvider.getConfigurationBinding(); ConfigurationHolder holder = build(configurationBinding.getConfigClass(), configurationBinding.getPrefix(), getConfigDefaults(configurationBinding.getKey())); instance = holder.getInstance(); // inform caller about warnings if (warningsMonitor != null) { for (Message message : holder.getProblems().getWarnings()) { warningsMonitor.onWarning(message.toString()); } } // add to instance cache T existingValue = putCachedInstance(configurationProvider, instance); // if key was already associated with a value, there was a // creation race and we lost. Just use the winners' instance; if (existingValue != null) { return existingValue; } return instance; }@Nullable private static DoubleSummaryStats processContentTimestamps(List contentTimestamps) { requireNonNull(contentTimestamps, "contentTimestamps is null"); // no content (HTTP 204) or there was a single response chunk (so no interarrival time) if (contentTimestamps.size() == 0 || contentTimestamps.size() == 1) { return null; } DoubleSummaryStatistics statistics = new DoubleSummaryStatistics(); long previousTimestamp = contentTimestamps.get(0); for (int i = 1; i < contentTimestamps.size(); i++) { long timestamp = contentTimestamps.get(i); statistics.accept(NANOSECONDS.toMillis(timestamp - previousTimestamp)); previousTimestamp = timestamp; } return new DoubleSummaryStats(statistics); }private static String percentDecode(String encoded) { Preconditions.checkArgument(ascii().matchesAllOf(encoded), "string must be ASCII"); ByteArrayOutputStream out = new ByteArrayOutputStream(encoded.length()); for (int i = 0; i < encoded.length(); i++) { char c = encoded.charAt(i); if (c == '%') { Preconditions.checkArgument(i + 2 < encoded.length(), "percent encoded value is truncated"); int high = Character.digit(encoded.charAt(i + 1), 16); int low = Character.digit(encoded.charAt(i + 2), 16); Preconditions.checkArgument(high != -1 && low != -1, "percent encoded value is not a valid hex string: ", encoded.substring(i, i + 2)); int value = (high << 4) | (low); out.write(value); i += 2; } else { out.write((int) c); } } try { return UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .decode(ByteBuffer.wrap(out.toByteArray())) .toString(); } catch (CharacterCodingException e) { throw new IllegalArgumentException("input does not represent a proper UTF8-encoded string"); } }public HttpUriBuilder replacePath(String path) { requireNonNull(path, "path is null"); if (!path.isEmpty() && !path.startsWith("/")) { path = "/" + path; } this.path = path; return this; }public void error(Throwable exception, String message) { logger.log(SEVERE, message, exception); }public void warn(Throwable exception, String message) { logger.log(WARNING, message, exception); }public void debug(Throwable exception, String message) { logger.log(FINE, message, exception); }public static Logger get(String name) { java.util.logging.Logger logger = java.util.logging.Logger.getLogger(name); return new Logger(logger); }public static byte[] encodeLength(int length) { if (length < 128) { return new byte[] {(byte) length}; } int numberOfBits = 32 - Integer.numberOfLeadingZeros(length); int numberOfBytes = (numberOfBits + 7) / 8; byte[] encoded = new byte[1 + numberOfBytes]; encoded[0] = (byte) (numberOfBytes | 0x80); for (int i = 0; i < numberOfBytes; i++) { int byteToEncode = (numberOfBytes - i); int shiftSize = (byteToEncode - 1) * 8; encoded[i + 1] = (byte) (length >>> shiftSize); } return encoded; }public static byte[] encodeOctetString(byte[] value) { byte[] lengthEncoded = encodeLength(value.length); ByteArrayDataOutput out = ByteStreams.newDataOutput(2 + lengthEncoded.length + value.length); out.write(OCTET_STRING_TAG); out.write(lengthEncoded); out.write(value); return out.toByteArray(); }public static byte[] encodeBitString(int padBits, byte[] value) { checkArgument(padBits >= 0 && padBits < 8, "Invalid pad bits"); byte[] lengthEncoded = encodeLength(value.length + 1); ByteArrayDataOutput out = ByteStreams.newDataOutput(2 + lengthEncoded.length + value.length); out.write(BIT_STRING_TAG); out.write(lengthEncoded); out.write(padBits); out.write(value); return out.toByteArray(); }public static byte[] decodeSequenceOptionalElement(byte[] element) { int index = 0; // check tag checkArgument((element[0] & 0xE0) == 0xA0, "Expected optional sequence element tag"); index++; // read length int length = decodeLength(element, index); index += encodedLengthSize(length); checkArgument(length + index == element.length, "Invalid optional sequence element"); return Arrays.copyOfRange(element, index, index + length); }public static List decodeSequence(byte[] sequence) { int index = 0; // check tag checkArgument(sequence[0] == SEQUENCE_TAG, "Expected sequence tag"); index++; // read length int sequenceDataLength = decodeLength(sequence, index); index += encodedLengthSize(sequenceDataLength); checkArgument(sequenceDataLength + index == sequence.length, "Invalid sequence"); // read elements ImmutableList.Builder elements = ImmutableList.builder(); while (index < sequence.length) { int elementStart = index; // skip the tag index++; // read length int length = decodeLength(sequence, index); index += encodedLengthSize(length); byte[] data = Arrays.copyOfRange(sequence, elementStart, index + length); elements.add(data); index += length; } return elements.build(); }public static byte[] encodeSequence(byte[]... encodedValues) { int length = 0; for (byte[] encodedValue : encodedValues) { length += encodedValue.length; } byte[] lengthEncoded = encodeLength(length); ByteArrayDataOutput out = ByteStreams.newDataOutput(1 + lengthEncoded.length + length); out.write(SEQUENCE_TAG); out.write(lengthEncoded); for (byte[] entry : encodedValues) { out.write(entry); } return out.toByteArray(); }public DenseHll mergeWith(DenseHll other) { if (indexBitLength != other.indexBitLength) { throw new IllegalArgumentException(String.format( "Cannot merge HLLs with different number of buckets: %s vs %s", numberOfBuckets(indexBitLength), numberOfBuckets(other.indexBitLength))); } int baseline = Math.max(this.baseline, other.baseline); int baselineCount = 0; int overflows = 0; int[] overflowBuckets = new int[OVERFLOW_GROW_INCREMENT]; byte[] overflowValues = new byte[OVERFLOW_GROW_INCREMENT]; int numberOfBuckets = numberOfBuckets(indexBitLength); for (int i = 0; i < numberOfBuckets; i++) { int value = Math.max(getValue(i), other.getValue(i)); int delta = value - baseline; if (delta == 0) { baselineCount++; } else if (delta > MAX_DELTA) { // grow overflows arrays if necessary overflowBuckets = Ints.ensureCapacity(overflowBuckets, overflows + 1, OVERFLOW_GROW_INCREMENT); overflowValues = Bytes.ensureCapacity(overflowValues, overflows + 1, OVERFLOW_GROW_INCREMENT); overflowBuckets[overflows] = i; overflowValues[overflows] = (byte) (delta - MAX_DELTA); overflows++; delta = MAX_DELTA; } setDelta(i, delta); } this.baseline = (byte) baseline; this.baselineCount = baselineCount; this.overflows = overflows; this.overflowBuckets = overflowBuckets; this.overflowValues = overflowValues; // all baseline values in one of the HLLs lost to the values // in the other HLL, so we need to adjust the final baseline adjustBaselineIfNeeded(); return this; }private boolean setOverflow(int bucket, int overflow) { for (int i = 0; i < overflows; i++) { if (overflowBuckets[i] == bucket) { overflowValues[i] = (byte) overflow; return true; } } return false; }public void addInstance(Object instance) throws Exception { State currentState = state.get(); if ((currentState == State.STOPPING) || (currentState == State.STOPPED)) { throw new IllegalStateException(); } else { startInstance(instance); if (methodsMap.get(instance.getClass()).hasFor(PreDestroy.class)) { managedInstances.add(instance); } } }private StateRepresentation getOrCreateRepresentation(TState state) { StateRepresentation result = stateConfiguration.get(state); if (result == null) { result = new StateRepresentation<>(state); stateConfiguration.put(state, result); } return result; }public StateConfiguration ignoreIf(T trigger, FuncBoolean guard) { assert guard != null : GUARD_IS_NULL; representation.addTriggerBehaviour(new InternalTriggerBehaviour(trigger, guard, NO_ACTION)); return this; }public StateConfiguration permitIfOtherwiseIgnore(T trigger, S destinationState, final FuncBoolean guard) { enforceNotIdentityTransition(destinationState); ignoreIf(trigger, new FuncBoolean() { @Override public boolean call() { return !guard.call(); } }); return publicPermitIf(trigger, destinationState, guard); }public StateConfiguration permitIf(T trigger, S destinationState, FuncBoolean guard) { enforceNotIdentityTransition(destinationState); return publicPermitIf(trigger, destinationState, guard); }public StateConfiguration permit(T trigger, S destinationState) { enforceNotIdentityTransition(destinationState); return publicPermit(trigger, destinationState); }public void attach(ViewGroup.LayoutParams layoutParams) { if(systemOverlay) { try { getWindowManager().addView(this, layoutParams); } catch(SecurityException e) { throw new SecurityException("Your application must have SYSTEM_ALERT_WINDOW " + "permission to create a system window."); } } else { ((ViewGroup) getActivityContentView()).addView(this, layoutParams); } }public void setPosition(int position, ViewGroup.LayoutParams layoutParams) { boolean setDefaultMargin = false; int gravity; switch (position) { case POSITION_TOP_CENTER: gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL; break; case POSITION_TOP_RIGHT: gravity = Gravity.TOP | Gravity.RIGHT; break; case POSITION_RIGHT_CENTER: gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL; break; case POSITION_BOTTOM_CENTER: gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL; break; case POSITION_BOTTOM_LEFT: gravity = Gravity.BOTTOM | Gravity.LEFT; break; case POSITION_LEFT_CENTER: gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL; break; case POSITION_TOP_LEFT: gravity = Gravity.TOP | Gravity.LEFT; break; case POSITION_BOTTOM_RIGHT: default: setDefaultMargin = true; gravity = Gravity.BOTTOM | Gravity.RIGHT; break; } if(!systemOverlay) { try { FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) layoutParams; lp.gravity = gravity; setLayoutParams(lp); } catch (ClassCastException e) { throw new ClassCastException("layoutParams must be an instance of " + "FrameLayout.LayoutParams, since this FAB is not a systemOverlay"); } } else { try { WindowManager.LayoutParams lp = (WindowManager.LayoutParams) layoutParams; lp.gravity = gravity; if(setDefaultMargin) { int margin = getContext().getResources().getDimensionPixelSize(R.dimen.action_button_margin); lp.x = margin; lp.y = margin; } setLayoutParams(lp); } catch(ClassCastException e) { throw new ClassCastException("layoutParams must be an instance of " + "WindowManager.LayoutParams, since this FAB is a systemOverlay"); } } }public void setContentView(View contentView, FrameLayout.LayoutParams params) { if(params == null) { params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER); final int margin = getResources().getDimensionPixelSize(R.dimen.sub_action_button_content_margin); params.setMargins(margin, margin, margin, margin); } contentView.setClickable(false); this.addView(contentView, params); }protected void restoreSubActionViewAfterAnimation(FloatingActionMenu.Item subActionItem, ActionType actionType) { ViewGroup.LayoutParams params = subActionItem.view.getLayoutParams(); subActionItem.view.setTranslationX(0); subActionItem.view.setTranslationY(0); subActionItem.view.setRotation(0); subActionItem.view.setScaleX(1); subActionItem.view.setScaleY(1); subActionItem.view.setAlpha(1); if(actionType == ActionType.OPENING) { FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) params; if(menu.isSystemOverlay()) { WindowManager.LayoutParams overlayParams = (WindowManager.LayoutParams) menu.getOverlayContainer().getLayoutParams(); lp.setMargins(subActionItem.x - overlayParams.x, subActionItem.y - overlayParams.y, 0, 0); } else { lp.setMargins(subActionItem.x, subActionItem.y, 0, 0); } subActionItem.view.setLayoutParams(lp); } else if(actionType == ActionType.CLOSING) { Point center = menu.getActionViewCenter(); FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) params; if(menu.isSystemOverlay()) { WindowManager.LayoutParams overlayParams = (WindowManager.LayoutParams) menu.getOverlayContainer().getLayoutParams(); lp.setMargins(center.x - overlayParams.x - subActionItem.width / 2, center.y - overlayParams.y - subActionItem.height / 2, 0, 0); } else { lp.setMargins(center.x - subActionItem.width / 2, center.y - subActionItem.height / 2, 0, 0); } subActionItem.view.setLayoutParams(lp); menu.removeViewFromCurrentContainer(subActionItem.view); if(menu.isSystemOverlay()) { // When all the views are removed from the overlay container, // we also need to detach it if (menu.getOverlayContainer().getChildCount() == 0) { menu.detachOverlayContainer(); } } } }private Point getScreenSize() { Point size = new Point(); getWindowManager().getDefaultDisplay().getSize(size); return size; }public View getActivityContentView() { try { return ((Activity) mainActionView.getContext()).getWindow().getDecorView().findViewById(android.R.id.content); } catch(ClassCastException e) { throw new ClassCastException("Please provide an Activity context for this FloatingActionMenu."); } }private Point calculateItemPositions() { // Create an arc that starts from startAngle and ends at endAngle // in an area that is as large as 4*radius^2 final Point center = getActionViewCenter(); RectF area = new RectF(center.x - radius, center.y - radius, center.x + radius, center.y + radius); Path orbit = new Path(); orbit.addArc(area, startAngle, endAngle - startAngle); PathMeasure measure = new PathMeasure(orbit, false); // Prevent overlapping when it is a full circle int divisor; if(Math.abs(endAngle - startAngle) >= 360 || subActionItems.size() <= 1) { divisor = subActionItems.size(); } else { divisor = subActionItems.size() -1; } // Measure this path, in order to find points that have the same distance between each other for(int i=0; i T castValue(final Object value) { return value != null ? (T) value : null; }@SuppressWarnings("deprecation") @Bean public UserDetailsService userDetailsService() { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(User.withDefaultPasswordEncoder().username("demo").password("demo").roles("ACTUATOR", "camunda-admin").build()); manager.createUser(User.withDefaultPasswordEncoder().username("john").password("john").roles("camunda-user").build()); return manager; }public static ProcessApplicationInfo getProcessApplicationInfo(String processDefinitionId) { ProcessEngineService processEngineService = BpmPlatform.getProcessEngineService(); ProcessApplicationService processAppService = BpmPlatform.getProcessApplicationService(); // iterate over all process applications for (String appName : processAppService.getProcessApplicationNames()) { ProcessApplicationInfo appInfo = processAppService .getProcessApplicationInfo(appName); // iterate over all deployments of a process application for (ProcessApplicationDeploymentInfo deploymentInfo : appInfo .getDeploymentInfo()) { long count = processEngineService .getProcessEngine(deploymentInfo.getProcessEngineName()) .getRepositoryService().createProcessDefinitionQuery() .deploymentId(deploymentInfo.getDeploymentId()) .processDefinitionId(processDefinitionId).count(); if (count > 0) { return appInfo; } } } return null; }public static ProcessApplicationInfo getProcessApplicationInfo( ProcessEngine processEngine, String processDefinitionId) { ProcessDefinition processDefinition = processEngine.getRepositoryService().getProcessDefinition(processDefinitionId); // get the name of the process application that made the deployment String processApplicationName = processEngine.getManagementService() .getProcessApplicationForDeployment(processDefinition.getDeploymentId()); if (processApplicationName == null) { // not a process application deployment return null; } else { ProcessApplicationService processApplicationService = BpmPlatform.getProcessApplicationService(); return processApplicationService.getProcessApplicationInfo(processApplicationName); } }public static String getServletContextPath(String processDefinitionId) { ProcessApplicationInfo processApplicationInfo = getProcessApplicationInfo(processDefinitionId); if (processApplicationInfo == null) { return null; } return processApplicationInfo.getProperties().get( ProcessApplicationInfo.PROP_SERVLET_CONTEXT_PATH); }public static String getServletContextPath( ProcessEngine processEngine, String processDefinitionId) { return getServletContextPath(getProcessApplicationInfo(processEngine, processDefinitionId)); }private void checkTaskSelectedViaBridge() { String bridgeTaskId = (String) getSharedSessionAttribute(BRIDGE_TASK_ID); String selectedTaskId = (String) getSharedSessionAttribute(ASSOCIATED_TASK_ID); if (selectedTaskId == null && bridgeTaskId != null) { switchTaskId(bridgeTaskId); } if (selectedTaskId != null && bridgeTaskId != null && !selectedTaskId.equals(bridgeTaskId)) { // task switched, TODO: think about if correct like this switchTaskId(bridgeTaskId); } }@PostDeploy public void deployProcessesToTenantEngines() { // copy the process definitions deployed to the default engine to all tenants for (ProcessEngine processEngine : BpmPlatform.getProcessEngineService().getProcessEngines()) { if (processEngine != BpmPlatform.getDefaultProcessEngine()) { TenantManager.deployDefaultProcessesToEngine(processEngine); } } }private void addFourEyesTaskListener(ActivityImpl activity) { UserTaskActivityBehavior userTaskActivityBehavior = (UserTaskActivityBehavior) activity.getActivityBehavior(); boolean listenerAlreadyExists = false; // check that the listener wasn't added in the XML explicitly List existingListeners = userTaskActivityBehavior.getTaskDefinition().getTaskListeners().get("complete"); for (TaskListener taskListener : existingListeners) { if (taskListener instanceof ClassDelegate && ((ClassDelegate)taskListener).getClassName().equals(TaskCompletionListener.class.getName())) { listenerAlreadyExists = true; logger.info(TaskCompletionListener.class.getSimpleName() + " was already explicitly added to usertask in the bpmn xml."); break; } } if (!listenerAlreadyExists) { logger.info("Adding " + TaskCompletionListener.class.getSimpleName() + " implicitly to usertask."); ClassDelegate taskListener = new ClassDelegate(TaskCompletionListener.class, null); userTaskActivityBehavior.getTaskDefinition().addTaskListener("complete", taskListener); } }public void updateModifiedFieldsFromEntity(ProcessDefinitionEntity updatingProcessDefinition) { if (!this.key.equals(updatingProcessDefinition.key) || !this.deploymentId.equals(updatingProcessDefinition.deploymentId)) { throw new ProcessEngineException("Cannot update entity from an unrelated process definition"); } // TODO: add a guard once the mismatch between revisions in deployment cache and database has been resolved this.revision = updatingProcessDefinition.revision; this.suspensionState = updatingProcessDefinition.suspensionState; }public static BoxDeveloperEditionAPIConnection userClient(String userId) { if (userId == null) { // session data has expired return null; } System.out.format("userClient called with userId %s \n\n", userId); try { BoxDeveloperEditionAPIConnection userClient = BoxDeveloperEditionAPIConnection.getAppUserConnection( userId, CLIENT_ID, CLIENT_SECRET, jwtEncryptionPreferences, accessTokenCache); return userClient; } catch (BoxAPIException apiException) { apiException.printStackTrace(); throw apiException; } }public void setAutoProxy(String autoProxyUrl) { proxyConfig = new ProxyConfig(); proxyConfig.setProxyAutoConfigUrl(autoProxyUrl); getWebClient().getOptions().setProxyConfig(proxyConfig); }public void setHTTPProxy(String host, int port, List noProxyHosts) { proxyConfig = new ProxyConfig(); proxyConfig.setProxyHost(host); proxyConfig.setProxyPort(port); if (noProxyHosts != null && noProxyHosts.size() > 0) { for (String noProxyHost : noProxyHosts) { proxyConfig.addHostsToProxyBypass(noProxyHost); } } getWebClient().getOptions().setProxyConfig(proxyConfig); }public void setProxySettings(Proxy proxy) { if (proxy == null || proxy.getProxyType() == Proxy.ProxyType.UNSPECIFIED) { return; } switch (proxy.getProxyType()) { case MANUAL: List noProxyHosts = new ArrayList<>(); String noProxy = proxy.getNoProxy(); if (noProxy != null && !noProxy.isEmpty()) { String[] hosts = noProxy.split(","); for (String host : hosts) { if (host.trim().length() > 0) { noProxyHosts.add(host.trim()); } } } String httpProxy = proxy.getHttpProxy(); if (httpProxy != null && !httpProxy.isEmpty()) { String host = httpProxy; int port = 0; int index = httpProxy.indexOf(":"); if (index != -1) { host = httpProxy.substring(0, index); port = Integer.parseInt(httpProxy.substring(index + 1)); } setHTTPProxy(host, port, noProxyHosts); } String socksProxy = proxy.getSocksProxy(); if (socksProxy != null && !socksProxy.isEmpty()) { String host = socksProxy; int port = 0; int index = socksProxy.indexOf(":"); if (index != -1) { host = socksProxy.substring(0, index); port = Integer.parseInt(socksProxy.substring(index + 1)); } setSocksProxy(host, port, noProxyHosts); } // sslProxy is not supported/implemented // ftpProxy is not supported/implemented break; case PAC: String pac = proxy.getProxyAutoconfigUrl(); if (pac != null && !pac.isEmpty()) { setAutoProxy(pac); } break; default: break; } }public Object execute(String scriptBody, Object[] parameters) { try { asyncResult = new AsyncScriptResult(); Function function = createInjectedScriptFunction(scriptBody, asyncResult); try { page.executeJavaScriptFunction(function, function, parameters, page.getDocumentElement()); } catch (ScriptException e) { throw new WebDriverException(e); } try { return asyncResult.waitForResult(timeoutMillis); } catch (InterruptedException e) { throw new WebDriverException(e); } } finally { asyncResult = null; } }void close() { lock.lock(); condition.signal(); setAutoAccept(true); lock.unlock(); holder_ = null; }public final TokenBuffer nextTokenBuffer() throws IOException { TokenBuffer buffer = new TokenBuffer(parser); // if token is consumed, but undelying parser is still sitting on this token, we move forward requirePeek(); buffer.copyCurrentStructure(parser); // when we will return to reading from reader, state will be cleared and nextToken after clearPeek(); return buffer; }protected String stringify(DeclaredType input, TypevarContext context) { return toTypeElement(input).getQualifiedName().toString(); }@Encoding.Expose public Optional> getImmutable() { return Optional.ofNullable(map); }public static FluentFuture from(ListenableFuture future) { if (future instanceof FluentFuture) { return (FluentFuture) future; } return new WrapingFluentFuture<>(future, MoreExecutors.directExecutor()); }public static Predicate of(Expression expression) { if (Expressions.isNil(expression)) { // always true return instance -> true; } return new InMemoryExpressionEvaluator<>(expression); }public String getMarshaledName() { String serializedName = getSerializedName(); if (!serializedName.isEmpty()) { return serializedName; } return names.raw; }public String getSerializedName() { if (serializedName == null) { Optional serializedNameAnnotation = SerializedNameMirror.find(element); if (serializedNameAnnotation.isPresent()) { SerializedNameMirror m = serializedNameAnnotation.get(); serializedName = m.value(); alternateSerializedNames = m.alternate(); return serializedName; } Optional namedAnnotation = NamedMirror.find(element); if (namedAnnotation.isPresent()) { String value = namedAnnotation.get().value(); if (!value.isEmpty()) { serializedName = value; return serializedName; } } Optional okNamedAnnotation = OkNamedMirror.find(element); if (okNamedAnnotation.isPresent()) { String value = okNamedAnnotation.get().name(); if (!value.isEmpty()) { serializedName = value; return serializedName; } } if (isMarkedAsMongoId()) { serializedName = ID_ATTRIBUTE_NAME; return serializedName; } serializedName = ""; return serializedName; } return serializedName; }private static String cachingKey(ValueAttribute valueAttribute) { return String.format("%s-%s", valueAttribute.containedTypeElement.getQualifiedName(), Joiner.on(".").join(valueAttribute.containingType.constitution.style().attributeBuilder())); }@Override public Iterator iterator() { return new AbstractIterator() { private final int length = length(); private int index = 0; @Override protected E computeNext() { int p = index++; if (p < length) { return get(p); } return endOfData(); } }; }@SuppressWarnings("unchecked") public static > ImmutableOrdinalSet of() { // safe unchecked: will contain no elements return (ImmutableOrdinalSet) EMPTY_SET; }@SuppressWarnings("unchecked") @Override @Nullable public TypeAdapter create(Gson gson, TypeToken type) { if (ID_TYPE_TOKEN.equals(type)) { return (TypeAdapter) WRAPPED_ID_ADAPTER; } if (TIME_INSTANT_TYPE_TOKEN.equals(type)) { return (TypeAdapter) WRAPPED_TIME_INSTANT_ADAPTER; } if (BINARY_TYPE_TOKEN.equals(type)) { return (TypeAdapter) WRAPPED_BINARY_ADAPTER; } if (PATTERN_TYPE_TOKEN.equals(type)) { return (TypeAdapter) PATTERN_ADAPTER; } if (DECIMAL128_TYPE_TOKEN.equals(type)) { return (TypeAdapter) DECIMAL128_ADAPTER; } return null; }@Value.Lazy public NameForms typeImmutable() { String simple, relative; if (protoclass().kind().isNested()) { String enclosingSimpleName = typeImmutableEnclosingSimpleName(); simple = names().typeImmutableNested(); relative = inPackage(enclosingSimpleName, simple); } else if (hasImmutableInBuilder()) { simple = names().typeImmutable; relative = inPackage(typeBuilderSimpleName(), simple); } else { simple = names().typeImmutable; relative = inPackage(simple); } return ImmutableConstitution.NameForms.builder() .simple(simple) .relativeRaw(relative) .genericArgs(generics().args()) .packageOf(implementationPackage()) .visibility(implementationVisibility()) .build(); }private String inPackage(String topLevel, String... nested) { return DOT_JOINER.join(null, topLevel, (Object[]) nested); }@Value.Lazy public NameForms typeAbstract() { if (protoclass().kind().isConstructor()) { return typeValue(); } List classSegments = Lists.newArrayListWithExpectedSize(2); Element e = SourceNames.collectClassSegments(protoclass().sourceElement(), classSegments); verify(e instanceof PackageElement); String packageOf = ((PackageElement) e).getQualifiedName().toString(); String relative = DOT_JOINER.join(classSegments); boolean relativeAlreadyQualified = false; if (!implementationPackage().equals(packageOf)) { relative = DOT_JOINER.join(packageOf, relative); relativeAlreadyQualified = true; } return ImmutableConstitution.NameForms.builder() .simple(names().typeAbstract) .relativeRaw(relative) .packageOf(packageOf) .genericArgs(generics().args()) .relativeAlreadyQualified(relativeAlreadyQualified) .visibility(protoclass().visibility()) .build(); }@SuppressWarnings("unchecked") @Override public T read(JsonReader in) throws IOException { List exceptions = new ArrayList<>(subtypes.length); ReaderSupplier readerSupplier = readForSupplier(in); for (TypeAdapter typeAdapter : adapters) { try { return (T) typeAdapter.read(readerSupplier.create()); } catch (Exception ex) { exceptions.add(ex); } } JsonParseException failure = new JsonParseException( String.format( "Cannot parse %s with following subtypes: %s", type, Arrays.toString(subtypes))); for (Exception exception : exceptions) { failure.addSuppressed(exception); } throw failure; }public static OkHttpClient.Builder configureToIgnoreCertificate(OkHttpClient.Builder builder) { log.warn("Ignore Ssl Certificate"); try { /*Create a trust manager that does not validate certificate chains*/ final TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } } }; /*Install the all-trusting trust manager*/ final SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); /*Create an ssl socket factory with our all-trusting manager*/ final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]); builder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } catch (Exception e) { log.warn("Exception while configuring IgnoreSslCertificate" + e, e); } return builder; }public static String getMD5Checksum(String filename) { try { byte[] b = createChecksum(filename); String result = ""; for (int i=0; i < b.length; i++) { result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 ); } return result; } catch (Exception e){ return ""; } }public void setOnBindSuggestionCallback(SearchSuggestionsAdapter.OnBindSuggestionCallback callback) { this.mOnBindSuggestionCallback = callback; if (mSuggestionsAdapter != null) { mSuggestionsAdapter.setOnBindSuggestionCallback(mOnBindSuggestionCallback); } }private int calculateSuggestionItemsHeight(List suggestions, int max) { //todo // 'i < suggestions.size()' in the below 'for' seems unneeded, investigate if there is a use for it. int visibleItemsHeight = 0; for (int i = 0; i < suggestions.size() && i < mSuggestionsList.getChildCount(); i++) { visibleItemsHeight += mSuggestionsList.getChildAt(i).getHeight(); if (visibleItemsHeight > max) { visibleItemsHeight = max; break; } } return visibleItemsHeight; }private boolean updateSuggestionsSectionHeight(List newSearchSuggestions, boolean withAnim) { final int cardTopBottomShadowPadding = Util.dpToPx(CARD_VIEW_CORNERS_AND_TOP_BOTTOM_SHADOW_HEIGHT); final int cardRadiusSize = Util.dpToPx(CARD_VIEW_TOP_BOTTOM_SHADOW_HEIGHT); int visibleSuggestionHeight = calculateSuggestionItemsHeight(newSearchSuggestions, mSuggestionListContainer.getHeight()); int diff = mSuggestionListContainer.getHeight() - visibleSuggestionHeight; int addedTranslationYForShadowOffsets = (diff <= cardTopBottomShadowPadding) ? -(cardTopBottomShadowPadding - diff) : diff < (mSuggestionListContainer.getHeight() - cardTopBottomShadowPadding) ? cardRadiusSize : 0; final float newTranslationY = -mSuggestionListContainer.getHeight() + visibleSuggestionHeight + addedTranslationYForShadowOffsets; //todo go over final float fullyInvisibleTranslationY = -mSuggestionListContainer.getHeight() + cardRadiusSize; ViewCompat.animate(mSuggestionListContainer).cancel(); if (withAnim) { ViewCompat.animate(mSuggestionListContainer). setInterpolator(SUGGEST_ITEM_ADD_ANIM_INTERPOLATOR). setDuration(mSuggestionSectionAnimDuration). translationY(newTranslationY) .setUpdateListener(new ViewPropertyAnimatorUpdateListener() { @Override public void onAnimationUpdate(View view) { if (mOnSuggestionsListHeightChanged != null) { float newSuggestionsHeight = Math.abs(view.getTranslationY() - fullyInvisibleTranslationY); mOnSuggestionsListHeightChanged.onSuggestionsListHeightChanged(newSuggestionsHeight); } } }) .setListener(new ViewPropertyAnimatorListenerAdapter() { @Override public void onAnimationCancel(View view) { mSuggestionListContainer.setTranslationY(newTranslationY); } }).start(); } else { mSuggestionListContainer.setTranslationY(newTranslationY); if (mOnSuggestionsListHeightChanged != null) { float newSuggestionsHeight = Math.abs(mSuggestionListContainer.getTranslationY() - fullyInvisibleTranslationY); mOnSuggestionsListHeightChanged.onSuggestionsListHeightChanged(newSuggestionsHeight); } } return mSuggestionListContainer.getHeight() == visibleSuggestionHeight; }public boolean setSearchFocused(final boolean focused) { boolean updatedToNotFocused = !focused && this.mIsFocused; if ((focused != this.mIsFocused) && mSuggestionSecHeightListener == null) { if (mIsSuggestionsSectionHeightSet) { setSearchFocusedInternal(focused); } else { mSuggestionSecHeightListener = new OnSuggestionSecHeightSetListener() { @Override public void onSuggestionSecHeightSet() { setSearchFocusedInternal(focused); mSuggestionSecHeightListener = null; } }; } } return updatedToNotFocused; }public void setDismissOnOutsideClick(boolean enable) { mDismissOnOutsideTouch = enable; mSuggestionsSection.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //todo check if this is called twice if (mDismissOnOutsideTouch && mIsFocused) { setSearchFocusedInternal(false); } return true; } }); }public void setShowSearchKey(boolean show) { mShowSearchKey = show; if (show) { mSearchInput.setImeOptions(EditorInfo.IME_ACTION_SEARCH); } else { mSearchInput.setImeOptions(EditorInfo.IME_ACTION_NONE); } }public void inflateOverflowMenu(int menuId) { mMenuId = menuId; mMenuView.reset(menuId, actionMenuAvailWidth()); if (mIsFocused) { mMenuView.hideIfRoomItems(false); } }public void closeMenu(boolean withAnim) { mMenuOpen = false; closeMenuDrawable(mMenuBtnDrawable, withAnim); if (mOnMenuClickListener != null) { mOnMenuClickListener.onMenuClosed(); } }public void openMenu(boolean withAnim) { mMenuOpen = true; openMenuDrawable(mMenuBtnDrawable, withAnim); if (mOnMenuClickListener != null) { mOnMenuClickListener.onMenuOpened(); } }public void setBackgroundColor(int color) { mBackgroundColor = color; if (mQuerySection != null && mSuggestionsList != null) { mQuerySection.setCardBackgroundColor(color); mSuggestionsList.setBackgroundColor(color); } }public void setLeftActionIconColor(int color) { mLeftActionIconColor = color; mMenuBtnDrawable.setColor(color); DrawableCompat.setTint(mIconBackArrow, color); DrawableCompat.setTint(mIconSearch, color); }private void handleOnVisibleMenuItemsWidthChanged(int menuItemsWidth) { if (menuItemsWidth == 0) { mClearButton.setTranslationX(-Util.dpToPx(4)); int paddingRight = Util.dpToPx(4); if (mIsFocused) { paddingRight += Util.dpToPx(CLEAR_BTN_WIDTH_DP); } else { paddingRight += Util.dpToPx(14); } mSearchInput.setPadding(0, 0, paddingRight, 0); } else { mClearButton.setTranslationX(-menuItemsWidth); int paddingRight = menuItemsWidth; if (mIsFocused) { paddingRight += Util.dpToPx(CLEAR_BTN_WIDTH_DP); } mSearchInput.setPadding(0, 0, paddingRight, 0); } }private Part[] parseValues(String contents) { String[] parts = contents.split(","); Part[] results = new Part[parts.length]; for (int i = 0; i < parts.length; i++) { try { results[i] = new Part(parts[i], property); } catch (Exception e) { LOG.warning(e.getMessage()); results[i] = null; } } return results; }private ArrayList parseProperties(String contents) { ArrayList parts = new ArrayList<>(); boolean bInsideString = false, bInsideURL = false; int j = 0; String substr; for (int i = 0; i < contents.length(); i++) { if (bInsideString) { // If we're inside a string bInsideString = !(contents.charAt(i) == '"'); } else if (bInsideURL) { // If we're inside a URL bInsideURL = !(contents.charAt(i) == ')'); } else if (contents.charAt(i) == '"') { bInsideString = true; } else if (contents.charAt(i) == '(') { if ((i - 3) > 0 && "url".equals(contents.substring(i - 3, i))) { bInsideURL = true; } } else if (contents.charAt(i) == ';') { substr = contents.substring(j, i); if (!(substr.trim().equals(""))) { parts.add(substr); } j = i + 1; } } substr = contents.substring(j, contents.length()); if (!(substr.trim().equals(""))) { parts.add(substr); } ArrayList results = new ArrayList<>(); for (String part : parts) { try { results.add(new Property(part)); } catch (IncompletePropertyException ipex) { LOG.warning("Incomplete property in selector \"" + this.selector + "\": \"" + ipex.getMessage() + "\""); } } return results; }public static String compressJs(String code) { InputStream inStream = new ByteArrayInputStream(code.getBytes()); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); JSMin jsmin = new JSMin(inStream, outStream); try { jsmin.jsmin(); return outStream.toString().trim(); } catch (Exception e) { e.printStackTrace(); return ""; } }public T withClasses(String... classes) { StringBuilder sb = new StringBuilder(); for (String s : classes) { sb.append(s != null ? s : "").append(" "); } return attr(Attr.CLASS, sb.toString().trim()); }public T attr(Attribute attribute) { Iterator iterator = attributes.iterator(); String name = attribute.getName(); if (name != null) { // name == null is allowed, but those Attributes are not rendered. So we add them anyway. while (iterator.hasNext()) { Attribute existingAttribute = iterator.next(); if (existingAttribute.getName().equals(name)) { iterator.remove(); } } } attributes.add(attribute); return (T) this; }public T attr(String attribute, Object value) { setAttribute(attribute, value == null ? null : String.valueOf(value)); return (T) this; }boolean setAttribute(String name, String value) { if (value == null) { return attributes.add(new Attribute(name)); } for (Attribute attribute : attributes) { if (attribute.getName().equals(name)) { attribute.setValue(value); // update with new value return true; } } return attributes.add(new Attribute(name, value)); }public static String document(ContainerTag htmlTag) { if (htmlTag.getTagName().equals("html")) { return document().render() + htmlTag.render(); } throw new IllegalArgumentException("Only HTML-tag can follow document declaration"); }@SuppressWarnings("OptionalUsedAsFieldOrParameterType") public static T iff(Optional optional, Function ifFunction) { if (Objects.nonNull(optional) && optional.isPresent()) { return optional.map(ifFunction).orElse(null); } return null; }public ContainerTag with(Iterable children) { if (children != null) { for (DomContent child : children) { this.with(child); } } return this; }public ContainerTag with(DomContent child) { if (this == child) { throw new RuntimeException("Cannot append a tag to itself."); } if (child == null) { return this; // in some cases, like when using iff(), we ignore null children } children.add(child); return this; }public EngineType readEngineType() throws IOException { try { engineType = EngineId.typeForMagic(new String(readBytes(8))); if (engineType == null) { throw new IOException(); } return engineType; } catch (IOException e) { throw new IOException("given stream does not seem to contain a valid replay"); } }public int readFixedInt32() throws IOException { return ByteBuffer.wrap(readBytes(4)).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get(); }public int readVarInt32() throws IOException { byte tmp = readByte(); if (tmp >= 0) { return tmp; } int result = tmp & 0x7f; if ((tmp = readByte()) >= 0) { result |= tmp << 7; } else { result |= (tmp & 0x7f) << 7; if ((tmp = readByte()) >= 0) { result |= tmp << 14; } else { result |= (tmp & 0x7f) << 14; if ((tmp = readByte()) >= 0) { result |= tmp << 21; } else { result |= (tmp & 0x7f) << 21; result |= (tmp = readByte()) << 28; if (tmp < 0) { throw new IOException("malformed varint detected"); } } } } return result; }private byte[] readPacket(Source source) throws IOException { int size = source.readFixedInt32(); return packetReader.readFromSource(source, size, false); }private static S2DotaMatchMetadata.CDOTAMatchMetadataFile metadataForStream(InputStream stream) throws IOException { return Packet.parse(S2DotaMatchMetadata.CDOTAMatchMetadataFile.class, ByteString.readFrom(stream)); }public static Demo.CDemoFileInfo infoForSource(final Source source) throws IOException { EngineType engineType = source.readEngineType(); source.setPosition(source.readFixedInt32()); PacketInstance pi = engineType.getNextPacketInstance(source); return (Demo.CDemoFileInfo) pi.parse(); }public boolean hasProperties(String... properties) { for (String property : properties) { if (!hasProperty(property)) { return false; } } return true; }public void shutdown() { if (isShutdown.compareAndSet(false, true)) { executorService.shutdown(); if (autoScaler != null) { autoScaler.shutdown(); } } }public void enableVM(String hostname) throws IllegalStateException { logger.debug("Enabling VM " + hostname); assignableVMs.enableVM(hostname); }public boolean disableVMByVMId(String vmID, long durationMillis) throws IllegalStateException { final String hostname = assignableVMs.getHostnameFromVMId(vmID); if (hostname == null) { return false; } disableVM(hostname, durationMillis); return true; }public void disableVM(String hostname, long durationMillis) throws IllegalStateException { logger.debug("Disable VM " + hostname + " for " + durationMillis + " millis"); assignableVMs.disableUntil(hostname, System.currentTimeMillis() + durationMillis); }public void setAutoscalerCallback(Action1 callback) throws IllegalStateException { checkIfShutdown(); if (autoScaler == null) { throw new IllegalStateException("No autoScaler setup"); } autoScaler.setCallback(callback); }@Override public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) { Set coTasks = coTasksGetter.call(taskRequest.getId()); String targetHostAttrVal = AttributeUtilities.getAttrValue(targetVM.getCurrAvailableResources(), hostAttributeName); if(targetHostAttrVal==null || targetHostAttrVal.isEmpty()) { return new Result(false, hostAttributeName + " attribute unavailable on host " + targetVM.getCurrAvailableResources().hostname()); } for(String coTask: coTasks) { TaskTracker.ActiveTask activeTask = taskTrackerState.getAllRunningTasks().get(coTask); if(activeTask==null) activeTask = taskTrackerState.getAllCurrentlyAssignedTasks().get(coTask); if(activeTask!=null) { String usedAttrVal = AttributeUtilities.getAttrValue(activeTask.getTotalLease(), hostAttributeName); if(usedAttrVal==null || usedAttrVal.isEmpty()) return new Result(false, hostAttributeName+" attribute unavailable on host " + activeTask.getTotalLease().hostname() + " running co-task " + coTask); if(usedAttrVal.equals(targetHostAttrVal)) { return new Result(false, hostAttributeName+" " + targetHostAttrVal + " already used for another co-task " + coTask); } } } return new Result(true, ""); }@Override public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) { String targetHostAttrVal = getAttrValue(targetVM.getCurrAvailableResources()); if(targetHostAttrVal==null || targetHostAttrVal.isEmpty()) { return new Result(false, hostAttributeName + " attribute unavailable on host " + targetVM.getCurrAvailableResources().hostname()); } String requiredAttrVal = hostAttributeValueGetter.call(taskRequest.getId()); return targetHostAttrVal.equals(requiredAttrVal)? new Result(true, "") : new Result(false, "Host attribute " + hostAttributeName + ": required=" + requiredAttrVal + ", got=" + targetHostAttrVal); }@Override public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) { Collection runningTasks = targetVM.getRunningTasks(); if(runningTasks!=null && !runningTasks.isEmpty()) return new Result(false, "Already has " + runningTasks.size() + " tasks running on it"); Collection tasksCurrentlyAssigned = targetVM.getTasksCurrentlyAssigned(); if(tasksCurrentlyAssigned!=null && !tasksCurrentlyAssigned.isEmpty()) return new Result(false, "Already has " + tasksCurrentlyAssigned.size() + " assigned on it"); return new Result(true, ""); }public void shutdown() { System.out.println("Stopping down mesos driver"); Protos.Status status = mesosSchedulerDriver.stop(); isShutdown.set(true); }public static void main(String[] args) { if(args.length!=1) { System.err.println("Must provide one argument - Mesos master location string"); System.exit(1); } int numTasks=10; int numIters=5; BlockingQueue taskQueue = new LinkedBlockingQueue<>(); final TaskGenerator taskGenerator = new TaskGenerator(taskQueue, numIters, numTasks); final SampleFramework framework = new SampleFramework(taskQueue, args[0], // mesos master location string new Action1() { @Override public void call(String s) { taskGenerator.tasksCompleted.incrementAndGet(); } }, new Func1() { @Override public String call(String s) { return "sleep 2"; } }); long start = System.currentTimeMillis(); (new Thread(taskGenerator)).start(); new Thread(new Runnable() { @Override public void run() { framework.runAll(); } }).start(); while(taskGenerator.tasksCompleted.get() < (numIters*numTasks)) { System.out.println("NUM TASKS COMPLETED: " + taskGenerator.tasksCompleted.get() + " of " + (numIters*numTasks)); try{Thread.sleep(1000);}catch(InterruptedException ie){} } System.out.println("Took " + (System.currentTimeMillis()-start) + " mS to complete " + (numIters*numTasks) + " tasks"); framework.shutdown(); System.exit(0); }public boolean editMap(ConfigurationHandler configurationHandler) { String method = configurationHandler.getMethod().toUpperCase(); if (configurationHandlerMap.containsKey(Method.valueOf(method))) { configurationHandlerMap.put(Method.valueOf(method), configurationHandler); return true; } return false; }public static Intent newResponseIntent(Context context, Uri responseUri) { Intent intent = new Intent(context, LoginActivity.class); intent.setData(responseUri); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); return intent; }private void validateConfiguration(SessionConfiguration configuration) { String nullError = "%s must not be null"; String sampleError = "Please update your %s in the gradle.properties of the project before " + "using the Uber SDK Sample app. For a more secure storage location, " + "please investigate storing in your user home gradle.properties "; checkNotNull(configuration, String.format(nullError, "SessionConfiguration")); checkNotNull(configuration.getClientId(), String.format(nullError, "Client ID")); checkNotNull(configuration.getRedirectUri(), String.format(nullError, "Redirect URI")); checkState(!configuration.getClientId().equals("insert_your_client_id_here"), String.format(sampleError, "Client ID")); checkState(!configuration.getRedirectUri().equals("insert_your_redirect_uri_here"), String.format(sampleError, "Redirect URI")); }public void execute() { final CustomTabsIntent intent = new CustomTabsIntent.Builder().build(); customTabsHelper.openCustomTab(context, intent, uri, new CustomTabsHelper.BrowserFallback()); }private void load() { AccessToken accessToken = accessTokenStorage.getAccessToken(); if (accessToken != null) { AccessTokenSession session = new AccessTokenSession(sessionConfiguration, accessTokenStorage); rideRequestView.setSession(session); loadRideRequestView(); } else { login(); } }private boolean hasSpecializedHandlerIntents(Context context, Intent intent) { try { PackageManager pm = context.getPackageManager(); List handlers = pm.queryIntentActivities( intent, PackageManager.GET_RESOLVED_FILTER); if (handlers == null || handlers.size() == 0) { return false; } for (ResolveInfo resolveInfo : handlers) { IntentFilter filter = resolveInfo.filter; if (filter == null) continue; if (filter.countDataAuthorities() == 0 || filter.countDataPaths() == 0) continue; if (resolveInfo.activityInfo == null) continue; return true; } } catch (RuntimeException e) { Log.e(TAG, "Runtime exception while getting specialized handlers"); } return false; }@Nullable public String getPackageNameToUse(Context context) { if (packageNameToUse != null) return packageNameToUse; PackageManager pm = context.getPackageManager(); // Get default VIEW intent handler. Intent activityIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com")); ResolveInfo defaultViewHandlerInfo = pm.resolveActivity(activityIntent, 0); String defaultViewHandlerPackageName = null; if (defaultViewHandlerInfo != null) { defaultViewHandlerPackageName = defaultViewHandlerInfo.activityInfo.packageName; } // Get all apps that can handle VIEW intents. List resolvedActivityList = pm.queryIntentActivities(activityIntent, 0); List packagesSupportingCustomTabs = new ArrayList<>(); for (ResolveInfo info : resolvedActivityList) { Intent serviceIntent = new Intent(); serviceIntent.setAction(ACTION_CUSTOM_TABS_CONNECTION); serviceIntent.setPackage(info.activityInfo.packageName); if (pm.resolveService(serviceIntent, 0) != null) { packagesSupportingCustomTabs.add(info.activityInfo.packageName); } } // Now packagesSupportingCustomTabs contains all apps that can handle both VIEW intents // and service calls. if (packagesSupportingCustomTabs.isEmpty()) { packageNameToUse = null; } else if (packagesSupportingCustomTabs.size() == 1) { packageNameToUse = packagesSupportingCustomTabs.get(0); } else if (!TextUtils.isEmpty(defaultViewHandlerPackageName) && !hasSpecializedHandlerIntents(context, activityIntent) && packagesSupportingCustomTabs.contains(defaultViewHandlerPackageName)) { packageNameToUse = defaultViewHandlerPackageName; } else if (packagesSupportingCustomTabs.contains(STABLE_PACKAGE)) { packageNameToUse = STABLE_PACKAGE; } else if (packagesSupportingCustomTabs.contains(BETA_PACKAGE)) { packageNameToUse = BETA_PACKAGE; } else if (packagesSupportingCustomTabs.contains(DEV_PACKAGE)) { packageNameToUse = DEV_PACKAGE; } else if (packagesSupportingCustomTabs.contains(LOCAL_PACKAGE)) { packageNameToUse = LOCAL_PACKAGE; } return packageNameToUse; }public void openCustomTab( final Context context, final CustomTabsIntent customTabsIntent, final Uri uri, CustomTabFallback fallback) { final String packageName = getPackageNameToUse(context); if (packageName != null) { final CustomTabsServiceConnection connection = new CustomTabsServiceConnection() { @Override public void onCustomTabsServiceConnected(ComponentName componentName, CustomTabsClient client) { client.warmup(0L); // This prevents backgrounding after redirection customTabsIntent.intent.setPackage(packageName); customTabsIntent.intent.setData(uri); customTabsIntent.launchUrl(context, uri); } @Override public void onServiceDisconnected(ComponentName name) {} }; CustomTabsClient.bindCustomTabsService(context, packageName, connection); } else if (fallback != null) { fallback.openUri(context, uri); } else { Log.e(UberSdk.UBER_SDK_LOG_TAG, "Use of openCustomTab without Customtab support or a fallback set"); } }public void publishAdditionalModelData(JavaSparkContext sparkContext, PMML pmml, JavaRDD newData, JavaRDD pastData, Path modelParentPath, TopicProducer modelUpdateTopic) { // Do nothing by default }public static T loadInstanceOf(String implClassName, Class superClass, Class[] constructorTypes, Object[] constructorArgs) { try { Class configClass = loadClass(implClassName, superClass); Constructor constructor = configClass.getConstructor(constructorTypes); return constructor.newInstance(constructorArgs); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException e) { throw new IllegalArgumentException("No valid " + superClass + " binding exists", e); } catch (InvocationTargetException ite) { throw new IllegalStateException("Could not instantiate " + superClass + " due to exception", ite.getCause()); } }public static void deleteRecursively(Path rootDir) throws IOException { if (rootDir == null || !Files.exists(rootDir)) { return; } Files.walkFileTree(rootDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); }public void compute() { // Make sure only one attempts to build at one time if (solverUpdating.compareAndSet(false, true)) { executor.execute(LoggingCallable.log(() -> { try { log.info("Computing cached solver"); // Not as much hurry if one already exists boolean lowPriority = solver.get() != null; Solver newYTYSolver = LinearSystemSolver.getSolver(vectorPartitions.getVTV(lowPriority)); if (newYTYSolver != null) { log.info("Computed new solver {}", newYTYSolver); solver.set(newYTYSolver); } } finally { // Allow any threads waiting for initial model to proceed. // It's possible the solver is still null here if there is no input. solverInitialized.countDown(); solverUpdating.set(false); } }).asRunnable()); } }public static double cosineSimilarity(float[] x, float[] y, double normY) { int length = x.length; double dot = 0.0; double totalXSq = 0.0; for (int i = 0; i < length; i++) { double xi = x[i]; totalXSq += xi * xi; dot += xi * y[i]; } return dot / (Math.sqrt(totalXSq) * normY); }public static float[] computeUpdatedXu(Solver solver, double value, float[] Xu, float[] Yi, boolean implicit) { if (Yi == null) { return null; } boolean noXu = Xu == null; double Qui = noXu ? 0.0 : VectorMath.dot(Xu, Yi); // Qui' is the target, new value of Qui // 0.5 reflects a "don't know" state double targetQui = computeTargetQui(implicit, value, noXu ? 0.5 : Qui); if (Double.isNaN(targetQui)) { return null; } double dQui = targetQui - Qui; double[] dQuiYi = new double[Yi.length]; for (int i = 0; i < dQuiYi.length; i++) { dQuiYi[i] = Yi[i] * dQui; } double[] dXu = solver.solveDToD(dQuiYi); float[] newXu = noXu ? new float[dXu.length] : Xu.clone(); for (int i = 0; i < newXu.length; i++) { newXu[i] += dXu[i]; } return newXu; }private OMElement efetuaConsultaStatusBahia(final OMElement omElement) throws RemoteException { final NfeStatusServicoStub.NfeCabecMsg cabec = new NfeStatusServicoStub.NfeCabecMsg(); cabec.setCUF(DFUnidadeFederativa.BA.getCodigoIbge()); cabec.setVersaoDados(this.config.getVersao()); final NfeStatusServicoStub.NfeCabecMsgE cabecEnv = new NfeStatusServicoStub.NfeCabecMsgE(); cabecEnv.setNfeCabecMsg(cabec); final NfeStatusServicoStub.NfeDadosMsg dados = new NfeStatusServicoStub.NfeDadosMsg(); dados.setExtraElement(omElement); final NFAutorizador31 autorizador = NFAutorizador31.valueOfCodigoUF(DFUnidadeFederativa.BA); final String endpoint = autorizador.getNfeStatusServico(this.config.getAmbiente()); if (endpoint == null) { throw new IllegalArgumentException("Nao foi possivel encontrar URL para StatusServico " + DFModelo.NFE.name() + ", autorizador " + autorizador.name() + ", UF " + DFUnidadeFederativa.BA.name()); } return new NfeStatusServicoStub(endpoint).nfeStatusServicoNF(dados, cabecEnv).getExtraElement(); }public void receiveResultmdfeStatusServicoMDF( com.fincatto.documentofiscal.mdfe3.webservices.statusservico.MDFeStatusServicoStub.MdfeStatusServicoMDFResult result ) { }public MDFeRetorno encerramentoAssinado(final String chaveAcesso, final String eventoAssinadoXml) throws Exception { return this.wsEncerramento.encerramentoMdfeAssinado(chaveAcesso, eventoAssinadoXml); }public MDFeRetorno encerramento(final String chaveAcesso, final String numeroProtocolo, final String codigoMunicipio, final LocalDate dataEncerramento, final DFUnidadeFederativa unidadeFederativa) throws Exception { return this.wsEncerramento.encerraMdfe(chaveAcesso, numeroProtocolo, codigoMunicipio, dataEncerramento, unidadeFederativa); }public MDFeRetorno cancelaMdfe(final String chave, final String numeroProtocolo, final String motivo) throws Exception { return this.wsCancelamento.cancelaNota(chave, numeroProtocolo, motivo); }public void receiveResultmdfeRetRecepcao( com.fincatto.documentofiscal.mdfe3.webservices.retornorecepcao.MDFeRetRecepcaoStub.MdfeRetRecepcaoResult result ) { }public void receiveResultmdfeConsultaMDF( com.fincatto.documentofiscal.mdfe3.webservices.consulta.MDFeConsultaStub.MdfeConsultaMDFResult result ) { }public CTeRetornoCancelamento cancelaNota(final String chave, final String numeroProtocolo, final String motivo) throws Exception { return this.wsCancelamento.cancelaNota(chave, numeroProtocolo, motivo); }public void receiveResultcteRecepcaoEvento( com.fincatto.documentofiscal.cte300.webservices.recepcaoevento.RecepcaoEventoStub.CteRecepcaoEventoResult result ) { }public String getXmlAssinado(final String chaveAcesso, final String textoCorrecao, final int numeroSequencialEvento) throws Exception { final String cartaCorrecaoXML = this.gerarDadosCartaCorrecao(chaveAcesso, textoCorrecao, numeroSequencialEvento).toString(); return new AssinaturaDigital(this.config).assinarDocumento(cartaCorrecaoXML); }public void receiveResultcteRetRecepcao( com.fincatto.documentofiscal.cte300.webservices.retrecepcao.CteRetRecepcaoStub.CteRetRecepcaoResult result ) { }public void receiveResultcteRecepcaoLote( com.fincatto.documentofiscal.cte300.webservices.recepcao.CteRecepcaoStub.CteRecepcaoLoteResult result ) { }public NFRetornoConsultaCadastro consultaCadastro(final String cnpj, final DFUnidadeFederativa uf) throws Exception { return this.wsConsultaCadastro.consultaCadastro(cnpj, uf); }public NFRetornoEventoInutilizacao inutilizaNota(final int anoInutilizacaoNumeracao, final String cnpjEmitente, final String serie, final String numeroInicial, final String numeroFinal, final String justificativa, final DFModelo modelo) throws Exception { return this.wsInutilizacao.inutilizaNota(anoInutilizacaoNumeracao, cnpjEmitente, serie, numeroInicial, numeroFinal, justificativa, modelo); }public NFEnviaEventoRetorno cancelaNota(final String chave, final String numeroProtocolo, final String motivo) throws Exception { return this.wsCancelamento.cancelaNota(chave, numeroProtocolo, motivo); }public NFEnviaEventoRetorno corrigeNota(final String chaveDeAcesso, final String textoCorrecao, final int numeroSequencialEvento) throws Exception { return this.wsCartaCorrecao.corrigeNota(chaveDeAcesso, textoCorrecao, numeroSequencialEvento); }public NFStatusServicoConsultaRetorno consultaStatus(final DFUnidadeFederativa uf, final DFModelo modelo) throws Exception { return this.wsStatusConsulta.consultaStatus(uf, modelo); }public NFLoteEnvioRetornoDados enviaLote(final NFLoteEnvio lote) throws Exception { if (lote.getIndicadorProcessamento().equals(NFLoteIndicadorProcessamento.PROCESSAMENTO_SINCRONO) && lote.getNotas().size() > 1) { throw new IllegalArgumentException("Apenas uma nota permitida no modo sincrono!"); } else if (lote.getNotas().size() == 0) { throw new IllegalArgumentException("Nenhuma nota informada no envio do Lote!"); } return this.wsLoteEnvio.enviaLote(lote); }NFLoteEnvio getLoteAssinado(final NFLoteEnvio lote) throws Exception { // adiciona a chave e o dv antes de assinar for (final NFNota nota : lote.getNotas()) { final NFGeraChave geraChave = new NFGeraChave(nota); nota.getInfo().getIdentificacao().setCodigoRandomico(StringUtils.defaultIfBlank(nota.getInfo().getIdentificacao().getCodigoRandomico(), geraChave.geraCodigoRandomico())); nota.getInfo().getIdentificacao().setDigitoVerificador(geraChave.getDV()); nota.getInfo().setIdentificador(geraChave.getChaveAcesso()); } // assina o lote final String documentoAssinado = new AssinaturaDigital(this.config).assinarDocumento(lote.toString()); final NFLoteEnvio loteAssinado = new DFParser().loteParaObjeto(documentoAssinado); // verifica se nao tem NFCe junto com NFe no lote e gera qrcode (apos assinar mesmo, eh assim) int qtdNF = 0, qtdNFC = 0; for (final NFNota nota : loteAssinado.getNotas()) { switch (nota.getInfo().getIdentificacao().getModelo()) { case NFE: qtdNF++; break; case NFCE: final NFGeraQRCode geraQRCode = new NFGeraQRCode(nota, this.config); nota.setInfoSuplementar(new NFNotaInfoSuplementar()); nota.getInfoSuplementar().setQrCode(geraQRCode.getQRCode()); qtdNFC++; break; default: throw new IllegalArgumentException(String.format("Modelo de nota desconhecida: %s", nota.getInfo().getIdentificacao().getModelo())); } } // verifica se todas as notas do lote sao do mesmo modelo if ((qtdNF > 0) && (qtdNFC > 0)) { throw new IllegalArgumentException("Lote contendo notas de modelos diferentes!"); } return loteAssinado; }public void receiveResultnfeConsultaNF( com.fincatto.documentofiscal.nfe310.webservices.nota.consulta.NfeConsultaStub.NfeConsultaNFResult result) { }private java.util.Map getEnvelopeNamespaces(final org.apache.axiom.soap.SOAPEnvelope env) { final java.util.Map returnMap = new java.util.HashMap(); final java.util.Iterator namespaceIterator = env.getAllDeclaredNamespaces(); while (namespaceIterator.hasNext()) { final org.apache.axiom.om.OMNamespace ns = (org.apache.axiom.om.OMNamespace) namespaceIterator.next(); returnMap.put(ns.getPrefix(), ns.getNamespaceURI()); } return returnMap; }@SuppressWarnings("unused") private org.apache.axiom.soap.SOAPEnvelope toEnvelope(final org.apache.axiom.soap.SOAPFactory factory) { return factory.getDefaultEnvelope(); }public void receiveResultmdfeConsNaoEnc( com.fincatto.documentofiscal.mdfe3.webservices.consultanaoencerrado.MDFeConsNaoEncStub.MdfeConsNaoEncResult result ) { }public void receiveResultcteConsultaCT( com.fincatto.documentofiscal.cte300.webservices.consulta.CteConsultaStub.CteConsultaCTResult result ) { }public void receiveResultmdfeRecepcaoEvento( com.fincatto.documentofiscal.mdfe3.webservices.recepcaoevento.MDFeRecepcaoEventoStub.MdfeRecepcaoEventoResult result ) { }public void receiveResultcteInutilizacaoCT( com.fincatto.documentofiscal.cte300.webservices.inutilizacao.CteInutilizacaoStub.CteInutilizacaoCTResult result ) { }public void receiveResultmdfeRecepcaoLote( com.fincatto.documentofiscal.mdfe3.webservices.recepcao.MDFeRecepcaoStub.MdfeRecepcaoLoteResult result ) { }public void receiveResultcteRecepcaoOS( com.fincatto.documentofiscal.cte300.webservices.recepcaoOS.CteRecepcaoOSStub.CteRecepcaoOSResult result ) { }public String process(String filename, String source, Config conf) throws Exception { return process(filename, source, conf, getClass().getClassLoader()); }public ApiTool raml(Options options, Consumer raml) { this.ramlOptions = Objects.requireNonNull(options, "Options required."); this.raml = raml; return this; }public ApiTool raml(String path, Consumer raml) { return raml(new Options(path, options), raml); }public ApiTool swagger(Options options, Consumer swagger) { this.swaggerOptions = Objects.requireNonNull(options, "Options required."); this.swagger = swagger; return this; }public ApiTool swagger(String path, Consumer swagger) { return swagger(new Options(path, options), swagger); }public Scanner scan(final Class type) { // standard vs guice annotations if (type == Named.class || type == com.google.inject.name.Named.class) { serviceTypes.add(Named.class); serviceTypes.add(com.google.inject.name.Named.class); } else if (type == Singleton.class || type == com.google.inject.Singleton.class) { serviceTypes.add(Singleton.class); serviceTypes.add(com.google.inject.Singleton.class); } else { serviceTypes.add(type); } return this; }public List parse(String application) throws Exception { return new BytecodeRouteParser(loader, dir).parse(application).stream() .filter(filter) .collect(Collectors.toList()); }public Pac4j form(String pattern) { return clientInternal(pattern, conf -> { showDevLogin = true; return new FormClient("/login", new SimpleTestUsernamePasswordAuthenticator()); }, null); }public Pac4j unauthenticated(Supplier provider) { requireNonNull(provider, "Unauthenticated provider required."); return unauthenticated(req -> provider.get()); }public Jackson module(final Module module) { requireNonNull(module, "Jackson Module is required."); modules.add(binder -> binder.addBinding().toInstance(module)); return this; }@Nonnull public static Result with(final Status status) { requireNonNull(status, "A HTTP status is required."); return new Result().status(status); }public Cassandra doWithCluster(final Consumer configurer) { requireNonNull(configurer, "Cluster conf callbackrequired."); return doWithCluster((cc, c) -> configurer.accept(cc)); }private void shutdownGracefully(final Iterator iterator) { if (iterator.hasNext()) { EventExecutorGroup group = iterator.next(); if (!group.isShuttingDown()) { group.shutdownGracefully().addListener(future -> { if (!future.isSuccess()) { log.debug("shutdown of {} resulted in exception", group, future.cause()); } shutdownGracefully(iterator); }); } } }public Quartz with(final Class jobClass, final BiConsumer> configurer) { requireNonNull(jobClass, "Job class is required."); JobBuilder job = JobBuilder.newJob(jobClass) .withIdentity( JobKey.jobKey(jobClass.getSimpleName(), jobClass.getPackage().getName()) ); TriggerBuilder trigger = TriggerBuilder.newTrigger() .withIdentity( TriggerKey.triggerKey(jobClass.getSimpleName(), jobClass.getPackage().getName()) ); configurer.accept(job, trigger); return with(job.build(), trigger.build()); }public Quartz with(final JobDetail job, final Trigger trigger) { requireNonNull(job, "Job is required."); requireNonNull(trigger, "Trigger is required."); jobMap.put(job, trigger); return this; }public jOOQ doWith(Consumer configurer) { return doWith((configuration, conf) -> configurer.accept(configuration)); }public Jdbi doWith(Consumer configurer) { return doWith((dbi, conf) -> configurer.accept(dbi)); }protected void send(final Request req, final Response rsp, final Asset asset) throws Throwable { rsp.send(asset); }@Override public RewrittenStatement rewrite(final String sql, final Binding params, final StatementContext ctx) { final ParsedStatement stmt = new ParsedStatement(); try { final String parsedSql = parseString(sql, stmt, params); return new MyRewrittenStatement(parsedSql, stmt, ctx); } catch (IllegalArgumentException e) { throw new UnableToCreateStatementException( "Exception parsing for named parameter replacement", e, ctx); } }public Jdbi3 doWith(Consumer configurer) { return doWith((jdbi, conf) -> configurer.accept(jdbi)); }public static Status valueOf(final int statusCode) { Integer key = Integer.valueOf(statusCode); Status status = statusMap.get(key); return status == null? new Status(key, key.toString()) : status; }public RouteMethod param(String name, Consumer customizer) { parameters().stream() .filter(p -> name.equals(p.name())) .findFirst() .ifPresent(customizer); return this; }public RouteMethod attribute(String name, Object value) { if (this.attributes == null) { this.attributes = new LinkedHashMap<>(); } this.attributes.put(name, value); return this; }public RouteMethod attributes(Map attributes) { if (attributes != null) { if (this.attributes == null) { this.attributes = new LinkedHashMap<>(); } this.attributes.putAll(attributes); } return this; }public static ClassLoader classLoader(final ClassLoader parent, File projectDir) throws IOException { requireNonNull(parent, "ClassLoader required."); File publicDir = new File(projectDir, "public"); if(publicDir.exists()) { return new URLClassLoader(new URL[]{publicDir.toURI().toURL()}, parent); } return parent; }public static ClassLoader classLoader(final ClassLoader parent) throws IOException { return classLoader(parent, new File(System.getProperty("user.dir"))); }@Nonnull public View put(final Map values) { values.forEach((k, v) -> model.put(k, v)); return this; }@Nonnull public View put(final String name, final Object value) { requireNonNull(name, "Model name is required."); model.put(name, value); return this; }@Nonnull public CompletableFuture> send(final Object data) { return event(data).send(); }@Nonnull public Optional lastEventId(final Class type) { return lastEventId.toOptional(type); }private Model doModel(Type type, Model model) { Map properties = model.getProperties(); if (properties != null) { BeanDescription desc = Json.mapper().getSerializationConfig() .introspect(Json.mapper().constructType(type)); for (BeanPropertyDefinition beanProperty : desc.findProperties()) { Property property = properties.get(beanProperty.getName()); if (property != null) { property.setRequired(beanProperty.isRequired()); } } } return model; }public TransactionalRequest handle(String name) { this.handleKey = Key.get(Handle.class, Names.named(name)); return this; }private void write(final Path path, final List sequence) throws IOException { log.debug("writing: {}", path.normalize().toAbsolutePath()); path.toFile().getParentFile().mkdirs(); Files.write(path, sequence); }private Tuple parse(final String value) { Matcher matcher = SIZE.matcher(value); if (matcher.find()) { String number = matcher.group(1); String unit = matcher.group(_3); boolean round = get("css.round"); Number num = Double.parseDouble(number); return new Tuple(round ? Math.round(num.doubleValue()) : num, unit); } return null; }private CharSequence css(final String id, final Element svg) { Throwing.Function, Tuple>> viewBox = Throwing ., Tuple>>throwingFunction(name -> { String vbox = svg.attr(name); String[] dimension = vbox.split("\\s+"); return new Tuple(parse(dimension[2]), parse(dimension[_3])); }).memoized(); Tuple w = Optional.ofNullable(Strings.emptyToNull(svg.attr("width"))) .map(this::parse) .orElseGet(() -> viewBox.apply("viewBox")._1); Tuple h = Optional.ofNullable(Strings.emptyToNull(svg.attr("height"))) .map(this::parse) .orElseGet(() -> viewBox.apply("viewBox")._2); StringBuilder css = new StringBuilder(); css.append(get("css.prefix").toString()).append(".").append(id) .append(" {\n width: ").append(w._1).append(w._2).append(";\n") .append(" height: ").append(h._1).append(h._2).append(";\n}"); return css; }private Map attrs(final String path, final String... without) { Map attrs = new LinkedHashMap<>(get(path)); Arrays.asList(without).forEach(attrs::remove); return attrs; }public XSS css(final CssStringEscapeType type, final CssStringEscapeLevel level) { this.csslevel = requireNonNull(level, "Level required."); this.csstype = requireNonNull(type, "Type required."); return this; }public XSS json(final JsonEscapeType type, final JsonEscapeLevel level) { this.jsonlevel = requireNonNull(level, "Level required."); this.jsontype = requireNonNull(type, "Type required."); return this; }public XSS html(final HtmlEscapeType type, final HtmlEscapeLevel level) { this.htmllevel = requireNonNull(level, "Level required."); this.htmltype = requireNonNull(type, "Type required."); return this; }public XSS js(final JavaScriptEscapeType type, final JavaScriptEscapeLevel level) { this.jslevel = requireNonNull(level, "Level required."); this.jstype = requireNonNull(type, "Type required."); return this; }public static Requery kotlin(final String name, final EntityModel model) { return new Requery(name, KotlinEntityDataStore.class, model, conf -> new KotlinEntityDataStore<>(conf)); }public static Requery completionStage(final String name, final EntityModel model) { return new Requery(name, CompletionStageEntityStore.class, model, conf -> new CompletableEntityStore(new EntityDataStore<>(conf))); }public static Requery reactor(final String name, final EntityModel model) { return new Requery(name, ReactorEntityStore.class, model, conf -> new ReactorEntityStore<>(new EntityDataStore<>(conf))); }public static Requery reactive(final String name, final EntityModel model) { return new Requery(name, ReactiveEntityStore.class, model, conf -> ReactiveSupport.toReactiveStore(new EntityDataStore<>(conf))); }@Override public int read(final byte[] b, int off, int len) throws IOException { int read = 0; while (len > 0) { if (encoderOut.position() > 0) { encoderOut.flip(); int c = Math.min(encoderOut.remaining(), len); encoderOut.get(b, off, c); off += c; len -= c; read += c; encoderOut.compact(); } else { if (!endOfInput && (lastCoderResult == null || lastCoderResult.isUnderflow())) { encoderIn.compact(); int position = encoderIn.position(); // We don't use Reader#read(CharBuffer) here because it is more efficient // to write directly to the underlying char array (the default implementation // copies data to a temporary char array). int c = reader.read(encoderIn.array(), position, encoderIn.remaining()); if (c == -1) { endOfInput = true; } else { encoderIn.position(position + c); } encoderIn.flip(); } lastCoderResult = encoder.encode(encoderIn, encoderOut, endOfInput); if (endOfInput && encoderOut.position() == 0) { break; } } } return read == 0 && endOfInput ? -1 : read; }public Hbv doWith(final Consumer configurer) { requireNonNull(configurer, "Configurer callback is required."); this.configurer = (hvc, conf) -> configurer.accept(hvc); return this; }public RamlResponse response(Integer status) { if (responses == null) { responses = new LinkedHashMap<>(); } RamlResponse response = responses.get(status); if (response == null) { response = new RamlResponse(); responses.put(status, response); } return response; }public RamlParameter headerParameter(String name) { if (headers == null) { headers = new LinkedHashMap<>(); } RamlParameter param = headers.get(name); if (param == null) { param = new RamlParameter(name); headers.put(name, param); } return param; }public RamlParameter formParameter(String name) { if (formParameters == null) { formParameters = new LinkedHashMap<>(); } RamlParameter param = formParameters.get(name); if (param == null) { param = new RamlParameter(name); formParameters.put(name, param); } return param; }public RamlParameter queryParameter(String name) { if (queryParameters == null) { queryParameters = new LinkedHashMap<>(); } RamlParameter param = queryParameters.get(name); if (param == null) { param = new RamlParameter(name); queryParameters.put(name, param); } return param; }public void setMediaType(final List mediaType) { this.mediaType = mediaType == null ? null : (mediaType.isEmpty() ? null : mediaType); }static Throwing.Runnable runEnhancer() { return () -> { Set packages = PKG.getAndSet(null); if (packages != null) { EbeanEnhancer.newEnhancer().run(packages); } }; }public void setMediaType(final String mediaType, RamlType body) { if (this.mediaType == null) { this.mediaType = new LinkedHashMap<>(); } this.mediaType.put(mediaType, body); }public RouteResponse status(final Map status) { if (status != null) { if (this.status == null) { this.status = new LinkedHashMap<>(); this.status.putAll(status); } } return this; }public int statusCode() { return status().entrySet().stream() .map(it -> it.getKey()) .filter(code -> code >= 200 && code < 400) .findFirst() .orElseGet(() -> type() == void.class ? 204 : 200); }public Map status() { return Optional.ofNullable(status).orElse(ImmutableMap.of()); }public String toYaml() throws IOException { YAMLMapper mapper = new YAMLMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, false); mapper.configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true); return "#%RAML 1.0\n" + mapper.writer().withDefaultPrettyPrinter().writeValueAsString(this); }public RamlType define(Type type) { if (types == null) { types = new LinkedHashMap<>(); } Type componentType = componentType(type); String typeName = MoreTypes.getRawType(componentType).getSimpleName(); RamlType ramlType = RamlType.valueOf(typeName); if (ramlType.isObject()) { RamlType existing = types.get(typeName); if (existing == null) { ModelConverters converter = ModelConverters.getInstance(); Property property = converter.readAsProperty(componentType); Map args = new EnumMap<>( PropertyBuilder.PropertyId.class); for (Map.Entry entry : converter.readAll(componentType).entrySet()) { define(entry.getKey(), entry.getValue()); } ramlType = define(typeName, PropertyBuilder.toModel(PropertyBuilder.merge(property, args))); } else { ramlType = existing; } } return type != componentType ? ramlType.toArray() : ramlType; }public RamlPath path(String pattern) { RamlPath path = resources.get(pattern); if (path == null) { path = new RamlPath(); resources.put(pattern, path); } return path; }public void resolve(@Nullable final Object value) { if (value == null) { handler.handle(null, null); } else { Result result; if (value instanceof Result) { super.set(value); result = (Result) value; } else { super.set(value); result = clone(); } handler.handle(result, null); } }public Auth basic(final String pattern, final Class> authenticator) { bindings.put(pattern, (binder, config) -> { TypeLiteral> usernamePasswordAuthenticator = new TypeLiteral>() { }; binder.bind(usernamePasswordAuthenticator.getRawType()).to(authenticator); bindProfile(binder, CommonProfile.class); Multibinder.newSetBinder(binder, Client.class) .addBinding().toProvider(BasicAuth.class); return new AuthFilter(IndirectBasicAuthClient.class, CommonProfile.class); }); return this; }public Auth form(final String pattern, final Class> authenticator) { bindings.put(pattern, (binder, conf) -> { TypeLiteral> usernamePasswordAuthenticator = new TypeLiteral>() { }; binder.bind(usernamePasswordAuthenticator.getRawType()).to(authenticator); bindProfile(binder, CommonProfile.class); Multibinder.newSetBinder(binder, Client.class) .addBinding().toProvider(FormAuth.class); return new FormFilter(conf.getString("auth.form.loginUrl"), conf.getString("application.path") + authCallbackPath(conf)); }); return this; }public Thl doWith(final Consumer callback) { requireNonNull(callback, "Callback required."); return doWith((e, c) -> callback.accept(e)); }public Micrometer doWith(@Nonnull final Consumer configurer) { return doWith((registry, conf) -> configurer.accept(registry)); }public Hbs doWith(final Consumer callback) { requireNonNull(callback, "Configurer is required."); return doWith((hbs, conf) -> callback.accept(hbs)); }public FileEventOptions kind(final WatchEvent.Kind kind) { requireNonNull(kind, "WatchEvent.Kind required."); kinds.add(kind); return this; }public static RamlType valueOf(String name) { switch (name.toLowerCase()) { case "boolean": return BOOLEAN; case "byte": case "short": case "int": case "integer": case "long": return INTEGER; case "float": case "double": return NUMBER; case "char": case "character": case "string": return STRING; case "file": case "upload": case "path": case "binary": return FILE; case "date": case "datetime": case "localdatetime": return DATE_TIME; } return new RamlType("object", name); }public RamlType newProperty(String name, String type, boolean required, String... values) { if (properties == null) { properties = new LinkedHashMap<>(); } if (values.length > 0) { properties.put(required ? name : name + "?", ImmutableMap.of("enum", values)); } else { properties.put(required ? name : name + "?", type); } return this; }private void register(final Path dir) throws IOException { WatchKey key = dir.register(watcher, new Kind[]{ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY }, HIGH); keys.put(key, dir); }public String summary(Map> result, Path outDir, String dist, long duration, String... extraInfo) { StringBuilder buffer = new StringBuilder(); buffer.append("Summary:\n"); long seconds = Duration.ofMillis(duration).getSeconds(); String took = seconds > 0 ? seconds + "s" : duration + "ms"; buffer.append("Pipeline: ").append(pipeline(dist)).append("\n"); buffer.append("Time: ").append(took).append("\n"); buffer.append("Output: ").append(outDir).append("\n"); Stream.of(extraInfo).forEach(line -> buffer.append(line).append("\n")); int w1 = result.keySet().stream() .map(it -> it.length() + 2) .max(Integer::compareTo) .orElse(0); int mw1 = Math.max(w1, "Fileset".length() + 2); int w2 = result.values().stream() .flatMap(List::stream) .map(file -> outDir.relativize(file.toPath()).toString()) .map(String::length) .max(Integer::compareTo) .orElse(0); buffer.append(format(w1, w2, "Fileset", "Output", "Size")); result.forEach((fileset, files) -> { if (files.size() > 0) { // Head buffer.append(format(mw1, w2, " " + fileset, "", "")); // Tail files.forEach(file -> buffer.append(format(mw1, w2, "", outDir.relativize(file.toPath()), AssetCompiler.humanReadableByteCount(file.length())))); } }); return buffer.toString(); }public Map> build(final String dist, final File dir) throws Exception { log.debug("{} aggregators: {}", dist, aggregators); aggregators(aggregators, conf); return buildInternal(dist, dir); }public LiveReload register(final Path path, final String... includes) { if (Files.exists(path)) { paths.add(new Object[]{path, Arrays.asList(includes)}); } return this; }@RequestMapping(value = "/api/todolist", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity> getAllTodoItems() { return new ResponseEntity<>(todoList, HttpStatus.OK); }@Bean @Scope(BeanDefinition.SCOPE_SINGLETON) @ConditionalOnMissingBean(AADAuthenticationFilter.class) public AADAuthenticationFilter azureADJwtTokenFilter() { LOG.info("AzureADJwtTokenFilter Constructor."); return new AADAuthenticationFilter(aadAuthProps, serviceEndpointsProps, getJWTResourceRetriever()); }public ServiceEndpoints getServiceEndpoints(String environment) { Assert.notEmpty(endpoints, "No service endpoints found"); if (!endpoints.containsKey(environment)) { throw new IllegalArgumentException(environment + " is not found in the configuration," + " only following environments are supported: " + endpoints.keySet()); } return endpoints.get(environment); }public Set convertGroupsToGrantedAuthorities(final List groups) { // Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities final Set mappedAuthorities = groups.stream().filter(this::isValidUserGroupToGrantAuthority) .map(userGroup -> new SimpleGrantedAuthority(DEFAULT_ROLE_PREFIX + userGroup.getDisplayName())) .collect(Collectors.toCollection(LinkedHashSet::new)); if (mappedAuthorities.isEmpty()) { mappedAuthorities.add(DEFAULT_AUTHORITY); } return mappedAuthorities; }private boolean isMatchingUserGroupKey(final JsonNode node) { return node.get(aadAuthenticationProperties.getUserGroup().getKey()).asText() .equals(aadAuthenticationProperties.getUserGroup().getValue()); }@SuppressFBWarnings("UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR") private void populateProperties(ConfigurableEnvironment environment, VcapPojo[] pojos) { final Map map = new HashMap<>(); populateDefaultStorageProperties(map, findPojoForServiceType(VcapServiceType.AZURE_STORAGE, pojos)); populateDefaultServiceBusProperties(map, findPojoForServiceType(VcapServiceType.AZURE_SERVICEBUS, pojos)); populateDefaultDocumentDBProperties(map, findPojoForServiceType(VcapServiceType.AZURE_DOCUMENTDB, pojos)); addOrReplace(environment.getPropertySources(), map); }public static String getUserAgent(String serviceName, boolean allowTelemetry) { String macAddress = "Not Collected"; if (allowTelemetry) { macAddress = GetHashMac.getHashMac(); } return String.format(serviceName + " MacAddressHash:%s", macAddress); }@SuppressWarnings("deprecation") public WriteConcern getWriteConcern() { WriteConcern retVal; if (writeConcern != null) { retVal = writeConcern; } else if (w != 0 || wtimeout != 0 || fsync | j) { retVal = WriteConcern.ACKNOWLEDGED; if (w != 0) { retVal = retVal.withW(w); } if (wtimeout != 0) { retVal = retVal.withWTimeout(wtimeout, TimeUnit.MILLISECONDS); } if (fsync) { retVal = retVal.withFsync(fsync); } if (j) { retVal = retVal.withJ(j); } } else if (safe) { retVal = WriteConcern.ACKNOWLEDGED; } else { retVal = WriteConcern.UNACKNOWLEDGED; } return retVal; }public MongoOptions copy() { MongoOptions m = new MongoOptions(); m.connectionsPerHost = connectionsPerHost; m.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier; m.maxWaitTime = maxWaitTime; m.connectTimeout = connectTimeout; m.socketFactory = socketFactory; m.socketTimeout = socketTimeout; m.socketKeepAlive = socketKeepAlive; m.readPreference = readPreference; m.writeConcern = writeConcern; m.safe = safe; m.w = w; m.wtimeout = wtimeout; m.fsync = fsync; m.j = j; m.dbDecoderFactory = dbDecoderFactory; m.dbEncoderFactory = dbEncoderFactory; m.description = description; m.cursorFinalizerEnabled = cursorFinalizerEnabled; m.alwaysUseMBeans = alwaysUseMBeans; m.requiredReplicaSetName = requiredReplicaSetName; return m; }public void reset() { connectionsPerHost = 10; threadsAllowedToBlockForConnectionMultiplier = 5; maxWaitTime = 1000 * 60 * 2; connectTimeout = 1000 * 10; socketFactory = SocketFactory.getDefault(); socketTimeout = 0; socketKeepAlive = false; readPreference = null; writeConcern = null; safe = false; w = 0; wtimeout = 0; fsync = false; j = false; dbDecoderFactory = DefaultDBDecoder.FACTORY; dbEncoderFactory = DefaultDBEncoder.FACTORY; description = null; cursorFinalizerEnabled = true; alwaysUseMBeans = false; requiredReplicaSetName = null; }public static Builder builder(final ClientSessionOptions options) { notNull("options", options); Builder builder = new Builder(); builder.causallyConsistent = options.isCausallyConsistent(); builder.defaultTransactionOptions = options.getDefaultTransactionOptions(); return builder; }public static Codec> createCodec(final Class fullDocumentClass, final CodecRegistry codecRegistry) { return new ChangeStreamDocumentCodec(fullDocumentClass, codecRegistry); }@BsonIgnore @Nullable public String getDatabaseName() { if (namespaceDocument == null) { return null; } if (!namespaceDocument.containsKey("db")) { return null; } return namespaceDocument.getString("db").getValue(); }@BsonIgnore @Nullable public MongoNamespace getNamespace() { if (namespaceDocument == null) { return null; } if (!namespaceDocument.containsKey("db") || !namespaceDocument.containsKey("coll")) { return null; } return new MongoNamespace(namespaceDocument.getString("db").getValue(), namespaceDocument.getString("coll").getValue()); }public PushOptions sortDocument(@Nullable final Bson sortDocument) { if (sort != null) { throw new IllegalStateException("sortDocument can not be set if sort already is"); } this.sortDocument = sortDocument; return this; }public PushOptions sort(@Nullable final Integer sort) { if (sortDocument != null) { throw new IllegalStateException("sort can not be set if sortDocument already is"); } this.sort = sort; return this; }void remove() { fs.getFilesCollection().remove(new BasicDBObject("_id", id)); fs.getChunksCollection().remove(new BasicDBObject("files_id", id)); }public long writeTo(final OutputStream out) throws IOException { int nc = numChunks(); for (int i = 0; i < nc; i++) { out.write(getChunk(i)); } return length; }public long writeTo(final File file) throws IOException { FileOutputStream out = null; try { out = new FileOutputStream(file); return writeTo(out); } finally { if (out != null) { out.close(); } } }public BsonDocument asDocument() { BsonDocument collation = new BsonDocument(); if (locale != null) { collation.put("locale", new BsonString(locale)); } if (caseLevel != null) { collation.put("caseLevel", new BsonBoolean(caseLevel)); } if (caseFirst != null) { collation.put("caseFirst", new BsonString(caseFirst.getValue())); } if (strength != null) { collation.put("strength", new BsonInt32(strength.getIntRepresentation())); } if (numericOrdering != null) { collation.put("numericOrdering", new BsonBoolean(numericOrdering)); } if (alternate != null) { collation.put("alternate", new BsonString(alternate.getValue())); } if (maxVariable != null) { collation.put("maxVariable", new BsonString(maxVariable.getValue())); } if (normalization != null) { collation.put("normalization", new BsonBoolean(normalization)); } if (backwards != null) { collation.put("backwards", new BsonBoolean(backwards)); } return collation; }public AggregateExplainOperation hint(final BsonValue hint) { isTrueArgument("BsonString or BsonDocument", hint == null || hint.isDocument() || hint.isString()); this.hint = hint; return this; }private byte[] getBytes() { byte[] bytes = new byte[15]; long mask = 0x00000000000000ff; for (int i = 14; i >= 7; i--) { bytes[i] = (byte) ((low & mask) >>> ((14 - i) << 3)); mask = mask << 8; } mask = 0x00000000000000ff; for (int i = 6; i >= 1; i--) { bytes[i] = (byte) ((high & mask) >>> ((6 - i) << 3)); mask = mask << 8; } mask = 0x0001000000000000L; bytes[0] = (byte) ((high & mask) >>> 48); return bytes; }public BigDecimal bigDecimalValue() { if (isNaN()) { throw new ArithmeticException("NaN can not be converted to a BigDecimal"); } if (isInfinite()) { throw new ArithmeticException("Infinity can not be converted to a BigDecimal"); } BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck(); // If the BigDecimal is 0, but the Decimal128 is negative, that means we have -0. if (isNegative() && bigDecimal.signum() == 0) { throw new ArithmeticException("Negative zero can not be converted to a BigDecimal"); } return bigDecimal; }public static Decimal128 parse(final String value) { String lowerCasedValue = value.toLowerCase(); if (NaN_STRINGS.contains(lowerCasedValue)) { return NaN; } if (NEGATIVE_NaN_STRINGS.contains(lowerCasedValue)) { return NEGATIVE_NaN; } if (POSITIVE_INFINITY_STRINGS.contains(lowerCasedValue)) { return POSITIVE_INFINITY; } if (NEGATIVE_INFINITY_STRINGS.contains(lowerCasedValue)) { return NEGATIVE_INFINITY; } return new Decimal128(new BigDecimal(value), value.charAt(0) == '-'); }protected void checkPreconditions(final String methodName, final BsonType type) { if (isClosed()) { throw new IllegalStateException("BsonWriter is closed"); } verifyBSONType(methodName, type); }protected void verifyName(final String expectedName) { readBsonType(); String actualName = readName(); if (!actualName.equals(expectedName)) { throw new BsonSerializationException(format("Expected element name to be '%s', not '%s'.", expectedName, actualName)); } }protected void verifyBSONType(final String methodName, final BsonType requiredBsonType) { if (state == State.INITIAL || state == State.SCOPE_DOCUMENT || state == State.TYPE) { readBsonType(); } if (state == State.NAME) { // ignore name skipName(); } if (state != State.VALUE) { throwInvalidState(methodName, State.VALUE); } if (currentBsonType != requiredBsonType) { throw new BsonInvalidOperationException(format("%s can only be called when CurrentBSONType is %s, " + "not when CurrentBSONType is %s.", methodName, requiredBsonType, currentBsonType)); } }protected void throwInvalidState(final String methodName, final State... validStates) { String validStatesString = StringUtils.join(" or ", asList(validStates)); String message = format("%s can only be called when State is %s, not when State is %s.", methodName, validStatesString, state); throw new BsonInvalidOperationException(message); }protected void throwInvalidContextType(final String methodName, final BsonContextType actualContextType, final BsonContextType... validContextTypes) { String validContextTypesString = StringUtils.join(" or ", asList(validContextTypes)); String message = format("%s can only be called when ContextType is %s, not when ContextType is %s.", methodName, validContextTypesString, actualContextType); throw new BsonInvalidOperationException(message); }public int pipe(final OutputStream os) throws IOException { WritableByteChannel channel = Channels.newChannel(os); return channel.write(getBufferForInternalBytes()); }@Override public void close() { closed = true; Iterator iter = available.iterator(); while (iter.hasNext()) { T t = iter.next(); close(t); iter.remove(); } }@Override public T get(final long timeout, final TimeUnit timeUnit) { if (closed) { throw new IllegalStateException("The pool is closed"); } if (!acquirePermit(timeout, timeUnit)) { throw new MongoTimeoutException(String.format("Timeout waiting for a pooled item after %d %s", timeout, timeUnit)); } T t = available.pollLast(); if (t == null) { t = createNewAndReleasePermitIfFailure(false); } return t; }@Override public void release(final T t, final boolean prune) { if (t == null) { throw new IllegalArgumentException("Can not return a null item to the pool"); } if (closed) { close(t); return; } if (prune) { close(t); } else { available.addLast(t); } releasePermit(); }public static TransactionOptions merge(final TransactionOptions options, final TransactionOptions defaultOptions) { notNull("options", options); notNull("defaultOptions", defaultOptions); return TransactionOptions.builder() .writeConcern(options.getWriteConcern() == null ? defaultOptions.getWriteConcern() : options.getWriteConcern()) .readConcern(options.getReadConcern() == null ? defaultOptions.getReadConcern() : options.getReadConcern()) .readPreference(options.getReadPreference() == null ? defaultOptions.getReadPreference() : options.getReadPreference()) .build(); }@SuppressWarnings("unchecked") private List constructValuesList(final Object key, final Class clazz, final List defaultValue) { List value = get(key, List.class); if (value == null) { return defaultValue; } for (Object item : value) { if (!clazz.isAssignableFrom(item.getClass())) { throw new ClassCastException(format("List element cannot be cast to %s", clazz.getName())); } } return (List) value; }@SuppressWarnings("unchecked") private T getEmbeddedValue(final List keys, final Class clazz, final T defaultValue) { Object value = this; Iterator keyIterator = keys.iterator(); while (keyIterator.hasNext()) { Object key = keyIterator.next(); value = ((Document) value).get(key); if (!(value instanceof Document)) { if (value == null) { return defaultValue; } else if (keyIterator.hasNext()) { throw new ClassCastException(format("At key %s, the value is not a Document (%s)", key, value.getClass().getName())); } } } return clazz != null ? clazz.cast(value) : (T) value; }public static WriteConcernResult unacknowledged() { return new WriteConcernResult() { @Override public boolean wasAcknowledged() { return false; } @Override public int getCount() { throw getUnacknowledgedWriteException(); } @Override public boolean isUpdateOfExisting() { throw getUnacknowledgedWriteException(); } @Override public BsonValue getUpsertedId() { throw getUnacknowledgedWriteException(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WriteConcernResult that = (WriteConcernResult) o; return !that.wasAcknowledged(); } @Override public int hashCode() { return 1; } @Override public String toString() { return "UnacknowledgedWriteResult{}"; } private UnsupportedOperationException getUnacknowledgedWriteException() { return new UnsupportedOperationException("Cannot get information about an unacknowledged write"); } }; }public static WriteConcernResult acknowledged(final int count, final boolean isUpdateOfExisting, @Nullable final BsonValue upsertedId) { return new WriteConcernResult() { @Override public boolean wasAcknowledged() { return true; } @Override public int getCount() { return count; } @Override public boolean isUpdateOfExisting() { return isUpdateOfExisting; } @Override @Nullable public BsonValue getUpsertedId() { return upsertedId; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WriteConcernResult that = (WriteConcernResult) o; if (!that.wasAcknowledged()) { return false; } if (count != that.getCount()) { return false; } if (isUpdateOfExisting != that.isUpdateOfExisting()) { return false; } if (upsertedId != null ? !upsertedId.equals(that.getUpsertedId()) : that.getUpsertedId() != null) { return false; } return true; } @Override public int hashCode() { int result = count; result = 31 * result + (isUpdateOfExisting ? 1 : 0); result = 31 * result + (upsertedId != null ? upsertedId.hashCode() : 0); return result; } @Override public String toString() { return "AcknowledgedWriteResult{" + "count=" + count + ", isUpdateOfExisting=" + isUpdateOfExisting + ", upsertedId=" + upsertedId + '}'; } }; }public ConnectionDescription withConnectionId(final ConnectionId connectionId) { notNull("connectionId", connectionId); return new ConnectionDescription(connectionId, serverVersion, maxWireVersion, serverType, maxBatchCount, maxDocumentSize, maxMessageSize, compressors); }public void updateOne(final DBObject update) { bulkWriteOperation.addRequest(new UpdateRequest(query, update, false, upsert, queryCodec, collation, arrayFilters)); }protected Object parseArray(final String name) { if (name != null) { _callback.arrayStart(name); } else { _callback.arrayStart(); } read('['); int i = 0; char current = get(); while (current != ']') { String elemName = String.valueOf(i++); Object elem = parse(elemName); doCallback(elemName, elem); if ((current = get()) == ',') { read(','); } else if (current == ']') { break; } else { throw new JSONParseException(s, pos); } } read(']'); return _callback.arrayDone(); }public void parseExponent() { // get past E pos++; if (check('-') || check('+')) { pos++; } outer: while (pos < s.length()) { switch (s.charAt(pos)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': pos++; break; default: break outer; } } }public Number parseNumber() { get(); int start = this.pos; boolean isDouble = false; if (check('-') || check('+')) { pos++; } outer: while (pos < s.length()) { switch (s.charAt(pos)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': pos++; break; case '.': isDouble = true; parseFraction(); break; case 'e': case 'E': isDouble = true; parseExponent(); break; default: break outer; } } try { if (isDouble) { return Double.valueOf(s.substring(start, pos)); } Long val = Long.valueOf(s.substring(start, pos)); if (val <= Integer.MAX_VALUE && val >= Integer.MIN_VALUE) { return val.intValue(); } return val; } catch (NumberFormatException e) { throw new JSONParseException(s, start, e); } }public String parseString(final boolean needQuote) { char quot = 0; if (check('\'')) { quot = '\''; } else if (check('\"')) { quot = '\"'; } else if (needQuote) { throw new JSONParseException(s, pos); } char current; if (quot > 0) { read(quot); } StringBuilder buf = new StringBuilder(); int start = pos; while (pos < s.length()) { current = s.charAt(pos); if (quot > 0) { if (current == quot) { break; } } else { if (current == ':' || current == ' ') { break; } } if (current == '\\') { pos++; char x = get(); char special = 0; //CHECKSTYLE:OFF switch (x) { case 'u': // decode unicode buf.append(s.substring(start, pos - 1)); pos++; int tempPos = pos; readHex(); readHex(); readHex(); readHex(); int codePoint = Integer.parseInt(s.substring(tempPos, tempPos + 4), 16); buf.append((char) codePoint); start = pos; continue; case 'n': special = '\n'; break; case 'r': special = '\r'; break; case 't': special = '\t'; break; case 'b': special = '\b'; break; case '"': special = '\"'; break; case '\\': special = '\\'; break; default: break; } //CHECKSTYLE:ON buf.append(s.substring(start, pos - 1)); if (special != 0) { pos++; buf.append(special); } start = pos; continue; } pos++; } buf.append(s.substring(start, pos)); if (quot > 0) { read(quot); } return buf.toString(); }public void skipWS() { while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) { pos++; } }public void readHex() { if (pos < s.length() && ((s.charAt(pos) >= '0' && s.charAt(pos) <= '9') || (s.charAt(pos) >= 'A' && s.charAt(pos) <= 'F') || (s.charAt(pos) >= 'a' && s.charAt(pos) <= 'f'))) { pos++; } else { throw new JSONParseException(s, pos); } }protected Object parse(final String name) { Object value = null; char current = get(); switch (current) { // null case 'n': read('n'); read('u'); read('l'); read('l'); value = null; break; // NaN case 'N': read('N'); read('a'); read('N'); value = Double.NaN; break; // true case 't': read('t'); read('r'); read('u'); read('e'); value = true; break; // false case 'f': read('f'); read('a'); read('l'); read('s'); read('e'); value = false; break; // string case '\'': case '\"': value = parseString(true); break; // number case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '+': case '-': value = parseNumber(); break; // array case '[': value = parseArray(name); break; // object case '{': value = parseObject(name); break; default: throw new JSONParseException(s, pos); } return value; }public UUID asUuid(final UuidRepresentation uuidRepresentation) { Assertions.notNull("uuidRepresentation", uuidRepresentation); final byte uuidType = uuidRepresentation == UuidRepresentation.STANDARD ? BsonBinarySubType.UUID_STANDARD.getValue() : BsonBinarySubType.UUID_LEGACY.getValue(); if (type != uuidType) { throw new BsonInvalidOperationException("uuidRepresentation does not match current uuidRepresentation."); } return UuidHelper.decodeBinaryToUuid(data.clone(), type, uuidRepresentation); }public UUID asUuid() { if (!BsonBinarySubType.isUuid(type)) { throw new BsonInvalidOperationException("type must be a UUID subtype."); } if (type != BsonBinarySubType.UUID_STANDARD.getValue()) { throw new BsonInvalidOperationException("uuidRepresentation must be set to return the correct UUID."); } return UuidHelper.decodeBinaryToUuid(this.data.clone(), this.type, UuidRepresentation.STANDARD); }public static JavaWrapper getWrapper(final Class c) { JavaWrapper w = _wrappers.get(c); if (w == null) { w = new JavaWrapper(c); _wrappers.put(c, w); } return w; }@Nullable public static JavaWrapper getWrapperIfReflectionObject(final Class c) { if (ReflectionDBObject.class.isAssignableFrom(c)) { return getWrapper(c); } return null; }@Deprecated public UpdateOptions getOptions() { return new UpdateOptions() .bypassDocumentValidation(options.getBypassDocumentValidation()) .collation(options.getCollation()) .upsert(options.isUpsert()); }public ClassModel build() { List> propertyModels = new ArrayList>(); PropertyModel idPropertyModel = null; stateNotNull("type", type); for (Convention convention : conventions) { convention.apply(this); } stateNotNull("instanceCreatorFactory", instanceCreatorFactory); if (discriminatorEnabled) { stateNotNull("discriminatorKey", discriminatorKey); stateNotNull("discriminator", discriminator); } for (PropertyModelBuilder propertyModelBuilder : propertyModelBuilders) { boolean isIdProperty = propertyModelBuilder.getName().equals(idPropertyName); if (isIdProperty) { propertyModelBuilder.readName(ID_PROPERTY_NAME).writeName(ID_PROPERTY_NAME); } PropertyModel model = propertyModelBuilder.build(); propertyModels.add(model); if (isIdProperty) { idPropertyModel = model; } } validatePropertyModels(type.getSimpleName(), propertyModels); return new ClassModel(type, propertyNameToTypeParameterMap, instanceCreatorFactory, discriminatorEnabled, discriminatorKey, discriminator, IdPropertyModelHolder.create(type, idPropertyModel, idGenerator), unmodifiableList(propertyModels)); }public PropertyModelBuilder getProperty(final String propertyName) { notNull("propertyName", propertyName); for (PropertyModelBuilder propertyModelBuilder : propertyModelBuilders) { if (propertyModelBuilder.getName().equals(propertyName)) { return propertyModelBuilder; } } return null; }public static void isTrue(final String name, final boolean condition, final SingleResultCallback callback) { if (!condition) { IllegalStateException exception = new IllegalStateException("state should be: " + name); callback.onResult(null, exception); throw exception; } }public static T notNull(final String name, final T value, final SingleResultCallback callback) { if (value == null) { IllegalArgumentException exception = new IllegalArgumentException(name + " can not be null"); callback.onResult(null, exception); throw exception; } return value; }@SuppressWarnings({"rawtypes", "unchecked"}) public static BsonDocument asBsonDocument(final Object document, final CodecRegistry codecRegistry) { if (document == null) { return null; } if (document instanceof BsonDocument) { return (BsonDocument) document; } else { return new BsonDocumentWrapper(document, codecRegistry.get(document.getClass())); } }8�3xGqUcj������vk { � � �����^?��#�'�+�,./�/�1�2�3g5�6r=�J\L�MN�N�SXzY�Z\"^d�emBtIu!v�xY|t����d�؉@�(�W�l�a����O���n�p�r�������Ƭ��`�Y����k�����������������#�D�����^��� ��x�P����Y�5�������V��=q � � |[HD&X#Z$U%�&�(�)�,.�.A2�5 9/:�=�?:A:C�D�E�F�I�LODQhT�W�X�Y�Zx[�\�^@aDd=ef%gJhoigjkk�lnmo�o�p�rtOu8v�{�Q��_�����s��>���-�����Ĥ����{����X�����:�I�*�$�� �7�9�%���!�J�����c������!��|�8�g�"�(�50=�@�D�H�O�S�X�Zjk>m�yP� �J��y�l���b���T������k��������� �i�����)���A������������?��������f��8�h�����r��ac� ����I�QGS!�#�&/)�-�.u/�0�1�4@8�:=�?�@pAC8NsO�P�R_U�U�V�Y�^A`�aqbkc5e"g�h�i�m�q�u�v�y�{g|���0����������*�y�5���y��3�P�I���^�Z�����C�>��������7�D� ���m������n����j�@Override public void handleRequest(final HttpRequest clientRequest) { if (trackTimeOuts) { httpRequestHolderList.add(new HttpRequestHolder(clientRequest, time)); } if (httpClientRequestPredicate.test(clientRequest)) { createBackEndRequestPopulateAndForward(clientRequest); } }private void checkClient() { try { /** If the errorCount is greater than 0, make sure we are still connected. */ if (errorCount.get() > 0) { errorCount.set(0); if (backendServiceHttpClient == null || backendServiceHttpClient.isClosed()) { if (backendServiceHttpClient != null) { try { backendServiceHttpClient.stop(); } catch (Exception ex) { logger.debug("Was unable to stop the client connection", ex); } } backendServiceHttpClient = httpClientBuilder.buildAndStart(); lastHttpClientStart = time; } } /** If the ping builder is present, use it to ping the service. */ if (pingBuilder.isPresent()) { if (backendServiceHttpClient != null) { pingBuilder.get().setBinaryReceiver((code, contentType, body) -> { if (code >= 200 && code < 299) { pingCount.incrementAndGet(); } else { errorCount.incrementAndGet(); } }).setErrorHandler(e -> { logger.error("Error doing ping operation", e); errorCount.incrementAndGet(); }); final HttpRequest httpRequest = pingBuilder.get().build(); backendServiceHttpClient.sendHttpRequest(httpRequest); } } } catch (Exception ex) { errorHandler.accept(ex); logger.error("Unable to check connection"); } }private void trackTimeouts() { new ArrayList<>(httpRequestHolderList).forEach(httpRequestHolder -> { /* If it is handled then remove it from the list. */ if (httpRequestHolder.request.isHandled()) { httpRequestHolderList.remove(httpRequestHolder); return; } /* Get the duration that this request has been around. */ final long duration = time - httpRequestHolder.startTime; /* See if the duration is greater than the timeout time. */ if (duration > timeOutIntervalMS) { /* If we timed out, mark the request as handled, and then notify the client that the backend timed out. */ httpRequestHolder.request.handled(); /* Tell client that the backend timed out. */ httpRequestHolder.request.getReceiver().timeoutWithMessage(String.format("\"TIMEOUT %s %s %s\"", httpRequestHolder.request.address(), httpRequestHolder.request.getRemoteAddress(), httpRequestHolder.startTime )); /* If we timed out then remove this from the list. */ httpRequestHolderList.remove(httpRequestHolder); //Not very fast if you a lot of outstanding requests } }); }protected void recordTiming(String statKey, long timeSpan) { final String longKey = getActualStatKey(statKey); statsCollector.recordTiming(longKey, timeSpan); }protected void recordLevel(final String statKey, final long level) { final String longKey = getActualStatKey(statKey); statsCollector.recordLevel(longKey, level); }public static List getParts(String string, final String... regexpList) { final List parts = new ArrayList<>(); for (final String regexp : regexpList) { final Pattern pattern = Pattern.compile(regexp); final Matcher matcher = pattern.matcher(string); final boolean found = matcher.find(); if (!found) { return new ArrayList<>(); } final String part = matcher.group(1).trim(); parts.add(part); string = string.replaceFirst(quote(matcher.group()), "").trim(); } return parts; }private String getClipPathRef() { if (this.clip == null) { return ""; } if (this.clipRef == null) { this.clipRef = registerClip(getClip()); } StringBuilder b = new StringBuilder(); b.append("clip-path=\"url(#").append(this.clipRef).append(")\""); return b.toString(); }private String getRadialGradientElement(String id, RadialGradientPaint rgp) { StringBuilder b = new StringBuilder(""); Color[] colors = rgp.getColors(); float[] fractions = rgp.getFractions(); for (int i = 0; i < colors.length; i++) { Color c = colors[i]; float f = fractions[i]; b.append(""); } return b.append("").toString(); }@Override public void drawRenderableImage(RenderableImage img, AffineTransform xform) { RenderedImage ri = img.createDefaultRendering(); drawRenderedImage(ri, xform); }@Override public void drawRenderedImage(RenderedImage img, AffineTransform xform) { BufferedImage bi = GraphicsUtils.convertRenderedImage(img); drawImage(bi, xform, null); }private byte[] getPNGBytes(Image img) { RenderedImage ri; if (img instanceof RenderedImage) { ri = (RenderedImage) img; } else { BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bi.createGraphics(); g2.drawImage(img, 0, 0, null); ri = bi; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(ri, "png", baos); } catch (IOException ex) { Logger.getLogger(SVGGraphics2D.class.getName()).log(Level.SEVERE, "IOException while writing PNG data.", ex); } return baos.toByteArray(); }@Override public void setClip(int x, int y, int width, int height) { setRect(x, y, width, height); setClip(this.rect); }@Override public void clipRect(int x, int y, int width, int height) { setRect(x, y, width, height); clip(this.rect); }@Override public void clip(Shape s) { if (s instanceof Line2D) { s = s.getBounds2D(); } if (this.clip == null) { setClip(s); return; } Shape ts = this.transform.createTransformedShape(s); if (!ts.intersects(this.clip.getBounds2D())) { setClip(new Rectangle2D.Double()); } else { Area a1 = new Area(ts); Area a2 = new Area(this.clip); a1.intersect(a2); this.clip = new Path2D.Double(a1); } this.clipRef = null; }private String registerClip(Shape clip) { if (clip == null) { this.clipRef = null; return null; } // generate the path String pathStr = getSVGPathData(new Path2D.Double(clip)); int index = this.clipPaths.indexOf(pathStr); if (index < 0) { this.clipPaths.add(pathStr); index = this.clipPaths.size() - 1; } return this.defsKeyPrefix + CLIP_KEY_PREFIX + index; }@Override public void setClip(Shape shape) { // null is handled fine here... this.clip = this.transform.createTransformedShape(shape); this.clipRef = null; }@Override public void setTransform(AffineTransform t) { if (t == null) { this.transform = new AffineTransform(); } else { this.transform = new AffineTransform(t); } this.clipRef = null; }@Override public void transform(AffineTransform t) { AffineTransform tx = getTransform(); tx.concatenate(t); setTransform(tx); }@Override public void scale(double sx, double sy) { AffineTransform t = getTransform(); t.scale(sx, sy); setTransform(t); }@Override public FontMetrics getFontMetrics(Font f) { if (this.fmImage == null) { this.fmImage = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); this.fmImageG2D = this.fmImage.createGraphics(); this.fmImageG2D.setRenderingHint( RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); } return this.fmImageG2D.getFontMetrics(f); }private String getSVGFontStyle() { StringBuilder b = new StringBuilder(); b.append("fill: ").append(svgColorStr()).append("; "); b.append("fill-opacity: ").append(getColorAlpha() * getAlpha()) .append("; "); String fontFamily = this.fontMapper.mapFont(this.font.getFamily()); b.append("font-family: ").append(fontFamily).append("; "); b.append("font-size: ").append(this.font.getSize()).append(this.fontSizeUnits).append(";"); if (this.font.isBold()) { b.append(" font-weight: bold;"); } if (this.font.isItalic()) { b.append(" font-style: italic;"); } return b.toString(); }private String getSVGFillStyle() { StringBuilder b = new StringBuilder(); b.append("fill: ").append(svgColorStr()).append("; "); b.append("fill-opacity: ").append(getColorAlpha() * getAlpha()); return b.toString(); }private String strokeStyle() { double strokeWidth = 1.0f; String strokeCap = DEFAULT_STROKE_CAP; String strokeJoin = DEFAULT_STROKE_JOIN; float miterLimit = DEFAULT_MITER_LIMIT; float[] dashArray = new float[0]; if (this.stroke instanceof BasicStroke) { BasicStroke bs = (BasicStroke) this.stroke; strokeWidth = bs.getLineWidth() > 0.0 ? bs.getLineWidth() : this.zeroStrokeWidth; switch (bs.getEndCap()) { case BasicStroke.CAP_ROUND: strokeCap = "round"; break; case BasicStroke.CAP_SQUARE: strokeCap = "square"; break; case BasicStroke.CAP_BUTT: default: // already set to "butt" } switch (bs.getLineJoin()) { case BasicStroke.JOIN_BEVEL: strokeJoin = "bevel"; break; case BasicStroke.JOIN_ROUND: strokeJoin = "round"; break; case BasicStroke.JOIN_MITER: default: // already set to "miter" } miterLimit = bs.getMiterLimit(); dashArray = bs.getDashArray(); } StringBuilder b = new StringBuilder(); b.append("stroke-width: ").append(strokeWidth).append(";"); b.append("stroke: ").append(svgColorStr()).append(";"); b.append("stroke-opacity: ").append(getColorAlpha() * getAlpha()) .append(";"); if (!strokeCap.equals(DEFAULT_STROKE_CAP)) { b.append("stroke-linecap: ").append(strokeCap).append(";"); } if (!strokeJoin.equals(DEFAULT_STROKE_JOIN)) { b.append("stroke-linejoin: ").append(strokeJoin).append(";"); } if (Math.abs(DEFAULT_MITER_LIMIT - miterLimit) < 0.001) { b.append("stroke-miterlimit: ").append(geomDP(miterLimit)); } if (dashArray != null && dashArray.length != 0) { b.append("stroke-dasharray: "); for (int i = 0; i < dashArray.length; i++) { if (i != 0) b.append(", "); b.append(dashArray[i]); } b.append(";"); } if (this.checkStrokeControlHint) { Object hint = getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); if (RenderingHints.VALUE_STROKE_NORMALIZE.equals(hint) && !this.shapeRendering.equals("crispEdges")) { b.append("shape-rendering:crispEdges;"); } if (RenderingHints.VALUE_STROKE_PURE.equals(hint) && !this.shapeRendering.equals("geometricPrecision")) { b.append("shape-rendering:geometricPrecision;"); } } return b.toString(); }private String rgbaColorStr(Color c) { StringBuilder b = new StringBuilder("rgba("); double alphaPercent = c.getAlpha() / 255.0; b.append(c.getRed()).append(",").append(c.getGreen()).append(",") .append(c.getBlue()); b.append(",").append(transformDP(alphaPercent)); b.append(")"); return b.toString(); }private String rgbColorStr(Color c) { StringBuilder b = new StringBuilder("rgb("); b.append(c.getRed()).append(",").append(c.getGreen()).append(",") .append(c.getBlue()).append(")"); return b.toString(); }private String getSVGPathData(Path2D path) { StringBuilder b = new StringBuilder("d=\""); float[] coords = new float[6]; boolean first = true; PathIterator iterator = path.getPathIterator(null); while (!iterator.isDone()) { int type = iterator.currentSegment(coords); if (!first) { b.append(" "); } first = false; switch (type) { case (PathIterator.SEG_MOVETO): b.append("M ").append(geomDP(coords[0])).append(" ") .append(geomDP(coords[1])); break; case (PathIterator.SEG_LINETO): b.append("L ").append(geomDP(coords[0])).append(" ") .append(geomDP(coords[1])); break; case (PathIterator.SEG_QUADTO): b.append("Q ").append(geomDP(coords[0])) .append(" ").append(geomDP(coords[1])) .append(" ").append(geomDP(coords[2])) .append(" ").append(geomDP(coords[3])); break; case (PathIterator.SEG_CUBICTO): b.append("C ").append(geomDP(coords[0])).append(" ") .append(geomDP(coords[1])).append(" ") .append(geomDP(coords[2])).append(" ") .append(geomDP(coords[3])).append(" ") .append(geomDP(coords[4])).append(" ") .append(geomDP(coords[5])); break; case (PathIterator.SEG_CLOSE): b.append("Z "); break; default: break; } iterator.next(); } return b.append("\"").toString(); }private void appendOptionalElementIDFromHint(StringBuilder sb) { String elementID = (String) this.hints.get(SVGHints.KEY_ELEMENT_ID); if (elementID != null) { this.hints.put(SVGHints.KEY_ELEMENT_ID, null); // clear it if (this.elementIDs.contains(elementID)) { throw new IllegalStateException("The element id " + elementID + " is already used."); } else { this.elementIDs.add(elementID); } this.sb.append("id=\"").append(elementID).append("\" "); } }public void setTextRendering(String value) { if (!value.equals("auto") && !value.equals("optimizeSpeed") && !value.equals("optimizeLegibility") && !value.equals("geometricPrecision")) { throw new IllegalArgumentException("Unrecognised value: " + value); } this.textRendering = value; }public void setShapeRendering(String value) { if (!value.equals("auto") && !value.equals("crispEdges") && !value.equals("geometricPrecision") && !value.equals("optimizeSpeed")) { throw new IllegalArgumentException("Unrecognised value: " + value); } this.shapeRendering = value; }@Override public String mapFont(String family) { Args.nullNotPermitted(family, "family"); String alternate = this.alternates.get(family); if (alternate != null) { return alternate; } return family; }public String valueStr() { return new StringBuilder().append(this.minX).append(" ") .append(this.minY).append(" ").append(this.width).append(" ") .append(this.height).toString(); }@Override public VolatileImage createCompatibleVolatileImage(int width, int height, ImageCapabilities caps, int transparency) throws AWTException { if (img == null) { img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); gc = img.createGraphics().getDeviceConfiguration(); } return gc.createCompatibleVolatileImage(width, height, caps, transparency); }@Override public BufferedImage createCompatibleImage(int width, int height) { ColorModel model = getColorModel(); WritableRaster raster = model.createCompatibleWritableRaster(width, height); return new BufferedImage(model, raster, model.isAlphaPremultiplied(), null); }public static void writeToHTML(File file, String title, String svgElement) throws IOException { BufferedWriter writer = null; try { FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); writer = new BufferedWriter(osw); writer.write("\n"); writer.write("\n"); writer.write(" \n"); writer.write("" + title + "\n"); writer.write("\n"); writer.write(" \n"); writer.write("\n"); writer.write(svgElement + "\n"); writer.write(" \n"); writer.write("\n"); writer.flush(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException ex) { Logger.getLogger(SVGUtils.class.getName()).log(Level.SEVERE, null, ex); } } }public static String escapeForXML(String source) { Args.nullNotPermitted(source, "source"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < source.length(); i++) { char c = source.charAt(i); switch (c) { case '<' : { sb.append("<"); break; } case '>' : { sb.append(">"); break; } case '&' : { String next = source.substring(i, Math.min(i + 6, source.length())); if (next.startsWith("<") || next.startsWith(">") || next.startsWith("&") || next.startsWith("'") || next.startsWith(""")) { sb.append(c); } else { sb.append("&"); } break; } case '\'' : { sb.append("'"); break; } case '\"' : { sb.append("""); break; } default : sb.append(c); } } return sb.toString(); }public static long parseDuration(String duration) { if (duration == null || duration.isEmpty()) { throw new IllegalArgumentException("duration may not be null"); } long toAdd = -1; if (days.matcher(duration).matches()) { Matcher matcher = days.matcher(duration); matcher.matches(); toAdd = Long.parseLong(matcher.group(1)) * 60 * 60 * 24 * 1000; } else if (hours.matcher(duration).matches()) { Matcher matcher = hours.matcher(duration); matcher.matches(); toAdd = Long.parseLong(matcher.group(1)) * 60 * 60 * 1000; } else if (minutes.matcher(duration).matches()) { Matcher matcher = minutes.matcher(duration); matcher.matches(); toAdd = Long.parseLong(matcher.group(1)) * 60 * 1000; } else if (seconds.matcher(duration).matches()) { Matcher matcher = seconds.matcher(duration); matcher.matches(); toAdd = Long.parseLong(matcher.group(1)) * 1000; } else if (milliseconds.matcher(duration).matches()) { Matcher matcher = milliseconds.matcher(duration); matcher.matches(); toAdd = Long.parseLong(matcher.group(1)); } if (toAdd == -1) { throw new IllegalArgumentException("Invalid duration pattern : " + duration); } return toAdd; }public void deselectAllSpans() { mBlockCompletion = true; Editable text = getText(); MentionSpan[] spans = text.getSpans(0, text.length(), MentionSpan.class); for (MentionSpan span : spans) { if (span.isSelected()) { span.setSelected(false); updateSpan(span); } } mBlockCompletion = false; }private boolean onCursorChanged(final int index) { Editable text = getText(); if (text == null) { return false; } MentionSpan[] allSpans = text.getSpans(0, text.length(), MentionSpan.class); for (MentionSpan span : allSpans) { // Deselect span if the cursor is not on the span. if (span.isSelected() && (index < text.getSpanStart(span) || index > text.getSpanEnd(span))) { span.setSelected(false); updateSpan(span); } } // Do not allow the user to set the cursor within a span. If the user tries to do so, select // move the cursor to the end of it. MentionSpan[] currentSpans = text.getSpans(index, index, MentionSpan.class); if (currentSpans.length != 0) { MentionSpan span = currentSpans[0]; int start = text.getSpanStart(span); int end = text.getSpanEnd(span); if (index > start && index < end) { super.setSelection(end); return true; } } return false; }private void updateSelectionIfRequired(final int selStart, final int selEnd) { MentionsEditable text = getMentionsText(); MentionSpan startMentionSpan = text.getMentionSpanAtOffset(selStart); MentionSpan endMentionSpan = text.getMentionSpanAtOffset(selEnd); boolean selChanged = false; int start = selStart; int end = selEnd; if (text.getSpanStart(startMentionSpan) < selStart && selStart < text.getSpanEnd(startMentionSpan)) { start = text.getSpanStart(startMentionSpan); selChanged = true; } if (text.getSpanStart(endMentionSpan) < selEnd && selEnd < text.getSpanEnd(endMentionSpan)) { end = text.getSpanEnd(endMentionSpan); selChanged = true; } if (selChanged) { setSelection(start, end); } }@TargetApi(Build.VERSION_CODES.HONEYCOMB) private void pasteHoneycombImpl(@IntRange(from = 0) int min, @IntRange(from = 0) int max) { ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = clipboard.getPrimaryClip(); if (clip != null) { for (int i = 0; i < clip.getItemCount(); i++) { ClipData.Item item = clip.getItemAt(i); String selectedText = item.coerceToText(getContext()).toString(); MentionsEditable text = getMentionsText(); MentionSpan[] spans = text.getSpans(min, max, MentionSpan.class); /* * We need to remove the span between min and max. This is required because in * {@link SpannableStringBuilder#replace(int, int, CharSequence)} existing spans within * the Editable that entirely cover the replaced range are retained, but any that * were strictly within the range that was replaced are removed. In our case the existing * spans are retained if the selection entirely covers the span. So, we just remove * the existing span and replace the new text with that span. */ for (MentionSpan span : spans) { if (text.getSpanEnd(span) == min) { // We do not want to remove the span, when we want to paste anything just next // to the existing span. In this case "text.getSpanEnd(span)" will be equal // to min. continue; } text.removeSpan(span); } Intent intent = item.getIntent(); // Just set the plain text if we do not have mentions data in the intent/bundle if (intent == null) { text.replace(min, max, selectedText); continue; } Bundle bundle = intent.getExtras(); if (bundle == null) { text.replace(min, max, selectedText); continue; } bundle.setClassLoader(getContext().getClassLoader()); int[] spanStart = bundle.getIntArray(KEY_MENTION_SPAN_STARTS); Parcelable[] parcelables = bundle.getParcelableArray(KEY_MENTION_SPANS); if (parcelables == null || parcelables.length <= 0 || spanStart == null || spanStart.length <= 0) { text.replace(min, max, selectedText); continue; } // Set the MentionSpan in text. SpannableStringBuilder s = new SpannableStringBuilder(selectedText); for (int j = 0; j < parcelables.length; j++) { MentionSpan mentionSpan = (MentionSpan) parcelables[j]; s.setSpan(mentionSpan, spanStart[j], spanStart[j] + mentionSpan.getDisplayString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } text.replace(min, max, s); } } }private void paste(@IntRange(from = 0) int min, @IntRange(from = 0) int max) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); MentionsEditable text = getMentionsText(); text.replace(text.length(), text.length(), clipboard.getText()); } else { pasteHoneycombImpl(min, max); } }private void copy(@IntRange(from = 0) int start, @IntRange(from = 0) int end) { MentionsEditable text = getMentionsText(); SpannableStringBuilder copiedText = (SpannableStringBuilder) text.subSequence(start, end); MentionSpan[] spans = text.getSpans(start, end, MentionSpan.class); Intent intent = null; if (spans.length > 0) { // Save MentionSpan and it's start offset. intent = new Intent(); intent.putExtra(KEY_MENTION_SPANS, spans); int[] spanStart = new int[spans.length]; for (int i = 0; i < spans.length; i++) { spanStart[i] = copiedText.getSpanStart(spans[i]); } intent.putExtra(KEY_MENTION_SPAN_STARTS, spanStart); } saveToClipboard(copiedText, intent); }public void setMentionSpanFactory(@NonNull final MentionsEditText.MentionSpanFactory factory) { if (mMentionsEditText != null) { mMentionsEditText.setMentionSpanFactory(factory); } }private void updateEditorTextCount() { if (mMentionsEditText != null && mTextCounterView != null) { int textCount = mMentionsEditText.getMentionsText().length(); mTextCounterView.setText(String.valueOf(textCount)); if (mTextCountLimit > 0 && textCount > mTextCountLimit) { mTextCounterView.setTextColor(mBeyondCountLimitTextColor); } else { mTextCounterView.setTextColor(mWithinCountLimitTextColor); } } }private void disableSpellingSuggestions(boolean disable) { // toggling suggestions often resets the cursor location, but we don't want that to happen int start = mMentionsEditText.getSelectionStart(); int end = mMentionsEditText.getSelectionEnd(); // -1 means there is no selection or cursor. if (start == -1 || end == -1) { return; } if (disable) { // store the previous input type mOriginalInputType = mMentionsEditText.getInputType(); } mMentionsEditText.setRawInputType(disable ? InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS : mOriginalInputType); mMentionsEditText.setSelection(start, end); }public void displayTextCounter(boolean display) { if (display) { mTextCounterView.setVisibility(TextView.VISIBLE); } else { mTextCounterView.setVisibility(TextView.GONE); } }protected int getSearchEndIndex(final @NonNull Spanned text, int cursor) { if (cursor < 0 || cursor > text.length()) { cursor = 0; } // Get index of the start of the first span after the cursor (or text.length() if does not exist) MentionSpan[] spans = text.getSpans(0, text.length(), MentionSpan.class); int closestAfterCursor = text.length(); for (MentionSpan span : spans) { int start = text.getSpanStart(span); if (start < closestAfterCursor && start >= cursor) { closestAfterCursor = start; } } // Get the index of the end of the line String textString = text.toString().substring(cursor, text.length()); int lineEndIndex = text.length(); if (textString.contains(mConfig.LINE_SEPARATOR)) { lineEndIndex = cursor + textString.indexOf(mConfig.LINE_SEPARATOR); } // Return whichever is closest after the cursor return Math.min(closestAfterCursor, lineEndIndex); }protected int getSearchStartIndex(final @NonNull Spanned text, int cursor) { if (cursor < 0 || cursor > text.length()) { cursor = 0; } // Get index of the end of the last span before the cursor (or 0 if does not exist) MentionSpan[] spans = text.getSpans(0, text.length(), MentionSpan.class); int closestToCursor = 0; for (MentionSpan span : spans) { int end = text.getSpanEnd(span); if (end > closestToCursor && end <= cursor) { closestToCursor = end; } } // Get the index of the start of the line String textString = text.toString().substring(0, cursor); int lineStartIndex = 0; if (textString.contains(mConfig.LINE_SEPARATOR)) { lineStartIndex = textString.lastIndexOf(mConfig.LINE_SEPARATOR) + 1; } // Return whichever is closer before to the cursor return Math.max(closestToCursor, lineStartIndex); }public boolean onlyLettersOrDigits(final @NonNull CharSequence input, final int numCharsToCheck, final int start) { // Starting position must be within the input string if (start < 0 || start > input.length()) { return false; } // Check the first "numCharsToCheck" characters to ensure they are a letter or digit for (int i = 0; i < numCharsToCheck; i++) { int positionToCheck = start + i; // Return false if we would throw an Out-of-Bounds exception if (positionToCheck >= input.length()) { return false; } // Return false early if current character is not a letter or digit char charToCheck = input.charAt(positionToCheck); if (!Character.isLetterOrDigit(charToCheck)) { return false; } } // First "numCharsToCheck" characters are either letters or digits, so return true return true; }public boolean containsWordBreakingChar(final @NonNull CharSequence input) { if (!TextUtils.isEmpty(input)) { for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (isWordBreakingChar(c)) { return true; } } } return false; }public boolean containsExplicitChar(final @NonNull CharSequence input) { if (!TextUtils.isEmpty(input)) { for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (isExplicitChar(c)) { return true; } } } return false; }public List getSuggestions(QueryToken queryToken) { String prefix = queryToken.getKeywords().toLowerCase(); List suggestions = new ArrayList<>(); if (mData != null) { for (T suggestion : mData) { String name = suggestion.getSuggestiblePrimaryText().toLowerCase(); if (name.startsWith(prefix)) { suggestions.add(suggestion); } } } return suggestions; }private void hideSuggestionsIfNecessary(final @NonNull QueryToken currentQuery, final @NonNull TokenSource source) { String queryTS = currentQuery.getTokenString(); String currentTS = source.getCurrentTokenString(); if (!isWaitingForResults(currentQuery) && queryTS != null && queryTS.equals(currentTS)) { mSuggestionsVisibilityManager.displaySuggestions(false); } }public void morphFromSheet(int endX, int endY, Side side, int arcDegrees, float scaleFactor, long duration, AnimationListener listener) { fab.setVisibility(View.VISIBLE); morph(endX, endY, side, arcDegrees, scaleFactor, duration, listener); }public void morphIntoSheet(int endX, int endY, Side side, int arcDegrees, float scaleFactor, long duration, AnimationListener listener) { morph(endX, endY, side, arcDegrees, scaleFactor, duration, listener); }private void updateSnackbar(int selectedPage) { View snackbar = findViewById(R.id.snackbar); switch (selectedPage) { case MainPagerAdapter.SHARED_POS: snackbar.setVisibility(View.VISIBLE); break; case MainPagerAdapter.ALL_POS: case MainPagerAdapter.FAVORITES_POS: default: snackbar.setVisibility(View.GONE); break; } }private void updateFab(int selectedPage) { switch (selectedPage) { case MainPagerAdapter.ALL_POS: materialSheetFab.showFab(); break; case MainPagerAdapter.SHARED_POS: materialSheetFab.showFab(0, -getResources().getDimensionPixelSize(R.dimen.snackbar_height)); break; case MainPagerAdapter.FAVORITES_POS: default: materialSheetFab.hideSheetThenFab(); break; } }private void setupFab() { Fab fab = (Fab) findViewById(R.id.fab); View sheetView = findViewById(R.id.fab_sheet); View overlay = findViewById(R.id.overlay); int sheetColor = getResources().getColor(R.color.background_card); int fabColor = getResources().getColor(R.color.theme_accent); // Create material sheet FAB materialSheetFab = new MaterialSheetFab<>(fab, sheetView, overlay, sheetColor, fabColor); // Set material sheet event listener materialSheetFab.setEventListener(new MaterialSheetFabEventListener() { @Override public void onShowSheet() { // Save current status bar color statusBarColor = getStatusBarColor(); // Set darker status bar color to match the dim overlay setStatusBarColor(getResources().getColor(R.color.theme_primary_dark2)); } @Override public void onHideSheet() { // Restore status bar color setStatusBarColor(statusBarColor); } }); // Set material sheet item click listeners findViewById(R.id.fab_sheet_item_recording).setOnClickListener(this); findViewById(R.id.fab_sheet_item_reminder).setOnClickListener(this); findViewById(R.id.fab_sheet_item_photo).setOnClickListener(this); findViewById(R.id.fab_sheet_item_note).setOnClickListener(this); }private void setupTabs() { // Setup view pager ViewPager viewpager = (ViewPager) findViewById(R.id.viewpager); viewpager.setAdapter(new MainPagerAdapter(this, getSupportFragmentManager())); viewpager.setOffscreenPageLimit(MainPagerAdapter.NUM_ITEMS); updatePage(viewpager.getCurrentItem()); // Setup tab layout TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewpager); viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int i) { updatePage(i); } @Override public void onPageScrollStateChanged(int i) { } }); }private void setupDrawer() { drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.opendrawer, R.string.closedrawer); drawerLayout.setDrawerListener(drawerToggle); }private void setupActionBar() { setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); }public void showSheet() { if (isAnimating()) { return; } isShowing = true; // Show overlay overlayAnimation.show(SHOW_OVERLAY_ANIM_DURATION, null); // Morph FAB into sheet morphIntoSheet(new AnimationListener() { @Override public void onEnd() { // Call event listener if (eventListener != null) { eventListener.onSheetShown(); } // Assuming that this is the last animation to finish isShowing = false; // Hide sheet after it is shown if (hideSheetAfterSheetIsShown) { hideSheet(); hideSheetAfterSheetIsShown = false; } } }); // Call event listener if (eventListener != null) { eventListener.onShowSheet(); } }public void hide(long duration, final AnimationListener listener) { overlay.animate().alpha(0).setDuration(duration).setInterpolator(interpolator) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { if (listener != null) { listener.onStart(); } } @Override public void onAnimationEnd(Animator animation) { overlay.setVisibility(View.GONE); if (listener != null) { listener.onEnd(); } } }).start(); }public void morphIntoFab(View fab, long hideSheetDuration, long hideSheetColorDuration, AnimationListener listener) { revealSheetWithFab(fab, getSheetRevealRadius(), getFabRevealRadius(fab), hideSheetDuration, sheetColor, fabColor, hideSheetColorDuration, listener); }public void morphFromFab(View fab, long showSheetDuration, long showSheetColorDuration, AnimationListener listener) { sheet.setVisibility(View.VISIBLE); revealSheetWithFab(fab, getFabRevealRadius(fab), getSheetRevealRadius(), showSheetDuration, fabColor, sheetColor, showSheetColorDuration, listener); }public void alignSheetWithFab(View fab) { // NOTE: View.getLocationOnScreen() returns the view's coordinates on the screen // whereas other view methods like getRight() and getY() return coordinates relative // to the view's parent. Using those methods can lead to incorrect calculations when // the two views do not have the same parent. // Get FAB's coordinates int[] fabCoords = new int[2]; fab.getLocationOnScreen(fabCoords); // Get sheet's coordinates int[] sheetCoords = new int[2]; sheet.getLocationOnScreen(sheetCoords); // NOTE: Use the diffs between the positions of the FAB and sheet to align the sheet. // We have to use the diffs because the coordinates returned by getLocationOnScreen() // include the status bar and any other system UI elements, meaning the coordinates // aren't representative of the usable screen space. int leftDiff = sheetCoords[0] - fabCoords[0]; int rightDiff = (sheetCoords[0] + sheet.getWidth()) - (fabCoords[0] + fab.getWidth()); int topDiff = sheetCoords[1] - fabCoords[1]; int bottomDiff = (sheetCoords[1] + sheet.getHeight()) - (fabCoords[1] + fab.getHeight()); // NOTE: Preserve the sheet's margins to allow users to shift the sheet's position // to compensate for the fact that the design support library's FAB has extra // padding within the view ViewGroup.MarginLayoutParams sheetLayoutParams = (ViewGroup.MarginLayoutParams) sheet .getLayoutParams(); // Set sheet's new coordinates (only if there is a change in coordinates because // setting the same coordinates can cause the view to "drift" - moving 0.5 to 1 pixels // around the screen) if (rightDiff != 0) { float sheetX = sheet.getX(); // Align the right side of the sheet with the right side of the FAB if // doing so would not move the sheet off the screen if (rightDiff <= sheetX) { sheet.setX(sheetX - rightDiff - sheetLayoutParams.rightMargin); revealXDirection = RevealXDirection.LEFT; } // Otherwise, align the left side of the sheet with the left side of the FAB else if (leftDiff != 0 && leftDiff <= sheetX) { sheet.setX(sheetX - leftDiff + sheetLayoutParams.leftMargin); revealXDirection = RevealXDirection.RIGHT; } } if (bottomDiff != 0) { float sheetY = sheet.getY(); // Align the bottom of the sheet with the bottom of the FAB if (bottomDiff <= sheetY) { sheet.setY(sheetY - bottomDiff - sheetLayoutParams.bottomMargin); revealYDirection = RevealYDirection.UP; } // Otherwise, align the top of the sheet with the top of the FAB else if (topDiff != 0 && topDiff <= sheetY) { sheet.setY(sheetY - topDiff + sheetLayoutParams.topMargin); revealYDirection = RevealYDirection.DOWN; } } }@Override public void hide() { // Only use scale animation if FAB is visible if (getVisibility() == View.VISIBLE) { // Pivots indicate where the animation begins from float pivotX = getPivotX() + getTranslationX(); float pivotY = getPivotY() + getTranslationY(); // Animate FAB shrinking ScaleAnimation anim = new ScaleAnimation(1, 0, 1, 0, pivotX, pivotY); anim.setDuration(FAB_ANIM_DURATION); anim.setInterpolator(getInterpolator()); startAnimation(anim); } setVisibility(View.INVISIBLE); }public T lastItem() { if (mDataList == null || mDataList.size() == 0) { return null; } return mDataList.get(mDataList.size() - 1); }@Override public void onResume() { super.onResume(); if (!mFirstResume) { onBack(); } if (mFirstResume) { mFirstResume = false; } if (DEBUG) { showStatus("onResume"); } }private static void notifyDrawable(Drawable drawable, final boolean isDisplayed) { if (drawable instanceof RecyclingBitmapDrawable) { // The drawable is a CountingBitmapDrawable, so notify it ((RecyclingBitmapDrawable) drawable).setIsDisplayed(isDisplayed); } else if (drawable instanceof LayerDrawable) { // The drawable is a LayerDrawable, so recurse on each layer LayerDrawable layerDrawable = (LayerDrawable) drawable; for (int i = 0, z = layerDrawable.getNumberOfLayers(); i < z; i++) { notifyDrawable(layerDrawable.getDrawable(i), isDisplayed); } } }@SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.GINGERBREAD) public static long getUsableSpace(File path) { if (path == null) { return -1; } if (Version.hasGingerbread()) { return path.getUsableSpace(); } else { if (!path.exists()) { return 0; } else { final StatFs stats = new StatFs(path.getPath()); return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks(); } } }@TargetApi(Build.VERSION_CODES.FROYO) public static File getExternalCacheDir(Context context) { if (Version.hasFroyo()) { File path = context.getExternalCacheDir(); // In some case, even the sd card is mounted, getExternalCacheDir will return null, may be it is nearly full. if (path != null) { return path; } } // Before Froyo or the path is null, we need to construct the external cache folder ourselves final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/"; return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir); }public static void deleteDirectoryQuickly(File dir) throws IOException { if (!dir.exists()) { return; } final File to = new File(dir.getAbsolutePath() + System.currentTimeMillis()); dir.renameTo(to); if (!dir.exists()) { // rebuild dir.mkdirs(); } // try to run "rm -r" to remove the whole directory if (to.exists()) { String deleteCmd = "rm -r " + to; Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec(deleteCmd); process.waitFor(); } catch (IOException e) { } catch (InterruptedException e) { e.printStackTrace(); } } if (!to.exists()) { return; } deleteDirectoryRecursively(to); if (to.exists()) { to.delete(); } }public DiskCache getDiskCache() { if (!mDiskCacheReady) { if (DEBUG) { CLog.d(LOG_TAG, "%s, try to access disk cache, but it is not open, try to open it.", mDiskCache); } openDiskCacheAsync(); } synchronized (mDiskCacheLock) { while (mDiskCacheStarting) { try { if (DEBUG) { CLog.d(LOG_TAG, "%s, try to access, but disk cache is not ready, wait", mDiskCache); } mDiskCacheLock.wait(); } catch (InterruptedException e) { } } } return mDiskCache; }public void flushDiskCacheAsyncWithDelay(int delay) { if (DEBUG) { CLog.d(LOG_TAG, "%s, flushDiskCacheAsyncWithDelay", delay); } if (mIsDelayFlushing) { return; } mIsDelayFlushing = true; new FileCacheTask(TASK_FLUSH_CACHE).executeAfter(delay); }public void openDiskCacheAsync() { if (DEBUG) { CLog.d(LOG_TAG, "%s: initDiskCacheAsync", mDiskCache); } synchronized (mDiskCacheLock) { mDiskCacheStarting = true; new FileCacheTask(TASK_INIT_CACHE).executeNow(); } }public static String joinSizeTagToKey(String key, String tag) { return new StringBuilder(key).append(SIZE_SP).append(tag).toString(); }public static String joinSizeInfoToKey(String key, int w, int h) { if (w > 0 && h != Integer.MAX_VALUE && h > 0 && h != Integer.MAX_VALUE) { return new StringBuilder(key).append(SIZE_SP).append(w).append(SIZE_SP).append(h).toString(); } return key; }public void onLoadTaskFinish(BitmapDrawable drawable, ImageLoadHandler handler) { mFlag &= ~STATUS_LOADING; if (null == handler) { return; } int errorCode = mFlag & ERROR_CODE_MASK; if (errorCode > 0) { onLoadError(errorCode, handler); return; } if (null != mImageTaskStatistics) { mImageTaskStatistics.s5_beforeShow(); } if (mFirstImageViewHolder == null) { handler.onLoadFinish(this, null, drawable); } else { ImageViewHolder holder = mFirstImageViewHolder; do { final CubeImageView imageView = holder.getImageView(); if (null != imageView) { imageView.onLoadFinish(); handler.onLoadFinish(this, imageView, drawable); } } while ((holder = holder.mNext) != null); } if (null != mImageTaskStatistics) { mImageTaskStatistics.s6_afterShow(ImageProvider.getBitmapSize(drawable)); ImagePerformanceStatistics.onImageLoaded(this, mImageTaskStatistics); } }public void onLoading(ImageLoadHandler handler) { mFlag = mFlag | STATUS_LOADING; if (null == handler) { return; } if (mFirstImageViewHolder == null) { handler.onLoading(this, null); } else { ImageViewHolder holder = mFirstImageViewHolder; do { final CubeImageView imageView = holder.getImageView(); if (null != imageView) { handler.onLoading(this, imageView); } } while ((holder = holder.mNext) != null); } }public void removeImageView(CubeImageView imageView) { if (null == imageView || null == mFirstImageViewHolder) { return; } ImageViewHolder holder = mFirstImageViewHolder; do { if (holder.contains(imageView)) { // Make sure entry is right. if (holder == mFirstImageViewHolder) { mFirstImageViewHolder = holder.mNext; } if (null != holder.mNext) { holder.mNext.mPrev = holder.mPrev; } if (null != holder.mPrev) { holder.mPrev.mNext = holder.mNext; } } } while ((holder = holder.mNext) != null); }public void addImageView(CubeImageView imageView) { if (null == imageView) { return; } if (null == mFirstImageViewHolder) { mFirstImageViewHolder = new ImageViewHolder(imageView); return; } ImageViewHolder holder = mFirstImageViewHolder; for (; ; holder = holder.mNext) { if (holder.contains(imageView)) { return; } if (holder.mNext == null) { break; } } ImageViewHolder newHolder = new ImageViewHolder(imageView); newHolder.mPrev = holder; holder.mNext = newHolder; }public boolean downloadToStream(ImageTask imageTask, String urlString, OutputStream outputStream, ProgressUpdateHandler progressUpdateHandler) { disableConnectionReuseIfNecessary(); HttpURLConnection urlConnection = null; BufferedOutputStream out = null; BufferedInputStream in = null; try { final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(0); int len = urlConnection.getContentLength(); int total = 0; in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE); out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE); int b; while ((b = in.read()) != -1) { total++; out.write(b); if (progressUpdateHandler != null) { progressUpdateHandler.onProgressUpdate(total, len); } } return true; } catch (final IOException e) { CLog.e(LOG_TAG, "Error in downloadBitmap - " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (final IOException e) { } } return false; }public void setCustomizedRightView(View view) { RelativeLayout.LayoutParams lp = makeLayoutParams(view); lp.addRule(CENTER_VERTICAL); lp.addRule(ALIGN_PARENT_RIGHT); getRightViewContainer().addView(view, lp); }public void setLoadingBitmap(Bitmap loadingBitmap) { if (Version.hasHoneycomb()) { mLoadingDrawable = new BitmapDrawable(mContext.getResources(), loadingBitmap); } }public void getResponse(StringBuilder sb) throws IOException { // checks server's status code first int status = mHttpURLConnection.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { InputStream ips = new BufferedInputStream(mHttpURLConnection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(ips, "UTF-8")); char[] buffer = new char[1024]; int bufferLength; while ((bufferLength = reader.read(buffer, 0, buffer.length)) > 0) { sb.append(buffer, 0, bufferLength); } reader.close(); ips.close(); mHttpURLConnection.disconnect(); } else { throw new IOException("Server returned non-OK status: " + status); } }private void notifyRequestFinish(ResultType type, T cacheData, boolean outOfDate) { if (DEBUG) { CLog.d(LOG_TAG, "%s, notifyRequestFinish: %s, %s", getCacheKey(), type, outOfDate); } if (mHasNotified) { return; } mHasNotified = true; mHandler.onCacheAbleRequestFinish(cacheData, type, outOfDate); }@Override protected T doRequestSync() { T data = RequestCacheManager.getInstance().requestCacheSync(this); if (data == null) { data = RequestManager.getInstance().getRequestProxy(this).requestSync(this); } return data; }public ImageReuseInfo create(String thisSize) { ArrayList list = new ArrayList(); boolean canBeReused = false; for (int i = 0; i < mSizeList.length; i++) { String size = mSizeList[i]; if (!canBeReused && thisSize.equals(size)) { canBeReused = true; continue; } if (canBeReused && !thisSize.equals(size)) { list.add(size); } } if (list.size() == 0) { return new ImageReuseInfo(thisSize, null); } else { String[] sizeList = new String[list.size()]; list.toArray(sizeList); return new ImageReuseInfo(thisSize, sizeList); } }@Override public void loadMoreFinish(boolean emptyResult, boolean hasMore) { mLoadError = false; mListEmpty = emptyResult; mIsLoading = false; mHasMore = hasMore; if (mLoadMoreUIHandler != null) { mLoadMoreUIHandler.onLoadFinish(this, emptyResult, hasMore); } }@Override public void onBackPressed() { // process back for fragment if (processBackPressed()) { return; } // process back for fragment boolean enableBackPressed = true; if (mCurrentFragment != null) { enableBackPressed = !mCurrentFragment.processBackPressed(); } if (enableBackPressed) { int cnt = getSupportFragmentManager().getBackStackEntryCount(); if (cnt <= 1 && isTaskRoot()) { String closeWarningHint = getCloseWarning(); if (!mCloseWarned && !TextUtils.isEmpty(closeWarningHint)) { Toast toast = Toast.makeText(this, closeWarningHint, Toast.LENGTH_SHORT); toast.show(); mCloseWarned = true; } else { doReturnBack(); } } else { mCloseWarned = false; doReturnBack(); } } }private synchronized void trimToSize() { if (mSize > mCapacity) { if (SimpleDiskLruCache.DEBUG) { CLog.d(SimpleDiskLruCache.LOG_TAG, "should trim, current is: %s", mSize); } } while (mSize > mCapacity) { Map.Entry toEvict = mLruEntries.entrySet().iterator().next(); String key = toEvict.getKey(); CacheEntry cacheEntry = toEvict.getValue(); mLruEntries.remove(key); mSize -= cacheEntry.getSize(); addActionLog(ACTION_PENDING_DELETE, cacheEntry); if (SimpleDiskLruCache.DEBUG) { CLog.d(SimpleDiskLruCache.LOG_TAG, "pending remove: %s, size: %s, after remove total: %s", key, cacheEntry.getSize(), mSize); } } }private void rebuildJournal() throws IOException { if (mJournalWriter != null) { mJournalWriter.close(); } Writer writer = new BufferedWriter(new FileWriter(mJournalFileTmp), IO_BUFFER_SIZE); writer.write(MAGIC); writer.write("\n"); writer.write(VERSION_1); writer.write("\n"); writer.write(Integer.toString(mAppVersion)); writer.write("\n"); writer.write("\n"); for (CacheEntry cacheEntry : mLruEntries.values()) { if (cacheEntry.isUnderEdit()) { writer.write(sACTION_LIST[ACTION_DIRTY] + ' ' + cacheEntry.getKey() + " " + cacheEntry.getSize() + '\n'); } else { writer.write(sACTION_LIST[ACTION_CLEAN] + ' ' + cacheEntry.getKey() + " " + cacheEntry.getSize() + '\n'); } } writer.close(); mJournalFileTmp.renameTo(mJournalFile); mJournalWriter = new BufferedWriter(new FileWriter(mJournalFile, true), IO_BUFFER_SIZE); }private void processJournal() throws IOException { FileUtils.deleteIfExists(mJournalFileTmp); for (Iterator i = mLruEntries.values().iterator(); i.hasNext(); ) { CacheEntry cacheEntry = i.next(); if (!cacheEntry.isUnderEdit()) { mSize += cacheEntry.getSize(); } else { cacheEntry.delete(); i.remove(); } } }public void tryToResume() throws IOException { if (mJournalFile.exists()) { try { readJournal(); processJournal(); mJournalWriter = new BufferedWriter(new FileWriter(mJournalFile, true), IO_BUFFER_SIZE); if (SimpleDiskLruCache.DEBUG) { CLog.d(SimpleDiskLruCache.LOG_TAG, "open success"); } } catch (IOException journalIsCorrupt) { journalIsCorrupt.printStackTrace(); if (SimpleDiskLruCache.DEBUG) { CLog.d(SimpleDiskLruCache.LOG_TAG, "clear old cache"); } clear(); } } else { if (SimpleDiskLruCache.DEBUG) { CLog.d(SimpleDiskLruCache.LOG_TAG, "create new cache"); } // create a new empty cache if (mDirectory.exists()) { mDirectory.delete(); } mDirectory.mkdirs(); rebuildJournal(); } }@Override public void clear() { if (mMemoryCache != null) { mMemoryCache.evictAll(); if (DEBUG) { Log.d(LOG_TAG, "Memory cache cleared"); } } }@SuppressWarnings({"unused"}) public RequestData addFile(String fieldName, String uploadFile, String fileName) { addFile(fieldName, new File(uploadFile), fileName); return this; }public void commit() throws IOException { if (!mIsUnderEdit) { throw new IOException("CacheEntry has been closed."); } if (hasErrors) { mDiskCache.delete(mKey); } else { File dirty = getTempFile(); if (dirty.exists()) { File clean = getCacheFile(); dirty.renameTo(clean); mOldSize = mSize; mSize = clean.length(); mDiskCache.commitEdit(this); } else { abortEdit(); } } mIsUnderEdit = false; }public boolean delete() throws IOException { if (mIsUnderEdit) { throw new IOException("Try to delete an cache entry that has been being editing."); } FileUtils.deleteIfExists(getCacheFile()); FileUtils.deleteIfExists(getTempFile()); return true; }public CacheEntry setString(String value) throws IOException { Writer writer = null; try { writer = new OutputStreamWriter(newOutputStream(), UTF_8); writer.write(value); } finally { FileUtils.closeQuietly(writer); } return this; }public String getString() throws IOException { InputStream in = getInputStream(); return in != null ? inputStreamToString(in) : null; }public void write(String key, Bitmap bitmap) { if (key == null || bitmap == null) { return; } // Add to disk cache OutputStream out = null; try { CacheEntry cacheEntry = mDiskCache.beginEdit(key); if (cacheEntry != null) { out = cacheEntry.newOutputStream(); bitmap.compress(DEFAULT_COMPRESS_FORMAT, DEFAULT_COMPRESS_QUALITY, out); cacheEntry.commit(); out.close(); } } catch (final IOException e) { CLog.e(LOG_TAG, "addBitmapToCache - " + e); } catch (Exception e) { CLog.e(LOG_TAG, "addBitmapToCache - " + e); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { } } }private SimpleHashSetEntry[] doubleCapacity() { SimpleHashSetEntry[] oldTable = mTable; int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { return oldTable; } int newCapacity = oldCapacity * 2; SimpleHashSetEntry[] newTable = makeTable(newCapacity); if (mSize == 0) { return newTable; } for (int j = 0; j < oldCapacity; j++) { /* * Rehash the bucket using the minimum number of field writes. * This is the most subtle and delicate code in the class. */ SimpleHashSetEntry e = oldTable[j]; if (e == null) { continue; } int highBit = e.mHash & oldCapacity; SimpleHashSetEntry broken = null; newTable[j | highBit] = e; for (SimpleHashSetEntry n = e.mNext; n != null; e = n, n = n.mNext) { int nextHighBit = n.mHash & oldCapacity; if (nextHighBit != highBit) { if (broken == null) { newTable[j | nextHighBit] = n; } else { broken.mNext = n; } broken = e; highBit = nextHighBit; } } if (broken != null) broken.mNext = null; } return newTable; }private SimpleHashSetEntry[] makeTable(int newCapacity) { @SuppressWarnings("unchecked") SimpleHashSetEntry[] newTable = (SimpleHashSetEntry[]) new SimpleHashSetEntry[newCapacity]; mTable = newTable; threshold = (newCapacity >> 1) + (newCapacity >> 2); // 3/4 capacity return newTable; }public void clearDiskCache() { if (null != mFileCache) { try { mFileCache.getDiskCache().clear(); } catch (IOException e) { if (DEBUG) { e.printStackTrace(); } } } }public void invalidateCache(String key) { if (DEBUG) { CLog.d(LOG_TAG, "key: %s, invalidateCache", key); } try { mFileCache.getDiskCache().delete(key); } catch (IOException e) { if (DEBUG) { e.printStackTrace(); } } mMemoryCache.remove(key); }public ImageLoader attachToCubeFragment(CubeFragment fragment) { if (fragment != null) { if (LifeCycleComponentManager.tryAddComponentToContainer(this, fragment, true)) { mHasBeenAddedToComponentManager = true; } } return this; }public void destroy() { if (DEBUG) { CLog.d(LOG_TAG, "work_status: destroy %s", this); } mExitTasksEarly = true; setPause(false); Iterator> it = (Iterator>) mLoadWorkList.entrySet().iterator(); while (it.hasNext()) { Entry item = it.next(); final LoadImageTask task = item.getValue(); it.remove(); if (task != null) { task.cancel(); } } mLoadWorkList.clear(); }public void stopWork() { if (DEBUG) { CLog.d(LOG_TAG, "work_status: stopWork %s", this); } mExitTasksEarly = true; setPause(false); flushFileCache(); }public void recoverWork() { if (DEBUG) { CLog.d(LOG_TAG, "work_status: recoverWork %s", this); } mExitTasksEarly = false; setPause(false); Iterator> it = (Iterator>) mLoadWorkList.entrySet().iterator(); while (it.hasNext()) { Entry item = it.next(); LoadImageTask task = item.getValue(); task.restart(); mImageTaskExecutor.execute(task); } }public boolean queryCache(ImageTask imageTask, CubeImageView imageView) { if (null == mImageProvider) { return false; } BitmapDrawable drawable = mImageProvider.getBitmapFromMemCache(imageTask); if (imageTask.getStatistics() != null) { imageTask.getStatistics().s0_afterCheckMemoryCache(drawable != null); } if (drawable == null) { return false; } if (DEBUG) { CLog.d(LOG_TAG, MSG_HIT_CACHE, imageTask, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); } imageTask.addImageView(imageView); imageTask.onLoadTaskFinish(drawable, mImageLoadHandler); return true; }public void addImageTask(ImageTask imageTask, CubeImageView imageView) { if (!mHasBeenAddedToComponentManager) { CLog.w(LOG_TAG, "ImageLoader has not been add to a Component Manager.", this); } LoadImageTask runningTask = mLoadWorkList.get(imageTask.getIdentityKey()); if (runningTask != null) { if (imageView != null) { if (DEBUG) { CLog.d(LOG_TAG, MSG_ATTACK_TO_RUNNING_TASK, imageTask, runningTask.getImageTask()); } runningTask.getImageTask().addImageView(imageView); runningTask.getImageTask().notifyLoading(mImageLoadHandler, imageView); } return; } else { imageTask.addImageView(imageView); } imageTask.onLoading(mImageLoadHandler); LoadImageTask loadImageTask = createLoadImageTask(imageTask); mLoadWorkList.put(imageTask.getIdentityKey(), loadImageTask); mImageTaskExecutor.execute(loadImageTask); }public void detachImageViewFromImageTask(ImageTask imageTask, CubeImageView imageView) { imageTask.removeImageView(imageView); if (imageTask.isLoading()) { if (!imageTask.isPreLoad() && !imageTask.stillHasRelatedImageView()) { LoadImageTask task = mLoadWorkList.get(imageTask.getIdentityKey()); if (task != null) { task.cancel(); } if (DEBUG) { CLog.d(LOG_TAG, "%s previous work is cancelled.", imageTask); } } } if (!imageTask.stillHasRelatedImageView()) { imageTask.tryToRecycle(); } }public void preLoadImages(String[] urls) { int len = urls.length; for (int i = 0; i < len; i++) { ImageLoadRequest request = new ImageLoadRequest(urls[i]); final ImageTask imageTask = createImageTask(request); imageTask.setIsPreLoad(); addImageTask(imageTask, null); } }public BitmapDrawable createBitmapDrawable(Resources resources, Bitmap bitmap) { if (bitmap == null) { return null; } BitmapDrawable drawable = null; if (bitmap != null) { if (Version.hasHoneycomb()) { // Running on Honeycomb or newer, so wrap in a standard BitmapDrawable drawable = new BitmapDrawable(resources, bitmap); } else { // Running on Gingerbread or older, so wrap in a RecyclingBitmapDrawable // which will recycle automatically drawable = new RecyclingBitmapDrawable(resources, bitmap); } } return drawable; }public void addFilePart(String fieldName, File uploadFile, String fileName) throws IOException { if (TextUtils.isEmpty(fileName)) { fileName = uploadFile.getName(); } mWriter.append("--" + mBoundary).append(LINE_FEED); mWriter.append( "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"") .append(LINE_FEED); mWriter.append( "Content-Type: " + URLConnection.guessContentTypeFromName(fileName)) .append(LINE_FEED); mWriter.append("Content-Transfer-Encoding: binary").append(LINE_FEED); mWriter.append(LINE_FEED); mWriter.flush(); FileInputStream inputStream = new FileInputStream(uploadFile); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { mOutputStream.write(buffer, 0, bytesRead); } mOutputStream.flush(); inputStream.close(); mWriter.append(LINE_FEED); mWriter.flush(); }public void addFormField(String name, String value) { mWriter.append("--" + mBoundary).append(LINE_FEED); mWriter.append("Content-Disposition: form-data; name=\"" + name + "\"") .append(LINE_FEED); mWriter.append("Content-Type: text/plain; charset=" + mCharset).append( LINE_FEED); mWriter.append(LINE_FEED); mWriter.append(value).append(LINE_FEED); mWriter.flush(); }public void send() throws IOException { HashMap uploadFiles = mRequestData.getUploadFiles(); HashMap mPostData = mRequestData.getPostData(); // send data to Server if (mPostData != null && mPostData.size() != 0) { Iterator> iterator = mPostData.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry item = iterator.next(); Object value = item.getValue(); if (value == null) { value = ""; } addFormField(item.getKey(), value.toString()); } } // send file to server Iterator> iterator = uploadFiles.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry item = iterator.next(); RequestData.UploadFileInfo uploadFileInfo = item.getValue(); addFilePart(uploadFileInfo.fieldName, uploadFileInfo.uploadFile, uploadFileInfo.fileName); } }public synchronized void stopListening() { if (mListening) { mContext.unregisterReceiver(mReceiver); mContext = null; mNetworkInfo = null; mOtherNetworkInfo = null; mIsFailOver = false; mReason = null; mListening = false; } }public synchronized void startListening(Context context) { if (!mListening) { mContext = context; IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); context.registerReceiver(mReceiver, filter); mListening = true; } }private boolean tryToMove(float deltaY) { // has reached the bottom if ((deltaY > 0 && mCurrentPos == 0)) { if (DEBUG) { Log.d(LOG_TAG, String.format("has reached the bottom")); } return false; } // has reached the top if ((deltaY < 0 && mCurrentPos == -mHeaderHeight)) { if (DEBUG) { Log.d(LOG_TAG, String.format("has reached the top")); } return false; } int to = mCurrentPos + (int) deltaY; // over top if (to < -mHeaderHeight) { if (DEBUG) { Log.d(LOG_TAG, String.format("over top")); } to = -mHeaderHeight; } // over bottom if (to > 0) { if (DEBUG) { Log.d(LOG_TAG, String.format("over bottom")); } to = 0; } return moveTo(to); }protected static int toDigit(final char ch, final int index) throws HexDecodeException { final int digit = Character.digit(ch, 16); if (digit == -1) { throw new HexDecodeException("Illegal hexadecimal character " + ch + " at index " + index); } return digit; }private static String readName( byte data[], int offset, HashSet jumps ) throws IOException { int c = data[offset] & 0xff; if ((c & 0xc0) == 0xc0) { c = ((c & 0x3f) << 8) + (data[offset + 1] & 0xff); if (jumps.contains(c)) { throw new DnsException("", "Cyclic offsets detected."); } jumps.add(c); return readName(data, c, jumps); } if (c == 0) { return ""; } String s = new String(data, offset + 1, c); String t = readName(data, offset + 1 + c, jumps); if (t.length() > 0) { s = s + "." + t; } return s; }public static String decrypt(String data, String key) { try { Cipher c = Cipher.getInstance("DES/ECB/PKCS5Padding"); c.init(Cipher.DECRYPT_MODE, SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(key.getBytes()))); return new String(c.doFinal(Hex.decodeHex(data.toCharArray())), Charset.defaultCharset()); } catch (Exception e) { e.printStackTrace(); } return null; }public static String encrypt(String data, String key) { try { Cipher c = Cipher.getInstance("DES/ECB/PKCS5Padding"); c.init(Cipher.ENCRYPT_MODE, SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(key.getBytes()))); return Hex.encodeHexString(c.doFinal(data.getBytes())); } catch (Exception e) { e.printStackTrace(); } return null; }public String[] getFileNames( File baseDirectory ) { if ( !baseDirectory.exists() ) { return new String[ 0 ]; } final DirectoryScanner directoryScanner = new DirectoryScanner(); directoryScanner.setBasedir( baseDirectory ); directoryScanner.setIncludes( includes ); directoryScanner.addDefaultExcludes(); directoryScanner.scan(); return directoryScanner.getIncludedFiles(); }public static String extractArchitectureFromArtifact( Artifact artifact, final String defaultArchitecture ) { String classifier = artifact.getClassifier(); if ( classifier != null ) { // // We loop backwards to catch the case where the classifier is // potentially armeabi-v7a - this collides with armeabi if looping // through this loop in the other direction // for ( int i = AndroidNdk.NDK_ARCHITECTURES.length - 1; i >= 0; i-- ) { String ndkArchitecture = AndroidNdk.NDK_ARCHITECTURES[i]; if ( classifier.startsWith( ndkArchitecture ) ) { return ndkArchitecture; } } } // Default case is to return the default architecture return defaultArchitecture; }private void performVersionCodeUpdateFromVersion( Element manifestElement ) throws MojoExecutionException { String verString = project.getVersion(); getLog().debug( "Generating versionCode for " + verString ); String verCode = generateVersionCodeFromVersionName( verString ); getLog().info( "Setting " + ATTR_VERSION_CODE + " to " + verCode ); manifestElement.setAttribute( ATTR_VERSION_CODE, verCode ); project.getProperties().setProperty( "android.manifest.versionCode", String.valueOf( verCode ) ); }private void exportProperties() { project.getProperties().setProperty( "android.manifest.versionName", parsedVersionName ); project.getProperties().setProperty( "android.manifest.versionCodeAutoIncrement", String.valueOf( parsedVersionCodeAutoIncrement ) ); project.getProperties().setProperty( "android.manifest.versionCodeUpdateFromVersion", String.valueOf( parsedVersionCodeUpdateFromVersion ) ); project.getProperties().setProperty( "android.manifest.debuggable", String.valueOf( parsedDebuggable ) ); if ( parsedSharedUserId != null ) { project.getProperties().setProperty( "android.manifest.sharedUserId", parsedSharedUserId ); } }private void writeManifest( File manifestFile, Document doc ) throws IOException, TransformerException { TransformerFactory xfactory = TransformerFactory.newInstance(); Transformer xformer = xfactory.newTransformer(); xformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); Source source = new DOMSource( doc ); OutputStreamWriter writer = null; try { manifestFile.getParentFile().mkdirs(); String encoding = doc.getXmlEncoding() != null ? doc.getXmlEncoding() : "UTF-8"; writer = new OutputStreamWriter( new FileOutputStream( manifestFile, false ), encoding ); if ( doc.getXmlEncoding() != null && doc.getXmlVersion() != null ) { String xmldecl = String .format( "%n", doc.getXmlVersion(), doc.getXmlEncoding() ); writer.write( xmldecl ); } Result result = new StreamResult( writer ); xformer.transform( source, result ); } finally { IOUtils.closeQuietly( writer ); } }private Document readManifest( File manifestFile ) throws IOException, ParserConfigurationException, SAXException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse( manifestFile ); return doc; }public String getNdkBuildPath() { if ( SystemUtils.IS_OS_WINDOWS ) { return new File( ndkPath, "/ndk-build.cmd" ).getAbsolutePath(); } else { return new File( ndkPath, "/ndk-build" ).getAbsolutePath(); } }public String getToolchain( File file ) throws MojoExecutionException { String resolvedNdkToolchain = null; // try to resolve the toolchain now String ndkArchitecture = file.getParentFile().getName(); if ( ndkArchitecture.startsWith( "armeabi" ) ) { resolvedNdkToolchain = resolveNdkToolchain( ARM_TOOLCHAIN ); } else if ( ndkArchitecture.startsWith( "arm64" ) ) { resolvedNdkToolchain = resolveNdkToolchain( ARM64_TOOLCHAIN ); } else if ( ndkArchitecture.startsWith( "x86_64" ) ) { resolvedNdkToolchain = resolveNdkToolchain( X86_64_TOOLCHAIN ); } else if ( ndkArchitecture.startsWith( "x86" ) ) { resolvedNdkToolchain = resolveNdkToolchain( X86_TOOLCHAIN ); } else if ( ndkArchitecture.startsWith( "mips64" ) ) { resolvedNdkToolchain = resolveNdkToolchain( MIPS64_TOOLCHAIN ); } else if ( ndkArchitecture.startsWith( "mips" ) ) { resolvedNdkToolchain = resolveNdkToolchain( MIPS_TOOLCHAIN ); } // if no toolchain can be found if ( resolvedNdkToolchain == null ) { throw new MojoExecutionException( "Can not resolve automatically a toolchain to use. Please specify one." ); } return resolvedNdkToolchain; }private File getJVMLibrary( String fileName ) { File libFile = new File( getJavaLibDir(), fileName ); if ( !libFile.exists() ) { libFile = new File( getAltJavaLibDir(), fileName ); if ( !libFile.exists() ) { libFile = null; } } return libFile; }private void collectJvmArguments( List< String > commands ) { if ( parsedJvmArguments != null ) { for ( String jvmArgument : parsedJvmArguments ) { // preserve backward compatibility allowing argument with or without dash (e.g. // Xmx512m as well as -Xmx512m should work) (see // http://code.google.com/p/maven-android-plugin/issues/detail?id=153) if ( !jvmArgument.startsWith( "-" ) ) { jvmArgument = "-" + jvmArgument; } commands.add( jvmArgument ); } } }public static String getGAV() { StringBuilder builder = new StringBuilder() .append( groupId ) .append( COLON ) .append( artifactId ) .append( COLON ) .append( version ); return builder.toString(); }@Override public void execute() throws MojoExecutionException, MojoFailureException { ConfigHandler configHandler = new ConfigHandler( this, this.session, this.execution ); configHandler.parseConfiguration(); getLog().debug( "Parsed values for Android Lint invocation: " ); getLog().debug( "failOnError:" + parsedFailOnError ); getLog().debug( "skip:" + parsedSkip ); getLog().debug( "legacy:" + parsedLegacy ); getLog().debug( "quiet:" + parsedQuiet ); getLog().debug( "ignoreWarnings:" + parsedIgnoreWarnings ); getLog().debug( "warnAll:" + parsedWarnAll ); getLog().debug( "warningsAsErrors:" + parsedWarningsAsErrors ); getLog().debug( "config2:" + parsedConfig ); getLog().debug( "fullPath:" + parsedFullPath ); getLog().debug( "showAll:" + parsedShowAll ); getLog().debug( "disableSourceLines:" + parsedDisableSourceLines ); getLog().debug( "enablehtml: " + parsedEnableHtml ); getLog().debug( "htmlOutputPath:" + parsedHtmlOutputPath ); getLog().debug( "enableSimpleHtml: " + parsedEnableSimpleHtml ); getLog().debug( "simpleHtmlOutputPath:" + parsedSimpleHtmlOutputPath ); getLog().debug( "enableXml: " + parsedEnableXml ); getLog().debug( "xmlOutputPath:" + parsedXmlOutputPath ); getLog().debug( "sources:" + parsedSources ); getLog().debug( "classpath:" + parsedClasspath ); getLog().debug( "libraries:" + parsedLibraries ); if ( parsedSkip ) { getLog().info( "Skipping lint analysis." ); } else { getLog().info( "Performing lint analysis." ); if ( parsedLegacy ) { getLog().info( "Using Lint from the Android SDK." ); executeWhenConfigured(); } else { getLog().info( "Using Lint dependency library." ); runLint(); } } }private void addClassesToClasspath( UnpackedLibHelper helper, MavenProject project, Artifact artifact ) throws MavenExecutionException { // Work out where the dep will be extracted and calculate the file path to the classes jar. // This is location where the GenerateSourcesMojo will extract the classes. final File classesJar = helper.getUnpackedClassesJar( artifact ); log.debug( "Adding to classpath : " + classesJar ); // In order to satisfy the LifecycleDependencyResolver on execution up to a phase that // has a Mojo requiring dependency resolution I need to create a dummy classesJar here. if ( !classesJar.exists() ) { classesJar.getParentFile().mkdirs(); try { final ZipOutputStream zipOutputStream = new ZipOutputStream( new FileOutputStream( classesJar ) ); zipOutputStream.putNextEntry( new ZipEntry( "dummy" ) ); zipOutputStream.close(); log.debug( "Created dummy " + classesJar.getName() + " exist=" + classesJar.exists() ); } catch ( IOException e ) { throw new MavenExecutionException( "Could not add " + classesJar.getName() + " as dependency", e ); } } // Modify the classpath to use an extracted dex file. This will overwrite // any exisiting dependencies with the same information. final Dependency dependency = createSystemScopeDependency( artifact, classesJar, null ); final Dependency providedJar = findProvidedDependencies( dependency, project ); if ( providedJar != null ) { project.getModel().removeDependency( providedJar ); } project.getModel().addDependency( dependency ); }private void addLibsJarsToClassPath( UnpackedLibHelper helper, MavenProject project, Artifact artifact ) throws MavenExecutionException { try { final File unpackLibFolder = helper.getUnpackedLibFolder( artifact ); final File artifactFile = helper.getArtifactToFile( artifact ); ZipFile zipFile = new ZipFile( artifactFile ); Enumeration enumeration = zipFile.entries(); while ( enumeration.hasMoreElements() ) { ZipEntry entry = ( ZipEntry ) enumeration.nextElement(); String entryName = entry.getName(); // Only jar files under 'libs' directory to be processed. if ( Pattern.matches( "^libs/.+\\.jar$", entryName ) ) { final File libsJarFile = new File( unpackLibFolder, entryName ); log.warn( "Adding jar from libs folder to classpath: " + libsJarFile ); // In order to satisfy the LifecycleDependencyResolver on execution up to a phase that // has a Mojo requiring dependency resolution I need to create a dummy classesJar here. if ( !libsJarFile.getParentFile().exists() ) { libsJarFile.getParentFile().mkdirs(); } libsJarFile.createNewFile(); // Add the jar to the classpath. final Dependency dependency = createSystemScopeDependency( artifact, libsJarFile, libsJarFile.getName() ); project.getModel().addDependency( dependency ); addedJarFromLibs = true; } } } catch ( MojoExecutionException e ) { log.debug( "Error extract jars" ); } catch ( ZipException e ) { log.debug( "Error" ); } catch ( IOException e ) { log.debug( "Error" ); } }private static void checkClientSecretsFile( GoogleClientSecrets clientSecrets ) { if ( clientSecrets.getDetails().getClientId().startsWith( "[[INSERT" ) || clientSecrets.getDetails().getClientSecret().startsWith( "[[INSERT" ) ) { LOG.error( "Enter Client ID and Secret from " + "APIs console into resources/client_secrets.json." ); System.exit( 1 ); } }public void execute() throws MojoExecutionException, MojoFailureException { // If we're not on a supported packaging with just skip (Issue 87) // http://code.google.com/p/maven-android-plugin/issues/detail?id=87 if ( ! SUPPORTED_PACKAGING_TYPES.contains( project.getPackaging() ) ) { getLog().info( "Skipping zipalign on " + project.getPackaging() ); return; } ConfigHandler configHandler = new ConfigHandler( this, this.session, this.execution ); configHandler.parseConfiguration(); parsedInputApk = FilenameUtils.separatorsToSystem( parsedInputApk ); parsedOutputApk = FilenameUtils.separatorsToSystem( parsedOutputApk ); getLog().debug( "skip:" + parsedSkip ); getLog().debug( "verbose:" + parsedVerbose ); getLog().debug( "inputApk:" + parsedInputApk ); getLog().debug( "outputApk:" + parsedOutputApk ); getLog().debug( "classifier:" + parsedClassifier ); if ( parsedSkip ) { getLog().info( "Skipping zipalign" ); } else { boolean outputToSameFile = sameOutputAsInput(); CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger( this.getLog() ); String command = getAndroidSdk().getZipalignPath(); List parameters = new ArrayList(); if ( parsedVerbose ) { parameters.add( "-v" ); } parameters.add( "-f" ); // force overwriting existing output file parameters.add( "4" ); // byte alignment has to be 4! parameters.add( parsedInputApk ); String outputApk = outputToSameFile ? getTemporaryOutputApkFilename() : parsedOutputApk; parameters.add( outputApk ); try { getLog().info( "Running command: " + command ); getLog().info( "with parameters: " + parameters ); executor.setCaptureStdOut( true ); executor.executeCommand( command, parameters ); if ( FileUtils.fileExists( outputApk ) ) { if ( outputToSameFile ) { // No needs to attach zipaligned apk to artifacts try { FileUtils.rename( new File( outputApk ), new File( parsedInputApk ) ); } catch ( IOException e ) { getLog().error( "Failed to replace original apk with aligned " + getFullPathWithName( outputApk ), e ); } } else { // Attach the resulting artifact (Issue 88) // http://code.google.com/p/maven-android-plugin/issues/detail?id=88 projectHelper.attachArtifact( project, APK, parsedClassifier, new File( outputApk ) ); getLog().info( "Attach " + getFullPathWithName( outputApk ) + " as '" + parsedClassifier + "' to the project" ); } } else { getLog().error( "Cannot attach " + getFullPathWithName( outputApk ) + " to the project" + " - The file does not exist" ); } } catch ( ExecutionException e ) { throw new MojoExecutionException( "", e ); } } }private Set< File > getDexInputFiles() throws MojoExecutionException { Set< File > inputs = new HashSet< File >(); if ( obfuscatedJar != null && obfuscatedJar.exists() ) { // proguard has been run, use this jar getLog().debug( "Adding dex input (obfuscatedJar) : " + obfuscatedJar ); inputs.add( obfuscatedJar ); } else { getLog().debug( "Using non-obfuscated input" ); // no proguard, use original config inputs.add( projectOutputDirectory ); getLog().debug( "Adding dex input : " + project.getBuild().getOutputDirectory() ); for ( Artifact artifact : filterArtifacts( getTransitiveDependencyArtifacts(), skipDependencies, artifactTypeSet.getIncludes(), artifactTypeSet.getExcludes(), artifactSet.getIncludes(), artifactSet.getExcludes() ) ) { if ( artifact.getType().equals( Const.ArtifactType.NATIVE_SYMBOL_OBJECT ) || artifact.getType().equals( Const.ArtifactType.NATIVE_IMPLEMENTATION_ARCHIVE ) ) { // Ignore native dependencies - no need for dexer to see those } else if ( artifact.getType().equals( APKLIB ) ) { // Any jars in the libs folder should now be // automatically included because they will be a transitive dependency. } else if ( artifact.getType().equals( AAR ) ) { // The Aar classes.jar should now be automatically included // because it will be a transitive dependency. As should any jars in the libs folder. } else if ( artifact.getType().equals( APK ) ) { // We need to dex the APK classes including the APK R. // But we don't want to add a second instance of the embedded Rs for any of the APK's dependencies // as they will already have been generated to target/classes. The R values from the APK will be // the correct ones, so best solution is to extract the APK classes (including all Rs) to // target/classes overwriting any generated Rs and let dex pick up the values from there. getLog().debug( "Extracting APK classes to target/classes : " + artifact.getArtifactId() ); final File apkClassesJar = getUnpackedLibHelper().getJarFileForApk( artifact ); getLog().debug( "Extracting APK : " + apkClassesJar + " to " + targetDirectory ); final ZipExtractor extractor = new ZipExtractor( getLog() ); extractor.extract( apkClassesJar, targetDirectory, ".class" ); } else { getLog().debug( "Adding dex input : " + artifact.getFile() ); inputs.add( artifact.getFile().getAbsoluteFile() ); } } } return inputs; }private boolean isBuildConfigPresent( Artifact artifact, String packageName ) throws MojoExecutionException { try { JarFile jar = new JarFile( getUnpackedAarClassesJar( artifact ) ); JarEntry entry = jar.getJarEntry( packageName.replace( '.', '/' ) + "/BuildConfig.class" ); return ( entry != null ); } catch ( IOException e ) { getLog().error( "Error generating BuildConfig ", e ); throw new MojoExecutionException( "Error generating BuildConfig", e ); } }private boolean isBuildConfigPresent( Artifact artifact ) throws MojoExecutionException { String depPackageName = extractPackageNameFromAndroidArtifact( artifact ); return isBuildConfigPresent( artifact, depPackageName ); }private void generateRForApkLibDependency( Artifact apklibArtifact ) throws MojoExecutionException { final File unpackDir = getUnpackedLibFolder( apklibArtifact ); getLog().debug( "Generating incomplete R file for apklib: " + apklibArtifact.getGroupId() + ":" + apklibArtifact.getArtifactId() ); final File apklibManifest = new File( unpackDir, "AndroidManifest.xml" ); final File apklibResDir = new File( unpackDir, "res" ); List dependenciesResDirectories = new ArrayList(); final Set apklibDeps = getDependencyResolver() .getLibraryDependenciesFor( this.session, this.repositorySystem, apklibArtifact ); getLog().debug( "apklib=" + apklibArtifact + " dependencies=" + apklibDeps ); for ( Artifact dependency : apklibDeps ) { // Add in the resources that are dependencies of the apklib. final String extension = dependency.getType(); final File dependencyResDir = getUnpackedLibResourceFolder( dependency ); if ( ( extension.equals( APKLIB ) || extension.equals( AAR ) ) && dependencyResDir.exists() ) { dependenciesResDirectories.add( dependencyResDir ); } } // Create combinedAssets for this apklib dependency - can't have multiple -A args final File apklibCombAssets = new File( getUnpackedLibFolder( apklibArtifact ), "combined-assets" ); for ( Artifact dependency : apklibDeps ) { // Accumulate assets for dependencies of the apklib (if they exist). final String extension = dependency.getType(); final File dependencyAssetsDir = getUnpackedLibAssetsFolder( dependency ); if ( ( extension.equals( APKLIB ) || extension.equals( AAR ) ) ) { copyFolder( dependencyAssetsDir, apklibCombAssets ); } } // Overlay the apklib dependency assets (if they exist) final File apkLibAssetsDir = getUnpackedLibAssetsFolder( apklibArtifact ); copyFolder( apkLibAssetsDir, apklibCombAssets ); final CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger( getLog() ); final AaptCommandBuilder commandBuilder = AaptCommandBuilder .packageResources( getLog() ) .makeResourcesNonConstant() .makePackageDirectories() .setResourceConstantsFolder( genDirectory ) .generateRIntoPackage( extractPackageNameFromAndroidManifest( apklibManifest ) ) .setPathToAndroidManifest( apklibManifest ) .addResourceDirectoryIfExists( apklibResDir ) .addResourceDirectoriesIfExists( dependenciesResDirectories ) .autoAddOverlay() .addRawAssetsDirectoryIfExists( apklibCombAssets ) .addExistingPackageToBaseIncludeSet( getAndroidSdk().getAndroidJar() ) .addConfigurations( configurations ) .setVerbose( aaptVerbose ) .addExtraArguments( aaptExtraArgs ) // We need to generate R.txt for all projects as it needs to be consumed when generating R class. // It also needs to be consumed when packaging aar. .generateRTextFile( unpackDir ); getLog().debug( getAndroidSdk().getAaptPath() + " " + commandBuilder.toString() ); try { executor.setCaptureStdOut( true ); final List commands = commandBuilder.build(); executor.executeCommand( getAndroidSdk().getAaptPath(), commands, project.getBasedir(), false ); } catch ( ExecutionException e ) { throw new MojoExecutionException( "", e ); } }private void generateCorrectRJavaForAarDependencies( ResourceClassGenerator resourceGenerator ) throws MojoExecutionException { // Generate corrected R.java for AAR dependencies. final Set aarLibraries = getTransitiveDependencyArtifacts( AAR ); if ( !aarLibraries.isEmpty() ) { // Generate R.java for each AAR based on R.txt getLog().debug( "Generating R file for AAR dependencies" ); resourceGenerator.generateLibraryRs( aarLibraries ); } }private void generateCorrectRJavaForApklibDependencies( ResourceClassGenerator resourceGenerator ) throws MojoExecutionException { getLog().debug( "" ); getLog().debug( "#generateCorrectRJavaFoApklibDeps" ); // Generate R.java for apklibs // Compatibility with Apklib which isn't present in AndroidBuilder getLog().debug( "Generating Rs for apklib deps of project " + project.getArtifact() ); final Set apklibDependencies = getTransitiveDependencyArtifacts( APKLIB ); for ( final Artifact artifact : apklibDependencies ) { getLog().debug( "Generating apklib R.java for " + artifact.getArtifactId() + "..." ); generateRForApkLibDependency( artifact ); } // Generate corrected R.java for APKLIB dependencies, but only if this is an APK build. if ( !apklibDependencies.isEmpty() && APK.equals( project.getArtifact().getType() ) ) { // Generate R.java for each APKLIB based on R.txt getLog().debug( "" ); getLog().debug( "Rewriting R files for APKLIB dependencies : " + apklibDependencies ); resourceGenerator.generateLibraryRs( apklibDependencies ); } }Map> getPackageCompareMap( Set dependencyArtifacts ) throws MojoExecutionException { if ( dependencyArtifacts == null ) { throw new IllegalArgumentException( "dependencies must be initialized" ); } Map> packageCompareMap = new HashMap>(); Set artifactSet = new HashSet(); artifactSet.add( project.getArtifact() ); packageCompareMap.put( getAndroidManifestPackageName(), artifactSet ); for ( Artifact artifact : dependencyArtifacts ) { String libPackage = extractPackageNameFromAndroidArtifact( artifact ); Set artifacts = packageCompareMap.get( libPackage ); if ( artifacts == null ) { artifacts = new HashSet(); packageCompareMap.put( libPackage, artifacts ); } artifacts.add( artifact ); } return packageCompareMap; }private void checkForApklibDependencies() throws MojoExecutionException { final boolean isAarBuild = project.getPackaging().equals( AAR ); final DependencyResolver dependencyResolver = getDependencyResolver(); final Set allArtifacts = project.getArtifacts(); Set dependencyArtifacts = getArtifactResolverHelper().getFilteredArtifacts( allArtifacts ); boolean foundApklib = false; for ( Artifact artifact : dependencyArtifacts ) { final String type = artifact.getType(); if ( type.equals( APKLIB ) && isAarBuild ) { getLog().warn( "Detected APKLIB transitive dependency: " + artifact.getId() ); foundApklib = true; } else if ( type.equals( AAR ) ) { final Set dependencies = dependencyResolver .getLibraryDependenciesFor( session, repositorySystem, artifact ); for ( Artifact dependency : dependencies ) { if ( dependency.getType().equals( APKLIB ) ) { getLog().warn( "Detected " + artifact.getId() + " that depends on APKLIB: " + dependency.getId() ); foundApklib = true; } } } } if ( foundApklib ) { getLog().warn( "AAR libraries should not depend or include APKLIB artifacts.\n" + "APKLIBs have been deprecated and the combination of the two may yield unexpected results.\n" + "Check the problematic AAR libraries for newer versions that use AAR packaging." ); } }private void extractAarLib( Artifact aarArtifact ) throws MojoExecutionException { getUnpackedLibHelper().extractAarLib( aarArtifact ); // Copy the assets to the the combinedAssets folder, but only if an APK build. // Ie we only want to package assets that we own. // Assets should only live within their owners or the final APK. if ( isAPKBuild() ) { copyFolder( getUnpackedLibAssetsFolder( aarArtifact ), combinedAssets ); } // Aar lib resources should only be included if we are building an apk. // So we need to extract them into a folder that we then add to the resource classpath. if ( isAPKBuild() ) { // (If we are including SYSTEM_SCOPE artifacts when considering resources for APK packaging) // then adding the AAR resources to the project would have them added twice. getLog().debug( "Not adding AAR resources to resource classpath : " + aarArtifact ); } }private void extractApklib( Artifact apklibArtifact ) throws MojoExecutionException { getUnpackedLibHelper().extractApklib( apklibArtifact ); // Copy the assets to the the combinedAssets folder. // Add the apklib source and resource to the compile. // NB apklib sources are added to compileSourceRoot because we may need to compile against them. // This means the apklib classes will be compiled into target/classes and packaged with this build. copyFolder( getUnpackedLibAssetsFolder( apklibArtifact ), combinedAssets ); final File apklibSourceFolder = getUnpackedApkLibSourceFolder( apklibArtifact ); final List resourceExclusions = Arrays.asList( "**/*.java", "**/*.aidl" ); projectHelper.addResource( project, apklibSourceFolder.getAbsolutePath(), null, resourceExclusions ); project.addCompileSourceRoot( apklibSourceFolder.getAbsolutePath() ); }protected void extractSourceDependencies() throws MojoExecutionException { for ( Artifact artifact : getDirectDependencyArtifacts() ) { String type = artifact.getType(); if ( type.equals( APKSOURCES ) ) { getLog().debug( "Detected apksources dependency " + artifact + " with file " + artifact.getFile() + ". Will resolve and extract..." ); final File apksourcesFile = resolveArtifactToFile( artifact ); getLog().debug( "Extracting " + apksourcesFile + "..." ); extractApksources( apksourcesFile ); } } if ( extractedDependenciesJavaResources.exists() ) { projectHelper.addResource( project, extractedDependenciesJavaResources.getAbsolutePath(), null, null ); project.addCompileSourceRoot( extractedDependenciesJavaSources.getAbsolutePath() ); } }protected void copyManifest() throws MojoExecutionException { getLog().debug( "copyManifest: " + androidManifestFile + " -> " + destinationManifestFile ); if ( androidManifestFile == null ) { getLog().debug( "Manifest copying disabled. Using default manifest only" ); return; } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse( androidManifestFile ); Source source = new DOMSource( doc ); TransformerFactory xfactory = TransformerFactory.newInstance(); Transformer xformer = xfactory.newTransformer(); xformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); FileWriter writer = null; try { destinationManifestFile.getParentFile().mkdirs(); writer = new FileWriter( destinationManifestFile, false ); if ( doc.getXmlEncoding() != null && doc.getXmlVersion() != null ) { String xmldecl = String.format( "%n", doc.getXmlVersion(), doc.getXmlEncoding() ); writer.write( xmldecl ); } Result result = new StreamResult( writer ); xformer.transform( source, result ); getLog().info( "Manifest copied from " + androidManifestFile + " to " + destinationManifestFile ); } finally { IOUtils.closeQuietly( writer ); } } catch ( Exception e ) { getLog().error( "Error during copyManifest" ); throw new MojoExecutionException( "Error during copyManifest", e ); } }public void execute() throws MojoExecutionException, MojoFailureException { // If the current POM isn't an Android-related POM, then don't do // anything. This helps work with multi-module projects. if ( !isCurrentProjectAndroid() ) { return; } validateStandardLocations(); try { targetDirectory.mkdirs(); copyManifest(); // Check for a deprecated AAR > APKLIB artifact combination if ( warnOnApklibDependencies ) { checkForApklibDependencies(); } // TODO Do we really want to continue supporting APKSOURCES? How long has it been deprecated extractSourceDependencies(); // Extract the apklib and aar dependencies into unpacked-libs so that they can be referenced in the build. extractLibraryDependencies(); // Copy project assets to combinedAssets so that aapt has a single assets folder to load. copyFolder( assetsDirectory, combinedAssets ); final String[] relativeAidlFileNames1 = findRelativeAidlFileNames( aidlSourceDirectory ); final String[] relativeAidlFileNames2 = findRelativeAidlFileNames( extractedDependenciesJavaSources ); final Map relativeApklibAidlFileNames = new HashMap(); if ( !isInstrumentationTest() ) { // Only add transitive APKLIB deps if we are building an APK and not an instrumentation test apk. for ( Artifact artifact : getTransitiveDependencyArtifacts( APKLIB ) ) { final File libSourceFolder = getUnpackedApkLibSourceFolder( artifact ); final String[] apklibAidlFiles = findRelativeAidlFileNames( libSourceFolder ); relativeApklibAidlFileNames.put( artifact.getId(), apklibAidlFiles ); } } checkPackagesForDuplicates(); checkForConflictingLayouts(); generateR(); generateBuildConfig(); // When compiling AIDL for this project, // make sure we compile AIDL for dependencies as well. // This is so project A, which depends on project B, can // use AIDL info from project B in its own AIDL final Map files = new HashMap(); files.put( aidlSourceDirectory, relativeAidlFileNames1 ); files.put( extractedDependenciesJavaSources, relativeAidlFileNames2 ); if ( !isInstrumentationTest() ) { // Only add transitive APKLIB deps if we are building an APK and not an instrumentation test apk. for ( Artifact artifact : getTransitiveDependencyArtifacts( APKLIB ) ) { final File unpackedLibSourceFolder = getUnpackedApkLibSourceFolder( artifact ); files.put( unpackedLibSourceFolder, relativeApklibAidlFileNames.get( artifact.getId() ) ); } } generateAidlFiles( files ); } catch ( MojoExecutionException e ) { getLog().error( "Error when generating sources.", e ); throw e; } }private void loadSDKToolsMajorVersion() { File propFile = new File( sdkPath, "tools/" + SOURCE_PROPERTIES_FILENAME ); Properties properties = new Properties(); try { properties.load( new FileInputStream( propFile ) ); } catch ( IOException e ) { throw new InvalidSdkException( "Error reading " + propFile.getAbsoluteFile() ); } if ( properties.containsKey( SDK_TOOLS_REVISION_PROPERTY ) ) { try { String versionString = properties.getProperty( SDK_TOOLS_REVISION_PROPERTY ); String majorVersion; if ( versionString.matches( ".*[\\.| ].*" ) ) { String[] versions = versionString.split( "[\\.| ]" ); majorVersion = versions[ 0 ]; } else { majorVersion = versionString; } sdkMajorVersion = Integer.parseInt( majorVersion ); } catch ( NumberFormatException e ) { throw new InvalidSdkException( "Error - The property '" + SDK_TOOLS_REVISION_PROPERTY + "' in the SDK source.properties file number is not an Integer: " + properties.getProperty( SDK_TOOLS_REVISION_PROPERTY ) ); } } }public File getPlatform() { assertPathIsDirectory( sdkPath ); final File platformsDirectory = new File( sdkPath, PLATFORMS_FOLDER_NAME ); assertPathIsDirectory( platformsDirectory ); final File platformDirectory; if ( androidTarget == null ) { IAndroidTarget latestTarget = null; AndroidTargetManager targetManager = sdkManager.getAndroidTargetManager( progressIndicator ); for ( IAndroidTarget target: targetManager.getTargets( progressIndicator ) ) { if ( target.isPlatform() ) { if ( latestTarget == null || target.getVersion().getApiLevel() > latestTarget.getVersion().getApiLevel() ) { latestTarget = target; } } } platformDirectory = new File ( latestTarget.getLocation() ); } else { platformDirectory = new File( androidTarget.getLocation() ); } assertPathIsDirectory( platformDirectory ); return platformDirectory; }public File getAndroidJar() throws MojoExecutionException { final String androidJarPath = androidTarget.getPath( IAndroidTarget.ANDROID_JAR ); if ( androidJarPath == null ) { throw new MojoExecutionException( "No AndroidJar found for " + androidTarget.getLocation() ); } return new File ( androidJarPath ); }public String getAndroidPath() { String cmd = "android"; String ext = SdkConstants.currentPlatform() == 2 ? ".bat" : ""; return getPathForTool( cmd + ext ); }public String getMainDexClassesRulesPath() { File mainDexClassesRules = new File( getBuildToolInfo().getLocation(), "mainDexClasses.rules" ); if ( mainDexClassesRules.exists() ) { return mainDexClassesRules.getAbsolutePath(); } throw new InvalidSdkException( "Cannot find " + mainDexClassesRules ); }public String getBuildToolsLibDirectoryPath() { File buildToolsLib = new File( getBuildToolInfo().getLocation(), "lib" ); if ( buildToolsLib.exists() ) { return buildToolsLib.getAbsolutePath(); } throw new InvalidSdkException( "Cannot find " + buildToolsLib ); }public String getShrinkedAndroidJarPath() { File shrinkedAndroidJar = new File( getBuildToolsLibDirectoryPath(), "shrinkedAndroid.jar" ); if ( shrinkedAndroidJar.exists() ) { return shrinkedAndroidJar.getAbsolutePath(); } throw new InvalidSdkException( "Cannot find " + shrinkedAndroidJar ); }public String getProguardJarPath() { File directory = new File( getToolsPath(), "proguard" + File.separator + "lib" + File.separator ); File proguardJar = new File( directory, "proguard.jar" ); if ( proguardJar.exists() ) { return proguardJar.getAbsolutePath(); } throw new InvalidSdkException( "Cannot find " + proguardJar ); }private static File getJavaExecutable() { final String javaHome = System.getProperty( "java.home" ); final String slash = File.separator; return new File( javaHome + slash + "bin" + slash + "java" ); }private void copyGdbServer( File destinationDirectory, String architecture ) throws MojoExecutionException { try { final File destDir = new File( destinationDirectory, architecture ); if ( destDir.exists() ) { // Copy the gdbserver binary to libs// final File gdbServerFile = getAndroidNdk().getGdbServer( architecture ); final File destFile = new File( destDir, "gdbserver" ); if ( ! destFile.exists() ) { getLog().debug( "Copying gdbServer to " + destFile ); FileUtils.copyFile( gdbServerFile, destFile ); } else { getLog().info( "Note: gdbserver binary already exists at destination, will not copy over" ); } } } catch ( Exception e ) { getLog().error( "Error while copying gdbserver: " + e.getMessage(), e ); throw new MojoExecutionException( "Error while copying gdbserver: " + e.getMessage(), e ); } }private static void copyStreamWithoutClosing( InputStream in, OutputStream out ) throws IOException { final int bufferSize = 4096; byte[] b = new byte[ bufferSize ]; int n; while ( ( n = in.read( b ) ) != - 1 ) { out.write( b, 0, n ); } }public void execute() throws MojoExecutionException, MojoFailureException { doWithDevices( new DeviceCallback() { public void doWithDevice( final IDevice device ) throws MojoExecutionException { getLog().info( DeviceHelper.getDescriptiveNameWithStatus( device ) ); } } ); }public void generateLibraryRs( final Set libraries ) { // list of all the symbol tables final List symbolTables = new ArrayList<>( libraries.size() ); // For each dependency, load its symbol file. for ( final Artifact lib : libraries ) { final File unpackedLibDirectory = mojo.getUnpackedLibFolder( lib ); final File rFile = new File( unpackedLibDirectory, "R.txt" ); if ( rFile.isFile() ) { final File libManifestFile = new File( unpackedLibDirectory, "AndroidManifest.xml" ); final String packageName = new DefaultManifestParser( libManifestFile ).getPackage(); if ( rJavaAlreadyExists( packageName ) ) { log.info( "Not creating R for " + packageName + " as it already exists" ); continue; } log.info( "Generating R for " + packageName + " at " + rFile ); SymbolTable libSymbols = SymbolIo.read( rFile ); libSymbols = libSymbols.rename( packageName, libSymbols.getTableName() ); symbolTables.add( libSymbols ); } } if ( symbolTables.isEmpty() ) { return; } // load the full resources values from the R.txt calculated for the project. final File projectR = new File( targetDirectory, "R.txt" ); final SymbolTable mainSymbols = SymbolIo.read( projectR ); // now loop on all the package name, merge all the symbols to write, and write them RGeneration.generateRForLibraries( mainSymbols, symbolTables, genDirectory.getAbsoluteFile(), false ); }protected String extractInstrumentationRunnerFromAndroidManifest( File manifestFile ) throws MojoExecutionException { final URL xmlURL; try { xmlURL = manifestFile.toURI().toURL(); } catch ( MalformedURLException e ) { throw new MojoExecutionException( "Error while trying to figure out instrumentation runner from inside AndroidManifest.xml file " + manifestFile, e ); } final DocumentContainer documentContainer = new DocumentContainer( xmlURL ); final Object instrumentationRunner; try { instrumentationRunner = JXPathContext.newContext( documentContainer ) .getValue( "manifest//instrumentation/@android:name", String.class ); } catch ( JXPathNotFoundException e ) { return null; } return ( String ) instrumentationRunner; }protected String extractPackageNameFromAndroidArtifact( Artifact artifact ) throws MojoExecutionException { final File unpackedLibFolder = getUnpackedLibFolder( artifact ); final File manifest = new File( unpackedLibFolder, "AndroidManifest.xml" ); if ( !manifest.exists() ) { throw new MojoExecutionException( "AndroidManifest.xml file wasn't found in next place: " + unpackedLibFolder ); } return extractPackageNameFromAndroidManifest( manifest ); }protected String extractPackageNameFromApk( File apkFile ) throws MojoExecutionException { CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger( this.getLog() ); executor.setCaptureStdOut( true ); executor.setCaptureStdErr( true ); AaptCommandBuilder commandBuilder = AaptCommandBuilder .dump( getLog() ) .xmlTree() .setPathToApk( apkFile.getAbsolutePath() ) .addAssetFile( "AndroidManifest.xml" ); getLog().info( getAndroidSdk().getAaptPath() + " " + commandBuilder.toString() ); try { executor.executeCommand( getAndroidSdk().getAaptPath(), commandBuilder.build(), false ); final String xmlTree = executor.getStandardOut(); return extractPackageNameFromAndroidManifestXmlTree( xmlTree ); } catch ( ExecutionException e ) { throw new MojoExecutionException( "Error while trying to figure out package name from inside apk file " + apkFile ); } finally { String errout = executor.getStandardError(); if ( ( errout != null ) && ( errout.trim().length() > 0 ) ) { getLog().error( errout ); } } }protected boolean undeployApk( final String packageName ) throws MojoExecutionException, MojoFailureException { final AtomicBoolean result = new AtomicBoolean( true ); // if no devices are present, it counts as successful doWithDevices( new DeviceCallback() { public void doWithDevice( final IDevice device ) throws MojoExecutionException { String deviceLogLinePrefix = DeviceHelper.getDeviceLogLinePrefix( device ); try { device.uninstallPackage( packageName ); getLog().info( deviceLogLinePrefix + "Successfully uninstalled " + packageName ); getLog().debug( " from " + DeviceHelper.getDescriptiveName( device ) ); result.set( true ); } catch ( InstallException e ) { result.set( false ); throw new MojoExecutionException( deviceLogLinePrefix + "Uninstall of " + packageName + " failed.", e ); } } } ); return result.get(); }protected boolean undeployApk( File apkFile ) throws MojoExecutionException, MojoFailureException { final String packageName; packageName = extractPackageNameFromApk( apkFile ); return undeployApk( packageName ); }protected void deployBuiltApk() throws MojoExecutionException, MojoFailureException { if ( project.getPackaging().equals( APK ) ) { File apkFile = new File( targetDirectory, finalName + "." + APK ); deployApk( apkFile ); } else { getLog().info( "Project packaging is not apk, skipping deployment." ); } }protected void deployApk( final File apkFile ) throws MojoExecutionException, MojoFailureException { if ( undeployBeforeDeploy ) { undeployApk( apkFile ); } doWithDevices( new DeviceCallback() { public void doWithDevice( final IDevice device ) throws MojoExecutionException { String deviceLogLinePrefix = DeviceHelper.getDeviceLogLinePrefix( device ); try { device.installPackage( apkFile.getAbsolutePath(), true ); getLog().info( deviceLogLinePrefix + "Successfully installed " + apkFile.getAbsolutePath() ); getLog().debug( " to " + DeviceHelper.getDescriptiveName( device ) ); } catch ( InstallException e ) { throw new MojoExecutionException( deviceLogLinePrefix + "Install of " + apkFile.getAbsolutePath() + " failed.", e ); } } } ); }protected void waitForInitialDeviceList( final AndroidDebugBridge androidDebugBridge ) throws MojoExecutionException { if ( ! androidDebugBridge.hasInitialDeviceList() ) { getLog().info( "Waiting for initial device list from the Android Debug Bridge" ); long limitTime = System.currentTimeMillis() + ADB_TIMEOUT_MS; while ( ! androidDebugBridge.hasInitialDeviceList() && ( System.currentTimeMillis() < limitTime ) ) { try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) { throw new MojoExecutionException( "Interrupted waiting for initial device list from Android Debug Bridge" ); } } if ( ! androidDebugBridge.hasInitialDeviceList() ) { getLog().error( "Did not receive initial device list from the Android Debug Bridge." ); } } }private void waitUntilConnected( AndroidDebugBridge adb ) { int trials = 10; final int connectionWaitTime = 50; while ( trials > 0 ) { try { Thread.sleep( connectionWaitTime ); } catch ( InterruptedException e ) { e.printStackTrace(); } if ( adb.isConnected() ) { break; } trials--; } }private Artifact resolveArtifact( Artifact artifact ) throws MojoExecutionException { final ArtifactResolutionRequest artifactResolutionRequest = new ArtifactResolutionRequest(); artifactResolutionRequest.setArtifact( artifact ); if ( remoteArtifactRepositories != null && !remoteArtifactRepositories.isEmpty() ) { artifactResolutionRequest.setRemoteRepositories( remoteArtifactRepositories ); } final ArtifactResolutionResult resolutionResult = this.artifactResolver.resolve( artifactResolutionRequest ); log.debug( "Resolving : " + artifact ); if ( resolutionResult.getArtifacts().size() == 0 ) { throw new MojoExecutionException( "Could not resolve artifact " + artifact + ". Please install it with \"mvn install:install-file ...\" or deploy it to a repository " + "with \"mvn deploy:deploy-file ...\"" ); } if ( resolutionResult.getArtifacts().size() > 1 ) { log.debug( "Resolved artifacts : " + resolutionResult.getArtifacts() ); throw new MojoExecutionException( "Could not resolve artifact " + artifact + " to single target. Found the following possible options : " + resolutionResult.getArtifacts() ); } final Artifact resolvedArtifact = resolutionResult.getArtifacts().iterator().next(); log.debug( "Resolved : " + resolvedArtifact ); return resolvedArtifact; }public void visit( DependencyNode node, boolean collecting ) { if ( collecting ) { dependencies.add( node.getArtifact() ); } if ( matchesTarget( node.getArtifact() ) ) { collecting = true; log.debug( "Found target. Collecting dependencies after " + node.getArtifact() ); } for ( final DependencyNode child : node.getChildren() ) { visit( child, collecting ); } }private Map calculateSourceDestinationMapping() throws MojoExecutionException { Map result = new HashMap(); File sourceFile = new File( parsedSource ); final String destinationPath; if ( parsedDestination.endsWith( "/" ) ) { destinationPath = parsedDestination + sourceFile.getName(); } else { destinationPath = parsedDestination; } if ( sourceFile.isFile() ) { // only put the source in final String sourcePath = sourceFile.getAbsolutePath(); result.put( sourcePath, destinationPath ); } else { if ( sourceFile.isDirectory() ) { // find recursively all files to be pushed @SuppressWarnings( "unchecked" ) Collection filesList = FileUtils .listFiles( sourceFile, null, true ); for ( File file : filesList ) { // make the file's path relative - this is kind of a hack but it // works just fine in this controlled environment String filePath = file.getAbsolutePath().substring( sourceFile.getAbsolutePath().length() ); filePath = filePath.replace( System.getProperty( "file.separator" ), "/" ); result.put( file.getAbsolutePath(), destinationPath + filePath ); } } else { throw new MojoExecutionException( "Cannot execute push goal: File or directory " + sourceFile.getAbsolutePath() + " does not exist." ); } } return result; }public static void unjar( JarFile jarFile, File outputDirectory, UnjarListener unjarListener ) throws IOException { for ( Enumeration en = jarFile.entries(); en.hasMoreElements(); ) { JarEntry entry = ( JarEntry ) en.nextElement(); File entryFile = new File( outputDirectory, entry.getName() ); if ( unjarListener.include( entry ) ) { // Create the output directory if need be if ( ! entryFile.getParentFile().exists() ) { if ( ! entryFile.getParentFile().mkdirs() ) { throw new IOException( "Error creating output directory: " + entryFile.getParentFile() ); } } // If the entry is an actual file, unzip that too if ( ! entry.isDirectory() ) { final InputStream in = jarFile.getInputStream( entry ); try { final OutputStream out = new FileOutputStream( entryFile ); try { IOUtil.copy( in, out ); } finally { IOUtils.closeQuietly( out ); } } finally { IOUtils.closeQuietly( in ); } } } } }String determineEmulatorLocation() { String location; if ( emulatorLocation != null ) { location = emulatorLocation; } else { location = "SdkTools"; } return location; }String determineAvd() { String avd; if ( emulatorAvd != null ) { avd = emulatorAvd; } else { avd = "Default"; } return avd; }private String determineOptions() { String options; if ( emulatorOptions != null ) { options = emulatorOptions; } else { options = ""; } return options; }String determineWait() { String wait; if ( emulatorWait != null ) { wait = emulatorWait; } else { wait = "5000"; } return wait; }private String determineExecutable() { String emulator; if ( emulatorExecutable != null ) { emulator = emulatorExecutable; } else { emulator = "emulator"; } return emulator; }private String assembleStartCommandLine() throws MojoExecutionException { String emulatorPath; if ( !"SdkTools".equals( parsedEmulatorLocation ) ) { emulatorPath = new File( parsedEmulatorLocation, parsedExecutable ).getAbsolutePath(); } else { emulatorPath = new File( getAndroidSdk().getToolsPath(), parsedExecutable ).getAbsolutePath(); } StringBuilder startCommandline = new StringBuilder( "\"\"" ).append( emulatorPath ).append( "\"\"" ) .append( " -avd " ).append( parsedAvd ).append( " " ); if ( !StringUtils.isEmpty( parsedOptions ) ) { startCommandline.append( parsedOptions ); } getLog().info( "Android emulator command: " + startCommandline ); return startCommandline.toString(); }private boolean sendEmulatorCommand( //final Launcher launcher, //final PrintStream logger, final int port, final String command ) { Callable task = new Callable() { public Boolean call() throws IOException { Socket socket = null; BufferedReader in = null; PrintWriter out = null; try { socket = new Socket( "127.0.0.1", port ); out = new PrintWriter( socket.getOutputStream(), true ); in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) ); if ( in.readLine() == null ) { return false; } out.write( command ); out.write( "\r\n" ); } finally { try { out.close(); in.close(); socket.close(); } catch ( Exception e ) { // Do nothing } } return true; } private static final long serialVersionUID = 1L; }; boolean result = false; try { ExecutorService executor = Executors.newSingleThreadExecutor(); Future future = executor.submit( task ); result = future.get(); } catch ( Exception e ) { getLog().error( String.format( "Failed to execute emulator command '%s': %s", command, e ) ); } return result; }private void stopEmulator( IDevice device ) { int devicePort = extractPortFromDevice( device ); if ( devicePort == -1 ) { getLog().info( "Unable to retrieve port to stop emulator " + DeviceHelper.getDescriptiveName( device ) ); } else { getLog().info( "Stopping emulator " + DeviceHelper.getDescriptiveName( device ) ); sendEmulatorCommand( devicePort, "avd stop" ); boolean killed = sendEmulatorCommand( devicePort, "kill" ); if ( !killed ) { getLog().info( "Emulator failed to stop " + DeviceHelper.getDescriptiveName( device ) ); } else { getLog().info( "Emulator stopped successfully " + DeviceHelper.getDescriptiveName( device ) ); } } }protected void stopAndroidEmulator() throws MojoExecutionException { parseParameters(); final AndroidDebugBridge androidDebugBridge = initAndroidDebugBridge(); if ( androidDebugBridge.isConnected() ) { List devices = Arrays.asList( androidDebugBridge.getDevices() ); int numberOfDevices = devices.size(); getLog().info( "Found " + numberOfDevices + " devices connected with the Android Debug Bridge" ); for ( IDevice device : devices ) { if ( device.isEmulator() ) { if ( isExistingEmulator( device ) ) { stopEmulator( device ); } } else { getLog().info( "Skipping stop. Not an emulator. " + DeviceHelper.getDescriptiveName( device ) ); } } } }private String writeEmulatorStartScriptUnix() throws MojoExecutionException { String filename = SCRIPT_FOLDER + "/android-maven-plugin-emulator-start.sh"; File sh; sh = new File( "/bin/bash" ); if ( !sh.exists() ) { sh = new File( "/usr/bin/bash" ); } if ( !sh.exists() ) { sh = new File( "/bin/sh" ); } File file = new File( filename ); PrintWriter writer = null; try { writer = new PrintWriter( new FileWriter( file ) ); writer.println( "#!" + sh.getAbsolutePath() ); writer.print( assembleStartCommandLine() ); writer.print( " 1>/dev/null 2>&1 &" ); // redirect outputs and run as background task } catch ( IOException e ) { getLog().error( "Failure writing file " + filename ); } finally { if ( writer != null ) { writer.flush(); writer.close(); } } file.setExecutable( true ); return filename; }private String writeEmulatorStartScriptWindows() throws MojoExecutionException { String filename = SCRIPT_FOLDER + "\\android-maven-plugin-emulator-start.vbs"; File file = new File( filename ); PrintWriter writer = null; try { writer = new PrintWriter( new FileWriter( file ) ); // command needs to be assembled before unique window title since it parses settings and sets up parsedAvd // and others. String command = assembleStartCommandLine(); String uniqueWindowTitle = "AndroidMavenPlugin-AVD" + parsedAvd; writer.println( "Dim oShell" ); writer.println( "Set oShell = WScript.CreateObject(\"WScript.shell\")" ); String cmdPath = System.getenv( "COMSPEC" ); if ( cmdPath == null ) { cmdPath = "cmd.exe"; } String cmd = cmdPath + " /X /C START /SEPARATE \"\"" + uniqueWindowTitle + "\"\" " + command.trim(); writer.println( "oShell.run \"" + cmd + "\"" ); } catch ( IOException e ) { getLog().error( "Failure writing file " + filename ); } finally { if ( writer != null ) { writer.flush(); writer.close(); } } file.setExecutable( true ); return filename; }void unlockEmulator( AndroidDebugBridge androidDebugBridge ) { if ( emulatorUnlock ) { IDevice myEmulator = findExistingEmulator( Arrays.asList( androidDebugBridge.getDevices() ) ); int devicePort = extractPortFromDevice( myEmulator ); if ( devicePort == -1 ) { getLog().info( "Unable to retrieve port to unlock emulator " + DeviceHelper.getDescriptiveName( myEmulator ) ); } else { getLog().info( "Unlocking emulator " + DeviceHelper.getDescriptiveName( myEmulator ) ); sendEmulatorCommand( devicePort, "event send EV_KEY:KEY_SOFT1:1" ); sendEmulatorCommand( devicePort, "event send EV_KEY:KEY_SOFT1:0" ); sendEmulatorCommand( devicePort, "event send EV_KEY:KEY_SOFT1:1" ); sendEmulatorCommand( devicePort, "event send EV_KEY:KEY_SOFT1:0" ); } } }protected void startAndroidEmulator() throws MojoExecutionException { parseParameters(); CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger( this.getLog() ); try { String filename; if ( isWindows() ) { filename = writeEmulatorStartScriptWindows(); } else { filename = writeEmulatorStartScriptUnix(); } final AndroidDebugBridge androidDebugBridge = initAndroidDebugBridge(); if ( androidDebugBridge.isConnected() ) { waitForInitialDeviceList( androidDebugBridge ); List devices = Arrays.asList( androidDebugBridge.getDevices() ); int numberOfDevices = devices.size(); getLog().info( "Found " + numberOfDevices + " devices connected with the Android Debug Bridge" ); IDevice existingEmulator = findExistingEmulator( devices ); if ( existingEmulator == null ) { getLog().info( START_EMULATOR_MSG + filename ); executor.executeCommand( filename, null ); getLog().info( START_EMULATOR_WAIT_MSG + parsedWait ); // wait for the emulator to start up boolean booted = waitUntilDeviceIsBootedOrTimeout( androidDebugBridge ); if ( booted ) { getLog().info( "Emulator is up and running." ); unlockEmulator( androidDebugBridge ); } else { throw new MojoExecutionException( "Timeout while waiting for emulator to startup." ); } } else { getLog().info( String.format( "Emulator already running [Serial No: '%s', AVD Name '%s']. " + "Skipping start and wait.", existingEmulator.getSerialNumber(), existingEmulator.getAvdName() ) ); } } } catch ( Exception e ) { throw new MojoExecutionException( "", e ); } }private boolean isWindows() { boolean result; if ( OS_NAME.toLowerCase().contains( "windows" ) ) { result = true; } else { result = false; } getLog().debug( "isWindows: " + result ); return result; }@Override public UserIdentity login(String username, Object password, ServletRequest request) { UserIdentity user = super.login(username,password,request); if (user!=null) { HttpSession session = ((HttpServletRequest)request).getSession(true); Authentication cached=new SessionAuthentication(getAuthMethod(),user,password); session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, cached); } return user; }private Map> getViewRiksdagenPoliticianDocumentDailySummaryMap() { final DataContainer politicianBallotSummaryDailyDataContainer = getApplicationManager() .getDataContainer(ViewRiksdagenPoliticianDocumentDailySummary.class); return politicianBallotSummaryDailyDataContainer.getAll().parallelStream().filter(Objects::nonNull) .collect(Collectors.groupingBy(t -> t.getEmbeddedId().getPersonId())); }protected final String getPartyName(final String party) { final DataContainer dataContainer = applicationManager .getDataContainer(ViewRiksdagenParty.class); final Optional matchingObjects =dataContainer.getAll().stream(). filter((final ViewRiksdagenParty p) -> p.getPartyId().equalsIgnoreCase(party)). findFirst(); if (matchingObjects.isPresent()) { return matchingObjects.get().getPartyName(); } else { return party; } }private static int getChartWindowHeight(final boolean fullPage) { if (fullPage) { return Math.max((int) (Page.getCurrent().getBrowserWindowHeight() * HEIGHT_PERCENTAGE_FULL_PAGE) ,MINIMUM_CHART_HEIGHT_FULL_PAGE); } else { return Math.max((int) (Page.getCurrent().getBrowserWindowHeight() * HEIGHT_PERCETAGE_HALF_PAGE),NINIMUM_CHART_HEIGHT_HALF_PAGE); } }protected final void addChart(final AbstractOrderedLayout content,final String caption, final DCharts chart, final boolean fullPage) { final HorizontalLayout horizontalLayout = new HorizontalLayout(); final int browserWindowWidth = getChartWindowWidth(); final int browserWindowHeight = getChartWindowHeight(fullPage); horizontalLayout.setWidth(browserWindowWidth, Unit.PIXELS); horizontalLayout.setHeight(browserWindowHeight, Unit.PIXELS); horizontalLayout.setMargin(true); horizontalLayout.setSpacing(false); horizontalLayout.addStyleName("v-layout-content-overview-panel-level1"); final Panel formPanel = new Panel(); formPanel.setSizeFull(); formPanel.setContent(horizontalLayout); formPanel.setCaption(caption); content.addComponent(formPanel); content.setExpandRatio(formPanel, ContentRatio.LARGE); chart.setWidth(100, Unit.PERCENTAGE); chart.setHeight(100, Unit.PERCENTAGE); chart.setMarginRight(CHART_RIGHT_MARGIN); chart.setMarginLeft(CHART_LEFT_MARGIN); chart.setMarginBottom(CHART_BOTTOM_MARGIN_SIZE); chart.setMarginTop(CHART_TOP_MARGIN_SIZE); horizontalLayout.addComponent(chart); chart.setCaption(caption); }public static Source setNameSpaceOnXmlStream(final InputStream in, final String nameSpace) throws JDOMException, IOException { final SAXBuilder sb = new SAXBuilder(new XMLReaderSAX2Factory(false)); final Document doc = sb.build(in); doc.getRootElement().setNamespace(Namespace.getNamespace(nameSpace)); return new JDOMSource(doc); }private static Map> createIssueConcernMap(final List partyBallotList) { final Map> concernIssuePartyBallotSummaryMap = new HashMap<>(); for (final ViewRiksdagenVoteDataBallotPartySummary partySummary: partyBallotList) { if (partySummary.getEmbeddedId().getIssue() !=null || partySummary.getEmbeddedId().getConcern() != null ) { final String key = partySummary.getEmbeddedId().getIssue() + partySummary.getEmbeddedId().getConcern(); final List partySummarList = concernIssuePartyBallotSummaryMap.computeIfAbsent(key, k -> new ArrayList<>()); partySummarList.add(partySummary); } } return concernIssuePartyBallotSummaryMap; }private static List getSupportedLocalesLanguageData() { final List languages = new ArrayList<>(); for (final Locale locale : DateFormat.getAvailableLocales()) { final String localeString = locale.toString().trim(); if (locale.getDisplayCountry(Locale.ENGLISH).length() == 0 && !StringUtils.isEmpty(localeString) && localeString.length() == EXPECTED_LOCALE_LENGTH) { languages.add(new LanguageData().withCreatedDate(new Date()).withLanguageCode(localeString) .withLanguageName(locale.getDisplayName(Locale.ENGLISH)).withLanguageEnabled(Boolean.FALSE)); } } return languages; }private LanguageData findLanguage(final String locale) { for (final LanguageData languageData : languageDataDAO.getAll()) { if (languageData.getLanguageCode().equalsIgnoreCase(locale)) { return languageData; } } return null; }private static int getSmtpPort(final ApplicationConfiguration smtpPort) { if (StringUtils.isNumeric(smtpPort.getPropertyValue())) { return Integer.parseInt(smtpPort.getPropertyValue()); } else { return Integer.parseInt(DEFAULT_SMTP_PORT); } }private JavaMailSender getMailSender() { final JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); final ApplicationConfiguration smtpHostConfig = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_HOST, SMTP_HOST, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_HOST, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_HOST, "localhost"); final ApplicationConfiguration smtpPort = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_PORT, SMTP_PORT, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_PORT, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_PORT, DEFAULT_SMTP_PORT); final ApplicationConfiguration smtpUsername = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_USERNAME, SMTP_USERNAME, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_USERNAME, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_USERNAME, "username"); final ApplicationConfiguration smtpPassword = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_SECRET, SMTP_SECRET, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_SECRET, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_SECRET, "password"); final ApplicationConfiguration smtpAuth = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_AUTH, SMTP_AUTH, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_AUTH, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_AUTH, "true"); final ApplicationConfiguration smtpStartTlsEnable = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_STARTTLS_ENABLE, SMTP_STARTTLS_ENABLE, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_STARTTLS_ENABLE, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_STARTTLS_ENABLE, "true"); javaMailSender.setHost(smtpHostConfig.getPropertyValue()); javaMailSender.setPort(getSmtpPort(smtpPort)); javaMailSender.setUsername(smtpUsername.getPropertyValue()); javaMailSender.setPassword(smtpPassword.getPropertyValue()); final Properties javaMailProperties = new Properties(); javaMailProperties.setProperty(MAIL_SMTP_AUTH, smtpAuth.getPropertyValue()); javaMailProperties.setProperty(MAIL_SMTP_STARTTLS_ENABLE, smtpStartTlsEnable.getPropertyValue()); javaMailSender.setJavaMailProperties(javaMailProperties); return javaMailSender; }private static void createTopTitleHeader(final HorizontalLayout topHeader) { final HorizontalLayout topTitleHeadertPanel = new HorizontalLayout(); final Label titleLabel = new Label("Citizen Intelligence Agency"); titleLabel.setStyleName("Header"); topTitleHeadertPanel.addComponent(titleLabel); topTitleHeadertPanel.setComponentAlignment(titleLabel, Alignment.MIDDLE_LEFT); final Label sloganLabel = new Label("// Tracking politicians like bugs!"); sloganLabel.setStyleName("HeaderSlogan"); topTitleHeadertPanel.addComponent(sloganLabel); topTitleHeadertPanel.setComponentAlignment(sloganLabel, Alignment.MIDDLE_RIGHT); topHeader.addComponent(topTitleHeadertPanel); topHeader.setComponentAlignment(topTitleHeadertPanel, Alignment.MIDDLE_LEFT); topHeader.setExpandRatio(topTitleHeadertPanel, ContentRatio.GRID); }private static void addLogoToHeader(final HorizontalLayout topHeader) { final ThemeResource ciaLogoResource = new ThemeResource("cia-logo.png"); final Image ciaLogoImage = new Image(null,ciaLogoResource); topHeader.addComponent(ciaLogoImage); ciaLogoImage.setWidth("60px"); ciaLogoImage.setHeight("60px"); topHeader.setComponentAlignment(ciaLogoImage, Alignment.MIDDLE_LEFT); topHeader.setExpandRatio(ciaLogoImage, ContentRatio.SMALL); }private static VerticalLayout createFullSizeVerticalLayout(final boolean margin, final boolean spacing) { final VerticalLayout layout = new VerticalLayout(); layout.setMargin(margin); layout.setSpacing(spacing); layout.setWidth(100, Unit.PERCENTAGE); layout.setHeight(100, Unit.PERCENTAGE); return layout; }private void createTopHeaderActionsForUserContext() { if (UserContextUtil.allowRoleInSecurityContext(ROLE_ADMIN) || UserContextUtil.allowRoleInSecurityContext(ROLE_USER)) { final Link userHomePageLink = pageLinkFactory.createUserHomeViewPageLink(); topHeaderRightPanel.addComponent(userHomePageLink); topHeaderRightPanel.setComponentAlignment(userHomePageLink, Alignment.MIDDLE_RIGHT); final Button logoutButton = new Button(LOGOUT,VaadinIcons.SIGN_OUT); final LogoutRequest logoutRequest = new LogoutRequest(); logoutRequest.setSessionId(RequestContextHolder.currentRequestAttributes().getSessionId()); logoutButton.addClickListener(new LogoutClickListener(logoutRequest)); topHeaderRightPanel.addComponent(logoutButton); topHeaderRightPanel.setComponentAlignment(logoutButton, Alignment.MIDDLE_RIGHT); } else { final Link createRegisterPageLink = pageLinkFactory.createRegisterPageLink(); topHeaderRightPanel.addComponent(createRegisterPageLink); topHeaderRightPanel.setComponentAlignment(createRegisterPageLink, Alignment.MIDDLE_RIGHT); final Link createLoginPageLink = pageLinkFactory.createLoginPageLink(); topHeaderRightPanel.addComponent(createLoginPageLink); topHeaderRightPanel.setComponentAlignment(createLoginPageLink, Alignment.MIDDLE_RIGHT); } }protected final void createBasicLayoutWithPanelAndFooter(final String panelName) { final VerticalLayout layout = createFullSizeVerticalLayout(); final VerticalLayout pageModeContent = createFullSizeVerticalLayout(false,false); layout.addComponent(pageModeContent); final HorizontalLayout topHeader = new HorizontalLayout(); addLogoToHeader(topHeader); createTopTitleHeader(topHeader); topHeaderRightPanel.removeAllComponents(); topHeader.addComponent(topHeaderRightPanel); topHeader.setComponentAlignment(topHeaderRightPanel, Alignment.MIDDLE_RIGHT); topHeader.setExpandRatio(topHeaderRightPanel, ContentRatio.LARGE); createTopHeaderActionsForUserContext(); topHeaderRightPanel.setWidth("100%"); topHeaderRightPanel.setHeight("50px"); topHeader.setWidth("100%"); topHeader.setHeight("50px"); pageModeContent.addComponent(topHeader); pageModeContent.setComponentAlignment(topHeader, Alignment.TOP_CENTER); pageModeContent.addComponent(getBarmenu()); pageModeContent.setComponentAlignment(getBarmenu(), Alignment.TOP_CENTER); panel = new Panel(panelName); panel.addStyleName("v-panel-page-panel"); panel.setSizeFull(); pageModeContent.addComponent(panel); pageModeContent.setExpandRatio(panel, ContentRatio.FULL_SIZE); pageModeContent.addComponent(pageLinkFactory.createMainViewPageLink()); setContent(layout); setWidth(100, Unit.PERCENTAGE); setHeight(100, Unit.PERCENTAGE); setSizeFull(); }@OneToMany(targetEntity = DocumentElement.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "DOKUMENT_DOCUMENT_CONTAINER__0") public List getDokument() { return this.dokument; }protected final Optional getActiveUserAccount() { final DataContainer dataContainer = getApplicationManager() .getDataContainer(UserAccount.class); return dataContainer .getAllBy(UserAccount_.userId, UserContextUtil.getUserIdFromSecurityContext()).stream().findFirst(); }@OneToMany(targetEntity = Portal.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "PORTALS_AGENCY_HJID") public List getPortals() { if (portals == null) { portals = new ArrayList<>(); } return this.portals; }protected final JobContextHolder getJobContextHolder(final JobExecutionContext jobContext) { final Scheduler scheduler = jobContext.getScheduler(); JobContextHolder bean = null; try { final SchedulerContext schedulerContext = scheduler.getContext(); final ApplicationContext appContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT); bean = appContext.getBean(JobContextHolder.class); } catch (final SchedulerException e) { LOGGER.error("Failed to get JobContextHolder",e ); } return bean; }@OneToMany(targetEntity = SwedenCountyElectoralRegion.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "COUNTY_ELECTORAL_REGIONS_SWE_0") public List getCountyElectoralRegions() { return this.countyElectoralRegions; }public String decryptValue(final String symmetricKey,final String value) { return getEncryptor(symmetricKey).decrypt(value); }private static StandardPBEStringEncryptor getEncryptor(final String symmetricKey) { Security.addProvider(new BouncyCastleProvider()); final StandardPBEStringEncryptor mySecondEncryptor = new StandardPBEStringEncryptor(); mySecondEncryptor.setProviderName(BC_PROVIDER_NAME); mySecondEncryptor.setAlgorithm(PBEWITHSHA256AND128BITAES_CBC_BC); mySecondEncryptor.setPassword(symmetricKey); return mySecondEncryptor; }public String encryptValue(final String symmetricKey,final String value) { return getEncryptor(symmetricKey).encrypt(value); }public static void main(String[] args) { if (args.length == EXPECTED_NUMBER_ARGS) { final String encryptValue = new EncryptProperty().encryptValue(args[0], args[1]); System.out.println(ENCRYPTED_VALUE +encryptValue); System.out.println(ENCRYPTED_PROPERTY_VALUE + ENC_CONTENT_PREFIX +encryptValue +ENC_CONTENT_SUFFIX); } else { System.out.println(HELP_MESSAGE); } }@ManyToOne(targetEntity = BallotDocumentElement.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "BALLOT_DOCUMENT_ELEMENT_BALL_0") public BallotDocumentElement getBallotDocumentElement() { return ballotDocumentElement; }@ManyToOne(targetEntity = BallotDocumentData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "BALLOT_DOCUMENT_DATA_BALLOT__0") public BallotDocumentData getBallotDocumentData() { return ballotDocumentData; }@Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "LENDING_TYPE_VALUE")), @AttributeOverride(name = "id", column = @Column(name = "LENDING_TYPE_ID")) }) public LendingType getLendingType() { return lendingType; }@Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "INCOME_LEVEL_VALUE")), @AttributeOverride(name = "id", column = @Column(name = "INCOME_LEVEL_ID")) }) public IncomeLevel getIncomeLevel() { return incomeLevel; }@Embedded @AttributeOverrides({ @AttributeOverride(name = "value", column = @Column(name = "ADMINREGION_VALUE")), @AttributeOverride(name = "id", column = @Column(name = "ADMINREGION_ID")) }) public Adminregion getAdminregion() { return adminregion; }@Basic @Column(name = "BALLOT_SUMMARY_ITEM") @Lob public String getBallotSummaryItem() { return XmlAdapterUtils.unmarshall(ElementAsString.class, this.getBallotSummary()); }@OneToMany(targetEntity = SwedenElectionType.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "ELECTION_TYPES_SWEDEN_ELECTI_0") public List getElectionTypes() { return this.electionTypes; }private static void addDataSeries(final SimpleDateFormat simpleDateFormat, final SimpleDateFormat parseInputDateFormat, final DataSeries dataSeries, final Series series, final Entry> entry) { series.addSeries(new XYseries().setLabel(entry.getKey())); dataSeries.newSeries(); for (final ViewRiksdagenDocumentTypeDailySummary item : entry.getValue()) { if (item != null && item.getEmbeddedId().getPublicDate().length() > 0) { try { dataSeries.add(simpleDateFormat.format(parseInputDateFormat.parse(item.getEmbeddedId().getPublicDate())), item.getTotal()); } catch (final ParseException e) { LOGGER.warn("Problem parsing date:{}", item.getEmbeddedId().getPublicDate()); } } } }private Map> getDocumentTypeMap() { final DataContainer documentTypeSummaryDailyDataContainer = getApplicationManager() .getDataContainer(ViewRiksdagenDocumentTypeDailySummary.class); return documentTypeSummaryDailyDataContainer.getAll().parallelStream() .filter(t -> t != null && !t.getEmbeddedId().getPublicDate().startsWith(YEAR_PREFIX) && StringUtils.containsIgnoreCase(MOT_PROP_BET, t.getEmbeddedId().getDocumentType())) .collect(Collectors.groupingBy(t -> t.getEmbeddedId().getDocumentType())); }private static void setColumnConverters(final ListPropertyConverter[] collectionPropertyConverter, final Grid grid) { if (collectionPropertyConverter != null) { for (final ListPropertyConverter converter : collectionPropertyConverter) { grid.removeColumn(converter.getColumn()); final Column column = grid.addColumn(converter); column.setCaption(WordUtils.capitalize(converter.getColumn())); column.setId(converter.getColumn()); } } }private static void createGridCellFilter(final String[] columnOrder, final Grid grid, final Class dataType) { if (columnOrder != null) { final GridCellFilter filter = new GridCellFilter(grid, dataType); for (final String column : columnOrder) { if (grid.getColumn(column) != null) { filter.setTextFilter(column, true, true); } } } }private static void configureListeners(final SelectionListener listener, final Grid grid) { if (listener != null) { grid.addSelectionListener(listener); } }private static void configureColumnOrdersAndHiddenFields(final String[] columnOrder, final String[] hideColumns, final Grid grid) { if (columnOrder != null) { grid.setColumnOrder(columnOrder); } if (hideColumns != null) { for (final String o : hideColumns) { grid.removeColumn(o); } } }@OneToMany(targetEntity = AssignmentData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "ASSIGNMENT_LIST_PERSON_ASSIG_0") public List getAssignmentList() { return this.assignmentList; }@OneToMany(targetEntity = VoteDataDto.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "VOTE_DATA_LIST_BALLOT_DOCUME_0") public List getVoteDataList() { return this.voteDataList; }private ManageUserAccountResponse performOperation(final ManageUserAccountRequest serviceRequest, final CreateApplicationEventRequest eventRequest) { ManageUserAccountResponse response; eventRequest.setElementId(serviceRequest.getUserAcountId()); eventRequest.setApplicationMessage(serviceRequest.getAccountOperation().toString()); final UserAccount accountToModify = getUserDAO().findFirstByProperty(UserAccount_.userId, serviceRequest.getUserAcountId()); final UserCommand userCommand = userCommandMap.get(serviceRequest.getAccountOperation()); if (accountToModify != null && userCommand != null) { response = userCommand.execute(accountToModify); } else { response = new ManageUserAccountResponse(ServiceResult.FAILURE); } eventRequest.setApplicationMessage(response.getResult().toString()); return response; }@PostConstruct public void initUserCommandMap() { userCommandMap.put(ManageUserAccountRequest.AccountOperation.DELETE, account -> { removeDataManager.removeUserAccountApplicationHistory(account.getUserId()); getUserDAO().delete(account); return new ManageUserAccountResponse(ServiceResult.SUCCESS); }); userCommandMap.put(ManageUserAccountRequest.AccountOperation.UNLOCK, account -> { account.setUserLockStatus(UserLockStatus.UNLOCKED); getUserDAO().persist(account); return new ManageUserAccountResponse(ServiceResult.SUCCESS); }); userCommandMap.put(ManageUserAccountRequest.AccountOperation.LOCK, account -> { account.setUserLockStatus(UserLockStatus.LOCKED); getUserDAO().persist(account); return new ManageUserAccountResponse(ServiceResult.SUCCESS); }); }private static void addDataItem(final DataSeries dataSeries, final SimpleDateFormat simpleDateFormat, final SimpleDateFormat parseIncomingDateFormat, final ViewRiksdagenOrgDocumentDailySummary item) { if (item != null && item.getEmbeddedId().getPublicDate().length() > 0) { try { dataSeries.add( simpleDateFormat .format(parseIncomingDateFormat.parse(item.getEmbeddedId().getPublicDate())), item.getTotal()); } catch (final ParseException e) { LOGGER.warn("Problem parsing date:{}", item.getEmbeddedId().getPublicDate()); } } }private static void addNewDataSerie(final DataSeries dataSeries, final Series series, final SimpleDateFormat simpleDateFormat, final SimpleDateFormat parseIncomingDateFormat, final Entry> entry) { series.addSeries(new XYseries().setLabel(entry.getKey())); dataSeries.newSeries(); if (entry.getValue() != null) { for (final ViewRiksdagenOrgDocumentDailySummary item : entry.getValue()) { addDataItem(dataSeries, simpleDateFormat, parseIncomingDateFormat, item); } } }private static void addDocumentHistoryByOrgData(final DataSeries dataSeries, final Series series, final List itemList) { final Map> map = itemList.parallelStream() .filter(Objects::nonNull) .collect(Collectors.groupingBy(t -> StringUtils.defaultIfBlank(t.getDocumentType(), NO_INFO))); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DD_MMM_YYYY, Locale.ENGLISH); final SimpleDateFormat parseIncomingDateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH); for (final Entry> entry : map.entrySet()) { addNewDataSerie(dataSeries, series, simpleDateFormat, parseIncomingDateFormat, entry); } }private Map> getViewRiksdagenOrgDocumentDailySummaryMap() { final DataContainer politicianBallotSummaryDailyDataContainer = getApplicationManager() .getDataContainer(ViewRiksdagenOrgDocumentDailySummary.class); return politicianBallotSummaryDailyDataContainer.getAll().parallelStream() .filter(t -> t != null && !t.getEmbeddedId().getPublicDate().startsWith(YEAR_PREFIX)) .collect(Collectors.groupingBy( t -> StringEscapeUtils.unescapeHtml4(t.getEmbeddedId().getOrg()).toUpperCase(Locale.ENGLISH) .replace(UNDER_SCORE, EMPTY_STRING).replace(MINUS_SIGN, EMPTY_STRING).trim())); }@OneToMany(targetEntity = SwedenParliamentElectoralRegion.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "PARLIAMENT_ELECTORAL_REGIONS_0") public List getParliamentElectoralRegions() { return this.parliamentElectoralRegions; }@OneToMany(targetEntity = CommitteeProposalData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "COMMITTEE_PROPOSAL_LIST_COMM_0") public List getCommitteeProposalList() { return this.committeeProposalList; }public static String getOperatingSystem(final WebBrowser webBrowser) { synchronized (USER_AGENT_ANALYZER) { final UserAgent userAgent = USER_AGENT_ANALYZER.parse(webBrowser.getBrowserApplication()); return userAgent.getValue(UserAgent.DEVICE_CLASS) + "." +userAgent.getValue(UserAgent.OPERATING_SYSTEM_NAME) +"." + userAgent.getValue(UserAgent.OPERATING_SYSTEM_VERSION); } }public static String getIpInformation(final WebBrowser webBrowser) { String ipInformation=webBrowser.getAddress(); final HttpServletRequest httpRequest=((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest(); final String xForwardedForHeader = httpRequest.getHeader(X_FORWARDED_FOR); if (xForwardedForHeader != null) { final String[] split = xForwardedForHeader.split(","); if (split.length != 0) { ipInformation = split[0]; } } return ipInformation; }public Date tryToFindValidVoteDate(final BallotContainer ballotContainer, final List voteDataList) throws ParseException { Date ballotDate; final Date sameDate = checkSameDate(voteDataList); if (sameDate != null) { ballotDate = sameDate; } else { ballotDate = bestGuessVoteDate(ballotContainer); } return ballotDate; }private static Date checkSameDate(final List voteList) throws ParseException { final Set set = new HashSet<>(); Date result=null; for (final VoteDataDto voteData : voteList) { final String voteDate = voteData.getVoteDate(); if (voteDate !=null && voteDate.length() >= YYYY_MM_DD.length()) { set.add(voteData.getVoteDate()); } } if (set.size() ==CONTAINS_ONE) { final String dateString = set.iterator().next(); result=new SimpleDateFormat(YYYY_MM_DD,Locale.ENGLISH).parse(dateString); } return result; }private static Date bestGuessVoteDate(final BallotContainer ballotContainer) throws ParseException { final com.hack23.cia.model.external.riksdagen.votering.impl.BallotDocumentElement ballotDocumentElement = ballotContainer.getBallotDocumentElement(); Date result; final String createdDate=ballotContainer.getBallotDocumentElement().getCreatedDate(); if(createdDate!= null && createdDate.length()>= YYYY_MM_DD.length()) { result=new SimpleDateFormat(YYYY_MM_DD,Locale.ENGLISH).parse(createdDate); } else { final String systemDate = ballotDocumentElement.getSystemDate(); if(systemDate!= null && systemDate.length()>= YYYY_MM_DD.length()) { result=new SimpleDateFormat(YYYY_MM_DD,Locale.ENGLISH).parse(systemDate); } else { result=new SimpleDateFormat(YYYY_MM_DD,Locale.ENGLISH).parse(ballotDocumentElement.getMadePublicDate()); } } return result; }@OneToMany(targetEntity = DocumentReferenceData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "DOCUMENT_REFERENCE_LIST_DOCU_0") public List getDocumentReferenceList() { return this.documentReferenceList; }private VerticalLayout createChangePasswordButton() { final VerticalLayout formLayout = new VerticalLayout(); formLayout.setSizeFull(); final Panel formPanel = new Panel(); formPanel.setSizeFull(); formLayout.addComponent(formPanel); final FormLayout formContent = new FormLayout(); formPanel.setContent(formContent); final ChangePasswordRequest request = new ChangePasswordRequest(); request.setSessionId(RequestContextHolder.currentRequestAttributes().getSessionId()); request.setCurrentPassword(""); request.setNewPassword(""); request.setRepeatNewPassword(""); final ClickListener listener = new ChangePasswordClickListener(request); getFormFactory().addRequestInputFormFields(formContent, request, ChangePasswordRequest.class, Arrays.asList("currentPassword","newPassword","repeatNewPassword"), "Change password", listener); return formLayout; }private VerticalLayout createDisableGoogleAuthButton() { final VerticalLayout formLayout = new VerticalLayout(); formLayout.setSizeFull(); final Panel formPanel = new Panel(); formPanel.setSizeFull(); formLayout.addComponent(formPanel); final FormLayout formContent = new FormLayout(); formPanel.setContent(formContent); final DisableGoogleAuthenticatorCredentialRequest request = new DisableGoogleAuthenticatorCredentialRequest(); request.setSessionId(RequestContextHolder.currentRequestAttributes().getSessionId()); request.setUserpassword(""); final ClickListener listener = new DisableGoogleAuthenticatorCredentialClickListener(request); getFormFactory().addRequestInputFormFields(formContent, request, DisableGoogleAuthenticatorCredentialRequest.class, AS_LIST, DISABLE_GOOGLE_AUTHENTICATOR, listener); return formLayout; }private VerticalLayout createEnableGoogleAuthButton() { final VerticalLayout formLayout = new VerticalLayout(); formLayout.setSizeFull(); final Panel formPanel = new Panel(); formPanel.setSizeFull(); formLayout.addComponent(formPanel); final FormLayout formContent = new FormLayout(); formPanel.setContent(formContent); final SetGoogleAuthenticatorCredentialRequest request = new SetGoogleAuthenticatorCredentialRequest(); request.setSessionId(RequestContextHolder.currentRequestAttributes().getSessionId()); request.setUserpassword(""); final ClickListener listener = new SetGoogleAuthenticatorCredentialClickListener(request); getFormFactory().addRequestInputFormFields(formContent, request, SetGoogleAuthenticatorCredentialRequest.class, AS_LIST, ENABLE_GOOGLE_AUTHENTICATOR, listener); return formLayout; }@OneToMany(targetEntity = SwedenPoliticalParty.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "PARTIES_SWEDEN_ELECTION_REGI_0") public List getParties() { return this.parties; }private static Date getDate(final String date) throws ParseException { if (RIKSDAGEN_JAVA_SIMPLE_DATE_FORMAT.length() > date.length()) { return new SimpleDateFormat(RIKSDAGEN_JAVA_SIMPLE_DATE_TIME_FORMAT, Locale.ENGLISH).parse(date); } else { return new SimpleDateFormat(RIKSDAGEN_JAVA_SIMPLE_DATE_FORMAT, Locale.ENGLISH).parse(date); } }private static boolean checkIncludeDate(final Date after, final List documentTypeValues, final DocumentElement documentElement) { try { if (documentElement.getMadePublicDate() != null && documentElement.getMadePublicDate().length() > 0) { return getDate(documentElement.getMadePublicDate()).after(after) && documentTypeValues.contains(documentElement.getDocumentType()); } else { return getDate(documentElement.getCreatedDate()).after(after) && documentTypeValues.contains(documentElement.getDocumentType()); } } catch (final ParseException e) { LOGGER.warn("Problem getting date from{} : exception:{}", documentElement, e); return false; } }private static Map createMapFromListVote(final List list) { final Map map = new ConcurrentHashMap<>(); for (final VoteDataEmbeddedId documentElement : list) { map.put(documentElement.getBallotId(), documentElement.getBallotId()); } return map; }public final void addViolation(final Status status,final String ruleName,final String ruleGroup,final String ruleDescription,final String positive) { final RuleViolation currentRuleViolation = ruleViolationMap.get(ruleName); if (currentRuleViolation == null || status.ordinal() > currentRuleViolation.getStatus().ordinal()) { ruleViolationMap.put(ruleName, new RuleViolation(getId(),getName(),resourceType,ruleName,ruleDescription,ruleGroup,status,positive)); } }@Override public final String getRuleSummary() { final Collection values = ruleViolationMap.values(); final StringBuilder builder = new StringBuilder(); for (final RuleViolation ruleViolation : values) { builder.append('[').append(ruleViolation.getRuleName()).append('/').append(ruleViolation.getStatus()) .append(']'); } return builder.toString(); }private static Key buildKey(final String userid, final String password) { return new SecretKeySpec(Arrays.copyOf( new SHA3.Digest512().digest((userid + ".uuid" + password).getBytes(StandardCharsets.UTF_8)), KEY_SIZE_IN_BYTES), ALGORITHM); }public static void createHeader2Label(final AbstractOrderedLayout panel,final String content) { final Label label = new Label(content); label.setStyleName("Level2Header"); panel.addComponent(label); panel.setExpandRatio(label,ContentRatio.SMALL); }private static void displayDocumentAttachements(final VerticalLayout panelContent, final List documentAttachmentList) { for (final DocumentAttachment documentAttachment : documentAttachmentList) { if (PDF.equalsIgnoreCase(documentAttachment.getFileType())) { final WTPdfViewer wtPdfViewer = new WTPdfViewer(); wtPdfViewer.setSizeFull(); wtPdfViewer.setResource(new StreamResource(new StreamSourceImplementation(documentAttachment.getFileUrl()), documentAttachment.getFileName())); panelContent.addComponent(wtPdfViewer); panelContent.setExpandRatio(wtPdfViewer, ContentRatio.LARGE); } else { final VerticalLayout verticalLayout = new VerticalLayout(); panelContent.addComponent(verticalLayout); panelContent.setExpandRatio(verticalLayout, ContentRatio.SMALL); final ExternalAttachmentDownloadLink link = new ExternalAttachmentDownloadLink( documentAttachment.getFileName(), documentAttachment.getFileType(), documentAttachment.getFileUrl()); verticalLayout.addComponent(link); } } }private static void addDecisionTypeByOrgData(final SimpleDateFormat simpleDateFormat, final DataSeries dataSeries, final Series series, final Map> map) { for (final Entry> entry : map.entrySet()) { if (!EMPTY_STRING.equals(entry.getKey())) { final XYseries label = new XYseries(); label.setLabel(entry.getKey()); series.addSeries(label); dataSeries.newSeries(); for (final ViewRiksdagenCommitteeDecisionTypeOrgDailySummary item : entry.getValue()) { dataSeries.add(simpleDateFormat.format(item.getEmbeddedId().getDecisionDate()), item.getTotal()); } } } }private Map> getCommitteeDecisionTypeOrgMap() { final DataContainer committeeBallotDecisionPartyDataContainer = getApplicationManager() .getDataContainer(ViewRiksdagenCommitteeDecisionTypeOrgDailySummary.class); return committeeBallotDecisionPartyDataContainer.getAll().parallelStream().filter(Objects::nonNull) .collect(Collectors.groupingBy(t -> t.getEmbeddedId().getOrg())); }private Map> getCommitteeDecisionTypeMap() { final DataContainer committeeBallotDecisionPartyDataContainer = getApplicationManager() .getDataContainer(ViewRiksdagenCommitteeDecisionTypeDailySummary.class); final Date now = new Date(); final Date notBefore = new GregorianCalendar(2000, Calendar.JANUARY, 1).getTime(); return committeeBallotDecisionPartyDataContainer.getAll().parallelStream() .filter(t -> t != null && !t.getEmbeddedId().getDecisionDate().after(now) && !notBefore.after(t.getEmbeddedId().getDecisionDate())) .collect(Collectors.groupingBy(t -> t.getEmbeddedId().getDecisionType())); }@ManyToOne(targetEntity = PersonDetailData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "PERSON_DETAIL_DATA_PERSON_DA_0") public PersonDetailData getPersonDetailData() { return personDetailData; }@ManyToOne(targetEntity = PersonAssignmentData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "PERSON_ASSIGNMENT_DATA_PERSO_0") public PersonAssignmentData getPersonAssignmentData() { return personAssignmentData; }private static GovernmentBodyAnnualSummary createGovernmentBodyAnnualSummaryFromRow(final int year, final Row row) { return new GovernmentBodyAnnualSummary(year, defaultValueIfNull(row.getCell(NAME_CELL)), getInteger(defaultValueIfNull(row.getCell(CONSECUTIVE_NUMBER_CELL))), defaultValueIfNull(row.getCell(GOVERNMENT_BODY_ID_CELL)), defaultValueIfNull(row.getCell(MCODE_CELL)), defaultValueIfNull(row.getCell(MINISTRY_CELL)), defaultValueIfNull(row.getCell(ORG_NUMBER_CELL)), getInteger(defaultValueIfNull(row.getCell(HEADCOUNT_CELL))), getInteger(defaultValueIfNull(row.getCell(ANNUAL_HEADCOUNT_CELL))), defaultValueIfNull(row.getCell(VAT_CELL)), defaultValueIfNull(row.getCell(COMMENT_CELL))); }private static void addGovernmentBodyAnnualSummaryToMap(final String name, final Map map, final int year, final Row row) { if (row.getLastCellNum() >= EXPECTED_COLUMN_LENGTH) { final GovernmentBodyAnnualSummary governmentBodyAnnualSummary = createGovernmentBodyAnnualSummaryFromRow( year, row); if (name == null || name.equalsIgnoreCase(governmentBodyAnnualSummary.getName())) { map.put(year, governmentBodyAnnualSummary); } } }private static void addDataForYearToMap(final String name, final Map map, final HSSFSheet mySheet) { if (mySheet.getSheetName().chars().allMatch(Character::isDigit)) { final int year = Integer.parseInt(mySheet.getSheetName()); final Iterator rowIterator = mySheet.iterator(); rowIterator.next(); while (rowIterator.hasNext()) { addGovernmentBodyAnnualSummaryToMap(name, map, year, rowIterator.next()); } } }private static int getInteger(final String str) { if (str == null || str.trim().length() == 0) { return 0; } else { return Integer.parseInt(str); } }private static void addGovernmentBodyAnnualSummaryToList(final String name, final int year, final List yearList, final Row row) { if (row.getLastCellNum() >= EXPECTED_COLUMN_LENGTH) { final GovernmentBodyAnnualSummary governmentBodyAnnualSummary = createGovernmentBodyAnnualSummaryFromRow( year, row); if (name == null || name.equalsIgnoreCase(governmentBodyAnnualSummary.getMinistry())) { yearList.add(governmentBodyAnnualSummary); } } }private static void addMinistryPerYearToMap(final String name, final Map> map, final HSSFSheet mySheet) { if (mySheet.getSheetName().chars().allMatch(Character::isDigit)) { final int year = Integer.parseInt(mySheet.getSheetName()); final List yearList = new ArrayList<>(); final Iterator rowIterator = mySheet.iterator(); // Skip header row, ignore first rowIterator.next(); while (rowIterator.hasNext()) { addGovernmentBodyAnnualSummaryToList(name, year, yearList, rowIterator.next()); } map.put(year, yearList); } }private void createRoleSummary(final VerticalLayout roleSummaryLayoutTabsheet, final List assignmentList, final ViewRiksdagenPolitician viewRiksdagenPolitician) { final VerticalLayout layout = new VerticalLayout(); layout.setSizeFull(); layout.addComponent(new Label(TOTAL_ASSIGNMENTS + assignmentList.size())); if (viewRiksdagenPolitician != null) { layout.addComponent(new Label(GOVERNMENT_EXPERIENCE + convertToYearsString(viewRiksdagenPolitician.getTotalDaysServedGovernment()))); layout.addComponent(new Label( SPEAKER_EXPERIENCE + convertToYearsString(viewRiksdagenPolitician.getTotalDaysServedSpeaker()))); layout.addComponent(new Label(COMMITTEE_EXPERIENCE + convertToYearsString(viewRiksdagenPolitician.getTotalDaysServedCommittee()))); layout.addComponent( new Label(EU_EXPERIENCE + convertToYearsString(viewRiksdagenPolitician.getTotalDaysServedEu()))); layout.addComponent(new Label(PARLIAMENT_EXPERIENCE + convertToYearsString(viewRiksdagenPolitician.getTotalDaysServedParliament()))); layout.addComponent(new Label( PARTY_EXPERIENCE + convertToYearsString(viewRiksdagenPolitician.getTotalDaysServedParty()))); } roleSummaryLayoutTabsheet.addComponent(layout); roleSummaryLayoutTabsheet.setExpandRatio(layout, ContentRatio.GRID); }@Bean public AuthorProvider authorProvider() { return () -> { final SecurityContext context = SecurityContextHolder.getContext(); if (context != null && context.getAuthentication() != null) { return context.getAuthentication().getPrincipal().toString(); } else { return "system"; } }; }@Bean public JaversAuditableAspect javersAuditableAspect(final Javers javers, final AuthorProvider authorProvider, final CommitPropertiesProvider commitPropertiesProvider) { return new JaversAuditableAspect(javers, authorProvider, commitPropertiesProvider); }@Bean public Javers getJavers(final PlatformTransactionManager txManager) { final JaversSqlRepository sqlRepository = SqlRepositoryBuilder.sqlRepository() .withConnectionProvider(new ConnectionProvider() { @Override public Connection getConnection() { final SessionImpl session = (SessionImpl) entityManager.unwrap(Session.class); return session.connection(); } }).withDialect(DialectName.POSTGRES).build(); return TransactionalJaversBuilder.javers().withTxManager(txManager) .withObjectAccessHook(new HibernateUnproxyObjectAccessHook()).registerJaversRepository(sqlRepository) .withMappingStyle(MappingStyle.BEAN).build(); }@Bean public KieContainer kieContainer() { final KieServices kieServices = KieServices.Factory.get(); final KieContainer kContainer = kieServices.getKieClasspathContainer(); LOGGER.info("Using classloader {}, parent {}",kContainer.getClassLoader(),kContainer.getClassLoader().getParent()); final Results verifyResults = kContainer.verify(); for (final Message m : verifyResults.getMessages()) { LOGGER.warn("Kie container message: {}", m); } final KieBase kieBase = kContainer.getKieBase(); for (final KiePackage kp : kieBase.getKiePackages()) { for (final Rule rule : kp.getRules()) { LOGGER.info("Loadded Rule: {} {}", kp, rule.getName()); } } return kContainer; }public void setResultElement(final List resultElement) { if (resultElement != null) { this.resultElement = resultElement.stream().collect(Collectors.toList()); } }protected final void createButtonLink(final ResponsiveRow row,final String linkText,final Resource icon, final ClickListener command, final String description) { final CssLayout layout = new CssLayout(); layout.addStyleName("v-layout-content-overview-panel-level2"); Responsive.makeResponsive(layout); layout.setSizeUndefined(); final Button button = new Button(linkText); Responsive.makeResponsive(button); button.setStyleName(LINK_STYLE_NAME); button.addStyleName("title"); button.addClickListener(command); button.setIcon(icon); button.setWidth(100, Unit.PERCENTAGE); layout.addComponent(button); final Label descriptionLabel = new Label(description); descriptionLabel.addStyleName("itembox"); Responsive.makeResponsive(descriptionLabel); descriptionLabel.setWidth(100, Unit.PERCENTAGE); layout.addComponent(descriptionLabel); row.addColumn().withDisplayRules(DISPLAY_SIZE_XS_DEVICE,DISPLAYS_SIZE_XM_DEVICE,DISPLAY_SIZE_MD_DEVICE,DISPLAY_SIZE_LG_DEVICE).withComponent(layout); }private static void createAdminMenu(final MenuItem mainViewItem) { if (UserContextUtil.allowRoleInSecurityContext(ROLE_ADMIN)) { final MenuItem adminMenuItem = mainViewItem.addItem(ADMIN_TEXT, VaadinIcons.SERVER, null); final MenuItem configurationMenuItem = adminMenuItem.addItem(CONFIGURATION, VaadinIcons.TOOLS, null); configurationMenuItem.addItem(APPLICATION_CONFIGURATION,VaadinIcons.TOOLS, COMMAND_APPLICATION_CONFIGURATION); configurationMenuItem.addItem(AGENCY,VaadinIcons.SERVER, COMMAND_AGENCY); configurationMenuItem.addItem(PORTAL, VaadinIcons.SITEMAP,COMMAND_PORTAL); configurationMenuItem.addItem(COUNTRY,VaadinIcons.FLAG, COMMAND_COUNTRY); configurationMenuItem.addItem(LANGUAGE,VaadinIcons.ACCESSIBILITY, COMMAND_LANGUAGE); configurationMenuItem.addItem(LANGUAGE_CONTENT,VaadinIcons.FILE_TEXT, COMMAND_LANGUAGE_CONTENT); final MenuItem managementMenuItem = adminMenuItem.addItem(MANAGEMENT, VaadinIcons.SERVER, null); managementMenuItem.addItem(AGENT_OPERATIONS_TEXT,VaadinIcons.BRIEFCASE, COMMAND_AGENT_OPERATION); managementMenuItem.addItem(DATA_SUMMARY_TEXT,VaadinIcons.DATABASE, COMMAND_DATASUMMARY); managementMenuItem.addItem(DATA_AUTHOR_SUMMARY,VaadinIcons.DATABASE, COMMAND_AUTHOR_DATASUMMARY); managementMenuItem.addItem(EMAIL,VaadinIcons.MAILBOX, COMMAND_EMAIL); managementMenuItem.addItem(SYSTEM_PERFORMANCE,VaadinIcons.DASHBOARD, COMMAND_MONITORING); final MenuItem userActivityMenuItem = adminMenuItem.addItem(USER_ACTIVITY, VaadinIcons.DATABASE, null); userActivityMenuItem.addItem(APPLICATION_SESSION,VaadinIcons.LAPTOP, COMMAND_APPLICATION_SESSION); userActivityMenuItem.addItem(APPLICATION_EVENT,VaadinIcons.ARROWS, COMMAND_APPLICATION_EVENTS); userActivityMenuItem.addItem(APPLICATION_EVENT_CHARTS,VaadinIcons.ARROWS, COMMAND_APPLICATION_EVENTS_CHARTS); userActivityMenuItem.addItem(USERACCOUNT,VaadinIcons.GROUP, COMMAND_USERACCOUNT); } }protected final void initApplicationMenuBar(final MenuBar menuBar) { menuBar.removeItems(); menuBar.setWidth(MENU_BAR_WIDTH); menuBar.setStyleName(HEADER_STYLE_NAME); final MenuItem mainViewItem = menuBar.addItem(APPLICATION, VaadinIcons.SERVER, null); mainViewItem.addItem(START_TEXT, VaadinIcons.STAR, COMMAND_MAINVIEW_OVERVIEW); final MenuItem mainItem = mainViewItem.addItem(MAIN, VaadinIcons.STAR, null); mainItem.addItem(PAGE_VISIT_HISTORY_TEXT, VaadinIcons.LINE_CHART, COMMAND_MAINVIEW_PAGEVISITHISTORY); if (UserContextUtil.allowRoleInSecurityContext(ROLE_ADMIN) || UserContextUtil.allowRoleInSecurityContext(ROLE_USER)) { mainViewItem.addItem(USERHOME, VaadinIcons.USER,COMMAND_USERHOME); createAdminMenu(mainViewItem); mainViewItem.addItem(LOGOUT, VaadinIcons.SIGN_OUT, COMMAND_LOGOUT); } else { mainViewItem.addItem(LOGIN, VaadinIcons.SIGN_IN, COMMAND_LOGIN); mainViewItem.addItem(REGISTER, VaadinIcons.FILE_ADD, COMMAND_REGISTER); } }private void createDataIndicatorSummaryChartPanel(final VerticalLayout verticalLayout,final String indicator) { final DataContainer indicatorDataCountrSummaryDailyDataContainer = getApplicationManager() .getDataContainer(ViewWorldbankIndicatorDataCountrySummary.class); final Optional indicatorSummary = indicatorDataCountrSummaryDailyDataContainer .getAll() .parallelStream() .filter(t -> t != null && t.getEmbeddedId().getIndicatorId().equals(indicator)).findFirst(); ViewWorldbankIndicatorDataCountrySummary indicatorSummaryValue = null; if (indicatorSummary.isPresent()) { indicatorSummaryValue = indicatorSummary.get(); getFormFactory().addFormPanelTextFields(verticalLayout, indicatorSummaryValue, ViewWorldbankIndicatorDataCountrySummary.class, AS_LIST); } final DataContainer dataContainer = getApplicationManager() .getDataContainer(WorldBankData.class); final List dataList = dataContainer.findListByEmbeddedProperty(WorldBankData.class, WorldBankData_.indicator, Indicator.class, Indicator_.id, indicator); chartDataManager.createIndicatorChart(verticalLayout,dataList,indicatorSummaryValue); }private void handleInputViolations(final CreateApplicationEventRequest eventRequest, final Set> requestConstraintViolations,final V response) { final String errorMessage = getHumanMessage(requestConstraintViolations); ((AbstractResponse) response).setErrorMessage(errorMessage); eventRequest.setErrorMessage(errorMessage); }private String getHumanMessage(final Set> requestConstraintViolations) { return requestConstraintViolations.stream() .sorted((p1, p2) -> p1.getPropertyPath().toString().compareTo(p2.getPropertyPath().toString())) .map(p -> p.getPropertyPath().toString() + " " + p.getMessage()).collect(Collectors.joining(", ")); }private Set> validateRequest(final T request) { final ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); return factory.getValidator().validate( request ); }protected final CreateApplicationEventRequest createBaseApplicationEventRequest() { final CreateApplicationEventRequest eventRequest = new CreateApplicationEventRequest(); final UserAccount userAccount = getUserAccountFromSecurityContext(); if (userAccount != null) { eventRequest.setUserId(userAccount.getUserId()); } return eventRequest; }protected final V inputValidation(final T serviceRequest) { final Set> validateRequest = validateRequest(serviceRequest); if (!validateRequest.isEmpty()) { final CreateApplicationEventRequest eventRequest = createApplicationEventForService(serviceRequest); final V response = createErrorResponse(); handleInputViolations(eventRequest, validateRequest, response); createApplicationEventService.processService(eventRequest); return response; } else { return null; } }private static void updateAssignmentData(final List assignmentList, final AssignmentData assignmentData) { for (final AssignmentData matchAssignmentData : assignmentList) { if (matchAssignmentData.getFromDate().equals(assignmentData.getFromDate()) && matchAssignmentData.getOrgCode().equals(assignmentData.getOrgCode()) && matchAssignmentData.getRoleCode().equals(assignmentData.getRoleCode())) { matchAssignmentData.setStatus(assignmentData.getStatus()); matchAssignmentData.setToDate(assignmentData.getToDate()); return; } } assignmentList.add(assignmentData); }private static void updatePersonAssignmentData(final PersonAssignmentData exist, final PersonAssignmentData update) { final List assignmentList = update.getAssignmentList(); for (final AssignmentData assignmentData : assignmentList) { updateAssignmentData(exist.getAssignmentList(), assignmentData); } }private static void addViewApplicationActionEventPageElementDailySummaryValues(final String label, final Series series, final List list, final DataSeries dataSeries, final SimpleDateFormat simpleDateFormat, final ToLongFunction t) { series.addSeries(new XYseries().setLabel(label)); dataSeries.newSeries(); for (final ViewApplicationActionEventPageElementDailySummary item : list) { dataSeries.add(simpleDateFormat.format(item.getEmbeddedId().getCreatedDate()), t.applyAsLong(item)); } }private List getApplicationActionEventPageElementDailySummaryList( final String page, final String elementId) { final DataContainer documentTypeSummaryDailyDataContainer = getApplicationManager() .getDataContainer(ViewApplicationActionEventPageElementDailySummary.class); final List findOrderedListByEmbeddedProperty = documentTypeSummaryDailyDataContainer .findOrderedListByEmbeddedProperty(ViewApplicationActionEventPageElementDailySummary.class, ViewApplicationActionEventPageElementDailySummary_.embeddedId, ApplicationActionEventPageElementPeriodSummaryEmbeddedId.class, ApplicationActionEventPageElementPeriodSummaryEmbeddedId_.elementId, elementId, ApplicationActionEventPageElementPeriodSummaryEmbeddedId_.createdDate); return findOrderedListByEmbeddedProperty.parallelStream() .filter(t -> t != null && t.getEmbeddedId().getPage().equals(page)).collect(Collectors.toList()); }private Map> getApplicationActionEventPageModeDailySummaryMap( final String page) { final DataContainer documentTypeSummaryDailyDataContainer = getApplicationManager() .getDataContainer(ViewApplicationActionEventPageModeDailySummary.class); final List findOrderedListByEmbeddedProperty = documentTypeSummaryDailyDataContainer .findOrderedListByEmbeddedProperty(ViewApplicationActionEventPageModeDailySummary.class, ViewApplicationActionEventPageModeDailySummary_.embeddedId, ApplicationActionEventPageModePeriodSummaryEmbeddedId.class, ApplicationActionEventPageModePeriodSummaryEmbeddedId_.page, page, ApplicationActionEventPageModePeriodSummaryEmbeddedId_.createdDate); return findOrderedListByEmbeddedProperty.parallelStream().filter(Objects::nonNull) .collect(Collectors.groupingBy(t -> t.getEmbeddedId().getPageMode())); }private Map> getApplicationActionEventPageDailySummaryMap() { final DataContainer documentTypeSummaryDailyDataContainer = getApplicationManager() .getDataContainer(ViewApplicationActionEventPageDailySummary.class); return documentTypeSummaryDailyDataContainer.getAll().parallelStream().filter(Objects::nonNull) .collect(Collectors.groupingBy(t -> t.getEmbeddedId().getPage())); }public static boolean allowRoleInSecurityContext(final String role) { boolean result = false; final SecurityContext context = SecurityContextHolder.getContext(); if (context != null && context.getAuthentication() != null) { final Collection authorities = context.getAuthentication().getAuthorities(); for (final GrantedAuthority grantedAuthority : authorities) { if (role.equalsIgnoreCase(grantedAuthority.getAuthority())) { result = true; } } } return result; }public static String getRequestUrl(final Page current) { if (current != null) { return current.getLocation().toString(); } else { final HttpServletRequest httpRequest=((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest(); return httpRequest.getRequestURL().toString(); } }public static String getUserIdFromSecurityContext() { final SecurityContext context = SecurityContextHolder.getContext(); if (context != null) { final Authentication authentication = context.getAuthentication(); if (authentication != null) { return authentication.getPrincipal().toString(); } } return null; }private static void addDocTypeDecisionDataRows(final SankeyChart chart, final Entry> entry) { final Map> docTypeMap = entry.getValue().stream() .collect(Collectors.groupingBy(ProposalCommitteeeSummary::getDocType)); for (final Entry> docEntry : docTypeMap.entrySet()) { final Map> decisionMap = docEntry.getValue().stream() .collect(Collectors.groupingBy(ProposalCommitteeeSummary::getDecision)); for (final Entry> decisionEntry : decisionMap.entrySet()) { if (decisionEntry.getKey().length() > 0 && entry.getKey().length() > 0) { chart.addDataRow(docEntry.getKey(), decisionEntry.getKey(), decisionEntry.getValue().size()); } } } }private static void addDocTypeDataRows(final SankeyChart chart, final Entry> entry, final ViewRiksdagenCommittee vewRiksdagenCommittee) { final Map> docTypeMap = entry.getValue().stream() .collect(Collectors.groupingBy(ProposalCommitteeeSummary::getDocType)); for (final Entry> docEntry : docTypeMap.entrySet()) { if (docEntry.getKey().length() > 0 && entry.getKey().length() > 0) { chart.addDataRow(docEntry.getKey(), vewRiksdagenCommittee.getEmbeddedId().getDetail(), docEntry.getValue().size()); } } }private static void addDecisionDataRows(final SankeyChart chart, final Entry> entry, final ViewRiksdagenCommittee vewRiksdagenCommittee) { final Map> decisionMap = entry.getValue().stream() .collect(Collectors.groupingBy(ProposalCommitteeeSummary::getDecision)); for (final Entry> decisionEntry : decisionMap.entrySet()) { if (decisionEntry.getKey().length() > 0 && entry.getKey().length() > 0) { chart.addDataRow(vewRiksdagenCommittee.getEmbeddedId().getDetail(), decisionEntry.getKey(), decisionEntry.getValue().size()); } } }private static void addEntry(final StringBuilder stringBuilder, final Entry> entry, final Entry> docEntry) { stringBuilder.append("( ").append(docEntry.getValue().size()).append(' ').append(docEntry.getKey()).append(" -> "); final Map> decisionMap = docEntry.getValue().stream() .collect(Collectors.groupingBy(ProposalCommitteeeSummary::getDecision)); for (final Entry> decisionEntry : decisionMap.entrySet()) { if (decisionEntry.getKey().length() > 0 && entry.getKey().length() > 0) { stringBuilder.append(decisionEntry.getValue().size()).append(' ').append(decisionEntry.getKey()).append(' '); } } stringBuilder.append(')'); }private static void addCommiteeSummary(final StringBuilder stringBuilder, final Entry> entry, final Optional vewRiksdagenCommittee) { if (vewRiksdagenCommittee.isPresent()) { final Map> docTypeMap = entry.getValue().stream() .collect(Collectors.groupingBy(ProposalCommitteeeSummary::getDocType)); stringBuilder.append('\n').append(vewRiksdagenCommittee.get().getEmbeddedId().getDetail()); for (final Entry> docEntry : docTypeMap.entrySet()) { if (docEntry.getKey().length() > 0 && entry.getKey().length() > 0) { addEntry(stringBuilder, entry, docEntry); } } } }@OneToMany(targetEntity = SwedenCountyElectoralArea.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "LANDSTINGSVALKRETS_SWEDEN_CO_0") public List getLandstingsvalkrets() { return this.landstingsvalkrets; }private void reencryptVaultValues(final ChangePasswordRequest serviceRequest, final UserAccount userAccount) { final String authKey= vaultManager.getEncryptedValue(serviceRequest.getCurrentPassword(), userAccount); if (authKey != null) { final EncryptedValue encryptedValue = encryptedValueDAO.findFirstByProperty(EncryptedValue_.userId, userAccount.getUserId()); encryptedValue.setStorage(vaultManager.encryptValue(serviceRequest.getNewPassword(), userAccount.getUserId(), authKey)); encryptedValueDAO.merge(encryptedValue); } }private void addFallbackValue(final StringBuilder stringBuilder, final Object object) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (fallbackColumn != null) { final String beanPropertyFallBack = BeanUtils.getProperty(object, fallbackColumn); if (beanPropertyFallBack != null) { stringBuilder.append(beanPropertyFallBack); } } }private void appendObjectPresentation(final StringBuilder stringBuilder, final Object object) { try { final String beanProperty = BeanUtils.getProperty(object, property); if (beanProperty != null) { stringBuilder.append(beanProperty); } else { addFallbackValue(stringBuilder, object); } } catch (final IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { LOGGER.warn("Problem getting property {}, object {} , exception {}", property, object, e); } stringBuilder.append(CONTENT_SEPARATOR); }private static String[] readMissingPersonList() { final Scanner sc = new Scanner(RiksdagenPersonsWorkGeneratorImpl.class.getResourceAsStream("/personlist.txt"),StandardCharsets.UTF_8.name()); final List lines = new ArrayList<>(); while (sc.hasNextLine()) { lines.add(sc.nextLine()); } sc.close(); return lines.toArray(new String[0]); }private static void addDocumentHistoryByPartyData(final DataSeries dataSeries, final Series series, final Map> map) { final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DD_MMM_YYYY, Locale.ENGLISH); for (final Entry> entry : map.entrySet()) { series.addSeries(new XYseries().setLabel(entry.getKey())); dataSeries.newSeries(); if (entry.getValue() != null) { for (final ViewRiksdagenPartyDocumentDailySummary item : entry.getValue()) { dataSeries.add(simpleDateFormat.format(item.getEmbeddedId().getPublicDate()), item.getTotal()); } } else { LOGGER.info(LOG_MSG_MISSING_DATA_FOR_KEY, entry); } } }private Map> getViewRiksdagenPartyDocumentDailySummaryMap() { final DataContainer politicianBallotSummaryDailyDataContainer = getApplicationManager() .getDataContainer(ViewRiksdagenPartyDocumentDailySummary.class); return politicianBallotSummaryDailyDataContainer.getAll().parallelStream().filter(Objects::nonNull) .collect(Collectors.groupingBy(t -> t.getEmbeddedId().getPartyShortCode().toUpperCase(Locale.ENGLISH) .replace(UNDER_SCORE, EMPTY_STRING).trim())); }@ManyToOne(targetEntity = DocumentPersonReferenceContainer.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "DOCUMENT_PERSON_REFERENCE_CO_1") public DocumentPersonReferenceContainer getDocumentPersonReferenceContainer() { return documentPersonReferenceContainer; }@ManyToOne(targetEntity = DocumentReferenceContainer.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "DOCUMENT_REFERENCE_CONTAINER_0") public DocumentReferenceContainer getDocumentReferenceContainer() { return documentReferenceContainer; }@ManyToOne(targetEntity = DocumentAttachmentContainer.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "DOCUMENT_ATTACHMENT_CONTAINE_0") public DocumentAttachmentContainer getDocumentAttachmentContainer() { return documentAttachmentContainer; }@ManyToOne(targetEntity = DocumentDetailContainer.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "DOCUMENT_DETAIL_CONTAINER_DO_0") public DocumentDetailContainer getDocumentDetailContainer() { return documentDetailContainer; }@ManyToOne(targetEntity = DocumentActivityContainer.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "DOCUMENT_ACTIVITY_CONTAINER__0") public DocumentActivityContainer getDocumentActivityContainer() { return documentActivityContainer; }@ManyToOne(targetEntity = DocumentProposalContainer.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "DOCUMENT_PROPOSAL_DOCUMENT_S_0") public DocumentProposalContainer getDocumentProposal() { return documentProposal; }private void sendCountryIndicatorWorkOrder(final Map currentSaved, final List indicators, final String countryIso2Code) { for (final String indicator : indicators) { if (countryIso2Code != null && countryIso2Code.length() > 0 && !currentSaved.containsKey(countryIso2Code + '.' + indicator)) { final List load = new ArrayList<>(); load.add(countryIso2Code); load.add(indicator); getJmsSender().send(dataWorkdestination, (Serializable) load); } } }public static ResponsiveRow createGridLayout(final AbstractOrderedLayout panelContent) { final ResponsiveLayout layout = new ResponsiveLayout(); Responsive.makeResponsive(layout); layout.addStyleName("v-layout-content-overview-panel-level1"); layout.setWidth(100, Unit.PERCENTAGE); layout.setHeight(100, Unit.PERCENTAGE); panelContent.addComponent(layout); panelContent.setExpandRatio(layout, ContentRatio.LARGE); return layout.addRow(); }public static void createRowItem(final ResponsiveRow row, final Button button, final String description) { final CssLayout layout = new CssLayout(); layout.addStyleName("v-layout-content-overview-panel-level2"); Responsive.makeResponsive(layout); layout.setSizeUndefined(); button.addStyleName(ITEMBOX); button.addStyleName(TITLE); Responsive.makeResponsive(button); button.setWidth(100, Unit.PERCENTAGE); layout.addComponent(button); final Label descriptionLabel = new Label(description); descriptionLabel.addStyleName(ITEMBOX); Responsive.makeResponsive(descriptionLabel); descriptionLabel.setWidth(100, Unit.PERCENTAGE); layout.addComponent(descriptionLabel); row.addColumn().withDisplayRules(DISPLAY_SIZE_XS_DEVICE, DISPLAYS_SIZE_XM_DEVICE, DISPLAY_SIZE_MD_DEVICE, DISPLAY_SIZE_LG_DEVICE).withComponent(layout); }private UserAccount createUserAccount(final RegisterUserRequest serviceRequest) { final ApplicationConfiguration registeredUsersGetAdminConfig = applicationConfigurationService .checkValueOrLoadDefault("Registered User All get Role Admin", "Registered User All get Role Admin", ConfigurationGroup.AUTHORIZATION, RegisterUserService.class.getSimpleName(), "Register User Service", "Responsible for create of useraccounts", "registered.users.get.admin", "true"); final UserAccount userAccount = new UserAccount(); userAccount.setCountry(serviceRequest.getCountry()); userAccount.setEmail(serviceRequest.getEmail()); userAccount.setUsername(serviceRequest.getUsername()); userAccount.setUserId(UUID.randomUUID().toString()); userAccount.setUserpassword( passwordEncoder.encode(userAccount.getUserId() + ".uuid" + serviceRequest.getUserpassword())); userAccount.setNumberOfVisits(1); if ( serviceRequest.getUserType() == null) { userAccount.setUserType(UserType.PRIVATE); } else { userAccount.setUserType(serviceRequest.getUserType()); } userAccount.setUserEmailStatus(UserEmailStatus.UNKNOWN); userAccount.setUserLockStatus(UserLockStatus.UNLOCKED); userAccount.setCreatedDate(new Date()); getUserDAO().persist(userAccount); final Collection authorities = new ArrayList<>(); if ("true".equals(registeredUsersGetAdminConfig.getPropertyValue())) { userAccount.setUserRole(UserRole.ADMIN); authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN")); } else { userAccount.setUserRole(UserRole.USER); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); } SecurityContextHolder.getContext().setAuthentication( new UsernamePasswordAuthenticationToken(userAccount.getUserId(), "n/a", authorities)); return userAccount; }@ManyToOne(targetEntity = PersonDetailElement.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "PERSON_DETAIL_ELEMENT_PERSON_0") public PersonDetailElement getPersonDetailElement() { return personDetailElement; }@ManyToOne(targetEntity = PersonAssignmentElement.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "PERSON_ASSIGNMENT_ELEMENT_PE_0") public PersonAssignmentElement getPersonAssignmentElement() { return personAssignmentElement; }private List getGovernmentBodyList() { final List result = new ArrayList<>(); try { result.addAll(esvGovernmentBodyOperationOutcomeReader.readIncomeCsv()); result.addAll(esvGovernmentBodyOperationOutcomeReader.readOutgoingCsv()); } catch (final IOException e) { LOGGER.error(GET_GOVERNMENT_BODY_REPORT,e); return result; } return result; }@OneToMany(targetEntity = BallotDocumentElement.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "VOTERING_VOTE_LIST_CONTAINER_0") public List getVotering() { return this.votering; }private static String readInputStream(final String accessUrl) throws IOException { final URL url = new URL(accessUrl.replace(" ", "")); return readWithStringBuffer(new BufferedReader(new InputStreamReader(url.openConnection().getInputStream(), StandardCharsets.UTF_8))); }private static String readWithStringBuffer(final Reader fr) throws IOException { final BufferedReader br = new BufferedReader(fr); String line; final StringBuilder result = new StringBuilder(); while ((line = br.readLine()) != null) { result.append(line); } return result.toString(); }private List loadDocumentList(final String url, final int maxNumberPages) throws XmlAgentException { final List result = new ArrayList<>(); DocumentContainerElement dokumentLista = ((JAXBElement) xmlAgent.unmarshallXml( riksdagenDocumentListMarshaller, url, HTTP_DOKUMENTLISTA_RIKSDAGEN_EXTERNAL_MODEL_CIA_HACK23_COM_IMPL, null, null)).getValue(); result.addAll(dokumentLista.getDokument()); final BigInteger pages = dokumentLista.getTotalPages(); for (int i = 1; i < pages.intValue() && i < maxNumberPages; i++) { dokumentLista = ((JAXBElement) xmlAgent.unmarshallXml( riksdagenDocumentListMarshaller, fixBrokenUrl(dokumentLista.getNextPage()), HTTP_DOKUMENTLISTA_RIKSDAGEN_EXTERNAL_MODEL_CIA_HACK23_COM_IMPL, null, null)).getValue(); result.addAll(dokumentLista.getDokument()); LOGGER.info(LOADING_DOCUMENTS, result.size(), dokumentLista.getHits()); } return result; }private void loadAndProcessDocumentList(final String url, final ProcessDataStrategy processStrategy) throws XmlAgentException { final DocumentContainerElement dokumentLista = ((JAXBElement) xmlAgent.unmarshallXml( riksdagenDocumentListMarshaller, url, HTTP_DOKUMENTLISTA_RIKSDAGEN_EXTERNAL_MODEL_CIA_HACK23_COM_IMPL, null, null)).getValue(); int resultSize = dokumentLista.getDokument().size(); processAll(dokumentLista.getDokument(), processStrategy); final BigInteger pages = dokumentLista.getTotalPages(); for (int i = 1; i < pages.intValue(); i++) { final DocumentContainerElement otherPagesdokumentLista = ((JAXBElement) xmlAgent .unmarshallXml(riksdagenDocumentListMarshaller, url + PAGE_PROPERTY + i, HTTP_DOKUMENTLISTA_RIKSDAGEN_EXTERNAL_MODEL_CIA_HACK23_COM_IMPL, null, null)).getValue(); resultSize = resultSize + otherPagesdokumentLista.getDokument().size(); processAll(otherPagesdokumentLista.getDokument(), processStrategy); LOGGER.info(LOADING_DOCUMENTS, resultSize, dokumentLista.getHits()); } }private static void processAll(final List dokument, final ProcessDataStrategy processStrategy) { for (final DocumentElement documentElement : dokument) { try { processStrategy.process(documentElement); } catch (final RuntimeException e) { LOGGER.warn(ERROR_PROCESSING_DOCUMENT, documentElement.getId(), e); } } }private void createRoleList(final VerticalLayout roleSummaryLayoutTabsheet, final List assignmentList) { final Comparator compare = (o1, o2) -> o1.getFromDate().compareTo(o2.getFromDate()); Collections.sort(assignmentList, compare); getGridFactory().createBasicBeanItemGrid(roleSummaryLayoutTabsheet, AssignmentData.class, assignmentList, ASSIGNMENTS, COLUMN_ORDER, HIDE_COLUMNS, null, null, null); }private void createMinistrySummary(final AbstractOrderedLayout content, final String field, final String label) { final DataSeries dataSeries = new DataSeries(); final Series series = new Series(); final Map> reportByMinistry = esvApi.getGovernmentBodyReportByMinistry(); for (final Entry> entry : reportByMinistry.entrySet()) { series.addSeries(new XYseries().setLabel(entry.getKey())); dataSeries.newSeries(); final Map annualSummaryMap = entry.getValue().stream().filter(t -> t.getDescriptionFields().get(field) != null).collect(Collectors.groupingBy(GovernmentBodyAnnualOutcomeSummary::getYear,Collectors.summingDouble(GovernmentBodyAnnualOutcomeSummary::getYearTotal))); for (final Entry entryData : annualSummaryMap.entrySet()) { if (entryData.getValue() != null && entryData.getValue().intValue() > 0) { dataSeries.add(entryData.getKey() +1 +"-01-01" , entryData.getValue()); } } } addChart(content, label, new DCharts().setDataSeries(dataSeries) .setOptions(getChartOptions().createOptionsXYDateFloatLogYAxisLegendOutside(series)).show(), true); }private static void addEntryData(final DataSeries dataSeries, final SimpleDateFormat simpleDateFormat, final Entry> entry) { for (final GovernmentBodyAnnualOutcomeSummary data : entry.getValue()) { final Map valueMap = data.getValueMap(); for (final Entry entryData : valueMap.entrySet()) { if (entryData.getValue() != null && entryData.getValue().intValue() > 0) { dataSeries.add(simpleDateFormat.format(entryData.getKey()) , entryData.getValue().intValue()); } } } }private void addAnnualData(final VerticalLayout content, final String name, final String label, final Map> collect) { final DataSeries dataSeries = new DataSeries(); final Series series = new Series(); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH); for (final Entry> entry : collect.entrySet()) { series.addSeries(new XYseries().setLabel(entry.getKey())); dataSeries.newSeries(); addEntryData(dataSeries, simpleDateFormat, entry); } addChart(content, name + label, new DCharts().setDataSeries(dataSeries) .setOptions(getChartOptions().createOptionsXYDateFloatLogYAxisLegendOutside(series)).show(), true); }private static void addAnnualSummaryData(final DataSeries dataSeries, final Series series, final Entry> entry, final List allValues) { series.addSeries(new XYseries().setLabel(entry.getKey()).setShowLabel(true)); dataSeries.newSeries(); final Map> map = allValues.stream() .collect(Collectors.groupingBy(GovernmentBodyAnnualOutcomeSummary::getYear)); for (final Entry> data : map.entrySet()) { final List values = data.getValue(); final double sum = values.stream().mapToDouble(GovernmentBodyAnnualOutcomeSummary::getYearTotal).sum(); if (sum > 0) { dataSeries.add(data.getKey() + FIRST_JAN_DATA_SUFFIX, (int) sum); } } }private void addAnnualSummary(final Map> report, final VerticalLayout content, final String label) { final DataSeries dataSeries = new DataSeries(); final Series series = new Series(); for (final Entry> entry : report.entrySet()) { final List allValues = entry.getValue(); if (!allValues.isEmpty()) { addAnnualSummaryData(dataSeries, series, entry, allValues); } } addChart(content, label, new DCharts().setDataSeries(dataSeries) .setOptions(getChartOptions().createOptionsXYDateFloatLogYAxisLegendOutside(series)).show(), true); }private static void addDataSerieValue(final DataSeries dataSeries, final Entry entry, final int value) { if (entry.getKey() != null && value > 0) { dataSeries.add(FIRST_OF_JAN + entry.getKey(), value); } }@OneToMany(targetEntity = AgainstProposalData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "AGAINST_PROPOSAL_LIST_AGAINS_0") public List getAgainstProposalList() { return this.againstProposalList; }private static void insertParty(final KieSession ksession, final ViewRiksdagenPartySummary partyData, final List dailyList, final List monthlyList, final List annualList, final List ballotDecisions) { if (partyData.isActiveParliament() && dailyList != null && monthlyList != null && annualList != null) { Collections.sort(dailyList, (e1, e2) -> e1.getEmbeddedId().getVoteDate().compareTo(e2.getEmbeddedId().getVoteDate())); final Optional dailyListFirst = dailyList.stream() .findFirst(); Collections.sort(monthlyList, (e1, e2) -> e1.getEmbeddedId().getVoteDate().compareTo(e2.getEmbeddedId().getVoteDate())); final Optional monthlyListFirst = monthlyList.stream() .findFirst(); Collections.sort(annualList, (e1, e2) -> e1.getEmbeddedId().getVoteDate().compareTo(e2.getEmbeddedId().getVoteDate())); final Optional annualListFirst = annualList.stream() .findFirst(); if (annualListFirst.isPresent() && monthlyListFirst.isPresent() && dailyListFirst.isPresent()) { final PartyComplianceCheckImpl politicianComplianceCheckImpl = new PartyComplianceCheckImpl(partyData, dailyListFirst.get(), monthlyListFirst.get(), annualListFirst.get(), ballotDecisions); ksession.insert(politicianComplianceCheckImpl); } } else { final PartyComplianceCheckImpl politicianComplianceCheckImpl = new PartyComplianceCheckImpl(partyData, null, null, null, new ArrayList<>()); ksession.insert(politicianComplianceCheckImpl); } }private static void insertPolitician(final KieSession ksession, final ViewRiksdagenPolitician politicianData, final List dailyList, final List monthlyList, final List annualList, final List decisionList) { if (politicianData.isActiveParliament() && dailyList != null && monthlyList != null && annualList != null) { Collections.sort(dailyList, (e1, e2) -> e1.getEmbeddedId().getVoteDate().compareTo(e2.getEmbeddedId().getVoteDate())); final Optional dailyListFirst = dailyList.stream() .findFirst(); Collections.sort(monthlyList, (e1, e2) -> e1.getEmbeddedId().getVoteDate().compareTo(e2.getEmbeddedId().getVoteDate())); final Optional monthlyListFirst = monthlyList.stream() .findFirst(); Collections.sort(annualList, (e1, e2) -> e1.getEmbeddedId().getVoteDate().compareTo(e2.getEmbeddedId().getVoteDate())); final Optional annualListFirst = annualList.stream() .findFirst(); if (annualListFirst.isPresent() && monthlyListFirst.isPresent() && dailyListFirst.isPresent()) { final PoliticianComplianceCheckImpl politicianComplianceCheckImpl = new PoliticianComplianceCheckImpl( politicianData, dailyListFirst.get(), monthlyListFirst.get(), annualListFirst.get(), decisionList); ksession.insert(politicianComplianceCheckImpl); } } else { final PoliticianComplianceCheckImpl politicianComplianceCheckImpl = new PoliticianComplianceCheckImpl( politicianData, null, null, null, new ArrayList<>()); ksession.insert(politicianComplianceCheckImpl); } }private void addPagingLink(final String label, final String name, final String pageId, final long maxPages, final HorizontalLayout pagingControls) { final Link previousPageLink = pageLinkFactory.createAdminPagingLink(label,name, pageId, String.valueOf(maxPages)); pagingControls.addComponent(previousPageLink); pagingControls.setExpandRatio(previousPageLink, ContentRatio.SMALL); }@Override public void createPagingControls(final AbstractOrderedLayout content, final String name, final String pageId, final Long size, final int pageNr, final int resultPerPage) { final HorizontalLayout pagingControls = new HorizontalLayout(); pagingControls.setSpacing(true); pagingControls.setMargin(true); final long maxPages = (size +resultPerPage-1) / resultPerPage; final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(PAGE_HEADER) .append(pageNr) .append(PAGE_SEPARATOR) .append(maxPages) .append(PAGES_TOTAL_RESULTS) .append(size) .append(RESULTS_PER_PAGE) .append(resultPerPage) .append(SHOW); final Label pageInfo = new Label(stringBuilder.toString()); pagingControls.addComponent(pageInfo); pagingControls.setExpandRatio(pageInfo, ContentRatio.SMALL); if (pageNr > PAGE_ONE) { addPagingLink(PREVIOUS_PAGE,name, pageId, pageNr -1L,pagingControls); } if (maxPages > PAGE_ONE && pageNr < maxPages) { addPagingLink(NEXT_PAGE,name, pageId, pageNr +1L,pagingControls); } if (maxPages > LIMIT_FOR_DISPLAYING_START_END_LINKS && pageNr > PAGE_ONE) { addPagingLink(FIRST_PAGE,name, pageId, 1,pagingControls); } if (maxPages > LIMIT_FOR_DISPLAYING_START_END_LINKS && pageNr < maxPages) { addPagingLink(LAST_PAGE,name, pageId, maxPages,pagingControls); } content.addComponent(pagingControls); content.setExpandRatio(pagingControls, ContentRatio.SMALL2); }private static List readUsingZipInputStream(final InputStream inputStream) throws IOException { final BufferedInputStream bis = new BufferedInputStream(inputStream); final ZipInputStream is = new ZipInputStream(bis); final List list = new ArrayList<>(); try { ZipEntry entry; while ((entry = is.getNextEntry()) != null) { if (entry.getName().startsWith("API_SWE_")) { list.addAll(readCsvContent(is)); } } } finally { is.close(); } return list; }protected final List getStringIdList(final SingularAttribute property) { final CriteriaQuery criteria = getCriteriaBuilder().createQuery(String.class); final Root root = criteria.from(persistentClass); criteria.select(getCriteriaBuilder().construct(String.class,root.get(property))); return getEntityManager().createQuery(criteria).getResultList(); }protected final void addCacheHints(final TypedQuery typedQuery, final String comment) { typedQuery.setHint("org.hibernate.cacheMode", CacheMode.NORMAL); typedQuery.setHint("org.hibernate.cacheable", Boolean.TRUE); typedQuery.setHint("org.hibernate.comment", comment); }@ElementCollection @OrderColumn(name = "HJINDEX") @Column(name = "HJVALUE") @CollectionTable(name = "USER_ACCOUNT_ADDRESS", joinColumns = { @JoinColumn(name = "HJID") }) public List getAddress() { if (address == null) { address = new ArrayList<>(); } return this.address; }private Map> getTopicIndicatorMap() { final DataContainer indicatorDataCountrSummaryDailyDataContainer = applicationManager .getDataContainer(ViewWorldbankIndicatorDataCountrySummary.class); return indicatorDataCountrSummaryDailyDataContainer .findListByEmbeddedProperty(ViewWorldbankIndicatorDataCountrySummary.class,ViewWorldbankIndicatorDataCountrySummary_.embeddedId,WorldbankIndicatorDataCountrySummaryEmbeddedId.class,WorldbankIndicatorDataCountrySummaryEmbeddedId_.countryId,"SE").parallelStream() .filter(t -> t != null && t.getSourceValue() != null && t.getEndYear() > DATA_POINTS_FOR_YEAR_ABOVE && t.getDataPoint() > MINIMUM_NUMBER_DATA_POINTS) .flatMap(t -> Arrays.asList(t.getTopics().split(";")).stream() .map(topic -> new AbstractMap.SimpleEntry<>(topic, t))) .collect(Collectors.groupingBy(SimpleEntry::getKey, Collectors.mapping(SimpleEntry::getValue, Collectors.toList()))); }private static void addSourcesAndIndicatorsToMenu(final MenuItem countryIndicators, final Map> sourceIndicatorMap) { final Map> sortedIndicatorMap = sourceIndicatorMap .entrySet().stream().sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); for (final Entry> entry : sortedIndicatorMap .entrySet()) { final MenuItem sourceItems = countryIndicators.addItem(entry.getKey(), null, null); final List sortedEntries = entry.getValue().stream() .sorted((e1, e2) -> e1.getIndicatorName().compareTo(e2.getIndicatorName())) .collect(Collectors.toList()); for (final ViewWorldbankIndicatorDataCountrySummary indciatorSummary : sortedEntries) { final MenuItem addItem = sourceItems.addItem(indciatorSummary.getIndicatorName(), new PageModeMenuCommand(UserViews.COUNTRY_RANKING_VIEW_NAME, PageMode.INDICATORS, indciatorSummary.getEmbeddedId().getIndicatorId())); addItem.setStyleName("RestrictedHeader"); } } }@OneToMany(targetEntity = Topic.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "TOPIC_TOPICS_HJID") public List getTopic() { return this.topic; }protected void showNotification(final String caption, final String description, final Type type) { Notification.show(caption, description, type); }protected ApplicationManager getApplicationManager() { return WebApplicationContextUtils .getWebApplicationContext(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()) .getRequest().getSession(true).getServletContext()) .getBean(ApplicationManager.class); }private static void navigateToPage(final RuleViolation violation) { if (violation.getResourceType() == ResourceType.PARTY) { UI.getCurrent().getNavigator().navigateTo(UserViews.PARTY_VIEW_NAME + PAGE_SEPARATOR + violation.getId()); } else { UI.getCurrent().getNavigator().navigateTo(UserViews.POLITICIAN_VIEW_NAME + PAGE_SEPARATOR + violation.getId()); } }private void blockBySessionOrIpFailedLoginAttempts(final String sessionId, final LoginBlockResultImpl loginBlockResultImpl) { final ApplicationSession applicationSession = applicationSessionDAO .findFirstByProperty(ApplicationSession_.sessionId, sessionId); if (applicationSession != null) { final ApplicationConfiguration maxLoginAttemptsBySession = applicationConfigurationService.checkValueOrLoadDefault(MAX_FAILED_LOGIN_ATTEMPTS_RECENT_HOUR_PER_SESSION, BLOCKS_ANY_LOGIN_ATTEMPTS_AFTER_THIS_NUMBER_IS_REACHED, ConfigurationGroup.AUTHENTICATION, LoginBlockedAccessImpl.class.getSimpleName(), LOGIN_BLOCKER, BLOCKS_LOGIN_ATTEMPTS, APPLICATION_AUTHENTICATION_ALLOW_MAX_RECENT_FAILED_LOGINS_BY_SESSION,DEFAULT_MAX_LOGIN_ATTEMPTS); final List failedLoginsByThisSession = applicationActionEventDAO.findListByProperty( new Object[] { sessionId, ApplicationOperationType.AUTHENTICATION, ServiceResult.FAILURE.toString() }, ApplicationActionEvent_.sessionId, ApplicationActionEvent_.applicationOperation, ApplicationActionEvent_.applicationMessage); if (failedLoginsByThisSession.size() > NumberUtils.toInt(maxLoginAttemptsBySession.getPropertyValue(),DEFAULT_MAX_LOGINS)) { loginBlockResultImpl.setBlocked(true); loginBlockResultImpl.addMessages(BLOCKED_BY_MORE_THAN_5_LOGIN_ATTEMPTS_BY_THIS_SESSION); } if (!("0:0:0:0:0:0:0:1".equals(applicationSession.getIpInformation()) || "127.0.0.1".equals(applicationSession.getIpInformation()))) { final List applicationSessionsByIp = applicationSessionDAO .findListByProperty(ApplicationSession_.ipInformation, applicationSession.getIpInformation()); final List sessionIdsWithIp = applicationSessionsByIp.stream().map(ApplicationSession::getSessionId) .collect(Collectors.toList()); final List applicationEventsWithIp = applicationActionEventDAO .findListByPropertyInList(ApplicationActionEvent_.sessionId, sessionIdsWithIp.toArray(new Object[sessionIdsWithIp.size()])); final Date oneHourAgo = new Date(System.currentTimeMillis() - ONE_HOUR); final Map> recentOldLoginAttemptsMap = applicationEventsWithIp .stream() .filter((final ApplicationActionEvent x) -> x.getApplicationOperation() == ApplicationOperationType.AUTHENTICATION && x.getApplicationMessage().equals(ServiceResult.FAILURE.toString())) .collect(Collectors.groupingBy((final ApplicationActionEvent x) -> x.getCreatedDate().after(oneHourAgo))); final List recentFailedLogins = recentOldLoginAttemptsMap .get(Boolean.TRUE); final ApplicationConfiguration maxLoginAttemptsByIp = applicationConfigurationService.checkValueOrLoadDefault(MAX_FAILED_LOGIN_ATTEMPTS_RECENT_HOUR_PER_IP, BLOCKS_ANY_LOGIN_ATTEMPTS_AFTER_THIS_NUMBER_IS_REACHED, ConfigurationGroup.AUTHENTICATION, LoginBlockedAccessImpl.class.getSimpleName(), LOGIN_BLOCKER, BLOCKS_LOGIN_ATTEMPTS, APPLICATION_AUTHENTICATION_ALLOW_MAX_RECENT_FAILED_LOGINS_BY_IP, DEFAULT_MAX_LOGIN_ATTEMPTS); if (recentFailedLogins != null && recentFailedLogins.size() > NumberUtils.toInt(maxLoginAttemptsByIp.getPropertyValue(),DEFAULT_MAX_LOGINS_BY_IP)) { loginBlockResultImpl.setBlocked(true); loginBlockResultImpl.addMessages(BLOCKED_BY_MORE_THAN_5_RECENT_LOGIN_ATTEMPTS_BY_THIS_IP); } } } }private void blockByUserFailedLoginAttempts(final String email, final LoginBlockResultImpl loginBlockResultImpl) { final UserAccount userExist = userDAO.findFirstByProperty(UserAccount_.email, email); if (userExist != null) { final ApplicationConfiguration maxLoginAttemptsByUser = applicationConfigurationService.checkValueOrLoadDefault(MAX_FAILED_LOGIN_ATTEMPTS_RECENT_HOUR_PER_USER, BLOCKS_ANY_LOGIN_ATTEMPTS_AFTER_THIS_NUMBER_IS_REACHED, ConfigurationGroup.AUTHENTICATION, LoginBlockedAccessImpl.class.getSimpleName(), LOGIN_BLOCKER, BLOCKS_LOGIN_ATTEMPTS, APPLICATION_AUTHENTICATION_ALLOW_MAX_RECENT_FAILED_LOGINS_BY_USER, DEFAULT_MAX_LOGIN_ATTEMPTS); final List failedLoginsByThisUser = applicationActionEventDAO.findListByProperty( new Object[] { email, ApplicationOperationType.AUTHENTICATION, ServiceResult.FAILURE.toString() }, ApplicationActionEvent_.elementId, ApplicationActionEvent_.applicationOperation, ApplicationActionEvent_.applicationMessage); final Date oneHourAgo = new Date(System.currentTimeMillis() - ONE_HOUR); final Map> recentOldLoginAttemptsMap = failedLoginsByThisUser.stream() .collect(Collectors.groupingBy((final ApplicationActionEvent x ) -> x.getCreatedDate().after(oneHourAgo))); final List recentFailedLogins = recentOldLoginAttemptsMap.get(Boolean.TRUE); if (recentFailedLogins != null && recentFailedLogins.size() > NumberUtils.toInt(maxLoginAttemptsByUser.getPropertyValue(),DEFAULT_MAX_LOGINS)) { loginBlockResultImpl.setBlocked(true); loginBlockResultImpl.addMessages(BLOCKED_BY_MORE_THAN_5_RECENT_LOGIN_ATTEMPTS_BY_THIS_USER); } } }private static String getCommittteeShortName(final DocumentProposalData proposal) { final String upperCase = proposal.getProcessedIn().replaceAll("\\d","").replace("/:","").toUpperCase(Locale.ENGLISH); if (upperCase.contains(",")) { return upperCase.substring(0, upperCase.indexOf(',')); } else { return upperCase; } }private static String getDocumentName(final DocumentStatusContainer document) { if ("prop".equalsIgnoreCase(document.getDocument().getDocumentType())) { return "Proposition"; } else if (document.getDocument().getSubType() != null && document.getDocument().getSubType().length() > "motion".length()) { return document.getDocument().getSubType(); } else { return "Motion"; } }private static String cleanupDecision(final String chamber) { return chamber.toUpperCase(Locale.ENGLISH).replace("(UTSKOTTET)", "").replace("UTKOTTET", "UTSKOTTET").replace("UTBSKOTTET", "UTSKOTTET").replace("UBTSKOTTET", "UTSKOTTET").replace("(", "").replace(")",""); }@OneToMany(targetEntity = DocumentPersonReferenceData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "DOCUMENT_PERSON_REFERENCE_LI_1") public List getDocumentPersonReferenceList() { return this.documentPersonReferenceList; }private void sendMessage(final DataAgentWorkOrder workOrder) { switch (workOrder.getTarget()) { case MODEL_EXTERNAL_RIKSDAGEN: for (final RiksdagenDataSources datasource :RiksdagenDataSources.values()) { jmsSender.send(riksdagenApiDestination, datasource); } break; case MODEL_EXTERNAL_WORLDBANK: for (final WorldBankDataSources datasource :WorldBankDataSources.values()) { jmsSender.send(worldBankApiDestination, datasource); } break; default: break; } }private Object loadSecretXADataSource(final Reference ref) { return loadBaseDataSource(new SecretPGXADataSource(((SecretReference)ref).getSecretCredentialsManager()), ref); }protected final String convertToYearsString(final long totalDays) { final long years = totalDays / DAYS_PER_STANDARD_YEAR; final long days = totalDays - years * DAYS_PER_STANDARD_YEAR; return years + " Years " + days + " days"; }private static final Gantt createGantt() { final Gantt gantt = new Gantt(); gantt.setSizeFull(); gantt.setWidth(100, Unit.PERCENTAGE); gantt.setHeight(100, Unit.PERCENTAGE); gantt.setResizableSteps(false); gantt.setMovableSteps(false); gantt.setResolution(Resolution.Week); return gantt; }private static final Date stripDatesAfterCurrentDate(final Date toDate) { final DateTime currentTime = new DateTime(); if (currentTime.isBefore(toDate.getTime())) { return currentTime.plusDays(1).toDate(); } else { return toDate; } }private void addViewGenericRoleMemberToStep(final String stepName, final Step step, final List assignments, final StepMapping stepMapping) { for (final T assignmentData : assignments) { String subStepName = ""; if (stepMapping.getRoleCode(assignmentData) != null) { subStepName = new StringBuilder().append(stepMapping.getFirstName(assignmentData)) .append(CONTENT_SEPARATOR).append(stepMapping.getLastName(assignmentData)) .append(PARTY_START_TAG).append(stepMapping.getParty(assignmentData)).append(PARTY_END_TAG) .toString(); } final SubStep sameRoleSubStep = new SubStep(stepName + '.' + subStepName,CaptionMode.HTML); sameRoleSubStep.setDescription(stepName + '.' + subStepName); sameRoleSubStep.setBackgroundColor(stepMapping.getBackgroundColor(assignmentData)); sameRoleSubStep.setStartDate(stepMapping.getFromDate(assignmentData).getTime()); sameRoleSubStep.setEndDate(stripDatesAfterCurrentDate(stepMapping.getToDate(assignmentData)).getTime()); step.addSubStep(sameRoleSubStep); } }private SortedSet>> entriesSortedByValues(final Map> map, final StepMapping stepMapping) { final Comparator>> compare = (o1, o2) -> { final Comparator compare1 = (o11, o21) -> { final int compareDate = stepMapping.getFromDate(o11).compareTo(stepMapping.getFromDate(o21)); if (compareDate == 0) { final int compareType = stepMapping.getRoleCode(o11).compareTo(stepMapping.getRoleCode(o21)); if (compareType == 0) { return stepMapping.getOrg(o11).compareTo(stepMapping.getOrg(o21)); } else { return compareType; } } return compareDate; }; Collections.sort(o1.getValue(), compare1); Collections.sort(o2.getValue(), compare1); return compare1.compare(o1.getValue().get(0), o2.getValue().get(0)); }; final SortedSet>> sortedEntries = new TreeSet<>(compare); sortedEntries.addAll(map.entrySet()); return sortedEntries; }private Gantt createGenericGantt(final List assignmentList, final Function roleMapping, final StepMapping stepMapping) { final Map> assignmentListMap = assignmentList.stream() .collect(Collectors.groupingBy(roleMapping, TreeMap::new, Collectors.toList())); final Gantt gantt = createGantt(); if (!assignmentList.isEmpty()) { gantt.setStartDate(stepMapping.getFromDate(assignmentList.get(0))); gantt.setEndDate( stripDatesAfterCurrentDate(stepMapping.getToDate(assignmentList.get(assignmentList.size() - 1)))); for (final Entry> entry : entriesSortedByValues(assignmentListMap, stepMapping)) { final String stepName = entry.getKey(); final Step step = new Step(stepName,CaptionMode.HTML); step.setDescription(stepName); final List assignments = entry.getValue(); Collections.sort(assignments, getComparator()); addViewGenericRoleMemberToStep(stepName, step, assignments, stepMapping); gantt.addStep(step); } } return gantt; }public final void createRoleGhant(final AbstractOrderedLayout roleSummaryLayoutTabsheet, final Collection assignmentList) { final Comparator compare = getComparator(); final List list = assignmentList.stream().filter( (final T x) -> new DateTime(getStepMapping().getFromDate(x).getTime()).getYear() > FILTER_DATA_BEFORE_YEAR) .collect(Collectors.toList()); Collections.sort(list, compare); final Gantt createGantt = createGenericGantt(list, getRoleMapping(), getStepMapping()); roleSummaryLayoutTabsheet.addComponent(createGantt); roleSummaryLayoutTabsheet.setExpandRatio(createGantt, ContentRatio.GRID); }public void setGoogleAuthScratchCodes(final List googleAuthScratchCodes) { if (googleAuthScratchCodes != null) { this.googleAuthScratchCodes = googleAuthScratchCodes.stream().collect(Collectors.toList()); } }private static void addPoliticanData(final List list, final DataSeries dataSeries, final SimpleDateFormat simpleDateFormat, final Function t) { dataSeries.newSeries(); for (final ViewRiksdagenVoteDataBallotPoliticianSummaryDaily viewRiksdagenVoteDataBallotPoliticianSummaryDaily : list) { if (viewRiksdagenVoteDataBallotPoliticianSummaryDaily != null) { dataSeries.add( simpleDateFormat.format( viewRiksdagenVoteDataBallotPoliticianSummaryDaily.getEmbeddedId().getVoteDate()), t.apply(viewRiksdagenVoteDataBallotPoliticianSummaryDaily)); } } }private static void addPoliticianIndicatorData(final List list, final DataSeries dataSeries, final SimpleDateFormat simpleDateFormat) { addPoliticanData(list, dataSeries, simpleDateFormat, ViewRiksdagenVoteDataBallotPoliticianSummaryDaily::getWonPercentage); addPoliticanData(list, dataSeries, simpleDateFormat, ViewRiksdagenVoteDataBallotPoliticianSummaryDaily::getRebelPercentage); addPoliticanData(list, dataSeries, simpleDateFormat, ViewRiksdagenVoteDataBallotPoliticianSummaryDaily::getPoliticianPercentageAbsent); addPoliticanData(list, dataSeries, simpleDateFormat, ViewRiksdagenVoteDataBallotPoliticianSummaryDaily::getNumberBallots); }protected final void createPageVisitHistory(final String pageName, final String pageId, final VerticalLayout panelContent) { final TabSheet tabsheet = new TabSheet(); tabsheet.setWidth(100, Unit.PERCENTAGE); tabsheet.setHeight(100, Unit.PERCENTAGE); panelContent.addComponent(tabsheet); panelContent.setExpandRatio(tabsheet, ContentRatio.LARGE); final HorizontalLayout tabContentPageItemRankHistory = new HorizontalLayout(); tabContentPageItemRankHistory.setWidth(100, Unit.PERCENTAGE); tabContentPageItemRankHistory.setHeight(100, Unit.PERCENTAGE); final Tab tabPageItemRankHistory = tabsheet.addTab(tabContentPageItemRankHistory); tabPageItemRankHistory.setCaption(CURRENT_PAGE_VISIT_HISTORY); adminChartDataManager.createApplicationActionEventPageElementDailySummaryChart(tabContentPageItemRankHistory, pageName, pageId); final HorizontalLayout tabContentPageModeSummary = new HorizontalLayout(); tabContentPageModeSummary.setWidth(100, Unit.PERCENTAGE); tabContentPageModeSummary.setHeight(100, Unit.PERCENTAGE); final Tab tabPageModeSummary = tabsheet.addTab(tabContentPageModeSummary); tabPageModeSummary.setCaption(GENERAL_PAGE_MODE_PAGE_VISIT); adminChartDataManager.createApplicationActionEventPageModeDailySummaryChart(tabContentPageModeSummary, pageName); }protected final VerticalLayout createPanelContent() { final VerticalLayout panelContent = new VerticalLayout(); panelContent.setMargin(true); panelContent.setWidth(100, Unit.PERCENTAGE); panelContent.setHeight(100, Unit.PERCENTAGE); panelContent.setStyleName("Header"); return panelContent; }protected final int getPageNr(final String parameters) { final String cleanedString = parameters; String pageNrValue; if (cleanedString != null && cleanedString.contains("[") && cleanedString.contains("]")) { pageNrValue = cleanedString.substring(cleanedString.indexOf('[') + 1, cleanedString.lastIndexOf(']')); } else { pageNrValue = ""; } int pageNr = 1; if (pageNrValue.length() > 0 && !pageNrValue.contains("/")) { pageNr = Integer.parseInt(pageNrValue); } return pageNr; }protected final String getPageId(final String parameters) { if (parameters != null) { String cleanedString = parameters; if (parameters.contains("[")) { cleanedString = cleanedString.replace(cleanedString.substring(cleanedString.indexOf('[') , cleanedString.lastIndexOf(']')+1), ""); } return cleanedString.substring(cleanedString.lastIndexOf('/') + "/".length(), cleanedString.length()); } else { return ""; } }@OneToMany(targetEntity = ApplicationActionEvent.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "EVENTS_APPLICATION_SESSION_H_0") public List getEvents() { if (events == null) { events = new ArrayList<>(); } return this.events; }@ManyToOne(targetEntity = CommitteeProposalContainer.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "COMMITTEE_PROPOSAL_CONTAINER_0") public CommitteeProposalContainer getCommitteeProposalContainer() { return committeeProposalContainer; }@ManyToOne(targetEntity = AgainstProposalContainer.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "AGAINST_PROPOSAL_CONTAINER_C_0") public AgainstProposalContainer getAgainstProposalContainer() { return againstProposalContainer; }@OneToMany(targetEntity = SwedenCountyData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "COUNTY_REGIONS_SWEDEN_COUNTY_0") public List getCountyRegions() { return this.countyRegions; }protected final UserAccount getUserAccountFromSecurityContext() { final SecurityContext context = SecurityContextHolder.getContext(); if (context != null) { final Authentication authentication = context.getAuthentication(); if (authentication != null) { return userDAO.findFirstByProperty(UserAccount_.userId, authentication.getPrincipal().toString()); } } return null; }@OneToMany(targetEntity = DocumentActivityData.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "DOCUMENT_ACTIVITIES_DOCUMENT_0") public List getDocumentActivities() { return this.documentActivities; }private static Class getTypeOfProperty(final PropertyDescriptor[] propertyDescriptors, final String property) { for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getName().equalsIgnoreCase(property)) { return propertyDescriptor.getPropertyType(); } } return null; }private static Converter getConverterForType(final Class typeOfProperty) { Converter converter; if (Date.class.equals(typeOfProperty)) { converter = new StringToDateConverter(); } else if (Integer.class.equals(typeOfProperty) || "int".equalsIgnoreCase(typeOfProperty.getName())) { converter = new StringToIntegerConverter("Input value should be an integer"); } else if (Long.class.equals(typeOfProperty) || "long".equalsIgnoreCase(typeOfProperty.getName())) { converter = new StringToLongConverter("Input value should be an long"); } else if (BigInteger.class.equals(typeOfProperty)) { converter = new StringToBigIntegerConverter("Input value should be an biginteger"); } else if (BigDecimal.class.equals(typeOfProperty)) { converter = new StringToBigDecimalConverter("Input value should be an bigdecimal"); } else if (Boolean.class.equals(typeOfProperty) || "boolean".equalsIgnoreCase(typeOfProperty.getName())) { converter = new StringToBooleanConverter("Input value should be an boolean"); } else if (typeOfProperty.isEnum()) { converter = new StringToEnumConverter(); } else { converter = null; } return converter; }G��~���85���WQs�6~ϯ���_�@�� I:��4�60Mz}�da-�z�r%9�i��]�11Ι޴s���Ziw�o���}�& �7�0��K�}��sPO�>0%Xd`�9�O6v 7L��\��p��cl��z ���Ś�0EݵI. ��A�����Č�� �= "�ذڎP2��Tx�0E�E�6���?�l�~2���Y���w���2� �����j�;ba4m���~���ڤhGA;�#��Q��nzro4���y8�~@k-2 �M���`ʄ" 8��))��Ƽ)4��2���"L��=�F���Y���S��٣����m���t$��/##�?���:����fA��sEayAi�@�BJ�ą����E5TZ3�x�@ 0� �z���i�i / �T�������b$�x��GG�i��� ��`��G�6�������)���Ub��?~p���s�����5����1�u��~�j�9����`<ꝝ]\���1��4�ԅn��N�^�鴛����X�%��X�j3�5�\����[���~ �r�K4�Q�O�Q�y����K3udqLʚ�g��h;e�c�qv�2kU���ǟ���3 �eތ�cE?[��s"Z��v ގjM~s�vlS�yOK����K.�;q!��\D�,�@�AmBC�C�D>HL�L�M�OvP?Z�\_�bbd.e�iZj7lJo�oWp�pr8w�w�x}yXz0{|E}�}|~9#���%������-�J�"���J�ĚA���s�^���ҭ8���+��޶ķ׸ �$�������T���p�B�R����p��:�n����b�E�j�<�+�k� �~���\�kdw �U������� !/"#r'�0�1O3H7;@�BLE H:K)M�P�TY�Z�[]�]_^_�` bVdve�f�hdjuk���������s�������������u���N\ ���s!�#]$�$�)q*�+�,�-�2.5}7�9�<�@�A?K?R�RTU�V�X?[<\_|`b�ckbm constraints = new LinkedList<>(constraintFormulas); BoundSet boundSet = BoundSet.empty(); while (constraints.size() > 0) { ConstraintFormula constraintFormula = constraints.remove(0); ConstraintFormula.ReductionResult reductionResult = constraintFormula.reduce(boundSet); constraints.addAll(reductionResult.getConstraintFormulas()); boundSet.incorporate(reductionResult.getBoundSet(), typeSolver); } return boundSet; }private static void setBlockSpan(SpannableStringBuilder builder, Object what) { int length = Math.max(0, builder.length() - 1); builder.setSpan(what, 0, length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); }public void moveChildView(View pChildView, float pScale_Left, float pScale_Top, float pScale_Width, float pScale_Height) { ScalableLayout.LayoutParams lSLLP = getChildLayoutParams(pChildView); lSLLP.mScale_Left = pScale_Left; lSLLP.mScale_Top = pScale_Top; lSLLP.mScale_Width = pScale_Width; lSLLP.mScale_Height = pScale_Height; postInvalidate(); }public void moveChildView(View pChildView, float pScale_Left, float pScale_Top) { ScalableLayout.LayoutParams lSLLP = getChildLayoutParams(pChildView); lSLLP.mScale_Left = pScale_Left; lSLLP.mScale_Top = pScale_Top; postInvalidate(); }public static Complexd fromAngleRad(double angle) { return new Complexd(TrigMath.cos(angle), TrigMath.sin(angle)); }public static Complexd from(double x, double y) { return x == 0 && y == 0 ? ZERO : new Complexd(x, y); }public Quaterniond toQuaternion(double x, double y, double z) { return Quaterniond.fromAngleRadAxis(getAngleRad(), x, y, z); }public Vector2d rotate(double x, double y) { final double length = length(); if (Math.abs(length) < GenericMath.DBL_EPSILON) { throw new ArithmeticException("Cannot rotate by the zero complex"); } final double nx = this.x / length; final double ny = this.y / length; return new Vector2d(x * nx - y * ny, y * nx + x * ny); }public Complexd div(double x, double y) { final double d = x * x + y * y; return new Complexd( (this.x * x + this.y * y) / d, (this.y * x - this.x * y) / d); }public Complexd mul(double x, double y) { return new Complexd( this.x * x - this.y * y, this.x * y + this.y * x); }public static Quaternionf fromAngleRadAxis(double angle, double x, double y, double z) { return fromAngleRadAxis((float) angle, (float) x, (float) y, (float) z); }public static Quaternionf fromAngleRadAxis(float angle, Vector3f axis) { return fromAngleRadAxis(angle, axis.getX(), axis.getY(), axis.getZ()); }public static Quaternionf fromAxesAnglesRad(float pitch, float yaw, float roll) { return Quaternionf.fromAngleRadAxis(yaw, Vector3f.UNIT_Y). mul(Quaternionf.fromAngleRadAxis(pitch, Vector3f.UNIT_X)). mul(Quaternionf.fromAngleRadAxis(roll, Vector3f.UNIT_Z)); }public static Quaternionf fromAxesAnglesDeg(float pitch, float yaw, float roll) { return Quaternionf.fromAngleDegAxis(yaw, Vector3f.UNIT_Y). mul(Quaternionf.fromAngleDegAxis(pitch, Vector3f.UNIT_X)). mul(Quaternionf.fromAngleDegAxis(roll, Vector3f.UNIT_Z)); }public static Quaternionf from(float x, float y, float z, float w) { return x == 0 && y == 0 && z == 0 && w == 0 ? ZERO : new Quaternionf(x, y, z, w); }public static Quaternionf fromImaginary(float x, float y, float z) { return x == 0 && y == 0 && z == 0 ? ZERO : new Quaternionf(x, y, z, 0); }public Vector3f getAxesAnglesRad() { final double roll; final double pitch; double yaw; final double test = w * x - y * z; if (Math.abs(test) < 0.4999) { roll = TrigMath.atan2(2 * (w * z + x * y), 1 - 2 * (x * x + z * z)); pitch = TrigMath.asin(2 * test); yaw = TrigMath.atan2(2 * (w * y + z * x), 1 - 2 * (x * x + y * y)); } else { final int sign = (test < 0) ? -1 : 1; roll = 0; pitch = sign * Math.PI / 2; yaw = -sign * 2 * TrigMath.atan2(z, w); } return new Vector3f(pitch, yaw, roll); }public Vector3f getAxis() { final float q = (float) Math.sqrt(1 - w * w); return new Vector3f(x / q, y / q, z / q); }@Override public Quaternionf div(float a) { return new Quaternionf(x / a, y / a, z / a, w / a); }@Override public Quaternionf mul(float a) { return new Quaternionf(x * a, y * a, z * a, w * a); }public Quaternionf add(float x, float y, float z, float w) { return new Quaternionf(this.x + x, this.y + y, this.z + z, this.w + w); }public static int hash(double value) { assert !Double.isNaN(value) : "Values of NaN are not supported."; long bits = Double.doubleToLongBits(value); return (int) (bits ^ (bits >>> 32)); //return (int) Double.doubleToLongBits(value*663608941.737); // This avoids excessive hashCollisions in the case values are of the form (1.0, 2.0, 3.0, ...) }@Override public int getMaxAxis() { long value = x; int axis = 0; if (y > value) { value = y; axis = 1; } if (z > value) { value = z; axis = 2; } if (w > value) { axis = 3; } return axis; }public static Complexf fromAngleRad(float angle) { return new Complexf(TrigMath.cos(angle), TrigMath.sin(angle)); }public static Complexf from(float x, float y) { return x == 0 && y == 0 ? ZERO : new Complexf(x, y); }public Quaternionf toQuaternion(float x, float y, float z) { return Quaternionf.fromAngleRadAxis(getAngleRad(), x, y, z); }@Override public Complexf normalize() { final float length = length(); if (Math.abs(length) < GenericMath.FLT_EPSILON) { throw new ArithmeticException("Cannot normalize the zero complex"); } return new Complexf(x / length, y / length); }public Vector2f rotate(float x, float y) { final float length = length(); if (Math.abs(length) < GenericMath.FLT_EPSILON) { throw new ArithmeticException("Cannot rotate by the zero complex"); } final float nx = this.x / length; final float ny = this.y / length; return new Vector2f(x * nx - y * ny, y * nx + x * ny); }public Complexf div(float x, float y) { final float d = x * x + y * y; return new Complexf( (this.x * x + this.y * y) / d, (this.y * x - this.x * y) / d); }public Complexf mul(float x, float y) { return new Complexf( this.x * x - this.y * y, this.x * y + this.y * x); }@Override public int getMinAxis() { int value = x; int axis = 0; if (y < value) { value = y; axis = 1; } if (z < value) { value = z; axis = 2; } if (w < value) { axis = 3; } return axis; }public static Quaterniond fromAngleDegAxis(float angle, float x, float y, float z) { return fromAngleRadAxis(Math.toRadians(angle), x, y, z); }public static Quaterniond fromAngleRadAxis(double angle, Vector3d axis) { return fromAngleRadAxis(angle, axis.getX(), axis.getY(), axis.getZ()); }public static Quaterniond fromAxesAnglesRad(double pitch, double yaw, double roll) { return Quaterniond.fromAngleRadAxis(yaw, Vector3d.UNIT_Y). mul(Quaterniond.fromAngleRadAxis(pitch, Vector3d.UNIT_X)). mul(Quaterniond.fromAngleRadAxis(roll, Vector3d.UNIT_Z)); }public static Quaterniond fromAxesAnglesDeg(double pitch, double yaw, double roll) { return Quaterniond.fromAngleDegAxis(yaw, Vector3d.UNIT_Y). mul(Quaterniond.fromAngleDegAxis(pitch, Vector3d.UNIT_X)). mul(Quaterniond.fromAngleDegAxis(roll, Vector3d.UNIT_Z)); }public static Quaterniond from(double x, double y, double z, double w) { return x == 0 && y == 0 && z == 0 && w == 0 ? ZERO : new Quaterniond(x, y, z, w); }public static Quaterniond fromImaginary(double x, double y, double z) { return x == 0 && y == 0 && z == 0 ? ZERO : new Quaterniond(x, y, z, 0); }@Override public Quaterniond normalize() { final double length = length(); if (Math.abs(length) < GenericMath.DBL_EPSILON) { throw new ArithmeticException("Cannot normalize the zero quaternion"); } return new Quaterniond(x / length, y / length, z / length, w / length); }@Override public double lengthSquared() { return x * x + y * y + z * z + w * w; }public Vector3d rotate(double x, double y, double z) { final double length = length(); if (Math.abs(length) < GenericMath.DBL_EPSILON) { throw new ArithmeticException("Cannot rotate by the zero quaternion"); } final double nx = this.x / length; final double ny = this.y / length; final double nz = this.z / length; final double nw = this.w / length; final double px = nw * x + ny * z - nz * y; final double py = nw * y + nz * x - nx * z; final double pz = nw * z + nx * y - ny * x; final double pw = -nx * x - ny * y - nz * z; return new Vector3d( pw * -nx + px * nw - py * nz + pz * ny, pw * -ny + py * nw - pz * nx + px * nz, pw * -nz + pz * nw - px * ny + py * nx); }@Override public Quaterniond div(double a) { return new Quaterniond(x / a, y / a, z / a, w / a); }@Override public Quaterniond mul(double a) { return new Quaterniond(x * a, y * a, z * a, w * a); }public static int multiplyToShift(int a) { if (a < 1) { throw new IllegalArgumentException("Multiplicand must be at least 1"); } int shift = 31 - Integer.numberOfLeadingZeros(a); if ((1 << shift) != a) { throw new IllegalArgumentException("Multiplicand must be a power of 2"); } return shift; }public static double mod(double a, double div) { final double remainder = a % div; return remainder < 0 ? remainder + div : remainder; }public static int mean(int... values) { int sum = 0; for (int v : values) { sum += v; } return sum / values.length; }public static Boolean castBoolean(Object o) { if (o == null) { return null; } if (o instanceof Boolean) { return (Boolean) o; } else if (o instanceof String) { try { return Boolean.parseBoolean((String) o); } catch (IllegalArgumentException e) { return null; } } return null; }public static Long castLong(Object o) { if (o == null) { return null; } if (o instanceof Number) { return ((Number) o).longValue(); } try { return Long.valueOf(o.toString()); } catch (NumberFormatException e) { return null; } }public static Double castDouble(Object o) { if (o == null) { return null; } if (o instanceof Number) { return ((Number) o).doubleValue(); } try { return Double.valueOf(o.toString()); } catch (NumberFormatException e) { return null; } }public static Integer castInt(Object o) { if (o == null) { return null; } if (o instanceof Number) { return ((Number) o).intValue(); } try { return Integer.valueOf(o.toString()); } catch (NumberFormatException e) { return null; } }public static Short castShort(Object o) { if (o == null) { return null; } if (o instanceof Number) { return ((Number) o).shortValue(); } try { return Short.valueOf(o.toString()); } catch (NumberFormatException e) { return null; } }public static Byte castByte(Object o) { if (o == null) { return null; } if (o instanceof Number) { return ((Number) o).byteValue(); } try { return Byte.valueOf(o.toString()); } catch (NumberFormatException e) { return null; } }public static Float castFloat(Object o) { if (o == null) { return null; } if (o instanceof Number) { return ((Number) o).floatValue(); } try { return Float.valueOf(o.toString()); } catch (NumberFormatException e) { return null; } }public static double inverseSqrt(double a) { final double halfA = 0.5d * a; a = Double.longBitsToDouble(0x5FE6EB50C7B537AAl - (Double.doubleToRawLongBits(a) >> 1)); return a * (1.5d - halfA * a * a); }public static double clamp(double value, double low, double high) { if (value < low) { return low; } if (value > high) { return high; } return value; }public static Color blend(Color a, Color b) { return lerp(a, b, a.getAlpha() / 255f); }public static double triLerp(double x, double y, double z, double q000, double q001, double q010, double q011, double q100, double q101, double q110, double q111, double x1, double x2, double y1, double y2, double z1, double z2) { double q00 = lerp(x, x1, x2, q000, q100); double q01 = lerp(x, x1, x2, q010, q110); double q10 = lerp(x, x1, x2, q001, q101); double q11 = lerp(x, x1, x2, q011, q111); double q0 = lerp(y, y1, y2, q00, q10); double q1 = lerp(y, y1, y2, q01, q11); return lerp(z, z1, z2, q0, q1); }public static double biLerp(double x, double y, double q00, double q01, double q10, double q11, double x1, double x2, double y1, double y2) { double q0 = lerp(x, x1, x2, q00, q10); double q1 = lerp(x, x1, x2, q01, q11); return lerp(y, y1, y2, q0, q1); }public static Quaternionf slerp(Quaternionf a, Quaternionf b, float percent) { final float inverted; float cosineTheta = a.dot(b); if (cosineTheta < 0) { cosineTheta = -cosineTheta; inverted = -1; } else { inverted = 1; } if (1 - cosineTheta < GenericMath.FLT_EPSILON) { return a.mul(1 - percent).add(b.mul(percent * inverted)); } final float theta = (float) TrigMath.acos(cosineTheta); final float sineTheta = TrigMath.sin(theta); final float coefficient1 = TrigMath.sin((1 - percent) * theta) / sineTheta; final float coefficient2 = TrigMath.sin(percent * theta) / sineTheta * inverted; return a.mul(coefficient1).add(b.mul(coefficient2)); }public static double lerp(double x, double x1, double x2, double q0, double q1) { return ((x2 - x) / (x2 - x1)) * q0 + ((x - x1) / (x2 - x1)) * q1; }public static double round(double input, int decimals) { final double p = Math.pow(10, decimals); return Math.round(input * p) / p; }public static double wrapAngleRad(double angle) { angle %= TrigMath.TWO_PI; if (angle <= -TrigMath.PI) { return angle + TrigMath.TWO_PI; } if (angle > TrigMath.PI) { return angle - TrigMath.TWO_PI; } return angle; }public static SafeHtmlProto toProto(SafeHtml safeHtml) { return SafeHtmlProto.newBuilder().setPrivateDoNotAccessOrElseSafeHtmlWrappedValue( safeHtml.getSafeHtmlString()).build(); }public static TrustedResourceUrlProto toProto(TrustedResourceUrl url) { return TrustedResourceUrlProto.newBuilder() .setPrivateDoNotAccessOrElseTrustedResourceUrlWrappedValue( url.getTrustedResourceUrlString()) .build(); }public static SafeStyleSheetProto toProto(SafeStyleSheet style) { return SafeStyleSheetProto.newBuilder() .setPrivateDoNotAccessOrElseSafeStyleSheetWrappedValue( style.getSafeStyleSheetString()) .build(); }public static SafeScriptProto toProto(SafeScript script) { return SafeScriptProto.newBuilder() .setPrivateDoNotAccessOrElseSafeScriptWrappedValue(script.getSafeScriptString()).build(); }public static SafeStyleProto toProto(SafeStyle style) { return SafeStyleProto.newBuilder() .setPrivateDoNotAccessOrElseSafeStyleWrappedValue(style.getSafeStyleString()).build(); }public static SafeUrlProto toProto(SafeUrl url) { return SafeUrlProto.newBuilder() .setPrivateDoNotAccessOrElseSafeUrlWrappedValue(url.getSafeUrlString()) .build(); }@Override public void onListScroll(View view, float deltaY) { int speed; if (view.getId() == mListViewLeft.getId() && !isLeftListEnabled) { speed = getSpeed(false, deltaY); mListViewRight.smoothScrollBy(speed, 0); } else if (view.getId() == mListViewRight.getId() && !isRightListEnabled) { speed = getSpeed(true, deltaY); mListViewLeft.smoothScrollBy(speed, 0); } }private void toogleListView(View v) { if (mLastViewTouchId != v.getId()) { if (mLastViewTouchId == mListViewLeft.getId()) { isLeftListEnabled = true; isRightListEnabled = false; } else { isLeftListEnabled = false; isRightListEnabled = true; } } }public static void addCustomToLaunch(Properties ltiProps, Properties custom) { Enumeration e = custom.propertyNames(); while (e.hasMoreElements()) { String keyStr = (String) e.nextElement(); String value = custom.getProperty(keyStr); setProperty(ltiProps,"custom_"+keyStr,value); } }public static String validateCapabilities(ToolConsumer consumer, JSONObject providerProfile) { List theTools = new ArrayList (); Properties info = new Properties(); // Mostly to catch casting errors from bad JSON try { String retval = parseToolProfile(theTools, info, providerProfile); if ( retval != null ) return retval; if ( theTools.size() < 1 ) return "No tools found in profile"; // Check all the capabilities requested by all the tools comparing against consumer List capabilities = consumer.getCapability_offered(); for ( Properties theTool : theTools ) { String ec = (String) theTool.get("enabled_capability"); JSONArray enabled_capability = (JSONArray) JSONValue.parse(ec); if ( enabled_capability != null ) for (Object o : enabled_capability) { ec = (String) o; if ( capabilities.contains(ec) ) continue; return "Capability not permitted="+ec; } } return null; } catch (Exception e ) { return "Exception:"+ e.getLocalizedMessage(); } }public static String validateServices(ToolConsumer consumer, JSONObject providerProfile) { // Mostly to catch casting errors from bad JSON try { JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT); if ( security_contract == null ) { return "JSON missing security_contract"; } JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE); List services_offered = consumer.getService_offered(); if ( tool_services != null ) for (Object o : tool_services) { JSONObject tool_service = (JSONObject) o; String json_service = (String) tool_service.get(LTI2Constants.SERVICE); boolean found = false; for (ServiceOffered service : services_offered ) { String service_endpoint = service.getEndpoint(); if ( service_endpoint.equals(json_service) ) { found = true; break; } } if ( ! found ) return "Service not allowed: "+json_service; } return null; } catch (Exception e) { return "Exception:"+ e.getLocalizedMessage(); } }protected ToolConsumer buildToolConsumerProfile(HttpServletRequest request, Map deploy, String profile_id) { // Load the configuration data LTI2Config cnf = new org.imsglobal.lti2.LTI2ConfigSample(); ToolConsumer consumer = new ToolConsumer(profile_id, "LTI-2p0", getServiceURL(request), cnf); // Normally we would check permissions before we offer capabilities List capabilities = consumer.getCapability_offered(); LTI2Util.allowEmail(capabilities); LTI2Util.allowName(capabilities); LTI2Util.allowSettings(capabilities); LTI2Util.allowResult(capabilities); // Normally we would check permissions before we offer services List services = consumer.getService_offered(); services.add(StandardServices.LTI2Registration(getServiceURL(request) + SVC_tc_registration + "/" + profile_id)); services.add(StandardServices.LTI2ResultItem(getServiceURL(request) + SVC_Result + "/{" + BasicLTIConstants.LIS_RESULT_SOURCEDID + "}")); services.add(StandardServices.LTI2LtiLinkSettings(getServiceURL(request) + SVC_Settings + "/" + LTI2Util.SCOPE_LtiLink + "/{" + BasicLTIConstants.RESOURCE_LINK_ID + "}")); services.add(StandardServices.LTI2ToolProxySettings(getServiceURL(request) + SVC_Settings + "/" + LTI2Util.SCOPE_ToolProxyBinding + "/{" + BasicLTIConstants.CONTEXT_ID + "}")); services.add(StandardServices.LTI2ToolProxySettings(getServiceURL(request) + SVC_Settings + "/" + LTI2Util.SCOPE_ToolProxy + "/{" + LTI2Constants.TOOL_PROXY_GUID + "}")); return consumer; }@SuppressWarnings("unused") protected void doLaunch(HttpServletRequest request, HttpServletResponse response) { String profile = PERSIST.get("profile"); response.setContentType("text/html"); String output = null; if ( profile == null ) { output = "Missing profile"; } else { JSONObject providerProfile = (JSONObject) JSONValue.parse(profile); List profileTools = new ArrayList (); Properties info = new Properties(); String retval = LTI2Util.parseToolProfile(profileTools, info, providerProfile); String launch = null; String parameter = null; for ( Properties profileTool : profileTools ) { launch = (String) profileTool.get("launch"); parameter = (String) profileTool.get("parameter"); } JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT); String shared_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET); System.out.println("launch="+launch); System.out.println("shared_secret="+shared_secret); Properties ltiProps = LTI2SampleData.getLaunch(); ltiProps.setProperty(BasicLTIConstants.LTI_VERSION,BasicLTIConstants.LTI_VERSION_2); Properties lti2subst = LTI2SampleData.getSubstitution(); String settings_url = getServiceURL(request) + SVC_Settings + "/"; lti2subst.setProperty("LtiLink.custom.url", settings_url + LTI2Util.SCOPE_LtiLink + "/" + ltiProps.getProperty(BasicLTIConstants.RESOURCE_LINK_ID)); lti2subst.setProperty("ToolProxyBinding.custom.url", settings_url + LTI2Util.SCOPE_ToolProxyBinding + "/" + ltiProps.getProperty(BasicLTIConstants.CONTEXT_ID)); lti2subst.setProperty("ToolProxy.custom.url", settings_url + LTI2Util.SCOPE_ToolProxy + "/" + TEST_KEY); lti2subst.setProperty("Result.url", getServiceURL(request) + SVC_Result + "/" + ltiProps.getProperty(BasicLTIConstants.RESOURCE_LINK_ID)); // Do the substitutions Properties custom = new Properties(); LTI2Util.mergeLTI2Parameters(custom, parameter); LTI2Util.substituteCustom(custom, lti2subst); // Place the custom values into the launch LTI2Util.addCustomToLaunch(ltiProps, custom); ltiProps = BasicLTIUtil.signProperties(ltiProps, launch, "POST", TEST_KEY, shared_secret, null, null, null); boolean dodebug = true; output = BasicLTIUtil.postLaunchHTML(ltiProps, launch, dodebug); } try { PrintWriter out = response.getWriter(); out.println(output); } catch (Exception e) { e.printStackTrace(); } }public void validateRequest(String oauth_consumer_key, String oauth_secret, HttpServletRequest request) { validateRequest(oauth_consumer_key, oauth_secret, request, null) ; }@Override public LtiVerificationResult verifyParameters(Map parameters, String url, String method, String secret) throws LtiVerificationException { OAuthMessage oam = new OAuthMessage(method, url, parameters.entrySet()); OAuthConsumer cons = new OAuthConsumer(null, parameters.get(OAUTH_KEY_PARAMETER), secret, null); OAuthValidator oav = new SimpleOAuthValidator(); OAuthAccessor acc = new OAuthAccessor(cons); try { oav.validateMessage(oam, acc); } catch (Exception e) { return new LtiVerificationResult(false, LtiError.BAD_REQUEST, "Failed to validate: " + e.getLocalizedMessage() + ", Parameters: " + Arrays.toString(parameters.entrySet().toArray())); } return new LtiVerificationResult(true, new LtiLaunch(parameters)); }@Override public LtiVerificationResult verify(HttpServletRequest request, String secret) throws LtiVerificationException { OAuthMessage oam = OAuthServlet.getMessage(request, OAuthServlet.getRequestURL(request)); String oauth_consumer_key = null; try { oauth_consumer_key = oam.getConsumerKey(); } catch (Exception e) { return new LtiVerificationResult(false, LtiError.BAD_REQUEST, "Unable to find consumer key in message"); } OAuthValidator oav = new SimpleOAuthValidator(); OAuthConsumer cons = new OAuthConsumer(null, oauth_consumer_key, secret, null); OAuthAccessor acc = new OAuthAccessor(cons); try { oav.validateMessage(oam, acc); } catch (Exception e) { return new LtiVerificationResult(false, LtiError.BAD_REQUEST, "Failed to validate: " + e.getLocalizedMessage()); } return new LtiVerificationResult(true, new LtiLaunch(request)); }static public String getRealPath(String servletUrl, String extUrl) { Pattern pat = Pattern.compile("^https??://[^/]*"); // Deal with potential bad extUrl formats Matcher m = pat.matcher(extUrl); if (m.find()) { extUrl = m.group(0); } String retval = pat.matcher(servletUrl).replaceFirst(extUrl); return retval; }public static String htmlspecialchars(String input) { if (input == null) { return null; } String retval = input.replace("&", "&"); retval = retval.replace("\"", """); retval = retval.replace("<", "<"); retval = retval.replace(">", ">"); retval = retval.replace(">", ">"); retval = retval.replace("=", "="); return retval; }public static void setProperty(Properties props, String key, String value) { if (value == null) { return; } if (value.trim().length() < 1) { return; } props.setProperty(key, value); }public static String prepareForExport(String descriptor) { Map tm = null; try { tm = XMLMap.getFullMap(descriptor.trim()); } catch (Exception e) { M_log.warning("BasicLTIUtil exception parsing BasicLTI descriptor" + e.getMessage()); return null; } if (tm == null) { M_log.warning("Unable to parse XML in prepareForExport"); return null; } XMLMap.removeSubMap(tm, "/basic_lti_link/x-secure"); String retval = XMLMap.getXML(tm, true); return retval; }public static boolean checkProperties( Map postProp, String url, String method, String oauth_consumer_key, String oauth_consumer_secret) { OAuthMessage oam = new OAuthMessage(method, url, postProp.entrySet()); OAuthConsumer cons = new OAuthConsumer("about:blank", oauth_consumer_key, oauth_consumer_secret, null); OAuthValidator oav = new SimpleOAuthValidator(); OAuthAccessor acc = new OAuthAccessor(cons); String base_string = null; try { base_string = OAuthSignatureMethod.getBaseString(oam); } catch (Exception e) { M_log.warning(e.getLocalizedMessage()); base_string = null; return false; } try { oav.validateMessage(oam, acc); } catch (Exception e) { M_log.warning("Provider failed to validate message"); M_log.warning(e.getLocalizedMessage()); if (base_string != null) { M_log.warning(base_string); } return false; } return true; }public static boolean checkProperties(Properties postProp, String url, String method, String oauth_consumer_key, String oauth_consumer_secret) { return checkProperties(convertToMap(postProp), url, method, oauth_consumer_key, oauth_consumer_secret); }public static void dPrint(String str) { if (verbosePrint) { System.out.println(str); } M_log.fine(str); }public int getHeight() { mParentView.measure(View.MeasureSpec.makeMeasureSpec(mParentView.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(mParentView.getHeight(), View.MeasureSpec.AT_MOST)); return mParentView.getMeasuredHeight(); }public void writeToParcel(Parcel out, int flags) { out.writeString(mMessage); out.writeString(mActionMessage); out.writeInt(mActionIcon); out.writeParcelable(mToken, 0); out.writeInt((int) mDuration); out.writeParcelable(mBtnTextColor, 0); out.writeParcelable(mBackgroundColor, 0); out.writeInt(mHeight); out.writeValue(mTypeface); }public void putPersistableBundle(String key, PersistableBundle value) { PersistableBundleCompat.putPersistableBundle(bundle, key, value.bundle); }public String getString(String key, String defaultValue) { return PersistableBundleCompat.getString(bundle, key, defaultValue); }public void putStringArray(String key, String[] value) { PersistableBundleCompat.putStringArray(bundle, key, value); }public void putString(String key, String value) { PersistableBundleCompat.putString(bundle, key, value); }private static boolean canStopTrackingJob(JobStatus job) { return (!job.hasTimingDelayConstraint() || job.timeDelayConstraintSatisfied.get()) && (!job.hasDeadlineConstraint() || job.deadlineConstraintSatisfied.get()); }public void onReceivedStopJob() { mShowStopView.setBackgroundColor(stopJobColor); Message m = Message.obtain(mHandler, MSG_UNCOLOUR_STOP); mHandler.sendMessageDelayed(m, 2000L); // uncolour in 1 second. mParamsTextView.setText(""); }public void onReceivedStartJob(JobParameters params) { mShowStartView.setBackgroundColor(startJobColor); Message m = Message.obtain(mHandler, MSG_UNCOLOUR_START); mHandler.sendMessageDelayed(m, 1000L); // uncolour in 1 second. mParamsTextView.setText("Executing: " + params.getJobId() + " " + params.getExtras()); }@Override public void clear() { if (mSize != 0) { freeArrays(mHashes, mArray, mSize); mHashes = EmptyArray.INT; mArray = EmptyArray.OBJECT; mSize = 0; } }private JobStatus rescheduleFailedJob(JobStatus job) { if (job.hasIdleConstraint()) { // Don't need to modify time on idle job, it will run whenever the next idle period is. return job; } final long elapsedNowMillis = SystemClock.elapsedRealtime(); final JobInfo jobInfo = job.getJob(); final long initialBackoffMillis = jobInfo.getInitialBackoffMillis(); final int backoffAttemps = job.getNumFailures() + 1; long delayMillis; switch (job.getJob().getBackoffPolicy()) { case JobInfo.BACKOFF_POLICY_LINEAR: delayMillis = initialBackoffMillis * backoffAttemps; break; default: case JobInfo.BACKOFF_POLICY_EXPONENTIAL: delayMillis = (long) Math.scalb(initialBackoffMillis, backoffAttemps - 1); break; } delayMillis = Math.min(delayMillis, JobInfo.MAX_BACKOFF_DELAY_MILLIS); return new JobStatus(job, elapsedNowMillis + delayMillis, JobStatus.NO_LATEST_RUNTIME, backoffAttemps); }public boolean remove(JobStatus jobStatus) { boolean removed = mJobSet.remove(jobStatus); if (!removed) { return false; } if (!jobStatus.isPersisted()) { unmarkForBootSession(jobStatus); } maybeWriteStatusToDiskAsync(); return removed; }public boolean containsJobId(int jobId) { for (int i = mJobSet.size() - 1; i >= 0; i--) { JobStatus ts = mJobSet.valueAt(i); if (ts.matches(jobId)) { return true; } } return false; }public boolean add(JobStatus jobStatus) { boolean replaced = mJobSet.remove(jobStatus); mJobSet.add(jobStatus); if (!jobStatus.isPersisted()) { markForBootSession(jobStatus); } maybeWriteStatusToDiskAsync(); return replaced; }void reportNewIdleState(Context context, boolean isIdle) { JobStore jobStore = JobStore.initAndGet(context); synchronized (jobStore) { ArraySet jobs = jobStore.getJobs(); for (int i = 0; i < jobs.size(); i++) { JobStatus ts = jobs.valueAt(i); ts.idleConstraintSatisfied.set(isIdle); } } startWakefulService(context, JobServiceCompat.maybeRunJobs(context)); }public static void enableReceiver(Context context) { IntentFilter filter = getFilter(); sReceiver = new IdleReceiver(); context.getApplicationContext().registerReceiver(sReceiver, filter); }private static void setAnywayTimer(Context context) { AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, IdleReceiver.class); intent.setAction(ACTION_TRIGGER_IDLE); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0); final long nowElapsed = SystemClock.elapsedRealtime(); final long when = nowElapsed + INACTIVITY_ANYWAY_THRESHOLD; compatSetWindow(am, AlarmManager.ELAPSED_REALTIME_WAKEUP, when, IDLE_WINDOW_SLOP, pendingIntent); }public Map createPatternObjects(Map stopById, SQLErrorStorage errorStorage) { // Make pattern ID one-based to avoid any JS type confusion between an ID of zero vs. null value. int nextPatternId = 1; // Create an in-memory list of Patterns because we will later rename them before inserting them into storage. Map patterns = new HashMap<>(); // TODO assign patterns sequential small integer IDs (may include route) for (TripPatternKey key : tripsForPattern.keySet()) { Collection trips = tripsForPattern.get(key); Pattern pattern = new Pattern(key.stops, trips, null); // Overwrite long UUID with sequential integer pattern ID pattern.pattern_id = Integer.toString(nextPatternId++); // FIXME: Should associated shapes be a single entry? pattern.associatedShapes = new HashSet<>(); trips.stream().forEach(trip -> pattern.associatedShapes.add(trip.shape_id)); if (pattern.associatedShapes.size() > 1 && errorStorage != null) { // Store an error if there is more than one shape per pattern. Note: error storage is null if called via // MapDB implementation. // TODO: Should shape ID be added to trip pattern key? errorStorage.storeError(NewGTFSError.forEntity( pattern, NewGTFSErrorType.MULTIPLE_SHAPES_FOR_PATTERN) .setBadValue(pattern.associatedShapes.toString())); } patterns.put(key, pattern); } // Name patterns before storing in SQL database. renamePatterns(patterns.values(), stopById); LOG.info("Total patterns: {}", tripsForPattern.keySet().size()); return patterns; }public ZoneId getAgencyTimeZoneForStop (String stop_id) { StopTime stopTime = getStopTimesForStop(stop_id).iterator().next(); Trip trip = this.trips.get(stopTime.trip_id); Route route = this.routes.get(trip.route_id); Agency agency = route.agency_id != null ? this.agency.get(route.agency_id) : this.agency.get(0); return ZoneId.of(agency.agency_timezone); }public List getServicesForDate (LocalDate date) { String dateString = date.format(dateFormatter); SortedSet> index = this.servicesPerDate .subSet(new Tuple2<>(dateString, null), new Tuple2(dateString, Fun.HI)); return index.stream() .map(tuple -> this.services.get(tuple.b)) .collect(Collectors.toList()); }public List getStopTimesForStop (String stop_id) { SortedSet> index = this.stopStopTimeSet .subSet(new Tuple2<>(stop_id, null), new Tuple2(stop_id, Fun.HI)); return index.stream() .map(tuple -> this.stop_times.get(tuple.b)) .collect(Collectors.toList()); }public double getTripSpeed (String trip_id, boolean straightLine) { StopTime firstStopTime = this.stop_times.ceilingEntry(Fun.t2(trip_id, null)).getValue(); StopTime lastStopTime = this.stop_times.floorEntry(Fun.t2(trip_id, Fun.HI)).getValue(); // ensure that stopTime returned matches trip id (i.e., that the trip has stoptimes) if (!firstStopTime.trip_id.equals(trip_id) || !lastStopTime.trip_id.equals(trip_id)) { return Double.NaN; } double distance = getTripDistance(trip_id, straightLine); // trip time (in seconds) int time = lastStopTime.arrival_time - firstStopTime.departure_time; return distance / time; // meters per second }public double getTripDistance (String trip_id, boolean straightLine) { return straightLine ? GeoUtils.getDistance(this.getStraightLineForStops(trip_id)) : GeoUtils.getDistance(this.getTripGeometry(trip_id)); }public void findPatterns () { PatternFinder patternFinder = new PatternFinder(); // Iterate over trips and process each trip and its stop times. for (Trip trip : this.trips.values()) { Iterable orderedStopTimesForTrip = this.getOrderedStopTimesForTrip(trip.trip_id); patternFinder.processTrip(trip, orderedStopTimesForTrip); } Map patternObjects = patternFinder.createPatternObjects(this.stops, null); this.patterns.putAll(patternObjects.values().stream() .collect(Collectors.toMap(Pattern::getId, pattern -> pattern))); }public static GTFSFeed fromFile(String file, String feedId) { GTFSFeed feed = new GTFSFeed(); ZipFile zip; try { zip = new ZipFile(file); if (feedId == null) { feed.loadFromFile(zip); } else { feed.loadFromFile(zip, feedId); } zip.close(); return feed; } catch (Exception e) { LOG.error("Error loading GTFS: {}", e.getMessage()); throw new RuntimeException(e); } }@Override public Set keySet() { // use a linkedhashset so values come out in order Set ret = new LinkedHashSet<>(); for (Tuple2 t : wrapped.keySet()) { ret.add(t.b); } // Don't let the user modify the set as it won't do what they expect (change the map) return Collections.unmodifiableSet(ret); }public static int getFieldIndex (Field[] fields, String name) { // Linear search, assuming a small number of fields per table. for (int i = 0; i < fields.length; i++) if (fields[i].name.equals(name)) return i; return -1; }public static void ensureValidNamespace(String namespace) throws InvalidNamespaceException { Pattern pattern = Pattern.compile("[^a-zA-Z0-9_\\.]"); Matcher matcher = pattern.matcher(namespace); if (matcher.find()) { throw new InvalidNamespaceException(); } }public int getKeyFieldIndex(Field[] fields) { String keyField = getKeyFieldName(); return Field.getFieldIndex(fields, keyField); }private void normalizeAndCloneStopTimes(Statement statement, String name, String tableToClone) throws SQLException { // Create table with matching columns first and then insert all rows with a special select query that // normalizes the stop sequences before inserting. // "Create table like" can optionally include indexes, but we want to avoid creating the indexes beforehand // because this will slow down our massive insert for stop times. String createTableLikeSql = String.format("create table %s (like %s)", name, tableToClone); LOG.info(createTableLikeSql); statement.execute(createTableLikeSql); long normalizeStartTime = System.currentTimeMillis(); LOG.info("Normalizing stop sequences"); // First get the column names (to account for any non-standard fields that may be present) List columns = new ArrayList<>(); ResultSet resultSet = statement.executeQuery(String.format("select * from %s limit 1", tableToClone)); ResultSetMetaData metadata = resultSet.getMetaData(); int nColumns = metadata.getColumnCount(); for (int i = 1; i <= nColumns; i++) { columns.add(metadata.getColumnName(i)); } // Replace stop sequence column with the normalized sequence values. columns.set(columns.indexOf("stop_sequence"), "-1 + row_number() over (partition by trip_id order by stop_sequence) as stop_sequence"); String insertAllSql = String.format("insert into %s (select %s from %s)", name, String.join(", ", columns), tableToClone); LOG.info(insertAllSql); statement.execute(insertAllSql); LOG.info("Normalized stop times sequences in {} ms", System.currentTimeMillis() - normalizeStartTime); }public boolean createSqlTableFrom(Connection connection, String tableToClone) { long startTime = System.currentTimeMillis(); try { Statement statement = connection.createStatement(); // Drop target table to avoid a conflict. String dropSql = String.format("drop table if exists %s", name); LOG.info(dropSql); statement.execute(dropSql); if (tableToClone.endsWith("stop_times")) { normalizeAndCloneStopTimes(statement, name, tableToClone); } else { // Adding the unlogged keyword gives about 12 percent speedup on loading, but is non-standard. // FIXME: Which create table operation is more efficient? String createTableAsSql = String.format("create table %s as table %s", name, tableToClone); // Create table in the image of the table we're copying (indexes are not included). LOG.info(createTableAsSql); statement.execute(createTableAsSql); } applyAutoIncrementingSequence(statement); // FIXME: Is there a need to add primary key constraint here? if (usePrimaryKey) { // Add primary key to ID column for any tables that require it. String addPrimaryKeySql = String.format("ALTER TABLE %s ADD PRIMARY KEY (id)", name); LOG.info(addPrimaryKeySql); statement.execute(addPrimaryKeySql); } return true; } catch (SQLException ex) { LOG.error("Error cloning table {}: {}", name, ex.getSQLState()); LOG.error("details: ", ex); try { connection.rollback(); // It is likely that if cloning the table fails, the reason was that the table did not already exist. // Try to create the table here from scratch. // FIXME: Maybe we should check that the reason the clone failed was that the table already exists. createSqlTable(connection, true); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } finally { LOG.info("Cloned table {} as {} in {} ms", tableToClone, name, System.currentTimeMillis() - startTime); } }public String generateDeleteSql (String namespace, String fieldName) { String whereField = fieldName == null ? "id" : fieldName; return String.format("delete from %s where %s = ?", String.join(".", namespace, name), whereField); }public String generateSelectAllExistingFieldsSql(Connection connection, String namespace) throws SQLException { // select all columns from table // FIXME This is postgres-specific and needs to be made generic for non-postgres databases. PreparedStatement statement = connection.prepareStatement( "SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ?" ); statement.setString(1, namespace); statement.setString(2, name); ResultSet result = statement.executeQuery(); // get result and add fields that are defined in this table List existingFields = new ArrayList<>(); while (result.next()) { String columnName = result.getString(1); existingFields.add(getFieldForName(columnName)); } String tableName = String.join(".", namespace, name); String fieldPrefix = tableName + "."; return String.format( "select %s from %s", commaSeparatedNames(existingFields, fieldPrefix, true), tableName ); }public String generateSelectSql (String namespace, Requirement minimumRequirement) { String fieldsString; String tableName = String.join(".", namespace, name); String fieldPrefix = tableName + "."; if (minimumRequirement.equals(EDITOR)) { fieldsString = commaSeparatedNames(editorFields(), fieldPrefix, true); } else if (minimumRequirement.equals(OPTIONAL)) { fieldsString = commaSeparatedNames(specFields(), fieldPrefix, true); } else if (minimumRequirement.equals(REQUIRED)) { fieldsString = commaSeparatedNames(requiredFields(), fieldPrefix, true); } else fieldsString = "*"; return String.format("select %s from %s", fieldsString, tableName); }public String generateUpdateSql (String namespace, int id) { // Collect field names for string joining from JsonObject. String joinedFieldNames = editorFields().stream() // If updating, add suffix for use in set clause .map(field -> field.name + " = ?") .collect(Collectors.joining(", ")); String tableName = namespace == null ? name : String.join(".", namespace, name); return String.format("update %s set %s where id = %d", tableName, joinedFieldNames, id); }public static String commaSeparatedNames(List fieldsToJoin, String prefix, boolean csvOutput) { return fieldsToJoin.stream() // NOTE: This previously only prefixed fields that were foreign refs or key fields. However, this // caused an issue where shared fields were ambiguously referenced in a select query (specifically, // wheelchair_accessible in routes and trips). So this filter has been removed. .map(f -> f.getColumnExpression(prefix, csvOutput)) .collect(Collectors.joining(", ")); }public String generateInsertSql (String namespace, boolean setDefaultId) { String tableName = namespace == null ? name : String.join(".", namespace, name); String joinedFieldNames = commaSeparatedNames(editorFields()); String idValue = setDefaultId ? "DEFAULT" : "?"; return String.format( "insert into %s (id, %s) values (%s, %s)", tableName, joinedFieldNames, idValue, String.join(", ", Collections.nCopies(editorFields().size(), "?")) ); }public boolean createSqlTable (Connection connection, String namespace, boolean makeIdSerial, String[] primaryKeyFields) { // Optionally join namespace and name to create full table name if namespace is not null (i.e., table object is // a spec table). String tableName = namespace != null ? String.join(".", namespace, name) : name; String fieldDeclarations = Arrays.stream(fields) .map(Field::getSqlDeclaration) .collect(Collectors.joining(", ")); if (primaryKeyFields != null) { fieldDeclarations += String.format(", primary key (%s)", String.join(", ", primaryKeyFields)); } String dropSql = String.format("drop table if exists %s", tableName); // Adding the unlogged keyword gives about 12 percent speedup on loading, but is non-standard. String idFieldType = makeIdSerial ? "serial" : "bigint"; String createSql = String.format("create table %s (id %s not null, %s)", tableName, idFieldType, fieldDeclarations); try { Statement statement = connection.createStatement(); LOG.info(dropSql); statement.execute(dropSql); LOG.info(createSql); return statement.execute(createSql); } catch (Exception ex) { throw new StorageException(ex); } }public List specFields () { List specFields = new ArrayList<>(); for (Field f : fields) if (f.requirement == REQUIRED || f.requirement == OPTIONAL) specFields.add(f); return specFields; }public List requiredFields () { // Filter out fields not used in editor (i.e., extension fields). List requiredFields = new ArrayList<>(); for (Field f : fields) if (f.requirement == REQUIRED) requiredFields.add(f); return requiredFields; }public List editorFields() { List editorFields = new ArrayList<>(); for (Field f : fields) if (f.requirement == REQUIRED || f.requirement == OPTIONAL || f.requirement == EDITOR) { editorFields.add(f); } return editorFields; }public static void initialize (DataSource dataSource) { GTFSGraphQL.dataSource = dataSource; GRAPHQL = GraphQL.newGraphQL(GraphQLGtfsSchema.feedBasedSchema) .build(); }public boolean activeOn (LocalDate date) { // first check for exceptions CalendarDate exception = calendar_dates.get(date); if (exception != null) return exception.exception_type == 1; else if (calendar == null) return false; else { boolean outsideValidityRange = date.isAfter(calendar.end_date) || date.isBefore(calendar.start_date); if (outsideValidityRange) return false; switch (date.getDayOfWeek()) { case MONDAY: return calendar.monday == 1; case TUESDAY: return calendar.tuesday == 1; case WEDNESDAY: return calendar.wednesday == 1; case THURSDAY: return calendar.thursday == 1; case FRIDAY: return calendar.friday == 1; case SATURDAY: return calendar.saturday == 1; case SUNDAY: return calendar.sunday == 1; default: throw new IllegalArgumentException("unknown day of week constant!"); } } }public T put (Function idGenerator, File feedFile) throws Exception { return put(null, feedFile, idGenerator); }public T put (String id, File feedFile) throws Exception { return put(id, feedFile, null); }private static String getValueForId(int id, String fieldName, String namespace, Table table, Connection connection) throws SQLException { String tableName = String.join(".", namespace, table.name); String selectIdSql = String.format("select %s from %s where id = %d", fieldName, tableName, id); LOG.info(selectIdSql); Statement selectIdStatement = connection.createStatement(); ResultSet selectResults = selectIdStatement.executeQuery(selectIdSql); String value = null; while (selectResults.next()) { value = selectResults.getString(1); } return value; }private static Set getReferencingTables(Table table) { Set
referencingTables = new HashSet<>(); for (Table gtfsTable : Table.tablesInOrder) { // IMPORTANT: Skip the table for the entity we're modifying or if loop table does not have field. if (table.name.equals(gtfsTable.name)) continue; for (Field field : gtfsTable.fields) { if (field.isForeignReference() && field.referenceTable.name.equals(table.name)) { // If any of the table's fields are foreign references to the specified table, add to the return set. referencingTables.add(gtfsTable); } } } return referencingTables; }private static int getRowCount(String tableName, Connection connection) throws SQLException { String rowCountSql = String.format("SELECT COUNT(*) FROM %s", tableName); LOG.info(rowCountSql); // Create statement for counting rows selected Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(rowCountSql); if (resultSet.next()) return resultSet.getInt(1); else return 0; }private static long handleStatementExecution(PreparedStatement statement, boolean isCreating) throws SQLException { // Log the SQL for the prepared statement LOG.info(statement.toString()); int affectedRows = statement.executeUpdate(); // Determine operation-specific action for any error messages String messageAction = isCreating ? "Creating" : "Updating"; if (affectedRows == 0) { // No update occurred. // TODO: add some clarity on cause (e.g., where clause found no entity with provided ID)? throw new SQLException(messageAction + " entity failed, no rows affected."); } try (ResultSet generatedKeys = statement.getGeneratedKeys()) { if (generatedKeys.next()) { // Get the auto-generated ID from the update execution long newId = generatedKeys.getLong(1); return newId; } else { throw new SQLException(messageAction + " entity failed, no ID obtained."); } } catch (SQLException e) { e.printStackTrace(); throw e; } }@Override public int delete(Integer id, boolean autoCommit) throws SQLException { try { // Handle "cascading" delete or constraints on deleting entities that other entities depend on // (e.g., keep a calendar from being deleted if trips reference it). // FIXME: actually add "cascading"? Currently, it just deletes one level down. deleteFromReferencingTables(tablePrefix, specTable, id); // Next, delete the actual record specified by id. PreparedStatement statement = connection.prepareStatement(specTable.generateDeleteSql(tablePrefix)); statement.setInt(1, id); LOG.info(statement.toString()); // Execute query int result = statement.executeUpdate(); if (result == 0) { LOG.error("Could not delete {} entity with id: {}", specTable.name, id); throw new SQLException("Could not delete entity"); } if (autoCommit) connection.commit(); // FIXME: change return message based on result value return result; } catch (Exception e) { LOG.error("Could not delete {} entity with id: {}", specTable.name, id); e.printStackTrace(); // Rollback changes if errors encountered. connection.rollback(); throw e; } finally { // Always close connection if auto-committing. Otherwise, leave open (for potential further updates). if (autoCommit) connection.close(); } }private void insertBlankStopTimes( List tripIds, List newStops, int startingStopSequence, int stopTimesToAdd, Connection connection ) throws SQLException { if (tripIds.isEmpty()) { // There is no need to insert blank stop times if there are no trips for the pattern. return; } String insertSql = Table.STOP_TIMES.generateInsertSql(tablePrefix, true); PreparedStatement insertStatement = connection.prepareStatement(insertSql); int count = 0; int totalRowsUpdated = 0; // Create a new stop time for each sequence value (times each trip ID) that needs to be inserted. for (int i = startingStopSequence; i < stopTimesToAdd + startingStopSequence; i++) { PatternStop patternStop = newStops.get(i); StopTime stopTime = new StopTime(); stopTime.stop_id = patternStop.stop_id; stopTime.drop_off_type = patternStop.drop_off_type; stopTime.pickup_type = patternStop.pickup_type; stopTime.timepoint = patternStop.timepoint; stopTime.shape_dist_traveled = patternStop.shape_dist_traveled; stopTime.stop_sequence = i; // Update stop time with each trip ID and add to batch. for (String tripId : tripIds) { stopTime.trip_id = tripId; stopTime.setStatementParameters(insertStatement, true); insertStatement.addBatch(); if (count % INSERT_BATCH_SIZE == 0) { int[] rowsUpdated = insertStatement.executeBatch(); totalRowsUpdated += rowsUpdated.length; } } } int[] rowsUpdated = insertStatement.executeBatch(); totalRowsUpdated += rowsUpdated.length; LOG.info("{} blank stop times inserted", totalRowsUpdated); }private static void verifyInteriorStopsAreUnchanged( List originalStopIds, List newStops, int firstDifferentIndex, int lastDifferentIndex, boolean movedRight ) { //Stops mapped to list of stop IDs simply for easier viewing/comparison with original IDs while debugging with // breakpoints. List newStopIds = newStops.stream().map(s -> s.stop_id).collect(Collectors.toList()); // Determine the bounds of the region that should be identical between the two lists. int beginRegion = movedRight ? firstDifferentIndex : firstDifferentIndex + 1; int endRegion = movedRight ? lastDifferentIndex - 1 : lastDifferentIndex; for (int i = beginRegion; i <= endRegion; i++) { // Shift index when selecting stop from original list to account for displaced stop. int shiftedIndex = movedRight ? i + 1 : i - 1; String newStopId = newStopIds.get(i); String originalStopId = originalStopIds.get(shiftedIndex); if (!newStopId.equals(originalStopId)) { // If stop ID for new stop at the given index does not match the original stop ID, the order of at least // one stop within the changed region has been changed, which is illegal according to the rule enforcing // only a single addition, deletion, or transposition per update. throw new IllegalStateException(RECONCILE_STOPS_ERROR_MSG); } } }private void verifyReferencesExist(String referringTableName, Multimap referencesPerTable) throws SQLException { for (Table referencedTable: referencesPerTable.keySet()) { LOG.info("Checking {} references to {}", referringTableName, referencedTable.name); Collection referenceStrings = referencesPerTable.get(referencedTable); String referenceFieldName = referencedTable.getKeyFieldName(); String questionMarks = String.join(", ", Collections.nCopies(referenceStrings.size(), "?")); String checkCountSql = String.format( "select %s from %s.%s where %s in (%s)", referenceFieldName, tablePrefix, referencedTable.name, referenceFieldName, questionMarks); PreparedStatement preparedStatement = connection.prepareStatement(checkCountSql); int oneBasedIndex = 1; for (String ref : referenceStrings) { preparedStatement.setString(oneBasedIndex++, ref); } LOG.info(preparedStatement.toString()); ResultSet resultSet = preparedStatement.executeQuery(); Set foundReferences = new HashSet<>(); while (resultSet.next()) { String referenceValue = resultSet.getString(1); foundReferences.add(referenceValue); } // Determine if any references were not found. referenceStrings.removeAll(foundReferences); if (referenceStrings.size() > 0) { throw new SQLException( String.format( "%s entities must contain valid %s references. (Invalid references: %s)", referringTableName, referenceFieldName, String.join(", ", referenceStrings))); } else { LOG.info("All {} {} {} references are valid.", foundReferences.size(), referencedTable.name, referenceFieldName); } } }private int updateStopTimesForPatternStop(ObjectNode patternStop, int previousTravelTime) throws SQLException { String sql = String.format( "update %s.stop_times st set arrival_time = ?, departure_time = ? from %s.trips t " + "where st.trip_id = t.trip_id AND t.pattern_id = ? AND st.stop_sequence = ?", tablePrefix, tablePrefix ); // Prepare the statement and set statement parameters PreparedStatement statement = connection.prepareStatement(sql); int oneBasedIndex = 1; int travelTime = patternStop.get("default_travel_time").asInt(); int arrivalTime = previousTravelTime + travelTime; statement.setInt(oneBasedIndex++, arrivalTime); int dwellTime = patternStop.get("default_dwell_time").asInt(); statement.setInt(oneBasedIndex++, arrivalTime + dwellTime); // Set "where clause" with value for pattern_id and stop_sequence statement.setString(oneBasedIndex++, patternStop.get("pattern_id").asText()); // In the editor, we can depend on stop_times#stop_sequence matching pattern_stops#stop_sequence because we // normalize stop sequence values for stop times during snapshotting for the editor. statement.setInt(oneBasedIndex++, patternStop.get("stop_sequence").asInt()); // Log query, execute statement, and log result. LOG.debug(statement.toString()); int entitiesUpdated = statement.executeUpdate(); LOG.debug("{} stop_time arrivals/departures updated", entitiesUpdated); return travelTime + dwellTime; }@Override public String create(String json, boolean autoCommit) throws SQLException, IOException { return update(null, json, autoCommit); }private static JsonNode getJsonNode (String json) throws IOException { try { return mapper.readTree(json); } catch (IOException e) { LOG.error("Bad JSON syntax", e); throw e; } }public int getHeadwayForStopByRoute (String stop_id, String route_id, LocalDate date, LocalTime from, LocalTime to) { List tripsForStop = feed.getDistinctTripsForStop(stop_id).stream() .filter(trip -> feed.trips.get(trip.trip_id).route_id.equals(route_id)) .filter(trip -> feed.services.get(trip.service_id).activeOn(date)) .collect(Collectors.toList()); return getStopHeadwayForTrips(stop_id, tripsForStop, from, to); }public Map getRouteHeadwaysForStop (String stop_id, LocalDate date, LocalTime from, LocalTime to) { Map routeHeadwayMap = new HashMap<>(); List routes = feed.patterns.values().stream() .filter(p -> p.orderedStops.contains(stop_id)) .map(p -> feed.routes.get(p.route_id)) .collect(Collectors.toList()); for (Route route : routes) { routeHeadwayMap.put(route.route_id, getHeadwayForStopByRoute(stop_id, route.route_id, date, from, to)); } return routeHeadwayMap; }public int getAverageHeadwayForStop (String stop_id, LocalDate date, LocalTime from, LocalTime to) { List tripsForStop = getTripsForDate(stop_id, date); return getStopHeadwayForTrips(stop_id, tripsForStop, from, to); }public List getTripsForDate (String stop_id, LocalDate date) { List tripIds = stats.getTripsForDate(date).stream() .map(trip -> trip.trip_id) .collect(Collectors.toList()); return feed.getDistinctTripsForStop(stop_id).stream() .filter(t -> tripIds.contains(t.trip_id)) // filter by trip_id list for date .collect(Collectors.toList()); }public int[] deduplicateIntArray(int[] original) { if (original == null) return null; IntArray intArray = new IntArray(original); IntArray canonical = canonicalIntArrays.get(intArray); if (canonical == null) { canonical = intArray; canonicalIntArrays.put(canonical, canonical); } return canonical.array; }public static GraphQLFieldDefinition groupedField(String tableName, String groupByColumn) { return newFieldDefinition() .name(groupByColumn) .type(groupCountType) .argument(stringArg("pattern_id")) .type(new GraphQLList(groupCountType)) .dataFetcher(new RowCountFetcher(tableName, null, groupByColumn)) .build(); }public static GraphQLFieldDefinition field (String fieldName, String tableName) { return newFieldDefinition() .name(fieldName) .type(GraphQLInt) .dataFetcher(new RowCountFetcher(tableName)) .build(); }public static double getDistance(LineString tripGeometry) { double distance = 0; for (int i = 0; i < tripGeometry.getNumPoints() - 1; i++) { try { distance += JTS.orthodromicDistance(tripGeometry.getCoordinateN(i), tripGeometry.getCoordinateN(i + 1), DefaultGeographicCRS.WGS84); } catch (TransformException e) { throw new RuntimeException(e); } } return distance; }@Override public int compareTo (GTFSError o) { int compare = super.compareTo(o); if (compare != 0) return compare; return this.badReference.compareTo((((ReferentialIntegrityError) o).badReference)); }@Override public ValidateFieldResult validateAndConvert(String hhmmss) { return ValidateFieldResult.from(getSeconds(hhmmss)); }private void commit() { try { // Execute any remaining batch inserts and commit the transaction. insertError.executeBatch(); insertInfo.executeBatch(); connection.commit(); } catch (SQLException ex) { throw new StorageException(ex); } }public int getErrorCount () { try { // Ensure any outstanding inserts are committed so that count is accurate. this.commit(); Statement statement = connection.createStatement(); statement.execute(String.format("select count(*) from %serrors", tablePrefix)); ResultSet resultSet = statement.getResultSet(); resultSet.next(); int count = resultSet.getInt(1); return count; } catch (SQLException ex) { throw new StorageException(ex); } }public static ValidateFieldResult from(ValidateFieldResult result) { ValidateFieldResult stringResult = new ValidateFieldResult<>(); stringResult.clean = String.valueOf(result.clean); stringResult.errors.addAll(result.errors); return stringResult; }private void copyEntityToSql(Iterable entities, Table table) throws SQLException { table.createSqlTable(connection, namespace, true); String entityInsertSql = table.generateInsertSql(namespace, true); PreparedStatement insertStatement = connection.prepareStatement(entityInsertSql); // Iterate over agencies and add to prepared statement int count = 0, batchSize = 0; for (E entity : entities) { entity.setStatementParameters(insertStatement, true); insertStatement.addBatch(); count++; batchSize++; // FIXME: Add batching execute on n if (batchSize > JdbcGtfsLoader.INSERT_BATCH_SIZE) { insertStatement.executeBatch(); batchSize = 0; } } // Handle remaining insertStatement.executeBatch(); LOG.info("Inserted {} {}", count, table.name); // FIXME: Should some tables not have indexes? table.createIndexes(connection, namespace); }public double getAverageStopSpacing (String pattern_id) { Pattern pattern = feed.patterns.get(pattern_id); return getPatternDistance(pattern_id) / pattern.orderedStops.size(); }public double getPatternDistance (String pattern_id) { Pattern pattern = feed.patterns.get(pattern_id); return feed.getTripDistance(pattern.associatedTrips.iterator().next(), false); }public LocalTime getEndTimeForTrips (Collection trips) { int latestArrival = Integer.MIN_VALUE; for (Trip trip : trips) { StopTime st = feed.getOrderedStopTimesForTrip(trip.trip_id).iterator().next(); if (st.arrival_time >= latestArrival) { latestArrival = st.arrival_time; } } // return end time as 2:00 am if last arrival occurs after midnight return LocalTime.ofSecondOfDay(latestArrival % 86399); }public LocalTime getStartTimeForTrips (Collection trips) { int earliestDeparture = Integer.MAX_VALUE; for (Trip trip : trips) { StopTime st = feed.getOrderedStopTimesForTrip(trip.trip_id).iterator().next(); int dep = st.departure_time; // these trips begin on the next day, so we need to cast them to 0 - 86399 if (dep > 86399) { dep = dep % 86399; } if (dep <= earliestDeparture) { earliestDeparture = dep; } } return LocalTime.ofSecondOfDay(earliestDeparture); }public double getAverageSpeedForTrips (Collection trips, LocalTime from, LocalTime to) { TDoubleList speeds = new TDoubleArrayList(); for (Trip trip : trips) { StopTime firstStopTime = feed.stop_times.ceilingEntry(Fun.t2(trip.trip_id, null)).getValue(); LocalTime tripBeginTime = LocalTime.ofSecondOfDay(firstStopTime.departure_time % 86399); // convert 24hr+ seconds to 0 - 86399 // skip trip if begin time is before or after specified time period if (tripBeginTime.isAfter(to) || tripBeginTime.isBefore(from)) { continue; } // TODO: swap straight lines for actual geometry? double speed = feed.getTripSpeed(trip.trip_id, true); if (!Double.isNaN(speed)) { speeds.add(speed); } } if (speeds.isEmpty()) return -1; return speeds.sum() / speeds.size(); }public double getPatternSpeed (String pattern_id, LocalDate date, LocalTime from, LocalTime to) { List trips = getTripsForDate(pattern_id, date); return getAverageSpeedForTrips(trips, from, to); }public static NewGTFSError forFeed (NewGTFSErrorType errorType, String badValue) { return new NewGTFSError(null, errorType).setBadValue(badValue); }public static NewGTFSError forEntity(Entity entity, NewGTFSErrorType errorType) { NewGTFSError error = new NewGTFSError(entity.getClass(), errorType); error.lineNumber = entity.id; error.entityId = entity.getId(); error.entitySequenceNumber = entity.getSequenceNumber(); return error; }public static NewGTFSError forLine (Table table, int lineNumber, NewGTFSErrorType errorType, String badValue) { NewGTFSError error = new NewGTFSError(table.getEntityClass(), errorType); error.lineNumber = lineNumber; error.badValue = badValue; return error; }public NewGTFSError addInfo (String key, String value) { errorInfo.put(key, value); return this; }public static DataSource createDataSource (String url, String username, String password) { String characterEncoding = Charset.defaultCharset().toString(); LOG.debug("Default character encoding: {}", characterEncoding); if (!Charset.defaultCharset().equals(StandardCharsets.UTF_8)) { // Character encoding must be set to UTF-8 in order for the database connection to work without error. // To override default encoding at runtime, run application jar with encoding environment variable set to // UTF-8 (or update IDE settings). TODO we should also check that JDBC and the database know to use UTF-8. throw new RuntimeException("Your system's default encoding (" + characterEncoding + ") is not supported. Please set it to UTF-8. Example: java -Dfile.encoding=UTF-8 application.jar"); } // ConnectionFactory can handle null username and password (for local host-based authentication) ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, username, password); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null); GenericObjectPool connectionPool = new GenericObjectPool(poolableConnectionFactory); // TODO: set other options on connectionPool? connectionPool.setMaxTotal(300); connectionPool.setMaxIdle(4); connectionPool.setMinIdle(2); poolableConnectionFactory.setPool(connectionPool); // We also want auto-commit switched off for bulk inserts, and also because fetches are super-slow with // auto-commit turned on. Apparently it interferes with result cursors. poolableConnectionFactory.setDefaultAutoCommit(false); return new PoolingDataSource(connectionPool); // We might want already-loaded feeds to be treated as read-only. // But we need to call this on the connection, not the connectionSource. // connection.setReadOnly(); // Not sure we need to close cursors - closing the pool-wrapped connection when we're done with it should also close cursors. // will this help? https://stackoverflow.com/a/18300252 // connection.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); }public static void delete (String feedId, DataSource dataSource) throws SQLException, InvalidNamespaceException { LOG.info("Deleting all tables (dropping schema) for {} feed namespace.", feedId); Connection connection = null; try { connection = dataSource.getConnection(); ensureValidNamespace(feedId); // Mark entry in feeds table as deleted. String deleteFeedEntrySql = "update feeds set deleted = true where namespace = ?"; PreparedStatement deleteFeedStatement = connection.prepareStatement(deleteFeedEntrySql); deleteFeedStatement.setString(1, feedId); deleteFeedStatement.executeUpdate(); // Drop all tables bearing the feedId namespace. // Note: It does not appear to be possible to use prepared statements with "drop schema." String dropSchemaSql = String.format("DROP SCHEMA %s CASCADE", feedId); Statement statement = connection.createStatement(); statement.executeUpdate(dropSchemaSql); // Commit the changes. connection.commit(); } catch (InvalidNamespaceException | SQLException e) { LOG.error(String.format("Could not drop feed for namespace %s", feedId), e); throw e; } finally { if (connection != null) DbUtils.closeQuietly(connection); } }public static ValidationResult validate (String feedId, DataSource dataSource) { Feed feed = new Feed(dataSource, feedId); ValidationResult result = feed.validate(); return result; }public static FeedLoadResult load (String filePath, DataSource dataSource) { JdbcGtfsLoader loader = new JdbcGtfsLoader(filePath, dataSource); FeedLoadResult result = loader.loadTables(); return result; }public static FeedLoadResult export (String feedId, String outFile, DataSource dataSource, boolean fromEditor) { JdbcGtfsExporter exporter = new JdbcGtfsExporter(feedId, outFile, dataSource, fromEditor); FeedLoadResult result = exporter.exportTables(); return result; }public void registerError(Entity entity, NewGTFSErrorType errorType, Object badValue) { errorStorage.storeError(NewGTFSError.forEntity(entity, errorType).setBadValue(badValue.toString())); }public void registerError(Entity entity, NewGTFSErrorType errorType) { errorStorage.storeError(NewGTFSError.forEntity(entity, errorType)); }private TableLoadResult export (Table table, String filterSql) { long startTime = System.currentTimeMillis(); TableLoadResult tableLoadResult = new TableLoadResult(); try { if (filterSql == null) { throw new IllegalArgumentException("filterSql argument cannot be null"); } else { // Surround filter SQL in parentheses. filterSql = String.format("(%s)", filterSql); } // Create entry for table String textFileName = table.name + ".txt"; ZipEntry zipEntry = new ZipEntry(textFileName); zipOutputStream.putNextEntry(zipEntry); // don't let CSVWriter close the stream when it is garbage-collected OutputStream protectedOut = new FilterOutputStream(zipOutputStream); String copySql = String.format("copy %s to STDOUT DELIMITER ',' CSV HEADER", filterSql); LOG.info(copySql); // Our connection pool wraps the Connection objects, so we need to unwrap the Postgres connection interface. CopyManager copyManager = new CopyManager(connection.unwrap(BaseConnection.class)); tableLoadResult.rowCount = (int) copyManager.copyOut(copySql, protectedOut); if (tableLoadResult.rowCount == 0) { // If no rows were exported, keep track of table name for later removal. emptyTableList.add(textFileName); } zipOutputStream.closeEntry(); LOG.info("Copied {} {} in {} ms.", tableLoadResult.rowCount, table.name, System.currentTimeMillis() - startTime); connection.commit(); } catch (SQLException | IOException | IllegalArgumentException e) { // Rollback connection so that fatal exception does not impact loading of other tables. try { connection.rollback(); } catch (SQLException ex) { ex.printStackTrace(); } tableLoadResult.fatalException = e.toString(); LOG.error("Exception while exporting tables", e); } return tableLoadResult; }private void cleanUpZipFile() { long startTime = System.currentTimeMillis(); // Define ZIP File System Properties in HashMap Map zip_properties = new HashMap<>(); // We want to read an existing ZIP File, so we set this to False zip_properties.put("create", "false"); // Specify the path to the ZIP File that you want to read as a File System // (File#toURI allows this to work across different operating systems, including Windows) URI zip_disk = URI.create("jar:" + new File(outFile).toURI()); // Create ZIP file System try (FileSystem fileSystem = FileSystems.newFileSystem(zip_disk, zip_properties)) { // Get the Path inside ZIP File to delete the ZIP Entry for (String fileName : emptyTableList) { Path filePath = fileSystem.getPath(fileName); // Execute Delete Files.delete(filePath); LOG.info("Empty file {} successfully deleted", fileName); } } catch (IOException e) { LOG.error("Could not remove empty zip files"); e.printStackTrace(); } LOG.info("Deleted {} empty files in {} ms", emptyTableList.size(), System.currentTimeMillis() - startTime); }public int executeRemaining() throws SQLException { if (currentBatchSize > 0) { totalRecordsProcessed += currentBatchSize; preparedStatement.executeBatch(); currentBatchSize = 0; } // Avoid reuse, signal that this was cleanly closed. preparedStatement = null; LOG.info(String.format("Processed %d %s records", totalRecordsProcessed, recordType)); return totalRecordsProcessed; }public String getId() { StringBuilder sb = new StringBuilder(); sb.append(trip_id); sb.append('_'); sb.append(convertToGtfsTime(start_time)); sb.append("_to_"); sb.append(convertToGtfsTime(end_time)); sb.append("_every_"); sb.append(String.format("%dm%02ds", headway_secs / 60, headway_secs % 60)); if (exact_times == 1) sb.append("_exact"); return sb.toString(); }private void registerSnapshot () { try { // We cannot simply insert into the feeds table because if we are creating an empty snapshot (to create/edit // a GTFS feed from scratch), the feed registry table will not exist. // TODO copy over feed_id and feed_version from source namespace? // TODO: Record total snapshot processing time? createFeedRegistryIfNotExists(connection); createSchema(connection, tablePrefix); PreparedStatement insertStatement = connection.prepareStatement( "insert into feeds values (?, null, null, null, null, null, current_timestamp, ?)"); insertStatement.setString(1, tablePrefix); insertStatement.setString(2, feedIdToSnapshot); insertStatement.execute(); connection.commit(); LOG.info("Created new snapshot namespace: {}", insertStatement); } catch (Exception ex) { LOG.error("Exception while registering snapshot namespace in feeds table", ex); DbUtils.closeQuietly(connection); } }private void addEditorSpecificFields(Connection connection, String tablePrefix, Table table) throws SQLException { LOG.info("Adding any missing columns for {}", tablePrefix + table.name); Statement statement = connection.createStatement(); for (Field field : table.editorFields()) { // The following statement requires PostgreSQL 9.6+. String addColumnSql = String.format("ALTER TABLE %s ADD COLUMN IF NOT EXISTS %s %s", tablePrefix + table.name, field.name, field.getSqlTypeName()); LOG.info(addColumnSql); statement.execute(addColumnSql); } }private boolean tableExists(String namespace, String tableName) { // Preempt SQL check with null check of either namespace or table name. if (namespace == null || tableName == null) return false; try { // This statement is postgres-specific. PreparedStatement tableExistsStatement = connection.prepareStatement( "SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = ? AND table_name = ?)" ); tableExistsStatement.setString(1, namespace); tableExistsStatement.setString(2, tableName); ResultSet resultSet = tableExistsStatement.executeQuery(); resultSet.next(); return resultSet.getBoolean(1); } catch (SQLException e) { e.printStackTrace(); return false; } }public SnapshotResult copyTables() { // This result object will be returned to the caller to summarize the feed and report any critical errors. SnapshotResult result = new SnapshotResult(); try { long startTime = System.currentTimeMillis(); // We get a single connection object and share it across several different methods. // This ensures that actions taken in one method are visible to all subsequent SQL statements. // If we create a schema or table on one connection, then access it in a separate connection, we have no // guarantee that it exists when the accessing statement is executed. connection = dataSource.getConnection(); // Generate a unique prefix that will identify this feed. this.tablePrefix = randomIdString(); result.uniqueIdentifier = tablePrefix; // Create entry in snapshots table. registerSnapshot(); // Include the dot separator in the table prefix. // This allows everything to work even when there's no prefix. this.tablePrefix += "."; // Copy each table in turn // FIXME: NO non-fatal exception errors are being captured during copy operations. result.agency = copy(Table.AGENCY, true); result.calendar = copy(Table.CALENDAR, true); result.calendarDates = copy(Table.CALENDAR_DATES, true); result.fareAttributes = copy(Table.FARE_ATTRIBUTES, true); result.fareRules = copy(Table.FARE_RULES, true); result.feedInfo = copy(Table.FEED_INFO, true); result.frequencies = copy(Table.FREQUENCIES, true); result.routes = copy(Table.ROUTES, true); // FIXME: Find some place to store errors encountered on copy for patterns and pattern stops. copy(Table.PATTERNS, true); copy(Table.PATTERN_STOP, true); // see method comments fo why different logic is needed for this table result.scheduleExceptions = createScheduleExceptionsTable(); result.shapes = copy(Table.SHAPES, true); result.stops = copy(Table.STOPS, true); // TODO: Should we defer index creation on stop times? // Copying all tables for STIF w/ stop times idx = 156 sec; w/o = 28 sec // Other feeds w/ stop times AC Transit = 3 sec; Brooklyn bus = result.stopTimes = copy(Table.STOP_TIMES, true); result.transfers = copy(Table.TRANSFERS, true); result.trips = copy(Table.TRIPS, true); result.completionTime = System.currentTimeMillis(); result.loadTimeMillis = result.completionTime - startTime; LOG.info("Copying tables took {} sec", (result.loadTimeMillis) / 1000); } catch (Exception ex) { // Note: Exceptions that occur during individual table loads are separately caught and stored in // TableLoadResult. LOG.error("Exception while creating snapshot: {}", ex.toString()); ex.printStackTrace(); result.fatalException = ex.toString(); } return result; }private void setFieldToNull(boolean postgresText, String[] transformedStrings, int fieldIndex, Field field) { if (postgresText) transformedStrings[fieldIndex + 1] = POSTGRES_NULL_TEXT; // Adjust parameter index by two: indexes are one-based and the first one is the CSV line number. else try { // LOG.info("setting {} index to null", fieldIndex + 2); field.setNull(insertStatement, fieldIndex + 2); } catch (SQLException e) { e.printStackTrace(); // FIXME: store error here? It appears that an exception should only be thrown if the type value is invalid, // the connection is closed, or the index is out of bounds. So storing an error may be unnecessary. } }private int getTableSize(Table table) { ZipEntry zipEntry = zip.getEntry(table.name + ".txt"); if (zipEntry == null) return 0; return (int) zipEntry.getSize(); }private TableLoadResult load (Table table) { // This object will be returned to the caller to summarize the contents of the table and any errors. TableLoadResult tableLoadResult = new TableLoadResult(); int initialErrorCount = errorStorage.getErrorCount(); try { tableLoadResult.rowCount = loadInternal(table); tableLoadResult.fileSize = getTableSize(table); LOG.info(String.format("loaded in %d %s records", tableLoadResult.rowCount, table.name)); } catch (Exception ex) { LOG.error("Fatal error loading table", ex); tableLoadResult.fatalException = ex.toString(); // Rollback connection so that fatal exception does not impact loading of other tables. try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } } finally { // Explicitly delete the tmp file now that load is finished (either success or failure). // Otherwise these multi-GB files clutter the drive. if (tempTextFile != null) { tempTextFile.delete(); } } int finalErrorCount = errorStorage.getErrorCount(); tableLoadResult.errorCount = finalErrorCount - initialErrorCount; return tableLoadResult; }private boolean checkDistanceAndTime (double distanceMeters, double travelTimeSeconds, StopTime stopTime) { boolean good = true; // TODO Use Epsilon for very tiny travel e.g. < 5 meters if (distanceMeters == 0) { registerError(stopTime, TRAVEL_DISTANCE_ZERO); good = false; } if (travelTimeSeconds < 0) { registerError(stopTime, TRAVEL_TIME_NEGATIVE, travelTimeSeconds); good = false; } else if (travelTimeSeconds == 0) { // Only register the travel time zero error if not all travel times are rounded. Otherwise, hold onto the // error in the travelTimeZeroErrors collection until the completion of this validator. if (!allTravelTimesAreRounded) registerError(stopTime, TRAVEL_TIME_ZERO); else travelTimeZeroErrors.add(createUnregisteredError(stopTime, TRAVEL_TIME_ZERO)); good = false; } return good; }public Rectangle2D getBounds () { Rectangle2D ret = null; for (Stop stop : feed.stops.values()) { // skip over stops that don't have any stop times if (!feed.stopCountByStopTime.containsKey(stop.stop_id)) { continue; } if (ret == null) { ret = new Rectangle2D.Double(stop.stop_lon, stop.stop_lat, 0, 0); } else { ret.add(new Point2D.Double(stop.stop_lon, stop.stop_lat)); } } return ret; }public LocalDate getCalendarServiceRangeStart() { int startDate = 0; for (Service service : feed.services.values()) { if (service.calendar == null) continue; // if (startDate == 0 || service.calendar.start_date < startDate) { // startDate = service.calendar.start_date; // } } if (startDate == 0) return null; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); return LocalDate.parse(String.valueOf(startDate), formatter); }private void handleWorkingDirectory() throws MojoExecutionException { if ( workingDirectory == null ) { workingDirectory = basedir; } if ( !workingDirectory.exists() ) { getLog().debug( "Making working directory '" + workingDirectory.getAbsolutePath() + "'." ); if ( !workingDirectory.mkdirs() ) { throw new MojoExecutionException( "Could not make working directory: '" + workingDirectory.getAbsolutePath() + "'" ); } } }protected Artifact findExecutableArtifact() throws MojoExecutionException { // ILimitedArtifactIdentifier execToolAssembly = this.getExecutableToolAssembly(); Artifact executableTool = null; for ( Artifact pluginDep : this.pluginDependencies ) { if ( this.executableDependency.matches( pluginDep ) ) { executableTool = pluginDep; break; } } if ( executableTool == null ) { throw new MojoExecutionException( "No dependency of the plugin matches the specified executableDependency." + " Specified executableToolAssembly is: " + executableDependency.toString() ); } return executableTool; }private Set resolveExecutableDependencies( Artifact executablePomArtifact ) throws MojoExecutionException { Set executableDependencies = new LinkedHashSet<>(); try { ProjectBuildingRequest buildingRequest = getSession().getProjectBuildingRequest(); MavenProject executableProject = this.projectBuilder.build( executablePomArtifact, buildingRequest ).getProject(); for ( ArtifactResult artifactResult : dependencyResolver.resolveDependencies( buildingRequest, executableProject.getModel(), null ) ) { executableDependencies.add( artifactResult.getArtifact() ); } } catch ( Exception ex ) { throw new MojoExecutionException( "Encountered problems resolving dependencies of the executable " + "in preparation for its execution.", ex ); } return executableDependencies; }private void addRelevantProjectDependenciesToClasspath( List path ) throws MojoExecutionException { if ( this.includeProjectDependencies ) { getLog().debug( "Project Dependencies will be included." ); List artifacts = new ArrayList<>(); List theClasspathFiles = new ArrayList<>(); collectProjectArtifactsAndClasspath( artifacts, theClasspathFiles ); for ( Path classpathFile : theClasspathFiles ) { getLog().debug( "Adding to classpath : " + classpathFile ); path.add( classpathFile ); } for ( Artifact classPathElement : artifacts ) { getLog().debug( "Adding project dependency artifact: " + classPathElement.getArtifactId() + " to classpath" ); path.add( classPathElement.getFile().toPath() ); } } else { getLog().debug( "Project Dependencies will be excluded." ); } }private void addRelevantPluginDependenciesToClasspath( List path ) throws MojoExecutionException { if ( hasCommandlineArgs() ) { arguments = parseCommandlineArgs(); } for ( Artifact classPathElement : this.determineRelevantPluginDependencies() ) { getLog().debug( "Adding plugin dependency artifact: " + classPathElement.getArtifactId() + " to classpath" ); path.add( classPathElement.getFile().toPath() ); } }private ClassLoader getClassLoader() throws MojoExecutionException { List classpathURLs = new ArrayList<>(); this.addRelevantPluginDependenciesToClasspath( classpathURLs ); this.addRelevantProjectDependenciesToClasspath( classpathURLs ); this.addAdditionalClasspathElements( classpathURLs ); try { return LoaderFinder.find( classpathURLs, mainClass ); } catch ( NullPointerException | IOException e ) { throw new MojoExecutionException( e.getMessage(), e ); } }private void register(Path directory, boolean useFileTreeModifier) throws IOException { logger.debug("Registering [{}].", directory); Watchable watchable = isMac ? new WatchablePath(directory) : directory; WatchEvent.Modifier[] modifiers = useFileTreeModifier ? new WatchEvent.Modifier[] {ExtendedWatchEventModifier.FILE_TREE} : new WatchEvent.Modifier[] {}; WatchEvent.Kind[] kinds = new WatchEvent.Kind[] {ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY}; WatchKey watchKey = watchable.register(watchService, kinds, modifiers); keyRoots.put(watchKey, directory); }public CompletableFuture watchAsync(Executor executor) { return CompletableFuture.supplyAsync( () -> { watch(); return null; }, executor); }final void signalEvent(WatchEvent.Kind kind, Path context) { post(new Event<>(kind, 1, context)); signal(); }public void onSaveInstanceState(Bundle outState) { hasSavedState = true; outState.putParcelable(KEY_STATE, new State(observableManager.id(), group.id())); }void destroy() { destroyed = true; for (Map> observableMap : groupMap.values()) { for (ManagedObservable managedObservable : observableMap.values()) { managedObservable.cancel(); } observableMap.clear(); } groupMap.clear(); }private static List buildEmptyTicks(ZonedDateTime beginTime, ZonedDateTime endTime, int duration) { List emptyTicks = new ArrayList<>(); Duration tickDuration = Duration.ofSeconds(duration); ZonedDateTime tickEndTime = beginTime; do { tickEndTime = tickEndTime.plus(tickDuration); emptyTicks.add(new BaseTick(tickDuration, tickEndTime)); } while (tickEndTime.isBefore(endTime)); return emptyTicks; }private void removeExceedingTicks() { int tickCount = ticks.size(); if (tickCount > maximumTickCount) { // Removing old ticks int nbTicksToRemove = tickCount - maximumTickCount; for (int i = 0; i < nbTicksToRemove; i++) { ticks.remove(0); } // Updating removed ticks count removedTicksCount += nbTicksToRemove; } }private static void displayChart(JFreeChart chart) { // Chart panel ChartPanel panel = new ChartPanel(chart); panel.setFillZoomRectangle(true); panel.setMouseWheelEnabled(true); panel.setPreferredSize(new Dimension(1024, 400)); // Application frame ApplicationFrame frame = new ApplicationFrame("Ta4j example - Cash flow to chart"); frame.setContentPane(panel); frame.pack(); RefineryUtilities.centerFrameOnScreen(frame); frame.setVisible(true); }private static void addCashFlowAxis(XYPlot plot, TimeSeriesCollection dataset) { final NumberAxis cashAxis = new NumberAxis("Cash Flow Ratio"); cashAxis.setAutoRangeIncludesZero(false); plot.setRangeAxis(1, cashAxis); plot.setDataset(1, dataset); plot.mapDatasetToRangeAxis(1, 1); final StandardXYItemRenderer cashFlowRenderer = new StandardXYItemRenderer(); cashFlowRenderer.setSeriesPaint(0, Color.blue); plot.setRenderer(1, cashFlowRenderer); }private static TimeSeriesCollection createAdditionalDataset(TimeSeries series) { ClosePriceIndicator indicator = new ClosePriceIndicator(series); TimeSeriesCollection dataset = new TimeSeriesCollection(); org.jfree.data.time.TimeSeries chartTimeSeries = new org.jfree.data.time.TimeSeries("Btc price"); for (int i = 0; i < series.getTickCount(); i++) { Tick tick = series.getTick(i); chartTimeSeries.add(new Second(new Date(tick.getEndTime().toEpochSecond() * 1000)), indicator.getValue(i).toDouble()); } dataset.addSeries(chartTimeSeries); return dataset; }private static OHLCDataset createOHLCDataset(TimeSeries series) { final int nbTicks = series.getTickCount(); Date[] dates = new Date[nbTicks]; double[] opens = new double[nbTicks]; double[] highs = new double[nbTicks]; double[] lows = new double[nbTicks]; double[] closes = new double[nbTicks]; double[] volumes = new double[nbTicks]; for (int i = 0; i < nbTicks; i++) { Tick tick = series.getTick(i); dates[i] = new Date(tick.getEndTime().toEpochSecond() * 1000); opens[i] = tick.getOpenPrice().toDouble(); highs[i] = tick.getMaxPrice().toDouble(); lows[i] = tick.getMinPrice().toDouble(); closes[i] = tick.getClosePrice().toDouble(); volumes[i] = tick.getVolume().toDouble(); } OHLCDataset dataset = new DefaultHighLowDataset("btc", dates, highs, lows, opens, closes, volumes); return dataset; }private static void loadLoggerConfiguration() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); try { configurator.doConfigure(LOGBACK_CONF_FILE); } catch (JoranException je) { Logger.getLogger(StrategyExecutionLogging.class.getName()).log(Level.SEVERE, "Unable to load Logback configuration", je); } }private void fillToTheEnd() { if (timeSeries.getEndIndex() >= values.size()) { Decimal lastValue = values.get(values.size() - 1); values.addAll(Collections.nCopies(timeSeries.getEndIndex() - values.size() + 1, lastValue)); } }private void calculate(Trade trade) { final int entryIndex = trade.getEntry().getIndex(); int begin = entryIndex + 1; if (begin > values.size()) { Decimal lastValue = values.get(values.size() - 1); values.addAll(Collections.nCopies(begin - values.size(), lastValue)); } int end = trade.getExit().getIndex(); for (int i = Math.max(begin, 1); i <= end; i++) { Decimal ratio; if (trade.getEntry().isBuy()) { ratio = timeSeries.getTick(i).getClosePrice().dividedBy(timeSeries.getTick(entryIndex).getClosePrice()); } else { ratio = timeSeries.getTick(entryIndex).getClosePrice().dividedBy(timeSeries.getTick(i).getClosePrice()); } values.add(values.get(entryIndex).multipliedBy(ratio)); } }private Decimal calculateSar(int index) { Decimal previousSar = getValue(index - 1); return extremePoint.multipliedBy(acceleration) .plus(Decimal.ONE.minus(acceleration).multipliedBy(previousSar)); }private void incrementAcceleration() { if (acceleration.isGreaterThanOrEqual(ACCELERATION_THRESHOLD)) { acceleration = MAX_ACCELERATION; } else { acceleration = acceleration.plus(ACCELERATION_INCREMENT); } }private static Tick generateRandomTick() { final Decimal maxRange = Decimal.valueOf("0.03"); // 3.0% Decimal openPrice = LAST_TICK_CLOSE_PRICE; Decimal minPrice = openPrice.minus(openPrice.multipliedBy(maxRange.multipliedBy(Decimal.valueOf(Math.random())))); Decimal maxPrice = openPrice.plus(openPrice.multipliedBy(maxRange.multipliedBy(Decimal.valueOf(Math.random())))); Decimal closePrice = randDecimal(minPrice, maxPrice); LAST_TICK_CLOSE_PRICE = closePrice; return new BaseTick(ZonedDateTime.now(), openPrice, maxPrice, minPrice, closePrice, Decimal.ONE); }private static Decimal randDecimal(Decimal min, Decimal max) { Decimal randomDecimal = null; if (min != null && max != null && min.isLessThan(max)) { randomDecimal = max.minus(min).multipliedBy(Decimal.valueOf(Math.random())).plus(min); } return randomDecimal; }private static org.jfree.data.time.TimeSeries buildChartTimeSeries(TimeSeries tickSeries, Indicator indicator, String name) { org.jfree.data.time.TimeSeries chartTimeSeries = new org.jfree.data.time.TimeSeries(name); for (int i = 0; i < tickSeries.getTickCount(); i++) { Tick tick = tickSeries.getTick(i); chartTimeSeries.add(new Minute(Date.from(tick.getEndTime().toInstant())), indicator.getValue(i).toDouble()); } return chartTimeSeries; }public Order operate(int index, Decimal price, Decimal amount) { Order order = null; if (isNew()) { order = new Order(index, startingType, price, amount); entry = order; } else if (isOpened()) { if (index < entry.getIndex()) { throw new IllegalStateException("The index i is less than the entryOrder index"); } order = new Order(index, startingType.complementType(), price, amount); exit = order; } return order; }private void calculateRegressionLine(int startIndex, int endIndex) { // First pass: compute xBar and yBar Decimal sumX = Decimal.ZERO; Decimal sumY = Decimal.ZERO; for (int i = startIndex; i <= endIndex; i++) { sumX = sumX.plus(Decimal.valueOf(i)); sumY = sumY.plus(indicator.getValue(i)); } Decimal nbObservations = Decimal.valueOf(endIndex - startIndex + 1); Decimal xBar = sumX.dividedBy(nbObservations); Decimal yBar = sumY.dividedBy(nbObservations); // Second pass: compute slope and intercept Decimal xxBar = Decimal.ZERO; Decimal xyBar = Decimal.ZERO; for (int i = startIndex; i <= endIndex; i++) { Decimal dX = Decimal.valueOf(i).minus(xBar); Decimal dY = indicator.getValue(i).minus(yBar); xxBar = xxBar.plus(dX.multipliedBy(dX)); xyBar = xyBar.plus(dX.multipliedBy(dY)); } slope = xyBar.dividedBy(xxBar); intercept = yBar.minus(slope.multipliedBy(xBar)); }public static List getSplitBeginIndexes(TimeSeries series, Duration splitDuration) { ArrayList beginIndexes = new ArrayList<>(); int beginIndex = series.getBeginIndex(); int endIndex = series.getEndIndex(); // Adding the first begin index beginIndexes.add(beginIndex); // Building the first interval before next split ZonedDateTime beginInterval = series.getFirstTick().getEndTime(); ZonedDateTime endInterval = beginInterval.plus(splitDuration); for (int i = beginIndex; i <= endIndex; i++) { // For each tick... ZonedDateTime tickTime = series.getTick(i).getEndTime(); if (tickTime.isBefore(beginInterval) || !tickTime.isBefore(endInterval)) { // Tick out of the interval if (!endInterval.isAfter(tickTime)) { // Tick after the interval // --> Adding a new begin index beginIndexes.add(i); } // Building the new interval before next split beginInterval = endInterval.isBefore(tickTime) ? tickTime : endInterval; endInterval = beginInterval.plus(splitDuration); } } return beginIndexes; }private Decimal calculateMaximumDrawdown(TimeSeries series, CashFlow cashFlow) { Decimal maximumDrawdown = Decimal.ZERO; Decimal maxPeak = Decimal.ZERO; if (!series.isEmpty()) { // The series is not empty for (int i = series.getBeginIndex(); i <= series.getEndIndex(); i++) { Decimal value = cashFlow.getValue(i); if (value.isGreaterThan(maxPeak)) { maxPeak = value; } Decimal drawdown = maxPeak.minus(value).dividedBy(maxPeak); if (drawdown.isGreaterThan(maximumDrawdown)) { maximumDrawdown = drawdown; } } } return maximumDrawdown; }private void increaseLengthTo(int index, int maxLength) { if (highestResultIndex > -1) { int newResultsCount = Math.min(index-highestResultIndex, maxLength); if (newResultsCount == maxLength) { results.clear(); results.addAll(Collections. nCopies(maxLength, null)); } else if (newResultsCount > 0) { results.addAll(Collections. nCopies(newResultsCount, null)); removeExceedingResults(maxLength); } } else { // First use of cache assert results.isEmpty() : "Cache results list should be empty"; results.addAll(Collections. nCopies(Math.min(index+1, maxLength), null)); } }public void addTrade(Decimal tradeVolume, Decimal tradePrice) { if (openPrice == null) { openPrice = tradePrice; } closePrice = tradePrice; if (maxPrice == null) { maxPrice = tradePrice; } else { maxPrice = maxPrice.isLessThan(tradePrice) ? tradePrice : maxPrice; } if (minPrice == null) { minPrice = tradePrice; } else { minPrice = minPrice.isGreaterThan(tradePrice) ? tradePrice : minPrice; } volume = volume.plus(tradeVolume); amount = amount.plus(tradeVolume.multipliedBy(tradePrice)); trades++; }public void throwException() throws InstagramException { if (errorMeta != null) { String msg = errorMeta.getErrorType() + ": " + errorMeta.getErrorMessage(); switch (errorMeta.getCode()) { case 400: throw new InstagramBadRequestException(errorMeta.getErrorType(), msg, this.headers); case 429: throw new InstagramRateLimitException(errorMeta.getErrorType(), msg, this.headers); default: throw new InstagramException(errorMeta.getErrorType(), msg, this.headers); } } else { throw new InstagramException("No metadata found in response", this.headers); } }public static Map queryStringToMap(String queryString) { Map result = new HashMap(); if ((queryString != null) && (queryString.length() > 0)) { for (String param : queryString.split(PARAM_SEPARATOR)) { String pair[] = param.split(PAIR_SEPARATOR); String key = formURLDecode(pair[0]); String value = (pair.length > 1) ? formURLDecode(pair[1]) : EMPTY_STRING; result.put(key, value); } } return result; }public static String concatSortedPercentEncodedParams(Map params) { StringBuilder result = new StringBuilder(); for (Map.Entry entry : params.entrySet()) { result.append(entry.getKey()).append(PAIR_SEPARATOR); result.append(entry.getValue()).append(PARAM_SEPARATOR); } return result.toString().substring(0, result.length() - 1); }public static String appendParametersToQueryString(String url, Map params) { Preconditions.checkNotNull(url, "Cannot append to null URL"); String queryString = URLUtils.formURLEncodeMap(params); if (queryString.equals(EMPTY_STRING)) { return url; } else { url += (url.indexOf(QUERY_STRING_SEPARATOR) != -1) ? PARAM_SEPARATOR : QUERY_STRING_SEPARATOR; url += queryString; return url; } }public static String percentEncode(String string) { String encoded = formURLEncode(string); for (EncodingRule rule : ENCODING_RULES) { encoded = rule.apply(encoded); } return encoded; }public static String formURLEncodeMap(Map map) { Preconditions.checkNotNull(map, "Cannot url-encode a null object"); return (map.size() <= 0) ? EMPTY_STRING : doFormUrlEncode(map); }public SubscriptionsListResponse getSubscriptionList() throws InstagramException { final OAuthRequest request = prepareOAuthRequest(Verbs.GET); try { final Response response = request.send(); return getSubscriptionsListResponse(response.getBody()); } catch (IOException e) { throw new InstagramException("Failed to get subscription list", e); } }public SubscriptionResponse deleteAllSubscription() throws InstagramException { final OAuthRequest request = prepareOAuthRequest(Verbs.DELETE); request.addQuerystringParameter(Constants.SUBSCRIPTION_TYPE, "all"); try { final Response response = request.send(); return getSubscriptionResponse(response.getBody()); } catch (IOException e) { throw new InstagramException("Failed to delete all subscriptions", e); } }public SubscriptionResponse deleteSubscription(String id) throws InstagramException { final OAuthRequest request = prepareOAuthRequest(Verbs.DELETE); request.addQuerystringParameter("id", id); try { final Response response = request.send(); return getSubscriptionResponse(response.getBody()); } catch (IOException e) { throw new InstagramException("Failed to delete subscription with id ["+id+"]", e); } }public InstagramSubscription radius(String radius){ Preconditions.checkValidRadius(radius, "Invalid 'radius' key"); this.params.put(Constants.RADIUS, radius); return this; }public InstagramSubscription longitude(String longitude){ Preconditions.checkValidLatLong(longitude, "Invalid 'lng' key"); this.params.put(Constants.LONGITUDE, longitude); return this; }public InstagramSubscription latitute(String latitude){ Preconditions.checkValidLatLong(latitude, "Invalid 'lat' key"); this.params.put(Constants.LATITUDE, latitude); return this; }public InstagramSubscription aspect(String aspect) { Preconditions.checkEmptyString(aspect, "Invalid 'aspect' key"); this.params.put(Constants.ASPECT, aspect); return this; }public InstagramSubscription verifyToken(String verifyToken) { Preconditions.checkEmptyString(verifyToken, "Invalid 'verifyToken' key"); this.params.put(Constants.VERIFY_TOKEN, verifyToken); return this; }public InstagramSubscription object(SubscriptionType type) { this.params.put(Constants.SUBSCRIPTION_TYPE, type.toString()); return this; }public InstagramSubscription clientSecret(String clientSecret) { Preconditions.checkEmptyString(clientSecret, "Invalid 'clientSecret' key"); this.params.put(Constants.CLIENT_SECRET, clientSecret); return this; }public InstagramSubscription clientId(String clientId) { Preconditions.checkEmptyString(clientId, "Invalid 'clientId' key"); this.params.put(Constants.CLIENT_ID, clientId); return this; }public InstagramSubscription callback(String callback) { Preconditions.checkValidUrl(callback, "Invalid Callback Url"); this.params.put(Constants.CALLBACK_URL, callback); return this; }public static void prettyPrintJSONResponse(Logger logger, String jsonString) { if(logger.isDebugEnabled()) { // it can fail...on 404 it usually not a json String s; try { final JsonElement element = new JsonParser().parse(jsonString); s = new GsonBuilder().setPrettyPrinting().create().toJson(element); } catch(Exception e) { s = jsonString; } logger.debug("Received JSON response from Instagram - " + s); } }public String getBodyContents() { try { return new String(getByteBodyContents(), getCharset()); } catch (UnsupportedEncodingException uee) { throw new OAuthException("Unsupported Charset: " + charset, uee); } }public static void configureConnectionSettings(final Request request, final InstagramConfig config) { request.setConnectTimeout(config.getConnectionTimeoutMills(), TimeUnit.MILLISECONDS); request.setReadTimeout(config.getReadTimeoutMills(), TimeUnit.MILLISECONDS); // #51 Connection Keep Alive request.setConnectionKeepAlive(config.isConnectionKeepAlive()); }@Deprecated public InstagramClient getSignedHeaderInstagram(Token accessToken, String ipAddress) { return new Instagram(accessToken.getToken(), config.getApiSecret(), ipAddress); }public static void checkValidOAuthCallback(String url, String errorMsg) { checkEmptyString(url, errorMsg); if (url.toLowerCase().compareToIgnoreCase(OAuthConstants.OUT_OF_BAND) != 0) { check(isUrl(url), errorMsg); } }public static void checkValidUrl(String url, String errorMsg) { checkEmptyString(url, errorMsg); check(isUrl(url), errorMsg); }public static void checkEmptyString(String string, String errorMsg) { check(StringUtils.isNotBlank(string), errorMsg); }public static void checkBothNotNull(Object object1, Object object2, String errorMsg) { check(!(object1 == null && object2 == null), errorMsg); }private static T createObjectFromResponse(Class clazz, final String response) throws InstagramException { Gson gson = new Gson(); T object; try { object = gson.fromJson(response, clazz); } catch (Exception e) { throw new InstagramException("Error parsing json to object type " + clazz.getName(), e); } return object; }private static T createInstagramObject(Verbs verbs, Class clazz, String methodName, Map params) throws InstagramException { Response response; try { response = getApiResponse(verbs, methodName, params); } catch (IOException e) { throw new InstagramException("IOException while retrieving data", e); } if (response.getCode() >= 200 && response.getCode() < 300) { return createObjectFromResponse(clazz, response.getBody()); } throw handleInstagramError(response); }public OembedInformation getOembedInformation(String url) throws InstagramException { String apiMethod = String.format(Methods.OEMBED_INFORMATION, url); return createInstagramObject(Verbs.GET, OembedInformation.class, apiMethod, null); }public static Map sort(Map map) { Preconditions.checkNotNull(map, "Cannot sort a null object."); Map sorted = new LinkedHashMap(); for (String key : getSortedKeys(map)) { sorted.put(key, map.get(key)); } return sorted; }public static String signature(String endpoint, Map params, String clientSecret) throws InstagramException { SecretKeySpec keySpec = new SecretKeySpec(clientSecret.getBytes(UTF_8), HMAC_SHA256); // ensure we iterate through the keys in sorted order List values = new ArrayList(params.size()); for (String key : MapUtils.getSortedKeys(params)) { values.add(String.format("%s=%s", key, params.get(key))); } // the sig string to sign in the form "endpoint|key1=value1|key2=value2|...." String sig = String.format("%s|%s", endpoint, StringUtils.join(values, '|')); try { Mac mac = Mac.getInstance(HMAC_SHA256); mac.init(keySpec); byte[] result = mac.doFinal(sig.getBytes(UTF_8)); return Hex.encodeHexString(result); } catch (NoSuchAlgorithmException e) { throw new InstagramException("Invalid algorithm name!", e); } catch (InvalidKeyException e) { throw new InstagramException("Invalid key: " + clientSecret, e); } }public List parse(String jsonText) throws RedditParseException { // Parse to a list of things List things = this.parseGeneric(jsonText); // List of comment and submission mixed elements List subreddits = new LinkedList(); // Iterate over things for (Thing t : things) { if (t instanceof Subreddit) { subreddits.add((Subreddit) t); } else { LOGGER.warn("Encountered an unexpected reddit thing (" + t.getKind().value() + "), skipping it."); } } // Return resulting comments list return subreddits; }protected List parseRecursive(JSONObject main) throws RedditParseException { List commentTree = new ArrayList(); // Iterate over the comment tree results JSONArray array = (JSONArray) ((JSONObject) main.get("data")).get("children"); for (Object element : array) { // Get the element JSONObject data = (JSONObject) element; // Make sure it is of the correct kind String kind = safeJsonToString(data.get("kind")); // If it is a comment if (kind != null && kind.equals(Kind.COMMENT.value())) { // Create comment Comment comment = new Comment( (JSONObject) data.get("data") ); // Retrieve replies Object replies = ((JSONObject) data.get("data")).get("replies"); // If it is an JSON object if (replies instanceof JSONObject) { comment.setReplies(parseRecursive( (JSONObject) replies )); // If there are no replies, end with an empty one } else { comment.setReplies(new ArrayList()); } // Add comment to the tree commentTree.add(comment); } // If it is a more if (kind != null && kind.equals(Kind.MORE.value())) { // Add to comment tree commentTree.add(new More((JSONObject) data.get("data"))); } } return commentTree; }public static Long safeJsonToLong(Object obj) { Long longValue = null; try { String str = safeJsonToString(obj); longValue = str != null ? Long.parseLong(str) : null; } catch (NumberFormatException e) { LOGGER.warn("Safe JSON conversion to Long failed", e); } return longValue; }public static Boolean safeJsonToBoolean(Object obj) { String str = safeJsonToString(obj); Boolean booleanValue = str != null ? Boolean.parseBoolean(str) : null; return booleanValue; }public static Double safeJsonToDouble(Object obj) { Double doubleValue = null; try { String str = safeJsonToString(obj); doubleValue = str != null ? Double.parseDouble(str) : null; } catch (NumberFormatException e) { LOGGER.warn("Safe JSON conversion to Double failed", e); } return doubleValue; }public static Integer safeJsonToInteger(Object obj) { Integer intValue = null; try { String str = safeJsonToString(obj); intValue = str != null ? Integer.parseInt(str) : null; } catch (NumberFormatException e) { LOGGER.warn("Safe JSON conversion to Integer failed", e); } return intValue; }public static String printCommentTree(List cs) { StringBuilder builder = new StringBuilder(); for (CommentTreeElement c : cs) { builder.append(printCommentTree(c, 0)); } return builder.toString(); }public void refresh(OAuthJSONAccessTokenResponse token) { this.accessToken = token.getAccessToken(); this.expiration = currentTimeSeconds() + token.getExpiresIn(); this.expirationSpan = token.getExpiresIn(); this.scopes = new RedditTokenCompleteScope(token.getScope()); this.tokenType = token.getParam(PARAM_TOKEN_TYPE); }private void addBasicAuthentication(OAuthClientRequest request, RedditApp app) { String authString = app.getClientID() + ":" + app.getClientSecret(); String authStringEnc = DatatypeConverter.printBase64Binary(authString.getBytes()); request.addHeader(HEADER_AUTHORIZATION, "Basic " + authStringEnc); }private void waitIfNeeded() { // Calculate elapsed milliseconds long elapsed = System.currentTimeMillis() - lastReqTime; // If enough time has elapsed, no need to wait if (elapsed >= interval) { return; } // If not enough time was elapsed, wait the remainder long toWait = interval - elapsed; try { Thread.sleep(toWait); } catch (InterruptedException ie) { LOGGER.warn("Interrupted Exception thrown while politely waiting for remainder of interval", ie); } }public static String formatCommaSeparatedList(List list) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < list.size(); i++) { if (i != 0) { builder.append(","); } builder.append(list.get(i)); } return builder.toString(); }public List parse(String jsonText) throws RedditParseException { // Parse to a list of things List things = this.parseGeneric(jsonText); // List of comment and submission mixed elements List mixedElements = new LinkedList(); // Iterate over things for (Thing t : things) { if (t instanceof Comment) { mixedElements.add((Comment) t); } else if (t instanceof Submission) { mixedElements.add((Submission) t); } else { LOGGER.warn("Encountered an unexpected reddit thing (" + t.getKind().value() + "), skipping it."); } } // Return result return mixedElements; }private Thing parseThing(Kind kind, JSONObject data) { // For a comment if (kind == Kind.COMMENT) { return new Comment(data); // For a submission } else if (kind == Kind.LINK) { return new Submission(data); // For a subreddit } else if (kind == Kind.SUBREDDIT) { return new Subreddit(data); // For a more } else if (kind == Kind.MORE) { return new More(data); // In all other cases (null, or of a different type) } else { return null; } }public void validate(Object response) throws RedditParseException { // Check for null if (response == null) { throw new RedditParseException(); } // Check it is a JSON response if (!(response instanceof JSONObject)) { throw new RedditParseException("not a JSON response"); } // Cast to JSON object JSONObject jsonResponse = ((JSONObject) response); // Check for error if (jsonResponse.get("error") != null) { throw new RedditParseException(JsonUtils.safeJsonToInteger(jsonResponse.get("error"))); } // Check that data exists if (jsonResponse.get("data") == null && jsonResponse.get("json") == null) { throw new RedditParseException("data is missing from listing"); } }private void addAuthorization(HttpRequest request, RedditToken rToken) { request.addHeader("Authorization", rToken.getTokenType() + " " + rToken.getAccessToken()); }private String executeHttpRequest(HttpUriRequest request) { try { // Attempt to do execute request HttpResponse response = httpClient.execute(request); // Return response if successful if (response != null) { return EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (UnsupportedEncodingException uee) { LOGGER.warn("Unsupported Encoding Exception thrown in request", uee); } catch (ClientProtocolException cpe) { LOGGER.warn("Client Protocol Exception thrown in request", cpe); } catch (IOException ioe) { LOGGER.warn("I/O Exception thrown in request", ioe); } return null; }public static > void setClassConf(Class thriftClass, Configuration jobConf) { ThriftUtils.setClassConf(jobConf, LzoThriftB64LineOutputFormat.class, thriftClass); }public static ArrayList findColumnsToRead( Configuration conf, List currFieldIds, ColumnarMetadata storedInfo) throws IOException { ArrayList columnsToRead = Lists.newArrayList(); // first find the required fields ArrayList requiredFieldIds = Lists.newArrayList(); String reqFieldStr = conf.get(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, ""); int numKnownFields = currFieldIds.size(); if (reqFieldStr == null || reqFieldStr.equals("")) { for(int i=0; i= numKnownFields) { throw new IOException("idx " + idx + " is out of range for known fields"); } requiredFieldIds.add(currFieldIds.get(idx)); } } List storedFieldIds = storedInfo.getFieldIdList(); for(int i=0; i < storedFieldIds.size(); i++) { int sid = storedFieldIds.get(i); if (sid > 0 && requiredFieldIds.contains(sid)) { columnsToRead.add(i); } } // unknown fields : the required fields that are not listed in storedFieldIds String unknownFields = ""; for(int rid : requiredFieldIds) { if (!storedFieldIds.contains(rid)) { unknownFields += " " + rid; } } if (unknownFields.length() > 0) { int last = storedFieldIds.size() - 1; LOG.info("unknown fields among required fileds :" + unknownFields); if (storedFieldIds.get(last) != -1) { // not expected throw new IOException("No unknowns column in in input"); } columnsToRead.add(last); } LOG.info(String.format( "reading %d%s out of %d stored columns for %d required columns", columnsToRead.size(), (unknownFields.length() > 0 ? " (including unknowns column)" : ""), storedInfo.getFieldIdList().size(), requiredFieldIds.size())); return columnsToRead; }public static> TypeRef getThriftTypeRef(String thriftClassName) { return ThriftUtils.getTypeRef(getClass(thriftClassName)); }public static Class getClass(String className) { try { return PigContext.resolveClassName(className); } catch (IOException e) { throw new RuntimeException("Could not instantiate " + className, e); } }public static > ThriftConverter newInstance(Class tClass) { return new ThriftConverter(new TypeRef(tClass){}); }private static void verifyWritableClass(Class writableClass, boolean isKeyClass, WritableConverter writableConverter) { Preconditions.checkNotNull(writableClass, "%s Writable class is undefined;" + " WritableConverter of type '%s' does not define default Writable type," + " and no type was specified by user", isKeyClass ? "Key" : "Value", writableConverter .getClass().getName()); }protected DataOutputStream getOutputStream(TaskAttemptContext job) throws IOException, InterruptedException { return LzoUtils.getIndexedLzoOutputStream( HadoopCompat.getConfiguration(job), getDefaultWorkFile(job, LzopCodec.DEFAULT_LZO_EXTENSION)); }public static boolean isUncountable(String word) { for (String w : uncountables_) { if (w.equalsIgnoreCase(word)) { return true; } } return false; }public static String pluralize(String word) { if (isUncountable(word)) { return word; } else { for (Inflection inflection : plurals_) { if (inflection.match(word)) { return inflection.replace(word); } } return word; } }public String replace(String word) { int flags = ignoreCase_ ? Pattern.CASE_INSENSITIVE : 0; return Pattern.compile(pattern_, flags).matcher(word).replaceAll(replacement_); }public boolean match(String word) { int flags = ignoreCase_ ? Pattern.CASE_INSENSITIVE : 0; return Pattern.compile(pattern_, flags).matcher(word).find(); }public static void setOutputFormat(Class realOutputFormatClass, Configuration conf) { conf.setClass("mapred.output.format.class", DeprecatedOutputFormatWrapper.class, org.apache.hadoop.mapred.OutputFormat.class); HadoopUtils.setClassConf(conf, CLASS_CONF_KEY, realOutputFormatClass); }public static LzoW3CLogInputFormat newInstance(final String fieldDefinitionFile) { return new LzoW3CLogInputFormat() { @Override public RecordReader createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { RecordReader reader = new LzoW3CLogRecordReader() { @Override protected String getFieldDefinitionFile() { return fieldDefinitionFile; } }; reader.initialize(split, context); return reader; } }; }public static ProtobufWritable newInstance(Class tClass) { return new ProtobufWritable(new TypeRef(tClass){}); }public static String ordinalize(int n) { int mod100 = n % 100; if (mod100 == 11 || mod100 == 12 || mod100 == 13) { return String.valueOf(n) + "th"; } switch (n % 10) { case 1: return String.valueOf(n) + "st"; case 2: return String.valueOf(n) + "nd"; case 3: return String.valueOf(n) + "rd"; default: return String.valueOf(n) + "th"; } }public static String underscore(String word) { String firstPattern = "([A-Z]+)([A-Z][a-z])"; String secondPattern = "([a-z\\d])([A-Z])"; String replacementPattern = "$1_$2"; // Replace package separator with slash. word = word.replaceAll("\\.", "/"); // Replace $ with two underscores for inner classes. word = word.replaceAll("\\$", "__"); // Replace capital letter with _ plus lowercase letter. word = word.replaceAll(firstPattern, replacementPattern); word = word.replaceAll(secondPattern, replacementPattern); word = word.replace('-', '_'); word = word.toLowerCase(); return word; }public void setPattern(byte[] pattern) { pattern_ = Arrays.copyOf(pattern, pattern.length); borders_ = new int[pattern_.length + 1]; preProcess(); }protected void checkContainerSize(int size) throws TProtocolException { if (size < 0) { throw new TProtocolException("Negative container size: " + size); } if (checkReadLength_ && (readLength_ - size) < 0) { throw new TProtocolException("Remaining message length is " + readLength_ + " but container size in underlying TTransport is set to at least: " + size); } }private void setTypeRef(Configuration conf) { String className = conf.get(CLASS_CONF_KEY); if (className == null) { throw new RuntimeException(CLASS_CONF_KEY + " is not set"); } Class clazz = null; try { clazz = conf.getClassByName(className); } catch (ClassNotFoundException e) { throw new RuntimeException("failed to instantiate class '" + className + "'", e); } typeRef = new TypeRef(clazz){}; }public static void setClassConf(Class protoClass, Configuration jobConf) { Protobufs.setClassConf(jobConf, LzoProtobufB64LineOutputFormat.class, protoClass); }@Override @SuppressWarnings("unchecked") public void putNext(Tuple tuple) throws IOException { json.clear(); if (tuple != null && tuple.size() >= 1) { Map map = (Map) tuple.get(0); if (keysToKeep_ == null) { json.putAll(map); } else { for (Map.Entry entry : map.entrySet()) { if (keysToKeep_.contains(entry.getKey())) { json.put(entry.getKey(), entry.getValue()); } } } } try { writer.write(null, new Text(json.toString())); } catch (InterruptedException e) { // Under what circumstances does this happen? throw new IOException(e); } }public static Message parseMessage(Class klass, InputStream in) { Method parseMethod = parseMethodFor(klass); return parseMessage(parseMethod, in); }public static Message parseMessage(Method parseMethod, InputStream in) { try { return (Message) parseMethod.invoke(null, in); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } }public static Method parseMethodFor(Class klass) { try { return klass.getMethod("parseDelimitedFrom", new Class[] {InputStream.class }); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } }private static void updateJobConfForLocalSettings(JobConf conf) { String localSetCompressionEnabled = conf.get(COMPRESS_ENABLE); if(localSetCompressionEnabled != null) { conf.set(MR_COMPRESS_ENABLE, localSetCompressionEnabled); } String localSetCompressionType = conf.get(COMPRESS_TYPE); if(localSetCompressionType != null) { conf.set(MR_COMPRESS_TYPE, localSetCompressionType); } String localSetCompressionCodec = conf.get(COMPRESS_CODEC); if(localSetCompressionCodec != null) { conf.set(MR_COMPRESS_CODEC, localSetCompressionCodec); } }public static void setColumnNumber(Configuration conf, int columnNum) { assert columnNum > 0; conf.setInt(RCFile.COLUMN_NUMBER_CONF_STR, columnNum); }public static long getDirectorySize(Path path, FileSystem fs, PathFilter filter) throws IOException { PathSizeVisitor visitor = new PathSizeVisitor(); PathFilter composite = new PathFilters.CompositePathFilter( PathFilters.newExcludeDirectoriesFilter(fs.getConf()), filter); walkPath(path, fs, composite, visitor); return visitor.getSize(); }public static void collectPaths(Path path, FileSystem fs, PathFilter filter, final List accumulator) throws IOException { walkPath(path, fs, filter, new PathVisitor() { @Override public void visit(FileStatus fileStatus) { accumulator.add(fileStatus.getPath()); } }); }public static void walkPath(Path path, FileSystem fs, PathFilter filter, PathVisitor visitor) throws IOException { FileStatus fileStatus = fs.getFileStatus(path); if (filter.accept(path)) { visitor.visit(fileStatus); } if (fileStatus.isDir()) { FileStatus[] children = fs.listStatus(path); for (FileStatus childStatus : children) { walkPath(childStatus.getPath(), fs, filter, visitor); } } }private String mapProtoMessageType(TStructDescriptor descriptor, Field field) { return String.format("%s_%s", protoMessageType(descriptor.getThriftClass()), field.getName()); }private Message buildMapEntryMessage(Message.Builder mapBuilder, Field field, Object mapKey, Object mapValue) { FieldDescriptor keyFieldDescriptor = mapBuilder.getDescriptorForType().findFieldByName(MAP_KEY_FIELD_NAME); FieldDescriptor valueFieldDescriptor = mapBuilder.getDescriptorForType().findFieldByName(MAP_VALUE_FIELD_NAME); boolean isKeyStruct = field.getMapKeyField().isStruct(); boolean isValueStruct = field.getMapValueField().isStruct(); Object convertedKey; if (isKeyStruct) { convertedKey = doConvert((TBase) mapKey); } else { convertedKey = sanitizeRawValue(mapKey, field.getMapKeyField()); } Object convertedValue; if (isValueStruct) { convertedValue = doConvert((TBase) mapValue); } else { convertedValue = sanitizeRawValue(mapValue, field.getMapValueField()); } mapBuilder.setField(keyFieldDescriptor, convertedKey); mapBuilder.setField(valueFieldDescriptor, convertedValue); return mapBuilder.build(); }@SuppressWarnings("unchecked") public Message doConvert(TBase thriftObj) { if (thriftObj == null) { return null; } Class> clazz = (Class>) thriftObj.getClass(); checkState(clazz); Message.Builder builder = getBuilder(clazz); TStructDescriptor fieldDesc = TStructDescriptor.getInstance(clazz); int fieldId = 0; for (Field tField : fieldDesc.getFields()) { // don't want to carry over default values from unset fields if (!thriftObj.isSet((F) tField.getFieldIdEnum()) || (!supportNestedObjects && hasNestedObject(tField))) { fieldId++; continue; } // recurse into the object if it's a struct, otherwise just add the field if (supportNestedObjects && tField.getType() == TType.STRUCT) { TBase fieldValue = (TBase) fieldDesc.getFieldValue(fieldId++, thriftObj); Message message = doConvert(fieldValue); if (message != null) { FieldDescriptor protoFieldDesc = builder.getDescriptorForType().findFieldByName( tField.getName()); builder.setField(protoFieldDesc, message); } } else { fieldId = convertField(thriftObj, builder, fieldDesc, fieldId, tField); } } return builder.build(); }@SuppressWarnings("unchecked") public Message convert(T thriftObj) { return doConvert((TBase) Preconditions.checkNotNull(thriftObj, "Can not convert a null object")); }private String resolveMessageTypeName(TStructDescriptor descriptor) throws DescriptorValidationException { String typeName = protoMessageType(descriptor.getThriftClass()); // Anytime we have a new message typeName, we make sure that we have a builder for it. // If not, we create one. DescriptorProtos.DescriptorProto.Builder builder = descriptorBuilderMap.get(typeName); if (builder == null) { builder = DescriptorProtos.DescriptorProto.newBuilder(); builder.setName(typeName); descriptorBuilderMap.put(typeName, builder); doSchemaMapping(builder, descriptor); } return typeName; }private DescriptorProtos.DescriptorProto.Builder mapDescriptorProtoBuilder( Field field, String typeName) throws DescriptorValidationException { DescriptorProtos.DescriptorProto.Builder mapBuilder = DescriptorProtos.DescriptorProto.newBuilder().setName(typeName); Field keyField = field.getMapKeyField(); Field valueField = field.getMapValueField(); DescriptorProtos.FieldDescriptorProto.Builder keyBuilder = mapKeyProtoBuilder(); DescriptorProtos.FieldDescriptorProto.Builder valueBuilder = mapValueProtoBuilder(); setBuilderTypeFromField(keyField, keyBuilder); setBuilderTypeFromField(valueField, valueBuilder); mapBuilder.addField(keyBuilder.build()); mapBuilder.addField(valueBuilder.build()); return mapBuilder; }private Message.Builder mapEntryProtoBuilder(TStructDescriptor descriptor, Field field) { return messageBuilderMap.get(mapProtoMessageType(descriptor, field)).clone(); }public Message.Builder getBuilder(Class> thriftClass) { return messageBuilderMap.get(protoMessageType(thriftClass)).clone(); }public T safeNewInstance() { try { return newInstance(); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(e); } catch (IllegalAccessException e) { throw new IllegalArgumentException(e); } catch (InvocationTargetException e) { throw new IllegalArgumentException(e); } catch (InstantiationException e) { throw new IllegalArgumentException(e); } }@SuppressWarnings("unchecked") public T newInstance() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { if (constructor_ == null) { constructor_ = getRawClass().getConstructor(); } return (T)constructor_.newInstance(); }public static > ThriftWritable newInstance(Class tClass) { return new ThriftWritable(new TypeRef(tClass){}); }public static MapContext newMapContext(Configuration conf, TaskAttemptID taskAttemptID, RecordReader recordReader, RecordWriter recordWriter, OutputCommitter outputCommitter, StatusReporter statusReporter, InputSplit inputSplit) { return (MapContext) newInstance(MAP_CONTEXT_CONSTRUCTOR, conf, taskAttemptID, recordReader, recordWriter, outputCommitter, statusReporter, inputSplit); }public static TaskAttemptContext newTaskAttemptContext( Configuration conf, TaskAttemptID taskAttemptId) { return (TaskAttemptContext) newInstance(TASK_CONTEXT_CONSTRUCTOR, conf, taskAttemptId); }public boolean readNextProtoBytes(BytesWritable writable) throws IOException { byte[] blob = readNextProtoBytes(); if (blob != null) { writable.set(blob, 0, blob.length); return true; } return false; }public byte[] readNextProtoBytes() throws IOException { while (true) { if (!setupNewBlockIfNeeded()) { return null; } int blobIndex = curBlobs_.size() - numLeftToReadThisBlock_; numLeftToReadThisBlock_--; byte[] blob = curBlobs_.get(blobIndex).toByteArray(); if (blob.length == 0 && skipEmptyRecords) { continue; } return blob; } }public boolean readNext(BinaryWritable writable) throws IOException { byte[] blob = readNextProtoBytes(); if (blob != null) { writable.set(protoConverter_.fromBytes(blob)); return true; } return false; }public static ProtobufConverter newInstance(Class protoClass) { return new ProtobufConverter(new TypeRef(protoClass){}); }public static Base64 createStandardBase64() { /* with constructor Base64() in commons-codec-1.4 * encode() inserts a newline after every 76 characters. * Base64(0) disables that incompatibility. */ try { return Base64.class.getConstructor(int.class).newInstance(0); } catch (SecurityException e) { } catch (NoSuchMethodException e) { } catch (IllegalArgumentException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return new Base64(); }@Override public Tuple getNext() throws IOException { if (reader == null) { return null; } Pattern pattern = getPattern(); Matcher matcher = pattern.matcher(""); Object lineObj; String line; Tuple t = null; // Read lines until a match is found, making sure there's no reading past the // end of the assigned byte range. try { while (reader.nextKeyValue()) { lineObj = reader.getCurrentValue(); if (lineObj == null) { break; } line = lineObj.toString(); matcher = matcher.reset(line); // Increment counters for the number of matched and unmatched lines. if (matcher.find()) { incrCounter(LzoBaseRegexLoaderCounters.MatchedRegexLines, 1L); t = tupleFactory_.newTuple(matcher.groupCount()); for (int i = 1; i <= matcher.groupCount(); i++) { if(matcher.group(i) != null) { t.set(i - 1, matcher.group(i)); } else { t.set(i - 1, ""); } } break; } else { incrCounter(LzoBaseRegexLoaderCounters.UnmatchedRegexLines, 1L); // TODO: stop doing this, as it can slow down the job. LOG.debug("No match for line " + line); } // If the read has walked beyond the end of the split, move on. } } catch (InterruptedException e) { int errCode = 6018; String errMsg = "Error while reading input"; throw new ExecException(errMsg, errCode, PigException.REMOTE_ENVIRONMENT, e); } return t; }public static void readFully(InputStream in, ByteArrayOutputStream out, byte[] buffer) { try { int numRead = 0; while ((numRead = in.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, numRead); } out.flush(); } catch (IOException e) { throw new RuntimeException(e); } }public static ResourceFieldSchema createResourceFieldSchema(RequiredField field) throws IOException { ResourceFieldSchema schema = new ResourceFieldSchema().setName(field.getAlias()).setType(field.getType()); List subFields = field.getSubFields(); if (subFields != null && !subFields.isEmpty()) { ResourceFieldSchema[] subSchemaFields = new ResourceFieldSchema[subFields.size()]; int i = 0; for (RequiredField subField : subFields) { subSchemaFields[i++] = createResourceFieldSchema(subField); } ResourceSchema subSchema = new ResourceSchema(); subSchema.setFields(subSchemaFields); schema.setSchema(subSchema); } return schema; }public static byte evaluateDelimiter(String inputDelimiter) { if (inputDelimiter.length() == 1) { return inputDelimiter.getBytes()[0]; } else if (inputDelimiter.length() > 1 && inputDelimiter.charAt(0) == '\\') { switch (inputDelimiter.charAt(1)) { case 't': return (byte)'\t'; case 'x': case 'u': return Integer.valueOf(inputDelimiter.substring(2)).byteValue(); default: throw new IllegalArgumentException("Unknown delimiter " + inputDelimiter); } } else { throw new IllegalArgumentException("LzoTokenizedStorage delimeter must be a single character"); } }public String[] getLocations() throws IOException, InterruptedException { if (locations == null) { Map hosts = new HashMap(); for (InputSplit s : splits) { String[] hints = s.getLocations(); if (hints != null) { for (String host : hints) { Integer value = hosts.get(host); if (value == null) { value = 0; } value++; hosts.put(host, value); } } } if (hosts.size() < 5) { locations = hosts.keySet().toArray(new String[hosts.size()]); } else { Queue> queue = new PriorityQueue>(hosts.size(), new Comparator>() { public int compare(Pair o1, Pair o2) { return -o1.getSecond().compareTo(o2.getSecond()); } }); for (Map.Entry entry : hosts.entrySet()) { queue.add(new Pair(entry.getKey(), entry.getValue())); } locations = new String[] { queue.remove().getFirst(), queue.remove().getFirst(), queue.remove().getFirst(), queue.remove().getFirst(), queue.remove().getFirst() }; } } return locations; }public void add(InputSplit split) throws IOException, InterruptedException { splits.add(split); totalSplitSizes += split.getLength(); locations = null; }public static Path[] getInputPaths(Configuration conf) { String[] pathStrs = Preconditions.checkNotNull(conf.getStrings(INPUT_PATHS_KEY), "You must call LuceneIndexInputFormat.setInputPaths()"); Path[] paths = new Path[pathStrs.length]; for (int i = 0; i < pathStrs.length; i++) { paths[i] = new Path(pathStrs[i]); } return paths; }public static void setInputPaths(List paths, Configuration conf) throws IOException { Preconditions.checkNotNull(paths); Preconditions.checkArgument(!paths.isEmpty()); String[] pathStrs = new String[paths.size()]; int i = 0; for (Path p : paths) { FileSystem fs = p.getFileSystem(conf); pathStrs[i++] = fs.makeQualified(p).toString(); } conf.setStrings(INPUT_PATHS_KEY, pathStrs); }protected PriorityQueue findSplits(Configuration conf) throws IOException { PriorityQueue splits = new PriorityQueue(); List indexDirs = Lists.newLinkedList(); // find all indexes nested under all the input paths // (which happen to be directories themselves) for (Path path : inputPaths) { HdfsUtils.collectPaths(path, path.getFileSystem(conf), indexDirPathFilter, indexDirs); } // compute the size of each index // and create a single split per index for (Path indexDir : indexDirs) { long size = HdfsUtils.getDirectorySize(indexDir, indexDir.getFileSystem(conf)); splits.add(new LuceneIndexInputSplit(Lists.newLinkedList(Arrays.asList(indexDir)), size)); } return splits; }public static void setCombinedInputFormatDelegate(Configuration conf, Class clazz) { HadoopUtils.setClassConf(conf, COMBINED_INPUT_FORMAT_DELEGATE, clazz); }private static TBase newTInstance(Class tClass) { try { return (TBase) tClass.newInstance(); } catch (Exception e) { // not expected. throw new RuntimeException(e); } }@SuppressWarnings("unchecked") public static Object toThriftValue(Field thriftField, Object pigValue) { try { switch (thriftField.getType()) { case TType.BOOL: return Boolean.valueOf(((Integer)pigValue) != 0); case TType.BYTE : return ((Integer)pigValue).byteValue(); case TType.I16 : return Short.valueOf(((Integer)pigValue).shortValue()); case TType.STRING: return toStringType(pigValue); case TType.STRUCT: return toThrift(thriftField.gettStructDescriptor(), (Tuple)pigValue); case TType.MAP: return toThriftMap(thriftField, (Map)pigValue); case TType.SET: return toThriftSet(thriftField.getSetElemField(), (DataBag) pigValue); case TType.LIST: return toThriftList(thriftField.getListElemField(), (DataBag)pigValue); case TType.ENUM: return toThriftEnum(thriftField, (String) pigValue); default: // standard types : I32, I64, DOUBLE, etc. return pigValue; } } catch (Exception e) { // mostly a schema mismatch. LOG.warn(String.format( "Failed to set field '%s' of type '%s' with value '%s' of type '%s'", thriftField.getName(), ThriftUtils.getFieldValueType(thriftField).getName(), pigValue, pigValue.getClass().getName()), e); } return null; }@SuppressWarnings("unchecked") private static TBase toThrift(TStructDescriptor tDesc, Tuple tuple) { int size = tDesc.getFields().size(); int tupleSize = tuple.size(); @SuppressWarnings("rawtypes") TBase tObj = newTInstance(tDesc.getThriftClass()); for(int i = 0; i map = (Map)value; proto.writeByte(innerField.getType()); proto.writeByte(valueField.getType()); proto.writeI32(map.size()); for(Entry entry : map.entrySet()) { writeSingleFieldNoTag(proto, innerField, entry.getKey()); writeSingleFieldNoTag(proto, valueField, entry.getValue()); } } else { // SET or LIST Collection coll = (Collection)value; proto.writeByte(innerField.getType()); proto.writeI32(coll.size()); for(Object v : coll) { writeSingleFieldNoTag(proto, innerField, v); } } }public static Class getFieldValueType(Field field) { switch (field.getType()) { case TType.BOOL: return Boolean.class; case TType.BYTE: return Byte.class; case TType.DOUBLE: return Double.class; case TType.ENUM: return field.getEnumClass(); case TType.I16: return Short.class; case TType.I32: return Integer.class; case TType.I64: return Long.class; case TType.LIST: return List.class; case TType.MAP: return Map.class; case TType.SET: return Set.class; case TType.STOP: return null; case TType.STRING: return String.class; case TType.STRUCT: return field.gettStructDescriptor().getThriftClass(); case TType.VOID: return null; } return null; }public static M getFieldValue(Class containingClass, String fieldName, Class fieldClass) { return getFieldValue(containingClass, null, fieldName, fieldClass); }public static M getFieldValue(Object containingObject, String fieldName, Class fieldClass) { return getFieldValue(containingObject.getClass(), containingObject, fieldName, fieldClass); }private static void verifyAncestry(Class tClass) { if (!TBase.class.isAssignableFrom(tClass)) { Utils.ensureClassLoaderConsistency(TBase.class, tClass.getClassLoader()); throw new ClassCastException(tClass.getName() + " is not a Thrift class"); } }@SuppressWarnings("unchecked") public static List readStringListFromConfAsBase64(String key, Configuration conf) { String b64List = conf.get(key); if (b64List == null) { return null; } List strings = Lists.newArrayList(); for (String b64 : COMMA_SPLITTER.split(b64List)) { byte[] bytes = Base64.decodeBase64(b64.getBytes(Charsets.UTF_8)); strings.add(new String(bytes, Charsets.UTF_8)); } return strings; }public static void writeStringListToConfAsBase64(String key, List list, Configuration conf) { Preconditions.checkNotNull(list); Iterator iter = list.iterator(); StringBuilder sb = new StringBuilder(); while(iter.hasNext()) { byte[] bytes = Base64.encodeBase64(iter.next().getBytes(Charsets.UTF_8), false); sb.append(new String(bytes, Charsets.UTF_8)); if (iter.hasNext()) { sb.append(','); } } conf.set(key, sb.toString()); }@SuppressWarnings("unchecked") public static List readStringListFromConfAsJson(String key, Configuration conf) { String json = conf.get(key); if (json == null) { return null; } return Lists.newArrayList(((JSONArray) JSONValue.parse(json))); }public static void writeStringListToConfAsJson(String key, List list, Configuration conf) { Preconditions.checkNotNull(list); conf.set(key, JSONArray.toJSONString(list)); }public static void setClassConf(Configuration conf, String configKey, Class clazz) { String existingClass = conf.get(configKey); String className = clazz.getName(); if (existingClass != null && !existingClass.equals(className)) { throw new RuntimeException( "Already registered a different thriftClass for " + configKey + ". old: " + existingClass + " new: " + className); } else { conf.set(configKey, className); } }public static void setInputFormat(Class realInputFormatClass, Configuration conf) { conf.setClass("mapred.input.format.class", DeprecatedInputFormatWrapper.class, org.apache.hadoop.mapred.InputFormat.class); HadoopUtils.setClassConf(conf, CLASS_CONF_KEY, realInputFormatClass); }private byte[] serialize() { if (messageBytes == null && message != null) { checkConverter(); messageBytes = converter.toBytes(message); if (messageBytes == null) { // should we throw an IOException instead? LOG.warn("Could not serialize " + message.getClass()); } else { message = null; // so that message and messageBytes don't go out of // sync. } } return messageBytes; }@Override public float getProgress() { if (start_ == end_) { return 0.0f; } else { return Math.min(1.0f, (pos_ - start_) / (float) (end_ - start_)); } }public static TypeRef getTypeRef(String protoClassName) { return new TypeRef(getProtobufClass(protoClassName)){}; }public static boolean useDynamicProtoMessage(Class protoClass) { return protoClass == null || protoClass.getCanonicalName().equals(DynamicMessage.class.getCanonicalName()); }public static PathFilter newIndexDirFilter(Configuration conf) { return new PathFilters.CompositePathFilter( PathFilters.newExcludeFilesFilter(conf), PathFilters.EXCLUDE_HIDDEN_PATHS_FILTER, new PathFilter() { @Override public boolean accept(Path path) { return path.getName().startsWith("index-"); } } ); }static private Map extractEnumMap(Class enumClass) { ImmutableMap.Builder builder = ImmutableMap.builder(); for(TEnum e : enumClass.getEnumConstants()) { builder.put(e.toString(), e); } return builder.build(); }public static TStructDescriptor getInstance(Class> tClass) { synchronized (structMap) { TStructDescriptor desc = structMap.get(tClass); if (desc == null) { desc = new TStructDescriptor(); desc.tClass = tClass; structMap.put(tClass, desc); desc.build(tClass); } return desc; } }private StringBuffer singleFieldToPigScript(FieldDescriptor fieldDescriptor, int numTabs, boolean isLast) throws FrontendException { assert fieldDescriptor.getType() != FieldDescriptor.Type.MESSAGE : "singleFieldToPigScript called with field of type " + fieldDescriptor.getType(); if (fieldDescriptor.isRepeated()) { return new StringBuffer().append(tabs(numTabs)).append(fieldDescriptor.getName()).append("_bag: bag {").append("\n") .append(tabs(numTabs + 1)).append(fieldDescriptor.getName()).append("_tuple: tuple (").append("\n") .append(tabs(numTabs + 2)).append(fieldDescriptor.getName()).append(": ").append(getPigScriptDataType(fieldDescriptor)).append("\n") .append(tabs(numTabs + 1)).append(")").append("\n") .append(tabs(numTabs)).append("}").append(isLast ? "" : ",").append("\n"); } else { return new StringBuffer().append(tabs(numTabs)).append(fieldDescriptor.getName()).append(": ") .append(getPigScriptDataType(fieldDescriptor)).append(isLast ? "" : ",").append("\n"); } }private StringBuffer messageToPigScript(FieldDescriptor fieldDescriptor, int numTabs, boolean isLast) throws FrontendException { assert fieldDescriptor.getType() == FieldDescriptor.Type.MESSAGE : "messageToPigScript called with field of type " + fieldDescriptor.getType(); if (fieldDescriptor.isRepeated()) { return new StringBuffer().append(tabs(numTabs)).append(fieldDescriptor.getName()).append(": bag {").append("\n") .append(tabs(numTabs + 1)).append(fieldDescriptor.getName()).append("_tuple: tuple (").append("\n") .append(toPigScriptInternal(fieldDescriptor.getMessageType(), numTabs + 2)) .append(tabs(numTabs + 1)).append(")").append("\n") .append(tabs(numTabs)).append("}").append(isLast ? "" : ",").append("\n"); } else { return new StringBuffer().append(tabs(numTabs)).append(fieldDescriptor.getName()).append(": tuple (").append("\n") .append(toPigScriptInternal(fieldDescriptor.getMessageType(), numTabs + 1)) .append(tabs(numTabs)).append(")").append(isLast ? "" : ",").append("\n"); } }private StringBuffer toPigScriptInternal(Descriptor msgDescriptor, int numTabs) { StringBuffer sb = new StringBuffer(); try { // Walk through all the possible fields in the message. for (FieldDescriptor fieldDescriptor : msgDescriptor.getFields()) { // We have to add a comma after every line EXCEPT for the last, or Pig gets mad. boolean isLast = (fieldDescriptor == msgDescriptor.getFields().get(msgDescriptor.getFields().size() - 1)); if (fieldDescriptor.getType() == FieldDescriptor.Type.MESSAGE) { sb.append(messageToPigScript(fieldDescriptor, numTabs + 1, isLast)); } else { sb.append(singleFieldToPigScript(fieldDescriptor, numTabs + 1, isLast)); } } } catch (FrontendException e) { LOG.warn("Could not convert descriptor " + msgDescriptor + " to pig script", e); } return sb; }public String toPigScript(Descriptor msgDescriptor, String loaderClassName) { StringBuffer sb = new StringBuffer(); final int initialTabOffset = 3; sb.append("raw_data = load '$INPUT_FILES' using " + loaderClassName + "()").append("\n"); sb.append(tabs(initialTabOffset)).append("as (").append("\n"); sb.append(toPigScriptInternal(msgDescriptor, initialTabOffset)); sb.append(tabs(initialTabOffset)).append(");").append("\n").append("\n"); return sb.toString(); }private FieldSchema singleFieldToFieldSchema(FieldDescriptor fieldDescriptor) throws FrontendException { assert fieldDescriptor.getType() != FieldDescriptor.Type.MESSAGE : "singleFieldToFieldSchema called with field of type " + fieldDescriptor.getType(); if (fieldDescriptor.isRepeated()) { Schema itemSchema = new Schema(); itemSchema.add(new FieldSchema(fieldDescriptor.getName(), null, getPigDataType(fieldDescriptor))); Schema itemTupleSchema = new Schema(); itemTupleSchema.add(new FieldSchema(fieldDescriptor.getName() + "_tuple", itemSchema, DataType.TUPLE)); return new FieldSchema(fieldDescriptor.getName() + "_bag", itemTupleSchema, DataType.BAG); } else { return new FieldSchema(fieldDescriptor.getName(), null, getPigDataType(fieldDescriptor)); } }private FieldSchema messageToFieldSchema(FieldDescriptor fieldDescriptor) throws FrontendException { assert fieldDescriptor.getType() == FieldDescriptor.Type.MESSAGE : "messageToFieldSchema called with field of type " + fieldDescriptor.getType(); Schema innerSchema = toSchema(fieldDescriptor.getMessageType()); if (fieldDescriptor.isRepeated()) { Schema tupleSchema = new Schema(); tupleSchema.add(new FieldSchema(fieldDescriptor.getName() + "_tuple", innerSchema, DataType.TUPLE)); return new FieldSchema(fieldDescriptor.getName(), tupleSchema, DataType.BAG); } else { return new FieldSchema(fieldDescriptor.getName(), innerSchema, DataType.TUPLE); } }public Schema toSchema(Descriptor msgDescriptor) { Schema schema = new Schema(); try { // Walk through all the possible fields in the message. for (FieldDescriptor fieldDescriptor : msgDescriptor.getFields()) { if (fieldDescriptor.getType() == FieldDescriptor.Type.MESSAGE) { schema.add(messageToFieldSchema(fieldDescriptor)); } else { schema.add(singleFieldToFieldSchema(fieldDescriptor)); } } } catch (FrontendException e) { LOG.warn("Could not convert descriptor " + msgDescriptor + " to schema", e); } return schema; }private Object coerceToPigTypes(FieldDescriptor fieldDescriptor, Object fieldValue) { if (fieldDescriptor.getType() == FieldDescriptor.Type.ENUM && fieldValue != null) { EnumValueDescriptor enumValueDescriptor = (EnumValueDescriptor)fieldValue; return enumValueDescriptor.getName(); } else if (fieldDescriptor.getType() == FieldDescriptor.Type.BOOL && fieldValue != null) { Boolean boolValue = (Boolean)fieldValue; return new Integer(boolValue ? 1 : 0); } else if (fieldDescriptor.getType() == FieldDescriptor.Type.BYTES && fieldValue != null) { ByteString bsValue = (ByteString)fieldValue; return new DataByteArray(bsValue.toByteArray()); } return fieldValue; }@SuppressWarnings("unchecked") protected Object singleFieldToTuple(FieldDescriptor fieldDescriptor, Object fieldValue) { assert fieldDescriptor.getType() != FieldDescriptor.Type.MESSAGE : "messageToFieldSchema called with field of type " + fieldDescriptor.getType(); if (fieldDescriptor.isRepeated()) { // The protobuf contract is that if the field is repeated, then the object returned is actually a List // of the underlying datatype, which in this case is a "primitive" like int, float, String, etc. // We have to make a single-item tuple out of it to put it in the bag. List fieldValueList = (List) (fieldValue != null ? fieldValue : Collections.emptyList()); DataBag bag = new NonSpillableDataBag(fieldValueList.size()); for (Object singleFieldValue : fieldValueList) { Object nonEnumFieldValue = coerceToPigTypes(fieldDescriptor, singleFieldValue); Tuple innerTuple = tupleFactory_.newTuple(1); try { innerTuple.set(0, nonEnumFieldValue); } catch (ExecException e) { // not expected throw new RuntimeException(e); } bag.add(innerTuple); } return bag; } else { return coerceToPigTypes(fieldDescriptor, fieldValue); } }@SuppressWarnings("unchecked") protected Object messageToTuple(FieldDescriptor fieldDescriptor, Object fieldValue) { if (fieldValue == null) { // protobufs unofficially ensures values are not null. just in case: return null; } assert fieldDescriptor.getType() == FieldDescriptor.Type.MESSAGE : "messageToTuple called with field of type " + fieldDescriptor.getType(); if (fieldDescriptor.isRepeated()) { // The protobuf contract is that if the field is repeated, then the object returned is actually a List // of the underlying datatype, which in this case is a nested message. List messageList = (List) (fieldValue != null ? fieldValue : Lists.newArrayList()); DataBag bag = new NonSpillableDataBag(messageList.size()); for (Message m : messageList) { bag.add(new ProtobufTuple(m)); } return bag; } else { return new ProtobufTuple((Message)fieldValue); } }public Tuple toTuple(Message msg) { if (msg == null) { // Pig tuples deal gracefully with nulls. // Also, we can be called with null here in recursive calls. return null; } Descriptor msgDescriptor = msg.getDescriptorForType(); Tuple tuple = tupleFactory_.newTuple(msgDescriptor.getFields().size()); int curField = 0; try { // Walk through all the possible fields in the message. for (FieldDescriptor fieldDescriptor : msgDescriptor.getFields()) { // Get the set value, or the default value, or null. Object fieldValue = msg.getField(fieldDescriptor); if (fieldDescriptor.getType() == FieldDescriptor.Type.MESSAGE) { tuple.set(curField++, messageToTuple(fieldDescriptor, fieldValue)); } else { tuple.set(curField++, singleFieldToTuple(fieldDescriptor, fieldValue)); } } } catch (ExecException e) { LOG.warn("Could not convert msg " + msg + " to tuple", e); } return tuple; }@Override public float getProgress() { if (numIndexes < 1) { return 1.0f; } float indexProgress = (float) currentIndexPathIter.previousIndex() / (float) numIndexes; float queriesProgress = 1.0f; if (queries.size() > 0) { queriesProgress = (float) currentQueryIter.previousIndex() / (float) queries.size(); } queriesProgress *= 1.0f / numIndexes; return indexProgress + queriesProgress; }protected IndexReader openIndex(Path path, Configuration conf) throws IOException { return DirectoryReader.open(new LuceneHdfsDirectory(path, path.getFileSystem(conf))); }public static void stringifySchema(StringBuilder sb, Schema schema, byte type, StringBuilder prefix) throws FrontendException{ // this is a modified version of {@link Schema#stringifySchema(StringBuilder, Schema, byte)} if (type == DataType.TUPLE) { sb.append("(") ; } else if (type == DataType.BAG) { sb.append("{") ; } prefix.append(" "); sb.append("\n").append(prefix); if (schema == null) { sb.append("null") ; } else { boolean isFirst = true ; for (int i=0; i< schema.size() ;i++) { if (!isFirst) { sb.append(",\n").append(prefix); } else { isFirst = false ; } FieldSchema fs = schema.getField(i) ; if(fs == null) { sb.append("null"); continue; } if (fs.alias != null) { sb.append(fs.alias); sb.append(": "); } if (DataType.isAtomic(fs.type)) { sb.append(DataType.findTypeName(fs.type)) ; } else if ( (fs.type == DataType.TUPLE) || (fs.type == DataType.BAG) ) { // safety net if (schema != fs.schema) { stringifySchema(sb, fs.schema, fs.type, prefix) ; } else { throw new AssertionError("Schema refers to itself " + "as inner schema") ; } } else if (fs.type == DataType.MAP) { sb.append(DataType.findTypeName(fs.type) + "["); if (fs.schema!=null) stringifySchema(sb, fs.schema, fs.type, prefix); sb.append("]"); } else { sb.append(DataType.findTypeName(fs.type)) ; } } } prefix.setLength(prefix.length()-2); sb.append("\n").append(prefix); if (type == DataType.TUPLE) { sb.append(")") ; } else if (type == DataType.BAG) { sb.append("}") ; } }public static String toPigScript(Class> thriftClass, Class pigLoader) { StringBuilder sb = new StringBuilder(); /* we are commenting out explicit schema specification. The schema is * included mainly to help the readers of the pig script. Pig learns the * schema directly from the loader. * If explicit schema is not commented, we might have surprising results * when a Thrift class (possibly in control of another team) changes, * but the Pig script is not updated. Commenting it out avoids this. */ StringBuilder prefix = new StringBuilder(" -- "); sb.append("raw_data = load '$INPUT_FILES' using ") .append(pigLoader.getName()) .append("('") .append(thriftClass.getName()) .append("');\n") .append(prefix) .append("as "); prefix.append(" "); try { stringifySchema(sb, toSchema(thriftClass), DataType.TUPLE, prefix); } catch (FrontendException e) { throw new RuntimeException(e); } sb.append("\n"); return sb.toString(); }public static void setConversionProperties(Configuration conf) { if (conf != null) { useEnumId = conf.getBoolean(USE_ENUM_ID_CONF_KEY, false); LOG.debug("useEnumId is set to " + useEnumId); } }private void _appendCharacterEscape(char esc, char ch) throws IOException, JsonGenerationException { if ((_outputTail + 1) >= _outputEnd) { _flushBuffer(); } _outputBuffer[_outputTail++] = esc; _outputBuffer[_outputTail++] = ch; }private int _prependOrWrite(char[] buffer, int ptr, char esc) throws IOException, JsonGenerationException { if (ptr > 0) { // fits, just prepend buffer[--ptr] = esc; } else { // won't fit, write _writer.write(esc); } return ptr; }private void _writeString(char[] text, int offset, int len) throws IOException, JsonGenerationException { /* Let's just find longest spans of non-escapable * content, and for each see if it makes sense * to copy them, or write through */ len += offset; // -> len marks the end from now on while (offset < len) { int start = offset; while (true) { char c = text[offset]; if (c == '!' || c == '\'') { break; } if (++offset >= len) { break; } } // Short span? Better just copy it to buffer first: int newAmount = offset - start; if (newAmount < SHORT_WRITE) { // Note: let's reserve room for escaped char (up to 6 chars) if ((_outputTail + newAmount) > _outputEnd) { _flushBuffer(); } if (newAmount > 0) { System.arraycopy(text, start, _outputBuffer, _outputTail, newAmount); _outputTail += newAmount; } } else { // Nope: better just write through _flushBuffer(); _writer.write(text, start, newAmount); } // Was this the end? if (offset >= len) { // yup break; } // Nope, need to escape the char. char c = text[offset++]; _appendCharacterEscape('!', c); } }public static boolean isIdStrict(char[] chars, int offset, int len) { if (len == 0) { return false; } int end = offset + len; if (!isIdStartStrict(chars[offset++])) { return false; } while (offset < end) { if (!isIdCharStrict(chars[offset++])) { return false; } } return true; }public static boolean isIdStrict(String string) { int len = string.length(); if (len == 0) { return false; } if (!isIdStartStrict(string.charAt(0))) { return false; } for (int i = 1; i < len; i++) { if (!isIdCharStrict(string.charAt(i))) { return false; } } return true; }protected void _matchToken(String matchStr, int i) throws IOException, JsonParseException { final int len = matchStr.length(); do { if (_inputPtr >= _inputEnd) { if (!loadMore()) { _reportInvalidEOFInValue(); } } if (_inputBuffer[_inputPtr] != matchStr.charAt(i)) { _reportInvalidToken(matchStr.substring(0, i), "'null', 'true', 'false' or NaN"); } ++_inputPtr; } while (++i < len); // but let's also ensure we either get EOF, or non-alphanum char... if (_inputPtr >= _inputEnd) { if (!loadMore()) { return; } } char c = _inputBuffer[_inputPtr]; if (c < '0' || c == ')') { // expected/allowed chars return; } // if letter, it's a problem tho if (IdentifierUtils.isIdCharLenient(c)) { _reportInvalidToken(matchStr.substring(0, i), "'null', 'true', 'false' or NaN"); } }protected void _skipString() throws IOException, JsonParseException { _tokenIncomplete = false; int inputPtr = _inputPtr; int inputLen = _inputEnd; char[] inputBuffer = _inputBuffer; while (true) { if (inputPtr >= inputLen) { _inputPtr = inputPtr; if (!loadMore()) { _reportInvalidEOF(": was expecting closing quote for a string value"); } inputPtr = _inputPtr; inputLen = _inputEnd; } char c = inputBuffer[inputPtr++]; if (c == INT_APOSTROPHE) { _inputPtr = inputPtr; break; } else if (c == '!') { _inputPtr = inputPtr; _decodeEscaped(); inputPtr = _inputPtr; inputLen = _inputEnd; } } }protected JsonToken _handleUnexpectedValue(int i) throws IOException, JsonParseException { // Most likely an error, unless we are to allow single-quote-strings switch (i) { case 'N': _matchToken("NaN", 1); if (isEnabled(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS)) { return resetAsNaN("NaN", Double.NaN); } _reportError("Non-standard token 'NaN': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); break; case '+': // note: '-' is taken as number if (_inputPtr >= _inputEnd) { if (!loadMore()) { _reportInvalidEOFInValue(); } } return _handleInvalidNumberStart(_inputBuffer[_inputPtr++], false); } _reportUnexpectedChar(i, "expected a valid value (number, String, array, object, 'true', 'false' or 'null')"); return null; }protected String _parseUnquotedFieldName(int i) throws IOException, JsonParseException { // Also: first char must be a valid name char, but NOT be number boolean firstOk = IdentifierUtils.isIdStartLenient(i); if (!firstOk) { _reportUnexpectedChar(i, "was expecting either valid name character (for unquoted name) or single-quote (for quoted) to start field name"); } int ptr = _inputPtr; int hash = 0; final int inputLen = _inputEnd; if (ptr < inputLen) { do { int ch = _inputBuffer[ptr]; if (!IdentifierUtils.isIdCharLenient(ch)) { int start = _inputPtr-1; // -1 to bring back first char _inputPtr = ptr; return _symbols.findSymbol(_inputBuffer, start, ptr - start, hash); } hash = (hash * 31) + ch; ++ptr; } while (ptr < inputLen); } int start = _inputPtr-1; _inputPtr = ptr; return _parseUnquotedFieldName2(start, hash); }private char _verifyNoLeadingZeroes() throws IOException, JsonParseException { // Ok to have plain "0" if (_inputPtr >= _inputEnd && !loadMore()) { return '0'; } char ch = _inputBuffer[_inputPtr]; // if not followed by a number (probably '.'); return zero as is, to be included if (ch < '0' || ch > '9') { return '0'; } if (!isEnabled(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS)) { reportInvalidNumber("Leading zeroes not allowed"); } // if so, just need to skip either all zeroes (if followed by number); or all but one (if non-number) ++_inputPtr; // Leading zero to be skipped if (ch == INT_0) { while (_inputPtr < _inputEnd || loadMore()) { ch = _inputBuffer[_inputPtr]; if (ch < '0' || ch > '9') { // followed by non-number; retain one zero return '0'; } ++_inputPtr; // skip previous zero if (ch != '0') { // followed by other number; return break; } } } return ch; }private Method getParseFromMethod(Class type) throws NoSuchMethodException { if (parseFromMethod == null) { parseFromMethod = type.getMethod("parseFrom", byte[].class); } return parseFromMethod; }public static Kryo addDefaultSerializers(Kryo kryo) { ArrayListSubListSerializer.addDefaultSerializer(kryo); AbstractListSubListSerializer.addDefaultSerializer(kryo); JavaUtilSubListSerializer.addDefaultSerializer(kryo); return kryo; }private void notifyListener(ChangeNotification changeNotification, boolean newListener) { lock.lock(); try { checkNotNull(changeNotification, "changeNotification"); final Listener listener = listenerRef.get(); if (listener != null) { try { final boolean notified = listenerNotified.getAndSet(true); if (!(newListener && notified)) { listener.onChange(changeNotification); } } catch (Throwable e) { log.error("Change notification listener threw exception", e); } } } finally { lock.unlock(); } }@Override public void beforeMethodSent(final MethodCallBuilder methodBuilder) { if (methodBuilder.getOriginatingRequest() == null) { final Optional> request = requestContext.getRequest(); if (request.isPresent()) { methodBuilder.setOriginatingRequest(request.get()); } } }public long reduceBy(Object function, String name) { return Lng.reduceBy(values, end, function, name); }@Override public Long set(int index, Long element) { long oldValue = values[index]; values[index] = element; return oldValue; }public boolean addArray(long... newValues) { if (end + newValues.length >= values.length) { values = Lng.grow(values, (values.length + newValues.length) * 2); } System.arraycopy(newValues, 0, values, end, newValues.length); end += newValues.length; return true; }@SuppressWarnings("UnusedReturnValue") public StatList add(int integer) { if (end + 1 >= values.length) { values = Lng.grow(values); } values[end] = integer; end++; return this; }@Override public boolean add(Long integer) { if (end + 1 >= values.length) { values = Lng.grow(values); } values[end] = integer; end++; return true; }private boolean addRequestToCheckForTimeouts(final Request request) { String key = Str.add("" + request.id(), "|", request.returnAddress()); this.outstandingRequestMap.put(key, request); return outstandingRequestMap.size() < numberOfOutstandingRequests; }@Override public void handleResponseFromServiceToHttpResponse(final Response response, final HttpRequest originatingRequest) { final String key = Str.add("" + originatingRequest.id(), "|", originatingRequest.returnAddress()); this.outstandingRequestMap.remove(key); if (response.wasErrors()) { handleError(response, originatingRequest); } else { if (response.body() instanceof HttpResponse) { writeHttpResponse(originatingRequest.getReceiver(), ((HttpResponse) response.body())); } else { final RequestMetaData requestMetaData = metaDataProviderMap .get(RequestMethod.valueOf(originatingRequest.getMethod())).get(originatingRequest.address()); final ServiceMethodMeta serviceMethodMeta = requestMetaData.getMethod(); final int responseCode = serviceMethodMeta.getResponseCode(); MultiMap headers = response.headers(); if (requestMetaData.getRequest().hasResponseHeaders()) { if (response.headers() == MultiMap.EMPTY) { headers = new MultiMapImpl<>(); } else { headers = response.headers(); } headers.putAllCopyLists(requestMetaData.getRequest().getResponseHeaders()); } writeResponse(originatingRequest.getReceiver(), responseCode == -1 ? HttpStatus.OK : responseCode, serviceMethodMeta.getContentType(), jsonMapper.toJson(response.body()), headers); } } }@Override public void handleRestCall(final HttpRequest request) { final List errorList = new ArrayList<>(0); final MethodCall methodCall = standardRequestTransformer.transform(request, errorList); if (methodCall != null && errorList.size() == 0) { if (!addRequestToCheckForTimeouts(request)) { handleOverflow(request); return; } sendMethodToServiceBundle(methodCall); } else { if (!request.isHandled()) { handleErrorConverting(request, errorList, methodCall); } return; } final RequestMetaData requestMetaData = metaDataProviderMap .get(RequestMethod.valueOf(request.getMethod())).get(request.address()); final ServiceMethodMeta serviceMethod = requestMetaData.getMethod(); if (serviceMethod.getMethodAccess().returnType() == void.class && !serviceMethod.hasCallBack()) { request.handled(); final int responseCode = serviceMethod.getResponseCode(); writeResponse(request.getReceiver(), responseCode == -1 ? HttpStatus.ACCEPTED : responseCode, serviceMethod.getContentType(), "\"success\"", requestMetaData.getRequest().getResponseHeaders()); } }private void extractHeaders(final HttpRequest httpRequest) { if (headersToAddToLoggingMappingDiagnosticsContext.size() > 0) { final MultiMap headers = httpRequest.getHeaders(); headersToAddToLoggingMappingDiagnosticsContext.forEach(header -> { String value = headers.getFirst(header); if (!Str.isEmpty(value)) { MDC.put(REQUEST_HEADER_PREFIX + header, value); } }); } }private void extractRequestInfoAndPutItIntoMappedDiagnosticContext(final HttpRequest httpRequest) { MDC.put(REQUEST_URI, httpRequest.getUri()); MDC.put(REQUEST_REMOTE_ADDRESS, httpRequest.getRemoteAddress()); MDC.put(REQUEST_HTTP_METHOD, httpRequest.getMethod()); MDC.put(REQUEST_ID, Long.toString(httpRequest.getMessageId())); extractHeaders(httpRequest); }@Override public boolean before(final MethodCall methodCall) { final Optional httpRequest = findHttpRequest(methodCall); if (httpRequest.isPresent()) { extractRequestInfoAndPutItIntoMappedDiagnosticContext(httpRequest.get()); } return true; }private void registerHandlerCallbackForClient(final MethodCall methodCall, final Callback handler) { final HandlerKey handlerKey = new HandlerKey(methodCall.returnAddress(), methodCall.address(), methodCall.id(), methodCall.timestamp()); if (debug) { if (handlers.containsKey(handlerKey)) { logger.debug("DUPLICATE HANDLERS {}", handlerKey); } } handlers.put(handlerKey, handler); }public static MicroserviceConfig readConfig(final String serviceName) { final Logger logger = LoggerFactory.getLogger(MicroserviceConfig.class); if (new File(resourceLocation).exists()) { final String json = IO.read(resourceLocation); return JsonFactory.fromJson(json, MicroserviceConfig.class); } else if (resourceLocationEnv != null && new File(resourceLocationEnv).exists()) { final String json = IO.read(resourceLocationEnv); return JsonFactory.fromJson(json, MicroserviceConfig.class); } else { logger.info("Reading config from classpath as it is not found on file system"); final String qbitEnv = System.getenv("QBIT_ENV"); final String resourceLocationOnClasspath = qbitEnv != null && !qbitEnv.isEmpty() ? serviceName + "_" + qbitEnv + ".json" : serviceName + ".json"; final String json = IO.read(Thread.currentThread().getContextClassLoader() .getResourceAsStream(resourceLocationOnClasspath)); return JsonFactory.fromJson(json, MicroserviceConfig.class); } }@Override public void flush() { for (int index = 0; index < eventConnectors.size(); index++) { EventConnector eventConnector = null; try { eventConnector = eventConnectors.get(index); if (eventConnector instanceof ClientProxy) { ServiceProxyUtils.flushServiceProxy(eventConnector); } else { eventConnector.flush(); } } catch (Exception ex) { logger.debug("problem sending event to event connector", ex); if (eventConnector instanceof RemoteTCPClientProxy) { if (!((RemoteTCPClientProxy) eventConnector).connected()) { eventConnectors.remove(eventConnector); } } } } }@Override public void forwardEvent(final EventTransferObject event) { if (debug) logger.debug("forwardEvent " + event.channel() + " size " + eventConnectors.size()); for (int index = 0; index < eventConnectors.size(); index++) { EventConnector eventConnector = null; try { eventConnector = eventConnectors.get(index); eventConnector.forwardEvent(event); } catch (Exception ex) { logger.error("problem sending event to event connector", ex); if (eventConnector instanceof RemoteTCPClientProxy) { if (!((RemoteTCPClientProxy) eventConnector).connected()) { eventConnectors.remove(eventConnector); } } } } if (debug) logger.debug("forwardEvent done " + event.channel()); }public void remove(final EventConnector eventConnector) { if (eventConnector != null) { try { if (eventConnector instanceof RemoteTCPClientProxy) { final RemoteTCPClientProxy remoteTCPClientProxy = (RemoteTCPClientProxy) eventConnector; logger.info(Str.sputs("Removing event connector host ", remoteTCPClientProxy.host(), " port ", remoteTCPClientProxy.port(), "connected ", remoteTCPClientProxy.connected())); remoteTCPClientProxy.silentClose(); } this.eventConnectors.remove(eventConnector); } catch (Exception ex) { logger.error("Unable to remove event connector", ex); } } }public Optional getHttpRequest() { final Optional> request = this.getRequest(); if (request.isPresent()) { return findHttpRequest(request.get()); } else { return Optional.empty(); } }public void start() { if (!queue.isPresent()) { initQueue(); } queue.ifPresent(actualQueue -> actualQueue.startListener(EventBusQueueAdapter.this::sendToEventManager)); }private void sendToEventManager(T item) { if (debug) { logger.debug("EventBusQueueAdapter::sendToEventManager({})", item); } try { if (lock.tryLock()) { eventManager.sendArguments(channel, item); } else { lock.lock(); eventManager.sendArguments(channel, item); } } finally { lock.unlock(); } }public void process() { if (!receiveQueue.isPresent()) { initQueue(); } receiveQueue.ifPresent(receiveQueue -> { T item; do { try { item = receiveQueue.poll(); } catch (Exception ex) { logger.debug("Unable to receive message", ex); initQueue(); item = null; } if (item != null) { sendToEventManager(item); } } while (item != null); }); }public void handleRequest(final HttpRequest request) { if (debug) { System.out.println("HttpServer::handleRequest " + request); logger.debug("HttpServer::handleRequest" + request); } if (shouldContinueHttpRequest.test(request)) { httpRequestConsumer.accept(request); } }private void delete(String key, Map params) { final URI uri = createURI("/" + key); final HttpRequestBuilder httpRequestBuilder = RequestUtils .getHttpRequestBuilder(null, null, RequestOptions.BLANK, ""); final Set> entries = params.entrySet(); for (Map.Entry entry : entries) { httpRequestBuilder.addParam(entry.getKey(), entry.getValue()); } httpRequestBuilder.setMethodDelete(); final HTTP.Response httpResponse = HTTP.deleteResponse(uri.toString() + "?" + httpRequestBuilder.paramString()); if (httpResponse.code() != 200) { die("Unable to delete key", uri, key, httpResponse.code(), httpResponse.body()); } }@Override public List loadServices(final String serviceName) { if (debug) logger.debug("Loading Service {}", serviceName); final CountDownLatch countDownLatch = new CountDownLatch(1); final AtomicReference> endPointsRef = new AtomicReference<>(); final AtomicReference exceptionAtomicReference = new AtomicReference<>(); dnsSupport.loadServiceEndpointsByServiceName(CallbackBuilder.newCallbackBuilder() .withListCallback(EndpointDefinition.class, endpointDefinitions -> { endPointsRef.set(endpointDefinitions); countDownLatch.countDown(); }).withErrorHandler(exceptionAtomicReference::set) .build(), serviceName); try { if (debug) logger.debug("Waiting for load services {} {}", timeout, timeUnit); countDownLatch.await(timeout, timeUnit); } catch (InterruptedException e) { throw new IllegalStateException("DNS Timeout", e); } if (exceptionAtomicReference.get() != null) { logger.error("DnsServiceDiscoveryProvider.loadServices EXCEPTION", exceptionAtomicReference.get()); throw new IllegalStateException("Unable to read from DNS", exceptionAtomicReference.get()); } else { if (debug) logger.debug("DnsServiceDiscoveryProvider.loadServices SUCCESS"); return endPointsRef.get(); } }public boolean destroy(final String sessionId, final Session session, final String datacenter) { final URI uri = createURI("/destroy/" + sessionId); final HttpRequestBuilder httpRequestBuilder = RequestUtils .getHttpRequestBuilder(datacenter, null, null, ""); HTTP.Response httpResponse = HTTP.jsonRestCallViaPUT(uri.toString() + "?" + httpRequestBuilder.paramString(), toJson(session)); if (httpResponse == null || httpResponse.code() != 200) { die("Unable destroy the session", sessionId, uri, httpResponse); } return httpResponse.code() == 200; }private Interceptors configureInterceptors() { Interceptors interceptors = new Interceptors(); SetupMdcForHttpRequestInterceptor setupMdcForHttpRequestInterceptor; if (enableLoggingMappedDiagnosticContext) { enableRequestChain = true; if (requestHeadersToTrackForMappedDiagnosticContext != null && requestHeadersToTrackForMappedDiagnosticContext.size() > 0) { setupMdcForHttpRequestInterceptor = new SetupMdcForHttpRequestInterceptor(requestHeadersToTrackForMappedDiagnosticContext); } else { setupMdcForHttpRequestInterceptor = new SetupMdcForHttpRequestInterceptor(Collections.emptySet()); } interceptors.before.add(setupMdcForHttpRequestInterceptor); interceptors.after.add(setupMdcForHttpRequestInterceptor); } if (enableRequestChain) { final CaptureRequestInterceptor captureRequestInterceptor = new CaptureRequestInterceptor(); interceptors.before.add(captureRequestInterceptor); interceptors.after.add(captureRequestInterceptor); interceptors.beforeSent.add(new ForwardCallMethodInterceptor(new RequestContext())); } return interceptors; }public ServiceEndpointServer getServiceEndpointServer() { final ServiceEndpointServer serviceEndpointServer = getEndpointServerBuilder().build(); if (managedServiceDefinitionList != null) { managedServiceDefinitionList.forEach(serviceDef -> { if (serviceDef.getAlias() == null) { serviceEndpointServer.addServiceWithQueueCallBackHandlers(serviceDef.getServiceObject(), serviceDef.getQueueCallBackHandlers()); } else { serviceEndpointServer.addServiceObjectWithQueueCallBackHandlers(serviceDef.getAlias(), serviceDef.getServiceObject(), serviceDef.getQueueCallBackHandlers()); } }); } return serviceEndpointServer; }public ManagedServiceBuilder addEndpointService(final String alias, final Object endpointService) { getContextMetaBuilder().addService(alias, endpointService.getClass()); getEndpointServiceMapWithAlias().put(alias, endpointService); return this; }public ManagedServiceBuilder addEndpointService(final Object endpointService) { getContextMetaBuilder().addService(endpointService.getClass()); getEndpointServices().add(endpointService); return this; }public ManagedServiceBuilder addEndpointServiceWithAliasAndServiceManagmentBundle( final String alias, final Object endpointService, final ServiceManagementBundle serviceManagementBundle) { addEndpointServiceWithAliasAndQueueHandlerCallbacks(alias, endpointService, new QueueCallBackHandler() { @Override public void queueProcess() { serviceManagementBundle.process(); } }); return this; }public ManagedServiceBuilder addEndpointServiceWithServiceManagmentBundle( final Object endpointService, final ServiceManagementBundle serviceManagementBundle) { addEndpointServiceWithAliasAndQueueHandlerCallbacks(null, endpointService, new QueueCallBackHandler() { @Override public void queueProcess() { serviceManagementBundle.process(); } }); return this; }public ContextMetaBuilder getContextMetaBuilder() { if (contextMetaBuilder == null) { contextMetaBuilder = ContextMetaBuilder.contextMetaBuilder(); contextMetaBuilder .setHostAddress(this.getPublicHost() + ":" + this.getPublicPort()) .setRootURI(this.getRootURI()); } return contextMetaBuilder; }public AdminBuilder getAdminBuilder() { if (adminBuilder == null) { adminBuilder = AdminBuilder.adminBuilder(); final String qbitAdminPort = findAdminPort(); if (qbitAdminPort != null && !qbitAdminPort.isEmpty()) { adminBuilder.setPort(Integer.parseInt(qbitAdminPort)); } adminBuilder.setContextBuilder(this.getContextMetaBuilder()); adminBuilder.setHealthService(getHealthService()); adminBuilder.registerJavaVMStatsJob(getStatServiceBuilder().buildStatsCollector()); } return adminBuilder; }public ManagedServiceBuilder enableConsulServiceDiscovery(final String dataCenter) { final ConsulServiceDiscoveryBuilder consulServiceDiscoveryBuilder = consulServiceDiscoveryBuilder(); consulServiceDiscoveryBuilder.setDatacenter(dataCenter); serviceDiscoverySupplier = consulServiceDiscoveryBuilder::build; return this; }public ManagedServiceBuilder enableLoggingMappedDiagnosticContext(final Set requestHeaders) { this.enableRequestChain = true; this.enableLoggingMappedDiagnosticContext = true; this.requestHeadersToTrackForMappedDiagnosticContext = Collections.unmodifiableSet(requestHeaders); return this; }@Override public void failWithError(final String name, final Throwable error) { logger.error("HealthService::fail() {}", name); super.incrementCount("fail"); final NodeHealthStat nodeHealthStat = getServiceHealthStat(name); nodeHealthStat.setStatus(HealthStatus.FAIL); nodeHealthStat.setReason(HealthFailReason.ERROR); nodeHealthStat.setLastCheckIn(super.time); nodeHealthStat.setError(error); onFail.ifPresent(checkIn -> checkIn.accept(BeanUtils.copy(nodeHealthStat))); }@Override public void checkInOk(final String name) { if (debug) logger.debug("HealthService::checkInOk() {} ", name); final NodeHealthStat nodeHealthStat = getServiceHealthStat(name); nodeHealthStat.setLastCheckIn(super.time); nodeHealthStat.setReason(null); nodeHealthStat.setStatus(HealthStatus.PASS); super.incrementCount("checkin"); onCheckIn.ifPresent(checkIn -> checkIn.accept(BeanUtils.copy(nodeHealthStat))); }public ServiceQueue build() { if (debug) logger.debug("Building a service"); ServiceQueueSizer serviceQueueSizer = null; if (statsConfig != null) { serviceQueueSizer = new ServiceQueueSizer(); this.addQueueCallbackHandler(new ServiceStatsListener(statsConfig.serviceName, statsConfig.statsCollector, getTimer(), statsConfig.flushTimeSeconds, TimeUnit.SECONDS, statsConfig.sampleEvery, serviceQueueSizer)); } ServiceQueue serviceQueue = new ServiceQueueImpl(this.getRootAddress(), this.getServiceAddress(), this.getServiceObject(), this.getRequestQueueBuilder(), this.getResponseQueueBuilder(), this.getServiceMethodHandler(), this.getResponseQueue(), this.isAsyncResponse(), this.isHandleCallbacks(), this.getSystemManager(), this.getBeforeMethodCall(), this.getBeforeMethodCallAfterTransform(), this.getAfterMethodCall(), this.getAfterMethodCallAfterTransform(), buildQueueCallBackHandler(), getCallbackManager(), getBeforeMethodSent(), getEventManager(), isJoinEventManager() ); if (serviceQueueSizer != null) { serviceQueueSizer.setServiceQueue(serviceQueue); } if (qBitSystemManager != null) { qBitSystemManager.registerService(serviceQueue); } return serviceQueue; }@Override public void startListener(final ReceiveQueueListener listener) { queue.startListener(item -> listener.receive(fromJsonFunction.apply(item))); }private SendQueue createJsonSendQueue(final SendQueue sendQueue) { return new SendQueue() { @Override public boolean send(T item) { sendQueue.send(toJsonFunction.apply(item)); return false; } @Override public void sendAndFlush(T item) { sendQueue.sendAndFlush(toJsonFunction.apply(item)); } @Override public void sendMany(T... items) { for (T item : items) { sendQueue.send(toJsonFunction.apply(item)); } } @Override public void sendBatch(Collection items) { for (T item : items) { sendQueue.send(toJsonFunction.apply(item)); } } @Override public void sendBatch(Iterable items) { for (T item : items) { sendQueue.send(toJsonFunction.apply(item)); } } @Override public boolean shouldBatch() { return sendQueue.shouldBatch(); } @Override public void flushSends() { sendQueue.flushSends(); } @Override public int size() { return sendQueue.size(); } @Override public String name() { return sendQueue.name(); } @Override public void stop() { sendQueue.stop(); } }; }@Override public ReceiveQueue receiveQueue() { final ReceiveQueue receiveQueue = queue.receiveQueue(); return new ReceiveQueue() { @Override public T pollWait() { final String item = receiveQueue.pollWait(); return getParsedItem(item); } private T getParsedItem(String item) { if (item != null) { return fromJsonFunction.apply(item); } else { return null; } } @Override public T poll() { final String item = receiveQueue.pollWait(); return getParsedItem(item); } @Override public T take() { final String item = receiveQueue.take(); return getParsedItem(item); } @Override public Iterable readBatch(int max) { final Iterable iterable = receiveQueue.readBatch(max); return getParsedItems(iterable); } private Iterable getParsedItems(Iterable iterable) { int size = 16; if (iterable instanceof List) { size = ((List) iterable).size(); } final List items = new ArrayList<>(size); for (String item : iterable) { items.add(getParsedItem(item)); } return items; } @Override public Iterable readBatch() { final Iterable iterable = receiveQueue.readBatch(); return getParsedItems(iterable); } @Override public void stop() { receiveQueue.stop(); } }; }private ReceiveQueueListener> createResponseQueueListener() { return new ReceiveQueueListener>() { @Override public void receive(final Response response) { if (debug) { logger.debug("createResponseQueueListener() Received a response: " + response); } handleResponseFromServiceBundle(response, response.request().originatingRequest()); } @Override public void limit() { httpRequestServerHandler.checkTimeoutsForRequests(); webSocketHandler.checkResponseBatchSend(); } @Override public void empty() { httpRequestServerHandler.checkTimeoutsForRequests(); webSocketHandler.checkResponseBatchSend(); } @Override public void idle() { httpRequestServerHandler.checkTimeoutsForRequests(); webSocketHandler.checkResponseBatchSend(); } }; }public T createProxy(final Class serviceInterface, final String serviceName) { return createProxy(serviceInterface, serviceName, Str.join('-', uri, serviceName, UUID.randomUUID().toString())); }private void send(final String serviceName, final String message, final Consumer exceptionConsumer) { if (webSocket == null) { String webSocketURI; if (serviceName.startsWith(uri)) { webSocketURI = serviceName; } else { webSocketURI = Str.add(uri, "/", serviceName); } this.webSocket = httpServerProxy.createWebSocket(webSocketURI); wireWebSocket(serviceName, message); } try { if (webSocket.isClosed() && connected()) { this.webSocket.openAndNotify(netSocket -> { connected.set(true); webSocket.sendText(message, exceptionConsumer); }, exceptionConsumer); } else { webSocket.sendText(message); } } catch (Exception ex) { this.connected.set(false); if (debug) throw ex; } }private void handleAsyncCallback(final Response response, final Callback handler) { if (response.wasErrors()) { handler.onError(new Exception(response.body().toString())); } else { handler.accept(response.body()); } }public void stop() { flush(); if (httpServerProxy != null) { try { httpServerProxy.stop(); } catch (Exception ex) { logger.warn("Problem closing httpServerProxy ", ex); } } }public void warn(String checkId, String note) throws NotRegisteredException { checkTtl(checkId, Status.WARN, note); }public void pass(String checkId, @SuppressWarnings("SameParameterValue") String note) throws NotRegisteredException { checkTtl(checkId, Status.PASS, note); }public void check(String checkId, Status status, String note) { final URI uri = createURI("/check/" + status.getUri() + "/" + checkId); final HTTP.Response httpResponse = Str.isEmpty(note) ? HTTP.getResponse(uri.toString()) : HTTP.getResponse(uri.toString() + "?note=" + note); if (httpResponse.code() != 200) { notRegistered("Unable to perform check", uri, httpResponse.code(), httpResponse.statusMessageAsString(), httpResponse.body()); } }public void deregisterCheck(String checkId) { final URI uri = createURI("/check/deregister/" + checkId); HTTP.Response response = HTTP.getResponse(uri.toString()); if (response.status() != 200) { die("Error removing registration of service with Consul", uri, checkId, response.status(), response.statusMessageAsString(), response.payloadAsString()); } }public void deregister(final String serviceId) { final URI uri = createURI("/service/deregister/" + serviceId); HTTP.Response response = HTTP.getResponse(uri.toString()); if (response.status() != 200) { die("Error removing registration of service with Consul", uri, serviceId, response.status(), response.payloadAsString()); } }public void register(final Registration registration) { final URI uri = createURI("/service/register"); HTTP.Response response = HTTP.jsonRestCallViaPUT(uri.toString(), toJson(registration)); if (response.status() != 200) { die("Error registering service with Consul", uri, registration, response.payloadAsString()); } }public void pingAgent() { HTTP.Response response = HTTP.getResponse(createURI("/self").toString()); if (response.status() != 200) { die("Error pinging Consul", response.payloadAsString()); } }public boolean isServiceRegistered(final String serviceId) { Map serviceIdToService = getServices(); return serviceIdToService.containsKey(serviceId); }public HttpResponseBuilder addHeader(final String name, final String value) { getHeaders().put(name, value); return this; }public CallbackBuilder withOptionalCallback(final Class cls, final Callback> callback) { this.callback = callback; return this; }public CallbackBuilder withMapCallback(final Class keyClass, final Class valueClass, final Callback> callback) { this.callback = callback; return this; }public CallbackBuilder withCollectionCallback(final Class componentClass, final Callback> callback) { this.callback = callback; return this; }public CallbackBuilder withSetCallback(final Class componentClass, final Callback> callback) { this.callback = callback; return this; }public CallbackBuilder withListCallback(final Class componentClass, final Callback> callback) { this.callback = callback; return this; }public CallbackBuilder wrap(final Callback callback) { this.withErrorHandler(callback::onError); this.withTimeoutHandler(callback::onTimeout); this.withCallback(callback); return this; }public CallbackBuilder setCallback(final Class returnType, final Callback callback) { return withCallback(returnType, callback); }public boolean couldHaveCallback(final String name) { final Boolean has = hasHandlerMap.get(name); if (has == null) { return true; } return has; }private V convertToMap(ValueMap valueMap) { final Map map = new LinkedHashMap<>(valueMap.size()); valueMap.entrySet().forEach(new Consumer>() { @Override public void accept(Map.Entry entry) { Object value = entry.getValue(); /* If the value is a value container then grab what is inside. */ if (value instanceof ValueContainer) { ValueContainer valueContainer = ((ValueContainer) entry.getValue()); value = valueContainer.toValue(); } /* If value is a Value then pull the real value. */ if (value instanceof Value) { map.put(entry.getKey(), ((Value) value).toValue()); } else if (value instanceof ValueMap) { /* If value is a value map then convert it into a regular map. */ map.put(entry.getKey(), convertToMap(((ValueMap) value))); } else if (value instanceof List) { map.put(entry.getKey(), convertList(value, mapper.get())); } else { map.put(entry.getKey(), value); } } }); return (V) map; }@Override public Map fromJsonMap(String json, Class componentClassKey, Class componentClassValue) { Map map = (Map) parser.get().parse(json); final Mapper mapper = this.mapper.get(); return extractMap(componentClassKey, componentClassValue, map, mapper); }@Override public String toJson(Object object) { return serializer.get().serialize(object).toString(); }@Override public List fromJsonArray(String json, Class componentClass) { return parser.get().parseList(componentClass, json); }@Override public T fromJson(String json, Class cls) { return parser.get().parse(cls, json); }public static ServiceDiscovery createDnsServiceDiscovery() { final ServiceDiscoveryBuilder serviceDiscoveryBuilder = ServiceDiscoveryBuilder.serviceDiscoveryBuilder(); final Vertx vertx = Vertx.vertx(); final DnsSupportBuilder dnsSupportBuilder = DnsSupportBuilder.dnsSupportBuilder(vertx) .setDnsClientSupplier(new DnsClientFromResolveConfSupplier(vertx)); final DnsServiceDiscoveryProviderBuilder dnsServiceDiscoveryProviderBuilder = DnsServiceDiscoveryProviderBuilder.dnsServiceDiscoveryProviderBuilder() .setDnsSupport(dnsSupportBuilder.build()); return serviceDiscoveryBuilder .setServiceDiscoveryProvider(dnsServiceDiscoveryProviderBuilder.build()).build(); }public void add(final EventListener eventListener) { if (eventListener.subscriber()) { if (debug) logger.debug("subscription to channel <> from <> ", name, eventListener); listeners.add(eventListener); stats.recordLevel(eventBusName + "::" + name, listeners.size()); } else { if (debug) logger.debug("consumer to channel <> from <> ", name, eventListener); consumer = eventListener; } }public void start() { server.setHttpRequestConsumer(proxyService::handleRequest); server.setHttpRequestsIdleConsumer(aVoid -> flushServiceProxy(proxyService)); server.startServer(); }public void handleWebSocketCall(final WebSocketMessage webSocketMessage) { if (debug) logger.debug("WebSocket message: " + webSocketMessage); WebSocketDelegate webSocketDelegate = webSocketDelegateMap.get(webSocketMessage.getRemoteAddress()); if (webSocketDelegate == null) { webSocketDelegate = new WebSocketDelegate(protocolBatchSize, webSocketMessage); webSocketDelegateMap.put(webSocketMessage.getRemoteAddress(), webSocketDelegate); } protocolParserThreadPool.execute(() -> { try { final List> methodCallListToBeParsedFromBody = createMethodCallListToBeParsedFromBody(webSocketMessage.getRemoteAddress(), webSocketMessage.getMessage(), webSocketMessage); if (methodCallListToBeParsedFromBody.size() > 0) { methodCallSendQueue.sendBatch(methodCallListToBeParsedFromBody); } } catch (Exception ex) { logger.error("", ex); } }); }public ProxyService buildProxy() { return getServiceBuilder().setServiceObject(build()).buildAndStart().createProxyWithAutoFlush(ProxyService.class, Duration.HUNDRED_MILLIS); }public ProxyService build() { return new ProxyServiceImpl(getReactor(), getTimer(), getHttpClientBuilder(), getBeforeSend(), getErrorHandler(), getHttpClientRequestPredicate(), getCheckClientDuration(), pingBuilder == null ? Optional.empty() : Optional.of(pingBuilder), isTrackTimeOuts(), getTimeOutInterval()); }public Callback wrapCallbackWithTimeout( final String operationDescription, final Callback callback, final Logger logger, final TimeUnit timeUnit, final long timeoutDuration) { return callbackBuilder().setCallback(new Callback() { @Override public void accept(T t) { if (logger.isDebugEnabled()) { logger.debug("{} returned {}", operationDescription, t); } callback.resolve(t); } }).setOnError(error -> { logger.error(String.format("ERROR calling %s", operationDescription), error); callback.onError(error); }).setOnTimeout(() -> { logger.error("TIMEOUT calling {}", operationDescription); callback.onTimeout(); }).setTimeoutTimeUnit(timeUnit).setTimeoutDuration(timeoutDuration) .build(); }private void monitorCallbackCoordinators() { if (coordinatorList.size() > 0) { final List removeList = new ArrayList<>(coordinatorList.size()); for (CallbackCoordinator callable : coordinatorList) { if (callable.checkComplete()) { callable.finished(); removeList.add(callable); } else if (callable.timedOut(currentTime)) { removeList.add(callable); } } coordinatorList.removeAll(removeList); } }private void monitorCallBacks() { if (futureList.size() > 0) { final List> removeList = new ArrayList<>(futureList.size()); long now = currentTime; for (AsyncFutureCallback callback : futureList) { if (callback.isDone()) { callback.run(); removeList.add(callback); } else { if (callback.checkTimeOut(now)) { removeList.add(callback); } } } futureList.removeAll(removeList); } }public CallbackCoordinator coordinateWithTimeout(final CallbackCoordinator coordinator, final long startTime, final long timeoutDuration, final TimeUnit timeUnit, final Runnable timeOutHandler, final Runnable finishedHandler) { final long timeoutDurationMS = timeUnit.toMillis(timeoutDuration); final long theStartTime = startTime == -1 ? currentTime : startTime; final CallbackCoordinator wrapper = new CallbackCoordinator() { AtomicBoolean done = new AtomicBoolean(); @Override public boolean checkComplete() { if (done.get()) { return true; } if (coordinator.checkComplete()) { done.set(true); } return done.get(); } public boolean timedOut(long now) { if (startTime() == -1 || timeOutDuration() == -1) { return false; } if ((now - startTime()) > timeOutDuration()) { if (!done.get()) { timeOutHandler.run(); done.set(true); } return true; } else { return false; } } @Override public long timeOutDuration() { return coordinator.timeOutDuration() == -1 ? timeoutDurationMS : coordinator.timeOutDuration(); } @Override public long startTime() { return coordinator.startTime() == -1 ? theStartTime : coordinator.startTime(); } public void finished() { if (checkComplete()) { removeCoordinator(this); } if (finishedHandler != null) { finishedHandler.run(); } coordinator.finished(); } public void cancel() { done.set(true); removeCoordinator(this); coordinator.cancel(); } }; this.coordinatorQueue.add(wrapper); return wrapper; }public AsyncFutureCallback removeFuture(AsyncFutureCallback asyncFutureCallback) { this.removeFutureQueue.offer(asyncFutureCallback); return asyncFutureCallback; }public void process() { /** Manages lists of coordinators, and callbacks which can come back async. */ drainQueues(); currentTime = timer.now(); /* Check to see if callbacks completed or timed out. */ monitorCallBacks(); /* Check to see if coordinators completed or timed out. */ monitorCallbackCoordinators(); /* flush services. */ collaboratingServices.forEach(ServiceProxyUtils::flushServiceProxy); processRepeatingTasks(); processFireOnceTasks(); }public void addOneShotAfterTask(final long fireAfter, final TimeUnit timeUnit, final Runnable task) { fireOnceAfterTasks.add(new FireOnceTask(task, timeUnit, fireAfter)); }@Override public DnsClient get() { if (debug) logger.debug("DnsSingleClientSupplier.get()::host = {}, port = {}", host, port); return vertx.createDnsClient(port, host); }private void doFailOverHealthServicesLoad(final String serviceNameToFetch, Exception ex) { /* If there is a backup provider, load from there. */ if (backupProvider != null) { if (debug) logger.debug("ServiceDiscoveryImpl::loadHealthyServices " + "Error while loading healthy" + " services for " + serviceNameToFetch, ex); final List healthyServices = backupProvider.loadServices(serviceNameToFetch); populateServiceMap(serviceNameToFetch, healthyServices); serviceNamesBeingLoaded.remove(serviceNameToFetch); } else { logger.error("ServiceDiscoveryImpl::loadHealthyServices " + "Error while loading healthy" + " services for " + serviceNameToFetch, ex); } Sys.sleep(10_000); //primary is down so slow it down so we don't flow the system with updates of service pools. }private void loadHealthyServices() { try { String serviceName = doneQueue.poll(); while (serviceName != null) { final String serviceNameToFetch = serviceName; /* Don't load the service if it is already being loaded. */ if (!serviceNamesBeingLoaded.contains(serviceNameToFetch)) { serviceNamesBeingLoaded.add(serviceNameToFetch); executorService.submit(() -> { /* Loading a service pool might take a while so the actual load operation happens in its own thread. */ doLoadHealthServices(serviceNameToFetch); }); } serviceName = doneQueue.poll(); } } catch (Exception ex) { ex.printStackTrace(); } }public Callback callback(final Consumer> promiseConsumer) { Promise promise = Promises.promise(); promiseConsumer.accept(promise); return Reakt.convertPromise(promise); }public static Callback convertPromise(final Reactor reactor, final Promise promise) { return convertPromiseToCallback(promise, reactor.callbackBuilder()); }public static Callback convertPromise(final Promise promise) { return convertPromiseToCallback(promise, CallbackBuilder.callbackBuilder()); }@Override public SendQueue sendQueue() { if (debug) logger.debug("SendQueue requested for {}", name); return sendQueueSupplier.get(); }@Override public ReceiveQueue receiveQueue() { if (debug) logger.debug("ReceiveQueue requested for {}", name); return new BasicReceiveQueue<>(queue, pollTimeWait, pollTimeTimeUnit, limit); }@Override public DnsClient get() { final URI uri = addressList.get(index); try { if (debug) logger.debug("DnsClient.get port {} host {}", uri.getPort(), uri.getHost()); return vertx.createDnsClient(uri.getPort(), uri.getHost()); } catch (Exception ex) { logger.error("DnsClient.get EXCEPTION ", ex); logger.error("DnsClient.get EXCEPTION port {} host {}", uri.getPort(), uri.getHost()); return getIfErrors(); } }public static Consul consul(final String host, final int port) { try { return new Consul(new URL("http", host, port, "").toString()); } catch (MalformedURLException e) { throw new ConsulException("Bad Consul URL", e); } }private boolean doHandleMethodCall(MethodCall methodCall, final ServiceMethodHandler serviceMethodHandler) { if (debug) { logger.debug("ServiceImpl::doHandleMethodCall() METHOD CALL" + methodCall); } if (callbackManager != null) { if (methodCall.hasCallback() && serviceMethodHandler.couldHaveCallback(methodCall.name())) { callbackManager.registerCallbacks(methodCall); } } //inputQueueListener.receive(methodCall); final boolean continueFlag[] = new boolean[1]; methodCall = beforeMethodProcessing(methodCall, continueFlag); if (continueFlag[0]) { if (debug) logger.debug("ServiceImpl::doHandleMethodCall() before handling stopped processing"); return false; } Response response = serviceMethodHandler.receiveMethodCall(methodCall); if (response != ServiceConstants.VOID) { if (!afterMethodCall.after(methodCall, response)) { return false; } //noinspection unchecked response = responseObjectTransformer.transform(response); if (!afterMethodCallAfterTransform.after(methodCall, response)) { return false; } if (debug) { if (response.body() instanceof Throwable) { logger.error("Unable to handle call ", ((Throwable) response.body())); } } if (!responseSendQueue.send(response)) { logger.error("Unable to send response {} for method {} for object {}", response, methodCall.name(), methodCall.objectName()); } } return false; }private void handleHttpRequest(final HttpServerRequest request) { if (debug) { setupMetrics(request); logger.debug("HttpServerVertx::handleHttpRequest::{}:{}", request.method(), request.uri()); } switch (request.method().toString()) { case "PUT": case "POST": case "OPTIONS": case "TRACE": case "DELETE": case "CONNECT": handleRequestWithBody(request); break; case "HEAD": case "GET": handleRequestWithNoBody(request); break; default: throw new IllegalStateException("method not supported yet " + request.method()); } }protected CORSRequestType checkRequestType(final HttpRequestHolder request) { CORSRequestType requestType = CORSRequestType.INVALID_CORS; if (request == null) { throw new IllegalArgumentException(CorsSupport.CORS_NULL_REQUEST); } String originHeader = request.getHeaders().get(REQUEST_HEADER_ORIGIN); // Section 6.1.1 and Section 6.2.1 if (originHeader != null) { if (originHeader.isEmpty()) { requestType = CORSRequestType.INVALID_CORS; } else if (!isValidOrigin(originHeader)) { requestType = CORSRequestType.INVALID_CORS; } else if (isLocalOrigin(request, originHeader)) { return CORSRequestType.NOT_CORS; } else { String method = request.getMethod(); if (method != null) { if ("OPTIONS".equals(method)) { String accessControlRequestMethodHeader = request.getHeaders().get( REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD); if (accessControlRequestMethodHeader != null && !accessControlRequestMethodHeader.isEmpty()) { requestType = CORSRequestType.PRE_FLIGHT; } else if (accessControlRequestMethodHeader != null && accessControlRequestMethodHeader.isEmpty()) { requestType = CORSRequestType.INVALID_CORS; } else { requestType = CORSRequestType.ACTUAL; } } else if ("GET".equals(method) || "HEAD".equals(method)) { requestType = CORSRequestType.SIMPLE; } else if ("POST".equals(method)) { String mediaType = request.getContentType(); if (mediaType != null) { // if (SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES // .contains(mediaType)) { // requestType = CORSRequestType.SIMPLE; // } else { // requestType = CORSRequestType.ACTUAL; // } //TODO: Will QBit support non-simple? requestType = CORSRequestType.SIMPLE; } } else { requestType = CORSRequestType.ACTUAL; } } } } else { requestType = CORSRequestType.NOT_CORS; } return requestType; }private EndpointDefinition convertSrvRecordToEndpointDefinition(final SrvRecord srvRecord) { return new EndpointDefinition(findServiceName(srvRecord.service()), srvRecord.target(), srvRecord.port()); }public void loadServiceEndpointsByServiceName(final Callback> callback, final String serviceName) { loadServiceEndpointsByDNSService(callback, findDnsServiceName(serviceName)); }public String findServiceName(final String dnsServiceName) { String serviceName = dnsServiceNameToServiceName.get(dnsServiceName); serviceName = serviceName == null ? dnsServiceName : serviceName; if (debug) logger.debug("FindServiceName dnsServiceName={} serviceName={}", dnsServiceName, serviceName); return serviceName; }public ServiceBundle startUpCallQueue() { methodQueue.startListener(new ReceiveQueueListener>() { long time; long lastTimeAutoFlush; /** * When we receive a method call, we call doCall. * @param item item */ @Override public void receive(MethodCall item) { doCall(item); //Do call calls forwardEvent but does not flush. Only when the queue is empty do we flush. } /** * If the queue is empty, then go ahead, and flush to each client all incoming requests every 50 milliseconds. */ @Override public void empty() { time = timer.now(); if (time > (lastTimeAutoFlush + 50)) { //noinspection Convert2streamapi for (SendQueue> sendQueue : sendQueues) { sendQueue.flushSends(); } lastTimeAutoFlush = time; } } }); return this; }@SuppressWarnings("Convert2streamapi") public void stop() { if (debug) { logger.debug(ServiceBundleImpl.class.getName(), "::stop()"); } methodQueue.stop(); for (Stoppable service : servicesToStop) { service.stop(); } try { responseQueue.stop(); } catch (Exception ex) { logger.debug("", ex); } try { webResponseQueue.stop(); } catch (Exception ex) { logger.debug("", ex); } if (systemManager != null) systemManager.serviceShutDown(); }private MethodCall transformBeforeMethodCall(MethodCall methodCall) { if (argTransformer == null || argTransformer == ServiceConstants.NO_OP_ARG_TRANSFORM) { return methodCall; } Object arg = this.argTransformer.transform(methodCall); return MethodCallBuilder.transformed(methodCall, arg); }private MethodCall beforeMethodCall(MethodCall methodCall, boolean[] continueCall) { if (this.beforeMethodCall.before(methodCall)) { continueCall[0] = true; methodCall = transformBeforeMethodCall(methodCall); continueCall[0] = this.beforeMethodCallAfterTransform.before(methodCall); return methodCall; } else { continueCall[0] = false; } return methodCall; }@Override public T createLocalProxy(final Class serviceInterface, final String myService) { final Consumer> callConsumer = this.serviceMapping.get(myService); if (callConsumer == null) { logger.error("Service requested does not exist " + myService); } return factory.createLocalProxy(serviceInterface, myService, this, beforeMethodSent); }@Override @SuppressWarnings("unchecked") public void call(final MethodCall methodCall) { if (debug) { logger.debug(ServiceBundleImpl.class.getName() + "::call() " + methodCall.name() + " " + " " + methodCall.address() + "\n" + methodCall); } methodSendQueue.send(methodCall); }private void doCall(MethodCall methodCall) { if (debug) { logger.debug(ServiceBundleImpl.class.getName(), "::doCall() ", methodCall.name(), methodCall.address(), "\n", methodCall); } try { if (methodCall.hasCallback()) { callbackManager.registerCallbacks(methodCall); } boolean[] continueFlag = new boolean[1]; methodCall = handleBeforeMethodCall(methodCall, continueFlag); if (!continueFlag[0]) { if (debug) { logger.debug(ServiceBundleImpl.class.getName() + "::doCall() " + "Flag from before call handling does not want to continue"); } } else { final Consumer> methodDispatcher = getMethodDispatcher(methodCall); methodDispatcher.accept(methodCall); } } catch (Exception ex) { Response response = new ResponseImpl<>(methodCall, ex); this.responseQueue.sendQueue().sendAndFlush(response); } }public static ServiceDiscovery createLokateServiceDiscovery(final List configs) { return serviceDiscoveryBuilder() .setServiceDiscoveryProvider( new LokateServiceDiscoveryProvider( DiscoveryService.create(configs))) .build(); }@QueueCallback({QueueCallbackType.EMPTY, QueueCallbackType.IDLE, QueueCallbackType.LIMIT}) public void process() { reactor.process(); time = timer.time(); }private void handleBackendClientResponses(final HttpRequest clientRequest, final int code, final String contentType, final byte[] body, final MultiMap headers) { /** If it is handled like it timed out already or some other error then don't do anything. */ if (!clientRequest.isHandled()) { /* If it was handled, let everyone know so we don't get a timeout. */ clientRequest.handled(); /* Send the response out the front end. */ clientRequest.getReceiver().response(code, contentType, body, headers); } }private void handleHttpClientErrorsForBackend(final HttpRequest clientRequest, final Exception e) { /* Notify error handler that we got an error. */ errorHandler.accept(e); /* Increment our error count. */ errorCount.incrementAndGet(); /* Create the error message. */ final String errorMessage = String.format("Unable to make request %s ", clientRequest.address()); /* Log the error. */ logger.error(errorMessage, e); /* Don't send the error to the client if we already handled this, i.e., timedout already. */ if (!clientRequest.isHandled()) { clientRequest.handled(); /* Notify the client that there was an error. */ clientRequest.getReceiver().error(String.format("\"%s\"", errorMessage)); } }private void createBackEndRequestPopulateAndForward(final HttpRequest clientRequest) { try { if (backendServiceHttpClient == null) { handleHttpClientErrorsForBackend(clientRequest, new HttpClientClosedConnectionException("Not connected")); long timeSinceLastStart = time - lastHttpClientStart; if (timeSinceLastStart > 10_000) { checkClient(); } return; } /* forward request to backend client. */ final HttpRequestBuilder httpRequestBuilder = HttpRequestBuilder.httpRequestBuilder() .copyRequest(clientRequest).setBinaryReceiver(new HttpBinaryReceiver() { @Override public void response(final int code, final String contentType, final byte[] body, final MultiMap headers) { handleBackendClientResponses(clientRequest, code, contentType, body, headers); } @Override public void response(int code, String contentType, byte[] body) { response(code, contentType, body, MultiMap.empty()); } }).setErrorHandler(e -> handleHttpClientErrorsForBackend(clientRequest, e)); /** Give user of the lib a chance to populate headers and such. */ beforeSend.accept(httpRequestBuilder); backendServiceHttpClient.sendHttpRequest(httpRequestBuilder.build()); } catch (HttpClientClosedConnectionException httpClientClosedConnectionException) { errorCount.incrementAndGet(); errorHandler.accept(httpClientClosedConnectionException); logger.error("Unable to forward request", httpClientClosedConnectionException); handleHttpClientErrorsForBackend(clientRequest, httpClientClosedConnectionException); backendServiceHttpClient = null; long timeSinceLastStart = time - lastHttpClientStart; if (timeSinceLastStart > 10_000) { checkClient(); } } catch (Exception ex) { errorCount.incrementAndGet(); errorHandler.accept(ex); logger.error("Unable to forward request", ex); handleHttpClientErrorsForBackend(clientRequest, ex); long timeSinceLastStart = time - lastHttpClientStart; if (timeSinceLastStart > 10_000) { checkClient(); } } }��7���S���X]r�6~�)v�Њ3&��K�8�d7�d2�X������9h�I|�ޢ��=r���� E�"�6~�Ip��؟P7�R�d�p����Uy)���ZR)�uӺ��Y��b�N�þ�9�ڄ>ޣ���4�U�$�'O�a_����Tk�rM��R.D��Y4+�݋�\�NUz�<�f���<��e�v�f�YJ���e3���9 ���si��ep���oKadA��t�;��Ue$�Z�j�H`T� }M�[��-��!%] ���̿�5�oI��TLb������ �,�R�^$)�+��f�4�K�,���k�+{5� zB��:�of������r�(C�h��M��nb�t��圑b5I����Ke���B�����r���G���D��ȗ4U49�������Hf�FE�;�LUB3��k�K�巩ʆ� ��ti��':jIae�����H��>�':#�[�nh��K�%&�M4�W�ـw����4��P^���)����W(#Q�Z�%Y���g���q��˦�����WR�,��jaĊ R}�*|#.��P�g#����D�/�%��5��s+8B�a������~B�����Po���؟��I�9Z��Uz3�#�l��-�tt>�ttc��uՔ]+��F������Qh).щp��_��0����o=��\h�b.���Yp��;9�Wu�aźt;v/c�_�N�^ i`���IQw ]�VeI�0�z,�P�ŬD|�֦*@�7��h�_��]I�B…��>�0�P�6qA+qÑ�����A�޴.�� ��u� �� �3N3X;���g���'�5]�"�a9��>���~+�d.��Do�R^����i�&k�m��}5��쒅�D�j��2���`۫�˰an䲰�)!L�`/_��^� ���Ɛi�f�E��R�D��Q��������&� C�+J$눑Xm� ���l���� ��HV9vYJVA���%!ې9�����z.�v����q B$&��He��� �*�G��bp͝B��5{4THC�a�+��nW�#�Q)c3�g<�����;�>4(&�n�I�@��=�<�s�L;��ɗ�?e?g�63T&;ޕ`dp5[TZ��VR�l�^4��v�E�2���ὐsO�f�.��)��_-a���&�jn����AKy��F��Q�ڣ�1����k�-�>{}M�(+���P����;cL0l���c�0� '����z����l]Y�xGbL��M�A��.�M����]� &�qd�L���d���ݫ�����Whc'��@d�ڈ�7�(�$.ΰ-�e��0`Fq�l&L�zg/�:������w$��+#Ӷg����jce�筱��4U��d,f�\,�+\;�\E/�+��L1 �86$���� E�м��>Q�v�82��o�2 ^����X 0�+�#�Z�x"�K< �"���s���$q����]���YF�Vk��a�� U�^K���� $�b)�� ���C�{t5�y��4��͐�����u��;!��d�5��ޜ�j�� JE��k�*Zh��޽�3�;�+��UHgm҉�6����9_��hg��pAeG.�²U��o����Yk��V��䍱� BW���|� �V8��dm„���|(���+�|1з ����붚n ����֕q�x�r�[��7�`T�S�����X�n�F��)��XBR�p�C�&���1,9==�ȑ�6�%�K)N ׾G��sk{��!�$�����,�M��`����|���nQMS�T�E�*q\`,g2~�f���|�%�1����"M��.J�����V����SQ # ��:������~x_�p� QJ&�X�v���jJ 3��ݏ�ã���ӂ������u'1,ƫ Rx()7�8$YZĊB� r�Y-�-m"�ݏ:݇����JL�A %H �R[�� 0@���p�1��Ÿ�b��L� �6����$l��ɿ*5��P�f:N� t���_�$�u��nr�R�j]ؿ���J:��^t�0W��dm�k��pA�K c���M�I��\%K���Ll��- �e3q�Rqe�֔I��I[J[f�)��4UKݝ�V �$����*��Fz{<`1Td(G�����*��'����ܺ�.1�ۛDkd���E4�v3ul�ـy� ABo�����WDB�f�*g��T(8-����6oKG�KpfL����-<�m"�Gr�B=�P� ��z�d��DJ�vӥ�A����(ҥ�^�!�w�2��Q�~&��Y��Le� ���L���h1������#��ݟ{��2�F/$�|S���� �$��f��2'�T@i���7ڗ=f0W��\X?�r;9 0��ݨt{8 �����4{ɷ����-��=\W6���龊ELxK������r,!J��ݨ�)�6�[������7ZLE�;?%�d��5V��_�o���]�xk���s�����*�_قr���7:.�T��'@2`�e, Zh�ҕ�WN�+�g��Ld�;E�`�!�4��L"Mzmw�| �i"ZC`�$��ܷ���2.�AE���«K�q�N)dљ� %�qwoX-�g�6r���O�9J[[������vb<ܯ���U V ���U����cW�&֦�LV��:/�x�)�;8�[��[��(3~X��r+����Ʃ�J���D���5 \g�C���U���Q�k�O嚧K��ֱ�T�rЖ9Ea^��m���!�hD8�L��tq}d�����u#UV����y�u?�зd���L�������]-�A��PϦ�$�P=Z+\��,?�aG�F����nM���m��^U9�e����w����v���hO�43�<��<���9�˨o��P$�� ;f��+��A`P�iW�[�dߝ�p3�o� ���>߇6I����7�[�h=F��0n�w�C��4s'�:Lyd��9��I�*F�'�ӅW���%�8f���k���A�wR���nj�icMs,~��檞����z㲂����8FLBLw\G�u��B%�Q�l�`�s:TJ�KN=6����w�o��w\����=8bc�����f����% ��u~F!M#�$A(W*F7�9�DYE�J���YMNN�O�P�Q"Y�Yf\C]�^#aHb�c,d�dmeHf>�;�7�A�F�[�@�%���K�@�=�>�G����������A�ё:�L�P�Y����j�9�s�w����,��K���T���������?�����p�s� �2���|�N�;�o�U�"��� ���74� +��j�#�$w(�.�/�:�?�C�HtJK�K|M/O�Q�U)W�\�]m_�c�d�ovq�r\t�~�j�Ɋf���ג �]���\�֝��۠W�����)����e�����(���?��� �X�&�>�=�>��������� ����������� �h � ��*5"~$�&f(�+ .�0�2M5G<*?F�JRPTTdU%Y[M_Sbti?k^n3p�rt�v�{)}�~U���x���čc���������5�������k��²j����̵��������ʼj�������%�F�k���b��� ������N�����w�d��X�P������@DoesServiceRequest public void upload(final InputStream sourceStream, final long length, final AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException, IOException, URISyntaxException { if (opContext == null) { opContext = new OperationContext(); } this.getShare().assertNoSnapshot(); options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient); if (length < 0) { throw new IllegalArgumentException(SR.INVALID_FILE_LENGTH); } if (sourceStream.markSupported()) { // Mark sourceStream for current position. sourceStream.mark(Constants.MAX_MARK_LENGTH); } final FileOutputStream streamRef = this.openWriteNew(length, accessCondition, options, opContext); try { streamRef.write(sourceStream, length); } finally { streamRef.close(); } }@DoesServiceRequest public void upload(final InputStream sourceStream, final long length) throws StorageException, IOException, URISyntaxException { this.upload(sourceStream, length, null /* accessCondition */, null /* options */, null /* opContext */); }public void resize(long size, AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException { if (opContext == null) { opContext = new OperationContext(); } this.getShare().assertNoSnapshot(); opContext.initialize(); options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient); ExecutionEngine.executeWithRetry(this.fileServiceClient, this, this.resizeImpl(size, accessCondition, options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest private void putRangeInternal(final FileRange range, final FileRangeOperationType operationType, final byte[] data, final long length, final String md5, final AccessCondition accessCondition, final FileRequestOptions options, final OperationContext opContext) throws StorageException { ExecutionEngine.executeWithRetry(this.fileServiceClient, this, putRangeImpl(range, operationType, data, length, md5, accessCondition, options, opContext), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public void uploadRange(final InputStream sourceStream, final long offset, final long length, final AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException, IOException, URISyntaxException { if (opContext == null) { opContext = new OperationContext(); } this.getShare().assertNoSnapshot(); options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient); final FileRange range = new FileRange(offset, offset + length - 1); final byte[] data = new byte[(int) length]; String md5 = null; int count = 0; int total = 0; while (total < length) { count = sourceStream.read(data, total, (int) Math.min(length - total, Integer.MAX_VALUE)); total += count; } if (options.getUseTransactionalContentMD5()) { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(data, 0, data.length); md5 = Base64.encode(digest.digest()); } catch (final NoSuchAlgorithmException e) { // This wont happen, throw fatal. throw Utility.generateNewUnexpectedStorageException(e); } } this.putRangeInternal(range, FileRangeOperationType.UPDATE, data, length, md5, accessCondition, options, opContext); }@DoesServiceRequest public void uploadRange(final InputStream sourceStream, final long offset, final long length) throws StorageException, IOException, URISyntaxException { this.uploadRange(sourceStream, offset, length, null /* accessCondition */, null /* options */, null /* opContext */); }public void uploadText(final String content, final String charsetName, final AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException, IOException, URISyntaxException { byte[] bytes = (charsetName == null) ? content.getBytes() : content.getBytes(charsetName); this.uploadFromByteArray(bytes, 0, bytes.length, accessCondition, options, opContext); }public void uploadText(final String content) throws StorageException, IOException, URISyntaxException { this.uploadText(content, null /* charsetName */, null /* accessCondition */, null /* options */, null /* opContext */); }public void uploadFromFile(final String path, final AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException, IOException, URISyntaxException { File file = new File(path); long fileLength = file.length(); InputStream inputStream = new BufferedInputStream(new java.io.FileInputStream(file)); this.upload(inputStream, fileLength, accessCondition, options, opContext); inputStream.close(); }public void uploadFromFile(final String path) throws StorageException, IOException, URISyntaxException { uploadFromFile(path, null /* accessCondition */, null /* options */, null /* opContext */); }private FileOutputStream openOutputStreamInternal(Long length, AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException { if (opContext == null) { opContext = new OperationContext(); } this.getShare().assertNoSnapshot(); options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient, false /* setStartTime */); if (length != null) { this.create(length, accessCondition, options, opContext); } else { if (options.getStoreFileContentMD5()) { throw new IllegalArgumentException(SR.FILE_MD5_NOT_POSSIBLE); } this.downloadAttributes(accessCondition, options, opContext); length = this.getProperties().getLength(); } if (accessCondition != null) { accessCondition = AccessCondition.generateLeaseCondition(accessCondition.getLeaseID()); } return new FileOutputStream(this, length, accessCondition, options, opContext); }@DoesServiceRequest public FileOutputStream openWriteExisting(AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException { return this.openOutputStreamInternal(null /* length */, accessCondition, options, opContext); }@DoesServiceRequest public FileOutputStream openWriteExisting() throws StorageException, URISyntaxException { return this .openOutputStreamInternal(null /* length */, null /* accessCondition */, null /* options */, null /* opContext */); }@DoesServiceRequest public ArrayList downloadFileRanges(final AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient); return ExecutionEngine.executeWithRetry(this.fileServiceClient, this, this.downloadFileRangesImpl(accessCondition, options), options.getRetryPolicyFactory(), opContext); }public String downloadText(final String charsetName, final AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); this.download(baos, accessCondition, options, opContext); return charsetName == null ? baos.toString() : baos.toString(charsetName); }private void deleteEmptyFileOnException(OutputStream outputStream, String path) { try { outputStream.close(); File fileToDelete = new File(path); fileToDelete.delete(); } catch (Exception e) { // Best effort delete. } }@DoesServiceRequest public void create(final long size, final AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException { if (opContext == null) { opContext = new OperationContext(); } this.getShare().assertNoSnapshot(); options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient); ExecutionEngine.executeWithRetry(this.fileServiceClient, this, this.createImpl(size, accessCondition, options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public void create(final long size) throws StorageException, URISyntaxException { this.create(size, null /* accessCondition */, null /* options */, null /* opContext */); }@DoesServiceRequest public final String startCopy(final URI source, final AccessCondition sourceAccessCondition, final AccessCondition destinationAccessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException { if (opContext == null) { opContext = new OperationContext(); } this.getShare().assertNoSnapshot(); opContext.initialize(); options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient); return ExecutionEngine.executeWithRetry(this.fileServiceClient, this, this.startCopyImpl(source, sourceAccessCondition, destinationAccessCondition, options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public final String startCopy(final URI source) throws StorageException, URISyntaxException { return this.startCopy(source, null /* sourceAccessCondition */, null /* destinationAccessCondition */, null /* options */, null /* opContext */); }@DoesServiceRequest public final String startCopy(final CloudFile sourceFile, final AccessCondition sourceAccessCondition, final AccessCondition destinationAccessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException { Utility.assertNotNull("sourceFile", sourceFile); return this.startCopy(sourceFile.getTransformedAddress(opContext).getPrimaryUri(), sourceAccessCondition, destinationAccessCondition, options, opContext); }@DoesServiceRequest public final String startCopy(final CloudFile sourceFile) throws StorageException, URISyntaxException { return this.startCopy(sourceFile, null /* sourceAccessCondition */, null /* destinationAccessCondition */, null /* options */, null /* opContext */); }@DoesServiceRequest public final String startCopy(final CloudBlob sourceBlob, final AccessCondition sourceAccessCondition, final AccessCondition destinationAccessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException { Utility.assertNotNull("sourceBlob", sourceBlob); URI source = sourceBlob.getSnapshotQualifiedUri(); if (sourceBlob.getServiceClient() != null && sourceBlob.getServiceClient().getCredentials() != null) { source = sourceBlob.getServiceClient().getCredentials().transformUri(sourceBlob.getSnapshotQualifiedUri()); } return this.startCopy(source, sourceAccessCondition, destinationAccessCondition, options, opContext); }@DoesServiceRequest public final String startCopy(final CloudBlob sourceBlob) throws StorageException, URISyntaxException { return this.startCopy(sourceBlob, null /* sourceAccessCondition */, null /* destinationAccessCondition */, null /* options */, null /* opContext */); }private void updateIterator() throws StorageException, URISyntaxException { if (this.currentPrefixTime != null && this.currentPrefixTime.isEmpty()) { // If we've already called listBlobs() with an empty prefix, don't do so again. this.isExpired = true; return; } GregorianCalendar now = new GregorianCalendar(); now.add(GregorianCalendar.HOUR_OF_DAY, 1); now.setTimeZone(TimeZone.getTimeZone("GMT")); updatePrefix(); if ((this.startDate == null || this.startDate.compareTo(now) <= 0) && (this.endDate == null || ((this.logDirectory.getPrefix() + this.currentPrefixTime) .compareTo(this.endPrefix) <= 0))) { // Only make the next call if the prefix is still possible this.currentIterator = this.logDirectory.listBlobs(this.currentPrefixTime, true, this.details, this.options, this.opContext).iterator(); } else { // We are in the future. this.isExpired = true; } }private boolean isCorrectLogType(ListBlobItem current) { HashMap metadata = ((CloudBlob) current).getMetadata(); String logType = metadata.get("LogType"); if (logType == null) { return true; } if (this.operations.contains(LoggingOperations.READ) && logType.contains("read")) { return true; } if (this.operations.contains(LoggingOperations.WRITE) && logType.contains("write")) { return true; } if (this.operations.contains(LoggingOperations.DELETE) && logType.contains("delete")) { return true; } return false; }public synchronized RequestResult getLastResult() { if (this.requestResults == null || this.requestResults.size() == 0) { return null; } else { return this.requestResults.get(this.requestResults.size() - 1); } }@Override protected String canonicalize(final HttpURLConnection conn, final String accountName, final Long contentLength) throws StorageException { if (contentLength < -1) { throw new InvalidParameterException(SR.INVALID_CONTENT_LENGTH); } return canonicalizeTableHttpRequest(conn.getURL(), accountName, conn.getRequestMethod(), Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_TYPE), contentLength, null, conn); }public void printSampleCompleteInfo(String sampleName) { outputText((TextView) findViewById(R.id.textView), String.format( "The Azure storage client library sample %s completed.\n", sampleName)); }public void printSampleStartInfo(String sampleName) { TextView view = (TextView) findViewById(R.id.textView); clearText(view); outputText(view, String.format( "The Azure storage client library sample %s is starting...", sampleName)); }public void printException(Throwable t) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); t.printStackTrace(printWriter); outputText( (TextView) findViewById(R.id.textView), String.format( "Got an exception from running samples. Exception details:\n%s\n", stringWriter.toString())); }public void outputText(final TextView view, final String value) { runOnUiThread(new Runnable() { @Override public void run() { view.append(value + "\n"); System.out.println(view); } }); }public void runTablePayloadFormatSample(View view) { new TablePayloadFormatTask(this, (TextView) findViewById(R.id.textView)) .execute(); }public void runTableGettingStartedSample(View view) { new TableGettingStartedTask(this, (TextView) findViewById(R.id.textView)).execute(); }public void runQueueGettingStartedSample(View view) { new QueueGettingStartedTask(this, (TextView) findViewById(R.id.textView)).execute(); }public void runBlobGettingStartedSample(View view) { new BlobGettingStartedTask(this, (TextView) findViewById(R.id.textView)) .execute(); }@Override public synchronized long skip(final long n) throws IOException { if (n == 0) { return 0; } if (n < 0 || this.currentAbsoluteReadPosition + n > this.streamLength) { throw new IndexOutOfBoundsException(); } this.validateFileMd5 = false; this.md5Digest = null; this.reposition(this.currentAbsoluteReadPosition + n); return n; }@Override public synchronized void reset() throws IOException { if (this.markedPosition + this.markExpiry < this.currentAbsoluteReadPosition) { throw new IOException(SR.MARK_EXPIRED); } this.validateFileMd5 = false; this.md5Digest = null; this.reposition(this.markedPosition); }@DoesServiceRequest private synchronized int readInternal(final byte[] b, final int off, int len) throws IOException { this.checkStreamState(); // if buffer is empty do next get operation if ((this.currentBuffer == null || this.currentBuffer.available() == 0) && this.currentAbsoluteReadPosition < this.streamLength) { this.dispatchRead((int) Math.min(this.readSize, this.streamLength - this.currentAbsoluteReadPosition)); } len = Math.min(len, this.readSize); // do read from buffer final int numberOfBytesRead = this.currentBuffer.read(b, off, len); if (numberOfBytesRead > 0) { this.currentAbsoluteReadPosition += numberOfBytesRead; if (this.validateFileMd5) { this.md5Digest.update(b, off, numberOfBytesRead); if (this.currentAbsoluteReadPosition == this.streamLength) { // Reached end of stream, validate md5. final String calculatedMd5 = Base64.encode(this.md5Digest.digest()); if (!calculatedMd5.equals(this.retrievedContentMD5Value)) { this.lastError = Utility .initIOException(new StorageException( StorageErrorCodeStrings.INVALID_MD5, String.format( "File data corrupted (integrity check failed), Expected value is %s, retrieved %s", this.retrievedContentMD5Value, calculatedMd5), Constants.HeaderConstants.HTTP_UNUSED_306, null, null)); this.streamFaulted = true; throw this.lastError; } } } } // update markers if (this.markExpiry > 0 && this.markedPosition + this.markExpiry < this.currentAbsoluteReadPosition) { this.markedPosition = 0; this.markExpiry = 0; } return numberOfBytesRead; }@Override @DoesServiceRequest public int read() throws IOException { final byte[] tBuff = new byte[1]; final int numberOfBytesRead = this.read(tBuff, 0, 1); if (numberOfBytesRead > 0) { return tBuff[0] & 0xFF; } else if (numberOfBytesRead == 0) { throw new IOException(SR.UNEXPECTED_STREAM_READ_ERROR); } else { return -1; } }@DoesServiceRequest private synchronized void dispatchRead(final int readLength) throws IOException { try { final byte[] byteBuffer = new byte[readLength]; this.parentFileRef.downloadRangeInternal(this.currentAbsoluteReadPosition, (long) readLength, byteBuffer, 0, null /* this.accessCondition */, this.options, this.opContext); // Check Etag manually for now -- use access condition once conditional headers supported. if (this.accessCondition != null) { if (!this.accessCondition.getIfMatch().equals(this.parentFileRef.getProperties().getEtag())) { throw new StorageException(StorageErrorCode.CONDITION_FAILED.toString(), SR.INVALID_CONDITIONAL_HEADERS, HttpURLConnection.HTTP_PRECON_FAILED, null, null); } } this.currentBuffer = new ByteArrayInputStream(byteBuffer); this.bufferSize = readLength; this.bufferStartOffset = this.currentAbsoluteReadPosition; } catch (final StorageException e) { this.streamFaulted = true; this.lastError = Utility.initIOException(e); throw this.lastError; } }@Override public synchronized void close() throws IOException { this.currentBuffer = null; this.streamFaulted = true; this.lastError = new IOException(SR.STREAM_CLOSED); }public static HttpURLConnection setFileProperties(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition, final FileProperties properties) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder builder = new UriQueryBuilder(); builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.PROPERTIES); final HttpURLConnection request = BaseRequest.createURLConnection(uri, fileOptions, builder, opContext); request.setFixedLengthStreamingMode(0); request.setDoOutput(true); request.setRequestMethod(Constants.HTTP_PUT); if (accessCondition != null) { accessCondition.applyConditionToRequest(request); } if (properties != null) { addProperties(request, properties); } return request; }public static HttpURLConnection snapshotShare(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder builder = new UriQueryBuilder(); builder.add(Constants.QueryConstants.RESOURCETYPE, "share"); builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.SNAPSHOT); final HttpURLConnection request = BaseRequest.createURLConnection(uri, fileOptions, builder, opContext); request.setFixedLengthStreamingMode(0); request.setDoOutput(true); request.setRequestMethod(Constants.HTTP_PUT); if (accessCondition != null) { accessCondition.applyConditionToRequest(request); } return request; }public static HttpURLConnection setFileMetadata(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition) throws IOException, URISyntaxException, StorageException { return setMetadata(uri, fileOptions, opContext, accessCondition, null); }private static HttpURLConnection setMetadata(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition, final UriQueryBuilder builder) throws IOException, URISyntaxException, StorageException { final HttpURLConnection request = BaseRequest.setMetadata(uri, fileOptions, builder, opContext); if (accessCondition != null) { accessCondition.applyConditionToRequest(request); } return request; }public static HttpURLConnection resize(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition, final Long newFileSize) throws IOException, URISyntaxException, StorageException { final HttpURLConnection request = setFileProperties(uri, fileOptions, opContext, accessCondition, null); if (newFileSize != null) { request.setRequestProperty(FileConstants.CONTENT_LENGTH_HEADER, newFileSize.toString()); } return request; }public static HttpURLConnection putRange(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition, final FileRange range, FileRangeOperationType operationType) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder builder = new UriQueryBuilder(); builder.add(Constants.QueryConstants.COMPONENT, RANGE_QUERY_ELEMENT_NAME); final HttpURLConnection request = BaseRequest.createURLConnection(uri, fileOptions, builder, opContext); request.setDoOutput(true); request.setRequestMethod(Constants.HTTP_PUT); if (operationType == FileRangeOperationType.CLEAR) { request.setFixedLengthStreamingMode(0); } // Range write is either update or clear; required request.setRequestProperty(FileConstants.FILE_RANGE_WRITE, operationType.toString()); request.setRequestProperty(Constants.HeaderConstants.STORAGE_RANGE_HEADER, range.toString()); if (accessCondition != null) { accessCondition.applyConditionToRequest(request); } return request; }public static HttpURLConnection putFile(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition, final FileProperties properties, final long fileSize) throws IOException, URISyntaxException, StorageException { final HttpURLConnection request = BaseRequest.createURLConnection(uri, fileOptions, null, opContext); request.setDoOutput(true); request.setRequestMethod(Constants.HTTP_PUT); addProperties(request, properties); request.setFixedLengthStreamingMode(0); request.setRequestProperty(Constants.HeaderConstants.CONTENT_LENGTH, "0"); request.setRequestProperty(FileConstants.FILE_TYPE_HEADER, FileConstants.FILE); request.setRequestProperty(FileConstants.CONTENT_LENGTH_HEADER, String.valueOf(fileSize)); properties.setLength(fileSize); if (accessCondition != null) { accessCondition.applyConditionToRequest(request); } return request; }public static HttpURLConnection listFilesAndDirectories(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final ListingContext listingContext, String snapshotVersion) throws URISyntaxException, IOException, StorageException { final UriQueryBuilder builder = getDirectoryUriQueryBuilder(); addShareSnapshot(builder, snapshotVersion); builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.LIST); if (listingContext != null) { if (!Utility.isNullOrEmpty(listingContext.getMarker())) { builder.add(Constants.QueryConstants.MARKER, listingContext.getMarker()); } if (listingContext.getMaxResults() != null && listingContext.getMaxResults() > 0) { builder.add(Constants.QueryConstants.MAX_RESULTS, listingContext.getMaxResults().toString()); } if (!Utility.isNullOrEmpty(listingContext.getPrefix())) { builder.add(Constants.QueryConstants.PREFIX, listingContext.getPrefix().toString()); } } final HttpURLConnection request = BaseRequest.createURLConnection(uri, fileOptions, builder, opContext); request.setRequestMethod(Constants.HTTP_GET); return request; }public static HttpURLConnection getDirectoryProperties(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, AccessCondition accessCondition, String snapshotVersion) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder directoryBuilder = getDirectoryUriQueryBuilder(); return getProperties(uri, fileOptions, opContext, accessCondition, directoryBuilder, snapshotVersion); }public static HttpURLConnection deleteDirectory(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder directoryBuilder = getDirectoryUriQueryBuilder(); HttpURLConnection request = BaseRequest.delete(uri, fileOptions, directoryBuilder, opContext); if (accessCondition != null) { accessCondition.applyConditionToRequest(request); } return request; }public static HttpURLConnection createDirectory(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder directoryBuilder = getDirectoryUriQueryBuilder(); return BaseRequest.create(uri, fileOptions, directoryBuilder, opContext); }public static HttpURLConnection setDirectoryMetadata(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder directoryBuilder = getDirectoryUriQueryBuilder(); return setMetadata(uri, fileOptions, opContext, accessCondition, directoryBuilder); }public static HttpURLConnection setShareMetadata(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder shareBuilder = getShareUriQueryBuilder(); return setMetadata(uri, fileOptions, opContext, accessCondition, shareBuilder); }public static HttpURLConnection listShares(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final ListingContext listingContext, final EnumSet detailsIncluded) throws URISyntaxException, IOException, StorageException { final UriQueryBuilder builder = BaseRequest.getListUriQueryBuilder(listingContext); if (detailsIncluded != null && detailsIncluded.size() > 0) { final StringBuilder sb = new StringBuilder(); boolean started = false; if (detailsIncluded.contains(ShareListingDetails.SNAPSHOTS)) { started = true; sb.append(SNAPSHOTS_QUERY_ELEMENT_NAME); } if (detailsIncluded.contains(ShareListingDetails.METADATA)) { if (started) { sb.append(","); } sb.append(Constants.QueryConstants.METADATA); } builder.add(Constants.QueryConstants.INCLUDE, sb.toString()); } final HttpURLConnection request = BaseRequest.createURLConnection(uri, fileOptions, builder, opContext); request.setRequestMethod(Constants.HTTP_GET); return request; }private static HttpURLConnection getProperties(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, AccessCondition accessCondition, final UriQueryBuilder builder, String snapshotVersion) throws IOException, URISyntaxException, StorageException { addShareSnapshot(builder, snapshotVersion); HttpURLConnection request = BaseRequest.getProperties(uri, fileOptions, builder, opContext); if (accessCondition != null) { accessCondition.applyLeaseConditionToRequest(request); } return request; }private static UriQueryBuilder getShareUriQueryBuilder() throws StorageException { final UriQueryBuilder uriBuilder = new UriQueryBuilder(); try { uriBuilder.add(Constants.QueryConstants.RESOURCETYPE, "share"); } catch (final IllegalArgumentException e) { throw Utility.generateNewUnexpectedStorageException(e); } return uriBuilder; }public static HttpURLConnection getShareStats(final URI uri, final FileRequestOptions options, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { UriQueryBuilder shareBuilder = getShareUriQueryBuilder(); shareBuilder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.STATS); final HttpURLConnection retConnection = BaseRequest.createURLConnection(uri, options, shareBuilder, opContext); retConnection.setRequestMethod(Constants.HTTP_GET); return retConnection; }public static HttpURLConnection getShareProperties(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, AccessCondition accessCondition, final String snapshotVersion) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder shareBuilder = getShareUriQueryBuilder(); return getProperties(uri, fileOptions, opContext, accessCondition, shareBuilder, snapshotVersion); }public static HttpURLConnection getFileRanges(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition, final String snapshotVersion) throws StorageException, IOException, URISyntaxException { final UriQueryBuilder builder = new UriQueryBuilder(); addShareSnapshot(builder, snapshotVersion); builder.add(Constants.QueryConstants.COMPONENT, RANGE_LIST_QUERY_ELEMENT_NAME); final HttpURLConnection request = BaseRequest.createURLConnection(uri, fileOptions, builder, opContext); request.setRequestMethod(Constants.HTTP_GET); if (accessCondition != null) { accessCondition.applyConditionToRequest(request); } return request; }public static HttpURLConnection getFileProperties(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition, final String snapshotVersion) throws StorageException, IOException, URISyntaxException { final UriQueryBuilder builder = new UriQueryBuilder(); return getProperties(uri, fileOptions, opContext, accessCondition, builder, snapshotVersion); }public static HttpURLConnection getFile(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition, final String snapshotVersion, final Long offset, final Long count, boolean requestRangeContentMD5) throws IOException, URISyntaxException, StorageException { if (offset != null && requestRangeContentMD5) { Utility.assertNotNull("count", count); Utility.assertInBounds("count", count, 1, Constants.MAX_BLOCK_SIZE); } final UriQueryBuilder builder = new UriQueryBuilder(); FileRequest.addShareSnapshot(builder, snapshotVersion); final HttpURLConnection request = BaseRequest.createURLConnection(uri, fileOptions, builder, opContext); request.setRequestMethod(Constants.HTTP_GET); if (accessCondition != null) { accessCondition.applyConditionToRequest(request); } if (offset != null) { long rangeStart = offset; long rangeEnd; if (count != null) { rangeEnd = offset + count - 1; request.setRequestProperty(Constants.HeaderConstants.STORAGE_RANGE_HEADER, String.format( Utility.LOCALE_US, Constants.HeaderConstants.RANGE_HEADER_FORMAT, rangeStart, rangeEnd)); } else { request.setRequestProperty(Constants.HeaderConstants.STORAGE_RANGE_HEADER, String.format( Utility.LOCALE_US, Constants.HeaderConstants.BEGIN_RANGE_HEADER_FORMAT, rangeStart)); } } if (offset != null && requestRangeContentMD5) { request.setRequestProperty(Constants.HeaderConstants.RANGE_GET_CONTENT_MD5, Constants.TRUE); } return request; }public static HttpURLConnection getAcl(final URI uri, final FileRequestOptions fileOptions, final AccessCondition accessCondition, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder builder = getShareUriQueryBuilder(); builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.ACL); final HttpURLConnection request = BaseRequest.createURLConnection(uri, fileOptions, builder, opContext); request.setRequestMethod(Constants.HTTP_GET); if (accessCondition != null && !Utility.isNullOrEmpty(accessCondition.getLeaseID())) { accessCondition.applyLeaseConditionToRequest(request); } return request; }public static HttpURLConnection deleteShare(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition, String snapshotVersion, DeleteShareSnapshotsOption deleteSnapshotsOption) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder shareBuilder = getShareUriQueryBuilder(); FileRequest.addShareSnapshot(shareBuilder, snapshotVersion); HttpURLConnection request = BaseRequest.delete(uri, fileOptions, shareBuilder, opContext); if (accessCondition != null) { accessCondition.applyConditionToRequest(request); } switch (deleteSnapshotsOption) { case NONE: // nop break; case INCLUDE_SNAPSHOTS: request.setRequestProperty(Constants.HeaderConstants.DELETE_SNAPSHOT_HEADER, Constants.HeaderConstants.INCLUDE_SNAPSHOTS_VALUE); break; default: break; } return request; }public static HttpURLConnection createShare(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final FileShareProperties properties) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder shareBuilder = getShareUriQueryBuilder(); final HttpURLConnection request = BaseRequest.create(uri, fileOptions, shareBuilder, opContext); addProperties(request, properties); return request; }public static HttpURLConnection copyFrom(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition sourceAccessCondition, final AccessCondition destinationAccessCondition, String source) throws StorageException, IOException, URISyntaxException { final HttpURLConnection request = BaseRequest.createURLConnection(uri, fileOptions, null, opContext); request.setFixedLengthStreamingMode(0); request.setDoOutput(true); request.setRequestMethod(Constants.HTTP_PUT); request.setRequestProperty(Constants.HeaderConstants.COPY_SOURCE_HEADER, source); if (sourceAccessCondition != null) { sourceAccessCondition.applyConditionToRequest(request); } if (destinationAccessCondition != null) { destinationAccessCondition.applyConditionToRequest(request); } return request; }public static void addShareSnapshot(final UriQueryBuilder builder, final String snapshotVersion) throws StorageException { if (snapshotVersion != null) { builder.add(Constants.QueryConstants.SHARE_SNAPSHOT, snapshotVersion); } }public static HttpURLConnection abortCopy(final URI uri, final FileRequestOptions fileOptions, final OperationContext opContext, final AccessCondition accessCondition, final String copyId) throws StorageException, IOException, URISyntaxException { final UriQueryBuilder builder = new UriQueryBuilder(); builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.COPY); builder.add(Constants.QueryConstants.COPY_ID, copyId); final HttpURLConnection request = BaseRequest.createURLConnection(uri, fileOptions, builder, opContext); request.setFixedLengthStreamingMode(0); request.setDoOutput(true); request.setRequestMethod(Constants.HTTP_PUT); request.setRequestProperty(Constants.HeaderConstants.COPY_ACTION_HEADER, Constants.HeaderConstants.COPY_ACTION_ABORT); if (accessCondition != null) { accessCondition.applyConditionToRequest(request); } return request; }private static void writeLoggingProperties(final XmlSerializer xmlw, final LoggingProperties logging) throws IllegalArgumentException, IllegalStateException, IOException { Utility.assertNotNull("logging.LogOperationTypes", logging.getLogOperationTypes()); // Logging xmlw.startTag(Constants.EMPTY_STRING, Constants.AnalyticsConstants.LOGGING_ELEMENT); // Version Utility.serializeElement(xmlw, Constants.AnalyticsConstants.VERSION_ELEMENT, logging.getVersion()); // Delete Utility.serializeElement(xmlw, Constants.AnalyticsConstants.DELETE_ELEMENT, logging.getLogOperationTypes() .contains(LoggingOperations.DELETE) ? Constants.TRUE : Constants.FALSE); // Read Utility.serializeElement(xmlw, Constants.AnalyticsConstants.READ_ELEMENT, logging.getLogOperationTypes() .contains(LoggingOperations.READ) ? Constants.TRUE : Constants.FALSE); // Write Utility.serializeElement(xmlw, Constants.AnalyticsConstants.WRITE_ELEMENT, logging.getLogOperationTypes() .contains(LoggingOperations.WRITE) ? Constants.TRUE : Constants.FALSE); // Retention Policy writeRetentionPolicy(xmlw, logging.getRetentionIntervalInDays()); // end Logging xmlw.endTag(Constants.EMPTY_STRING, Constants.AnalyticsConstants.LOGGING_ELEMENT); }private static void writeMetricsProperties(final XmlSerializer xmlw, final MetricsProperties metrics, final String metricsName) throws IllegalArgumentException, IllegalStateException, IOException { Utility.assertNotNull("metrics.Configuration", metrics.getMetricsLevel()); // Metrics xmlw.startTag(Constants.EMPTY_STRING, metricsName); // Version Utility.serializeElement(xmlw, Constants.AnalyticsConstants.VERSION_ELEMENT, metrics.getVersion()); // Enabled Utility.serializeElement(xmlw, Constants.AnalyticsConstants.ENABLED_ELEMENT, metrics.getMetricsLevel() != MetricsLevel.DISABLED ? Constants.TRUE : Constants.FALSE); if (metrics.getMetricsLevel() != MetricsLevel.DISABLED) { // Include APIs Utility.serializeElement(xmlw, Constants.AnalyticsConstants.INCLUDE_APIS_ELEMENT, metrics.getMetricsLevel() == MetricsLevel.SERVICE_AND_API ? Constants.TRUE : Constants.FALSE); } // Retention Policy writeRetentionPolicy(xmlw, metrics.getRetentionIntervalInDays()); // end Metrics xmlw.endTag(Constants.EMPTY_STRING, metricsName); }private static void writeCorsProperties(final XmlSerializer xmlw, final CorsProperties cors) throws IllegalArgumentException, IllegalStateException, IOException { Utility.assertNotNull("CorsRules", cors.getCorsRules()); // CORS xmlw.startTag(Constants.EMPTY_STRING, Constants.AnalyticsConstants.CORS_ELEMENT); for (CorsRule rule : cors.getCorsRules()) { if (rule.getAllowedOrigins().isEmpty() || rule.getAllowedMethods().isEmpty() || rule.getMaxAgeInSeconds() < 0) { throw new IllegalArgumentException(SR.INVALID_CORS_RULE); } xmlw.startTag(Constants.EMPTY_STRING, Constants.AnalyticsConstants.CORS_RULE_ELEMENT); Utility.serializeElement(xmlw, Constants.AnalyticsConstants.ALLOWED_ORIGINS_ELEMENT, joinToString(rule.getAllowedOrigins(), ",")); Utility.serializeElement(xmlw, Constants.AnalyticsConstants.ALLOWED_METHODS_ELEMENT, joinToString(rule.getAllowedMethods(), ",")); Utility.serializeElement(xmlw, Constants.AnalyticsConstants.EXPOSED_HEADERS_ELEMENT, joinToString(rule.getExposedHeaders(), ",")); Utility.serializeElement(xmlw, Constants.AnalyticsConstants.ALLOWED_HEADERS_ELEMENT, joinToString(rule.getAllowedHeaders(), ",")); Utility.serializeElement(xmlw, Constants.AnalyticsConstants.MAX_AGE_IN_SECONDS_ELEMENT, Integer.toString(rule.getMaxAgeInSeconds())); xmlw.endTag(Constants.EMPTY_STRING, Constants.AnalyticsConstants.CORS_RULE_ELEMENT); } // end CORS xmlw.endTag(Constants.EMPTY_STRING, Constants.AnalyticsConstants.CORS_ELEMENT); }private static void writeRetentionPolicy(final XmlSerializer xmlw, final Integer val) throws IllegalArgumentException, IllegalStateException, IOException { xmlw.startTag(Constants.EMPTY_STRING, Constants.AnalyticsConstants.RETENTION_POLICY_ELEMENT); // Enabled Utility.serializeElement(xmlw, Constants.AnalyticsConstants.ENABLED_ELEMENT, val != null ? Constants.TRUE : Constants.FALSE); if (val != null) { // Days Utility.serializeElement(xmlw, Constants.AnalyticsConstants.DAYS_ELEMENT, val.toString()); } // End Retention Policy xmlw.endTag(Constants.EMPTY_STRING, Constants.AnalyticsConstants.RETENTION_POLICY_ELEMENT); }public static byte[] serializeToByteArray(final ServiceProperties properties) throws IllegalArgumentException, IllegalStateException, IOException { final StringWriter outWriter = new StringWriter(); final XmlSerializer xmlw = Utility.getXmlSerializer(outWriter); // default is UTF8 xmlw.startDocument(Constants.UTF8_CHARSET, true); xmlw.startTag(Constants.EMPTY_STRING, Constants.AnalyticsConstants.STORAGE_SERVICE_PROPERTIES_ELEMENT); if (properties.getLogging() != null) { // Logging Properties writeLoggingProperties(xmlw, properties.getLogging()); } if (properties.getHourMetrics() != null) { // Hour Metrics writeMetricsProperties(xmlw, properties.getHourMetrics(), Constants.AnalyticsConstants.HOUR_METRICS_ELEMENT); } if (properties.getMinuteMetrics() != null) { // Minute Metrics writeMetricsProperties(xmlw, properties.getMinuteMetrics(), Constants.AnalyticsConstants.MINUTE_METRICS_ELEMENT); } if (properties.getCors() != null) { // CORS Properties writeCorsProperties(xmlw, properties.getCors()); } // Default Service Version if (properties.getDefaultServiceVersion() != null) { Utility.serializeElement(xmlw, Constants.AnalyticsConstants.DEFAULT_SERVICE_VERSION, properties.getDefaultServiceVersion()); } // end StorageServiceProperties xmlw.endTag(Constants.EMPTY_STRING, Constants.AnalyticsConstants.STORAGE_SERVICE_PROPERTIES_ELEMENT); // end doc xmlw.endDocument(); return outWriter.toString().getBytes(Constants.UTF8_CHARSET); }public static HttpURLConnection setAcl(final URI rootUri, final TableRequestOptions options, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { UriQueryBuilder queryBuilder = new UriQueryBuilder(); queryBuilder.add(Constants.QueryConstants.COMPONENT, "acl"); final HttpURLConnection retConnection = BaseRequest.createURLConnection(rootUri, options, queryBuilder, opContext); retConnection.setRequestMethod("PUT"); retConnection.setDoOutput(true); return retConnection; }public static HttpURLConnection update(final URI rootUri, final TableRequestOptions tableOptions, final UriQueryBuilder queryBuilder, final OperationContext opContext, final String tableName, final String identity, final String eTag) throws IOException, URISyntaxException, StorageException { final HttpURLConnection retConnection = coreCreate(rootUri, tableOptions, queryBuilder, opContext, tableName, eTag, identity, "PUT"); retConnection.setDoOutput(true); return retConnection; }public static HttpURLConnection query(final URI rootUri, final TableRequestOptions tableOptions, UriQueryBuilder queryBuilder, final OperationContext opContext, final String tableName, final String identity, final ResultContinuation continuationToken) throws IOException, URISyntaxException, StorageException { if (queryBuilder == null) { queryBuilder = new UriQueryBuilder(); } applyContinuationToQueryBuilder(queryBuilder, continuationToken); final HttpURLConnection retConnection = coreCreate(rootUri, tableOptions, queryBuilder, opContext, tableName, null, identity, "GET"); return retConnection; }public static HttpURLConnection merge(final URI rootUri, final TableRequestOptions tableOptions, final UriQueryBuilder queryBuilder, final OperationContext opContext, final String tableName, final String identity, final String eTag) throws IOException, URISyntaxException, StorageException { final HttpURLConnection retConnection = coreCreate(rootUri, tableOptions, queryBuilder, opContext, tableName, eTag, identity, "POST"); retConnection.setRequestProperty(TableConstants.HeaderConstants.X_HTTP_METHOD, "MERGE"); retConnection.setDoOutput(true); return retConnection; }private static void applyContinuationToQueryBuilder(final UriQueryBuilder builder, final ResultContinuation continuationToken) throws StorageException { if (continuationToken != null) { if (continuationToken.getNextPartitionKey() != null) { builder.add(TableConstants.TABLE_SERVICE_NEXT_PARTITION_KEY, continuationToken.getNextPartitionKey()); } if (continuationToken.getNextRowKey() != null) { builder.add(TableConstants.TABLE_SERVICE_NEXT_ROW_KEY, continuationToken.getNextRowKey()); } if (continuationToken.getNextTableName() != null) { builder.add(TableConstants.TABLE_SERVICE_NEXT_TABLE_NAME, continuationToken.getNextTableName()); } } }public static ListResponse getFileAndDirectoryList(final InputStream stream, final CloudFileDirectory directory) throws ParserConfigurationException, SAXException, IOException { SAXParser saxParser = Utility.getSAXParser(); FileListHandler handler = new FileListHandler(directory); saxParser.parse(stream, handler); return handler.response; }public final String getMessageContentAsString() throws StorageException { if (this.messageType == QueueMessageType.RAW_STRING) { return this.messageContent; } else { if (Utility.isNullOrEmpty(this.messageContent)) { return null; } try { return new String(Base64.decode(this.messageContent), Constants.UTF8_CHARSET); } catch (final UnsupportedEncodingException e) { throw Utility.generateNewUnexpectedStorageException(e); } } }public final byte[] getMessageContentAsByte() throws StorageException { if (Utility.isNullOrEmpty(this.messageContent)) { return new byte[0]; } if (this.messageType == QueueMessageType.RAW_STRING) { try { return this.messageContent.getBytes(Constants.UTF8_CHARSET); } catch (final UnsupportedEncodingException e) { throw Utility.generateNewUnexpectedStorageException(e); } } else { return Base64.decode(this.messageContent); } }public CloudTable getMinuteMetricsTable(StorageService service, StorageLocation location) throws URISyntaxException, StorageException { Utility.assertNotNull("service", service); if (location == null) { location = StorageLocation.PRIMARY; } switch (service) { case BLOB: if (location == StorageLocation.PRIMARY) { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_MINUTE_PRIMARY_TRANSACTIONS_BLOB); } else { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_MINUTE_SECONDARY_TRANSACTIONS_BLOB); } case FILE: if (location == StorageLocation.PRIMARY) { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_MINUTE_PRIMARY_TRANSACTIONS_FILE); } else { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_MINUTE_SECONDARY_TRANSACTIONS_FILE); } case QUEUE: if (location == StorageLocation.PRIMARY) { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_MINUTE_PRIMARY_TRANSACTIONS_QUEUE); } else { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_MINUTE_SECONDARY_TRANSACTIONS_QUEUE); } case TABLE: if (location == StorageLocation.PRIMARY) { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_MINUTE_PRIMARY_TRANSACTIONS_TABLE); } else { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_MINUTE_SECONDARY_TRANSACTIONS_TABLE); } default: throw new IllegalArgumentException(SR.INVALID_STORAGE_SERVICE); } }public CloudTable getHourMetricsTable(StorageService service, StorageLocation location) throws URISyntaxException, StorageException { Utility.assertNotNull("service", service); if (location == null) { location = StorageLocation.PRIMARY; } switch (service) { case BLOB: if (location == StorageLocation.PRIMARY) { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_HOUR_PRIMARY_TRANSACTIONS_BLOB); } else { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_HOUR_SECONDARY_TRANSACTIONS_BLOB); } case FILE: if (location == StorageLocation.PRIMARY) { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_HOUR_PRIMARY_TRANSACTIONS_FILE); } else { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_HOUR_SECONDARY_TRANSACTIONS_FILE); } case QUEUE: if (location == StorageLocation.PRIMARY) { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_HOUR_PRIMARY_TRANSACTIONS_QUEUE); } else { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_HOUR_SECONDARY_TRANSACTIONS_QUEUE); } case TABLE: if (location == StorageLocation.PRIMARY) { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_HOUR_PRIMARY_TRANSACTIONS_TABLE); } else { return this.tableClient.getTableReference( Constants.AnalyticsConstants.METRICS_HOUR_SECONDARY_TRANSACTIONS_TABLE); } default: throw new IllegalArgumentException(SR.INVALID_STORAGE_SERVICE); } }private final StorageUri getTransformedAddress(final OperationContext opContext) throws URISyntaxException, StorageException { return this.queueServiceClient.getCredentials().transformUri(this.getStorageUri(), opContext); }@DoesServiceRequest public QueuePermissions downloadPermissions(QueueRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient); return ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.downloadPermissionsImpl(options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public void uploadPermissions(final QueuePermissions permissions, QueueRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient); ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.uploadPermissionsImpl(permissions, options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public void updateMessage(final CloudQueueMessage message, final int visibilityTimeoutInSeconds, final EnumSet messageUpdateFields, QueueRequestOptions options, OperationContext opContext) throws StorageException { Utility.assertNotNull("message", message); Utility.assertNotNullOrEmpty("messageId", message.getId()); Utility.assertNotNullOrEmpty("popReceipt", message.getPopReceipt()); Utility.assertInBounds("visibilityTimeoutInSeconds", visibilityTimeoutInSeconds, 0, QueueConstants.MAX_TIME_TO_LIVE_IN_SECONDS); if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient); ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.updateMessageImpl(message, visibilityTimeoutInSeconds, messageUpdateFields, options), options.getRetryPolicyFactory(), opContext); }public void updateMessage(final CloudQueueMessage message, final int visibilityTimeoutInSeconds) throws StorageException { this.updateMessage(message, visibilityTimeoutInSeconds, EnumSet.of(MessageUpdateFields.VISIBILITY), null /* options */, null /* opContext */); }@DoesServiceRequest public Iterable retrieveMessages(final int numberOfMessages, final int visibilityTimeoutInSeconds, QueueRequestOptions options, OperationContext opContext) throws StorageException { Utility.assertInBounds("numberOfMessages", numberOfMessages, 1, QueueConstants.MAX_NUMBER_OF_MESSAGES_TO_PEEK); Utility.assertInBounds("visibilityTimeoutInSeconds", visibilityTimeoutInSeconds, 0, QueueConstants.MAX_TIME_TO_LIVE_IN_SECONDS); if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient); return ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.retrieveMessagesImpl(numberOfMessages, visibilityTimeoutInSeconds, options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public Iterable retrieveMessages(final int numberOfMessages) throws StorageException { return this.retrieveMessages(numberOfMessages, QueueConstants.DEFAULT_VISIBILITY_MESSAGE_TIMEOUT_IN_SECONDS, null /* options */, null /* opContext */); }@DoesServiceRequest public CloudQueueMessage retrieveMessage(final int visibilityTimeoutInSeconds, final QueueRequestOptions options, final OperationContext opContext) throws StorageException { return getFirstOrNull(this.retrieveMessages(1, visibilityTimeoutInSeconds, options, opContext)); }@DoesServiceRequest public Iterable peekMessages(final int numberOfMessages, QueueRequestOptions options, OperationContext opContext) throws StorageException { Utility.assertInBounds("numberOfMessages", numberOfMessages, 1, QueueConstants.MAX_NUMBER_OF_MESSAGES_TO_PEEK); if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient); return ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.peekMessagesImpl(numberOfMessages, options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public Iterable peekMessages(final int numberOfMessages) throws StorageException { return this.peekMessages(numberOfMessages, null /* options */, null /* opContext */); }@DoesServiceRequest public CloudQueueMessage peekMessage(final QueueRequestOptions options, final OperationContext opContext) throws StorageException { return getFirstOrNull(this.peekMessages(1, null /* options */, null /* opContext */)); }@DoesServiceRequest public boolean exists(QueueRequestOptions options, OperationContext opContext) throws StorageException { return this.exists(false, options, opContext); }@DoesServiceRequest public void downloadAttributes(QueueRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient); ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.downloadAttributesImpl(options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public void deleteMessage(final CloudQueueMessage message, QueueRequestOptions options, OperationContext opContext) throws StorageException { Utility.assertNotNull("message", message); Utility.assertNotNullOrEmpty("messageId", message.getId()); Utility.assertNotNullOrEmpty("popReceipt", message.getPopReceipt()); if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient); ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.deleteMessageImpl(message, options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public boolean deleteIfExists(QueueRequestOptions options, OperationContext opContext) throws StorageException { options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient); boolean exists = this.exists(true, options, opContext); if (exists) { try { this.delete(options, opContext); return true; } catch (StorageException e) { if (e.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND && StorageErrorCodeStrings.QUEUE_NOT_FOUND.equals(e.getErrorCode())) { return false; } else { throw e; } } } else { return false; } }@DoesServiceRequest public void delete(QueueRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient); ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.deleteImpl(options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public boolean createIfNotExists(QueueRequestOptions options, OperationContext opContext) throws StorageException { options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient); boolean exists = this.exists(true, options, opContext); if (exists) { return false; } else { try { this.create(options, opContext); return true; } catch (StorageException e) { if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT && StorageErrorCodeStrings.QUEUE_ALREADY_EXISTS.equals(e.getErrorCode())) { return false; } else { throw e; } } } }@DoesServiceRequest public void create(QueueRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient); ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.createImpl(options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public void clear(QueueRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient); ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.clearImpl(options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public void addMessage(final CloudQueueMessage message, final int timeToLiveInSeconds, final int initialVisibilityDelayInSeconds, QueueRequestOptions options, OperationContext opContext) throws StorageException { Utility.assertNotNull("message", message); Utility.assertNotNull("messageContent", message.getMessageContentAsByte()); Utility.assertInBounds("timeToLiveInSeconds", timeToLiveInSeconds, 0, QueueConstants.MAX_TIME_TO_LIVE_IN_SECONDS); final int realTimeToLiveInSeconds = timeToLiveInSeconds == 0 ? QueueConstants.MAX_TIME_TO_LIVE_IN_SECONDS : timeToLiveInSeconds; Utility.assertInBounds("initialVisibilityDelayInSeconds", initialVisibilityDelayInSeconds, 0, realTimeToLiveInSeconds - 1); if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = QueueRequestOptions.populateAndApplyDefaults(options, this.queueServiceClient); ExecutionEngine.executeWithRetry(this.queueServiceClient, this, this.addMessageImpl(message, realTimeToLiveInSeconds, initialVisibilityDelayInSeconds, options), options.getRetryPolicyFactory(), opContext); }private static CloudQueueMessage getFirstOrNull(final Iterable messages) { for (final CloudQueueMessage m : messages) { return m; } return null; }public static void signTableRequest(final StorageCredentials creds, final java.net.HttpURLConnection request, final long contentLength, OperationContext opContext) throws InvalidKeyException, StorageException { if (creds.getClass().equals(StorageCredentialsAccountAndKey.class)) { opContext = opContext == null ? new OperationContext() : opContext; request.setRequestProperty(Constants.HeaderConstants.DATE, Utility.getGMTTime()); final Canonicalizer canonicalizer = CanonicalizerFactory.getTableCanonicalizer(request); final String stringToSign = canonicalizer.canonicalize(request, creds.getAccountName(), contentLength); final String computedBase64Signature = StorageCredentialsHelper.computeHmac256(creds, stringToSign); Logger.debug(opContext, LogConstants.SIGNING, stringToSign); request.setRequestProperty(Constants.HeaderConstants.AUTHORIZATION, String.format("%s %s:%s", "SharedKey", creds.getAccountName(), computedBase64Signature)); } }public static synchronized String computeHmac256(final StorageCredentials creds, final String value) throws InvalidKeyException { if (creds.getClass().equals(StorageCredentialsAccountAndKey.class)) { byte[] utf8Bytes = null; try { utf8Bytes = value.getBytes(Constants.UTF8_CHARSET); } catch (final UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } return Base64.encode(((StorageCredentialsAccountAndKey) creds).getHmac256().doFinal(utf8Bytes)); } else { return null; } }protected static String canonicalizeTableHttpRequest(final java.net.URL address, final String accountName, final String method, final String contentType, final long contentLength, final String date, final HttpURLConnection conn) throws StorageException { // The first element should be the Method of the request. // I.e. GET, POST, PUT, or HEAD. final StringBuilder canonicalizedString = new StringBuilder(ExpectedTableCanonicalizedStringLength); canonicalizedString.append(conn.getRequestMethod()); // The second element should be the MD5 value. // This is optional and may be empty. final String httpContentMD5Value = Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_MD5); appendCanonicalizedElement(canonicalizedString, httpContentMD5Value); // The third element should be the content type. appendCanonicalizedElement(canonicalizedString, contentType); // The fourth element should be the request date. // See if there's an storage date header. // If there's one, then don't use the date header. final String dateString = Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.DATE); // If x-ms-date header exists, Date should be that value. appendCanonicalizedElement(canonicalizedString, dateString.equals(Constants.EMPTY_STRING) ? date : dateString); appendCanonicalizedElement(canonicalizedString, getCanonicalizedResourceLite(address, accountName)); return canonicalizedString.toString(); }protected static String canonicalizeHttpRequest(final java.net.URL address, final String accountName, final String method, final String contentType, final long contentLength, final String date, final HttpURLConnection conn) throws StorageException { // The first element should be the Method of the request. // I.e. GET, POST, PUT, or HEAD. final StringBuilder canonicalizedString = new StringBuilder(ExpectedBlobQueueCanonicalizedStringLength); canonicalizedString.append(conn.getRequestMethod()); // The next elements are // If any element is missing it may be empty. appendCanonicalizedElement(canonicalizedString, Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_ENCODING)); appendCanonicalizedElement(canonicalizedString, Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_LANGUAGE)); appendCanonicalizedElement(canonicalizedString, contentLength <= 0 ? Constants.EMPTY_STRING : String.valueOf(contentLength)); appendCanonicalizedElement(canonicalizedString, Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_MD5)); appendCanonicalizedElement(canonicalizedString, contentType != null ? contentType : Constants.EMPTY_STRING); final String dateString = Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.DATE); // If x-ms-date header exists, Date should be empty string appendCanonicalizedElement(canonicalizedString, dateString.equals(Constants.EMPTY_STRING) ? date : Constants.EMPTY_STRING); appendCanonicalizedElement(canonicalizedString, Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.IF_MODIFIED_SINCE)); appendCanonicalizedElement(canonicalizedString, Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.IF_MATCH)); appendCanonicalizedElement(canonicalizedString, Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.IF_NONE_MATCH)); appendCanonicalizedElement(canonicalizedString, Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.IF_UNMODIFIED_SINCE)); appendCanonicalizedElement(canonicalizedString, Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.RANGE)); addCanonicalizedHeaders(conn, canonicalizedString); appendCanonicalizedElement(canonicalizedString, getCanonicalizedResource(address, accountName)); return canonicalizedString.toString(); }protected static void appendCanonicalizedElement(final StringBuilder builder, final String element) { builder.append("\n"); builder.append(element); }private static void addCanonicalizedHeaders(final HttpURLConnection conn, final StringBuilder canonicalizedString) { // Look for header names that start with // HeaderNames.PrefixForStorageHeader // Then sort them in case-insensitive manner. final Map> headers = conn.getRequestProperties(); final ArrayList httpStorageHeaderNameArray = new ArrayList(); for (final String key : headers.keySet()) { if (key.toLowerCase(Utility.LOCALE_US).startsWith(Constants.PREFIX_FOR_STORAGE_HEADER)) { httpStorageHeaderNameArray.add(key.toLowerCase(Utility.LOCALE_US)); } } Collections.sort(httpStorageHeaderNameArray); // Now go through each header's values in the sorted order and append // them to the canonicalized string. for (final String key : httpStorageHeaderNameArray) { final StringBuilder canonicalizedElement = new StringBuilder(key); String delimiter = ":"; final ArrayList values = getHeaderValues(headers, key); boolean appendCanonicalizedElement = false; // Go through values, unfold them, and then append them to the // canonicalized element string. for (final String value : values) { if (value != null) { appendCanonicalizedElement = true; } // Unfolding is simply removal of CRLF. final String unfoldedValue = CRLF.matcher(value) .replaceAll(Matcher.quoteReplacement(Constants.EMPTY_STRING)); // Append it to the canonicalized element string. canonicalizedElement.append(delimiter); canonicalizedElement.append(unfoldedValue); delimiter = ","; } // Now, add this canonicalized element to the canonicalized header // string. if (appendCanonicalizedElement) { appendCanonicalizedElement(canonicalizedString, canonicalizedElement.toString()); } } }public static byte[] generateMessageRequestBody(final String message) throws IllegalArgumentException, IllegalStateException, IOException { final StringWriter outWriter = new StringWriter(); final XmlSerializer xmlw = Utility.getXmlSerializer(outWriter); // default is UTF8 xmlw.startDocument(Constants.UTF8_CHARSET, true); xmlw.startTag(Constants.EMPTY_STRING, QueueConstants.QUEUE_MESSAGE_ELEMENT); Utility.serializeElement(xmlw, QueueConstants.MESSAGE_TEXT_ELEMENT, message); // end QueueMessage_ELEMENT xmlw.endTag(Constants.EMPTY_STRING, QueueConstants.QUEUE_MESSAGE_ELEMENT); // end doc xmlw.endDocument(); return outWriter.toString().getBytes(Constants.UTF8_CHARSET); }public static void writeSharedAccessIdentifiersToStream( final HashMap sharedAccessPolicies, final StringWriter outWriter) throws IllegalArgumentException, IllegalStateException, IOException { Utility.assertNotNull("sharedAccessPolicies", sharedAccessPolicies); Utility.assertNotNull("outWriter", outWriter); final XmlSerializer xmlw = Utility.getXmlSerializer(outWriter); if (sharedAccessPolicies.keySet().size() > Constants.MAX_SHARED_ACCESS_POLICY_IDENTIFIERS) { final String errorMessage = String.format(SR.TOO_MANY_SHARED_ACCESS_POLICY_IDENTIFIERS, sharedAccessPolicies.keySet().size(), Constants.MAX_SHARED_ACCESS_POLICY_IDENTIFIERS); throw new IllegalArgumentException(errorMessage); } // default is UTF8 xmlw.startDocument(Constants.UTF8_CHARSET, true); xmlw.startTag(Constants.EMPTY_STRING, Constants.SIGNED_IDENTIFIERS_ELEMENT); for (final Entry entry : sharedAccessPolicies.entrySet()) { final SharedAccessPolicy policy = entry.getValue(); xmlw.startTag(Constants.EMPTY_STRING, Constants.SIGNED_IDENTIFIER_ELEMENT); // Set the identifier Utility.serializeElement(xmlw, Constants.ID, entry.getKey()); xmlw.startTag(Constants.EMPTY_STRING, Constants.ACCESS_POLICY); // Set the Start Time Utility.serializeElement(xmlw, Constants.START, Utility .getUTCTimeOrEmpty(policy.getSharedAccessStartTime()).toString()); // Set the Expiry Time Utility.serializeElement(xmlw, Constants.EXPIRY, Utility.getUTCTimeOrEmpty(policy.getSharedAccessExpiryTime()).toString()); // Set the Permissions Utility.serializeElement(xmlw, Constants.PERMISSION, policy.permissionsToString()); // end AccessPolicy xmlw.endTag(Constants.EMPTY_STRING, Constants.ACCESS_POLICY); // end SignedIdentifier xmlw.endTag(Constants.EMPTY_STRING, Constants.SIGNED_IDENTIFIER_ELEMENT); } // end SignedIdentifiers xmlw.endTag(Constants.EMPTY_STRING, Constants.SIGNED_IDENTIFIERS_ELEMENT); // end doc xmlw.endDocument(); }protected final void setStorageUri(final StorageUri storageUri) { this.usePathStyleUris = Utility.determinePathStyleFromUri(storageUri.getPrimaryUri()); this.storageUri = storageUri; }public static String combineFilters(String filterA, String operator, String filterB) { return String.format("(%s) %s (%s)", filterA, operator, filterB); }public boolean verifyConditional(final String etag, final Date lastModified) { if (this.ifModifiedSinceDate != null) { // The IfModifiedSince has a special helper in HttpURLConnection, use it instead of manually setting the // header. if (!lastModified.after(this.ifModifiedSinceDate)) { return false; } } if (this.ifUnmodifiedSinceDate != null) { if (lastModified.after(this.ifUnmodifiedSinceDate)) { return false; } } if (!Utility.isNullOrEmpty(this.ifMatchETag)) { if (!this.ifMatchETag.equals(etag) && !this.ifMatchETag.equals("*")) { return false; } } if (!Utility.isNullOrEmpty(this.ifNoneMatchETag)) { if (this.ifNoneMatchETag.equals(etag)) { return false; } } return true; }public void applySequenceConditionToRequest(final HttpURLConnection request) { if (this.ifSequenceNumberLessThanOrEqual != null) { request.setRequestProperty( Constants.HeaderConstants.IF_SEQUENCE_NUMBER_LESS_THAN_OR_EQUAL, this.ifSequenceNumberLessThanOrEqual.toString()); } if (this.ifSequenceNumberLessThan != null) { request.setRequestProperty( Constants.HeaderConstants.IF_SEQUENCE_NUMBER_LESS_THAN, this.ifSequenceNumberLessThan.toString()); } if (this.ifSequenceNumberEqual != null) { request.setRequestProperty( Constants.HeaderConstants.IF_SEQUENCE_NUMBER_EQUAL, this.ifSequenceNumberEqual.toString()); } }public void applyLeaseConditionToRequest(final HttpURLConnection request) { if (!Utility.isNullOrEmpty(this.leaseID)) { request.setRequestProperty(Constants.HeaderConstants.LEASE_ID_HEADER, this.leaseID); } }public void applyAppendConditionToRequest(final HttpURLConnection request) { if (this.ifMaxSizeLessThanOrEqual != null) { request.setRequestProperty(Constants.HeaderConstants.IF_MAX_SIZE_LESS_THAN_OR_EQUAL, this.ifMaxSizeLessThanOrEqual.toString()); } if (this.ifAppendPositionEqual != null) { request.setRequestProperty(Constants.HeaderConstants.IF_APPEND_POSITION_EQUAL_HEADER, this.ifAppendPositionEqual.toString()); } }public void applySourceConditionToRequest(final HttpURLConnection request) { if (!Utility.isNullOrEmpty(this.leaseID)) { // Unsupported throw new IllegalArgumentException(SR.LEASE_CONDITION_ON_SOURCE); } if (this.ifModifiedSinceDate != null) { request.setRequestProperty( Constants.HeaderConstants.SOURCE_IF_MODIFIED_SINCE_HEADER, Utility.getGMTTime(this.ifModifiedSinceDate)); } if (this.ifUnmodifiedSinceDate != null) { request.setRequestProperty(Constants.HeaderConstants.SOURCE_IF_UNMODIFIED_SINCE_HEADER, Utility.getGMTTime(this.ifUnmodifiedSinceDate)); } if (!Utility.isNullOrEmpty(this.ifMatchETag)) { request.setRequestProperty( Constants.HeaderConstants.SOURCE_IF_MATCH_HEADER, this.ifMatchETag); } if (!Utility.isNullOrEmpty(this.ifNoneMatchETag)) { request.setRequestProperty( Constants.HeaderConstants.SOURCE_IF_NONE_MATCH_HEADER, this.ifNoneMatchETag); } }public void applyConditionToRequest(final HttpURLConnection request) { applyLeaseConditionToRequest(request); if (this.ifModifiedSinceDate != null) { request.setRequestProperty(Constants.HeaderConstants.IF_MODIFIED_SINCE, Utility.getGMTTime(this.ifModifiedSinceDate)); } if (this.ifUnmodifiedSinceDate != null) { request.setRequestProperty(Constants.HeaderConstants.IF_UNMODIFIED_SINCE, Utility.getGMTTime(this.ifUnmodifiedSinceDate)); } if (!Utility.isNullOrEmpty(this.ifMatchETag)) { request.setRequestProperty(Constants.HeaderConstants.IF_MATCH, this.ifMatchETag); } if (!Utility.isNullOrEmpty(this.ifNoneMatchETag)) { request.setRequestProperty(Constants.HeaderConstants.IF_NONE_MATCH, this.ifNoneMatchETag); } }public static AccessCondition generateIfSequenceNumberEqualCondition(long sequenceNumber) { AccessCondition retCondition = new AccessCondition(); retCondition.ifSequenceNumberEqual = sequenceNumber; return retCondition; }public static AccessCondition generateIfSequenceNumberLessThanCondition(long sequenceNumber) { AccessCondition retCondition = new AccessCondition(); retCondition.ifSequenceNumberLessThan = sequenceNumber; return retCondition; }public static AccessCondition generateIfSequenceNumberLessThanOrEqualCondition(long sequenceNumber) { AccessCondition retCondition = new AccessCondition(); retCondition.ifSequenceNumberLessThanOrEqual = sequenceNumber; return retCondition; }public static StorageExtendedErrorInformation getExtendedErrorInformation(final InputStream stream) throws SAXException, IOException, ParserConfigurationException { SAXParser saxParser = Utility.getSAXParser(); StorageErrorHandler handler = new StorageErrorHandler(); saxParser.parse(stream, handler); return handler.errorInfo; }protected static void applyBaseDefaultsInternal(final RequestOptions modifiedOptions) { Utility.assertNotNull("modifiedOptions", modifiedOptions); if (modifiedOptions.getRetryPolicyFactory() == null) { modifiedOptions.setRetryPolicyFactory(new RetryExponentialRetry()); } if (modifiedOptions.getLocationMode() == null) { modifiedOptions.setLocationMode(LocationMode.PRIMARY_ONLY); } }@DoesServiceRequest public TablePermissions downloadPermissions(TableRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient); return ExecutionEngine.executeWithRetry(this.tableServiceClient, this, this.downloadPermissionsImpl(options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public void uploadPermissions(final TablePermissions permissions, TableRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient); ExecutionEngine.executeWithRetry(this.tableServiceClient, this, this.uploadPermissionsImpl(permissions, options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public boolean deleteIfExists(TableRequestOptions options, OperationContext opContext) throws StorageException { options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient); if (this.exists(true, options, opContext)) { try { this.delete(options, opContext); } catch (StorageException ex) { if (ex.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND && StorageErrorCodeStrings.RESOURCE_NOT_FOUND.equals(ex.getErrorCode())) { return false; } else { throw ex; } } return true; } else { return false; } }@DoesServiceRequest public void delete(TableRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient); Utility.assertNotNullOrEmpty("tableName", this.name); final DynamicTableEntity tableEntry = new DynamicTableEntity(); tableEntry.getProperties().put(TableConstants.TABLE_NAME, new EntityProperty(this.name)); TableOperation deleteOp = new TableOperation(tableEntry, TableOperationType.DELETE); deleteOp.execute(this.tableServiceClient, TableConstants.TABLES_SERVICE_TABLES_NAME, options, opContext); }@DoesServiceRequest public boolean createIfNotExists(TableRequestOptions options, OperationContext opContext) throws StorageException { options = TableRequestOptions.populateAndApplyDefaults(options, this.tableServiceClient); boolean exists = this.exists(true, options, opContext); if (exists) { return false; } else { try { this.create(options, opContext); return true; } catch (StorageException e) { if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT && StorageErrorCodeStrings.TABLE_ALREADY_EXISTS.equals(e.getErrorCode())) { return false; } else { throw e; } } } }public static ArrayList readMessages(final InputStream stream, final boolean shouldEncodeMessage) throws SAXException, IOException, ParserConfigurationException { SAXParser saxParser = Utility.getSAXParser(); QueueMessageHandler handler = new QueueMessageHandler(shouldEncodeMessage); saxParser.parse(stream, handler); return handler.messages; }protected static ArrayList getFileRanges(InputStream streamRef) throws ParserConfigurationException, SAXException, IOException { SAXParser saxParser = Utility.getSAXParser(); FileRangeHandler handler = new FileRangeHandler(); saxParser.parse(streamRef, handler); return handler.fileRanges; }public KeycloakConfig setSystemProperties() { if ( !isEnabled() ) { return this; } final Properties properties = System.getProperties(); properties.setProperty( KEYCLOAK_REALM, getRealm() ); properties.setProperty( KEYCLOAK_URL, getUrl() ); if ( getServerResource() != null ) { properties.setProperty( KEYCLOAK_SERVER_RESOURCE, getServerResource() ); } if ( getServerCredentialSecret() != null ) { properties.setProperty( KEYCLOAK_SERVER_CREDENTIAL_SECRET, getServerCredentialSecret() ); } if ( getRealmPublicKey() != null ) { properties.setProperty( KEYCLOAK_REALM_PUBLIC_KEY, getRealmPublicKey() ); } System.setProperties( properties ); return this; }private void handleGroupMembersChanged(final ArtifactStore store, final Map changeMap) { final StoreKey key = store.getKey(); if ( StoreType.group == key.getType() ) { final List newMembers = ( (Group) store ).getConstituents(); logger.trace( "New members of: {} are: {}", store.getKey(), newMembers ); final Group group = (Group) changeMap.get( store ); final List oldMembers = group.getConstituents(); logger.trace( "Old members of: {} are: {}", group.getName(), oldMembers ); boolean membersChanged = false; if ( newMembers.size() != oldMembers.size() ) { membersChanged = true; } else { for ( StoreKey storeKey : newMembers ) { if ( !oldMembers.contains( storeKey ) ) { membersChanged = true; } } } if ( membersChanged ) { logger.trace( "Membership change confirmed. Clearing caches for group: {} and groups affected by it.", group.getKey() ); clearGroupMetaCache( group, group ); try { storeManager.query().getGroupsAffectedBy( group.getKey() ).forEach( g -> clearGroupMetaCache( g, group ) ); } catch ( IndyDataException e ) { logger.error( String.format( "Can not get affected groups of %s", group.getKey() ), e ); } } else { logger.trace( "No members changed, no need to expunge merged metadata" ); } } }private KojiRepairResult.RepairResult doRepair( String packageType, RemoteRepository repository, KojiBuildInfo buildInfo, String user, boolean isDryRun ) throws KojiRepairException { StoreKey storeKey; if ( repository != null ) { storeKey = repository.getKey(); } else { String name = kojiUtils.getRepositoryName( buildInfo ); storeKey = new StoreKey( packageType, StoreType.remote, name ); try { repository = (RemoteRepository) storeManager.getArtifactStore( storeKey ); } catch ( IndyDataException e ) { throw new KojiRepairException( "Cannot get store: %s. Reason: %s", e, storeKey, e.getMessage() ); } } KojiRepairResult.RepairResult repairResult = new KojiRepairResult.RepairResult( storeKey ); String url = repository.getUrl(); String newUrl; try { newUrl = kojiUtils.formatStorageUrl( config.getStorageRootUrl(), buildInfo ); // volume is involved } catch ( MalformedURLException e ) { throw new KojiRepairException( "Failed to format storage Url: %s. Reason: %s", e, storeKey, e.getMessage() ); } boolean changed = !url.equals( newUrl ); if ( changed ) { repairResult.withPropertyChange( "url", url, newUrl ); if ( !isDryRun ) { ChangeSummary changeSummary = new ChangeSummary( user, "Repair " + storeKey + " url with volume: " + buildInfo .getVolumeName() ); repository.setUrl( newUrl ); repository.setMetadata( METADATA_KOJI_BUILD_ID, Integer.toString( buildInfo.getId() ) ); boolean fireEvents = false; boolean skipIfExists = false; try { storeManager.storeArtifactStore( repository, changeSummary, skipIfExists, fireEvents, new EventMetadata() ); } catch ( IndyDataException e ) { throw new KojiRepairException( "Failed to repair store: %s. Reason: %s", e, storeKey, e.getMessage() ); } } } return repairResult; }public CloseableHttpClient createClient( final String siteId ) throws IndyHttpException { try { return httpFactory.createClient( siteConfigLookup.lookup( siteId ) ); } catch ( JHttpCException e ) { throw new IndyHttpException( "Failed to create http client: %s", e, e.getMessage() ); } }public HttpClientContext createContext( final String siteId ) throws IndyHttpException { try { return httpFactory.createContext( siteConfigLookup.lookup( siteId ) ); } catch ( JHttpCException e ) { throw new IndyHttpException( "Failed to create http client context: %s", e, e.getMessage() ); } }public HostedRepository createStoreByArc( final InputStream fileInput, final String repoName, final String user, final String ignoredPrefix ) throws IndyWorkflowException { final HostedRepository repo = createHostedByName( repoName, user, "Create hosted by zip." ); storeZipContentInHosted( fileInput, ignoredPrefix, repo ); return repo; }public static void loadFromDiskAnd( DataFileManager manager, IndyObjectMapper serializer, StoreKey key, final ChangeSummary summary, Consumer consumer ) { if ( key != null ) // Load a single file { DataFile f = manager.getDataFile( INDY_STORE, key.getPackageType(), key.getType().singularEndpointName(), key.getName() + ".json" ); if ( f.exists() ) { ArtifactStore store; try { String json = f.readString(); store = serializer.readValue( json, key.getType().getStoreClass() ); } catch ( IOException e ) { logger.error( "Failed to read file", e ); return; } consumer.accept( store ); } return; } // Load all DataFile[] packageDirs = manager.getDataFile( INDY_STORE ).listFiles( ( f ) -> true ); for ( DataFile pkgDir : packageDirs ) { for ( StoreType type : StoreType.values() ) { DataFile[] files = pkgDir.getChild( type.singularEndpointName() ).listFiles( f -> true ); if ( files != null ) { for ( final DataFile f : files ) { try { final String json = f.readString(); final ArtifactStore store = serializer.readValue( json, type.getStoreClass() ); if ( store == null ) { f.delete( summary ); } else { consumer.accept( store ); } } catch ( final IOException e ) { logger.error( String.format( "Failed to load %s store: %s. Reason: %s", type, f, e.getMessage() ), e ); try { f.delete( summary ); } catch ( IOException e1 ) { logger.error( "Failed to delete invalid store definition file: " + f, e ); } } } } } } }public static void loadFromDiskAnd( DataFileManager manager, IndyObjectMapper serializer, final ChangeSummary summary, Consumer consumer ) { loadFromDiskAnd( manager, serializer, null, summary, consumer ); }@ApiOperation( "Check if a given store exists" ) @ApiResponses( { @ApiResponse( code = 200, message = "The store exists" ), @ApiResponse( code = 404, message = "The store doesn't exist" ) } ) @Path( "/{name}" ) @HEAD public Response exists( final @PathParam( "packageType" ) String packageType, final @ApiParam( allowableValues = "hosted,group,remote", required = true ) @PathParam( "type" ) String type, @ApiParam( required = true ) @PathParam( "name" ) final String name ) { Response response; final StoreType st = StoreType.get( type ); logger.info( "Checking for existence of: {}:{}:{}", packageType, st, name ); if ( adminController.exists( new StoreKey( packageType, st, name ) ) ) { logger.info( "returning OK" ); response = Response.ok().build(); } else { logger.info( "Returning NOT FOUND" ); response = Response.status( Status.NOT_FOUND ).build(); } return response; }public String parse( String repoName ) { String prefix = null; if ( repoName.startsWith( KOJI_BINARY_ ) ) { prefix = KOJI_BINARY_; } else if ( repoName.startsWith( KOJI_ ) ) { prefix = KOJI_; } if ( prefix != null ) { return repoName.substring( prefix.length() ); } return null; }private void clearObsoleteFiles( Transfer item ) { Transfer httpMeta = item.getSiblingMeta( HTTP_METADATA_EXT ); try { httpMeta.delete(); } catch ( IOException e ) { logger.warn( "Failed to delete {}", httpMeta.getResource() ); } }public static boolean checkListingMask( final ArtifactStore store, final String path ) { Set maskPatterns = store.getPathMaskPatterns(); logger.trace( "Checking mask in: {}", store.getKey() ); logger.trace( "Mask patterns in {}: {}", store.getName(), maskPatterns ); if (maskPatterns == null || maskPatterns.isEmpty()) { logger.trace( "Checking mask in: {}, - NO PATTERNS", store.getName() ); return true; } for ( String pattern : maskPatterns ) { if ( isRegexPattern( pattern ) ) { // if there is a regexp pattern we cannot check presence of directory listing, because we would have to // check only the beginning of the regexp and that's impossible, so we have to assume that the path is // present return true; } } for ( String pattern : maskPatterns ) { if ( path.startsWith( pattern ) || pattern.startsWith( path ) ) { logger.trace( "Checking mask in: {}, pattern: {} - MATCH", store.getName(), pattern ); return true; } } logger.debug( "Listing for path {} not enabled by path mask {} of repo {}", path, maskPatterns, store.getKey() ); return false; }private StoreKey getTargetKey( final String targetName ) { return targetGroupKeyMap.computeIfAbsent( targetName, k -> new StoreKey( MavenPackageTypeDescriptor.MAVEN_PKG_KEY, StoreType.group, targetName ) ); }public static int readZipInputStreamAnd( InputStream inputStream, Consumer consumer ) throws IOException, ClassNotFoundException { int count = 0; try ( ZipInputStream stream = new ZipInputStream( inputStream ) ) { ZipEntry entry; while((entry = stream.getNextEntry())!=null) { logger.trace( "Read entry: %s, len: %d", entry.getName(), entry.getSize() ); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len; byte[] buffer = new byte[1024]; while ((len = stream.read( buffer)) > 0) { bos.write(buffer, 0, len); } bos.close(); ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( bos.toByteArray() )); TrackedContent record = (TrackedContent) ois.readObject(); consumer.accept( record ); count++; } } return count; }public static void zipTrackedContent( File out, Set sealed ) throws IOException { logger.info( "Writing sealed zip to: '{}'", out.getAbsolutePath() ); try (ZipOutputStream zip = new ZipOutputStream( new FileOutputStream( out ) )) { for ( TrackedContent f : sealed ) { String name = SEALED.getValue() + "/" + f.getKey().getId(); logger.trace( "Adding {} to zip", name ); zip.putNextEntry( new ZipEntry( name ) ); copy( toInputStream( f ), zip ); } } }public Set getCacheNames() { Set ret = new HashSet<>(); if ( kojiConfig.isEnabled() && kojiConfig.isQueryCacheEnabled() ) { ret.add( KOJI_TAGS ); ret.add( KOJI_BUILD_INFO ); ret.add( KOJI_BUILD_INFO_CONTAINING_ARTIFACT ); ret.add( KOJI_ARCHIVES_FOR_BUILD ); ret.add( KOJI_ARCHIVES_MATCHING_GA ); } return ret; }public void send( String topic, String message, LogbackFormatter formatter, long timeoutMillis ) throws IOException, InterruptedException, ExecutionException, TimeoutException { Future future = doKafkaSend( topic, message, formatter ); if ( future != null ) { future.get( timeoutMillis, TimeUnit.MILLISECONDS ); } }public void send( String topic, String message, long timeoutMillis ) throws IOException, InterruptedException, ExecutionException, TimeoutException { send( topic, message, null, timeoutMillis ); }public void send( String topic, String message, LogbackFormatter formatter ) throws IOException { doKafkaSend( topic, message, formatter ); }public String getNextName( List names ) { if ( names.isEmpty() ) { return null; } String name0 = names.get( 0 ); if ( names.size() == 1 ) { return name0 + "_1"; } Collections.sort( names ); String last = names.get( names.size() - 1 ); String index = last.substring( last.lastIndexOf( "_" ) + 1 ); return name0 + "_" + ( Integer.parseInt( index ) + 1 ); }private String getRemoteRepositoryName( URL url ) throws IndyDataException { final String name = repoCreator.formatId( url.getHost(), getPort( url ), 0, null, StoreType.remote ); logger.debug( "Looking for remote repo starts with name: {}", name ); AbstractProxyRepositoryCreator abstractProxyRepositoryCreator = null; if ( repoCreator instanceof AbstractProxyRepositoryCreator ) { abstractProxyRepositoryCreator = (AbstractProxyRepositoryCreator) repoCreator; } if ( abstractProxyRepositoryCreator == null ) { return name; } Predicate filter = abstractProxyRepositoryCreator.getNameFilter( name ); List l = storeManager.query() .packageType( GENERIC_PKG_KEY ) .storeType( RemoteRepository.class ) .stream( filter ) .map( repository -> repository.getName() ) .collect( Collectors.toList() ); if ( l.isEmpty() ) { return name; } return abstractProxyRepositoryCreator.getNextName( l ); }private void addSnapshotDataObject( String key, Snapshot snapshot, long clock, List dataObjectList ) { dataObjectList.add( toDataObject( key, ".min", snapshot.getMin(), clock ) ); dataObjectList.add( toDataObject( key, ".max", snapshot.getMax(), clock ) ); dataObjectList.add( toDataObject( key, ".mean", snapshot.getMean(), clock ) ); dataObjectList.add( toDataObject( key, ".stddev", snapshot.getStdDev(), clock ) ); dataObjectList.add( toDataObject( key, ".median", snapshot.getMedian(), clock ) ); dataObjectList.add( toDataObject( key, ".75th", snapshot.get75thPercentile(), clock ) ); dataObjectList.add( toDataObject( key, ".95th", snapshot.get95thPercentile(), clock ) ); dataObjectList.add( toDataObject( key, ".98th", snapshot.get98thPercentile(), clock ) ); dataObjectList.add( toDataObject( key, ".99th", snapshot.get99thPercentile(), clock ) ); dataObjectList.add( toDataObject( key, ".99.9th", snapshot.get999thPercentile(), clock ) ); }public int commit() throws GitSubsystemException { int committed = lockAnd(me->{ final int size = changelogEntries.size(); if ( !changelogEntries.isEmpty() ) { try { CommitCommand commit = git.commit(); StringBuilder sb = new StringBuilder().append( COMMIT_CHANGELOG_ENTRIES + "\n\n" ); for ( ChangelogEntry et : changelogEntries ) { sb.append( et.getUsername() + " " + et.getTimestamp() + " " + et.getMessage() ); sb.append( "\n\n" ); } String message = sb.toString(); logger.info( message ); commit.setMessage( message ).setAuthor( SYSTEM_USER, email ).call(); changelogEntries.clear(); } catch ( final JGitInternalException | GitAPIException e ) { throw new GitSubsystemException( "Cannot commit to git: " + e.getMessage(), e ); } } return size; }); return committed; }public Transfer generateRelationshipFile( Transfer transfer, TransferOperation op ) { final Logger logger = LoggerFactory.getLogger( getClass() ); if ( !config.isEnabled() ) { logger.debug( "Relate Add-on is not enabled." ); return null; } logger.debug( "Relate generation for {}", transfer ); if ( transfer == null ) { logger.debug( "No transfer. No .rel generation performed." ); return null; } String txfrPath = transfer.getPath(); if ( !txfrPath.endsWith( ".pom" ) ) { logger.debug( "This is not a pom transfer." ); return null; } ArtifactPathInfo artPathInfo = ArtifactPathInfo.parse( txfrPath ); if ( artPathInfo == null ) { logger.debug( "Not an artifact download ({}). No .rel generation performed.", txfrPath ); return null; } ConcreteResource pomResource = transfer.getResource(); StoreKey storeKey = StoreKey.fromString( transfer.getLocation().getName() ); ArtifactStore store; try { store = storeManager.getArtifactStore( storeKey ); } catch ( final IndyDataException ex ) { logger.error( "Error retrieving artifactStore with key " + storeKey, ex ); return null; } logger.debug( "Generate .rel corresponding to associated POM download: {}/{}", storeKey, pomResource.getPath() ); try { URI source = new URI( pomResource.getLocation().getUri() + REL_SUFFIX ); ProjectVersionRef ref = artPathInfo.getProjectId(); // get all groups that this store is a member of Set stores = new HashSet<>(); stores.add( store ); stores.addAll( storeManager.query().getGroupsContaining( store.getKey() ) ); List supplementalLocations = LocationUtils.toLocations( stores.toArray( new ArtifactStore[0] ) ); MavenPomView pomView = mavenPomReader.read( ref, transfer, supplementalLocations, ALL_PROFILES ); EProjectDirectRelationships rel = mavenModelProcessor.readRelationships( pomView, source, new ModelProcessorConfig() ); Transfer transferRel = transfer.getSiblingMeta( REL_SUFFIX ); writeRelationships( rel, transferRel, op ); return transferRel; } catch ( Exception e ) { logger.error( "Error generating .rel file for " + txfrPath + " from store " + store, e ); return null; } }public static String getName( String nodePrefix, String name, String defaultName, String... suffix ) { if ( isBlank( name ) || name.equals( DEFAULT ) ) { name = defaultName; } return name( name( nodePrefix, name ), suffix ); }public static X509Certificate generateX509Certificate( KeyPair pair, String dn, int days, String algorithm ) throws GeneralSecurityException, IOException { PrivateKey privateKey = pair.getPrivate(); X509CertInfo info = new X509CertInfo(); Date from = new Date(); Date to = new Date( from.getTime() + TimeUnit.DAYS.toMillis( days ) ); CertificateValidity interval = new CertificateValidity( from, to ); BigInteger sn = new BigInteger( 64, new SecureRandom() ); X500Name owner = new X500Name( dn ); info.set( X509CertInfo.VALIDITY, interval ); info.set( X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber( sn ) ); info.set( X509CertInfo.SUBJECT, owner ); info.set( X509CertInfo.ISSUER, owner ); info.set( X509CertInfo.KEY, new CertificateX509Key( pair.getPublic() ) ); info.set( X509CertInfo.VERSION, new CertificateVersion( CertificateVersion.V3 ) ); AlgorithmId algo = new AlgorithmId( AlgorithmId.sha256WithRSAEncryption_oid ); info.set( X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId( algo ) ); // Sign the cert to identify the algorithm that's used. X509CertImpl cert = new X509CertImpl( info ); cert.sign( privateKey, algorithm ); // Update the algorithm, and resign. algo = (AlgorithmId) cert.get( X509CertImpl.SIG_ALG ); info.set( CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo ); cert = new X509CertImpl( info ); cert.sign( privateKey, algorithm ); return cert; }public void updateImpliedStores( @Observes final ArtifactStorePreUpdateEvent event ) { if ( !storeManager.isStarted() ) { return; } if ( !config.isEnabled() ) { logger.debug( "Implied-repository processing is not enabled." ); return; } try { // TODO: Update for changes map. final Map currentStores = mapStores( event ); for ( final ArtifactStore store : event ) { logger.debug( "Processing store: {} for implied repo metadata", store ); processStore( store, currentStores ); } } catch ( Throwable error ) { Logger logger = LoggerFactory.getLogger( getClass() ); logger.error( String.format( "Implied-repository maintenance failed: %s", error.getMessage() ), error ); } }protected String extractClientCertificate(HttpServletRequest request) { String[] certs = extractClientCertificateChain(request); if (certs != null && certs.length > 0) { return certs[0]; } else { return null; } }private Response process(MultivaluedMap parameters, String clientId, String clientSecret) { // Call Authlete's /api/auth/revocation API. RevocationResponse response = getApiCaller().callRevocation(parameters, clientId, clientSecret); // 'action' in the response denotes the next action which // this service implementation should take. Action action = response.getAction(); // The content of the response to the client application. String content = response.getResponseContent(); // Dispatch according to the action. switch (action) { case INVALID_CLIENT: // 401 Unauthorized return ResponseUtil.unauthorized(content, CHALLENGE); case INTERNAL_SERVER_ERROR: // 500 Internal Server Error return ResponseUtil.internalServerError(content); case BAD_REQUEST: // 400 Bad Request return ResponseUtil.badRequest(content); case OK: // 200 OK return ResponseUtil.javaScript(content); default: // This never happens. throw getApiCaller().unknownAction("/api/auth/revocation", action); } }private void noInteractionCheckAuthentication(AuthorizationResponse response) { // If the current user has already been authenticated. if (mSpi.isUserAuthenticated()) { // OK. return; } // A user must have logged in. throw getApiCaller().authorizationFail(response.getTicket(), Reason.NOT_LOGGED_IN); }private Response process(MultivaluedMap parameters) { // Call Authlete's /api/auth/authorization API. AuthorizationResponse response = getApiCaller().callAuthorization(parameters); // 'action' in the response denotes the next action which // this service implementation should take. AuthorizationResponse.Action action = response.getAction(); // The content of the response to the client application. // The format of the content varies depending on the action. String content = response.getResponseContent(); // Dispatch according to the action. switch (action) { case INTERNAL_SERVER_ERROR: // 500 Internal Server Error return ResponseUtil.internalServerError(content); case BAD_REQUEST: // 400 Bad Request return ResponseUtil.badRequest(content); case LOCATION: // 302 Found return ResponseUtil.location(content); case FORM: // 200 OK return ResponseUtil.form(content); case INTERACTION: // Process the authorization request with user interaction. return handleInteraction(response); case NO_INTERACTION: // Process the authorization request without user interaction. // The flow reaches here only when the authorization request // contained prompt=none. return handleNoInteraction(response); default: // This never happens. throw getApiCaller().unknownAction("/api/auth/authorization", action); } }public Response handle( AuthleteApi api, UserInfoRequestHandlerSpi spi, String accessToken) { try { // Create a handler. UserInfoRequestHandler handler = new UserInfoRequestHandler(api, spi); // Delegate the task to the handler. return handler.handle(accessToken); } catch (WebApplicationException e) { // An error occurred in the handler. onError(e); // Convert the error to a Response. return e.getResponse(); } }private Response process(String accessToken) { // Call Authlete's /api/auth/userinfo API. UserInfoResponse response = getApiCaller().callUserInfo(accessToken); // 'action' in the response denotes the next action which // this service implementation should take. Action action = response.getAction(); // The content of the response to the client application. String content = response.getResponseContent(); // Dispatch according to the action. switch (action) { case INTERNAL_SERVER_ERROR: // 500 Internal Server Error return ResponseUtil.bearerError(Status.INTERNAL_SERVER_ERROR, content); case BAD_REQUEST: // 400 Bad Request return ResponseUtil.bearerError(Status.BAD_REQUEST, content); case UNAUTHORIZED: // 401 Unauthorized return ResponseUtil.bearerError(Status.UNAUTHORIZED, content); case FORBIDDEN: // 403 Forbidden return ResponseUtil.bearerError(Status.FORBIDDEN, content); case OK: // Return the user information. return getUserInfo(response); default: // This never happens. throw getApiCaller().unknownAction("/api/auth/userinfo", action); } }private Response process(MultivaluedMap parameters) { // Call Authlete's /api/auth/introspection/standard API. StandardIntrospectionResponse response = getApiCaller().callStandardIntrospection(parameters); // 'action' in the response denotes the next action which // this service implementation should take. Action action = response.getAction(); // The content of the response to the client application. String content = response.getResponseContent(); // Dispatch according to the action. switch (action) { case INTERNAL_SERVER_ERROR: // 500 Internal Server Error return ResponseUtil.internalServerError(content); case BAD_REQUEST: // 400 Bad Request return ResponseUtil.badRequest(content); case OK: // 200 OK return ResponseUtil.ok(content); default: // This never happens. throw getApiCaller().unknownAction("/api/auth/introspection/standard", action); } }public Response handle( AuthleteApi api, AuthorizationRequestHandlerSpi spi, MultivaluedMap parameters) { try { // Create a handler. AuthorizationRequestHandler handler = new AuthorizationRequestHandler(api, spi); // Delegate the task to the handler. return handler.handle(parameters); } catch (WebApplicationException e) { // An error occurred in the handler. onError(e); // Convert the error to a Response. return e.getResponse(); } }private TResponse executeApiCall(AuthleteApiCall apiCall) throws AuthleteApiException { try { // Call the Authlete API. return apiCall.call(); } catch (WebApplicationException e) { // Throw an exception with HTTP response information. throw createApiException(e, e.getResponse()); } catch (ResponseProcessingException e) { // Throw an exception with HTTP response information. throw createApiException(e, e.getResponse()); } catch (Throwable t) { // Throw an exception without HTTP response information. throw createApiException(t, null); } }private void setReadTimeout(javax.ws.rs.client.Client client) { // The timeout value. int timeout = mSettings.getReadTimeout(); synchronized (mReadTimeoutLock) { if (mCurrentReadTimeout == timeout) { // The given value is the same as the current one. // Let's skip calling property() method. return; } // The given value is different from the current value. // Let's update the configuration. mCurrentReadTimeout = timeout; } //---------------------------------------------------------------------- // Note that there was no standardized way to set the read timeout // before JAX-RS API 2.1 (Java EE 8) (cf. ClientBuilder.readTimeout). //---------------------------------------------------------------------- // Convert int to Integer before calling property() method multiple times // in order to reduce the number of object creation by autoboxing. Integer value = Integer.valueOf(timeout); // For Jersey client.property("jersey.config.client.readTimeout", value); // For Apache CXF client.property("http.receive.timeout", value); // For WebSphere (8.5.5.7+) client.property("com.ibm.ws.jaxrs.client.receive.timeout", value); }private void setConnectionTimeout(javax.ws.rs.client.Client client) { // The timeout value. int timeout = mSettings.getConnectionTimeout(); synchronized (mConnectionTimeoutLock) { if (mCurrentConnectionTimeout == timeout) { // The given value is the same as the current one. // Let's skip calling property() method. return; } // The given value is different from the current value. // Let's update the configuration. mCurrentConnectionTimeout = timeout; } //---------------------------------------------------------------------- // Note that there was no standardized way to set the connection timeout // before JAX-RS API 2.1 (Java EE 8) (cf. ClientBuilder.connectTimeout). //---------------------------------------------------------------------- // Convert int to Integer before calling property() method multiple times // in order to reduce the number of object creation by autoboxing. Integer value = Integer.valueOf(timeout); // For Jersey client.property("jersey.config.client.connectTimeout", value); // For Apache CXF client.property("http.connection.timeout", value); // For WebSphere (8.5.5.7+) client.property("com.ibm.ws.jaxrs.client.connection.timeout", value); }private javax.ws.rs.client.Client createJaxRsClient() { if (getJaxRsClientBuilder() != null) { // if we have a builder configured, use it return getJaxRsClientBuilder().build(); } else { // otherwise just use the system discovered default return ClientBuilder.newClient(); } }private javax.ws.rs.client.Client getJaxRsClient() { // If a JAX-RS client has not been created yet. if (mJaxRsClient == null) { // Create a JAX-RS client. javax.ws.rs.client.Client client = createJaxRsClient(); synchronized (this) { if (mJaxRsClient == null) { mJaxRsClient = client; } } } // Set a connection timeout. setConnectionTimeout(mJaxRsClient); // Set a read timeout. setReadTimeout(mJaxRsClient); return mJaxRsClient; }private String createServiceCredentials(AuthleteConfiguration configuration) { if (configuration.getServiceAccessToken() != null) { return "Bearer " + configuration.getServiceAccessToken(); } else { String key = configuration.getServiceApiKey(); String secret = configuration.getServiceApiSecret(); return new BasicCredentials(key, secret).format(); } }private String createServiceOwnerCredentials(AuthleteConfiguration configuration) { if (configuration.getServiceOwnerAccessToken() != null) { return "Bearer " + configuration.getServiceOwnerAccessToken(); } else { String key = configuration.getServiceOwnerApiKey(); String secret = configuration.getServiceOwnerApiSecret(); return new BasicCredentials(key, secret).format(); } }public Response handle(AuthleteApi api, MultivaluedMap parameters) { try { // Create a handler. IntrospectionRequestHandler handler = new IntrospectionRequestHandler(api); // Delegate the task to the handler. return handler.handle(parameters); } catch (WebApplicationException e) { // An error occurred in the handler. onError(e); // Convert the error to a Response. return e.getResponse(); } }public Response handle(AuthleteApi api) { try { // Create a handler. JwksRequestHandler handler = new JwksRequestHandler(api); // Delegate the task to the handler. return handler.handle(); } catch (WebApplicationException e) { // An error occurred in the handler. onError(e); // Convert the error to a Response. return e.getResponse(); } }private static String computeLoginId(AuthorizationResponse info) { if (info.getSubject() != null) { return info.getSubject(); } return info.getLoginHint(); }public Response userInfoIssue(String accessToken, Map claims) { // Call Authlete's /api/auth/userinfo/issue API. UserInfoIssueResponse response = callUserInfoIssue(accessToken, claims); // 'action' in the response denotes the next action which // this service implementation should take. UserInfoIssueResponse.Action action = response.getAction(); // The content of the response to the client application. // The format of the content varies depending on the action. String content = response.getResponseContent(); // Dispatch according to the action. switch (action) { case INTERNAL_SERVER_ERROR: // 500 Internal Server Error return ResponseUtil.bearerError(Status.INTERNAL_SERVER_ERROR, content); case BAD_REQUEST: // 400 Bad Request return ResponseUtil.bearerError(Status.BAD_REQUEST, content); case UNAUTHORIZED: // 401 Unauthorized return ResponseUtil.bearerError(Status.UNAUTHORIZED, content); case FORBIDDEN: // 403 Forbidden return ResponseUtil.bearerError(Status.FORBIDDEN, content); case JSON: // 200 OK, application/json;charset=UTF-8 return ResponseUtil.ok(content); case JWT: // 200 OK, application/jwt return ResponseUtil.ok(content, ResponseUtil.MEDIA_TYPE_JWT); default: // This never happens. throw unknownAction("/api/auth/userinfo/issue", action); } }public Response handle( AuthleteApi api, AuthorizationDecisionHandlerSpi spi, String ticket, String[] claimNames, String[] claimLocales) { try { // Create a handler. AuthorizationDecisionHandler handler = new AuthorizationDecisionHandler(api, spi); // Delegate the task to the handler. return handler.handle(ticket, claimNames, claimLocales); } catch (WebApplicationException e) { // An error occurred in the handler. onError(e); // Convert the error to a Response. return e.getResponse(); } }private Map collectClaims(String subject, String[] claimNames, String[] claimLocales) { // If no claim is required. if (claimNames == null || claimNames.length == 0) { return null; } // Drop empty and duplicate entries from claimLocales. claimLocales = normalizeClaimLocales(claimLocales); // Claim values. Map claims = new HashMap(); // For each requested claim. for (String claimName : claimNames) { // If the claim name is empty. if (claimName == null || claimName.length() == 0) { continue; } // Split the claim name into the name part and the tag part. String[] elements = claimName.split("#", 2); String name = elements[0]; String tag = (elements.length == 2) ? elements[1] : null; // If the name part is empty. if (name == null || name.length() == 0) { continue; } // Get the claim value of the claim. Object value = getClaim(name, tag, claimLocales); // If the claim value was not obtained. if (value == null) { continue; } if (tag == null) { // Just for an edge case where claimName ends with "#". claimName = name; } // Add the pair of the claim name and the claim value. claims.put(claimName, value); } // If no claim value has been obtained. if (claims.size() == 0) { return null; } // Obtained claim values. return claims; }private Response process(String ticket, String[] claimNames, String[] claimLocales) { // If the end-user did not grant authorization to the client application. if (mSpi.isClientAuthorized() == false) { // The end-user denied the authorization request. return fail(ticket, Reason.DENIED); } // The subject (= unique identifier) of the end-user. String subject = mSpi.getUserSubject(); // If the subject of the end-user is not available. if (subject == null || subject.length() == 0) { // The end-user is not authenticated. return fail(ticket, Reason.NOT_AUTHENTICATED); } // The time when the end-user was authenticated. long authTime = mSpi.getUserAuthenticatedAt(); // The ACR (Authentication Context Class Reference) of the // end-user authentication. String acr = mSpi.getAcr(); // Collect claim values. Map claims = collectClaims(subject, claimNames, claimLocales); // Extra properties to associate with an access token and/or // an authorization code. Property[] properties = mSpi.getProperties(); // Scopes to associate with an access token and/or an authorization code. // If a non-null value is returned from mSpi.getScopes(), the scope set // replaces the scopes that have been specified in the original // authorization request. String[] scopes = mSpi.getScopes(); // Authorize the authorization request. return authorize(ticket, subject, authTime, acr, claims, properties, scopes); }public Response handle(String ticket, String[] claimNames, String[] claimLocales) throws WebApplicationException { try { // Process the end-user's decision. return process(ticket, claimNames, claimLocales); } catch (WebApplicationException e) { throw e; } catch (Throwable t) { // Unexpected error. throw unexpected("Unexpected error in AuthorizationDecisionHandler", t); } }private Response handlePassword(TokenResponse response) { // The credentials of the resource owner. String username = response.getUsername(); String password = response.getPassword(); // Validate the credentials. String subject = mSpi.authenticateUser(username, password); // Extra properties to associate with an access token. Property[] properties = mSpi.getProperties(); // The ticket for Authlete's /api/auth/token/* API. String ticket = response.getTicket(); if (subject != null) { // Issue an access token and optionally an ID token. return getApiCaller().tokenIssue(ticket, subject, properties); } else { // The credentials are invalid. An access token is not issued. throw getApiCaller().tokenFail(ticket, Reason.INVALID_RESOURCE_OWNER_CREDENTIALS); } }private Response process( MultivaluedMap parameters, String clientId, String clientSecret, String[] clientCertificatePath) { // Extra properties to associate with an access token. Property[] properties = mSpi.getProperties(); String clientCertificate = null; if (clientCertificatePath != null && clientCertificatePath.length > 0) { // The first one is the client's certificate. clientCertificate = clientCertificatePath[0]; // if we have more in the path, pass them along separately without the first one if (clientCertificatePath.length > 1) { clientCertificatePath = Arrays.copyOfRange( clientCertificatePath, 1, clientCertificatePath.length); } } // Call Authlete's /api/auth/token API. TokenResponse response = getApiCaller().callToken( parameters, clientId, clientSecret, properties, clientCertificate, clientCertificatePath); // 'action' in the response denotes the next action which // this service implementation should take. Action action = response.getAction(); // The content of the response to the client application. String content = response.getResponseContent(); // Dispatch according to the action. switch (action) { case INVALID_CLIENT: // 401 Unauthorized return ResponseUtil.unauthorized(content, CHALLENGE); case INTERNAL_SERVER_ERROR: // 500 Internal Server Error return ResponseUtil.internalServerError(content); case BAD_REQUEST: // 400 Bad Request return ResponseUtil.badRequest(content); case PASSWORD: // Process the token request whose flow is "Resource Owner Password Credentials". return handlePassword(response); case OK: // 200 OK return ResponseUtil.ok(content); default: // This never happens. throw getApiCaller().unknownAction("/api/auth/token", action); } }public Object send(AsyncCallback callback) { return jsonpBuilder.requestObject(resource.getUri(), callback); }@SuppressWarnings("rawtypes") private String[] getAnnotationsAsStringArray(Class[] classes) { if (null == classes) { return null; } List ret = new ArrayList(); for (Class c : classes) { ret.add(c.getName()); } return ret.toArray(new String[ret.size()]); }@Override public RequestCallback filter(Method method, Response response, RequestCallback callback) { int code = response.getStatusCode(); final CacheKey ck = cacheKey(method.builder); final List removedCallbacks = cache.removeCallbacks(ck); if (removedCallbacks != null) { callback = new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { if (GWT.isClient() && LogConfiguration.loggingIsEnabled()) { Logger.getLogger(CachingCallbackFilter.class.getName()) .finer("call " + removedCallbacks.size() + " more queued callbacks for " + ck); } // call all callbacks found in cache for (RequestCallback cb : removedCallbacks) { cb.onResponseReceived(request, response); } } @Override public void onError(Request request, Throwable exception) { if (LogConfiguration.loggingIsEnabled()) { Logger.getLogger(CachingCallbackFilter.class.getName()).severe( "cannot call " + (removedCallbacks.size() + 1) + " callbacks for " + ck + " due to error: " + exception.getMessage()); } if (LogConfiguration.loggingIsEnabled()) { Logger.getLogger(CachingCallbackFilter.class.getName()) .finer("call " + removedCallbacks.size() + " more queued callbacks for " + ck); } // and all the others, found in cache for (RequestCallback cb : removedCallbacks) { cb.onError(request, exception); } } }; } else { if (GWT.isClient() && LogConfiguration.loggingIsEnabled()) { Logger.getLogger(CachingCallbackFilter.class.getName()) .finer("removed one or no " + "callback for cachekey " + ck); } } if (isCachingStatusCode(code)) { cacheResult(method, response); return callback; } if (GWT.isClient() && LogConfiguration.loggingIsEnabled()) { Logger.getLogger(CachingCallbackFilter.class.getName()) .info("cannot cache due to invalid response code: " + code); } return callback; }protected static boolean getBooleanProperty(TreeLogger logger, PropertyOracle propertyOracle, String propertyName, boolean defaultValue) { try { SelectionProperty prop = propertyOracle.getSelectionProperty(logger, propertyName); String propVal = prop.getCurrentValue(); return Boolean.parseBoolean(propVal); } catch (BadPropertyValueException e) { // return the default value } return defaultValue; }private String reduceName(String newClassName, String suffix) { if (newClassName.length() < MAX_FILE_NAME_LENGTH) { return newClassName; } // String sufx = "_Gen_GwtJackEncDec_"; //Lets first try to reduce the package name of the parametrized types // according to parametersName2ClassName parametrized types //Lets find if there are parametrized types String noSufix = newClassName.substring(0, newClassName.length() - suffix.length()); if (newClassName.indexOf("__") > 0) { //has generic String primaryName = noSufix.substring(0, noSufix.indexOf("__")); String genericPart = noSufix.substring(noSufix.indexOf("__") + 2); StringBuilder stringBuilder = new StringBuilder(); String[] eachGeneric = genericPart.split("__"); for (String genericType : eachGeneric) { stringBuilder.append("__"); stringBuilder.append(reduceType(genericType)); } String finalName = primaryName + stringBuilder.toString() + suffix; if (finalName.length() > MAX_FILE_NAME_LENGTH) { //File name is still too long wrapping it out aggressively String baseName = primaryName + stringBuilder.toString(); int firstPosition = baseName.indexOf("__"); int lastPosition = baseName.lastIndexOf("__"); String middle = baseName.substring(firstPosition, lastPosition); finalName = baseName.substring(0, firstPosition) + middle.subSequence(0, 4) + "_" + (middle.length() - 5) + "_" + middle.substring(middle.length() - 9) + baseName.substring(lastPosition) + suffix; return finalName; } return finalName; } //If there is no generic type lets give an error and force the client to reduce className return newClassName; }public Method expect(int... statuses) { if (statuses.length == 1 && statuses[0] < 0) { anyStatus = true; } else { anyStatus = false; expectedStatuses.clear(); for (int status : statuses) { expectedStatuses.add(status); } } return this; }public static List getAnnotationResolvers(GeneratorContext context, TreeLogger logger) { // do this only the first time call if (null == _annotationResolversRequested) { // call additional AnnotationResolvers if there are some configured try { for (String className : context.getPropertyOracle() .getConfigurationProperty("org.fusesource.restygwt.annotationresolver").getValues()) { logger.log(TreeLogger.INFO, "classname to resolve: " + className); Class clazz; try { clazz = Class.forName(className); } catch (ClassNotFoundException e) { throw new RuntimeException("could not resolve class " + className + " " + e.getMessage()); } if (null != clazz) { try { logger.log(TreeLogger.INFO, "add annotationresolver: " + clazz.getName()); addAnnotationResolver((AnnotationResolver) clazz.newInstance()); } catch (InstantiationException e) { throw new RuntimeException("could not instanciate class " + className + " " + e.getMessage()); } catch (IllegalAccessException e) { throw new RuntimeException("could not access class " + className + " " + e.getMessage()); } } else { throw new RuntimeException("could not create instance for classname " + className); } } } catch (BadPropertyValueException ignored) { /* * ignored since there is no * * */ logger.log(TreeLogger.DEBUG, "no additional annotationresolvers found"); } } // return a copy List ret = new ArrayList(); ret.addAll(annotationResolvers); return _annotationResolversRequested = ret; }private boolean exists(JClassType type, JField field, String fieldName, boolean isSetter) { if (field instanceof DummyJField) { return true; } JType[] args; if (isSetter) { args = new JType[] { field.getType() }; } else { args = new JType[] {}; } JMethod m = type.findMethod(fieldName, args); if (null != m) { if (isIgnored(m)) { return false; } if (isSetter) { return true; } JClassType returnType = m.getReturnType().isClassOrInterface(); JClassType fieldType = field.getType().isClassOrInterface(); if (returnType == null || fieldType == null) { // at least one is a primitive type return m.getReturnType().equals(field.getType()); } // both are non-primitives return returnType.isAssignableFrom(fieldType); } try { JType objectType = find(Object.class, getLogger(), context); JClassType superType = type.getSuperclass(); if (!objectType.equals(superType)) { return exists(superType, field, fieldName, isSetter); } } catch (UnableToCompleteException e) { // do nothing } return false; }static String getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(String fieldName) { if (fieldName.length() > 1 && Character.isUpperCase(fieldName.charAt(1))) { return fieldName; } return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); }@Factory public static Matcher notEmptyString() { return new CustomTypeSafeMatcher("not empty") { @Override protected boolean matchesSafely(String s) { return !s.isEmpty(); } }; }@Factory public static Matcher named(String name, Matcher matcher) { return describedAs("%0 = %1", matcher, name, matcher); }public void assertIsSorted(Description description, char[] actual) { if(actual == null) { throw failures.failure("The actual is null"); } if (actual.length == 0) { return; } for (int i = 0; i < actual.length - 1; i++) { if (actual[i] > actual[i + 1]) { throw failures.failure(description, shouldBeSorted(i, actual)); } } }public void assertDoesNotContain(Description description, char[] actual, char[] values) { arrays.assertDoesNotContain(description, actual, values); }public void assertNotSame(Description description, Object actual, Object other) { if (actual == other) { String format = "expected not same:<%s>"; throw failures.failure(description, new BasicErrorMessageFactory(format, actual)); } }public void assertSame(Description description, Object actual, Object expected) { if (actual != expected) { String format = "expected:<%s> and actual:<%s> should refer to the same instance"; throw failures.failure(description, new BasicErrorMessageFactory(format, expected, actual)); } }public void assertNotEqual(Description description, Object actual, Object other) { if (areEqual(actual, other)) { throw failures.failure(description, shouldNotBeEqual(actual, other)); } }public void assertEqual(Description description, Object actual, Object expected) { if (!areEqual(actual, expected)) { throw shouldBeEqual(actual, expected).newAssertionError(description); } }public void assertContainsSequence(Description description, byte[] actual, byte[] sequence) { arrays.assertContainsSequence(description, actual, sequence); }public void assertContainsOnly(Description description, byte[] actual, byte[] values) { arrays.assertContainsOnly(description, actual, values); }public void assertNotLessThan(Description description, Double actual, double expected) { assertNotNull(description, actual); if (isLessThan(actual, expected)) { throw failures.failure(description, shouldNotBeLessThan(actual, expected)); } }public void assertLessThan(Description description, Double actual, double expected) { assertNotNull(description, actual); if (!isLessThan(actual, expected)) { throw failures.failure(description, shouldBeLessThan(actual, expected)); } }public void assertNotGreaterThan(Description description, Double actual, double expected) { assertNotNull(description, actual); if (isGreaterThan(actual, expected)) { throw failures.failure(description, shouldNotBeGreaterThan(actual, expected)); } }public void assertNotEqual(Description description, Double actual, Double expected, Offset offset) { checkOffsetIsNotNull(offset); checkNumberIsNotNull(expected); assertNotNull(description, actual); if (isEqualTo(actual, expected, offset)) { throw failures.failure(description, shouldNotBeEqual(actual, expected)); } }public ByteArrayAssert contains(byte value, Index index) { arrays.assertContains(description, actual, value, index); return this; }public FloatAssert isEqualTo(float expected, Offset offset) { floats.assertEqual(description, actual, expected, offset); return this; }public void assertIsNegative(Description description, BigDecimal actual) { comparables.assertLessThan(description, actual, ZERO); }public void assertIsPositive(Description description, BigDecimal actual) { comparables.assertGreaterThan(description, actual, ZERO); }public void assertIsNotZero(Description description, BigDecimal actual) { comparables.assertNotEqual(description, actual, ZERO); }public void assertIsZero(Description description, BigDecimal actual) { comparables.assertEqual(description, actual, ZERO); }public void assertEqual(Description description, BigDecimal actual, BigDecimal expected) { checkNumberIsNotNull(expected); assertNotNull(description, actual); comparables.assertEqual(description, actual, expected); }public void assertDoesNotContainDuplicateValues(Description description, Map actual) { assertNotNull(description, actual); Collection duplicates = duplicatesFrom(actual.values()); if (!duplicates.isEmpty()) { throw failures.failure(description, shouldNotHaveDuplicates(actual, duplicates)); } }public void assertDoesNotContainValue(Description description, Map actual, V value) { assertNotNull(description, actual); if (actual.containsValue(value)) { throw failures.failure(description, shouldNotContainValue(actual, value)); } }public void assertContainsValue(Description description, Map actual, V value) { assertNotNull(description, actual); if (!actual.containsValue(value)) { throw failures.failure(description, shouldContainValue(actual, value)); } }public void assertDoesNotContainKey(Description description, Map actual, K key) { assertNotNull(description, actual); if (actual.containsKey(key)) { throw failures.failure(description, shouldNotContainKey(actual, key)); } }public void assertContainsKey(Description description, Map actual, K key) { assertNotNull(description, actual); if (!actual.containsKey(key)) { throw failures.failure(description, shouldContainKey(actual, key)); } }public void assertContains(Description description, int[] actual, int[] values) { arrays.assertContains(description, actual, values); }public void assertHasSize(Description description, int[] actual, int expectedSize) { arrays.assertHasSize(description, actual, expectedSize); }public void assertUpperCase(Description description, Character actual) { assertNotNull(description, actual); if (!isUpperCase(actual)) { throw failures.failure(description, shouldBeUpperCase(actual)); } }public void assertLowerCase(Description description, Character actual) { assertNotNull(description, actual); if (!isLowerCase(actual)) { throw failures.failure(description, shouldBeLowerCase(actual)); } }public void assertNotLessThan(Description description, Character actual, char other) { assertNotNull(description, actual); if (isLessThan(actual, other)) { throw failures.failure(description, ShouldNotBeLessThan.shouldNotBeLessThan(actual, other)); } }public void assertGreaterThan(Description description, Character actual, char other) { assertNotNull(description, actual); if (!isGreaterThan(actual, other)) { throw failures.failure(description, shouldBeGreaterThan(actual, other)); } }public void assertNotGreaterThan(Description description, Character actual, char other) { assertNotNull(description, actual); if (isGreaterThan(actual, other)) { throw failures.failure(description, shouldNotBeGreaterThan(actual, other)); } }public void assertLessThan(Description description, Character actual, char other) { assertNotNull(description, actual); if (!isLessThan(actual, other)) { throw failures.failure(description, shouldBeLessThan(actual, other)); } }public void assertNotEqual(Description description, Character actual, char other) { assertNotNull(description, actual); if (actual.charValue() == other) { throw failures.failure(description, shouldNotBeEqual(actual, other)); } }public void assertEqual(Description description, Character actual, char expected) { assertNotNull(description, actual); if (actual.charValue() != expected) { throw failures.failure(description, shouldBeEqual(actual, expected)); } }public void assertGreaterThan(Description description, Float actual, float expected) { assertNotNull(description, actual); if (!isGreaterThan(actual, expected)) { throw failures.failure(description, shouldBeGreaterThan(actual, expected)); } }public void assertGreaterThan(Description description, Short actual, short expected) { assertNotNull(description, actual); if (!isGreaterThan(actual, expected)) { throw failures.failure(description, ShouldBeGreaterThan.shouldBeGreaterThan(actual, expected)); } }public void assertNotEqualTo(Description description, Short actual, short expected) { assertNotNull(description, actual); if (isEqualTo(actual, expected)) { throw failures.failure(description, shouldNotBeEqual(actual, expected)); } }public void assertEqualTo(Description description, Short actual, short expected) { assertNotNull(description, actual); if (!isEqualTo(actual, expected)) { throw failures.failure(description, shouldBeEqual(actual, expected)); } }public void setDefaultScriptNames(String scriptNames) { if (!scriptNames.trim().isEmpty()) service.setDefaultScripts(asList(scriptNames.split(","))); }public byte[] decode(byte[] buf) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Node node = root; int current = 0; int bits = 0; for (int i = 0; i < buf.length; i++) { int b = buf[i] & 0xFF; current = (current << 8) | b; bits += 8; while (bits >= 8) { int c = (current >>> (bits - 8)) & 0xFF; node = node.children[c]; bits -= node.bits; if (node.isTerminal()) { if (node.symbol == HpackUtil.HUFFMAN_EOS) { throw EOS_DECODED; } baos.write(node.symbol); node = root; } } } while (bits > 0) { int c = (current << (8 - bits)) & 0xFF; node = node.children[c]; if (node.isTerminal() && node.bits <= bits) { bits -= node.bits; baos.write(node.symbol); node = root; } else { break; } } // Section 5.2. String Literal Representation // Padding not corresponding to the most significant bits of the code // for the EOS symbol (0xFF) MUST be treated as a decoding error. int mask = (1 << bits) - 1; if ((current & mask) != mask) { throw INVALID_PADDING; } return baos.toByteArray(); }private static int hash(byte[] name) { int h = 0; for (int i = 0; i < name.length; i++) { h = 31 * h + name[i]; } if (h > 0) { return h; } else if (h == Integer.MIN_VALUE) { return Integer.MAX_VALUE; } else { return -h; } }private void add(byte[] name, byte[] value) { int headerSize = HeaderField.sizeOf(name, value); // Clear the table if the header field size is larger than the capacity. if (headerSize > capacity) { clear(); return; } // Evict oldest entries until we have enough capacity. while (size + headerSize > capacity) { remove(); } // Copy name and value that modifications of original do not affect the dynamic table. name = Arrays.copyOf(name, name.length); value = Arrays.copyOf(value, value.length); int h = hash(name); int i = index(h); HeaderEntry old = headerFields[i]; HeaderEntry e = new HeaderEntry(h, name, value, head.before.index - 1, old); headerFields[i] = e; e.addBefore(head); size += headerSize; }private int getIndex(byte[] name) { if (length() == 0 || name == null) { return -1; } int h = hash(name); int i = index(h); int index = -1; for (HeaderEntry e = headerFields[i]; e != null; e = e.next) { if (e.hash == h && HpackUtil.equals(name, e.name)) { index = e.index; break; } } return getIndex(index); }private HeaderEntry getEntry(byte[] name, byte[] value) { if (length() == 0 || name == null || value == null) { return null; } int h = hash(name); int i = index(h); for (HeaderEntry e = headerFields[i]; e != null; e = e.next) { if (e.hash == h && HpackUtil.equals(name, e.name) && HpackUtil.equals(value, e.value)) { return e; } } return null; }HeaderField getHeaderField(int index) { HeaderEntry entry = head; while(index-- >= 0) { entry = entry.before; } return entry; }private void ensureCapacity(int headerSize) throws IOException { while (size + headerSize > capacity) { int index = length(); if (index == 0) { break; } remove(); } }private void encodeLiteral(OutputStream out, byte[] name, byte[] value, IndexType indexType, int nameIndex) throws IOException { int mask; int prefixBits; switch(indexType) { case INCREMENTAL: mask = 0x40; prefixBits = 6; break; case NONE: mask = 0x00; prefixBits = 4; break; case NEVER: mask = 0x10; prefixBits = 4; break; default: throw new IllegalStateException("should not reach here"); } encodeInteger(out, mask, prefixBits, nameIndex == -1 ? 0 : nameIndex); if (nameIndex == -1) { encodeStringLiteral(out, name); } encodeStringLiteral(out, value); }private void encodeStringLiteral(OutputStream out, byte[] string) throws IOException { int huffmanLength = Huffman.ENCODER.getEncodedLength(string); if ((huffmanLength < string.length && !forceHuffmanOff) || forceHuffmanOn) { encodeInteger(out, 0x80, 7, huffmanLength); Huffman.ENCODER.encode(out, string); } else { encodeInteger(out, 0x00, 7, string.length); out.write(string, 0, string.length); } }private static void encodeInteger(OutputStream out, int mask, int n, int i) throws IOException { if (n < 0 || n > 8) { throw new IllegalArgumentException("N: " + n); } int nbits = 0xFF >>> (8 - n); if (i < nbits) { out.write(mask | i); } else { out.write(mask | nbits); int length = i - nbits; while (true) { if ((length & ~0x7F) == 0) { out.write(length); return; } else { out.write((length & 0x7F) | 0x80); length >>>= 7; } } } }public void setMaxHeaderTableSize(OutputStream out, int maxHeaderTableSize) throws IOException { if (maxHeaderTableSize < 0) { throw new IllegalArgumentException("Illegal Capacity: " + maxHeaderTableSize); } if (capacity == maxHeaderTableSize) { return; } capacity = maxHeaderTableSize; ensureCapacity(0); encodeInteger(out, 0x20, 5, maxHeaderTableSize); }public void encodeHeader(OutputStream out, byte[] name, byte[] value, boolean sensitive) throws IOException { // If the header value is sensitive then it must never be indexed if (sensitive) { int nameIndex = getNameIndex(name); encodeLiteral(out, name, value, IndexType.NEVER, nameIndex); return; } // If the peer will only use the static table if (capacity == 0) { int staticTableIndex = StaticTable.getIndex(name, value); if (staticTableIndex == -1) { int nameIndex = StaticTable.getIndex(name); encodeLiteral(out, name, value, IndexType.NONE, nameIndex); } else { encodeInteger(out, 0x80, 7, staticTableIndex); } return; } int headerSize = HeaderField.sizeOf(name, value); // If the headerSize is greater than the max table size then it must be encoded literally if (headerSize > capacity) { int nameIndex = getNameIndex(name); encodeLiteral(out, name, value, IndexType.NONE, nameIndex); return; } HeaderEntry headerField = getEntry(name, value); if (headerField != null) { int index = getIndex(headerField.index) + StaticTable.length; // Section 6.1. Indexed Header Field Representation encodeInteger(out, 0x80, 7, index); } else { int staticTableIndex = StaticTable.getIndex(name, value); if (staticTableIndex != -1) { // Section 6.1. Indexed Header Field Representation encodeInteger(out, 0x80, 7, staticTableIndex); } else { int nameIndex = getNameIndex(name); if (useIndexing) { ensureCapacity(headerSize); } IndexType indexType = useIndexing ? IndexType.INCREMENTAL : IndexType.NONE; encodeLiteral(out, name, value, indexType, nameIndex); if (useIndexing) { add(name, value); } } } }public void setCapacity(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Illegal Capacity: "+ capacity); } // initially capacity will be -1 so init won't return here if (this.capacity == capacity) { return; } this.capacity = capacity; if (capacity == 0) { clear(); } else { // initially size will be 0 so remove won't be called while (size > capacity) { remove(); } } int maxEntries = capacity / HEADER_ENTRY_OVERHEAD; if (capacity % HEADER_ENTRY_OVERHEAD != 0) { maxEntries++; } // check if capacity change requires us to reallocate the array if (headerFields != null && headerFields.length == maxEntries) { return; } HeaderField[] tmp = new HeaderField[maxEntries]; // initially length will be 0 so there will be no copy int len = length(); int cursor = tail; for (int i = 0; i < len; i++) { HeaderField entry = headerFields[cursor++]; tmp[i] = entry; if (cursor == headerFields.length) { cursor = 0; } } this.tail = 0; this.head = tail + len; this.headerFields = tmp; }public void add(HeaderField header) { int headerSize = header.size(); if (headerSize > capacity) { clear(); return; } while (size + headerSize > capacity) { remove(); } headerFields[head++] = header; size += header.size(); if (head == headerFields.length) { head = 0; } }public int length() { int length; if (head < tail) { length = headerFields.length - tail + head; } else { length = head - tail; } return length; }public int getEncodedLength(byte[] data) { if (data == null) { throw new NullPointerException("data"); } long len = 0; for (byte b : data) { len += lengths[b & 0xFF]; } return (int)((len + 7) >> 3); }private static Map createMap() { int length = STATIC_TABLE.size(); HashMap ret = new HashMap(length); // Iterate through the static table in reverse order to // save the smallest index for a given name in the map. for (int index = length; index > 0; index--) { HeaderField entry = getEntry(index); String name = new String(entry.name, 0, entry.name.length, ISO_8859_1); ret.put(name, index); } return ret; }static int getIndex(byte[] name, byte[] value) { int index = getIndex(name); if (index == -1) { return -1; } // Note this assumes all entries for a given header field are sequential. while (index <= length) { HeaderField entry = getEntry(index); if (!HpackUtil.equals(name, entry.name)) { break; } if (HpackUtil.equals(value, entry.value)) { return index; } index++; } return -1; }static int getIndex(byte[] name) { String nameString = new String(name, 0, name.length, ISO_8859_1); Integer index = STATIC_INDEX_BY_NAME.get(nameString); if (index == null) { return -1; } return index; }private static int decodeULE128(InputStream in) throws IOException { in.mark(5); int result = 0; int shift = 0; while (shift < 32) { if (in.available() == 0) { // Buffer does not contain entire integer, // reset reader index and return -1. in.reset(); return -1; } byte b = (byte) in.read(); if (shift == 28 && (b & 0xF8) != 0) { break; } result |= (b & 0x7F) << shift; if ((b & 0x80) == 0) { return result; } shift += 7; } // Value exceeds Integer.MAX_VALUE in.reset(); throw DECOMPRESSION_EXCEPTION; }public void setMaxHeaderTableSize(int maxHeaderTableSize) { maxDynamicTableSize = maxHeaderTableSize; if (maxDynamicTableSize < encoderMaxDynamicTableSize) { // decoder requires less space than encoder // encoder MUST signal this change maxDynamicTableSizeChangeRequired = true; dynamicTable.setCapacity(maxDynamicTableSize); } }protected void compress( PlexusIoResource resource, OutputStream zOut ) throws IOException { InputStream in = Streams.bufferedInputStream( resource.getContents() ); try { compressFile( in, zOut ); } finally { IOUtil.close( in ); } }private void compressFile( InputStream in, OutputStream zOut ) throws IOException { byte[] buffer = new byte[8 * 1024]; int count = 0; do { zOut.write( buffer, 0, count ); count = in.read( buffer, 0, buffer.length ); } while ( count != -1 ); }public void reset() { setDestFile( null ); // duplicate = "add"; archiveType = "zip"; doCompress = true; doUpdate = false; doFilesonly = false; encoding = null; }@SuppressWarnings({"JavaDoc"}) protected boolean createEmptyZip( File zipFile ) throws ArchiverException { // In this case using java.util.zip will not work // because it does not permit a zero-entry archive. // Must create it manually. getLogger().info( "Note: creating empty " + archiveType + " archive " + zipFile ); OutputStream os = null; try { os = new FileOutputStream( zipFile ); // Cf. PKZIP specification. byte[] empty = new byte[22]; empty[0] = 80; // P empty[1] = 75; // K empty[2] = 5; empty[3] = 6; // remainder zeros os.write( empty ); } catch ( IOException ioe ) { throw new ArchiverException( "Could not create empty ZIP archive " + "(" + ioe.getMessage() + ")", ioe ); } finally { IOUtil.close( os ); } return true; }@SuppressWarnings({"JavaDoc"}) protected void zipFile( InputStream in, ZipArchiveOutputStream zOut, String vPath, long lastModified, File fromArchive, int mode, String symlinkDestination ) throws IOException, ArchiverException { getLogger().debug( "adding entry " + vPath ); entries.put( vPath, vPath ); if ( !skipWriting ) { ZipArchiveEntry ze = new ZipArchiveEntry( vPath ); setTime(ze, lastModified); byte[] header = new byte[4]; int read = in.read(header); boolean compressThis = doCompress; if (!recompressAddedZips && isZipHeader(header)){ compressThis = false; } ze.setMethod( compressThis ? ZipArchiveEntry.DEFLATED : ZipArchiveEntry.STORED ); ze.setUnixMode( UnixStat.FILE_FLAG | mode ); /* * ZipOutputStream.putNextEntry expects the ZipEntry to * know its size and the CRC sum before you start writing * the data when using STORED mode - unless it is seekable. * * This forces us to process the data twice. */ if (ze.isUnixSymlink()){ zOut.putArchiveEntry( ze ); ZipEncoding enc = ZipEncodingHelper.getZipEncoding( getEncoding() ); final byte[] bytes = enc.encode( symlinkDestination).array(); zOut.write( bytes, 0, bytes.length); } else if (zOut.isSeekable() || compressThis) { zOut.putArchiveEntry( ze ); if (read > 0) zOut.write(header, 0, read); IOUtil.copy( in, zOut, 8 * 1024); } else { if (in.markSupported()) { in.mark( Integer.MAX_VALUE ); readWithZipStats(in, header, read, ze, null); in.reset(); zOut.putArchiveEntry( ze); if (read > 0) zOut.write(header, 0, read); IOUtil.copy(in, zOut, 8 * 1024); } else { // Store data into a byte[] // todo: explain how on earth this code works with zip streams > 128KB ??? ByteArrayOutputStream bos = new ByteArrayOutputStream(128 * 1024); readWithZipStats(in, header,read, ze, bos); zOut.putArchiveEntry(ze); if (read > 0) zOut.write(header, 0, read); bos.writeTo( zOut); } } zOut.closeArchiveEntry(); } }@SuppressWarnings({"JavaDoc"}) private void addParentDirs( ArchiveEntry archiveEntry, File baseDir, String entry, ZipArchiveOutputStream zOut, String prefix ) throws IOException { if ( !doFilesonly && getIncludeEmptyDirs() ) { Stack directories = new Stack(); // Don't include the last entry itself if it's // a dir; it will be added on its own. int slashPos = entry.length() - ( entry.endsWith( "/" ) ? 1 : 0 ); while ( ( slashPos = entry.lastIndexOf( '/', slashPos - 1 ) ) != -1 ) { String dir = entry.substring( 0, slashPos + 1 ); if ( addedDirs.contains( prefix + dir ) ) { break; } directories.push( dir ); } while ( !directories.isEmpty() ) { String dir = directories.pop(); File f; if ( baseDir != null ) { f = new File( baseDir, dir ); } else { f = new File( dir ); } // the // At this point we could do something like read the atr final PlexusIoResource res = new AnonymousResource( f); zipDir( res, zOut, prefix + dir, archiveEntry.getDefaultDirMode() ); } } }@SuppressWarnings({"JavaDoc"}) protected final void addResources( ResourceIterator resources, ZipArchiveOutputStream zOut ) throws IOException, ArchiverException { File base = null; while ( resources.hasNext() ) { ArchiveEntry entry = resources.next(); String name = entry.getName(); name = name.replace( File.separatorChar, '/' ); if ( "".equals( name ) ) { continue; } if ( entry.getResource().isDirectory() && !name.endsWith( "/" ) ) { name = name + "/"; } addParentDirs( entry, base, name, zOut, "" ); if ( entry.getResource().isFile() ) { zipFile( entry, zOut, name ); } else { zipDir( entry.getResource(), zOut, name, entry.getMode() ); } } }public void compress() throws ArchiverException { try { zOut = new SnappyOutputStream( bufferedOutputStream( fileOutputStream( getDestFile() ) ) ); compress( getSource(), zOut ); } catch ( IOException ioe ) { String msg = "Problem creating snappy " + ioe.getMessage(); throw new ArchiverException( msg, ioe ); } }public void addArchives( File directoryName, String[] includes, String[] excludes ) throws ArchiverException { addDirectory( directoryName, "/", includes, excludes ); }public void addArchive( File fileName ) throws ArchiverException { addDirectory( fileName.getParentFile(), "/", new String[]{fileName.getName()}, null ); }public void setAppxml( File descr ) throws ArchiverException { deploymentDescriptor = descr; if ( !deploymentDescriptor.exists() ) { throw new ArchiverException( "Deployment descriptor: " + deploymentDescriptor + " does not exist." ); } addFile( descr, "META-INF/application.xml" ); }public static void mergeAttributes( java.util.jar.Attributes target, java.util.jar.Attributes section ) { for ( Object o : section.keySet() ) { java.util.jar.Attributes.Name key = (Attributes.Name) o; final Object value = section.get( o ); // the merge file always wins target.put( key, value ); } }public void compress() throws ArchiverException { try { zOut = new GZIPOutputStream( Streams.bufferedOutputStream( new FileOutputStream( getDestFile() ) )); compress( getSource(), zOut ); } catch ( IOException ioe ) { String msg = "Problem creating gzip " + ioe.getMessage(); throw new ArchiverException( msg, ioe ); } }private InputStream decompress( UntarCompressionMethod compression, final File file, final InputStream istream ) throws IOException, ArchiverException { if ( compression == UntarCompressionMethod.GZIP ) { return new GZIPInputStream( istream ); } else if ( compression == UntarCompressionMethod.BZIP2 ) { return new BZip2CompressorInputStream( istream ); } else if ( compression == UntarCompressionMethod.SNAPPY ) { return new SnappyInputStream( istream ); } return istream; }protected static void grabFilesAndDirs( String file, List dirs, List files ) throws IOException { File zipFile = new File( file ); if ( !zipFile.exists() ) { Logger logger = new ConsoleLogger( Logger.LEVEL_INFO, "console" ); logger.error( "JarArchive skipping non-existing file: " + zipFile.getAbsolutePath() ); } else if ( zipFile.isDirectory() ) { Logger logger = new ConsoleLogger( Logger.LEVEL_INFO, "console" ); logger.info( "JarArchiver skipping indexJar " + zipFile + " because it is not a jar" ); } else { org.apache.commons.compress.archivers.zip.ZipFile zf = null; try { zf = new org.apache.commons.compress.archivers.zip.ZipFile( file, "utf-8" ); Enumeration entries = zf.getEntries(); HashSet dirSet = new HashSet(); while ( entries.hasMoreElements() ) { ZipArchiveEntry ze = entries.nextElement(); String name = ze.getName(); // avoid index for manifest-only jars. if ( !name.equals( META_INF_NAME ) && !name.equals( META_INF_NAME + '/' ) && !name.equals( INDEX_NAME ) && !name.equals( MANIFEST_NAME ) ) { if ( ze.isDirectory() ) { dirSet.add( name ); } else if ( !name.contains( "/" ) ) { files.add( name ); } else { // a file, not in the root // since the jar may be one without directory // entries, add the parent dir of this file as // well. dirSet.add( name.substring( 0, name.lastIndexOf( "/" ) + 1 ) ); } } } dirs.addAll( dirSet ); } finally { if ( zf != null ) { zf.close(); } } } }protected final void writeIndexLikeList( List dirs, List files, PrintWriter writer ) { // JarIndex is sorting the directories by ascending order. // it has no value but cosmetic since it will be read into a // hashtable by the classloader, but we'll do so anyway. Collections.sort( dirs ); Collections.sort( files ); Iterator iter = dirs.iterator(); while ( iter.hasNext() ) { String dir = (String) iter.next(); // try to be smart, not to be fooled by a weird directory name dir = dir.replace( '\\', '/' ); if ( dir.startsWith( "./" ) ) { dir = dir.substring( 2 ); } while ( dir.startsWith( "/" ) ) { dir = dir.substring( 1 ); } int pos = dir.lastIndexOf( '/' ); if ( pos != -1 ) { dir = dir.substring( 0, pos ); } // name newline writer.println( dir ); } iter = files.iterator(); while ( iter.hasNext() ) { writer.println( iter.next() ); } }public void reset() { super.reset(); configuredManifest = null; filesetManifestConfig = null; mergeManifestsMain = false; manifestFile = null; index = false; }protected void cleanUp() throws IOException { super.cleanUp(); // we want to save this info if we are going to make another pass if ( !doubleFilePass || !skipWriting ) { manifest = null; configuredManifest = savedConfiguredManifest; filesetManifest = null; originalManifest = null; } rootEntries.removeAllElements(); }protected void zipFile( InputStream is, ZipArchiveOutputStream zOut, String vPath, long lastModified, File fromArchive, int mode, String symlinkDestination ) throws IOException, ArchiverException { if ( MANIFEST_NAME.equalsIgnoreCase( vPath ) ) { if ( !doubleFilePass || skipWriting ) { filesetManifest( fromArchive, is ); } } else if ( INDEX_NAME.equalsIgnoreCase( vPath ) && index ) { getLogger().warn( "Warning: selected " + archiveType + " files include a META-INF/INDEX.LIST which will" + " be replaced by a newly generated one." ); } else { if ( index && ( !vPath.contains( "/" ) ) ) { rootEntries.addElement( vPath ); } super.zipFile( is, zOut, vPath, lastModified, fromArchive, mode, symlinkDestination ); } }public void addConfiguredManifest( Manifest newManifest ) throws ManifestException { if ( configuredManifest == null ) { configuredManifest = newManifest; } else { JdkManifestFactory.merge( configuredManifest, newManifest, false ); } savedConfiguredManifest = configuredManifest; }protected void copyFile( final ArchiveEntry entry, final String vPath ) throws ArchiverException, IOException { // don't add "" to the archive if ( vPath.length() <= 0 ) { return; } final PlexusIoResource in = entry.getResource(); final File outFile = new File( vPath ); final long inLastModified = in.getLastModified(); final long outLastModified = outFile.lastModified(); if ( ResourceUtils.isUptodate( inLastModified, outLastModified ) ) { return; } if ( !in.isDirectory() ) { if ( !outFile.getParentFile().exists() ) { // create the parent directory... if ( !outFile.getParentFile().mkdirs() ) { // Failure, unable to create specified directory for some unknown reason. throw new ArchiverException( "Unable to create directory or parent directory of " + outFile ); } } ResourceUtils.copyFile( entry.getInputStream(), outFile ); if ( !isIgnorePermissions() ) { ArchiveEntryUtils.chmod( outFile, entry.getMode(), getLogger(), isUseJvmChmod() ); } } else { // file is a directory if ( outFile.exists() ) { if ( !outFile.isDirectory() ) { // should we just delete the file and replace it with a directory? // throw an exception, let the user delete the file manually. throw new ArchiverException( "Expected directory and found file at copy destination of " + in.getName() + " to " + outFile ); } } else if ( !outFile.mkdirs() ) { // Failure, unable to create specified directory for some unknown reason. throw new ArchiverException( "Unable to create directory or parent directory of " + outFile ); } } outFile.setLastModified( inLastModified == PlexusIoResource.UNKNOWN_MODIFICATION_DATE ? System.currentTimeMillis() : inLastModified ); }public ExistingSection getSection( String name ) { Attributes attributes = getAttributes( name ); if ( attributes != null ) { return new ExistingSection( attributes, name ); } return null; }Enumeration getWarnings() { Vector warnings = new Vector(); Enumeration warnEnum = mainSection.getWarnings(); while ( warnEnum.hasMoreElements() ) { warnings.addElement( warnEnum.nextElement() ); } return warnings.elements(); }public void write( PrintWriter writer ) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); super.write( byteArrayOutputStream ); for ( byte b : byteArrayOutputStream.toByteArray() ) { writer.write( (char) b ); } }public void addConfiguredSection( Section section ) throws ManifestException { String sectionName = section.getName(); if ( sectionName == null ) { throw new ManifestException( "Sections must have a name" ); } Attributes attributes = getOrCreateAttributes( sectionName ); for ( String s : section.attributes.keySet() ) { Attribute attribute = section.getAttribute( s ); attributes.putValue( attribute.getName(), attribute.getValue() ); } }public static Manifest getDefaultManifest() throws ArchiverException { try { String defManifest = "/org/codehaus/plexus/archiver/jar/defaultManifest.mf"; InputStream in = Manifest.class.getResourceAsStream( defManifest ); if ( in == null ) { throw new ArchiverException( "Could not find default manifest: " + defManifest ); } try { Manifest defaultManifest = new Manifest( new InputStreamReader( in, "UTF-8" ) ); defaultManifest.getMainAttributes().putValue( "Created-By", System.getProperty( "java.vm.version" ) + " (" + System.getProperty( "java.vm.vendor" ) + ")" ); return defaultManifest; } catch ( UnsupportedEncodingException e ) { return new Manifest( new InputStreamReader( in ) ); } finally { IOUtil.close( in ); } } catch ( ManifestException e ) { throw new ArchiverException( "Default manifest is invalid !!", e ); } catch ( IOException e ) { throw new ArchiverException( "Unable to read default manifest", e ); } }protected void zipFile( ArchiveEntry entry, ZipArchiveOutputStream zOut, String vPath ) throws IOException, ArchiverException { // If the file being added is WEB-INF/web.xml, we warn if it's // not the one specified in the "webxml" attribute - or if // it's being added twice, meaning the same file is specified // by the "webxml" attribute and in a element. if ( vPath.equalsIgnoreCase( "WEB-INF/web.xml" ) ) { if ( descriptorAdded || ( expectWebXml && ( deploymentDescriptor == null || !ResourceUtils.isCanonicalizedSame( entry.getResource(), deploymentDescriptor ) ) ) ) { getLogger().warn( "Warning: selected " + archiveType + " files include a WEB-INF/web.xml which will be ignored " + "\n(webxml attribute is missing from " + archiveType + " task, or ignoreWebxml attribute is specified as 'true')" ); } else { super.zipFile( entry, zOut, vPath ); descriptorAdded = true; } } else { super.zipFile( entry, zOut, vPath ); } }protected void initZipOutputStream( ZipArchiveOutputStream zOut ) throws ArchiverException, IOException { // If no webxml file is specified, it's an error. if ( expectWebXml && deploymentDescriptor == null && !isInUpdateMode() ) { throw new ArchiverException( "webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)" ); } super.initZipOutputStream( zOut ); }public void addWebinf( File directoryName, String[] includes, String[] excludes ) throws ArchiverException { addDirectory( directoryName, "WEB-INF/", includes, excludes ); }public static boolean isSame( PlexusIoResource resource, File file ) { if ( resource instanceof FileSupplier ) { File resourceFile = ((FileSupplier) resource).getFile(); return file.equals( resourceFile ); } return false; }public static void copyFile( PlexusIoResource in, File outFile ) throws IOException { InputStream input = null; OutputStream output = null; try { input = in.getContents(); output = new FileOutputStream( outFile ); IOUtil.copy( input, output ); } finally { IOUtil.close( input ); IOUtil.close( output ); } }static boolean agentIsAvailable() { try { if (instrumentation == null) { instrumentation = (Instrumentation)System.getProperties().get(INSTRUMENTATION_INSTANCE_SYSTEM_PROPERTY_NAME); } if (instrumentation == null) { Class sizeOfAgentClass = ClassLoader.getSystemClassLoader().loadClass(SIZEOF_AGENT_CLASSNAME); Method getInstrumentationMethod = sizeOfAgentClass.getMethod("getInstrumentation"); instrumentation = (Instrumentation)getInstrumentationMethod.invoke(sizeOfAgentClass); } return instrumentation != null; } catch (SecurityException e) { LOGGER.warn("Couldn't access the system classloader because of the security policies applied by " + "the security manager. You either want to loosen these, so ClassLoader.getSystemClassLoader() and " + "reflection API calls are permitted or the sizing will be done using some other mechanism.\n" + "Alternatively, set the system property org.ehcache.sizeof.agent.instrumentationSystemProperty to true " + "to have the agent put the required instances in the System Properties for the loader to access."); return false; } catch (Throwable e) { return false; } }static boolean loadAgent() { synchronized (AgentLoader.class.getName().intern()) { if (!agentIsAvailable() && VIRTUAL_MACHINE_LOAD_AGENT != null) { try { warnIfOSX(); String name = ManagementFactory.getRuntimeMXBean().getName(); Object vm = VIRTUAL_MACHINE_ATTACH.invoke(null, name.substring(0, name.indexOf('@'))); try { File agent = getAgentFile(); LOGGER.info("Trying to load agent @ {}", agent); if (agent != null) { VIRTUAL_MACHINE_LOAD_AGENT.invoke(vm, agent.getAbsolutePath()); } } finally { VIRTUAL_MACHINE_DETACH.invoke(vm); } } catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); LOGGER.info("Failed to attach to VM and load the agent: {}: {}", cause.getClass(), cause.getMessage()); } catch (Throwable t) { LOGGER.info("Failed to attach to VM and load the agent: {}: {}", t.getClass(), t.getMessage()); } } final boolean b = agentIsAvailable(); if (b) { LOGGER.info("Agent successfully loaded and available!"); } return b; } }public V remove(K key) { cleanUp(); return map.remove(new IdentityWeakReference<>(key, queue)); }public V put(K key, V value) { cleanUp(); return map.put(new IdentityWeakReference<>(key, queue), value); }private static Collection getAllFields(Class refClass) { Collection fields = new ArrayList<>(); for (Class klazz = refClass; klazz != null; klazz = klazz.getSuperclass()) { for (Field field : klazz.getDeclaredFields()) { if (!Modifier.isStatic(field.getModifiers()) && !field.getType().isPrimitive()) { try { field.setAccessible(true); } catch (SecurityException e) { LOG.error("Security settings prevent Ehcache from accessing the subgraph beneath '{}'" + " - cache sizes may be underestimated as a result", field, e); continue; } fields.add(field); } } } return fields; }private Collection getFilteredFields(Class refClass) { SoftReference> ref = fieldCache.get(refClass); Collection fieldList = ref != null ? ref.get() : null; if (fieldList != null) { return fieldList; } else { Collection result; result = sizeOfFilter.filterFields(refClass, getAllFields(refClass)); if (USE_VERBOSE_DEBUG_LOGGING && LOG.isDebugEnabled()) { for (Field field : result) { if (Modifier.isTransient(field.getModifiers())) { LOG.debug("SizeOf engine walking transient field '{}' of class {}", field.getName(), refClass.getName()); } } } fieldCache.put(refClass, new SoftReference<>(result)); return result; } }@SuppressWarnings("unchecked") public static T getAnnotationProxy(Annotation customAnnotation, Class referenceAnnotation) { InvocationHandler handler = new AnnotationInvocationHandler(customAnnotation); return (T)Proxy.newProxyInstance(referenceAnnotation.getClassLoader(), new Class[] { referenceAnnotation }, handler); }private Type getRequiredType(Class clazz) { TypeVariable[] typeParameters = clazz.getTypeParameters(); if (typeParameters.length > 0) { Type[] actualTypeParameters = new Type[typeParameters.length]; for (int i = 0; i < typeParameters.length; i++) { actualTypeParameters[i] = new WildcardTypeImpl(new Type[] { Object.class }, new Type[] {}); } return new ParameterizedTypeImpl(clazz, actualTypeParameters, null); } return clazz; }public void processDynaView(final PrettyContext prettyContext, final FacesContext facesContext) { log.trace("Requesting DynaView processing for: " + prettyContext.getRequestURL()); String viewId = ""; try { viewId = prettyContext.getCurrentViewId(); log.trace("Invoking DynaView method: " + viewId); Object result = computeDynaViewId(facesContext); if (result instanceof String) { viewId = (String) result; log.trace("Forwarding to DynaView: " + viewId); prettyContext.setDynaviewProcessed(true); facesContext.getExternalContext().dispatch(viewId); facesContext.responseComplete(); } } catch (Exception e) { log.error("Failed to process dynaview", e); PrettyRedirector prettyRedirector = new PrettyRedirector(); prettyRedirector.send404(facesContext); throw new PrettyException("Could not forward to view: " + viewId + "", e); } }public String buildDynaViewId(final String facesServletMapping) { StringBuffer result = new StringBuffer(); Map patterns = new LinkedHashMap(); Pattern pathMapping = Pattern.compile("^(/.*/)\\*$"); Pattern extensionMapping = Pattern.compile("^\\*(\\..*)$"); Pattern defaultMapping = Pattern.compile("^/$"); patterns.put(pathMapping, "$1" + DYNAVIEW + ".jsf"); patterns.put(extensionMapping, "/" + DYNAVIEW + "$1"); patterns.put(defaultMapping, "/" + DYNAVIEW + ".jsf"); boolean matched = false; Iterator iterator = patterns.keySet().iterator(); while ((matched == false) && iterator.hasNext()) { Pattern p = iterator.next(); Matcher m = p.matcher(facesServletMapping); if (m.matches()) { String replacement = patterns.get(p); m.appendReplacement(result, replacement); matched = true; } } if (matched == false) { // This is an exact url-mapping, use it. result.append(facesServletMapping); } return result.toString(); }private String translate(String lang, String value) { String translatation = null; if (value != null) { if (!bundleMap.containsKey(lang)) { Locale locale = new Locale(lang); try { ResourceBundle loadedBundle = ResourceBundle.getBundle(bundleName, locale, ResourceBundle.Control.getNoFallbackControl(ResourceBundle.Control.FORMAT_DEFAULT)); bundleMap.put(lang, loadedBundle); } catch (MissingResourceException e) { return null; } } try { // can we received more than one path section? e.g./search/service/ translatation = bundleMap.get(lang).getString(value); } catch (MissingResourceException mrEx) { // ignore } } return translatation; }private String stripContextPath(final String contextPath, String uri) { if (!contextPath.equals("/") && uri.startsWith(contextPath)) { uri = uri.substring(contextPath.length()); } return uri; }private String prependContextPath(ExternalContext externalContext, String url) { String contextPath = externalContext.getRequestContextPath(); if ("/".equals(contextPath) || (url.startsWith(contextPath))) { return url; } return contextPath + url; }@Override public void visit(Class clazz) { ClassContextImpl context = new ClassContextImpl(builder, clazz); context.put(clazz, payload); if (log.isTraceEnabled()) { log.trace("Scanning class: {}", clazz.getName()); } // first process the class visit(clazz, context); // only process fields and classes if a rule building has been started if (context.hasRuleBuildingStarted()) { // walk up the inheritance hierarchy Class currentType = clazz; while (currentType != null) { // then process the fields for (Field field : currentType.getDeclaredFields()) { visit(field, new FieldContextImpl(context, field)); } // then the methods for (Method method : currentType.getDeclaredMethods()) { MethodContextImpl methodContext = new MethodContextImpl(context, method); visit(method, methodContext); // then the method parameters for (int i = 0; i < method.getParameterTypes().length; i++) { ParameterImpl parameter = new ParameterImpl(method, method.getParameterTypes()[i], method.getParameterAnnotations()[i], i); visit(parameter, new ParameterContextImpl(methodContext, parameter)); } } currentType = currentType.getSuperclass(); } } }public void sendError(int code, String message, HttpServletResponse response) { Assert.notNull(response, "HttpServletResponse argument was null"); try { if (message != null) { response.sendError(code, message); } else { response.sendError(code); } } catch (IOException e) { throw new IllegalStateException("Failed to send error code: " + code, e); } }public URL buildURL(final UrlMapping mapping) { URL result = null; String expression = ""; Object value = null; try { FacesContext context = FacesContext.getCurrentInstance(); URLPatternParser parser = mapping.getPatternParser(); List parameters = parser.getPathParameters(); List parameterValues = new ArrayList(); for (PathParameter injection : parameters) { // read value of the path parameter expression = injection.getExpression().getELExpression(); value = elUtils.getValue(context, expression); if (value == null) { throw new PrettyException("PrettyFaces: Exception occurred while building URL for MappingId < " + mapping.getId() + " >, Required value " + " < " + expression + " > was null"); } // convert the value to a string using the correct converter Converter converter = context.getApplication().createConverter(value.getClass()); if (converter != null) { String convertedValue = converter.getAsString(context, new NullComponent(), value); if (convertedValue == null) { throw new PrettyException("PrettyFaces: The converter <" + converter.getClass().getName() + "> returned null while converting the object <" + value.toString() + ">!"); } value = convertedValue; } parameterValues.add(value.toString()); } result = parser.getMappedURL(parameterValues).encode(); } catch (ELException e) { throw new PrettyException("PrettyFaces: Exception occurred while building URL for MappingId < " + mapping.getId() + " >, Error occurred while extracting values from backing bean" + " < " + expression + ":" + value + " >", e); } return result; }public EncodeQuery excluding(final String... params) { if ((params != null) && (params.length > 0)) this.excludedParams.addAll(Arrays.asList(params)); return this; }AddressBuilderQuery queryLiteral(String query) { if (query != null) { if (query.startsWith("?")) query = query.substring(1); /* * Linked hash map is important here in order to retain the order of query parameters. */ Map> params = new LinkedHashMap>(); query = decodeHTMLAmpersands(query); int index = 0; while ((index = query.indexOf('&')) >= 0 || !query.isEmpty()) { String pair = query; if (index >= 0) { pair = query.substring(0, index); query = query.substring(index); if (!query.isEmpty()) query = query.substring(1); } else query = ""; String name; String value; int pos = pair.indexOf('='); // for "n=", the value is "", for "n", the value is null if (pos == -1) { name = pair; value = null; } else { name = pair.substring(0, pos); value = pair.substring(pos + 1, pair.length()); } List list = params.get(name); if (list == null) { list = new ArrayList(); params.put(name, list); } list.add(value); } for (Entry> entry : params.entrySet()) { query(entry.getKey(), entry.getValue().toArray()); } } return new AddressBuilderQuery(this); }private void handleClassEntry(String entryName, ClassVisitor visitor) { // build class name from relative name String className = getClassName(entryName.substring(CLASSES_FOLDER.length())); // check filter if (mustProcessClass(className) && !processedClasses.contains(className)) { // mark this class as processed processedClasses.add(className); // the class file stream InputStream classFileStream = null; // close the stream in finally block try { /* * Try to open the .class file. if this isn't possible, we will scan it anyway. */ classFileStream = servletContext.getResourceAsStream(entryName); if (classFileStream == null) { if (log.isDebugEnabled()) { log.debug("Could not obtain InputStream for class file: " + entryName); } } // analyze the class (with or without classFileStream) processClass(className, classFileStream, visitor); } finally { try { if (classFileStream != null) { classFileStream.close(); } } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to close input stream: " + e.getMessage()); } } } } }private String buildStandardOutcome() { StringBuilder outcome = new StringBuilder(); outcome.append(viewId); boolean first = true; for (Entry> param : parameters.entrySet()) { for (String value : param.getValue()) { outcome.append(first ? '?' : '&'); outcome.append(param.getKey()); outcome.append('='); outcome.append(value); first = false; } } return outcome.toString(); }public Navigate with(CharSequence name, Object value) { Assert.notNull(name, "name must not be null"); if (value != null) { parameters.put(name.toString(), value.toString()); } return this; }public static int getNegationCount(final EvaluationContext context) { if (context == null) return 0; Integer count = (Integer)context.get(NEGATION_COUNT_KEY); return count == null ? 0 : count; }@SuppressWarnings("unchecked") private List getDispatcherTypeProviders(HttpServletRewrite event) { List providers = (List) event.getRequest().getAttribute(PROVIDER_KEY); if (providers == null) { providers = Iterators.asList(ServiceLoader.loadTypesafe(DispatcherTypeProvider.class).iterator()); Collections.sort(providers, new WeightedComparator()); event.getRequest().setAttribute(PROVIDER_KEY, providers); } return providers; }public void addParameter(final String name, final String... values) { Map parameter = new LinkedHashMap(); parameter.put(name, values); addParameterArrays(parameter); }public static String extractQuery(String url) { if (url != null) { int index = url.indexOf('?'); if (index >= 0) { url = url.substring(index + 1); } } return url; }public static QueryStringBuilder createFromEncoded(final String parameters) { QueryStringBuilder queryString = new QueryStringBuilder(); queryString.addParameters(parameters); return queryString; }public List getValidatorsForPathParam(final PathParameter param) { List result = new ArrayList(); for (PathValidator pv : pathValidators) { if (pv.getIndex() == param.getPosition()) { result.add(pv); } } return result; }public URLPatternParser getPatternParser() { if ((parser == null) && (pattern != null)) { this.parser = new URLPatternParser(pattern); } return parser; }@Override public String deriveViewId(final FacesContext context, final String rawViewId) { String canonicalViewId = new URLDuplicatePathCanonicalizer().canonicalize(rawViewId); return parent.deriveViewId(context, canonicalViewId); }public void addParameters(String url) { if ((url != null) && !"".equals(url)) { url = url.trim(); if (url.length() > 1) { if (url.contains("?")) { url = url.substring(url.indexOf('?') + 1); } String pairs[] = url.split("&(amp;)?"); for (String pair : pairs) { String name; String value; int pos = pair.indexOf('='); // for "n=", the value is "", for "n", the value is null if (pos == -1) { name = pair; value = null; } else { try { // FIXME This probably shouldn't be happening here. name = URLDecoder.decode(pair.substring(0, pos), "UTF-8"); value = URLDecoder.decode(pair.substring(pos + 1, pair.length()), "UTF-8"); } catch (IllegalArgumentException e) { // thrown by URLDecoder if character decoding fails log.warn("Ignoring invalid query parameter: " + pair); continue; } catch (UnsupportedEncodingException e) { throw new PrettyException( "UTF-8 encoding not supported. Something is seriously wrong with your environment."); } } List list = parameters.get(name); if (list == null) { list = new ArrayList(); parameters.put(name, list); } list.add(value); } } } return; }public String[] getParameterValues(final String name) { List values = parameters.get(name); if (values == null) { return null; } return values.toArray(new String[values.size()]); }public String getParameter(final String name) { List values = parameters.get(name); if (values == null) { return null; } if (values.size() == 0) { return ""; } return values.get(0); }public static QueryString build(final String url) { QueryString queryString = new QueryString(); queryString.addParameters(url); return queryString; }public URI toURI() { try { URI uri = new URI(toURL()); return uri; } catch (URISyntaxException e) { throw new IllegalStateException("URL cannot be parsed.", e); } }protected static CharSequence encodeUriQuery(CharSequence in) { /* * Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things. TODO: * replace/compare to with Rewrite Encoding */ StringBuilder outBuf = null; Formatter formatter = null; for (int i = 0; i < in.length(); i++) { char c = in.charAt(i); boolean escape = true; if (c < 128) { if (asciiQueryChars.get(c)) { escape = false; } } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) { /* * not-ascii */ escape = false; } if (!escape) { if (outBuf != null) outBuf.append(c); } else { /* * escape */ if (outBuf == null) { outBuf = new StringBuilder(in.length() + 5 * 3); outBuf.append(in, 0, i); formatter = new Formatter(outBuf); } /* * leading %, 0 padded, width 2, capital hex */ formatter.format("%%%02X", (int) c);// TODO } } return outBuf != null ? outBuf : in; }protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletResponse servletResponse) { for (Header header : proxyResponse.getAllHeaders()) { if (hopByHopHeaders.containsHeader(header.getName())) continue; servletResponse.addHeader(header.getName(), header.getValue()); } }private boolean containsFieldDescriptor(String str) { for (String descriptor : fieldDescriptors) { if (str.contains(descriptor)) { return true; } } return false; }public static El method(final String retrieve, final String submit) { return new ElMethod(new ConstantExpression(retrieve), new ConstantExpression(submit)); }private String buildScriptInternal(final String url) { StringBuilder builder = new StringBuilder(); builder.append("window.location.href = '"); builder.append(url); builder.append("'; return false;"); return builder.toString(); }public static boolean containsEL(final String value) { if (value == null) { return false; } return elPattern.matcher(value).find(); }public static boolean isEL(final String value) { if (value == null) { return false; } return elPattern.matcher(value).matches(); }public boolean detectTierOtherPhones() { if ((this.initCompleted == true) || (this.isTierGenericMobile == true)) return this.isTierGenericMobile; // Exclude devices in the other 2 categories if (detectMobileLong() && !detectTierIphone() && !detectTierRichCss()) return true; return false; }public boolean detectTierIphone() { if ((this.initCompleted == true) || (this.isTierIphone == true)) return this.isTierIphone; if (detectIphoneOrIpod() || detectAndroidPhone() || detectWindowsPhone() || detectBlackBerry10Phone() || (detectBlackBerryWebKit() && detectBlackBerryTouch()) || detectPalmWebOS() || detectBada() || detectTizen() || detectGamingHandheld()) { return true; } return false; }public boolean detectMobileQuick() { // Let's exclude tablets if (detectTierTablet()) return false; if ((initCompleted == true) || (isMobilePhone == true)) return isMobilePhone; // Most mobile browsing is done on smartphones if (detectSmartphone()) return true; if (detectWapWml() || detectBrewDevice() || detectOperaMobile()) return true; if ((userAgent.indexOf(engineObigo) != -1) || (userAgent.indexOf(engineNetfront) != -1) || (userAgent.indexOf(engineUpBrowser) != -1) || (userAgent.indexOf(engineOpenWeb) != -1)) return true; if (detectDangerHiptop() || detectMidpCapable() || detectMaemoTablet() || detectArchos()) return true; if ((userAgent.indexOf(devicePda) != -1) && (userAgent.indexOf(disUpdate) < 0)) // no index found return true; if (userAgent.indexOf(mobile) != -1) return true; // We also look for Kindle devices if (detectKindle() || detectAmazonSilk()) return true; return false; }public boolean detectMaemoTablet() { if (userAgent.indexOf(maemo) != -1) { return true; } else if (userAgent.indexOf(linux) != -1 && userAgent.indexOf(deviceTablet) != -1 && !detectWebOSTablet() && !detectAndroid()) { return true; } return false; }public boolean detectOperaAndroidTablet() { if (userAgent.indexOf(engineOpera) != -1 && (userAgent.indexOf(deviceAndroid) != -1 && userAgent.indexOf(deviceTablet) != -1)) { return true; } return false; }public boolean detectOperaAndroidPhone() { if (userAgent.indexOf(engineOpera) != -1 && (userAgent.indexOf(deviceAndroid) != -1 && userAgent.indexOf(mobi) != -1)) { return true; } return false; }public boolean detectPalmOS() { // Make sure it's not WebOS first if (detectPalmWebOS()) return false; // Most devices nowadays report as 'Palm', but some older ones reported as Blazer or Xiino. if (userAgent.indexOf(devicePalm) != -1 || userAgent.indexOf(engineBlazer) != -1 || userAgent.indexOf(engineXiino) != -1) { return true; } return false; }public boolean detectS60OssBrowser() { // First, test for WebKit, then make sure it's either Symbian or S60. if (detectWebkit() && (userAgent.indexOf(deviceSymbian) != -1 || userAgent.indexOf(deviceS60) != -1)) { return true; } return false; }public boolean detectBlackBerry() { if (userAgent.indexOf(deviceBB) != -1 || httpAccept.indexOf(vndRIM) != -1) return true; if (detectBlackBerry10Phone()) return true; return false; }public boolean detectWindowsMobile() { if (detectWindowsPhone()) { return false; } // Most devices use 'Windows CE', but some report 'iemobile' // and some older ones report as 'PIE' for Pocket IE. // We also look for instances of HTC and Windows for many of their WinMo devices. if (userAgent.indexOf(deviceWinMob) != -1 || userAgent.indexOf(deviceWinMob) != -1 || userAgent.indexOf(deviceIeMob) != -1 || userAgent.indexOf(enginePie) != -1 || (userAgent.indexOf(manuHtc) != -1 && userAgent.indexOf(deviceWindows) != -1) || (detectWapWml() && userAgent.indexOf(deviceWindows) != -1)) { return true; } // Test for Windows Mobile PPC but not old Macintosh PowerPC. if (userAgent.indexOf(devicePpc) != -1 && !(userAgent.indexOf(deviceMacPpc) != -1)) return true; return false; }public boolean detectWebkit() { if ((this.initCompleted == true) || (this.isWebkit == true)) return this.isWebkit; if (userAgent.indexOf(engineWebKit) != -1) { return true; } return false; }public boolean detectIphone() { if ((this.initCompleted == true) || (this.isIphone == true)) return this.isIphone; // The iPad and iPod touch say they're an iPhone! So let's disambiguate. if (userAgent.indexOf(deviceIphone) != -1 && !detectIpad() && !detectIpod()) { return true; } return false; }public void initDeviceScan() { // Save these properties to speed processing this.isWebkit = detectWebkit(); this.isIphone = detectIphone(); this.isAndroid = detectAndroid(); this.isAndroidPhone = detectAndroidPhone(); // Generally, these tiers are the most useful for web development this.isMobilePhone = detectMobileQuick(); this.isTierTablet = detectTierTablet(); this.isTierIphone = detectTierIphone(); // Optional: Comment these out if you NEVER use them this.isTierRichCss = detectTierRichCss(); this.isTierGenericMobile = detectTierOtherPhones(); this.initCompleted = true; }private static String join(String[] values, String separator) { StringBuilder result = new StringBuilder(); if (values != null) { for (int i = 0; i < values.length; i++) { if (i > 0) { result.append(separator); } result.append(values[i]); } } return result.toString(); }public String[] processClassMappingAnnotations(Class clazz) { // list of all mapping IDs found on the class List classMappingIds = new ArrayList(); // get reference to @URLMapping annotation URLMapping mappingAnnotation = (URLMapping) clazz.getAnnotation(URLMapping.class); // process annotation if it exists if (mappingAnnotation != null) { String mappingId = processPrettyMappingAnnotation(clazz, mappingAnnotation); classMappingIds.add(mappingId); } // container annotation URLMappings mappingsAnnotation = (URLMappings) clazz.getAnnotation(URLMappings.class); if (mappingsAnnotation != null) { // process all contained @URLMapping annotations for (URLMapping child : mappingsAnnotation.mappings()) { String mappingId = processPrettyMappingAnnotation(clazz, child); classMappingIds.add(mappingId); } } // return list of mappings found return classMappingIds.toArray(new String[classMappingIds.size()]); }private Digester configureDigester(final Digester digester) { /* * We use the context class loader to resolve classes. This fixes * ClassNotFoundExceptions on Geronimo. */ digester.setUseContextClassLoader(true); /* * Parse RewriteRules */ digester.addObjectCreate("pretty-config/rewrite", RewriteRule.class); digester.addSetProperties("pretty-config/rewrite"); digester.addSetNext("pretty-config/rewrite", "addRewriteRule"); /* * Create Mapping Object */ digester.addObjectCreate("pretty-config/url-mapping", UrlMapping.class); digester.addSetProperties("pretty-config/url-mapping"); digester.addCallMethod("pretty-config/url-mapping/pattern", "setPattern", 1); digester.addCallParam("pretty-config/url-mapping/pattern", 0, "value"); digester.addCallMethod("pretty-config/url-mapping/pattern", "setPattern", 0); /* * Parse View Id */ digester.addCallMethod("pretty-config/url-mapping/view-id", "setViewId", 1); digester.addCallParam("pretty-config/url-mapping/view-id", 0, "value"); digester.addCallMethod("pretty-config/url-mapping/view-id", "setViewId", 0); /* * Parse Path Validators */ digester.addObjectCreate("pretty-config/url-mapping/pattern/validate", PathValidator.class); digester.addSetProperties("pretty-config/url-mapping/pattern/validate"); digester.addSetNext("pretty-config/url-mapping/pattern/validate", "addPathValidator"); /* * Parse Query Params */ digester.addObjectCreate("pretty-config/url-mapping/query-param", QueryParameter.class); digester.addSetProperties("pretty-config/url-mapping/query-param"); digester.addCallMethod("pretty-config/url-mapping/query-param", "setExpression", 0); digester.addSetNext("pretty-config/url-mapping/query-param", "addQueryParam"); /* * Parse Action Methods */ digester.addObjectCreate("pretty-config/url-mapping/action", UrlAction.class); digester.addSetProperties("pretty-config/url-mapping/action"); digester.addCallMethod("pretty-config/url-mapping/action", "setAction", 0); digester.addSetNext("pretty-config/url-mapping/action", "addAction"); /* * Add Mapping to Builder */ digester.addSetNext("pretty-config/url-mapping", "addMapping"); return digester; }protected String stripKnownPrefix(String str, String prefix) { int startIndex = str.lastIndexOf(prefix); if (startIndex != -1) { return str.substring(startIndex + prefix.length()); } return null; }public Metadata copy() { Metadata result = new Metadata(); result.setEncoding(encoding); result.setTrailingSlash(trailingSlash); result.setLeadingSlash(leadingSlash); return result; }@Override public final Subscription observe(O observer) { P adapted = adaptObserver(observer); underlying.addObserver(adapted); return () -> underlying.removeObserver(adapted); }public T onWhile(Supplier f) { try(Guard g = on()) { return f.get(); } }@Deprecated public static ObservableList wrap(javafx.collections.ObservableList delegate) { return LiveList.suspendable(delegate); }public static EventStream merge( ObservableSet> set) { return new EventStreamBase() { @Override protected Subscription observeInputs() { return Subscription.dynamic(set, s -> s.subscribe(this::emit)); } }; }public static EventStream animationFrames() { return animationTicks() .accumulate(t(0L, -1L), (state, now) -> state.map((d, last) -> { return t(last == -1L ? 0L : now - last, now); })) .map(t -> t._1); }public static EventStream repeatOnInvalidation(O observable) { return new EventStreamBase() { @Override protected Subscription observeInputs() { InvalidationListener listener = obs -> emit(observable); observable.addListener(listener); return () -> observable.removeListener(listener); } @Override protected void newObserver(Consumer subscriber) { subscriber.accept(observable); } }; }public static EventStream invalidationsOf(Observable observable) { return new EventStreamBase() { @Override protected Subscription observeInputs() { InvalidationListener listener = obs -> emit(null); observable.addListener(listener); return () -> observable.removeListener(listener); } }; }public static List concatView(List> lists) { if(lists.isEmpty()) { return Collections.emptyList(); } else { return ConcatView.create(lists); } }public Map flattenAsMap() { if (flattenedMap != null) return flattenedMap; flattenedMap = newJsonifyLinkedHashMap(); reduce(source); while (!elementIters.isEmpty()) { IndexedPeekIterator deepestIter = elementIters.getLast(); if (!deepestIter.hasNext()) { elementIters.removeLast(); } else if (deepestIter.peek() instanceof Member) { Member mem = (Member) deepestIter.next(); reduce(mem.getValue()); } else { // JsonValue JsonValue val = (JsonValue) deepestIter.next(); reduce(val); } } return flattenedMap; }public String flatten() { flattenAsMap(); if (source.isObject() || isObjectifiableArray()) return flattenedMap.toString(printMode); else return javaObj2Json(flattenedMap.get(ROOT)); }public String unflatten() { StringWriter sw = new StringWriter(); if (root.isArray()) { try { unflattenArray(root.asArray()).writeTo(sw, getWriterConfig()); } catch (IOException e) {} return sw.toString(); } if (!root.isObject()) { return root.toString(); } JsonObject flattened = root.asObject(); JsonValue unflattened = flattened.names().isEmpty() ? Json.object() : null; for (String key : flattened.names()) { JsonValue currentVal = unflattened; String objKey = null; Integer aryIdx = null; Matcher matcher = keyPartPattern().matcher(key); while (matcher.find()) { String keyPart = matcher.group(); if (objKey != null ^ aryIdx != null) { if (isJsonArray(keyPart)) { currentVal = findOrCreateJsonArray(currentVal, objKey, aryIdx); objKey = null; aryIdx = extractIndex(keyPart); } else { // JSON object if (flattened.get(key).isArray()) { // KEEP_ARRAYS mode flattened.set(key, unflattenArray(flattened.get(key).asArray())); } currentVal = findOrCreateJsonObject(currentVal, objKey, aryIdx); objKey = extractKey(keyPart); aryIdx = null; } } if (objKey == null && aryIdx == null) { if (isJsonArray(keyPart)) { aryIdx = extractIndex(keyPart); if (currentVal == null) currentVal = Json.array(); } else { // JSON object objKey = extractKey(keyPart); if (currentVal == null) currentVal = Json.object(); } } if (unflattened == null) unflattened = currentVal; } setUnflattenedValue(flattened, key, currentVal, objKey, aryIdx); } try { unflattened.writeTo(sw, getWriterConfig()); } catch (IOException e) {} return sw.toString(); }@Override public float getLeafValue(FVec feat, int root_id) { Node n = nodes[root_id]; while (!n._isLeaf) { n = nodes[n.next(feat)]; } return n.leaf_value; }@Override public int getLeafIndex(FVec feat, int root_id) { int pid = root_id; Node n; while (!(n = nodes[pid])._isLeaf) { pid = n.next(feat); } return pid; }public void loadModel(ModelReader reader) throws IOException { param = new Param(reader); nodes = new Node[param.num_nodes]; for (int i = 0; i < param.num_nodes; i++) { nodes[i] = new Node(reader); } stats = new RTreeNodeStat[param.num_nodes]; for (int i = 0; i < param.num_nodes; i++) { stats[i] = new RTreeNodeStat(reader); } }public float[] predict(FVec feat, boolean output_margin, int ntree_limit) { float[] preds = predictRaw(feat, ntree_limit); if (! output_margin) { preds = obj.predTransform(preds); } return preds; }private static boolean appearsInAssignmentContext(Expression expression) { if (expression.getParentNode().isPresent()) { Node parent = expression.getParentNode().get(); if (parent instanceof ExpressionStmt) { return false; } if (parent instanceof MethodCallExpr) { return false; } if (parent instanceof ReturnStmt) { return false; } throw new UnsupportedOperationException(parent.getClass().getCanonicalName()); } return false; }�public boolean invocationApplicabilityInference(MethodCallExpr methodCallExpr, ResolvedMethodDeclaration methodDeclaration) { if (!methodCallExpr.getNameAsString().equals(methodDeclaration.getName())) { throw new IllegalArgumentException(); } Optional partial = instantiationInference(methodCallExpr, methodDeclaration); if (!partial.isPresent()) { return false; } int nActualParams = methodCallExpr.getArguments().size(); int nFormalParams = methodDeclaration.getNumberOfParams(); if (nActualParams != nFormalParams) { if (methodDeclaration.hasVariadicParameter()) { if (nActualParams < (nFormalParams - 1)) { return false; } } else { return false; } } //MethodUsage methodUsage = instantiationSetToMethodUsage(methodDeclaration, partial.get()); // for (int i=0;i= nFormalParams ? nFormalParams - 1 : i; // Type formalType = methodDeclaration.getParam(formalIndex).getType(); // Type actualType = JavaParserFacade.get(typeSolver).getType(methodCallExpr.getArgument(i)); // //if (!formalType.isAssignableBy(actualType)) { // // return false; // //} // } return true; }public static Value from(ResolvedValueDeclaration decl) { ResolvedType type = decl.getType(); return new Value(type, decl.getName()); }public static SymbolReference solveMethodInType(ResolvedTypeDeclaration typeDeclaration, String name, List argumentsTypes, boolean staticOnly, TypeSolver typeSolver) { if (typeDeclaration instanceof JavaParserClassDeclaration) { Context ctx = ((JavaParserClassDeclaration) typeDeclaration).getContext(); return ctx.solveMethod(name, argumentsTypes, staticOnly, typeSolver); } if (typeDeclaration instanceof JavaParserInterfaceDeclaration) { Context ctx = ((JavaParserInterfaceDeclaration) typeDeclaration).getContext(); return ctx.solveMethod(name, argumentsTypes, staticOnly, typeSolver); } if (typeDeclaration instanceof JavaParserEnumDeclaration) { if (name.equals("values") && argumentsTypes.isEmpty()) { return SymbolReference.solved(new JavaParserEnumDeclaration.ValuesMethod((JavaParserEnumDeclaration) typeDeclaration, typeSolver)); } Context ctx = ((JavaParserEnumDeclaration) typeDeclaration).getContext(); return ctx.solveMethod(name, argumentsTypes, staticOnly, typeSolver); } if (typeDeclaration instanceof JavaParserAnonymousClassDeclaration) { Context ctx = ((JavaParserAnonymousClassDeclaration) typeDeclaration).getContext(); return ctx.solveMethod(name, argumentsTypes, staticOnly, typeSolver); } if (typeDeclaration instanceof ReflectionClassDeclaration) { return ((ReflectionClassDeclaration) typeDeclaration).solveMethod(name, argumentsTypes, staticOnly); } if (typeDeclaration instanceof ReflectionInterfaceDeclaration) { return ((ReflectionInterfaceDeclaration) typeDeclaration).solveMethod(name, argumentsTypes, staticOnly); } if (typeDeclaration instanceof ReflectionEnumDeclaration) { return ((ReflectionEnumDeclaration) typeDeclaration).solveMethod(name, argumentsTypes, staticOnly); } if (typeDeclaration instanceof JavassistInterfaceDeclaration) { return ((JavassistInterfaceDeclaration) typeDeclaration).solveMethod(name, argumentsTypes, staticOnly); } if (typeDeclaration instanceof JavassistClassDeclaration) { return ((JavassistClassDeclaration) typeDeclaration).solveMethod(name, argumentsTypes, staticOnly); } if (typeDeclaration instanceof JavassistEnumDeclaration) { return ((JavassistEnumDeclaration) typeDeclaration).solveMethod(name, argumentsTypes, staticOnly); } throw new UnsupportedOperationException(typeDeclaration.getClass().getCanonicalName()); }@Deprecated public SymbolReference solveTypeInType(ResolvedTypeDeclaration typeDeclaration, String name) { if (typeDeclaration instanceof JavaParserClassDeclaration) { return ((JavaParserClassDeclaration) typeDeclaration).solveType(name, typeSolver); } if (typeDeclaration instanceof JavaParserInterfaceDeclaration) { return ((JavaParserInterfaceDeclaration) typeDeclaration).solveType(name, typeSolver); } return SymbolReference.unsolved(ResolvedReferenceTypeDeclaration.class); }public boolean canCompleteNormally(Statement statement) { if (!isReachable(statement)) { return false; } GenericVisitor visitor = new GenericVisitorAdapter(){ @Override public Boolean visit(BlockStmt n, Void arg) { // An empty block that is not a switch block can complete normally iff it is reachable if (n.isEmpty() && !parentIs(statement, SwitchStmt.class)) { return isReachable(statement); } // A non-empty block that is not a switch block can complete normally iff the last statement in // it can complete normally. if (!n.isEmpty() && !parentIs(statement, SwitchStmt.class)) { return canCompleteNormally(n.getStatement(n.getStatements().size() - 1)); } throw new UnsupportedOperationException(); } @Override public Boolean visit(LabeledStmt n, Void arg) { // A labeled statement can complete normally if at least one of the following is true: // – The contained statement can complete normally. // – There is a reachable break statement that exits the labeled statement. throw new UnsupportedOperationException(); } @Override public Boolean visit(EmptyStmt n, Void arg) { // An empty statement can complete normally iff it is reachable. return isReachable(n); } @Override public Boolean visit(LocalClassDeclarationStmt n, Void arg) { // A local class declaration statement can complete normally iff it is reachable. return isReachable(n); } @Override public Boolean visit(IfStmt n, Void arg) { if (n.getElseStmt().isPresent()) { // An if-then-else statement can complete normally iff the then-statement can // complete normally or the else-statement can complete normally. return canCompleteNormally(n.getThenStmt()) || canCompleteNormally(n.getElseStmt().get()); } else { // An if-then statement can complete normally iff it is reachable. return isReachable(n); } } @Override public Boolean visit(AssertStmt n, Void arg) { // An assert statement can complete normally iff it is reachable. return isReachable(n); } @Override public Boolean visit(ExpressionStmt n, Void arg) { // A local variable declaration statement can complete normally iff it is reachable. if (n.getExpression() instanceof VariableDeclarationExpr) { VariableDeclarationExpr expr = (VariableDeclarationExpr) n.getExpression(); return isReachable(n); } // An expression statement can complete normally iff it is reachable. return isReachable(n); } }; return statement.accept(visitor, null); }public boolean exitTheStatement(BreakStmt breakStmt) { if (!isReachable(breakStmt)) { return false; } Statement breakTarget = breakTarget(breakStmt); for (TryStmt tryStmt : containedTryStmts(breakTarget)) { if (contains(tryStmt.getTryBlock(), breakStmt)) { if (!tryStmt.getFinallyBlock().isPresent() && !canCompleteNormally(tryStmt.getFinallyBlock().get())) { return false; } } } return true; }public ResolvedType getTypeOfThisIn(Node node) { // TODO consider static methods if (node instanceof ClassOrInterfaceDeclaration) { return new ReferenceTypeImpl(getTypeDeclaration((ClassOrInterfaceDeclaration) node), typeSolver); } else if (node instanceof EnumDeclaration) { JavaParserEnumDeclaration enumDeclaration = new JavaParserEnumDeclaration((EnumDeclaration) node, typeSolver); return new ReferenceTypeImpl(enumDeclaration, typeSolver); } else if (node instanceof ObjectCreationExpr && ((ObjectCreationExpr) node).getAnonymousClassBody().isPresent()) { JavaParserAnonymousClassDeclaration anonymousDeclaration = new JavaParserAnonymousClassDeclaration((ObjectCreationExpr) node, typeSolver); return new ReferenceTypeImpl(anonymousDeclaration, typeSolver); } else { return getTypeOfThisIn(getParentNode(node)); } }private String qName(ClassOrInterfaceType classOrInterfaceType) { String name = classOrInterfaceType.getName().getId(); if (classOrInterfaceType.getScope().isPresent()) { return qName(classOrInterfaceType.getScope().get()) + "." + name; } else { return name; } }private Optional find(Map map, LambdaExpr lambdaExpr) { for (Node key : map.keySet()) { if (key instanceof LambdaExpr) { LambdaExpr keyLambdaExpr = (LambdaExpr) key; if (keyLambdaExpr.toString().equals(lambdaExpr.toString()) && getParentNode(keyLambdaExpr) == getParentNode(lambdaExpr)) { return Optional.of(map.get(keyLambdaExpr)); } } } return Optional.empty(); }public SymbolReference solve(MethodCallExpr methodCallExpr, boolean solveLambdas) { List argumentTypes = new LinkedList<>(); List placeholders = new LinkedList<>(); solveArguments(methodCallExpr, methodCallExpr.getArguments(), solveLambdas, argumentTypes, placeholders); SymbolReference res = JavaParserFactory.getContext(methodCallExpr, typeSolver).solveMethod(methodCallExpr.getName().getId(), argumentTypes, false, typeSolver); for (LambdaArgumentTypePlaceholder placeholder : placeholders) { placeholder.setMethod(res); } return res; }public SymbolReference solve(ObjectCreationExpr objectCreationExpr, boolean solveLambdas) { List argumentTypes = new LinkedList<>(); List placeholders = new LinkedList<>(); solveArguments(objectCreationExpr, objectCreationExpr.getArguments(), solveLambdas, argumentTypes, placeholders); ResolvedType classDecl = JavaParserFacade.get(typeSolver).convert(objectCreationExpr.getType(), objectCreationExpr); if (!classDecl.isReferenceType()) { return SymbolReference.unsolved(ResolvedConstructorDeclaration.class); } SymbolReference res = ConstructorResolutionLogic.findMostApplicable(((ResolvedClassDeclaration) classDecl.asReferenceType().getTypeDeclaration()).getConstructors(), argumentTypes, typeSolver); for (LambdaArgumentTypePlaceholder placeholder : placeholders) { placeholder.setMethod(res); } return res; }private ResolvedType solveDotExpressionType(ResolvedReferenceTypeDeclaration parentType, FieldAccessExpr node) { // Fields and internal type declarations cannot have the same name. // Thus, these checks will always be mutually exclusive. if (parentType.hasField(node.getName().getId())) { return parentType.getField(node.getName().getId()).getType(); } else if (parentType.hasInternalType(node.getName().getId())) { return new ReferenceTypeImpl(parentType.getInternalType(node.getName().getId()), typeSolver); } else { throw new UnsolvedSymbolException(node.getName().getId()); } }public static ResolvedType glb(Set types) { if (types.size() == 0) { throw new IllegalArgumentException(); } if (types.size() == 1) { return types.iterator().next(); } return new ResolvedIntersectionType(types); }private static ResolvedReferenceType nonWildcardParameterizationOf(ResolvedReferenceType originalType, TypeSolver typeSolver) { List TIs = new LinkedList<>(); List AIs = originalType.typeParametersValues(); List TPs = originalType.getTypeDeclaration().getTypeParameters(); // Let P1...Pn be the type parameters of I with corresponding bounds B1...Bn. For all i (1 ≤ i ≤ n), // Ti is derived according to the form of Ai: ResolvedReferenceType object = new ReferenceTypeImpl(typeSolver.solveType(Object.class.getCanonicalName()), typeSolver); for (int i=0;i(Arrays.asList(Ui, Bi))); } // - If Ai is a lower-bounded wildcard ? super Li, then Ti = Li. else if (Ai.isWildcard() && Ai.asWildcard().isLowerBounded()) { Ti = Ai.asWildcard().getBoundedType(); } else throw new RuntimeException("This should not happen"); } TIs.add(Ti); } return new ReferenceTypeImpl(originalType.getTypeDeclaration(), TIs, typeSolver); }public static Pair groundTargetTypeOfLambda(LambdaExpr lambdaExpr, ResolvedType T, TypeSolver typeSolver) { // The ground target type is derived from T as follows: // boolean used18_5_3 = false; boolean wildcardParameterized = T.asReferenceType().typeParametersValues().stream() .anyMatch(tp -> tp.isWildcard()); if (wildcardParameterized) { // - If T is a wildcard-parameterized functional interface type and the lambda expression is explicitly typed, // then the ground target type is inferred as described in §18.5.3. if (ExpressionHelper.isExplicitlyTyped(lambdaExpr)) { used18_5_3 = true; throw new UnsupportedOperationException(); } // - If T is a wildcard-parameterized functional interface type and the lambda expression is implicitly typed, // then the ground target type is the non-wildcard parameterization (§9.9) of T. else { return new Pair<>(nonWildcardParameterizationOf(T.asReferenceType(), typeSolver), used18_5_3); } } // - Otherwise, the ground target type is T. return new Pair<>(T, used18_5_3); }public static boolean isProperType(ResolvedType type) { if (type instanceof InferenceVariable) { return false; } if (type instanceof ResolvedReferenceType) { ResolvedReferenceType referenceType = (ResolvedReferenceType) type; return referenceType.typeParametersValues().stream().allMatch(it -> isProperType(it)); } if (type instanceof ResolvedWildcard) { ResolvedWildcard wildcard = (ResolvedWildcard)type; if (wildcard.isBounded()) { return isProperType(wildcard.getBoundedType()); } else { return true; } } if (type.isPrimitive()) { return true; } if (type.isTypeVariable()) { // FIXME I am not sure... return false; } if (type.isArray()) { return isProperType(type.asArrayType().getComponentType()); } throw new UnsupportedOperationException(type.toString()); }public static SymbolReference unsolved(Class clazz) { return new SymbolReference<>(Optional.empty()); }public static SymbolReference solved(S2 symbolDeclaration) { return new SymbolReference(Optional.of(symbolDeclaration)); }@Override public ResolvedType transformTypeParameters(ResolvedTypeTransformer transformer) { ResolvedType result = this; int i = 0; for (ResolvedType tp : this.typeParametersValues()) { ResolvedType transformedTp = transformer.transform(tp); // Identity comparison on purpose if (transformedTp != tp) { List typeParametersCorrected = result.asReferenceType().typeParametersValues(); typeParametersCorrected.set(i, transformedTp); result = create(typeDeclaration, typeParametersCorrected); } i++; } return result; } �; B2f�P���W�n�8��)�ZH��u����k �Q�E�-�-nd�%�8F�w�R�)Y֦�b����~��p����fV �bx6Pd�B��d�|-��� �͵�6�$�)l�P��xǪG,YtfsabaFB�t��R��A I�$�7P�����[��h�z�/Aǣqr{�p�܎����tp�W����.�]��k��(����dd�q��3�,�2+(9����*��gÄd�)G��$�ʲT������[�JH����"�W1{��y%�1Yɔ�DˎCj�t)���a�0S Hyi T�L��ZκWϖJ����^�#�R�x�� n�Q���973�>R:�1T�H\Ph�_<|�v�s�S��_�6���������,��P$%#�O ?ZGR��=H�X)kH� -�Ȋ��&�ڋm[�-Hl�/��'w4�Ʒ�?f�i���Crw�L����-�T��j��Kc=ڱ���/���ȣD��%�G즘�f� K1}}xfo��Y�d �!C٨�@Y�[ׂ�d��:y}�a�(�7vǞxQ�QJ|@��WM ��#=M��i8\�����7 ���-7����Z�������µ�E�����)�(ӥG(�rHd� �sV�1!�#{��� �%>ҷ�#���꽡R'�r��6[(1K�4<+ �u��qO?�x1����jL_�M��+[��Y@�Z�TFڗ�O�� �E���-&jn��o6 �(��W�О� VH v� P%���5U3�m������@{C� זv���Y��\�R[:o�L��M�rt!,E�UY7�x'��G��o��� 1荼���^%�q~��r�yo��a��m=���l���i���ޘt61���a��Kjȍ���S�Ez^�~q6Ex�_� v��'4�@�u��O�jF{�/�ޣ���a��|ۆ�K1�t��~�k�lBes�����X$ !;{EH6�K�:"� A.|�zŤ��{���߆x��0��7�!]���,�p�1�`*⣒�ʅ�P��A�B��j q�CA����%-N-�i��ڻ R&�؝�����{�s����o�)i�o��G���*�7�t��w����� �}��o�nw/gS\� ��iڠ��9� *:��r�%X��3R'�}nei�ݠ�>���ݭ�Un�����g���*��b���[�L�هN �!��|�Y.=����C��0S.�#�ؤ�($P�m�Fvh�x�7-�l���Z�>��1A�VUҨ��o�z‘��=.����%��̫��=���p�����Ր��ht��|��U�y'�! �\ ʭ�ԩ�@I*nWϫg!�J�?FW�y��G?��KoD>���Dh�n�5��K�R� �p��1|$1 M�3�]!���Q�2��^�Z���dim Z<ޓ����'K[�׼R�e�Vr0<)�����-8V^��o�[�?*!/m�����r�i1i��x�p�J˱�� �s,�����c��פ��K.��4��1; '{9(�j��8�k����]?@���*M[ڲrȌXr��w���D'�9>�b�� ��P\���,���9Z7@�����V�38�;2�h�\����ݵ7ߧ������f]H�r��7QewK.�|��B����J��ۼ��u���",�͛c��D�ȕ%��s���JR���=.���ZT^u���u�߮F��uS����3�1�O���=o�c-R�\�衧Lh � �1xj���_�AI�e2C���@[b����|-�Hh�B����hCT\/F:�����@S�r)H��P r$)�B�G�2\�?�B��_�����؛ҿ_�� �`I�,���*p����P�� � ��9Vt��1�" )u+�/#2�5�9�:�;@=Z>?@iB�E*HK�M0PUR�S�T�U�WGYIa|ggjJk^nFp�s�tv-wvxj{�|�}t~7��Ր��,���f�����o���߳H�����E�S�U����*�s�W�����.�<�������� �#���o�g�d�t�������������c���'������_(�������;!&#�%�(�-Z/!8W:<B=I>�A�BFٹ��qHJaL�N)Q�S�W�X�Y�Z�[J]�]�^Z_ `�`La�a�b,e�f�i�j]m�q�rqu�vzs�!� �=���Ԓ-�2���I�ݨ��]�,�����D�O��Ŷ �J�ۺ?������P�"�����,�~���J�k����������������_���=���\$lK��"�$�%Y,Y8�@�DPI�M�P�S|W}Z�]�d�h�q&x.�̍X�����<��c�����C�#��ä�ب����������`����ڿ������������{�f�$�'���9�����Q���������n Y �q`T/� E!�#�-�8�;�<t=~C�G�H�IGK�K�L/U![�\�a�h�i�j�k�n�o�rwx6z��������L�>�/�����N����� �\��ե��C��v�d�_�$��� ���������������������0����������C�)������|� �����Z����� ���2���9�����V�������}�V����\���public void initAfterLoad(ClusteredSipStack sipStackImpl) { String transport = getLastResponseTopMostVia().getTransport(); Iterator providers = sipStackImpl.getSipProviders(); boolean providerNotFound = true; while(providers.hasNext()) { SipProviderImpl providerImpl = providers.next(); if(providerImpl.getListeningPoint(transport) != null) { setSipProvider(providerImpl); providerNotFound = false; } } if(providerNotFound) { throw new RuntimeException("No providers found for transport=" + transport + " on this node. Make sure connectors are configured for this transport"); } setStack((SIPTransactionStack)sipStackImpl); setAssigned(); firstTransactionPort = getSipProvider().getListeningPoint(getLastResponseTopMostVia().getTransport()).getPort(); ackProcessed = true; // ackSeen = true; }protected void removeDialogFromDistributedCache(String dialogId) { if(getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) { getStackLogger().logDebug("sipStack " + this + " removing the dialog " + dialogId + " from the distributed cache"); } // remove the corresponding dialog from the cache instance // put the corresponding dialog into the cache instance try { sipCache.removeDialog(dialogId); } catch (SipCacheException e) { getStackLogger().logError("sipStack " + this + " problem removing dialog " + dialogId + " from the distributed cache", e); } }protected void putDialogIntoDistributedCache(SIPDialog dialog) { String dialogId = dialog.getDialogId(); if(getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) { getStackLogger().logDebug("sipStack " + this + " storing the dialog " + dialogId + " in the distributed cache"); } // put the corresponding dialog into the cache instance try { sipCache.putDialog(dialog); } catch (SipCacheException e) { getStackLogger().logError("sipStack " + this + " problem storing the dialog " + dialogId + " into the distributed cache", e); } }protected SIPDialog getDialogFromDistributedCache(String dialogId) { if(getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) { getStackLogger().logDebug("sipStack " + this + " checking if the dialog " + dialogId + " is present in the distributed cache"); } // fetch the corresponding dialog from the cache instance SIPDialog sipDialog = null; try { sipDialog = sipCache.getDialog(dialogId); } catch (SipCacheException e) { getStackLogger().logError("sipStack " + this + " problem getting dialog " + dialogId + " from the distributed cache", e); } if(sipDialog != null) { if(getStackLogger().isLoggingEnabled(StackLogger.TRACE_DEBUG)) { getStackLogger().logDebug("sipStack " + this + " dialog " + dialogId + " was present in the distributed cache, initializing it after the load"); } ((HASipDialog)sipDialog).initAfterLoad(this); } return sipDialog; }private ToStringBuilder appendFormattedValue(String name, Object value) { if (!first) { sb.append(SEPARATOR); } sb.append(name).append(FIELD_VALUE_SEPARATOR).append(value); first = false; return this; }public ToStringBuilder append(String name, Iterable values) { StringBuilder pending = new StringBuilder().append(OPEN_ARRAY); boolean firstItem = true; for (T value : values) { if (!firstItem) { pending.append(SEPARATOR); } pending.append(formatValue(value)); firstItem = false; } return appendFormattedValue(name, pending.append(CLOSE_ARRAY).toString()); }public ToStringBuilder append(String name, Map map) { StringBuilder sb = new StringBuilder(START_OBJ); for (Map.Entry entry : map.entrySet()) { sb.append(entry.getKey()).append(FIELD_VALUE_SEPARATOR).append(formatValue(entry.getValue())); } sb.append(END_OBJ); return appendFormattedValue(name, sb.toString()); }private void handleHeaders(RequestBuilder builder) { for (HttpHeader header : headers.values()) { builder.addHeader(header.getName(), header.serializeValues()); } }private void handleCookies(RequestBuilder builder) { if (!cookies.isEmpty()) { builder.addHeader(HttpHeaders.COOKIE, Cookies.serialize(cookies)); } }private void handleFormParameters(RequestBuilder builder) { for (HttpParameter p : formParams.values()) { builder.addFormParam(p.getName(), p.getValue()); } }private void handleBody(RequestBuilder builder) { if (!hasBody()) { return; } if (body != null) { handleRequestBody(builder); } else { handleFormParameters(builder); } }private void handleQueryParameters(RequestBuilder builder) { for (HttpParameter p : queryParams.values()) { builder.addQueryParam(p.getEncodedName(), p.getEncodedValue()); } }public static String join(String separator, Collection values) { StringBuilder builder = new StringBuilder(); boolean first = true; for (String value : values) { if (!first) { builder.append(separator); } builder.append(value); first = false; } return builder.toString(); }public static String removePrefix(String value, String prefix) { if (value == null || prefix == null || prefix.length() > value.length()) { return value; } return value.startsWith(prefix) ? value.substring(prefix.length()) : value; }static boolean isBlank(String value) { if (value == null) { return true; } for (char character : value.toCharArray()) { if (!Character.isWhitespace(character)) { return false; } } return true; }private void handleHeaders(Request.Builder builder) { for (HttpHeader h : headers.values()) { builder.addHeader(h.getName(), h.serializeValues()); } }static String formatTime(long time, String pattern) { Date date = new Date(); date.setTime(time); return format(date, pattern); }public static String format(Date date, String pattern) { return df(pattern).format(date); }@SuppressWarnings("unchecked") public static T invoke(Method method) { boolean forceAccess = false; try { if (!method.isAccessible()) { method.setAccessible(true); forceAccess = true; } return (T) method.invoke(null); } catch (InvocationTargetException | IllegalAccessException ex) { throw new ReflectionException(ex); } finally { if (forceAccess) { method.setAccessible(false); } } }@SuppressWarnings("unchecked") public static T getter(Object target, Field field) { boolean forceAccess = false; try { if (!field.isAccessible()) { field.setAccessible(true); forceAccess = true; } return (T) field.get(target); } catch (IllegalAccessException ex) { throw new ReflectionException(ex); } finally { if (forceAccess) { field.setAccessible(false); } } }public static void setter(Object instance, Field field, Object value) { boolean forceAccess = false; try { if (!field.isAccessible()) { forceAccess = true; field.setAccessible(true); } field.set(instance, value); } catch (IllegalAccessException ex) { throw new ReflectionException(ex); } finally { if (forceAccess) { field.setAccessible(false); } } }public static List findStaticMethodsAnnotatedWith(Class type, Class klass) { List methods = findStaticMethods(type); return filter(methods, new MethodAnnotatedWithPredicate(klass)); }public static List findStaticFieldsAnnotatedWith(Class type, Class klass) { List fields = findStaticFields(type); return filter(fields, new FieldAnnotatedWithPredicate(klass)); }private static List findStaticMethods(Class type) { return filter(asList(type.getDeclaredMethods()), STATIC_METHOD_PREDICATE); }private static List findStaticFields(Class type) { return filter(asList(type.getDeclaredFields()), STATIC_FIELD_PREDICATE); }public static List findAllFields(Class type) { List fields = new LinkedList<>(); if (type != null) { addAll(fields, type.getDeclaredFields()); if (type.getSuperclass() != null) { fields.addAll(findAllFields(type.getSuperclass())); } } return fields; }@Deprecated public static OkHttpClient newOkHttpClient(EmbeddedServer server, okhttp3.OkHttpClient client) { return new OkHttpClient(HttpClientConfiguration.defaultConfiguration(), server, client); }public static OkHttpClient defaultOkHttpClient(EmbeddedServer server) { HttpClientConfiguration configuration = HttpClientConfiguration.defaultConfiguration(); return newOkHttpClient(configuration, server); }private static EmbeddedJetty instantiate(Class klass) { final EmbeddedJettyConfiguration configuration = extractConfiguration(klass); return configuration == null ? new EmbeddedJetty() : new EmbeddedJetty(configuration); }public static DefaultHttpResponse of(long duration, int status, String body, Collection headers) { return new DefaultHttpResponse(duration, status, body, headers); }static List filter(List list, Predicate predicate) { List results = new ArrayList<>(); for (T current : list) { if (predicate.apply(current)) { results.add(current); } } return results; }public static List concat(List inputs, T newValue) { List outputs = new ArrayList<>(inputs.size() + 1); outputs.addAll(inputs); outputs.add(newValue); return outputs; }public static List map(Collection inputs, Mapper mapper) { if (inputs == null) { return null; } List outputs = new ArrayList<>(inputs.size()); for (T input : inputs) { outputs.add(mapper.apply(input)); } return outputs; }private static int parseJavaVersion() { String[] parts = JAVA_SPECIFICATION_VERSION.split("\\."); int nbParts = parts.length; int majorIndex = nbParts > 1 ? 1 : 0; return Integer.parseInt(parts[majorIndex]); }public static AsyncHttpClient defaultAsyncHttpClient(EmbeddedServer server) { HttpClientConfiguration configuration = HttpClientConfiguration.defaultConfiguration(); return newAsyncHttpClient(configuration, server); }private void handleCookies(HttpRequestBase httpRequest) { if (!cookies.isEmpty()) { httpRequest.addHeader(COOKIE, Cookies.serialize(cookies)); } }private void handleRequestBody(HttpEntityEnclosingRequestBase httpRequest) { HttpEntity entity = new StringEntity(body, Charset.defaultCharset()); httpRequest.setEntity(entity); }private void handleFormParameters(HttpEntityEnclosingRequestBase httpRequest) { List pairs = map(formParams.values(), PARAM_MAPPER); HttpEntity entity = new UrlEncodedFormEntity(pairs, Charset.defaultCharset()); httpRequest.setEntity(entity); }private void handleHeaders(HttpRequestBase httpRequest) { for (HttpHeader header : headers.values()) { httpRequest.addHeader(header.getName(), header.serializeValues()); } }private URI createRequestURI() throws URISyntaxException { URI uri = getEndpoint().toURI(); URIBuilder builder = new URIBuilder(uri).setCharset(StandardCharsets.UTF_8); for (HttpParameter parameter : queryParams.values()) { builder.addParameter(parameter.getName(), parameter.getValue()); } return builder.build(); }private void handleBody(HttpRequestBase httpRequest) { if (hasBody()) { HttpEntityEnclosingRequestBase rq = (HttpEntityEnclosingRequestBase) httpRequest; if (!formParams.isEmpty()) { handleFormParameters(rq); } else if (body != null) { handleRequestBody(rq); } } }public static ApacheHttpClient defaultApacheHttpClient(EmbeddedServer server) { HttpClientConfiguration configuration = HttpClientConfiguration.defaultConfiguration(); return newApacheHttpClient(configuration, server); }@Deprecated public static ApacheHttpClient newApacheHttpClient(EmbeddedServer server, CloseableHttpClient client) { return new ApacheHttpClient(HttpClientConfiguration.defaultConfiguration(), server, client); }private void processField(Object target, AnnotationHandler handler, Field field, boolean before) { for (Annotation annotation : field.getAnnotations()) { if (handler.support(annotation)) { if (before) { handler.before(target, field); } else { handler.after(target, field); } } } }private void process(Object target, boolean before) { List fields = findAllFields(target.getClass()); for (Field field : fields) { for (AnnotationHandler handler : handlers) { processField(target, handler, field, before); } } }private void execHooks(boolean pre) { for (Hook hook : configuration.getHooks()) { if (pre) { hook.pre(this); } else { hook.post(this); } } }private WebAppContext createdWebAppContext() throws Exception { final String path = configuration.getPath(); final String webapp = configuration.getWebapp(); final String classpath = configuration.getClasspath(); final ClassLoader parentClassLoader = configuration.getParentClassLoader(); final String overrideDescriptor = configuration.getOverrideDescriptor(); final Resource baseResource = configuration.getBaseResource(); final String containerJarPattern = configuration.getContainerJarPattern(); final String webInfJarPattern = configuration.getWebInfJarPattern(); WebAppContext ctx = new WebAppContext(); if (containerJarPattern != null) { ctx.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, containerJarPattern); } else if (JavaUtils.isPostJdk9()) { // Fix to make TLD scanning works with Java >= 9 ctx.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, ".*\\.jar"); } if (webInfJarPattern != null) { ctx.setAttribute(WebInfConfiguration.WEBINF_JAR_PATTERN, webInfJarPattern); } final ClassLoader systemClassLoader = Thread.currentThread().getContextClassLoader(); final ClassLoader classLoader; if (parentClassLoader != null) { classLoader = new CompositeClassLoader(parentClassLoader, systemClassLoader); } else { classLoader = systemClassLoader; } ctx.setClassLoader(classLoader); ctx.setContextPath(path); if (baseResource == null) { // use default base resource ctx.setBaseResource(newResource(webapp)); } else { ctx.setBaseResource(baseResource); } if (overrideDescriptor != null) { ctx.setOverrideDescriptor(overrideDescriptor); } ctx.setConfigurations(new Configuration[] { new WebInfConfiguration(), new WebXmlConfiguration(), new AnnotationConfiguration(), new JettyWebXmlConfiguration(), new MetaInfConfiguration(), new FragmentConfiguration() }); if (isNotBlank(classpath)) { // Fix to scan Spring WebApplicationInitializer // This will add compiled classes to jetty classpath // See: http://stackoverflow.com/questions/13222071/spring-3-1-webapplicationinitializer-embedded-jetty-8-annotationconfiguration // And more precisely: http://stackoverflow.com/a/18449506/1215828 File classes = new File(classpath); PathResource containerResources = new PathResource(classes.toURI()); ctx.getMetaData().addContainerResource(containerResources); } ctx.setParentLoaderPriority(true); ctx.setWar(webapp); ctx.setServer(server); // Add server context server.setHandler(ctx); return ctx; }public static HttpHeader header(String name, Collection values) { return new HttpHeader(name, values); }public static HttpHeader header(String name, String value) { return new HttpHeader(name, singletonList(value)); }public static Cookie read(String rawValue) { notBlank(rawValue, "Cookie value"); final String[] parts = rawValue.split(FIELD_SEPARATOR); // Extract name and value final String[] nameAndValue = parts[0].split(NAME_VALUE_SEPARATOR); if (nameAndValue.length != 2) { throw new IllegalArgumentException("Cookie must have a valid name and a valid value"); } final String name = nameAndValue[0].trim(); final String value = nameAndValue[1].trim(); if (name.isEmpty()) { throw new IllegalArgumentException("Cookie must have a valid name"); } // Extract other parts Map params = new HashMap<>(); if (parts.length > 1) { for (String part : parts) { String[] param = part.split(NAME_VALUE_SEPARATOR); String paramName = param[0].toLowerCase().trim(); String paramValue = param.length == 2 ? param[1].trim() : ""; params.put(paramName, paramValue); } } final String domain = params.get("domain"); final String path = params.get("path"); final boolean secure = params.containsKey("secure"); final boolean httpOnly = params.containsKey("httponly"); final String maxAgeTt = params.get("max-age"); final String expiresDate = params.get("expires"); Long expires; Long maxAge = maxAgeTt == null ? null : Long.valueOf(maxAgeTt); if (expiresDate != null) { expires = getTime(expiresDate, "EEE, d MMM yyyy HH:mm:ss Z", "EEE, d-MMM-yyyy HH:mm:ss Z", "EEE, d/MMM/yyyy HH:mm:ss Z"); } else { expires = null; } if (maxAge == null && expires == null) { maxAge = 0L; } else if (maxAge == null) { maxAge = expires - System.currentTimeMillis(); } return Cookies.cookie(name, value, domain, path, expires, maxAge, secure, httpOnly); }@Deprecated protected Context createContext() throws Exception { Context context = null; final String webapp = configuration.getWebapp(); final String path = configuration.getPath(); final String classpath = configuration.getClasspath(); final boolean forceMetaInf = configuration.isForceMetaInf(); final ClassLoader parentClassLoader = configuration.getParentClasspath(); final String descriptor = configuration.getOverrideDescriptor(); File webappDirectory = new File(webapp); if (webappDirectory.exists()) { String webappAbsolutePath = webappDirectory.getAbsolutePath(); tomcat.getHost().setAppBase(webappAbsolutePath); context = tomcat.addWebapp(path, webappAbsolutePath); // Add additional classpath entry if (isNotBlank(classpath)) { File file = new File(classpath); if (file.exists()) { // Check that additional classpath entry contains META-INF directory File metaInf = new File(file, "META-INF"); if (!metaInf.exists() && forceMetaInf) { metaInf.mkdir(); } // == Tomcat 8 String absolutePath = file.getAbsolutePath(); StandardRoot root = new StandardRoot(context); root.createWebResourceSet( WebResourceRoot.ResourceSetType.PRE, "/WEB-INF/classes", absolutePath, null, path ); context.setResources(root); // == Tomcat 8 // == Tomcat 7 // String s = file.toURI().toString(); // loader.addRepository(s); // == Tomcat 7 // Used to scan additional classpath directory // https://issues.apache.org/bugzilla/show_bug.cgi?id=52853 ((StandardJarScanner) context.getJarScanner()).setScanAllDirectories(true); } } // Custom parent classloader. final ClassLoader threadCl = Thread.currentThread().getContextClassLoader(); final ClassLoader tomcatParentClassLoader; if (parentClassLoader != null) { tomcatParentClassLoader = new CompositeClassLoader(parentClassLoader, threadCl); } else { tomcatParentClassLoader = threadCl; } // Set the parent class loader that will be given // to the created loader. // // Setting the parent class loader here is a shortcut for (code in previous versions): // // Loader loader = context.getLoader(); // if (loader == null) { // loader = new WebappLoader(parentClassLoader); // } // context.setParentClassLoader(tomcatParentClassLoader); // Override web.xml path if (descriptor != null) { context.setAltDDName(descriptor); } } return context; }public static String concatenatePath(String path, String endpoint) { String firstSegment = ensureAbsolutePath(path); if (endpoint == null || endpoint.isEmpty()) { return firstSegment; } StringBuilder sb = new StringBuilder(firstSegment); if (path.charAt(path.length() - 1) != PATH_SEPARATOR) { sb.append(PATH_SEPARATOR); } if (endpoint.charAt(0) == PATH_SEPARATOR) { sb.append(endpoint.substring(1)); } else { sb.append(endpoint); } return sb.toString(); }@SuppressWarnings("unchecked") private static T findInStore(ExtensionContext context, String name) { return (T) getStore(context).get(name); }@SuppressWarnings("unchecked") private static void putInStore(ExtensionContext context, String name, T value) { getStore(context).put(name, value); }private void unregisterEmbeddedServer(ExtensionContext context, boolean staticMode) { boolean registeredAsStatic = findInStore(context, SERVER_RUNNER_STATIC_MODE); if (registeredAsStatic == staticMode) { try { EmbeddedServerRunner serverAdapter = findEmbeddedServerAdapterInStore(context); serverAdapter.afterAll(); } finally { removeEmbeddedServerAdapterFromStore(context); } } }private EmbeddedServerRunner registerEmbeddedServer(ExtensionContext context, boolean staticMode) { Class testClass = context.getRequiredTestClass(); EmbeddedServer server = this.server == null ? instantiateServer(testClass, configuration) : this.server; EmbeddedServerRunner serverAdapter = new EmbeddedServerRunner(server); serverAdapter.beforeAll(); putEmbeddedServerAdapterInStore(context, serverAdapter, staticMode); return serverAdapter; }private static EmbeddedTomcat instantiate(Class klass) { EmbeddedTomcatConfiguration configuration = extractConfiguration(klass); return configuration == null ? new EmbeddedTomcat() : new EmbeddedTomcat(configuration); }@SuppressWarnings("unchecked") public T getModuleConfig(ConfigProvider provider) throws ConfigurationParseException { Class moduleClass = provider.getType(); if(configCache.containsKey(moduleClass)) return (T) configCache.get(moduleClass); synchronized(this) { if(configCache.containsKey(moduleClass)) { return (T) configCache.get(moduleClass); } T config = configurationJsonParser.parseJSONPNCConfig(CONFIG_STRING, provider); configCache.put(moduleClass, config); return config; } }public static String retrieveCloneName(String bcName, Date now) { String bcNameToAppend = ""; int index = bcName.indexOf("_"); if (index == -1) { // No '_' was found, need to append date prefix to whole bcName bcNameToAppend = bcName; } else { // A '_' char was found, need to analyze if the prefix is a date (to // be replaced with new one) String prefix = bcName.substring(0, index); if (prefix.length() == CLONE_PREFIX_DATE_FORMAT.length()) { try { new SimpleDateFormat(CLONE_PREFIX_DATE_FORMAT).parse(prefix); // The prefix was a date, need to append new date to a substring // of original bcName bcNameToAppend = bcName.substring(index + 1); } catch (ParseException ex) { // The prefix was not a date, need to append date prefix to // whole bcName bcNameToAppend = bcName; } } else { bcNameToAppend = bcName; } } StringBuilder sb = new StringBuilder(); sb.append(new SimpleDateFormat(CLONE_PREFIX_DATE_FORMAT).format(now)).append("_").append(bcNameToAppend); return sb.toString(); }private boolean removeDependant(BuildConfiguration dependant) { boolean result = dependants.remove(dependant); if (dependant.getDependencies().contains(this)) { dependant.removeDependency(this); } return result; }private boolean addDependant(BuildConfiguration dependant) { boolean result = dependants.add(dependant); if (!dependant.getDependencies().contains(this)) { dependant.addDependency(this); } return result; }public Set getAllDependencies() { Set allDependencies = new HashSet(); allDependencies.addAll(getDependencies()); allDependencies.addAll(getIndirectDependencies()); return allDependencies; }public boolean deleteTemporaryBuild(Integer buildRecordId, String authToken, Consumer onComplete) throws ValidationException { BuildRecord buildRecord = buildRecordRepository.findByIdFetchAllProperties(buildRecordId); if (buildRecord == null) { return false; } if (!buildRecord.isTemporaryBuild()) { throw new ValidationException("Only deletion of the temporary builds is allowed"); } executorService.submit(() -> { try { Result result = temporaryBuildsCleaner.deleteTemporaryBuild(buildRecordId, authToken); onComplete.accept(result); } catch (ValidationException e) { logger.error("Failed to delete temporary buildRecord.id: " + buildRecordId + ".", e); onComplete.accept(new Result(buildRecordId.toString(), Result.Status.FAILED, "Failed to delete temporary buildRecord.")); } }); return true; }public BuildRecord removeBuildRecord(BuildRecord buildRecord) { getBuildRecords().remove(buildRecord); buildRecord.setUser(null); return buildRecord; }public BuildRecord addBuildRecord(BuildRecord buildRecord) { getBuildRecords().add(buildRecord); buildRecord.setUser(this); return buildRecord; }static boolean isTrusted(String artifactOriginUrl, TargetRepository targetRepository) { if (targetRepository.temporaryRepo) { return false; } if (artifactOriginUrl == null || artifactOriginUrl.isEmpty()) { return false; } for (String trustedRepoUrl : TRUSTED_REPOSITORY_URLS) { if (artifactOriginUrl.startsWith(trustedRepoUrl)) { return true; } } return false; }public synchronized Optional getTask(BuildConfigurationAudited buildConfigAudited) { Optional ready = readyTasks.stream().filter(bt -> bt.getBuildConfigurationAudited().equals(buildConfigAudited)).findAny(); Optional waiting = waitingTasksWithCallbacks.keySet().stream().filter(bt -> bt.getBuildConfigurationAudited().equals(buildConfigAudited)).findAny(); Optional inProgress = tasksInProgress.stream().filter(bt -> bt.getBuildConfigurationAudited().equals(buildConfigAudited)).findAny(); return ready.isPresent() ? ready : waiting.isPresent() ? waiting : inProgress; }public synchronized void executeNewReadyTasks() { List newReadyTasks = extractReadyTasks(); log.debug("starting new ready tasks. New ready tasks: {}", newReadyTasks); readyTasks.addAll(newReadyTasks); }public synchronized void addWaitingTask(BuildTask task, Runnable taskReadyCallback) { unfinishedTasks.add(task); log.debug("adding waiting task: {}", task); waitingTasksWithCallbacks.put(task, taskReadyCallback); }public synchronized boolean addReadyTask(BuildTask task) { if (!task.readyToBuild()) { throw new IllegalArgumentException("a not ready task added to the queue: " + task); } unfinishedTasks.add(task); log.debug("adding task: {}", task); readyTasks.add(task); return true; }public static String serializeInt(Integer[] integers) { if (integers == null) { return ""; } return Arrays.stream(integers) .map(i -> Integer.toString(i)).collect(Collectors.joining(",")); }public static Integer[] deserializeInt(String string) { if (string == null) { return new Integer[0]; } return Arrays.stream(string.split(",")) .filter(s -> !s.equals("")) .map(Integer::parseInt).toArray(Integer[]::new); }public static String addEndingSlash(String string) { if (string == null) { return null; } if (!string.endsWith("/")) { string += "/"; } return string; }public CollectionInfo getBuiltArtifactsForBuildRecord(int pageIndex, int pageSize, String sortingRsql, String query, int buildRecordId) { return queryForCollection(pageIndex, pageSize, sortingRsql, query, withBuildRecordId(buildRecordId)); }private void fillBuildTaskSet( BuildSetTask buildSetTask, User user, Supplier buildTaskIdProvider, ProductMilestone productMilestone, Set toBuild, Set alreadySubmittedBuildTasks, BuildOptions buildOptions) { for (BuildConfigurationAudited buildConfigAudited : toBuild) { Optional taskOptional = alreadySubmittedBuildTasks.stream() .filter(bt -> bt.getBuildConfigurationAudited().equals(buildConfigAudited)) .findAny(); BuildTask buildTask; if (taskOptional.isPresent()) { buildTask = taskOptional.get(); log.debug("Linking BuildConfigurationAudited {} to existing task {}.", buildConfigAudited, buildTask); } else { int buildId = buildTaskIdProvider.get(); String buildContentId = ContentIdentityManager.getBuildContentId(buildId); MDCUtils.addBuildContext(buildContentId, buildOptions.isTemporaryBuild(), temporaryBuildExpireDate); buildTask = BuildTask.build( buildConfigAudited, buildSetTask.getBuildOptions(), user, buildId, buildSetTask, buildSetTask.getStartTime(), productMilestone, buildContentId); log.debug("Created new buildTask {} for BuildConfigurationAudited {}.", buildTask, buildConfigAudited); } buildSetTask.addBuildTask(buildTask); } // Loop again to set dependencies for (BuildTask buildTask : buildSetTask.getBuildTasks()) { for (BuildTask checkDepBuildTask : buildSetTask.getBuildTasks()) { if (buildTask.hasDirectConfigDependencyOn(checkDepBuildTask)) { buildTask.addDependency(checkDepBuildTask); } } } }public BuildSetTask createBuildSetTask( BuildConfigurationSet buildConfigurationSet, Map buildConfigurationAuditedsMap, User user, BuildOptions buildOptions, Supplier buildTaskIdProvider, Set submittedBuildTasks) throws CoreException { BuildSetTask buildSetTask = initBuildSetTask(buildConfigurationSet, user, buildOptions); Set buildConfigurationAuditeds = new HashSet<>(); for (BuildConfiguration buildConfiguration : datastoreAdapter.getBuildConfigurations(buildConfigurationSet)) { BuildConfigurationAudited buildConfigurationAudited = buildConfigurationAuditedsMap.get(buildConfiguration.getId()); if(buildConfigurationAudited == null) { buildConfigurationAudited = datastoreAdapter.getLatestBuildConfigurationAuditedInitializeBCDependencies(buildConfiguration.getId()); } buildConfigurationAuditeds.add(buildConfigurationAudited); } // initializeBuildTasksInSet log.debug("Initializing BuildTasks In Set for BuildConfigurationAuditeds: {}.", buildConfigurationAuditeds.stream().map(bc ->bc.toString()).collect(Collectors.joining("; "))); fillBuildTaskSet( buildSetTask, user, buildTaskIdProvider, buildConfigurationSet.getCurrentProductMilestone(), buildConfigurationAuditeds, submittedBuildTasks, buildOptions); return buildSetTask; }public BuildSetTask createBuildSetTask( BuildConfigurationSet buildConfigurationSet, User user, BuildOptions buildOptions, Supplier buildTaskIdProvider, Set submittedBuildTasks) throws CoreException { return createBuildSetTask(buildConfigurationSet, Collections.emptyMap(), user, buildOptions, buildTaskIdProvider, submittedBuildTasks); }private boolean collectDependentConfigurations(BuildConfiguration buildConfiguration, BuildConfigurationAudited buildConfigurationAudited, Set toBuild, Set visited, boolean checkImplicitDependencies, boolean forceRebuild, boolean temporaryBuild) { if (visited.contains(buildConfiguration)) { return toBuild.contains(buildConfigurationAudited); } visited.add(buildConfiguration); boolean requiresRebuild = forceRebuild || datastoreAdapter.requiresRebuild(buildConfigurationAudited, checkImplicitDependencies, temporaryBuild); for (BuildConfiguration dependency : buildConfiguration.getDependencies()) { boolean dependencyRequiresRebuild = collectDependentConfigurations(dependency, datastoreAdapter.getLatestBuildConfigurationAuditedInitializeBCDependencies(dependency.getId()), toBuild, visited, checkImplicitDependencies, forceRebuild, temporaryBuild); requiresRebuild = requiresRebuild || dependencyRequiresRebuild; } log.debug("Configuration {} requires rebuild: ", buildConfiguration.getId(), requiresRebuild); if (requiresRebuild) { toBuild.add(buildConfigurationAudited); } return requiresRebuild; }Map getExtendedProcessParameters() throws CoreException { Serializable processParameters = getProcessParameters(); requireNonNull(processParameters); Map actualParameters = new HashMap<>(); try { actualParameters.put("processParameters", MAPPER.writeValueAsString(processParameters)); } catch (JsonProcessingException e) { throw new CoreException("Could not serialize process processParameters '" + processParameters + "'.", e); } //global not process related parameters actualParameters.put("taskId", taskId); actualParameters.put("usersAuthToken", accessToken); return actualParameters; }public void addListener(BpmEventType eventType, Consumer listener) { List> consumers = listeners.computeIfAbsent(eventType, (k) -> new ArrayList<>()); consumers.add(listener); }private boolean hasARebuiltExplicitDependency(BuildRecord latestSuccessfulBuildRecord, Set dependencies, boolean temporaryBuild) { for (BuildConfiguration dependencyBuildConfiguration : dependencies) { BuildRecord dependencyLatestSuccessfulBuildRecord = buildRecordRepository.getLatestSuccessfulBuildRecord(dependencyBuildConfiguration.getId(), temporaryBuild); if (dependencyLatestSuccessfulBuildRecord == null) { return true; } boolean newer = dependencyLatestSuccessfulBuildRecord.getEndTime().after(latestSuccessfulBuildRecord.getEndTime()); if (newer) { return true; } } return false; }private boolean hasARebuiltImplicitDependency(BuildRecord latestSuccessfulBuildRecord, boolean temporaryBuild) { Collection lastBuiltFrom = getRecordsUsedFor(latestSuccessfulBuildRecord); return lastBuiltFrom.stream() .anyMatch(br -> hasNewerVersion(br, temporaryBuild)); }@Override public Set getBuildConfigurations(BuildConfigurationSet buildConfigurationSet) { return new HashSet<>(buildConfigurationRepository.queryWithPredicates(withBuildConfigurationSetId(buildConfigurationSet.getId()))); }@Override @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public BuildConfigSetRecord saveBuildConfigSetRecord(BuildConfigSetRecord buildConfigSetRecord) { return buildConfigSetRecordRepository.save(buildConfigSetRecord); }private Set saveArtifacts(Collection artifacts, Map repositoriesCache, Map artifactCache) { logger.debug("Saving {} artifacts.", artifacts.size()); Set savedArtifacts = new HashSet<>(); Set artifactConstraints = new HashSet<>(); for (Artifact artifact : artifacts) { artifactConstraints.add(new Artifact.IdentifierSha256(artifact.getIdentifier(), artifact.getSha256())); } Set artifactsInDb = null; if (artifactConstraints.size() > 0) { artifactsInDb = artifactRepository.withIdentifierAndSha256s(artifactConstraints); } if (artifactsInDb != null) { for (Artifact artifact : artifactsInDb) { logger.trace("Found in DB, adding to cache. Artifact {}", artifact); artifactCache.put(artifact.getIdentifierSha256(), artifact); } } for (Artifact artifact : artifacts) { TargetRepository targetRepository = artifact.getTargetRepository(); linkTargetRepository(repositoriesCache, artifact, targetRepository); Artifact artifactFromDb; if (RepositoryType.GENERIC_PROXY.equals(targetRepository.getRepositoryType())) { artifactFromDb = saveHttpArtifact(artifact); } else { artifactFromDb = getOrSaveRepositoryArtifact(artifact, artifactCache); } savedArtifacts.add(artifactFromDb); } logger.debug("Artifacts saved: {}.", artifacts); return savedArtifacts; }boolean isJenkinsServerSecuredWithCSRF(String url) throws BuildDriverException { try { JenkinsBuildDriverModuleConfig config = configuration .getModuleConfig(new PncConfigProvider(JenkinsBuildDriverModuleConfig.class)); String username = config.getUsername(); String password = config.getPassword(); if (url == null || username == null || password == null) { throw new BuildDriverException("Missing config to instantiate " + JenkinsBuildDriver.DRIVER_ID + "."); } try { JenkinsHttpClient jenkinsHttpClient = new JenkinsHttpClient(new URI(url), username, password); try { jenkinsHttpClient.get("/crumbIssuer/api/xml"); return true ; } catch (IOException e) { return false; } } catch (URISyntaxException e) { throw new BuildDriverException("Cannot instantiate " + JenkinsBuildDriver.DRIVER_ID + ". Make sure you are using valid url: " + url, e); } } catch (ConfigurationParseException e) { throw new BuildDriverException("Cannot read configuration for " + JenkinsBuildDriver.DRIVER_ID + ".", e); } }public static Predicate withBuildConfigurationId(Integer buildConfigurationId) { return (root, query, cb) -> { SetJoin buildConfigurationJoin = root.join(ProductVersion_.buildConfigurations); return cb.equal(buildConfigurationJoin.get(BuildConfiguration_.id), buildConfigurationId); }; }private BuildRecord.Builder initBuildRecordBuilder(BuildTask buildTask) { BuildOptions buildOptions = buildTask.getBuildOptions(); BuildRecord.Builder builder = BuildRecord.Builder.newBuilder() .id(buildTask.getId()) .buildConfigurationAudited(buildTask.getBuildConfigurationAudited()) .user(buildTask.getUser()) .submitTime(buildTask.getSubmitTime()) .startTime(buildTask.getStartTime()) .productMilestone(buildTask.getProductMilestone()) .temporaryBuild(buildOptions.isTemporaryBuild()); if (buildTask.getEndTime() == null) { buildTask.setEndTime(Date.from(Instant.now())); } builder.endTime(buildTask.getEndTime()); if (buildTask.getBuildConfigSetRecordId() != null) { BuildConfigSetRecord buildConfigSetRecord = datastore.getBuildConfigSetRecordById(buildTask.getBuildConfigSetRecordId()); builder.buildConfigSetRecord(buildConfigSetRecord); } List dependencies = buildTask.getDependencies().stream().map(t -> t.getId()).collect(Collectors.toList()); builder.dependencyBuildRecordIds(dependencies.toArray(new Integer[dependencies.size()])); List dependants = buildTask.getDependants().stream().map(t -> t.getId()).collect(Collectors.toList()); builder.dependentBuildRecordIds(dependants.toArray(new Integer[dependants.size()])); return builder; }public BuildRecord storeResult(BuildTask buildTask, Optional buildResult, Throwable e) throws DatastoreException { BuildRecord.Builder buildRecordBuilder = initBuildRecordBuilder(buildTask); buildRecordBuilder.status(SYSTEM_ERROR); StringBuilder errorLog = new StringBuilder(); buildResult.ifPresent(result -> { result.getRepourResult().ifPresent(repourResult -> { buildRecordBuilder.executionRootName(repourResult.getExecutionRootName()); buildRecordBuilder.executionRootVersion(repourResult.getExecutionRootVersion()); buildRecordBuilder.repourLog(repourResult.getLog()); }); result.getBuildDriverResult().ifPresent( buildDriverResult -> { errorLog.append(buildDriverResult.getBuildLog()); errorLog.append("\n---- End Build Log ----\n"); }); result.getRepositoryManagerResult().ifPresent( rmr -> { errorLog.append(rmr.getLog()); errorLog.append("\n---- End Repository Manager Log ----\n"); }); result.getEnvironmentDriverResult().ifPresent( r -> { if (r.getLog() != null && !r.getLog().equals("")) errorLog.append(r.getLog()); errorLog.append("\n---- End Environment Driver Log ----\n"); }); }); errorLog.append("Build status: ").append(getBuildStatus(buildResult)).append("\n"); errorLog.append("Caught exception: ").append(e.toString()).append("\n"); StringWriter stackTraceWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stackTraceWriter)); errorLog.append(stackTraceWriter.getBuffer()); buildRecordBuilder.buildLog(errorLog.toString()); userLog.error("Build status: {}.", getBuildStatus(buildResult)); log.debug("Storing ERROR result of buildTask.getBuildConfigurationAudited().getName() to datastore.", e); return datastore.storeCompletedBuild(buildRecordBuilder); }private void loadBuildConfigurations(BuildConfigurationAudited buildConfigAudited) { Project project = buildConfigAudited.getProject(); project.getBuildConfigurations().forEach(BuildConfiguration::getId); }public static Predicate isNotArchived() { return (root, query, cb) -> cb.isTrue(root.get(BuildConfiguration_.active)); }public EnvironmentDriver getDriver(SystemImageType systemImageType) throws ExecutorException { for (EnvironmentDriver driver : availableDrivers) { if (driver.canRunImageType(systemImageType)) return driver; } throw new ExecutorException("No environment driver available for " + systemImageType + " system image type."); }private void checkForEmptyBuildSetTask(BuildSetTask buildSetTask) { if (buildSetTask.getBuildTasks() == null || buildSetTask.getBuildTasks().isEmpty()) { updateBuildSetTaskStatus(buildSetTask, BuildSetStatus.REJECTED, "Build config set is empty"); } }@Override public BuildSetTask build(BuildConfigurationAudited buildConfigurationAudited, User user, BuildOptions buildOptions) throws BuildConflictException { return build0(user, buildOptions, buildConfigurationAudited); }public Result deleteTemporaryBuildConfigSetRecord(Integer buildConfigSetRecordId, String authToken) throws ValidationException { BuildConfigSetRecord buildConfigSetRecord = buildConfigSetRecordRepository.queryById(buildConfigSetRecordId); if (!buildConfigSetRecord.isTemporaryBuild()) { throw new ValidationException("Only deletion of the temporary builds is allowed"); } log.info("Starting deletion of a temporary build record set " + buildConfigSetRecord); for (BuildRecord br : buildConfigSetRecord.getBuildRecords()) { Result result = deleteTemporaryBuild(br.getId(), authToken); if (!result.isSuccess()) { return result; } } buildConfigSetRecordRepository.delete(buildConfigSetRecord.getId()); log.info("Deletion of a temporary build record set {} finished successfully.", buildConfigSetRecord); return new Result(buildConfigSetRecordId.toString(), Result.Status.SUCCESS); }public Result deleteTemporaryBuild(Integer buildRecordId, String authToken) throws ValidationException { BuildRecord buildRecord = buildRecordRepository.findByIdFetchAllProperties(buildRecordId); if (!buildRecord.isTemporaryBuild()) { throw new ValidationException("Only deletion of the temporary builds is allowed"); } log.info("Starting deletion of a temporary build " + buildRecord + "; Built artifacts: " + buildRecord.getBuiltArtifacts() + "; Dependencies: " + buildRecord.getDependencies()); Result result = remoteBuildsCleaner.deleteRemoteBuilds(buildRecord, authToken); if (!result.isSuccess()) { log.error("Failed to delete remote temporary builds for BR.id:{}.", buildRecord.getId()); return new Result(buildRecordId.toString(), Result.Status.FAILED, "Failed to delete remote temporary builds."); } /** Delete relation between BuildRecord and Artifact */ Set artifactsToBeDeleted = new HashSet<>(); removeRelationBuildRecordArtifact(buildRecord, artifactsToBeDeleted); /** * Delete artifacts, if the artifacts are not used in other builds */ deleteArtifacts(artifactsToBeDeleted); deleteDependencies(buildRecord); buildRecordRepository.delete(buildRecord.getId()); log.info("Deletion of the temporary build {} finished successfully.", buildRecord); return new Result(buildRecordId.toString(), Result.Status.SUCCESS); }public static void setSslRequired(boolean sslRequired) { if (HttpUtil.sslRequired != sslRequired) { HttpUtil.sslRequired = sslRequired; HttpUtil.httpClient = null; } }public static Artifact mockImportedArtifact(int id) { return getArtifactBuilder(id) .importDate(Date.from(Instant.now())) .originUrl("http://central.maven.org/org/jboss/mock/artifactFile" + id + ".jar") .build(); }private void addWebsocketForwardingListeners(RepositoryCreationTask task) { Consumer doNotify = (e) -> wsNotifier.sendMessage(e); task.addListener(BpmEventType.RC_REPO_CREATION_SUCCESS, doNotify); task.addListener(BpmEventType.RC_REPO_CREATION_ERROR, doNotify); task.addListener(BpmEventType.RC_REPO_CLONE_SUCCESS, doNotify); task.addListener(BpmEventType.RC_REPO_CLONE_ERROR, doNotify); //clients are notified from callback in startRCreationTask //task.addListener(BpmEventType.RC_CREATION_SUCCESS, doNotify); task.addListener(BpmEventType.RC_CREATION_ERROR, doNotify); }private void onRCCreationSuccess(BpmNotificationRest notification, BuildConfigurationRest buildConfigurationRest) { LOG.debug("Received BPM event RC_CREATION_SUCCESS: " + notification); BpmStringMapNotificationRest repositoryCreationTaskResult = (BpmStringMapNotificationRest) notification; int repositoryConfigurationId = -1; int buildConfigurationSavedId = -1; try { repositoryConfigurationId = Integer.valueOf(repositoryCreationTaskResult.getData().get("repositoryConfigurationId")); } catch (NumberFormatException ex) { String errorMessage = "Receive notification about successful BC creation '" + repositoryCreationTaskResult + "' but the ID of the newly created RC '" + repositoryCreationTaskResult.getData() .get("repositoryConfigurationId") + "' is not a number. It should be present under 'repositoryConfigurationId' key."; LOG.error(errorMessage, ex); sendErrorMessage(repositoryConfigurationId, buildConfigurationSavedId, errorMessage); return; } RepositoryConfiguration repositoryConfiguration = repositoryConfigurationRepository.queryById(repositoryConfigurationId); if (repositoryConfiguration == null) { String errorMessage = "Repository Configuration was not found in database."; LOG.error(errorMessage); sendErrorMessage(repositoryConfigurationId, buildConfigurationSavedId, errorMessage); return; } if (buildConfigurationRest != null) { //TODO test me BuildConfiguration buildConfiguration = buildConfigurationRest.toDBEntityBuilder() .repositoryConfiguration(repositoryConfiguration) .build(); BuildConfiguration buildConfigurationSaved = buildConfigurationRepository.save(buildConfiguration); buildConfigurationSavedId = buildConfigurationSaved.getId(); Set bcSetIds = buildConfigurationRest.getBuildConfigurationSetIds(); try { if (bcSetIds != null) { addBuildConfigurationToSet(buildConfigurationSaved, bcSetIds); } } catch (Exception e) { LOG.error(e.getMessage()); sendErrorMessage(repositoryConfigurationId, buildConfigurationSavedId, e.getMessage()); return; } } RepositoryCreationResultRest repositoryCreationResultRest = new RepositoryCreationResultRest( repositoryConfigurationId, buildConfigurationSavedId, RepositoryCreationResultRest.EventType.RC_CREATION_SUCCESS, null); wsNotifier.sendMessage(repositoryCreationResultRest); //TODO test me! }private void setupBuildRepos(BuildExecution execution, String packageType, Indy indy, Map genericParameters) throws IndyClientException { String buildContentId = execution.getBuildContentId(); int id = execution.getId(); // if the build-level group doesn't exist, create it. StoreKey groupKey = new StoreKey(packageType, StoreType.group, buildContentId); if (!indy.stores().exists(groupKey)) { // if the product-level storage repo (for in-progress product builds) doesn't exist, create it. StoreKey hostedKey = new StoreKey(packageType, StoreType.hosted, buildContentId); boolean tempBuild = execution.isTempBuild(); if (!indy.stores().exists(hostedKey)) { HostedRepository buildArtifacts = new HostedRepository(packageType, buildContentId); buildArtifacts.setAllowSnapshots(tempBuild); buildArtifacts.setAllowReleases(true); buildArtifacts.setDescription(String.format("Build output for PNC %s build #%s", packageType, id)); indy.stores().create(buildArtifacts, "Creating hosted repository for " + packageType + " build: " + id + " (repo: " + buildContentId + ")", HostedRepository.class); } Group buildGroup = new Group(packageType, buildContentId); String adjective = tempBuild ? "temporary " : ""; buildGroup.setDescription(String.format("Aggregation group for PNC %sbuild #%s", adjective, id)); // build-local artifacts buildGroup.addConstituent(hostedKey); // Global-level repos, for captured/shared artifacts and access to the outside world addGlobalConstituents(packageType, buildGroup, tempBuild); // add extra repositories removed from poms by the adjust process and set in BC by user List extraDependencyRepositories = extractExtraRepositoriesFromGenericParameters(genericParameters); if (execution.getArtifactRepositories() != null) { extraDependencyRepositories.addAll(execution.getArtifactRepositories()); } addExtraConstituents(packageType, extraDependencyRepositories, id, buildContentId, indy, buildGroup); indy.stores().create(buildGroup, "Creating repository group for resolving artifacts in build: " + id + " (repo: " + buildContentId + ")", Group.class); } }@Schedule public void cleanupExpiredTemporaryBuilds() throws ValidationException { log.info("Regular cleanup of expired temporary builds started. Removing builds older than " + TEMPORARY_BUILD_LIFESPAN + " days."); Date expirationThreshold = TimeUtils.getDateXDaysAgo(TEMPORARY_BUILD_LIFESPAN); String authToken = serviceClient.getAuthToken(); deleteExpiredBuildConfigSetRecords(expirationThreshold, authToken); deleteExpiredBuildRecords(expirationThreshold, authToken); log.info("Regular cleanup of expired temporary builds finished."); }public static Collector, List, List> toFlatList() { return Collector.of( ArrayList::new, List::addAll, (left, right) -> { left.addAll(right); return left; }); }@Deprecated public Integer getTaskIdByBuildId(int buildId) { List result = tasks.values().stream() .filter(t -> t instanceof BpmBuildTask) .filter(t -> ((BpmBuildTask) t).getBuildTask().getId() == buildId) .map(BpmTask::getTaskId) .collect(Collectors.toList()); if (result.size() > 1) throw new IllegalStateException("More that one task with the same build id: " + result); return result.size() == 1 ? result.get(0) : null; }public void cleanup() { //TODO remove tasks immediately after the completion, see: BuildTaskEndpoint.buildTaskCompleted log.debug("Bpm manager tasks cleanup started"); if (session == null) { log.error("Kie session not available."); } Map clonedTaskMap = new HashMap<>(this.tasks); Set toBeRemoved = clonedTaskMap.values().stream() .filter(bpmTask -> { if (bpmTask == null) { log.warn("Listing invalid entry for removal from the tasks list."); return true; } log.debug("Attempting to fetch process instance for bpmTask: {}.", bpmTask.getTaskId()); Long processInstanceId = bpmTask.getProcessInstanceId(); ProcessInstance processInstance = session.getProcessInstance(processInstanceId); log.debug("fetched: {}", processInstance); if (processInstance == null) // instance has been terminated from outside return true; int state = processInstance.getState(); return state == STATE_COMPLETED || state == STATE_ABORTED; }) .map(BpmTask::getTaskId) .collect(Collectors.toSet()); toBeRemoved.forEach(id -> { BpmTask removed = tasks.remove(id); if (removed != null) { log.debug("Removed bpmTask.id: {}.", removed.getTaskId()); } else { log.warn("Unable to remove bpmTask.id: {}.", id); } }); log.debug("Bpm manager tasks cleanup finished"); }public void startRelease(ProductMilestone milestone, String accessToken) { ProductMilestoneRelease release = triggerRelease(milestone, accessToken); productMilestoneReleaseRepository.save(release); }public static String readStreamAsString(InputStream stream) throws IOException { try (Scanner sc = new Scanner(stream, Charset.defaultCharset().name())) { sc.useDelimiter("\\A"); return sc.next(); } }public static String readFileAsString(File fileName) throws IOException { try (Scanner sc = new Scanner(fileName, Charset.defaultCharset().name())) { sc.useDelimiter("\\A"); return sc.next(); } }public static void merge(Graph target, Graph toMerge) { for (Vertex vertex : toMerge.getVerticies()) { target.addVertex(vertex); } // merge edges List> edges = target.getEdges(); for (Edge newEdge : toMerge.getEdges()) { Optional> any = edges.stream() .filter(existing -> existing.getFrom().getName().equals(newEdge.getFrom().getName()) && existing.getTo().getName().equals(newEdge.getTo().getName()) ).findAny(); if (!any.isPresent()) { edges.add(newEdge); } } }@Override public void monitor(Consumer onComplete, Consumer onError) { try { StoreKey fromKey = new StoreKey(pakageType, fromType, fromId); if (!indy.stores().exists(fromKey)) { throw new RepositoryManagerException("No such %s repository: %s", fromType.singularEndpointName(), fromId); } StoreKey toKey = new StoreKey(pakageType, StoreType.group, toId); Group recordSetGroup = indy.stores().load(toKey, Group.class); if (recordSetGroup == null) { throw new RepositoryManagerException("No such group: %s", toId); } recordSetGroup.addConstituent(fromKey); boolean result = indy.stores().update(recordSetGroup, "Promoting " + fromType.singularEndpointName() + " repository : " + fromId + " to group: " + toId); onComplete.accept(new IndyCompletedPromotion(result)); } catch (IndyClientException | RepositoryManagerException e) { onError.accept(e); } }public BuildTask getBuildTask(BuildConfigurationAudited buildConfigurationAudited) { return buildTasks.stream().filter((bt) -> bt.getBuildConfigurationAudited().equals(buildConfigurationAudited)).findFirst().orElse(null); }public void taskStatusUpdatedToFinalState() { // If any of the build tasks have failed or all are complete, then the build set is done if(buildTasks.stream().anyMatch(bt -> bt.getStatus().equals(BuildCoordinationStatus.CANCELLED))) { log.debug("Marking build set as CANCELLED as one or more tasks were cancelled. BuildSetTask: {}", this); if (log.isDebugEnabled()) { logTasksStatus(buildTasks); } buildConfigSetRecord.ifPresent(r -> r.setStatus(BuildStatus.CANCELLED)); finishBuildSetTask(); } else if(buildTasks.stream().anyMatch(bt -> bt.getStatus().hasFailed())) { log.debug("Marking build set as FAILED as one or more tasks failed. BuildSetTask: {}", this); if (log.isDebugEnabled()) { logTasksStatus(buildTasks); } buildConfigSetRecord.ifPresent(r -> r.setStatus(BuildStatus.FAILED)); finishBuildSetTask(); } else if (buildTasks.stream().allMatch(bt -> bt.getStatus().isCompleted())) { log.debug("Marking build set as SUCCESS. BuildSetTask: {}", this); buildConfigSetRecord.ifPresent(r -> r.setStatus(BuildStatus.SUCCESS)); finishBuildSetTask(); } else { if (log.isTraceEnabled()) { List running = buildTasks.stream() .filter(bt -> !bt.getStatus().isCompleted()) .filter(bt -> !bt.getStatus().hasFailed()) .map(BuildTask::getId) .collect(Collectors.toList()); log.trace("There are still running or waiting builds [{}].", running); } } }@Override public void monitor(Consumer onComplete, Consumer onError) { try { StoreKey fromKey = new StoreKey(pakageType, fromType, fromId); if (indy.stores().exists(fromKey)) { indy.stores().delete(fromKey, "Deleting artifacts for PNC build"); } onComplete.accept(new IndyCompletedDeletion(true)); } catch (IndyClientException e) { onError.accept(e); } }public T parseJSONPNCConfig( String configContent, ConfigProvider provider) throws ConfigurationParseException { try { ObjectMapper mapper = new ObjectMapper(); provider.registerProvider(mapper); PNCModuleGroup pncGroup = getModuleGroup(mapper, configContent, PNCModuleGroup.class); for (AbstractModuleConfig config : pncGroup.getConfigs()) { if (config.getClass().isAssignableFrom(provider.getType())) { return (T) config; } } throw new ConfigurationParseException("Did not find config for provider " + provider.getType().getSimpleName() + "."); } catch (IOException | RuntimeException e) { log.error(e.getMessage()); throw new ConfigurationParseException("Config could not be parsed", e); } }public boolean hasDirectConfigDependencyOn(BuildTask buildTask) { if (buildTask == null || this.equals(buildTask)) { return false; } BuildConfiguration buildConfiguration = buildConfigurationAudited.getBuildConfiguration(); if (buildConfiguration == null || buildConfiguration.getDependencies() == null) { return false; } return buildConfiguration.getDependencies().contains(buildTask.getBuildConfigurationAudited().getBuildConfiguration()); }public boolean hasConfigDependencyOn(BuildTask buildTask) { if (buildTask == null || this.equals(buildTask)) { return false; } BuildConfiguration buildConfiguration = buildConfigurationAudited.getBuildConfiguration(); if (buildConfiguration == null || buildConfiguration.getAllDependencies() == null) { return false; } return buildConfiguration.dependsOn(buildTask.getBuildConfigurationAudited().getBuildConfiguration()); }private Artifact validateArtifact(Artifact artifact) throws RepositoryManagerException { Set> violations = validator.validate(artifact); if (!violations.isEmpty()) { throw new RepositoryManagerException("Repository manager returned invalid artifact: " + artifact.toString() + " Constraint Violations: %s", violations); } return artifact; }private String computeGenericIdentifier(String originUrl, String localUrl, String sha256) { String identifier = originUrl; if (identifier == null) { // this is from/to a hosted repository, either the build repo or something like that. identifier = localUrl; } identifier += '|' + sha256; return identifier; }private String computeIdentifier(final TrackedContentEntryDTO transfer) { String identifier = null; switch (transfer.getStoreKey().getPackageType()) { case MAVEN_PKG_KEY: ArtifactPathInfo pathInfo = ArtifactPathInfo.parse(transfer.getPath()); if (pathInfo != null) { ArtifactRef aref = new SimpleArtifactRef(pathInfo.getProjectId(), pathInfo.getType(), pathInfo.getClassifier()); identifier = aref.toString(); } break; case NPM_PKG_KEY: NpmPackagePathInfo npmPathInfo = NpmPackagePathInfo.parse(transfer.getPath()); if (npmPathInfo != null) { NpmPackageRef packageRef = new NpmPackageRef(npmPathInfo.getName(), npmPathInfo.getVersion()); identifier = packageRef.toString(); } break; case GENERIC_PKG_KEY: // handle generic downloads along with other invalid download paths for other package types break; default: // do not do anything by default logger.warn("Package type {} is not handled by Indy repository session.", transfer.getStoreKey().getPackageType()); break; } if (identifier == null) { identifier = computeGenericIdentifier(transfer.getOriginUrl(), transfer.getLocalUrl(), transfer.getSha256()); } return identifier; }private List processUploads(TrackedContentDTO report) throws RepositoryManagerException { Logger logger = LoggerFactory.getLogger(getClass()); Set uploads = report.getUploads(); if (uploads != null) { List builds = new ArrayList<>(); for (TrackedContentEntryDTO upload : uploads) { String path = upload.getPath(); StoreKey storeKey = upload.getStoreKey(); if (ignoreContent(storeKey.getPackageType(), path)) { logger.debug("Ignoring upload (matched in ignored-suffixes): {} (From: {})", path, storeKey); continue; } String identifier = computeIdentifier(upload); logger.info("Recording upload: {}", identifier); IndyContentClientModule content; try { content = indy.content(); } catch (IndyClientException e) { throw new RepositoryManagerException("Failed to retrieve Indy content module. Reason: %s", e, e.getMessage()); } RepositoryType repoType = toRepoType(storeKey.getPackageType()); TargetRepository targetRepository = getUploadsTargetRepository(repoType, content); ArtifactQuality artifactQuality = getArtifactQuality(isTempBuild); Artifact.Builder artifactBuilder = Artifact.Builder.newBuilder() .md5(upload.getMd5()) .sha1(upload.getSha1()) .sha256(upload.getSha256()) .size(upload.getSize()) .deployPath(upload.getPath()) .filename(new File(path).getName()) .identifier(identifier) .targetRepository(targetRepository) .artifactQuality(artifactQuality); Artifact artifact = validateArtifact(artifactBuilder.build()); builds.add(artifact); } return builds; } return Collections.emptyList(); }@Override public RepositoryManagerResult extractBuildArtifacts() throws RepositoryManagerException { TrackedContentDTO report; try { IndyFoloAdminClientModule foloAdmin = indy.module(IndyFoloAdminClientModule.class); boolean sealed = foloAdmin.sealTrackingRecord(buildContentId); if (!sealed) { throw new RepositoryManagerException("Failed to seal content-tracking record for: %s.", buildContentId); } report = foloAdmin.getTrackingReport(buildContentId); } catch (IndyClientException e) { throw new RepositoryManagerException("Failed to retrieve tracking report for: %s. Reason: %s", e, buildContentId, e.getMessage()); } if (report == null) { throw new RepositoryManagerException("Failed to retrieve tracking report for: %s.", buildContentId); } Comparator comp = (one, two) -> one.getIdentifier().compareTo(two.getIdentifier()); List uploads = processUploads(report); Collections.sort(uploads, comp); List downloads = processDownloads(report); Collections.sort(downloads, comp); try { StoreKey key = new StoreKey(packageType, StoreType.group, buildContentId); serviceAccountIndy.stores().delete(key, "[Post-Build] Removing build aggregation group: " + buildContentId); } catch (IndyClientException e) { throw new RepositoryManagerException("Failed to retrieve Indy stores module. Reason: %s", e, e.getMessage()); } Logger logger = LoggerFactory.getLogger(getClass()); logger.info("Returning built artifacts / dependencies:\nUploads:\n {}\n\nDownloads:\n {}\n\n", StringUtils.join(uploads, "\n "), StringUtils.join(downloads, "\n ")); String log = ""; CompletionStatus status = CompletionStatus.SUCCESS; try { promoteToBuildContentSet(uploads); } catch (RepositoryManagerException rme) { status = CompletionStatus.FAILED; log = rme.getMessage(); logger.error("Promotion validation error(s): \n" + log); userLog.error("Artifact promotion failed. Promotion validation error(s): {}", log); // prevent saving artifacts and dependencies to a failed build downloads = Collections.emptyList(); uploads = Collections.emptyList(); } return new IndyRepositoryManagerResult(uploads, downloads, buildContentId, log, status); }protected static Result parseResponse(String response) throws SonarBreakException { ObjectMapper mapper = new ObjectMapper(); final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); mapper.setDateFormat(df); List results; try { results = mapper.readValue(response, new TypeReference>() { }); } catch (IOException e) { throw new SonarBreakException("Unable to parse the json into a List of QualityGateResults. Json is: " + response, e); } if (results == null || results.size() != 1) { throw new SonarBreakException("Unable to deserialize JSON response: " + response); } return results.get(0); }private Result fetchSonarStatus(URL queryURL) throws IOException, SonarBreakException { InputStream in = null; try { URLConnection connection = queryURL.openConnection(); connection.setRequestProperty("Accept", "application/json"); in = connection.getInputStream(); String response = IOUtils.toString(in); return parseResponse(response); } finally { IOUtils.closeQuietly(in); } }private Result fetchSonarStatusWithRetries(URL queryURL, String version) throws IOException, SonarBreakException { DateTime oneMinuteAgo = DateTime.now().minusSeconds(sonarLookBackSeconds); DateTime waitUntil = DateTime.now().plusSeconds(waitForProcessingSeconds); do { // If this is the first time the job is running on sonar the URL might not be available. Return null and wait. if (isURLAvailable(queryURL, 1)) { Result result = fetchSonarStatus(queryURL); if (result.getVersion().equals(version) && result.getDatetime().isAfter(oneMinuteAgo)) { log.debug("Found a sonar job run that matches version and in the correct time frame"); return result; } String message = String.format("Sleeping while waiting for sonar to process job. Target Version: %s. " + "Sonar reporting Version: %s. Looking back until: %s Last result time: %s", version, result.getVersion(), oneMinuteAgo.toString(), result.getDatetime().toString()); log.debug(message); } else { log.debug(String.format("Query url not available yet: %s", queryURL)); } try { Thread.sleep(SONAR_PROCESSING_WAIT_TIME); } catch (InterruptedException e) { // Do nothing } } while (!waitUntil.isBeforeNow()); String message = String.format("Timed out while waiting for Sonar. Waited %d seconds. This time can be extended " + "using the \"waitForProcessingSeconds\" configuration parameter.", waitForProcessingSeconds); throw new SonarBreakException(message); }protected static URL buildURL(URL sonarURL, Query query) throws MalformedURLException, IllegalArgumentException { if (query.getSonarKey() == null || query.getSonarKey().length() == 0) { throw new IllegalArgumentException("No resource specified in the Query"); } String sonarPathWithResource = String.format(SONAR_FORMAT_PATH, query.getSonarKey()); return new URL(sonarURL, sonarPathWithResource); }public Result execute(Query query) throws SonarBreakException, IOException { URL queryURL = buildURL(sonarURL, query); log.debug("Built a sonar query url of: " + queryURL.toString()); if (!isURLAvailable(sonarURL, SONAR_CONNECTION_RETRIES)) { throw new SonarBreakException(String.format("Unable to get a valid response after %d tries", SONAR_CONNECTION_RETRIES)); } return fetchSonarStatusWithRetries(queryURL, query.getVersion()); }private String getText(JsonNode node, String propertyName) { JsonNode childNode = node.get(propertyName); if (childNode == null) { return null; } return childNode.asText(); }public Flowable observeSensor(int sensorType, final int samplingPeriodInUs, final Handler handler, final BackpressureStrategy strategy) { if (!hasSensor(sensorType)) { String format = "Sensor with id = %d is not available on this device"; String message = String.format(Locale.getDefault(), format, sensorType); return Flowable.error(new SensorNotFoundException(message)); } final Sensor sensor = sensorManager.getDefaultSensor(sensorType); final SensorEventListenerWrapper wrapper = new SensorEventListenerWrapper(); final SensorEventListener listener = wrapper.create(); return Flowable.create(new FlowableOnSubscribe() { @Override public void subscribe(final FlowableEmitter emitter) throws Exception { wrapper.setEmitter(emitter); if (handler == null) { sensorManager.registerListener(listener, sensor, samplingPeriodInUs); } else { sensorManager.registerListener(listener, sensor, samplingPeriodInUs, handler); } } }, strategy).doOnCancel(new Action() { @Override public void run() throws Exception { sensorManager.unregisterListener(listener); } }); }private void flushLeftOver(CharBuffer input) throws IOException { if (!_hasLeftOver) { return; } for (;;) { if (input != null && input.hasRemaining()) { _leftOverBuffer.put(input.get()); } _leftOverBuffer.flip(); CoderResult cr = _encoder.encode(_leftOverBuffer, _buffer, input == null); if (cr.isUnderflow()) { if (_leftOverBuffer.hasRemaining()) { _leftOverBuffer.compact(); } else { break; } } if (cr.isOverflow()) { flushBufferToWriter(); } } _hasLeftOver = false; _leftOverBuffer.clear(); }private void flushBufferToWriter() throws IOException { _out.write(_buffer.array(), 0, _buffer.position()); _buffer.clear(); }public String encode(String str) { if (str == null) { str = "null"; } int n = str.length(); int j = _first.firstEncodedOffset(str, 0, n); if (j == n) { // string is unchanged after encoding with the first encoder return Encode.encode(_last, str); } final int remaining = n - j; final int m = j + _first.maxEncodedLength(n); CharBuffer input = CharBuffer.allocate(m); str.getChars(0, j, input.array(), 0); str.getChars(j, n, input.array(), m - remaining); input.limit(m).position(m - remaining); CharBuffer tmp = input.duplicate(); tmp.position(j); CoderResult cr = _first.encode(input, tmp, true); assert cr.isUnderflow() : "maxEncodedLength was incorrect"; CharBuffer output = CharBuffer.allocate(_last.maxEncodedLength(tmp.position())); tmp.flip(); cr = _last.encode(tmp, output, true); assert cr.isUnderflow() : "maxEncodedLength was incorrect"; return new String(output.array(), 0, output.position()); }static int append(char[] src, char[] out, int j) { System.arraycopy(src, 0, out, j, src.length); return j + src.length; }public static Encoder forName(String contextName) throws NullPointerException, UnsupportedContextException { if (contextName == null) { throw new NullPointerException(); } Encoder encoder = ENCODERS_MAP.get(contextName); if (encoder == null) { throw new UnsupportedContextException(contextName); } return encoder; }private static T map(String name, T encoder) { Encoder old = ENCODERS_MAP.put(name, encoder); assert old == null; return encoder; }static void encode(Encoder encoder, Writer out, String str) throws IOException { if (str == null) { // consistent with String.valueOf(...) use "null" for null. str = "null"; } // quick pass--see if we need to actually encode anything, if not // return the value unchanged. final int n = str.length(); int j = encoder.firstEncodedOffset(str, 0, n); if (j == n) { out.write(str); return; } // otherwise, we need to encode. We use a buffer to avoid // excessive memory allocation for these calls. Note: this means that // an encoder implementation must NEVER call this method internally. new Buffer().encode(encoder, out, str, j); }static String encode(Encoder encoder, String str) { if (str == null) { // consistent with String.valueOf(...) use "null" for null. str = "null"; } // quick pass--see if we need to actually encode anything, if not // return the value unchanged. final int n = str.length(); int j = encoder.firstEncodedOffset(str, 0, n); if (j == n) { return str; } // otherwise, we need to encode. We use a buffer to avoid // excessive memory allocation for these calls. Note: this means that // an encoder implementation must NEVER call this method internally. return new Buffer().encode(encoder, str, j); }ASCIIBits set(int min, int max) { // There are faster bit-twiddling tricks to accomplish the same // thing as below. Minor optimization for later. int i=min; for (int n = Math.min(max,63) ; i<=n ; ++i) { _lowerMask |= (1L << i); } for ( ; i<=max ; ++i) { _upperMask |= (1L << i); } return this; }static CoderResult underflow(CharBuffer input, int i, CharBuffer output, int j) { input.position(i - input.arrayOffset()); output.position(j - output.arrayOffset()); return CoderResult.UNDERFLOW; }static CoderResult overflow(CharBuffer input, int i, CharBuffer output, int j) { input.position(i - input.arrayOffset()); output.position(j - output.arrayOffset()); return CoderResult.OVERFLOW; }public boolean viewRestrict(final List roles, final DeadboltHandler handler, final Optional content, final long timeoutInMillis, final Http.RequestHeader requestHeader) throws Throwable { boolean allowed; try { allowed = constraintLogic.restrict(requestHeader, handler(handler), content, () -> roles, rh -> CompletableFuture.completedFuture(Boolean.TRUE), (rh, dh, cnt) -> CompletableFuture.completedFuture(Boolean.FALSE), ConstraintPoint.TEMPLATE) .toCompletableFuture() .get(timeoutInMillis, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { allowed = timeoutHandler.apply(timeoutInMillis, e); } return allowed; }public static List allOfGroup(final String... args) { return Collections.singletonList(args == null ? new String[0] : args); }public static String[] permissions(final Permission... permissions) { final List values = new ArrayList<>(permissions.length); for (Permission permission : permissions) { values.add(permission.getValue()); } return values.toArray(new String[values.size()]); }public static String[] roles(final Role... roles) { final List names = new ArrayList<>(roles.length); for (Role role : roles) { names.add(role.getName()); } return names.toArray(new String[names.size()]); }public FilterFunction subjectPresent(final Optional content) { return (Http.RequestHeader requestHeader, DeadboltHandler handler, Function> next) -> beforeAuthCheckCache.apply(handler, requestHeader, content) .thenCompose(maybePreAuth -> maybePreAuth._1.map(preAuthResult -> (CompletionStage) CompletableFuture.completedFuture(preAuthResult)) .orElseGet(() -> constraintLogic.subjectPresent(maybePreAuth._2, handler, content, (rh, hdlr, cntent) -> next.apply(rh), (rh, hdlr, cntent) -> hdlr.onAuthFailure(rh, cntent), ConstraintPoint.FILTER))); }public boolean hasRole(final Optional subjectOption, final String roleName) { return getRoleNames(subjectOption).contains(roleName); }public List getRoleNames(final Optional subjectOption) { final List roleNames = new ArrayList<>(); subjectOption.ifPresent(subject -> { final List roles = subject.getRoles(); if (roles != null) { roleNames.addAll(roles.stream() .filter(Objects::nonNull) .map(Role::getName) .collect(Collectors.toList())); } }); return roleNames; }private static boolean deadboltActionLeftInActionChain(final Action action) { if(action != null) { if(action.delegate instanceof AbstractDeadboltAction) { return true; // yes, there is at least one deadbolt action remaining } // action.delegate wasn't a deadbolt action, let's check the next one in the chain return deadboltActionLeftInActionChain(action.delegate); } return false; }protected CompletionStage authorizeAndExecute(final Http.RequestHeader request) { if(constraintAnnotationMode != ConstraintAnnotationMode.AND) { // In AND mode we don't mark an action as authorised because we want ALL (remaining) constraints to be evaluated as well! return delegate.call((Http.Request)markAsAuthorised(request)); } return delegate.call((Http.Request)request); }@SuppressWarnings("unchecked") public F.Tuple, Http.RequestHeader> getDeferredAction(final Http.RequestHeader request) { return request.attrs().getOptional(ACTION_DEFERRED).map(action -> { action.delegate = this; return F., Http.RequestHeader>Tuple(action, request.removeAttr(ACTION_DEFERRED).addAttr(IGNORE_DEFERRED_FLAG, true)); }).orElseGet(() -> F.Tuple(null, request)); }protected Http.RequestHeader defer(final Http.RequestHeader request, final AbstractDeadboltAction action) { if (action != null) { LOGGER.info("Deferring action [{}]", this.getClass().getName()); return request.addAttr(ACTION_DEFERRED, action); } return request; }protected static boolean isAuthorised(final Http.RequestHeader request) { return request.attrs().getOptional(ACTION_AUTHORISED).orElse(false); }private Http.RequestHeader markAsAuthorised(final Http.RequestHeader request) { this.authorised = true; return request.addAttr(ACTION_AUTHORISED, true); } �@Nonnull @ReturnsMutableCopy public static MapBasedNamespaceContext createNamespaceMapping (@Nonnull final PSSchema aSchema) { final MapBasedNamespaceContext ret = new MapBasedNamespaceContext (); ret.addDefaultNamespaceURI (CSchematron.NAMESPACE_SCHEMATRON); for (final PSNS aItem : aSchema.getAllNSs ()) ret.addMapping (aItem.getPrefix (), aItem.getUri ()); return ret; }@Nonnull public PSValueOf readValueOfFromXML (@Nonnull final IMicroElement eValueOf) { final PSValueOf ret = new PSValueOf (); eValueOf.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_SELECT)) ret.setSelect (sAttrValue); else ret.addForeignAttribute (sAttrName, sAttrValue); }); eValueOf.forAllChildElements (eValueOfChild -> { if (CSchematron.NAMESPACE_SCHEMATRON.equals (eValueOfChild.getNamespaceURI ())) { _warn (ret, "Unsupported Schematron element '" + eValueOfChild.getLocalName () + "'"); } else _warn (ret, "Unsupported namespace URI '" + eValueOfChild.getNamespaceURI () + "'"); }); return ret; }@Nonnull public PSTitle readTitleFromXML (@Nonnull final IMicroElement eTitle) { final PSTitle ret = new PSTitle (); eTitle.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); _warn (ret, "Unsupported attribute '" + sAttrName + "'='" + sAttrValue + "'"); }); eTitle.forAllChildren (aTitleChild -> { switch (aTitleChild.getType ()) { case TEXT: ret.addText (((IMicroText) aTitleChild).getNodeValue ()); break; case ELEMENT: final IMicroElement eElement = (IMicroElement) aTitleChild; if (CSchematron.NAMESPACE_SCHEMATRON.equals (eElement.getNamespaceURI ())) { final String sLocalName = eElement.getLocalName (); if (sLocalName.equals (CSchematronXML.ELEMENT_DIR)) ret.addDir (readDirFromXML (eElement)); else _warn (ret, "Unsupported Schematron element '" + sLocalName + "'"); } else _warn (ret, "Unsupported namespace URI '" + eElement.getNamespaceURI () + "'"); break; case COMMENT: // Ignore comments break; default: _warn (ret, "Unsupported child node: " + aTitleChild); } }); return ret; }@Nonnull public PSSpan readSpanFromXML (@Nonnull final IMicroElement eSpan) { final PSSpan ret = new PSSpan (); eSpan.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_CLASS)) ret.setClazz (sAttrValue); else ret.addForeignAttribute (sAttrName, sAttrValue); }); eSpan.forAllChildren (aSpanChild -> { switch (aSpanChild.getType ()) { case TEXT: ret.addText (((IMicroText) aSpanChild).getNodeValue ()); break; case ELEMENT: final IMicroElement eElement = (IMicroElement) aSpanChild; if (CSchematron.NAMESPACE_SCHEMATRON.equals (eElement.getNamespaceURI ())) { _warn (ret, "Unsupported Schematron element '" + eElement.getLocalName () + "'"); } else ret.addForeignElement (eElement.getClone ()); break; case COMMENT: // Ignore comments break; default: _warn (ret, "Unsupported child node: " + aSpanChild); } }); return ret; }@Nonnull public PSSchema readSchemaFromXML (@Nonnull final IMicroElement eSchema) throws SchematronReadException { ValueEnforcer.notNull (eSchema, "Schema"); if (!CSchematron.NAMESPACE_SCHEMATRON.equals (eSchema.getNamespaceURI ())) throw new SchematronReadException (m_aResource, "The passed element is not an ISO Schematron element!"); final PSSchema ret = new PSSchema (m_aResource); final PSRichGroup aRichGroup = new PSRichGroup (); eSchema.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_ID)) ret.setID (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_SCHEMA_VERSION)) ret.setSchemaVersion (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_DEFAULT_PHASE)) ret.setDefaultPhase (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_QUERY_BINDING)) ret.setQueryBinding (sAttrValue); else if (PSRichGroup.isRichAttribute (sAttrName)) _handleRichGroup (sAttrName, sAttrValue, aRichGroup); else ret.addForeignAttribute (sAttrName, sAttrValue); }); ret.setRich (aRichGroup); eSchema.forAllChildElements (eSchemaChild -> { if (CSchematron.NAMESPACE_SCHEMATRON.equals (eSchemaChild.getNamespaceURI ())) { if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_INCLUDE)) ret.addInclude (readIncludeFromXML (eSchemaChild)); else if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_TITLE)) ret.setTitle (readTitleFromXML (eSchemaChild)); else if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_NS)) ret.addNS (readNSFromXML (eSchemaChild)); else if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_P)) { final PSP aP = readPFromXML (eSchemaChild); if (ret.hasNoPatterns ()) ret.addStartP (aP); else ret.addEndP (aP); } else if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_LET)) ret.addLet (readLetFromXML (eSchemaChild)); else if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_PHASE)) ret.addPhase (readPhaseFromXML (eSchemaChild)); else if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_PATTERN)) ret.addPattern (readPatternFromXML (eSchemaChild)); else if (eSchemaChild.getLocalName ().equals (CSchematronXML.ELEMENT_DIAGNOSTICS)) ret.setDiagnostics (readDiagnosticsFromXML (eSchemaChild)); else _warn (ret, "Unsupported Schematron element '" + eSchemaChild.getLocalName () + "'"); } else ret.addForeignElement (eSchemaChild.getClone ()); }); return ret; }@Nonnull public PSRule readRuleFromXML (@Nonnull final IMicroElement eRule) { final PSRule ret = new PSRule (); final PSRichGroup aRichGroup = new PSRichGroup (); final PSLinkableGroup aLinkableGroup = new PSLinkableGroup (); eRule.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_FLAG)) ret.setFlag (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_ABSTRACT)) ret.setAbstract (StringParser.parseBool (sAttrValue)); else if (sAttrName.equals (CSchematronXML.ATTR_CONTEXT)) ret.setContext (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_ID)) ret.setID (sAttrValue); else if (PSRichGroup.isRichAttribute (sAttrName)) _handleRichGroup (sAttrName, sAttrValue, aRichGroup); else if (PSLinkableGroup.isLinkableAttribute (sAttrName)) _handleLinkableGroup (sAttrName, sAttrValue, aLinkableGroup); else ret.addForeignAttribute (sAttrName, sAttrValue); }); ret.setRich (aRichGroup); ret.setLinkable (aLinkableGroup); eRule.forAllChildElements (eRuleChild -> { if (CSchematron.NAMESPACE_SCHEMATRON.equals (eRuleChild.getNamespaceURI ())) { final String sLocalName = eRuleChild.getLocalName (); if (sLocalName.equals (CSchematronXML.ELEMENT_INCLUDE)) ret.addInclude (readIncludeFromXML (eRuleChild)); else if (sLocalName.equals (CSchematronXML.ELEMENT_LET)) ret.addLet (readLetFromXML (eRuleChild)); else if (sLocalName.equals (CSchematronXML.ELEMENT_ASSERT) || sLocalName.equals (CSchematronXML.ELEMENT_REPORT)) ret.addAssertReport (readAssertReportFromXML (eRuleChild)); else if (sLocalName.equals (CSchematronXML.ELEMENT_EXTENDS)) ret.addExtends (readExtendsFromXML (eRuleChild)); else _warn (ret, "Unsupported Schematron element '" + sLocalName + "'"); } else ret.addForeignElement (eRuleChild.getClone ()); }); return ret; }@Nonnull public PSPhase readPhaseFromXML (@Nonnull final IMicroElement ePhase) { final PSPhase ret = new PSPhase (); final PSRichGroup aRichGroup = new PSRichGroup (); ePhase.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_ID)) ret.setID (sAttrValue); else if (PSRichGroup.isRichAttribute (sAttrName)) _handleRichGroup (sAttrName, sAttrValue, aRichGroup); else ret.addForeignAttribute (sAttrName, sAttrValue); }); ret.setRich (aRichGroup); ePhase.forAllChildElements (ePhaseChild -> { if (CSchematron.NAMESPACE_SCHEMATRON.equals (ePhaseChild.getNamespaceURI ())) { if (ePhaseChild.getLocalName ().equals (CSchematronXML.ELEMENT_INCLUDE)) ret.addInclude (readIncludeFromXML (ePhaseChild)); else if (ePhaseChild.getLocalName ().equals (CSchematronXML.ELEMENT_P)) ret.addP (readPFromXML (ePhaseChild)); else if (ePhaseChild.getLocalName ().equals (CSchematronXML.ELEMENT_LET)) ret.addLet (readLetFromXML (ePhaseChild)); else if (ePhaseChild.getLocalName ().equals (CSchematronXML.ELEMENT_ACTIVE)) ret.addActive (readActiveFromXML (ePhaseChild)); else _warn (ret, "Unsupported Schematron element '" + ePhaseChild.getLocalName () + "'"); } else ret.addForeignElement (ePhaseChild.getClone ()); }); return ret; }@Nonnull public PSPattern readPatternFromXML (@Nonnull final IMicroElement ePattern) { final PSPattern ret = new PSPattern (); final PSRichGroup aRichGroup = new PSRichGroup (); ePattern.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_ABSTRACT)) ret.setAbstract (StringParser.parseBool (sAttrValue)); else if (sAttrName.equals (CSchematronXML.ATTR_ID)) ret.setID (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_IS_A)) ret.setIsA (sAttrValue); else if (PSRichGroup.isRichAttribute (sAttrName)) _handleRichGroup (sAttrName, sAttrValue, aRichGroup); else ret.addForeignAttribute (sAttrName, sAttrValue); }); ret.setRich (aRichGroup); ePattern.forAllChildElements (ePatternChild -> { if (CSchematron.NAMESPACE_SCHEMATRON.equals (ePatternChild.getNamespaceURI ())) { if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_INCLUDE)) ret.addInclude (readIncludeFromXML (ePatternChild)); else if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_TITLE)) ret.setTitle (readTitleFromXML (ePatternChild)); else if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_P)) ret.addP (readPFromXML (ePatternChild)); else if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_LET)) ret.addLet (readLetFromXML (ePatternChild)); else if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_RULE)) ret.addRule (readRuleFromXML (ePatternChild)); else if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_PARAM)) ret.addParam (readParamFromXML (ePatternChild)); else _warn (ret, "Unsupported Schematron element '" + ePatternChild.getLocalName () + "' in " + ret.toString ()); } else ret.addForeignElement (ePatternChild.getClone ()); }); return ret; }@Nonnull public PSParam readParamFromXML (@Nonnull final IMicroElement eParam) { final PSParam ret = new PSParam (); eParam.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_NAME)) ret.setName (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_VALUE)) ret.setValue (sAttrValue); else _warn (ret, "Unsupported attribute '" + sAttrName + "'='" + sAttrValue + "'"); }); eParam.forAllChildElements (eParamChild -> { if (CSchematron.NAMESPACE_SCHEMATRON.equals (eParamChild.getNamespaceURI ())) { _warn (ret, "Unsupported Schematron element '" + eParamChild.getLocalName () + "'"); } else _warn (ret, "Unsupported namespace URI '" + eParamChild.getNamespaceURI () + "'"); }); return ret; }@Nonnull public PSP readPFromXML (@Nonnull final IMicroElement eP) { final PSP ret = new PSP (); eP.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_ID)) ret.setID (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_CLASS)) ret.setClazz (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_ICON)) ret.setIcon (sAttrValue); else ret.addForeignAttribute (sAttrName, sAttrValue); }); eP.forAllChildren (aChild -> { switch (aChild.getType ()) { case TEXT: ret.addText (((IMicroText) aChild).getNodeValue ()); break; case ELEMENT: final IMicroElement eElement = (IMicroElement) aChild; if (CSchematron.NAMESPACE_SCHEMATRON.equals (eElement.getNamespaceURI ())) { final String sLocalName = eElement.getLocalName (); if (sLocalName.equals (CSchematronXML.ELEMENT_DIR)) ret.addDir (readDirFromXML (eElement)); else if (sLocalName.equals (CSchematronXML.ELEMENT_EMPH)) ret.addEmph (readEmphFromXML (eElement)); else if (sLocalName.equals (CSchematronXML.ELEMENT_SPAN)) ret.addSpan (readSpanFromXML (eElement)); else _warn (ret, "Unsupported Schematron element '" + sLocalName + "'"); } else ret.addForeignElement (eElement.getClone ()); break; case COMMENT: // Ignore comments break; default: _warn (ret, "Unsupported child node: " + aChild); } }); return ret; }@Nonnull public PSNS readNSFromXML (@Nonnull final IMicroElement eNS) { final PSNS ret = new PSNS (); eNS.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_URI)) ret.setUri (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_PREFIX)) ret.setPrefix (sAttrValue); else ret.addForeignAttribute (sAttrName, sAttrValue); }); eNS.forAllChildElements (eLetChild -> { if (CSchematron.NAMESPACE_SCHEMATRON.equals (eLetChild.getNamespaceURI ())) { _warn (ret, "Unsupported Schematron element '" + eLetChild.getLocalName () + "'"); } else _warn (ret, "Unsupported namespace URI '" + eLetChild.getNamespaceURI () + "'"); }); return ret; }@Nonnull public PSName readNameFromXML (@Nonnull final IMicroElement eName) { final PSName ret = new PSName (); eName.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_PATH)) ret.setPath (sAttrValue); else ret.addForeignAttribute (sAttrName, sAttrValue); }); eName.forAllChildElements (eNameChild -> { if (CSchematron.NAMESPACE_SCHEMATRON.equals (eNameChild.getNamespaceURI ())) { _warn (ret, "Unsupported Schematron element '" + eNameChild.getLocalName () + "'"); } else _warn (ret, "Unsupported namespace URI '" + eNameChild.getNamespaceURI () + "'"); }); return ret; }@Nonnull public PSLet readLetFromXML (@Nonnull final IMicroElement eLet) { final PSLet ret = new PSLet (); eLet.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_NAME)) ret.setName (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_VALUE)) ret.setValue (sAttrValue); else _warn (ret, "Unsupported attribute '" + sAttrName + "'='" + sAttrValue + "'"); }); eLet.forAllChildElements (eLetChild -> { if (CSchematron.NAMESPACE_SCHEMATRON.equals (eLetChild.getNamespaceURI ())) { _warn (ret, "Unsupported Schematron element '" + eLetChild.getLocalName () + "'"); } else _warn (ret, "Unsupported namespace URI '" + eLetChild.getNamespaceURI () + "'"); }); return ret; }@Nonnull public PSInclude readIncludeFromXML (@Nonnull final IMicroElement eInclude) { final PSInclude ret = new PSInclude (); eInclude.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_HREF)) ret.setHref (sAttrValue); else _warn (ret, "Unsupported attribute '" + sAttrName + "'='" + sAttrValue + "'"); }); eInclude.forAllChildElements (eValueOfChild -> { if (CSchematron.NAMESPACE_SCHEMATRON.equals (eValueOfChild.getNamespaceURI ())) { _warn (ret, "Unsupported Schematron element '" + eValueOfChild.getLocalName () + "'"); } else _warn (ret, "Unsupported namespace URI '" + eValueOfChild.getNamespaceURI () + "'"); }); return ret; }@Nonnull public PSExtends readExtendsFromXML (@Nonnull final IMicroElement eExtends) { final PSExtends ret = new PSExtends (); eExtends.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_RULE)) ret.setRule (sAttrValue); else ret.addForeignAttribute (sAttrName, sAttrValue); }); eExtends.forAllChildElements (eChild -> { if (CSchematron.NAMESPACE_SCHEMATRON.equals (eChild.getNamespaceURI ())) { _warn (ret, "Unsupported Schematron element '" + eChild.getLocalName () + "'"); } else _warn (ret, "Unsupported namespace URI '" + eChild.getNamespaceURI () + "'"); }); return ret; }@Nonnull public PSEmph readEmphFromXML (@Nonnull final IMicroElement eEmph) { final PSEmph ret = new PSEmph (); eEmph.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); _warn (ret, "Unsupported attribute '" + sAttrName + "'='" + sAttrValue + "'"); }); eEmph.forAllChildren (aEmphChild -> { switch (aEmphChild.getType ()) { case TEXT: ret.addText (((IMicroText) aEmphChild).getNodeValue ()); break; case ELEMENT: final IMicroElement eElement = (IMicroElement) aEmphChild; if (CSchematron.NAMESPACE_SCHEMATRON.equals (eElement.getNamespaceURI ())) { _warn (ret, "Unsupported Schematron element '" + eElement.getLocalName () + "'"); } else _warn (ret, "Unsupported namespace URI '" + eElement.getNamespaceURI () + "'"); break; case COMMENT: // Ignore comments break; default: _warn (ret, "Unsupported child node: " + aEmphChild); } }); return ret; }@Nonnull public PSDir readDirFromXML (@Nonnull final IMicroElement eDir) { final PSDir ret = new PSDir (); eDir.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_VALUE)) ret.setValue (EDirValue.getFromIDOrNull (sAttrValue)); else ret.addForeignAttribute (sAttrName, sAttrValue); }); eDir.forAllChildren (aDirChild -> { switch (aDirChild.getType ()) { case TEXT: ret.addText (((IMicroText) aDirChild).getNodeValue ()); break; case ELEMENT: final IMicroElement eElement = (IMicroElement) aDirChild; if (CSchematron.NAMESPACE_SCHEMATRON.equals (eElement.getNamespaceURI ())) { _warn (ret, "Unsupported Schematron element '" + eElement.getLocalName () + "'"); } else ret.addForeignElement (eElement.getClone ()); break; case COMMENT: // Ignore comments break; default: _warn (ret, "Unsupported child node: " + aDirChild); } }); return ret; }@Nonnull public PSDiagnostics readDiagnosticsFromXML (@Nonnull final IMicroElement eDiagnostics) { final PSDiagnostics ret = new PSDiagnostics (); eDiagnostics.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); ret.addForeignAttribute (sAttrName, sAttrValue); }); eDiagnostics.forAllChildElements (eDiagnosticsChild -> { if (CSchematron.NAMESPACE_SCHEMATRON.equals (eDiagnosticsChild.getNamespaceURI ())) { if (eDiagnosticsChild.getLocalName ().equals (CSchematronXML.ELEMENT_INCLUDE)) ret.addInclude (readIncludeFromXML (eDiagnosticsChild)); else if (eDiagnosticsChild.getLocalName ().equals (CSchematronXML.ELEMENT_DIAGNOSTIC)) ret.addDiagnostic (readDiagnosticFromXML (eDiagnosticsChild)); else _warn (ret, "Unsupported Schematron element '" + eDiagnosticsChild.getLocalName () + "'"); } else ret.addForeignElement (eDiagnosticsChild.getClone ()); }); return ret; }@Nonnull public PSDiagnostic readDiagnosticFromXML (@Nonnull final IMicroElement eDiagnostic) { final PSDiagnostic ret = new PSDiagnostic (); final PSRichGroup aRichGroup = new PSRichGroup (); eDiagnostic.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_ID)) ret.setID (sAttrValue); else if (PSRichGroup.isRichAttribute (sAttrName)) _handleRichGroup (sAttrName, sAttrValue, aRichGroup); else ret.addForeignAttribute (sAttrName, sAttrValue); }); ret.setRich (aRichGroup); eDiagnostic.forAllChildren (aDiagnosticChild -> { switch (aDiagnosticChild.getType ()) { case TEXT: ret.addText (((IMicroText) aDiagnosticChild).getNodeValue ()); break; case ELEMENT: final IMicroElement eElement = (IMicroElement) aDiagnosticChild; if (CSchematron.NAMESPACE_SCHEMATRON.equals (eElement.getNamespaceURI ())) { final String sLocalName = eElement.getLocalName (); if (sLocalName.equals (CSchematronXML.ELEMENT_VALUE_OF)) ret.addValueOf (readValueOfFromXML (eElement)); else if (sLocalName.equals (CSchematronXML.ELEMENT_EMPH)) ret.addEmph (readEmphFromXML (eElement)); else if (sLocalName.equals (CSchematronXML.ELEMENT_DIR)) ret.addDir (readDirFromXML (eElement)); else if (sLocalName.equals (CSchematronXML.ELEMENT_SPAN)) ret.addSpan (readSpanFromXML (eElement)); else _warn (ret, "Unsupported Schematron element '" + sLocalName + "'"); } else ret.addForeignElement (eElement.getClone ()); break; case COMMENT: // Ignore comments break; default: _warn (ret, "Unsupported child node: " + aDiagnosticChild); } }); return ret; }@Nonnull public PSAssertReport readAssertReportFromXML (@Nonnull final IMicroElement eAssertReport) { final PSAssertReport ret = new PSAssertReport (eAssertReport.getLocalName () .equals (CSchematronXML.ELEMENT_ASSERT)); final PSRichGroup aRichGroup = new PSRichGroup (); final PSLinkableGroup aLinkableGroup = new PSLinkableGroup (); eAssertReport.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_TEST)) ret.setTest (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_FLAG)) ret.setFlag (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_ID)) ret.setID (sAttrValue); else if (sAttrName.equals (CSchematronXML.ATTR_DIAGNOSTICS)) ret.setDiagnostics (sAttrValue); else if (PSRichGroup.isRichAttribute (sAttrName)) _handleRichGroup (sAttrName, sAttrValue, aRichGroup); else if (PSLinkableGroup.isLinkableAttribute (sAttrName)) _handleLinkableGroup (sAttrName, sAttrValue, aLinkableGroup); else ret.addForeignAttribute (sAttrName, sAttrValue); }); ret.setRich (aRichGroup); ret.setLinkable (aLinkableGroup); eAssertReport.forAllChildren (aAssertReportChild -> { switch (aAssertReportChild.getType ()) { case TEXT: ret.addText (((IMicroText) aAssertReportChild).getNodeValue ()); break; case ELEMENT: final IMicroElement eElement = (IMicroElement) aAssertReportChild; if (CSchematron.NAMESPACE_SCHEMATRON.equals (eElement.getNamespaceURI ())) { final String sLocalName = eElement.getLocalName (); if (sLocalName.equals (CSchematronXML.ELEMENT_NAME)) ret.addName (readNameFromXML (eElement)); else if (sLocalName.equals (CSchematronXML.ELEMENT_VALUE_OF)) ret.addValueOf (readValueOfFromXML (eElement)); else if (sLocalName.equals (CSchematronXML.ELEMENT_EMPH)) ret.addEmph (readEmphFromXML (eElement)); else if (sLocalName.equals (CSchematronXML.ELEMENT_DIR)) ret.addDir (readDirFromXML (eElement)); else if (sLocalName.equals (CSchematronXML.ELEMENT_SPAN)) ret.addSpan (readSpanFromXML (eElement)); else _warn (ret, "Unsupported Schematron element '" + sLocalName + "'"); } else ret.addForeignElement (eElement.getClone ()); break; case COMMENT: // Ignore comments break; default: _warn (ret, "Unsupported child node: " + aAssertReportChild); } }); return ret; }@Nonnull public PSActive readActiveFromXML (@Nonnull final IMicroElement eActive) { final PSActive ret = new PSActive (); eActive.forAllAttributes ( (sNS, sAttrName, sVal) -> { final String sAttrValue = _getAttributeValue (sVal); if (sAttrName.equals (CSchematronXML.ATTR_PATTERN)) ret.setPattern (sAttrValue); else ret.addForeignAttribute (sAttrName, sAttrValue); }); eActive.forAllChildren (aActiveChild -> { switch (aActiveChild.getType ()) { case TEXT: ret.addText (((IMicroText) aActiveChild).getNodeValue ()); break; case ELEMENT: final IMicroElement eElement = (IMicroElement) aActiveChild; if (CSchematron.NAMESPACE_SCHEMATRON.equals (eElement.getNamespaceURI ())) { final String sLocalName = eElement.getLocalName (); if (sLocalName.equals (CSchematronXML.ELEMENT_DIR)) ret.addDir (readDirFromXML (eElement)); else if (sLocalName.equals (CSchematronXML.ELEMENT_EMPH)) ret.addEmph (readEmphFromXML (eElement)); else if (sLocalName.equals (CSchematronXML.ELEMENT_SPAN)) ret.addSpan (readSpanFromXML (eElement)); else _warn (ret, "Unsupported Schematron element '" + sLocalName + "'"); } else ret.addForeignElement (eElement.getClone ()); break; case COMMENT: // Ignore comments break; default: _warn (ret, "Unsupported child node: " + aActiveChild); } }); return ret; }private void _warn (@Nonnull final IPSElement aSourceElement, @Nonnull final String sMessage) { ValueEnforcer.notNull (aSourceElement, "SourceElement"); ValueEnforcer.notNull (sMessage, "Message"); m_aErrorHandler.warn (m_aResource, aSourceElement, sMessage); }@Nullable public static String getBeautifiedLocation (@Nonnull final String sNamespaceURI, @Nonnull final String sLocalName) { for (final ISVRLLocationBeautifierSPI aBeautifier : s_aList) { final String sBeautified = aBeautifier.getReplacementText (sNamespaceURI, sLocalName); if (sBeautified != null) return sBeautified; } if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Unsupported elements for beautification: " + sNamespaceURI + " -- " + sLocalName); return null; }@Nonnull private String _getErrorText (@Nonnull final List aBoundContentElements, @Nonnull final Node aSourceNode) throws SchematronValidationException { final StringBuilder aSB = new StringBuilder (); for (final PSXPathBoundElement aBoundElement : aBoundContentElements) { final Object aContent = aBoundElement.getElement (); if (aContent instanceof String) aSB.append ((String) aContent); else if (aContent instanceof PSName) { final PSName aName = (PSName) aContent; if (aName.hasPath ()) { // XPath present try { aSB.append ((String) XPathEvaluationHelper.evaluate (aBoundElement.getBoundExpression (), aSourceNode, XPathConstants.STRING, m_sBaseURI)); } catch (final XPathExpressionException ex) { _error (aName, "Failed to evaluate XPath expression to a string: '" + aBoundElement.getExpression () + "'", ex.getCause () != null ? ex.getCause () : ex); // Append the path so that something is present in the output aSB.append (aName.getPath ()); } } else { // No XPath present aSB.append (aSourceNode.getNodeName ()); } } else if (aContent instanceof PSValueOf) { final PSValueOf aValueOf = (PSValueOf) aContent; try { aSB.append ((String) XPathEvaluationHelper.evaluate (aBoundElement.getBoundExpression (), aSourceNode, XPathConstants.STRING, m_sBaseURI)); } catch (final XPathExpressionException ex) { _error (aValueOf, "Failed to evaluate XPath expression to a string: '" + aBoundElement.getExpression () + "'", ex); // Append the path so that something is present in the output aSB.append (aValueOf.getSelect ()); } } else if (aContent instanceof PSEmph) aSB.append (((PSEmph) aContent).getAsText ()); else if (aContent instanceof PSDir) aSB.append (((PSDir) aContent).getAsText ()); else if (aContent instanceof PSSpan) aSB.append (((PSSpan) aContent).getAsText ()); else throw new SchematronValidationException ("Unsupported assert/report content element: " + aContent); } return aSB.toString (); }@Nullable public static SchematronProviderXSLTFromSCH getSchematronXSLTProvider (@Nonnull final IReadableResource aSchematronResource, @Nonnull final SCHTransformerCustomizer aTransformerCustomizer) { ValueEnforcer.notNull (aSchematronResource, "SchematronResource"); ValueEnforcer.notNull (aTransformerCustomizer, "TransformerCustomizer"); if (!aSchematronResource.exists ()) { LOGGER.warn ("Schematron resource " + aSchematronResource + " does not exist!"); return null; } if (!aTransformerCustomizer.canCacheResult ()) { // Create new object and return without cache handling because the custom // parameters may have side effects on the created XSLT! return createSchematronXSLTProvider (aSchematronResource, aTransformerCustomizer); } // Determine the unique resource ID for caching final String sCacheKey = StringHelper. getImploded (':', aSchematronResource.getResourceID (), StringHelper.getNotNull (aTransformerCustomizer.getPhase ()), StringHelper.getNotNull (aTransformerCustomizer.getLanguageCode ())); s_aLock.lock (); try { // Validator already in the cache? SchematronProviderXSLTFromSCH aProvider = s_aCache.get (sCacheKey); if (aProvider == null) { // Create new object and put in cache aProvider = createSchematronXSLTProvider (aSchematronResource, aTransformerCustomizer); if (aProvider != null) s_aCache.put (sCacheKey, aProvider); } return aProvider; } finally { s_aLock.unlock (); } }@Nullable public static SchematronProviderXSLTFromSCH createSchematronXSLTProvider (@Nonnull final IReadableResource aSchematronResource, @Nonnull final SCHTransformerCustomizer aTransformerCustomizer) { if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Compiling Schematron instance " + aSchematronResource.toString ()); final SchematronProviderXSLTFromSCH aXSLTPreprocessor = new SchematronProviderXSLTFromSCH (aSchematronResource, aTransformerCustomizer); if (!aXSLTPreprocessor.isValidSchematron ()) { // Schematron is invalid -> parsing failed LOGGER.warn ("The Schematron resource '" + aSchematronResource.getResourceID () + "' is invalid!"); if (LOGGER.isDebugEnabled () && aXSLTPreprocessor.getXSLTDocument () != null) { // Log the created XSLT document for better error tracking LOGGER.debug (" Created XSLT document:\n" + XMLWriter.getNodeAsString (aXSLTPreprocessor.getXSLTDocument ())); } return null; } // If it is a valid schematron, there must be a result XSLT present! if (aXSLTPreprocessor.getXSLTDocument () == null) throw new IllegalStateException ("No XSLT document retrieved from Schematron resource '" + aSchematronResource.getResourceID () + "'!"); if (LOGGER.isDebugEnabled ()) LOGGER.debug ("Finished compiling Schematron instance " + aSchematronResource.toString ()); // Create the main validator for the schematron return aXSLTPreprocessor; }public static boolean isValidSchematron (@Nullable final Source aSource) { if (aSource == null) return false; try { // Get a validator from the RNC schema. final Validator aValidator = RelaxNGCompactSchemaCache.getInstance ().getValidator (SCHEMATRON_RNC); // Ensure a collecting error handler is set final ErrorHandler aOldEH = aValidator.getErrorHandler (); CollectingSAXErrorHandler aCEH; if (aOldEH instanceof CollectingSAXErrorHandler) aCEH = (CollectingSAXErrorHandler) aOldEH; else { aCEH = new CollectingSAXErrorHandler (); aValidator.setErrorHandler (aCEH.andThen (aOldEH)); } // Perform validation aValidator.validate (aSource, null); // Check results return aCEH.getErrorList ().getMostSevereErrorLevel ().isLT (EErrorLevel.ERROR); } catch (final SAXException ex) { // Document is not valid in respect to XML } catch (final IOException ex) { LOGGER.warn ("Failed to read source " + aSource, ex); } return false; }public static boolean isValidSchematron (@Nullable final IReadableResource aRes) { if (aRes == null) return false; return isValidSchematron (TransformSourceFactory.create (aRes)); }public static boolean isValidSchematron (@Nullable final Node aNode) { if (aNode == null) return false; return isValidSchematron (TransformSourceFactory.create (aNode)); }public static boolean isValidSchematron (@Nullable final IMicroNode aNode) { if (aNode == null) return false; return isValidSchematron (TransformSourceFactory.create (MicroWriter.getNodeAsString (aNode))); }private String _format (final String format, final Object first, final Object second) { final FormattingTuple tuple = MessageFormatter.format (format, first, second); return tuple.getMessage (); }private String _format (final String format, final Object arg) { final FormattingTuple tuple = MessageFormatter.format (format, arg); return tuple.getMessage (); }@Nonnull public MapBasedXPathFunctionResolver loadXQuery (@Nonnull @WillClose final InputStream aXQueryIS) throws XPathException, IOException { ValueEnforcer.notNull (aXQueryIS, "XQueryIS"); try { final MapBasedXPathFunctionResolver aFunctionResolver = new MapBasedXPathFunctionResolver (); // create a Configuration object final Configuration aConfiguration = new Configuration (); final DynamicQueryContext aDynamicQueryContext = new DynamicQueryContext (aConfiguration); final StaticQueryContext aStaticQueryCtx = aConfiguration.newStaticQueryContext (); // The base URI required for resolving within the XQuery aStaticQueryCtx.setBaseURI (m_sBaseURL); // null == auto detect final String sEncoding = null; final XQueryExpression exp = aStaticQueryCtx.compileQuery (aXQueryIS, sEncoding); final Controller aXQController = exp.newController (aDynamicQueryContext); // find all loaded methods and convert them to XPath functions final FunctionLibraryList aFuncLibList = exp.getExecutable ().getFunctionLibrary (); for (final FunctionLibrary aFuncLib : aFuncLibList.getLibraryList ()) { // Ignore all Vendor, System etc. internal libraries if (aFuncLib instanceof FunctionLibraryList) { // This block works with Saxon HE 9.5.1-x :) // This is the custom function library list final FunctionLibraryList aRealFuncLib = (FunctionLibraryList) aFuncLib; for (final FunctionLibrary aNestedFuncLib : aRealFuncLib.getLibraryList ()) { // Currently the user functions are in ExecutableFunctionLibrary if (aNestedFuncLib instanceof ExecutableFunctionLibrary) for (final UserFunction aUserFunc : new IterableIterator <> (((ExecutableFunctionLibrary) aNestedFuncLib).iterateFunctions ())) { // Saxon 9.7 changes "getNumberOfArguments" to "getArity" aFunctionResolver.addUniqueFunction (aUserFunc.getFunctionName ().getNamespaceBinding ().getURI (), aUserFunc.getFunctionName ().getLocalPart (), aUserFunc.getArity (), new XPathFunctionFromUserFunction (aConfiguration, aXQController, aUserFunc)); } } } else if (aFuncLib instanceof XQueryFunctionLibrary) { // This block works with Saxon HE 9.6.0-x :) final XQueryFunctionLibrary aRealFuncLib = (XQueryFunctionLibrary) aFuncLib; for (final XQueryFunction aXQueryFunction : new IterableIterator <> (aRealFuncLib.getFunctionDefinitions ())) { // Ensure the function is compiled aXQueryFunction.compile (); aFunctionResolver.addUniqueFunction (aXQueryFunction.getFunctionName ().getNamespaceBinding ().getURI (), aXQueryFunction.getFunctionName ().getLocalPart (), aXQueryFunction.getNumberOfArguments (), new XPathFunctionFromUserFunction (aConfiguration, aXQController, aXQueryFunction.getUserFunction ())); } } } return aFunctionResolver; } finally { StreamHelper.close (aXQueryIS); } }@Nonnull public static IPSQueryBinding getQueryBindingOfNameOrThrow (@Nullable final String sName) throws SchematronBindException { final IPSQueryBinding aQB = getQueryBindingOfName (sName); if (aQB == null) throw new SchematronBindException ("No query binding implementation present for query binding '" + sName + "'"); return aQB; }@Nullable public static IPSQueryBinding getQueryBindingOfName (@Nullable final String sName) { if (sName == null) return DEFAULT_QUERY_BINDING; return s_aRWLock.readLocked ( () -> s_aMap.get (sName)); }public static void setErrorLevelDeterminator (@Nonnull final ISVRLErrorLevelDeterminator aELD) { ValueEnforcer.notNull (aELD, "ErrorLevelDeterminator"); s_aRWLock.readLocked ( () -> s_aELD = aELD); }@Nonnull @ReturnsMutableCopy public static ICommonsList getAllFailedAssertionsAndSuccessfulReports (@Nullable final SchematronOutputType aSchematronOutput) { final ICommonsList ret = new CommonsArrayList <> (); if (aSchematronOutput != null) for (final Object aObj : aSchematronOutput.getActivePatternAndFiredRuleAndFailedAssert ()) if (aObj instanceof FailedAssert) ret.add (new SVRLFailedAssert ((FailedAssert) aObj)); else if (aObj instanceof SuccessfulReport) ret.add (new SVRLSuccessfulReport ((SuccessfulReport) aObj)); return ret; }@Nonnull @ReturnsMutableCopy public static ICommonsList getAllSuccessfulReportsMoreOrEqualSevereThan (@Nullable final SchematronOutputType aSchematronOutput, @Nonnull final IErrorLevel aErrorLevel) { final ICommonsList ret = new CommonsArrayList <> (); if (aSchematronOutput != null) for (final Object aObj : aSchematronOutput.getActivePatternAndFiredRuleAndFailedAssert ()) if (aObj instanceof SuccessfulReport) { final SVRLSuccessfulReport aSR = new SVRLSuccessfulReport ((SuccessfulReport) aObj); if (aSR.getFlag ().isGE (aErrorLevel)) ret.add (aSR); } return ret; }@Nonnull @ReturnsMutableCopy public static ICommonsList getAllSuccessfulReports (@Nullable final SchematronOutputType aSchematronOutput) { final ICommonsList ret = new CommonsArrayList <> (); if (aSchematronOutput != null) for (final Object aObj : aSchematronOutput.getActivePatternAndFiredRuleAndFailedAssert ()) if (aObj instanceof SuccessfulReport) ret.add (new SVRLSuccessfulReport ((SuccessfulReport) aObj)); return ret; }@Nonnull @ReturnsMutableCopy public static ICommonsList getAllFailedAssertionsMoreOrEqualSevereThan (@Nullable final SchematronOutputType aSchematronOutput, @Nonnull final IErrorLevel aErrorLevel) { final ICommonsList ret = new CommonsArrayList <> (); if (aSchematronOutput != null) for (final Object aObj : aSchematronOutput.getActivePatternAndFiredRuleAndFailedAssert ()) if (aObj instanceof FailedAssert) { final SVRLFailedAssert aFA = new SVRLFailedAssert ((FailedAssert) aObj); if (aFA.getFlag ().isGE (aErrorLevel)) ret.add (aFA); } return ret; }@Nonnull @ReturnsMutableCopy public static ICommonsList getAllFailedAssertions (@Nullable final SchematronOutputType aSchematronOutput) { final ICommonsList ret = new CommonsArrayList <> (); if (aSchematronOutput != null) for (final Object aObj : aSchematronOutput.getActivePatternAndFiredRuleAndFailedAssert ()) if (aObj instanceof FailedAssert) ret.add (new SVRLFailedAssert ((FailedAssert) aObj)); return ret; }@Nonnull public EChange removeAll (@Nullable final Iterable aVars) { EChange eChange = EChange.UNCHANGED; if (aVars != null) for (final String sName : aVars) eChange = eChange.or (remove (sName)); return eChange; } @Nonnull @ReturnsMutableCopy public ICommonsNavigableMap getAll () { return m_aMap.getClone (); } public boolean contains (@Nullable final String sName) { if (StringHelper.hasNoText (sName)) return false; return m_aMap.containsKey (sName); }@Nonnull public EChange remove (@Nullable final String sVarName) { if (StringHelper.hasText (sVarName)) if (m_aMap.remove (PSXPathQueryBinding.PARAM_VARIABLE_PREFIX + sVarName) == null) return EChange.CHANGED; return EChange.UNCHANGED; }@Nullable public static SchematronOutputType applySchematron (@Nonnull final ISchematronResource aSchematron, @Nonnull final Node aNode) { ValueEnforcer.notNull (aSchematron, "SchematronResource"); ValueEnforcer.notNull (aNode, "Node"); return applySchematron (aSchematron, new DOMSource (aNode)); }@Nullable public static SchematronOutputType applySchematron (@Nonnull final ISchematronResource aSchematron, @Nonnull final IReadableResource aXML) { ValueEnforcer.notNull (aSchematron, "SchematronResource"); ValueEnforcer.notNull (aXML, "XMLSource"); try { // Apply Schematron on XML return aSchematron.applySchematronValidationToSVRL (aXML); } catch (final Exception ex) { throw new IllegalArgumentException ("Failed to apply Schematron " + aSchematron.getID () + " onto XML resource " + aXML.getResourceID (), ex); } }@Nonnull public ESuccess writeToWriter (@Nonnull final IPSElement aPSElement, @Nonnull @WillClose final Writer aWriter) { ValueEnforcer.notNull (aPSElement, "PSElement"); final IMicroElement eXML = aPSElement.getAsMicroElement (); return MicroWriter.writeToWriter (getAsDocument (eXML), aWriter, m_aWriterSettings.getXMLWriterSettings ()); }@Nonnull public ESuccess writeToStream (@Nonnull final IPSElement aPSElement, @Nonnull @WillClose final OutputStream aOS) { ValueEnforcer.notNull (aPSElement, "PSElement"); final IMicroElement eXML = aPSElement.getAsMicroElement (); return MicroWriter.writeToStream (getAsDocument (eXML), aOS, m_aWriterSettings.getXMLWriterSettings ()); }@Nonnull public ESuccess writeToFile (@Nonnull final IPSElement aPSElement, @Nonnull final File aFile) { ValueEnforcer.notNull (aPSElement, "PSElement"); final IMicroElement eXML = aPSElement.getAsMicroElement (); return MicroWriter.writeToFile (getAsDocument (eXML), aFile, m_aWriterSettings.getXMLWriterSettings ()); }@Nonnull @OverrideOnDemand public PSSchema createPreprocessedSchema (@Nonnull final PSSchema aSchema, @Nonnull final IPSQueryBinding aQueryBinding) throws SchematronException { final PSPreprocessor aPreprocessor = createPreprocessor (aQueryBinding); final PSSchema aPreprocessedSchema = aPreprocessor.getAsPreprocessedSchema (aSchema); if (aPreprocessedSchema == null) throw new SchematronPreprocessException ("Failed to preprocess schema " + aSchema + " with query binding " + aQueryBinding); if (SchematronDebug.isShowPreprocessedSchematron ()) LOGGER.info ("Preprocessed Schematron:\n" + MicroWriter.getNodeAsString (aPreprocessedSchema.getAsMicroElement ())); return aPreprocessedSchema; }@Nonnull @OverrideOnDemand public IPSQueryBinding getQueryBinding (@Nonnull final PSSchema aSchema) throws SchematronException { return PSQueryBindingRegistry.getQueryBindingOfNameOrThrow (aSchema.getQueryBinding ()); }@Nonnull @OverrideOnDemand public PSSchema readSchema (@Nonnull final IReadableResource aResource, @Nullable final IPSErrorHandler aErrorHandler, @Nullable final EntityResolver aEntityResolver) throws SchematronException { return new PSReader (aResource, aErrorHandler, aEntityResolver).readSchema (); }@Nullable public PSSchema getForcedPreprocessedSchema (@Nonnull final PSSchema aSchema) throws SchematronPreprocessException { ValueEnforcer.notNull (aSchema, "Schema"); final PreprocessorLookup aLookup = new PreprocessorLookup (aSchema); final PreprocessorIDPool aIDPool = new PreprocessorIDPool (); final PSSchema ret = new PSSchema (aSchema.getResource ()); ret.setID (aIDPool.getUniqueID (aSchema.getID ())); ret.setRich (aSchema.getRichClone ()); ret.setSchemaVersion (aSchema.getSchemaVersion ()); ret.setDefaultPhase (aSchema.getDefaultPhase ()); ret.setQueryBinding (aSchema.getQueryBinding ()); if (m_bKeepTitles && aSchema.hasTitle ()) ret.setTitle (aSchema.getTitle ().getClone ()); if (aSchema.hasAnyInclude ()) throw new SchematronPreprocessException ("Cannot preprocess with an "); for (final PSNS aNS : aSchema.getAllNSs ()) ret.addNS (aNS.getClone ()); // start ps are skipped for (final PSLet aLet : aSchema.getAllLets ()) ret.addLet (aLet.getClone ()); for (final PSPhase aPhase : aSchema.getAllPhases ()) ret.addPhase (_getPreprocessedPhase (aPhase, aIDPool)); for (final PSPattern aPattern : aSchema.getAllPatterns ()) { final PSPattern aMinifiedPattern = _getPreprocessedPattern (aPattern, aLookup, aIDPool); if (aMinifiedPattern != null) { // Pattern without rules? if (aMinifiedPattern.getRuleCount () > 0 || m_bKeepEmptyPatterns) ret.addPattern (aMinifiedPattern); } } // Schema without patterns? if (aSchema.getPatternCount () == 0 && !m_bKeepEmptySchema) return null; // end ps are skipped if (m_bKeepDiagnostics && aSchema.hasDiagnostics ()) ret.setDiagnostics (_getPreprocessedDiagnostics (aSchema.getDiagnostics ())); ret.addForeignElements (aSchema.getAllForeignElements ()); ret.addForeignAttributes (aSchema.getAllForeignAttributes ()); return ret; }@Nullable public PSSchema getAsPreprocessedSchema (@Nonnull final PSSchema aSchema) throws SchematronPreprocessException { ValueEnforcer.notNull (aSchema, "Schema"); // Anything to do? if (aSchema.isPreprocessed ()) return aSchema; return getForcedPreprocessedSchema (aSchema); }@Nullable public PSSchema getAsMinimalSchema (@Nonnull final PSSchema aSchema) throws SchematronPreprocessException { ValueEnforcer.notNull (aSchema, "Schema"); // Anything to do? if (aSchema.isMinimal ()) return aSchema; return getForcedPreprocessedSchema (aSchema); }private void _resolveRuleContent (@Nonnull final ICommonsList aRuleContent, @Nonnull final PreprocessorLookup aLookup, @Nonnull final PreprocessorIDPool aIDPool, @Nullable final ICommonsMap aParamValueMap, @Nonnull final PSRule aTargetRule) throws SchematronPreprocessException { for (final IPSElement aElement : aRuleContent) { if (aElement instanceof PSAssertReport) { final PSAssertReport aAssertReport = (PSAssertReport) aElement; aTargetRule.addAssertReport (_getPreprocessedAssert (aAssertReport, aIDPool, aParamValueMap)); } else { final PSExtends aExtends = (PSExtends) aElement; final String sRuleID = aExtends.getRule (); final PSRule aBaseRule = aLookup.getAbstractRuleOfID (sRuleID); if (aBaseRule == null) throw new SchematronPreprocessException ("Failed to resolve rule ID '" + sRuleID + "' in extends statement. Available rules are: " + aLookup.getAllAbstractRuleIDs ()); // Recursively resolve the extends of the base rule _resolveRuleContent (aBaseRule.getAllContentElements (), aLookup, aIDPool, aParamValueMap, aTargetRule); // Copy all lets for (final PSLet aBaseLet : aBaseRule.getAllLets ()) aTargetRule.addLet (aBaseLet.getClone ()); } } }@Nonnull public SchematronOutputType applySchematronValidationToSVRL (@Nonnull final Node aXMLNode, @Nullable final String sBaseURI) throws SchematronException { ValueEnforcer.notNull (aXMLNode, "XMLNode"); final SchematronOutputType aSOT = getOrCreateBoundSchema ().validateComplete (aXMLNode, sBaseURI); // Debug print the created SVRL document if (SchematronDebug.isShowCreatedSVRL ()) LOGGER.info ("Created SVRL:\n" + new SVRLMarshaller (false).getAsString (aSOT)); return aSOT; }public void validateCompletely (@Nonnull final IPSErrorHandler aErrorHandler) { ValueEnforcer.notNull (aErrorHandler, "ErrorHandler"); try { getOrCreateBoundSchema ().getOriginalSchema ().validateCompletely (aErrorHandler); } catch (final RuntimeException ex) { // May happen when XPath errors are contained } }@Nonnull public IPSBoundSchema getOrCreateBoundSchema () { if (m_aBoundSchema == null) try { m_aBoundSchema = createBoundSchema (); } catch (final RuntimeException ex) { if (m_aErrorHandler != null) m_aErrorHandler.error (getResource (), null, "Error creating bound schema", ex); throw ex; } return m_aBoundSchema; }@Nonnull public SchematronResourcePure setEntityResolver (@Nullable final EntityResolver aEntityResolver) { if (m_aBoundSchema != null) throw new IllegalStateException ("Schematron was already bound and can therefore not be altered!"); internalSetEntityResolver (aEntityResolver); return this; }@Nonnull public SchematronResourcePure setFunctionResolver (@Nullable final XPathFunctionResolver aFunctionResolver) { if (m_aBoundSchema != null) throw new IllegalStateException ("Schematron was already bound and can therefore not be altered!"); m_aFunctionResolver = aFunctionResolver; return this; }@Nonnull public SchematronResourcePure setVariableResolver (@Nullable final XPathVariableResolver aVariableResolver) { if (m_aBoundSchema != null) throw new IllegalStateException ("Schematron was already bound and can therefore not be altered!"); m_aVariableResolver = aVariableResolver; return this; }@Nonnull public SchematronResourcePure setErrorHandler (@Nullable final IPSErrorHandler aErrorHandler) { if (m_aBoundSchema != null) throw new IllegalStateException ("Schematron was already bound and can therefore not be altered!"); m_aErrorHandler = aErrorHandler; return this; }@Nonnull public SchematronResourcePure setPhase (@Nullable final String sPhase) { if (m_aBoundSchema != null) throw new IllegalStateException ("Schematron was already bound and can therefore not be altered!"); m_sPhase = sPhase; return this; }@Nullable public String getUniqueID (@Nullable final String sID) { if (sID == null) return null; if (m_aUsedIDs.add (sID)) { // Unique ID return sID; } // Non-unique ID int nIndex = 0; String sNewID = sID + nIndex; do { if (m_aUsedIDs.add (sNewID)) { // Now it's unique return sNewID; } ++nIndex; sNewID = sID + nIndex; } while (true); }public void addConfiguredXMLCatalog (@Nonnull final XMLCatalog aXmlCatalog) { m_aXmlCatalog.addConfiguredXMLCatalog (aXmlCatalog); log ("Added XMLCatalog " + aXmlCatalog, Project.MSG_DEBUG); }@DoesServiceRequest public ResultSegment listQueuesSegmented(final String prefix, final QueueListingDetails detailsIncluded, final Integer maxResults, final ResultContinuation continuationToken, QueueRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = QueueRequestOptions.populateAndApplyDefaults(options, this); SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest(); segmentedRequest.setToken(continuationToken); return ExecutionEngine.executeWithRetry(this, null, this.listQueuesSegmentedImpl(prefix, detailsIncluded, maxResults, options, segmentedRequest), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public ResultSegment listQueuesSegmented() throws StorageException { return this.listQueuesSegmented(null, QueueListingDetails.NONE, null, null, null, null); }@DoesServiceRequest public Iterable listQueues(final String prefix, final QueueListingDetails detailsIncluded, QueueRequestOptions options, OperationContext opContext) { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = QueueRequestOptions.populateAndApplyDefaults(options, this); SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest(); return new LazySegmentedIterable(this.listQueuesSegmentedImpl(prefix, detailsIncluded, null, options, segmentedRequest), this, null, options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public Iterable listQueues(final String prefix) { return this.listQueues(prefix, QueueListingDetails.NONE, null, null); }@DoesServiceRequest public Iterable listQueues() { return this.listQueues(null, QueueListingDetails.NONE, null, null); }protected static StorageException translateFromHttpStatus(final int statusCode, final String statusDescription, final Exception inner) { String errorCode; switch (statusCode) { case HttpURLConnection.HTTP_FORBIDDEN: errorCode = StorageErrorCode.ACCESS_DENIED.toString(); break; case HttpURLConnection.HTTP_GONE: case HttpURLConnection.HTTP_NOT_FOUND: errorCode = StorageErrorCode.RESOURCE_NOT_FOUND.toString(); break; case 416: case HttpURLConnection.HTTP_BAD_REQUEST: // 416: RequestedRangeNotSatisfiable - No corresponding enum in HttpURLConnection errorCode = StorageErrorCode.BAD_REQUEST.toString(); break; case HttpURLConnection.HTTP_PRECON_FAILED: case HttpURLConnection.HTTP_NOT_MODIFIED: errorCode = StorageErrorCode.CONDITION_FAILED.toString(); break; case HttpURLConnection.HTTP_CONFLICT: errorCode = StorageErrorCode.RESOURCE_ALREADY_EXISTS.toString(); break; case HttpURLConnection.HTTP_UNAVAILABLE: errorCode = StorageErrorCode.SERVER_BUSY.toString(); break; case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: errorCode = StorageErrorCode.SERVICE_TIMEOUT.toString(); break; case HttpURLConnection.HTTP_INTERNAL_ERROR: errorCode = StorageErrorCode.SERVICE_INTERNAL_ERROR.toString(); break; case HttpURLConnection.HTTP_NOT_IMPLEMENTED: errorCode = StorageErrorCode.NOT_IMPLEMENTED.toString(); break; case HttpURLConnection.HTTP_BAD_GATEWAY: errorCode = StorageErrorCode.BAD_GATEWAY.toString(); break; case HttpURLConnection.HTTP_VERSION: errorCode = StorageErrorCode.HTTP_VERSION_NOT_SUPPORTED.toString(); break; default: errorCode = null; } if (errorCode == null) { return null; } else { return new StorageException(errorCode, statusDescription, statusCode, null, inner); } }public static ListResponse getQueues(final InputStream stream, final CloudQueueClient serviceClient) throws SAXException, IOException, ParserConfigurationException { SAXParser saxParser = Utility.getSAXParser(); QueueListHandler handler = new QueueListHandler(serviceClient); saxParser.parse(stream, handler); return handler.response; }private void populateVersion1Log(LogRecordStreamReader reader) throws IOException, ParseException, URISyntaxException { this.requestStartTime = reader.readDate(LogRecord.REQUEST_START_TIME_FORMAT); this.operationType = reader.readString(); this.requestStatus = reader.readString(); this.httpStatusCode = reader.readString(); this.endToEndLatencyInMS = reader.readInteger(); this.serverLatencyInMS = reader.readInteger(); this.authenticationType = reader.readString(); this.requesterAccountName = reader.readString(); this.ownerAccountName = reader.readString(); this.serviceType = reader.readString(); this.requestUrl = reader.readUri(); this.requestedObjectKey = reader.readQuotedString(); this.requestIdHeader = reader.readUuid(); this.operationCount = reader.readInteger(); this.requesterIPAddress = reader.readString(); this.requestVersionHeader = reader.readString(); this.requestHeaderSize = reader.readLong(); this.requestPacketSize = reader.readLong(); this.responseHeaderSize = reader.readLong(); this.responsePacketSize = reader.readLong(); this.requestContentLength = reader.readLong(); this.requestMD5 = reader.readQuotedString(); this.serverMD5 = reader.readQuotedString(); this.eTagIdentifier = reader.readQuotedString(); this.lastModifiedTime = reader.readDate(LogRecord.LAST_MODIFIED_TIME_FORMAT); this.conditionsUsed = reader.readQuotedString(); this.userAgentHeader = reader.readQuotedString(); this.referrerHeader = reader.readQuotedString(); this.clientRequestId = reader.readQuotedString(); reader.endCurrentRecord(); }protected Iterable generateIteratorForQuery(final TableQuery queryRef, final EntityResolver resolver, TableRequestOptions options, OperationContext opContext) { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = TableRequestOptions.populateAndApplyDefaults(options, this); SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest(); if (resolver == null) { return new LazySegmentedIterable, T>(this.executeQuerySegmentedCoreImpl( queryRef, resolver, options, segmentedRequest), this, queryRef, options.getRetryPolicyFactory(), opContext); } else { return new LazySegmentedIterable, R>( this.executeQuerySegmentedWithResolverCoreImpl(queryRef, resolver, options, segmentedRequest), this, queryRef, options.getRetryPolicyFactory(), opContext); } }protected ResultSegment executeQuerySegmentedImpl(final TableQuery queryToExecute, final EntityResolver resolver, final ResultContinuation continuationToken, TableRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = TableRequestOptions.populateAndApplyDefaults(options, this); Utility.assertContinuationType(continuationToken, ResultContinuationType.TABLE); SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest(); segmentedRequest.setToken(continuationToken); return ExecutionEngine.executeWithRetry(this, queryToExecute, this.executeQuerySegmentedWithResolverCoreImpl(queryToExecute, resolver, options, segmentedRequest), options.getRetryPolicyFactory(), opContext); }private TableQuery generateListTablesQuery(final String prefix) { TableQuery listQuery = TableQuery. from(TableServiceEntity.class); listQuery.setSourceTableName(TableConstants.TABLES_SERVICE_TABLES_NAME); if (!Utility.isNullOrEmpty(prefix)) { // Append Max char to end '{' is 1 + 'z' in AsciiTable > uppperBound = prefix + '{' final String prefixFilter = String.format("(%s ge '%s') and (%s lt '%s{')", TableConstants.TABLE_NAME, prefix, TableConstants.TABLE_NAME, prefix); listQuery = listQuery.where(prefixFilter); } return listQuery; }public void BasicListing() { // List the tables with a given prefix. Iterable listTables = tableClient.listTables(tableName, null, null); for (String s : listTables) { act.outputText(view, String.format("List of tables: %s", s)); } }public void BasicDeleteEntity() throws StorageException { // Create an operation to retrieve the entity with partition key of // "Smith" and row key of "Jeff". TableOperation retrieveSmithJeff = TableOperation.retrieve("Smith", "Jeff", CustomerEntity.class); // Retrieve the entity with partition key of "Smith" and row key of // "Jeff". CustomerEntity entitySmithJeff = table.execute(retrieveSmithJeff) .getResultAsType(); // Create an operation to delete the entity. TableOperation deleteSmithJeff = TableOperation.delete(entitySmithJeff); // Submit the delete operation to the table service. table.execute(deleteSmithJeff); }public void BasicUpsert() throws StorageException { // Retrieve the entity with partition key of "Smith" and row key of // "Jeff". TableOperation retrieveSmithJeff = TableOperation.retrieve("Smith", "Jeff", CustomerEntity.class); // Submit the operation to the table service and get the specific // entity. CustomerEntity specificEntity = table.execute(retrieveSmithJeff) .getResultAsType(); // Specify a new phone number. specificEntity.setPhoneNumber("425-555-0105"); // Create an operation to replace the entity. TableOperation replaceEntity = TableOperation.merge(specificEntity); // Submit the operation to the table service. table.execute(replaceEntity); }public void BasicQuery() throws StorageException { // Retrieve a single entity. // Retrieve the entity with partition key of "Smith" and row key of // "Jeff". TableOperation retrieveSmithJeff = TableOperation.retrieve("Smith", "Jeff", CustomerEntity.class); // Submit the operation to the table service and get the specific // entity. @SuppressWarnings("unused") CustomerEntity specificEntity = table.execute(retrieveSmithJeff) .getResultAsType(); // Retrieve all entities in a partition. // Create a filter condition where the partition key is "Smith". String partitionFilter = TableQuery.generateFilterCondition( "PartitionKey", QueryComparisons.EQUAL, "Smith"); // Specify a partition query, using "Smith" as the partition key filter. TableQuery partitionQuery = TableQuery.from( CustomerEntity.class).where(partitionFilter); // Loop through the results, displaying information about the entity. for (CustomerEntity entity : table.execute(partitionQuery)) { act.outputText( view, entity.getPartitionKey() + " " + entity.getRowKey() + "\t" + entity.getEmail() + "\t" + entity.getPhoneNumber()); } }public void BasicBatch() throws StorageException { // Note: the limitations on a batch operation are // - up to 100 operations // - all operations must share the same PartitionKey // - if a retrieve is used it can be the only operation in the batch // - the serialized batch payload must be 4 MB or less // Define a batch operation. TableBatchOperation batchOperation = new TableBatchOperation(); // Create a customer entity to add to the table. CustomerEntity customer = new CustomerEntity("Smith", "Jeff"); customer.setEmail("Jeff@contoso.com"); customer.setPhoneNumber("425-555-0104"); batchOperation.insert(customer); // Create another customer entity to add to the table. CustomerEntity customer2 = new CustomerEntity("Smith", "Ben"); customer2.setEmail("Ben@contoso.com"); customer2.setPhoneNumber("425-555-0102"); batchOperation.insert(customer2); // Create a third customer entity to add to the table. CustomerEntity customer3 = new CustomerEntity("Smith", "Denise"); customer3.setEmail("Denise@contoso.com"); customer3.setPhoneNumber("425-555-0103"); batchOperation.insert(customer3); // Execute the batch of operations on the "tablebasics" table. table.execute(batchOperation); }public void BasicInsertEntity() throws StorageException { // Note: the limitations on an insert operation are // - the serialized payload must be 1 MB or less // - up to 252 properties in addition to the partition key, row key and // timestamp. 255 properties in total // - the serialized payload of each property must be 64 KB or less // Create a new customer entity. CustomerEntity customer1 = new CustomerEntity("Harp", "Walter"); customer1.setEmail("Walter@contoso.com"); customer1.setPhoneNumber("425-555-0101"); // Create an operation to add the new customer to the tablebasics table. TableOperation insertCustomer1 = TableOperation.insert(customer1); // Submit the operation to the table service. table.execute(insertCustomer1); }public final URI getQualifiedUri() throws URISyntaxException, StorageException { if (this.isSnapshot()) { return PathUtility.addToQuery(this.getUri(), String.format("sharesnapshot=%s", this.snapshotID)); } return this.fileServiceClient.getCredentials().transformUri(this.getUri()); }@DoesServiceRequest public void uploadPermissions(final FileSharePermissions permissions, final AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException { assertNoSnapshot(); if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient); ExecutionEngine.executeWithRetry(this.fileServiceClient, this, uploadPermissionsImpl(permissions, accessCondition, options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public void uploadPermissions(final FileSharePermissions permissions) throws StorageException { this.uploadPermissions(permissions, null /* accessCondition */, null /* options */, null /* opContext */); }public String generateSharedAccessSignature( final SharedAccessFilePolicy policy, final String groupPolicyIdentifier, final IPRange ipRange, final SharedAccessProtocols protocols) throws InvalidKeyException, StorageException { if (!StorageCredentialsHelper.canCredentialsSignRequest(this.fileServiceClient.getCredentials())) { final String errorMessage = SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY; throw new IllegalArgumentException(errorMessage); } final String resourceName = this.getSharedAccessCanonicalName(); final String signature = SharedAccessSignatureHelper.generateSharedAccessSignatureHashForBlobAndFile( policy, null /* SharedAccessHeaders */, groupPolicyIdentifier, resourceName, ipRange, protocols, this.fileServiceClient); final UriQueryBuilder builder = SharedAccessSignatureHelper.generateSharedAccessSignatureForBlobAndFile( policy, null /* SharedAccessHeaders */, groupPolicyIdentifier, "s", ipRange, protocols, signature); return builder.toString(); }@DoesServiceRequest public FileSharePermissions downloadPermissions(AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } assertNoSnapshot(); opContext.initialize(); options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient); return ExecutionEngine.executeWithRetry(this.fileServiceClient, this, downloadPermissionsImpl(accessCondition, options), options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public boolean deleteIfExists(AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException { return this.deleteIfExists(DeleteShareSnapshotsOption.NONE, accessCondition, options, opContext); }@DoesServiceRequest public void create(FileRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } assertNoSnapshot(); if (this.properties != null && this.properties.getShareQuota() != null) { Utility.assertInBounds("Share Quota", this.properties.getShareQuota(), 1, FileConstants.MAX_SHARE_QUOTA); } opContext.initialize(); options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient); ExecutionEngine.executeWithRetry(this.fileServiceClient, this, createImpl(options), options.getRetryPolicyFactory(), opContext); }private void lockToPartitionKey(final String partitionKey) { if (this.partitionKey == null) { this.partitionKey = partitionKey; } else { if (partitionKey.length() != partitionKey.length() || !this.partitionKey.equals(partitionKey)) { throw new IllegalArgumentException(SR.OPS_IN_BATCH_MUST_HAVE_SAME_PARTITION_KEY); } } }private void checkSingleQueryPerBatch(final TableOperation op, final int size) { // if this has a query then no other operations can be added. if (this.hasQuery) { throw new IllegalArgumentException(SR.RETRIEVE_MUST_BE_ONLY_OPERATION_IN_BATCH); } if (op.getOperationType() == TableOperationType.RETRIEVE) { if (size > 0) { throw new IllegalArgumentException(SR.RETRIEVE_MUST_BE_ONLY_OPERATION_IN_BATCH); } else { this.hasQuery = true; } } this.containsWrites = op.getOperationType() != TableOperationType.RETRIEVE; }public void replace(final TableEntity entity) { this.lockToPartitionKey(entity.getPartitionKey()); this.add(TableOperation.replace(entity)); }@Override public boolean removeAll(java.util.Collection c) { boolean ret = super.removeAll(c); checkResetEntityLocks(); return ret; }@Override public TableOperation remove(int index) { TableOperation op = super.remove(index); checkResetEntityLocks(); return op; }public void merge(final TableEntity entity) { this.lockToPartitionKey(entity.getPartitionKey()); this.add(TableOperation.merge(entity)); }public void insertOrReplace(final TableEntity entity) { this.lockToPartitionKey(entity.getPartitionKey()); this.add(TableOperation.insertOrReplace(entity)); }public void insertOrMerge(final TableEntity entity) { this.lockToPartitionKey(entity.getPartitionKey()); this.add(TableOperation.insertOrMerge(entity)); }public void insert(final TableEntity entity, boolean echoContent) { this.lockToPartitionKey(entity.getPartitionKey()); this.add(TableOperation.insert(entity, echoContent)); }public void delete(final TableEntity entity) { this.lockToPartitionKey(entity.getPartitionKey()); this.add(TableOperation.delete(entity)); }public StorageExtendedErrorInformation parseErrorDetails() { try { if (this.getConnection() == null || this.getConnection().getErrorStream() == null) { return null; } return StorageErrorHandler.getExtendedErrorInformation(this.getConnection().getErrorStream()); } catch (final Exception e) { return null; } }public R postProcessResponse(HttpURLConnection connection, P parentObject, C client, OperationContext context, R storageObject) throws Exception { return storageObject; }protected final StorageException materializeException(final OperationContext opContext) { if (this.getException() != null) { return this.getException(); } return StorageException.translateException(this, null, opContext); }protected final void initialize(OperationContext opContext) { RequestResult currResult = new RequestResult(); this.setResult(currResult); opContext.appendRequestResult(currResult); this.setException(null); this.setNonExceptionedRetryableFailure(false); this.setIsSent(false); }protected String generateRequestIdentityWithTable(final String tableName) throws StorageException { return String.format("%s(%s)", tableName, generateRequestIdentity(false, null)); }protected String generateRequestIdentity(boolean isSingleIndexEntry, final String entryName) throws StorageException { if (isSingleIndexEntry) { return String.format("'%s'", entryName.replace("'", "''")); } if (this.opType == TableOperationType.INSERT) { return Constants.EMPTY_STRING; } else { String pk = null; String rk = null; if (this.opType == TableOperationType.RETRIEVE) { final QueryTableOperation qOp = (QueryTableOperation) this; pk = qOp.getPartitionKey(); rk = qOp.getRowKey(); } else { pk = this.getEntity().getPartitionKey(); rk = this.getEntity().getRowKey(); } return String.format("%s='%s',%s='%s'", TableConstants.PARTITION_KEY, pk.replace("'", "''"), TableConstants.ROW_KEY, rk.replace("'", "''")); } }public String generateSharedAccessSignature(SharedAccessAccountPolicy policy) throws InvalidKeyException, StorageException { if (!StorageCredentialsHelper.canCredentialsSignRequest(this.getCredentials())) { throw new IllegalArgumentException(SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY); } final String sig = SharedAccessSignatureHelper.generateSharedAccessSignatureHashForAccount( this.credentials.getAccountName(), policy, this.getCredentials()); final UriQueryBuilder sasBuilder = SharedAccessSignatureHelper.generateSharedAccessSignatureForAccount(policy, sig); return sasBuilder.toString(); }public CloudTableClient createCloudTableClient() { if (this.getTableStorageUri() == null) { throw new IllegalArgumentException(SR.TABLE_ENDPOINT_NOT_CONFIGURED); } if (this.credentials == null) { throw new IllegalArgumentException(SR.MISSING_CREDENTIALS); } if (!StorageCredentialsHelper.canCredentialsGenerateClient(this.credentials)) { throw new IllegalArgumentException(SR.CREDENTIALS_CANNOT_SIGN_REQUEST); } return new CloudTableClient(this.getTableStorageUri(), this.getCredentials()); }public CloudQueueClient createCloudQueueClient() { if (this.getQueueStorageUri() == null) { throw new IllegalArgumentException(SR.QUEUE_ENDPOINT_NOT_CONFIGURED); } if (this.credentials == null) { throw new IllegalArgumentException(SR.MISSING_CREDENTIALS); } if (!StorageCredentialsHelper.canCredentialsGenerateClient(this.credentials)) { throw new IllegalArgumentException(SR.CREDENTIALS_CANNOT_SIGN_REQUEST); } return new CloudQueueClient(this.getQueueStorageUri(), this.getCredentials()); }public CloudFileClient createCloudFileClient() { if (this.getFileStorageUri() == null) { throw new IllegalArgumentException(SR.FILE_ENDPOINT_NOT_CONFIGURED); } if (this.credentials == null) { throw new IllegalArgumentException(SR.MISSING_CREDENTIALS); } if (!StorageCredentialsHelper.canCredentialsGenerateClient(this.credentials)) { throw new IllegalArgumentException(SR.CREDENTIALS_CANNOT_SIGN_REQUEST); } return new CloudFileClient(this.getFileStorageUri(), this.getCredentials()); }public CloudBlobClient createCloudBlobClient() { if (this.getBlobStorageUri() == null) { throw new IllegalArgumentException(SR.BLOB_ENDPOINT_NOT_CONFIGURED); } if (this.credentials == null) { throw new IllegalArgumentException(SR.MISSING_CREDENTIALS); } return new CloudBlobClient(this.getBlobStorageUri(), this.getCredentials()); }public CloudAnalyticsClient createCloudAnalyticsClient() { if (this.getBlobStorageUri() == null) { throw new IllegalArgumentException(SR.BLOB_ENDPOINT_NOT_CONFIGURED); } if (this.getTableStorageUri() == null) { throw new IllegalArgumentException(SR.TABLE_ENDPOINT_NOT_CONFIGURED); } if (this.credentials == null) { throw new IllegalArgumentException(SR.MISSING_CREDENTIALS); } return new CloudAnalyticsClient(this.getBlobStorageUri(), this.getTableStorageUri(), this.getCredentials()); } �private static CloudStorageAccount tryConfigureDevStore(final Map settings) throws URISyntaxException { if (matchesSpecification( settings, allRequired(USE_DEVELOPMENT_STORAGE_NAME), optional(DEVELOPMENT_STORAGE_PROXY_URI_NAME))) { if (!Boolean.parseBoolean(settings.get(USE_DEVELOPMENT_STORAGE_NAME))) { throw new IllegalArgumentException(SR.INVALID_CONNECTION_STRING_DEV_STORE_NOT_TRUE); } URI devStoreProxyUri = null; if (settings.containsKey(DEVELOPMENT_STORAGE_PROXY_URI_NAME)) { devStoreProxyUri = new URI(settings.get(DEVELOPMENT_STORAGE_PROXY_URI_NAME)); } return getDevelopmentStorageAccount(devStoreProxyUri); } else { return null; } }private static String getDNS(String service, String base) { if (base == null) { base = DEFAULT_DNS; } return String.format(DNS_NAME_FORMAT, service, base); }@DoesServiceRequest private synchronized void writeInternal(final byte[] data, int offset, int length) throws IOException { while (length > 0) { this.checkStreamState(); final int availableBufferBytes = this.internalWriteThreshold - this.currentBufferedBytes; final int nextWrite = Math.min(availableBufferBytes, length); // If we need to set MD5 then update the digest accordingly if (this.options.getStoreFileContentMD5()) { this.md5Digest.update(data, offset, nextWrite); } this.outBuffer.write(data, offset, nextWrite); this.currentBufferedBytes += nextWrite; offset += nextWrite; length -= nextWrite; if (this.currentBufferedBytes == this.internalWriteThreshold) { this.dispatchWrite(this.internalWriteThreshold); } } }@DoesServiceRequest public void write(final InputStream sourceStream, final long writeLength) throws IOException, StorageException { Utility.writeToOutputStream(sourceStream, this, writeLength, false, false, this.opContext, this.options, false); }@Override @DoesServiceRequest public void write(final byte[] data, final int offset, final int length) throws IOException { if (offset < 0 || length < 0 || length > data.length - offset) { throw new IndexOutOfBoundsException(); } this.writeInternal(data, offset, length); }private void waitForTaskToComplete() throws IOException { try { final Future future = this.completionService.take(); future.get(); } catch (final InterruptedException e) { throw Utility.initIOException(e); } catch (final ExecutionException e) { throw Utility.initIOException(e); } this.outstandingRequests--; }@Override @DoesServiceRequest public synchronized void flush() throws IOException { this.checkStreamState(); // Dispatch a write for the current bytes in the buffer this.dispatchWrite(this.currentBufferedBytes); // Waits for all submitted tasks to complete while (this.outstandingRequests > 0) { // Wait for a task to complete this.waitForTaskToComplete(); // If that task threw an error, fail fast this.checkStreamState(); } }@DoesServiceRequest private synchronized void dispatchWrite(final int writeLength) throws IOException { if (writeLength == 0) { return; } Callable worker = null; if (this.outstandingRequests > this.options.getConcurrentRequestCount() * 2) { this.waitForTaskToComplete(); } final ByteArrayInputStream bufferRef = new ByteArrayInputStream(this.outBuffer.toByteArray()); final CloudFile fileRef = this.parentFileRef; long tempOffset = this.currentOffset; long tempLength = writeLength; final long opWriteLength = tempLength; final long opOffset = tempOffset; this.currentOffset += writeLength; worker = new Callable() { @Override public Void call() { try { fileRef.uploadRange(bufferRef, opOffset, opWriteLength, FileOutputStream.this.accessCondition, FileOutputStream.this.options, FileOutputStream.this.opContext); } catch (final IOException e) { synchronized (FileOutputStream.this.lastErrorLock) { FileOutputStream.this.streamFaulted = true; FileOutputStream.this.lastError = e; } } catch (final StorageException e) { synchronized (FileOutputStream.this.lastErrorLock) { FileOutputStream.this.streamFaulted = true; FileOutputStream.this.lastError = Utility.initIOException(e); } } catch (URISyntaxException e) { synchronized (FileOutputStream.this.lastErrorLock) { FileOutputStream.this.streamFaulted = true; FileOutputStream.this.lastError = Utility.initIOException(e); } } return null; } }; // Do work and reset buffer. this.completionService.submit(worker); this.outstandingRequests++; this.currentBufferedBytes = 0; this.outBuffer = new ByteArrayOutputStream(); }@DoesServiceRequest private void commit() throws StorageException, URISyntaxException { if (this.options.getStoreFileContentMD5()) { this.parentFileRef.getProperties().setContentMD5(Base64.encode(this.md5Digest.digest())); } this.parentFileRef.uploadProperties(this.accessCondition, this.options, this.opContext); }@Override @DoesServiceRequest public void close() throws IOException { try { // if the user has already closed the stream, this will throw a STREAM_CLOSED exception // if an exception was thrown by any thread in the threadExecutor, realize it now this.checkStreamState(); // flush any remaining data this.flush(); // shut down the ExecutorService. this.threadExecutor.shutdown(); // try to commit the file try { this.commit(); } catch (final StorageException e) { throw Utility.initIOException(e); } catch (URISyntaxException e) { throw Utility.initIOException(e); } } finally { // if close() is called again, an exception will be thrown synchronized (this.lastErrorLock) { this.streamFaulted = true; this.lastError = new IOException(SR.STREAM_CLOSED); } // if an exception was thrown and the executor was not yet closed, call shutDownNow() to cancel all tasks // and shutdown the ExecutorService if (!this.threadExecutor.isShutdown()) { this.threadExecutor.shutdownNow(); } } }public static HttpURLConnection setServiceProperties(final URI uri, final RequestOptions options, UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { if (builder == null) { builder = new UriQueryBuilder(); } builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.PROPERTIES); builder.add(Constants.QueryConstants.RESOURCETYPE, SERVICE); final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext); retConnection.setDoOutput(true); retConnection.setRequestMethod(Constants.HTTP_PUT); return retConnection; }public static HttpURLConnection setMetadata(final URI uri, final RequestOptions options, UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { if (builder == null) { builder = new UriQueryBuilder(); } builder.add(Constants.QueryConstants.COMPONENT, METADATA); final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext); retConnection.setFixedLengthStreamingMode(0); retConnection.setDoOutput(true); retConnection.setRequestMethod(Constants.HTTP_PUT); return retConnection; }public static String getUserAgent() { if (userAgent == null) { String userAgentComment = String.format(Utility.LOCALE_US, "(Android %s; %s; %s)", android.os.Build.VERSION.RELEASE, android.os.Build.BRAND, android.os.Build.MODEL); userAgent = String.format("%s/%s %s", Constants.HeaderConstants.USER_AGENT_PREFIX, Constants.HeaderConstants.USER_AGENT_VERSION, userAgentComment); } return userAgent; }public static HttpURLConnection getServiceProperties(final URI uri, final RequestOptions options, UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { if (builder == null) { builder = new UriQueryBuilder(); } builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.PROPERTIES); builder.add(Constants.QueryConstants.RESOURCETYPE, SERVICE); final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext); retConnection.setRequestMethod(Constants.HTTP_GET); return retConnection; }public static HttpURLConnection delete(final URI uri, final RequestOptions options, UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { if (builder == null) { builder = new UriQueryBuilder(); } final HttpURLConnection retConnection = createURLConnection(uri, options, builder, opContext); retConnection.setRequestMethod(Constants.HTTP_DELETE); return retConnection; }public static HttpURLConnection createURLConnection(final URI uri, final RequestOptions options, UriQueryBuilder builder, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { if (builder == null) { builder = new UriQueryBuilder(); } if (options.getTimeoutIntervalInMs() != null && options.getTimeoutIntervalInMs() != 0) { builder.add(TIMEOUT, String.valueOf(options.getTimeoutIntervalInMs() / 1000)); } final URL resourceUrl = builder.addToURI(uri).toURL(); // Get the proxy settings Proxy proxy = OperationContext.getDefaultProxy(); if (opContext != null && opContext.getProxy() != null) { proxy = opContext.getProxy(); } // Set up connection, optionally with proxy settings final HttpURLConnection retConnection; if (proxy != null) { retConnection = (HttpURLConnection) resourceUrl.openConnection(proxy); } else { retConnection = (HttpURLConnection) resourceUrl.openConnection(); } /* * ReadTimeout must be explicitly set to avoid a bug in JDK 6. In certain cases, this bug causes an immediate * read timeout exception to be thrown even if ReadTimeout is not set. * * Both connect and read timeout are set to the same value as we have no way of knowing how to partition * the remaining time between these operations. The user can override these timeouts using the SendingRequest * event handler if more control is desired. */ int timeout = Utility.getRemainingTimeout(options.getOperationExpiryTimeInMs(), options.getTimeoutIntervalInMs()); retConnection.setReadTimeout(timeout); retConnection.setConnectTimeout(timeout); // Note : by default sends Accept behavior as text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2 retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT, Constants.HeaderConstants.XML_TYPE); retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT_CHARSET, Constants.UTF8_CHARSET); // Note: by default sends Accept-Encoding as gzip retConnection.setRequestProperty(Constants.HeaderConstants.ACCEPT_ENCODING, Constants.EMPTY_STRING); // Note : by default sends Content-type behavior as application/x-www-form-urlencoded for posts. retConnection.setRequestProperty(Constants.HeaderConstants.CONTENT_TYPE, Constants.EMPTY_STRING); retConnection.setRequestProperty(Constants.HeaderConstants.STORAGE_VERSION_HEADER, Constants.HeaderConstants.TARGET_STORAGE_VERSION); retConnection.setRequestProperty(Constants.HeaderConstants.USER_AGENT, getUserAgent()); retConnection.setRequestProperty(Constants.HeaderConstants.CLIENT_REQUEST_ID_HEADER, opContext.getClientRequestID()); return retConnection; }public static void addOptionalHeader(final HttpURLConnection request, final String name, final String value) { if (value != null && !value.equals(Constants.EMPTY_STRING)) { request.setRequestProperty(name, value); } }public URI addToURI(final URI uri) throws URISyntaxException, StorageException { final String origRawQuery = uri.getRawQuery(); final String rawFragment = uri.getRawFragment(); final String uriString = uri.resolve(uri).toASCIIString(); final HashMap origQueryMap = PathUtility.parseQueryString(origRawQuery); // Try/Insert original queries to map for (final Entry entry : origQueryMap.entrySet()) { for (final String val : entry.getValue()) { this.insertKeyValue(entry.getKey(), val); } } final StringBuilder retBuilder = new StringBuilder(); // has a fragment if (Utility.isNullOrEmpty(origRawQuery) && !Utility.isNullOrEmpty(rawFragment)) { final int bangDex = uriString.indexOf('#'); retBuilder.append(uriString.substring(0, bangDex)); } else if (!Utility.isNullOrEmpty(origRawQuery)) { // has a query final int queryDex = uriString.indexOf('?'); retBuilder.append(uriString.substring(0, queryDex)); } else { // no fragment or query retBuilder.append(uriString); if (uri.getRawPath().length() <= 0) { retBuilder.append("/"); } } final String finalQuery = this.toString(); if (finalQuery.length() > 0) { retBuilder.append("?"); retBuilder.append(finalQuery); } if (!Utility.isNullOrEmpty(rawFragment)) { retBuilder.append("#"); retBuilder.append(rawFragment); } return new URI(retBuilder.toString()); }public void add(final String name, final String value) throws StorageException { if (Utility.isNullOrEmpty(name)) { throw new IllegalArgumentException(SR.QUERY_PARAMETER_NULL_OR_EMPTY); } this.insertKeyValue(name, value); }private static void writeMIMEContentType(final OutputStreamWriter outWriter, final String boundaryName) throws IOException { outWriter.write(String.format("Content-Type: multipart/mixed; boundary=%s\r\n", boundaryName)); }private static void writeMIMEBoundaryClosure(final OutputStreamWriter outWriter, final String boundaryID) throws IOException { outWriter.write(String.format("--%s--\r\n", boundaryID)); }private static void writeMIMEBoundary(final OutputStreamWriter outWriter, final String boundaryID) throws IOException { outWriter.write(String.format("--%s\r\n", boundaryID)); }protected void setResolver(final EntityResolver resolver) { Utility.assertNotNull(SR.QUERY_REQUIRES_VALID_CLASSTYPE_OR_RESOLVER, resolver); this.resolver = resolver; }protected void setClazzType(final Class clazzType) { Utility.assertNotNull("clazzType", clazzType); Utility.checkNullaryCtor(clazzType); this.clazzType = clazzType; }@Override @DoesServiceRequest public boolean hasNext() { while (this.currentSegment == null || (!this.currentSegmentIterator.hasNext() && this.currentSegment != null && this.currentSegment .getHasMoreResults())) { try { this.currentSegment = ExecutionEngine.executeWithRetry(this.client, this.parentObject, this.segmentGenerator, this.policyFactory, this.opContext); } catch (final StorageException e) { final NoSuchElementException ex = new NoSuchElementException(SR.ENUMERATION_ERROR); ex.initCause(e); throw ex; } this.currentSegmentIterator = this.currentSegment.getResults().iterator(); if (!this.currentSegmentIterator.hasNext() && !this.currentSegment.getHasMoreResults()) { return false; } } return this.currentSegmentIterator.hasNext(); }@Override public RetryPolicy createInstance(final OperationContext opContext) { return new RetryExponentialRetry(this.resolvedMinBackoff, this.deltaBackoffIntervalInMs, this.resolvedMaxBackoff, this.maximumAttempts); } private boolean tryPeekDelimiter(char delimiter) throws IOException { if (this.isEndOfFile()) { throw new EOFException(SR.LOG_STREAM_END_ERROR); } else { if ((char) this.peek() != delimiter) { return false; } else { return true; } } }private void readDelimiter(char delimiter) throws IOException { if (this.isEndOfFile()) { throw new EOFException(SR.LOG_STREAM_END_ERROR); } else { int read = this.read(); if (read == -1 || (char) read != delimiter) { throw new IllegalStateException(SR.LOG_STREAM_DELIMITER_ERROR); } } }public URI readUri() throws URISyntaxException, IOException { String temp = this.readField(true /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return new URI(Html.fromHtml(temp).toString()); } }public Long readLong() throws IOException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return Long.parseLong(temp); } }public Integer readInteger() throws IOException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return Integer.parseInt(temp); } }public UUID readUuid() throws IOException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return UUID.fromString(temp); } }public Double readDouble() throws IOException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return Double.parseDouble(temp); } }public Date readDate(DateFormat format) throws IOException, ParseException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return format.parse(temp); } }public Boolean readBoolean() throws IOException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return Boolean.parseBoolean(temp); } }public String readQuotedString() throws IOException { String temp = this.readField(true /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return temp; } }public String readString() throws IOException { String temp = this.readField(false /* isQuotedString */); if (Utility.isNullOrEmpty(temp)) { return null; } else { return temp; } }protected static final QueueRequestOptions populateAndApplyDefaults(QueueRequestOptions options, final CloudQueueClient client) { QueueRequestOptions modifiedOptions = new QueueRequestOptions(options); RequestOptions.populateRequestOptions(modifiedOptions, client.getDefaultRequestOptions(), true /* setStartTime */); QueueRequestOptions.applyDefaults(modifiedOptions); return modifiedOptions; }public static RequestLocationMode getListingLocationMode(ResultContinuation token) { if ((token != null) && token.getTargetLocation() != null) { switch (token.getTargetLocation()) { case PRIMARY: return RequestLocationMode.PRIMARY_ONLY; case SECONDARY: return RequestLocationMode.SECONDARY_ONLY; default: throw new IllegalArgumentException(String.format(SR.ARGUMENT_OUT_OF_RANGE_ERROR, "token", token.getTargetLocation())); } } return RequestLocationMode.PRIMARY_OR_SECONDARY; }public static Date parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch(dateString.length()) { case 28: // "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"-> [2012-01-04T23:21:59.1234567Z] length = 28 case 27: // "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"-> [2012-01-04T23:21:59.123456Z] length = 27 case 26: // "yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'"-> [2012-01-04T23:21:59.12345Z] length = 26 case 25: // "yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'"-> [2012-01-04T23:21:59.1234Z] length = 25 case 24: // "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"-> [2012-01-04T23:21:59.123Z] length = 24 dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: // "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"-> [2012-01-04T23:21:59.12Z] length = 23 // SS is assumed to be milliseconds, so a trailing 0 is necessary dateString = dateString.replace("Z", "0"); break; case 22: // "yyyy-MM-dd'T'HH:mm:ss.S'Z'"-> [2012-01-04T23:21:59.1Z] length = 22 // S is assumed to be milliseconds, so trailing 0's are necessary dateString = dateString.replace("Z", "00"); break; case 20: // "yyyy-MM-dd'T'HH:mm:ss'Z'"-> [2012-01-04T23:21:59Z] length = 20 pattern = Utility.ISO8601_PATTERN; break; case 17: // "yyyy-MM-dd'T'HH:mm'Z'"-> [2012-01-04T23:21Z] length = 17 pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(SR.INVALID_DATE_STRING, dateString)); } final DateFormat format = new SimpleDateFormat(pattern, Utility.LOCALE_US); format.setTimeZone(UTC_ZONE); try { return format.parse(dateString); } catch (final ParseException e) { throw new IllegalArgumentException(String.format(SR.INVALID_DATE_STRING, dateString), e); } }public static String trimStart(final String value) { int spaceDex = 0; while (spaceDex < value.length() && value.charAt(spaceDex) == ' ') { spaceDex++; } return value.substring(spaceDex); }protected static String trimEnd(final String value, final char trimChar) { int stopDex = value.length() - 1; while (stopDex > 0 && value.charAt(stopDex) == trimChar) { stopDex--; } return stopDex == value.length() - 1 ? value : value.substring(stopDex); }public static void logHttpResponse(HttpURLConnection conn, OperationContext opContext) throws IOException { if (Logger.shouldLog(opContext, Log.VERBOSE)) { try { StringBuilder bld = new StringBuilder(); // This map's null key will contain the response code and message for (Map.Entry> header : conn.getHeaderFields().entrySet()) { if (header.getKey() != null) { bld.append(header.getKey()); bld.append(": "); } for (int i = 0; i < header.getValue().size(); i++) { bld.append(header.getValue().get(i)); if (i < header.getValue().size() - 1) { bld.append(","); } } bld.append('\n'); } Logger.verbose(opContext, bld.toString()); } catch (Exception e) { // Do nothing } } }public static void logHttpError(StorageException ex, OperationContext opContext) { if (Logger.shouldLog(opContext, Log.DEBUG)) { try { StringBuilder bld = new StringBuilder(); bld.append("Error response received. "); bld.append("HttpStatusCode= "); bld.append(ex.getHttpStatusCode()); bld.append(", HttpStatusMessage= "); bld.append(ex.getMessage()); bld.append(", ErrorCode= "); bld.append(ex.getErrorCode()); StorageExtendedErrorInformation extendedError = ex.getExtendedErrorInformation(); if (extendedError != null) { bld.append(", ExtendedErrorInformation= {ErrorMessage= "); bld.append(extendedError.getErrorMessage()); HashMap details = extendedError.getAdditionalDetails(); if (details != null) { bld.append(", AdditionalDetails= { "); for (Entry detail : details.entrySet()) { bld.append(detail.getKey()); bld.append("= "); for (String value : detail.getValue()) { bld.append(value); } bld.append(","); } bld.setCharAt(bld.length() - 1, '}'); } bld.append("}"); } Logger.debug(opContext, bld.toString()); } catch (Exception e) { // Do nothing } } }public static String safeRelativize(final URI baseURI, final URI toUri) throws URISyntaxException { // For compatibility followed // http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri.aspx // if host and scheme are not identical return from uri if (!baseURI.getHost().equals(toUri.getHost()) || !baseURI.getScheme().equals(toUri.getScheme())) { return toUri.toString(); } final String basePath = baseURI.getPath(); String toPath = toUri.getPath(); int truncatePtr = 1; // Seek to first Difference // int maxLength = Math.min(basePath.length(), toPath.length()); int m = 0; int ellipsesCount = 0; for (; m < basePath.length(); m++) { if (m >= toPath.length()) { if (basePath.charAt(m) == '/') { ellipsesCount++; } } else { if (basePath.charAt(m) != toPath.charAt(m)) { break; } else if (basePath.charAt(m) == '/') { truncatePtr = m + 1; } } } // ../containername and ../containername/{path} should increment the truncatePtr // otherwise toPath will incorrectly begin with /containername if (m < toPath.length() && toPath.charAt(m) == '/') { // this is to handle the empty directory case with the '/' delimiter // for example, ../containername/ and ../containername// should not increment the truncatePtr if (!(toPath.charAt(m - 1) == '/' && basePath.charAt(m - 1) == '/')) { truncatePtr = m + 1; } } if (m == toPath.length()) { // No path difference, return query + fragment return new URI(null, null, null, toUri.getQuery(), toUri.getFragment()).toString(); } else { toPath = toPath.substring(truncatePtr); final StringBuilder sb = new StringBuilder(); while (ellipsesCount > 0) { sb.append("../"); ellipsesCount--; } if (!Utility.isNullOrEmpty(toPath)) { sb.append(toPath); } if (!Utility.isNullOrEmpty(toUri.getQuery())) { sb.append("?"); sb.append(toUri.getQuery()); } if (!Utility.isNullOrEmpty(toUri.getFragment())) { sb.append("#"); sb.append(toUri.getRawFragment()); } return sb.toString(); } }public static Date parseRFC1123DateFromStringInGMT(final String value) throws ParseException { final DateFormat format = new SimpleDateFormat(RFC1123_GMT_PATTERN, Utility.LOCALE_US); format.setTimeZone(GMT_ZONE); return format.parse(value); }public static Date parseDateFromString(final String value, final String pattern, final TimeZone timeZone) throws ParseException { final DateFormat rfc1123Format = new SimpleDateFormat(pattern, Utility.LOCALE_US); rfc1123Format.setTimeZone(timeZone); return rfc1123Format.parse(value); }public static String getStandardHeaderValue(final HttpURLConnection conn, final String headerName) { final String headerValue = conn.getRequestProperty(headerName); // Coalesce null value return headerValue == null ? Constants.EMPTY_STRING : headerValue; }public static StorageException generateNewUnexpectedStorageException(final Exception cause) { final StorageException exceptionRef = new StorageException(StorageErrorCode.NONE.toString(), "Unexpected internal storage client error.", 306, // unused null, null); exceptionRef.initCause(cause); return exceptionRef; }public static String formatETag(final String etag) { if (etag.startsWith("\"") && etag.endsWith("\"")) { return etag; } else { return String.format("\"%s\"", etag); } }private static boolean isHostDnsName(URI uri) { String host = uri.getHost(); for (int i = 0; i < host.length(); i++) { char hostChar = host.charAt(i); if (!Character.isDigit(hostChar) && !(hostChar == '.')) { return true; } } return false; }public static boolean determinePathStyleFromUri(final URI baseURI) { String path = baseURI.getPath(); if (path != null && path.startsWith("/")) { path = path.substring(1); } // if the path is null or empty, this is not path-style if (Utility.isNullOrEmpty(path)) { return false; } // if this contains a port or has a host which is not DNS, this is path-style return pathStylePorts.contains(baseURI.getPort()) || !isHostDnsName(baseURI); }public static int getRemainingTimeout(Long operationExpiryTimeInMs, Integer timeoutIntervalInMs) throws StorageException { if (operationExpiryTimeInMs != null) { long remainingTime = operationExpiryTimeInMs - new Date().getTime(); if (remainingTime > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else if (remainingTime > 0) { return (int) remainingTime; } else { TimeoutException timeoutException = new TimeoutException(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION); StorageException translatedException = new StorageException( StorageErrorCodeStrings.OPERATION_TIMED_OUT, SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION, Constants.HeaderConstants.HTTP_UNUSED_306, null, timeoutException); throw translatedException; } } else if (timeoutIntervalInMs != null) { return timeoutIntervalInMs + Constants.DEFAULT_READ_TIMEOUT; } else { return Constants.DEFAULT_READ_TIMEOUT; } }public static boolean validateMaxExecutionTimeout(Long operationExpiryTimeInMs, long additionalInterval) { if (operationExpiryTimeInMs != null) { long currentTime = new Date().getTime(); return operationExpiryTimeInMs < currentTime + additionalInterval; } return false; }public static void assertGreaterThanOrEqual(final String param, final long value, final long min) { if (value < min) { throw new IllegalArgumentException(String.format(SR.PARAMETER_SHOULD_BE_GREATER_OR_EQUAL, param, min)); } }public static void assertInBounds(final String param, final long value, final long min, final long max) { if (value < min || value > max) { throw new IllegalArgumentException(String.format(SR.PARAMETER_NOT_IN_RANGE, param, min, max)); } }public static void assertContinuationType(final ResultContinuation continuationToken, final ResultContinuationType continuationType) { if (continuationToken != null) { if (!(continuationToken.getContinuationType() == ResultContinuationType.NONE || continuationToken .getContinuationType() == continuationType)) { final String errorMessage = String.format(Utility.LOCALE_US, SR.UNEXPECTED_CONTINUATION_TYPE, continuationToken.getContinuationType(), continuationType); throw new IllegalArgumentException(errorMessage); } } }private static void fireRetryingEvent(OperationContext opContext, HttpURLConnection request, RequestResult result, RetryContext retryContext) { if (opContext.getRetryingEventHandler().hasListeners() || OperationContext.getGlobalRetryingEventHandler().hasListeners()) { RetryingEvent event = new RetryingEvent(opContext, request, result, retryContext); opContext.getRetryingEventHandler().fireEvent(event); OperationContext.getGlobalRetryingEventHandler().fireEvent(event); } }private static void fireRequestCompletedEvent(OperationContext opContext, HttpURLConnection request, RequestResult result) { if (opContext.getRequestCompletedEventHandler().hasListeners() || OperationContext.getGlobalRequestCompletedEventHandler().hasListeners()) { RequestCompletedEvent event = new RequestCompletedEvent(opContext, request, result); opContext.getRequestCompletedEventHandler().fireEvent(event); OperationContext.getGlobalRequestCompletedEventHandler().fireEvent(event); } }private static void fireErrorReceivingResponseEvent(OperationContext opContext, HttpURLConnection request, RequestResult result) { if (opContext.getErrorReceivingResponseEventHandler().hasListeners() || OperationContext.getGlobalErrorReceivingResponseEventHandler().hasListeners()) { ErrorReceivingResponseEvent event = new ErrorReceivingResponseEvent(opContext, request, result); opContext.getErrorReceivingResponseEventHandler().fireEvent(event); OperationContext.getGlobalErrorReceivingResponseEventHandler().fireEvent(event); } }private static void fireResponseReceivedEvent(OperationContext opContext, HttpURLConnection request, RequestResult result) { if (opContext.getResponseReceivedEventHandler().hasListeners() || OperationContext.getGlobalResponseReceivedEventHandler().hasListeners()) { ResponseReceivedEvent event = new ResponseReceivedEvent(opContext, request, result); opContext.getResponseReceivedEventHandler().fireEvent(event); OperationContext.getGlobalResponseReceivedEventHandler().fireEvent(event); } }private static void fireSendingRequestEvent(OperationContext opContext, HttpURLConnection request, RequestResult result) { if (opContext.getSendingRequestEventHandler().hasListeners() || OperationContext.getGlobalSendingRequestEventHandler().hasListeners()) { SendingRequestEvent event = new SendingRequestEvent(opContext, request, result); opContext.getSendingRequestEventHandler().fireEvent(event); OperationContext.getGlobalSendingRequestEventHandler().fireEvent(event); } }public void fireEvent(final EVENT_TYPE event) { for (final StorageEvent listener : this.listeners) { listener.eventOccurred(event); } }static String getHttpVerbForOperation(final TableOperationType operationType) { if (operationType == TableOperationType.INSERT) { return "POST"; } else if (operationType == TableOperationType.DELETE) { return "DELETE"; } else if (operationType == TableOperationType.MERGE || operationType == TableOperationType.INSERT_OR_MERGE) { return "MERGE"; } else if (operationType == TableOperationType.REPLACE || operationType == TableOperationType.INSERT_OR_REPLACE) { return "PUT"; } else if (operationType == TableOperationType.RETRIEVE) { return "GET"; } else { throw new IllegalArgumentException(SR.UNKNOWN_TABLE_OPERATION); } }public static FileAttributes getFileAttributes(final HttpURLConnection request, final StorageUri resourceURI) throws URISyntaxException, ParseException { final FileAttributes fileAttributes = new FileAttributes(); final FileProperties properties = fileAttributes.getProperties(); properties.setCacheControl(request.getHeaderField(Constants.HeaderConstants.CACHE_CONTROL)); properties.setContentDisposition(request.getHeaderField(Constants.HeaderConstants.CONTENT_DISPOSITION)); properties.setContentEncoding(request.getHeaderField(Constants.HeaderConstants.CONTENT_ENCODING)); properties.setContentLanguage(request.getHeaderField(Constants.HeaderConstants.CONTENT_LANGUAGE)); // For range gets, only look at 'x-ms-content-md5' for overall MD5 if (!Utility.isNullOrEmpty(request.getHeaderField(Constants.HeaderConstants.CONTENT_RANGE))) { properties.setContentMD5(request.getHeaderField(FileConstants.FILE_CONTENT_MD5_HEADER)); } else { properties.setContentMD5(request.getHeaderField(Constants.HeaderConstants.CONTENT_MD5)); } properties.setContentType(request.getHeaderField(Constants.HeaderConstants.CONTENT_TYPE)); properties.setEtag(BaseResponse.getEtag(request)); properties.setCopyState(FileResponse.getCopyState(request)); properties.setServerEncrypted( Constants.TRUE.equals(request.getHeaderField(Constants.HeaderConstants.SERVER_ENCRYPTED))); final Calendar lastModifiedCalendar = Calendar.getInstance(Utility.LOCALE_US); lastModifiedCalendar.setTimeZone(Utility.UTC_ZONE); lastModifiedCalendar.setTime(new Date(request.getLastModified())); properties.setLastModified(lastModifiedCalendar.getTime()); final String rangeHeader = request.getHeaderField(Constants.HeaderConstants.CONTENT_RANGE); final String xContentLengthHeader = request.getHeaderField(FileConstants.CONTENT_LENGTH_HEADER); if (!Utility.isNullOrEmpty(rangeHeader)) { properties.setLength(Long.parseLong(rangeHeader.split("/")[1])); } else if (!Utility.isNullOrEmpty(xContentLengthHeader)) { properties.setLength(Long.parseLong(xContentLengthHeader)); } else { // using this instead of the request property since the request // property only returns an int. final String contentLength = request.getHeaderField(Constants.HeaderConstants.CONTENT_LENGTH); if (!Utility.isNullOrEmpty(contentLength)) { properties.setLength(Long.parseLong(contentLength)); } } fileAttributes.setStorageUri(resourceURI); fileAttributes.setMetadata(BaseResponse.getMetadata(request)); return fileAttributes; }public static FileDirectoryAttributes getFileDirectoryAttributes(final HttpURLConnection request, final boolean usePathStyleUris) throws StorageException { final FileDirectoryAttributes directoryAttributes = new FileDirectoryAttributes(); URI tempURI; try { tempURI = PathUtility.stripSingleURIQueryAndFragment(request.getURL().toURI()); } catch (final URISyntaxException e) { final StorageException wrappedUnexpectedException = Utility.generateNewUnexpectedStorageException(e); throw wrappedUnexpectedException; } directoryAttributes.setName(PathUtility.getDirectoryNameFromURI(tempURI, usePathStyleUris)); final FileDirectoryProperties directoryProperties = directoryAttributes.getProperties(); directoryProperties.setEtag(BaseResponse.getEtag(request)); directoryProperties.setLastModified(new Date(request.getLastModified())); directoryAttributes.setMetadata(getMetadata(request)); directoryProperties.setServerEncrypted( Constants.TRUE.equals(request.getHeaderField(Constants.HeaderConstants.SERVER_ENCRYPTED))); return directoryAttributes; }public static FileShareAttributes getFileShareAttributes(final HttpURLConnection request, final boolean usePathStyleUris) throws StorageException { final FileShareAttributes shareAttributes = new FileShareAttributes(); final FileShareProperties shareProperties = shareAttributes.getProperties(); shareProperties.setEtag(BaseResponse.getEtag(request)); shareProperties.setShareQuota(parseShareQuota(request)); shareProperties.setLastModified(new Date(request.getLastModified())); shareAttributes.setMetadata(getMetadata(request)); return shareAttributes; }public static CopyState getCopyState(final HttpURLConnection request) throws URISyntaxException, ParseException { String copyStatusString = request.getHeaderField(Constants.HeaderConstants.COPY_STATUS); if (!Utility.isNullOrEmpty(copyStatusString)) { final CopyState copyState = new CopyState(); copyState.setStatus(CopyStatus.parse(copyStatusString)); copyState.setCopyId(request.getHeaderField(Constants.HeaderConstants.COPY_ID)); copyState.setStatusDescription(request.getHeaderField(Constants.HeaderConstants.COPY_STATUS_DESCRIPTION)); final String copyProgressString = request.getHeaderField(Constants.HeaderConstants.COPY_PROGRESS); if (!Utility.isNullOrEmpty(copyProgressString)) { String[] progressSequence = copyProgressString.split("/"); copyState.setBytesCopied(Long.parseLong(progressSequence[0])); copyState.setTotalBytes(Long.parseLong(progressSequence[1])); } final String copySourceString = request.getHeaderField(Constants.HeaderConstants.COPY_SOURCE); if (!Utility.isNullOrEmpty(copySourceString)) { copyState.setSource(new URI(copySourceString)); } final String copyCompletionTimeString = request.getHeaderField(Constants.HeaderConstants.COPY_COMPLETION_TIME); if (!Utility.isNullOrEmpty(copyCompletionTimeString)) { copyState.setCompletionTime(Utility.parseRFC1123DateFromStringInGMT(copyCompletionTimeString)); } return copyState; } else { return null; } }public static HashMap getAccessIdentifiers(final InputStream stream, final Class cls) throws ParserConfigurationException, SAXException, IOException { SAXParser saxParser = Utility.getSAXParser(); SharedAccessPolicyHandler handler = new SharedAccessPolicyHandler(cls); saxParser.parse(stream, handler); return handler.policies; }private static HashMap parseJsonErrorException(JsonParser parser) throws JsonParseException, IOException { HashMap additionalDetails = new HashMap(); parser.nextToken(); JsonUtilities.assertIsStartObjectJsonToken(parser); parser.nextToken(); JsonUtilities.assertIsFieldNameJsonToken(parser); while (parser.getCurrentToken() != JsonToken.END_OBJECT) { if (parser.getCurrentName().equals(TableConstants.ErrorConstants.ERROR_MESSAGE)) { parser.nextToken(); additionalDetails.put(TableConstants.ErrorConstants.ERROR_MESSAGE, new String[] { parser.getValueAsString() }); } else if (parser.getCurrentName().equals(TableConstants.ErrorConstants.ERROR_EXCEPTION_TYPE)) { parser.nextToken(); additionalDetails.put(TableConstants.ErrorConstants.ERROR_EXCEPTION_TYPE, new String[] { parser.getValueAsString() }); } else if (parser.getCurrentName().equals(TableConstants.ErrorConstants.ERROR_EXCEPTION_STACK_TRACE)) { parser.nextToken(); additionalDetails .put(Constants.ERROR_EXCEPTION_STACK_TRACE, new String[] { parser.getValueAsString() }); } parser.nextToken(); } return additionalDetails; }public static StorageExtendedErrorInformation parseErrorDetails(StorageRequest request) { try { if (request == null || request.getConnection().getErrorStream() == null) { return null; } return getExtendedErrorInformation(new InputStreamReader( request.getConnection().getErrorStream()), TablePayloadFormat.Json); } catch (Exception e) { return null; } }public static StorageExtendedErrorInformation getExtendedErrorInformation(final Reader reader, final TablePayloadFormat format) throws JsonParseException, IOException { JsonFactory jsonFactory = new JsonFactory(); JsonParser parser = jsonFactory.createParser(reader); try { final StorageExtendedErrorInformation errorInfo = new StorageExtendedErrorInformation(); if (!parser.hasCurrentToken()) { parser.nextToken(); } JsonUtilities.assertIsStartObjectJsonToken(parser); parser.nextToken(); JsonUtilities.assertIsFieldNameJsonToken(parser); JsonUtilities.assertIsExpectedFieldName(parser, "odata.error"); // start getting extended error information parser.nextToken(); JsonUtilities.assertIsStartObjectJsonToken(parser); // get code parser.nextValue(); JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_CODE); errorInfo.setErrorCode(parser.getValueAsString()); // get message parser.nextToken(); JsonUtilities.assertIsFieldNameJsonToken(parser); JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.ERROR_MESSAGE); parser.nextToken(); JsonUtilities.assertIsStartObjectJsonToken(parser); parser.nextValue(); JsonUtilities.assertIsExpectedFieldName(parser, "lang"); parser.nextValue(); JsonUtilities.assertIsExpectedFieldName(parser, "value"); errorInfo.setErrorMessage(parser.getValueAsString()); parser.nextToken(); JsonUtilities.assertIsEndObjectJsonToken(parser); parser.nextToken(); // get innererror if it exists if (parser.getCurrentToken() == JsonToken.FIELD_NAME) { JsonUtilities.assertIsExpectedFieldName(parser, TableConstants.ErrorConstants.INNER_ERROR); errorInfo.getAdditionalDetails().putAll(parseJsonErrorException(parser)); parser.nextToken(); } // end code object JsonUtilities.assertIsEndObjectJsonToken(parser); // end odata.error object parser.nextToken(); JsonUtilities.assertIsEndObjectJsonToken(parser); return errorInfo; } finally { parser.close(); } }public static boolean isServerRequestEncrypted(HttpURLConnection request) { return Constants.TRUE.equals(request.getHeaderField(Constants.HeaderConstants.SERVER_REQUEST_ENCRYPTED)); }public static HashMap getMetadata(final HttpURLConnection request) { return getValuesByHeaderPrefix(request, Constants.HeaderConstants.PREFIX_FOR_STORAGE_METADATA); }public static String getDate(final HttpURLConnection request) { final String retString = request.getHeaderField("Date"); return retString == null ? request.getHeaderField(Constants.HeaderConstants.DATE) : retString; }public static void setReflectedEntityCacheDisabled(boolean disableReflectedEntityCache) { if (TableServiceEntity.reflectedEntityCache != null && disableReflectedEntityCache) { TableServiceEntity.reflectedEntityCache.clear(); } TableServiceEntity.disableReflectedEntityCache = disableReflectedEntityCache; }private Iterable listSharesWithPrefix(final String prefix, final EnumSet detailsIncluded, FileRequestOptions options, OperationContext opContext) { if (opContext == null) { opContext = new OperationContext(); } opContext.initialize(); options = FileRequestOptions.populateAndApplyDefaults(options, this); SegmentedStorageRequest segmentedRequest = new SegmentedStorageRequest(); return new LazySegmentedIterable(this.listSharesWithPrefixSegmentedImpl( prefix, detailsIncluded, null, options, segmentedRequest), this, null, options.getRetryPolicyFactory(), opContext); }@DoesServiceRequest public ResultSegment listSharesSegmented(final String prefix) throws StorageException { return this.listSharesWithPrefixSegmented(prefix, EnumSet.noneOf(ShareListingDetails.class), null, null /* continuationToken */, null /* options */, null /* opContext */); }@DoesServiceRequest public ResultSegment listSharesSegmented() throws StorageException { return this.listSharesSegmented(null, EnumSet.noneOf(ShareListingDetails.class), null, null /* continuationToken */, null /* options */, null /* opContext */); }@DoesServiceRequest public Iterable listShares(final String prefix, final EnumSet detailsIncluded, final FileRequestOptions options, final OperationContext opContext) { return this.listSharesWithPrefix(prefix, detailsIncluded, options, opContext); }@DoesServiceRequest public Iterable listShares(final String prefix) { return this.listSharesWithPrefix(prefix, EnumSet.noneOf(ShareListingDetails.class), null /* options */, null /* opContext */); }public static void validateTableName(String tableName) { if (Utility.isNullOrEmptyOrWhitespace(tableName)) { throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.RESOURCE_NAME_EMPTY, SR.TABLE)); } if (tableName.length() < NameValidator.CONTAINER_SHARE_QUEUE_TABLE_MIN_LENGTH || tableName.length() > NameValidator.CONTAINER_SHARE_QUEUE_TABLE_MAX_LENGTH) { throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.INVALID_RESOURCE_NAME_LENGTH, SR.TABLE, NameValidator.CONTAINER_SHARE_QUEUE_TABLE_MIN_LENGTH, NameValidator.CONTAINER_SHARE_QUEUE_TABLE_MAX_LENGTH)); } if (!(NameValidator.TABLE_REGEX.matcher(tableName).matches() || NameValidator.METRICS_TABLE_REGEX.matcher(tableName).matches() || tableName.equalsIgnoreCase("$MetricsCapacityBlob"))) { throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.INVALID_RESOURCE_NAME, SR.TABLE)); } }public static void validateFileName(String fileName) { NameValidator.ValidateFileDirectoryHelper(fileName, SR.FILE); if (fileName.endsWith("/")) { throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.INVALID_RESOURCE_NAME, SR.FILE)); } for (String s : NameValidator.RESERVED_FILE_NAMES) { if (s.equalsIgnoreCase(fileName)) { throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.INVALID_RESOURCE_RESERVED_NAME, SR.FILE)); } } }public static void validateBlobName(String blobName) { if (Utility.isNullOrEmptyOrWhitespace(blobName)) { throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.RESOURCE_NAME_EMPTY, SR.BLOB)); } if (blobName.length() < NameValidator.BLOB_FILE_DIRECTORY_MIN_LENGTH || blobName.length() > NameValidator.BLOB_MAX_LENGTH) { throw new IllegalArgumentException(String.format(Utility.LOCALE_US, SR.INVALID_RESOURCE_NAME_LENGTH, SR.BLOB, NameValidator.BLOB_FILE_DIRECTORY_MIN_LENGTH, NameValidator.BLOB_MAX_LENGTH)); } int slashCount = 0; for (int i = 0; i < blobName.length(); i++) { if (blobName.charAt(i) == '/') { slashCount++; } } if (slashCount >= 254) { throw new IllegalArgumentException(SR.TOO_MANY_PATH_SEGMENTS); } }public static void validateContainerName(String containerName) { if (!("$root".equals(containerName) || "$logs".equals(containerName))) { NameValidator.validateShareContainerQueueHelper(containerName, SR.CONTAINER); } }public static boolean validateIsBase64String(final String data) { if (data == null || data.length() % 4 != 0) { return false; } for (int m = 0; m < data.length(); m++) { final byte charByte = (byte) data.charAt(m); // pad char detected if (DECODE_64[charByte] == -2) { if (m < data.length() - 2) { return false; } else if (m == data.length() - 2 && DECODE_64[(byte) data.charAt(m + 1)] != -2) { return false; } } if (charByte < 0 || DECODE_64[charByte] == -1) { return false; } } return true; }public static String encode(final Byte[] data) { final StringBuilder builder = new StringBuilder(); final int dataRemainder = data.length % 3; int j = 0; int n = 0; for (; j < data.length; j += 3) { if (j < data.length - dataRemainder) { n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8) + (data[j + 2] & 0xFF); } else { if (dataRemainder == 1) { n = (data[j] & 0xFF) << 16; } else if (dataRemainder == 2) { n = ((data[j] & 0xFF) << 16) + ((data[j + 1] & 0xFF) << 8); } } // Left here for readability // byte char1 = (byte) ((n >>> 18) & 0x3F); // byte char2 = (byte) ((n >>> 12) & 0x3F); // byte char3 = (byte) ((n >>> 6) & 0x3F); // byte char4 = (byte) (n & 0x3F); builder.append(BASE_64_CHARS.charAt((byte) ((n >>> 18) & 0x3F))); builder.append(BASE_64_CHARS.charAt((byte) ((n >>> 12) & 0x3F))); builder.append(BASE_64_CHARS.charAt((byte) ((n >>> 6) & 0x3F))); builder.append(BASE_64_CHARS.charAt((byte) (n & 0x3F))); } final int bLength = builder.length(); // append '=' to pad if (data.length % 3 == 1) { builder.replace(bLength - 2, bLength, "=="); } else if (data.length % 3 == 2) { builder.replace(bLength - 1, bLength, "="); } return builder.toString(); }public static byte[] decode(final String data) { if (data == null) { throw new IllegalArgumentException(SR.STRING_NOT_VALID); } int byteArrayLength = 3 * data.length() / 4; if (data.endsWith("==")) { byteArrayLength -= 2; } else if (data.endsWith("=")) { byteArrayLength -= 1; } final byte[] retArray = new byte[byteArrayLength]; int byteDex = 0; int charDex = 0; for (; charDex < data.length(); charDex += 4) { // get 4 chars, convert to 3 bytes final int char1 = DECODE_64[(byte) data.charAt(charDex)]; final int char2 = DECODE_64[(byte) data.charAt(charDex + 1)]; final int char3 = DECODE_64[(byte) data.charAt(charDex + 2)]; final int char4 = DECODE_64[(byte) data.charAt(charDex + 3)]; if (char1 < 0 || char2 < 0 || char3 == -1 || char4 == -1) { // invalid character(-1), or bad padding (-2) throw new IllegalArgumentException(SR.STRING_NOT_VALID); } int tVal = char1 << 18; tVal += char2 << 12; tVal += (char3 & 0xff) << 6; tVal += char4 & 0xff; if (char3 == -2) { // two "==" pad chars, check bits 12-24 tVal &= 0x00FFF000; retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF); } else if (char4 == -2) { // one pad char "=" , check bits 6-24. tVal &= 0x00FFFFC0; retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF); retArray[byteDex++] = (byte) (tVal >> 8 & 0xFF); } else { // No pads take all 3 bytes, bits 0-24 retArray[byteDex++] = (byte) (tVal >> 16 & 0xFF); retArray[byteDex++] = (byte) (tVal >> 8 & 0xFF); retArray[byteDex++] = (byte) (tVal & 0xFF); } } return retArray; }private static void validateIPAddress(String ipAddress) { try { @SuppressWarnings("unused") Inet4Address address = (Inet4Address) Inet4Address.getByName(ipAddress); } catch (Exception ex) { throw new IllegalArgumentException(String.format(SR.INVALID_IP_ADDRESS, ipAddress), ex); } }public synchronized Mac getHmac256() throws InvalidKeyException { if (this.hmacSha256 == null) { // Initializes the HMAC-SHA256 Mac and SecretKey. try { this.hmacSha256 = Mac.getInstance("HmacSHA256"); } catch (final NoSuchAlgorithmException e) { throw new IllegalArgumentException(); } this.hmacSha256.init(new SecretKeySpec(this.key, "HmacSHA256")); } return this.hmacSha256; }public synchronized void updateKey(final byte[] key) { if (key == null || key.length == 0) { throw new IllegalArgumentException(SR.INVALID_KEY); } this.key = key; this.hmacSha256 = null; }private static EnumSet splitToEnumSet(String str, String delimiter) { EnumSet set = EnumSet.noneOf(CorsHttpMethods.class); StringTokenizer st = new StringTokenizer(str, delimiter); while (st.hasMoreElements()) { set.add(CorsHttpMethods.valueOf(st.nextToken())); } return set; }private static List splitToList(String str, String delimiter) { ArrayList list = new ArrayList(); StringTokenizer st = new StringTokenizer(str, delimiter); while (st.hasMoreElements()) { list.add(st.nextToken()); } return list; }public static HttpURLConnection getAcl(final URI uri, final QueueRequestOptions queueOptions, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder builder = new UriQueryBuilder(); builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.ACL); final HttpURLConnection request = BaseRequest.createURLConnection(uri, queueOptions, builder, opContext); request.setRequestMethod(Constants.HTTP_GET); return request; }public static HttpURLConnection setAcl(final URI uri, final QueueRequestOptions queueOptions, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { final UriQueryBuilder builder = new UriQueryBuilder(); builder.add(Constants.QueryConstants.COMPONENT, Constants.QueryConstants.ACL); final HttpURLConnection request = BaseRequest.createURLConnection(uri, queueOptions, builder, opContext); request.setDoOutput(true); request.setRequestMethod(Constants.HTTP_PUT); return request; }public static HttpURLConnection updateMessage(final URI uri, final QueueRequestOptions queueOptions, final OperationContext opContext, final String popReceipt, final int visibilityTimeoutInSeconds) throws URISyntaxException, IOException, StorageException { final UriQueryBuilder builder = new UriQueryBuilder(); builder.add(POP_RECEIPT, popReceipt); builder.add(VISIBILITY_TIMEOUT, Integer.toString(visibilityTimeoutInSeconds)); final HttpURLConnection request = BaseRequest.createURLConnection(uri, queueOptions, builder, opContext); request.setDoOutput(true); request.setRequestMethod(Constants.HTTP_PUT); return request; }public static HttpURLConnection retrieveMessages(final URI uri, final QueueRequestOptions queueOptions, final OperationContext opContext, final int numberOfMessages, final int visibilityTimeoutInSeconds) throws URISyntaxException, IOException, StorageException { final UriQueryBuilder builder = new UriQueryBuilder(); if (numberOfMessages != 0) { builder.add(NUMBER_OF_MESSAGES, Integer.toString(numberOfMessages)); } builder.add(VISIBILITY_TIMEOUT, Integer.toString(visibilityTimeoutInSeconds)); final HttpURLConnection request = BaseRequest.createURLConnection(uri, queueOptions, builder, opContext); request.setRequestMethod("GET"); return request; }public static HttpURLConnection peekMessages(final URI uri, final QueueRequestOptions queueOptions, final OperationContext opContext, final int numberOfMessages) throws URISyntaxException, IOException, StorageException { final UriQueryBuilder builder = new UriQueryBuilder(); builder.add(PEEK_ONLY, "true"); if (numberOfMessages != 0) { builder.add(NUMBER_OF_MESSAGES, Integer.toString(numberOfMessages)); } final HttpURLConnection request = BaseRequest.createURLConnection(uri, queueOptions, builder, opContext); request.setRequestMethod(Constants.HTTP_GET); return request; }public static HttpURLConnection list(final URI uri, final QueueRequestOptions queueOptions, final OperationContext opContext, final ListingContext listingContext, final QueueListingDetails detailsIncluded) throws URISyntaxException, IOException, StorageException { final UriQueryBuilder builder = BaseRequest.getListUriQueryBuilder(listingContext); if (detailsIncluded == QueueListingDetails.ALL || detailsIncluded == QueueListingDetails.METADATA) { builder.add(Constants.QueryConstants.INCLUDE, Constants.QueryConstants.METADATA); } final HttpURLConnection request = BaseRequest.createURLConnection(uri, queueOptions, builder, opContext); request.setRequestMethod(Constants.HTTP_GET); return request; }public static HttpURLConnection downloadAttributes(final URI uri, final QueueRequestOptions queueOptions, final OperationContext opContext) throws IOException, URISyntaxException, StorageException { UriQueryBuilder builder = new UriQueryBuilder(); builder.add(Constants.QueryConstants.COMPONENT, METADATA); final HttpURLConnection retConnection = BaseRequest.createURLConnection(uri, queueOptions, builder, opContext); retConnection.setRequestMethod(Constants.HTTP_HEAD); return retConnection; }public static HttpURLConnection deleteMessage(final URI uri, final QueueRequestOptions queueOptions, final OperationContext opContext, final String popReceipt) throws URISyntaxException, IOException, StorageException { final UriQueryBuilder builder = new UriQueryBuilder(); builder.add(POP_RECEIPT, popReceipt); final HttpURLConnection request = BaseRequest.delete(uri, queueOptions, builder, opContext); return request; }public static HttpURLConnection clearMessages(final URI uri, final QueueRequestOptions queueOptions, final OperationContext opContext) throws URISyntaxException, IOException, StorageException { return BaseRequest.delete(uri, queueOptions, null, opContext); }@Override public CloudFileShare getShare() throws StorageException, URISyntaxException { if (this.share == null) { this.share = this.fileServiceClient.getShareReference(PathUtility.getShareNameFromUri(this.getUri(), this.fileServiceClient.isUsePathStyleUris())); } return this.share; }@DoesServiceRequest public ResultSegment listFilesAndDirectoriesSegmented() throws StorageException { return this.listFilesAndDirectoriesSegmented(null /* prefix */, null /* maxResults */, null /* continuationToken */, null /* options */, null /* opContext */); }@DoesServiceRequest public boolean exists(final AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException { return this.exists(false, accessCondition, options, opContext); }@DoesServiceRequest public boolean deleteIfExists(AccessCondition accessCondition, FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException { options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient); boolean exists = this.exists(true /* primaryOnly */, accessCondition, options, opContext); if (exists) { try { this.delete(accessCondition, options, opContext); return true; } catch (StorageException e) { if (e.getHttpStatusCode() == HttpURLConnection.HTTP_NOT_FOUND && StorageErrorCodeStrings.RESOURCE_NOT_FOUND.equals(e.getErrorCode())) { return false; } else { throw e; } } } else { return false; } }@DoesServiceRequest public boolean createIfNotExists(FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException { options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient); this.getShare().assertNoSnapshot(); boolean exists = this.exists(true /* primaryOnly */, null /* accessCondition */, options, opContext); if (exists) { return false; } else { try { this.create(options, opContext); return true; } catch (StorageException e) { if (e.getHttpStatusCode() == HttpURLConnection.HTTP_CONFLICT && StorageErrorCodeStrings.RESOURCE_ALREADY_EXISTS.equals(e.getErrorCode())) { return false; } else { throw e; } } } }@DoesServiceRequest public void create(FileRequestOptions options, OperationContext opContext) throws StorageException, URISyntaxException { if (opContext == null) { opContext = new OperationContext(); } this.getShare().assertNoSnapshot(); opContext.initialize(); options = FileRequestOptions.populateAndApplyDefaults(options, this.fileServiceClient); ExecutionEngine.executeWithRetry(this.fileServiceClient, this, createDirectoryImpl(options), options.getRetryPolicyFactory(), opContext); }public static String generateSharedAccessSignatureHashForTable( final SharedAccessTablePolicy policy, final String accessPolicyIdentifier, final String resourceName, final IPRange ipRange, final SharedAccessProtocols protocols, final String startPartitionKey, final String startRowKey, final String endPartitionKey, final String endRowKey, final ServiceClient client) throws InvalidKeyException, StorageException { String stringToSign = generateSharedAccessSignatureStringToSign( policy, resourceName, ipRange, protocols, accessPolicyIdentifier); stringToSign = String.format("%s\n%s\n%s\n%s\n%s", stringToSign, startPartitionKey == null ? Constants.EMPTY_STRING : startPartitionKey, startRowKey == null ? Constants.EMPTY_STRING : startRowKey, endPartitionKey == null ? Constants.EMPTY_STRING : endPartitionKey, endRowKey == null ? Constants.EMPTY_STRING : endRowKey); return generateSharedAccessSignatureHashHelper(stringToSign, client.getCredentials()); }public static String generateSharedAccessSignatureHashForQueue( final SharedAccessQueuePolicy policy, final String accessPolicyIdentifier, final String resourceName, final IPRange ipRange, final SharedAccessProtocols protocols, final ServiceClient client) throws InvalidKeyException, StorageException { final String stringToSign = generateSharedAccessSignatureStringToSign( policy, resourceName, ipRange, protocols, accessPolicyIdentifier); return generateSharedAccessSignatureHashHelper(stringToSign, client.getCredentials()); }public static String generateSharedAccessSignatureHashForBlobAndFile(final SharedAccessPolicy policy, SharedAccessHeaders headers, final String accessPolicyIdentifier, final String resourceName, final IPRange ipRange, final SharedAccessProtocols protocols, final ServiceClient client) throws InvalidKeyException, StorageException { String stringToSign = generateSharedAccessSignatureStringToSign( policy, resourceName, ipRange, protocols, accessPolicyIdentifier); String cacheControl = null; String contentDisposition = null; String contentEncoding = null; String contentLanguage = null; String contentType = null; if (headers != null) { cacheControl = headers.getCacheControl(); contentDisposition = headers.getContentDisposition(); contentEncoding = headers.getContentEncoding(); contentLanguage = headers.getContentLanguage(); contentType = headers.getContentType(); } stringToSign = String.format("%s\n%s\n%s\n%s\n%s\n%s", stringToSign, cacheControl == null ? Constants.EMPTY_STRING : cacheControl, contentDisposition == null ? Constants.EMPTY_STRING : contentDisposition, contentEncoding == null ? Constants.EMPTY_STRING : contentEncoding, contentLanguage == null ? Constants.EMPTY_STRING : contentLanguage, contentType == null ? Constants.EMPTY_STRING : contentType); return generateSharedAccessSignatureHashHelper(stringToSign, client.getCredentials()); }public static HashMap parseQueryString(String parseString) throws StorageException { final HashMap retVals = new HashMap(); if (Utility.isNullOrEmpty(parseString)) { return retVals; } // 1. Remove ? if present final int queryDex = parseString.indexOf("?"); if (queryDex >= 0 && parseString.length() > 0) { parseString = parseString.substring(queryDex + 1); } // 2. split name value pairs by splitting on the 'c&' character final String[] valuePairs = parseString.contains("&") ? parseString.split("&") : parseString.split(";"); // 3. for each field value pair parse into appropriate map entries for (int m = 0; m < valuePairs.length; m++) { final int equalDex = valuePairs[m].indexOf("="); if (equalDex < 0 || equalDex == valuePairs[m].length() - 1) { continue; } String key = valuePairs[m].substring(0, equalDex); String value = valuePairs[m].substring(equalDex + 1); key = Utility.safeDecode(key); value = Utility.safeDecode(value); // 3.1 add to map String[] values = retVals.get(key); if (values == null) { values = new String[] { value }; if (!value.equals(Constants.EMPTY_STRING)) { retVals.put(key, values); } } else if (!value.equals(Constants.EMPTY_STRING)) { final String[] newValues = new String[values.length + 1]; for (int j = 0; j < values.length; j++) { newValues[j] = values[j]; } newValues[newValues.length] = value; } } return retVals; }public static StorageUri getShareURI(final StorageUri fileAddress, final boolean usePathStyleUris) throws URISyntaxException { final String shareName = getShareNameFromUri(fileAddress.getPrimaryUri(), usePathStyleUris); final StorageUri shareUri = appendPathToUri(getServiceClientBaseAddress(fileAddress, usePathStyleUris), shareName); return shareUri; }public static StorageUri getContainerURI(final StorageUri blobAddress, final boolean usePathStyleUris) throws URISyntaxException { final String containerName = getContainerNameFromUri(blobAddress.getPrimaryUri(), usePathStyleUris); final StorageUri containerUri = appendPathToUri(getServiceClientBaseAddress(blobAddress, usePathStyleUris), containerName); return containerUri; }private static String getResourceNameFromUri(final URI resourceAddress, final boolean usePathStyleUris, final String error) { Utility.assertNotNull("resourceAddress", resourceAddress); final String[] pathSegments = resourceAddress.getRawPath().split("/"); final int expectedPartsLength = usePathStyleUris ? 3 : 2; if (pathSegments.length < expectedPartsLength) { throw new IllegalArgumentException(error); } final String resourceName = usePathStyleUris ? pathSegments[2] : pathSegments[1]; return Utility.trimEnd(resourceName, '/'); }public static String getTableNameFromUri(final URI resourceAddress, final boolean usePathStyleUris) { return getResourceNameFromUri(resourceAddress, usePathStyleUris, String.format("Invalid table address '%s', missing table information", resourceAddress)); }public static String getShareNameFromUri(final URI resourceAddress, final boolean usePathStyleUris) { return getResourceNameFromUri(resourceAddress, usePathStyleUris, String.format("Invalid file address '%s', missing share information", resourceAddress)); }public static String getFileNameFromURI(final URI resourceAddress, final boolean usePathStyleUris) { // generate an array of the different levels of the path final String[] pathSegments = resourceAddress.getRawPath().split("/"); // usePathStyleUris ? baseuri/accountname/sharename/objectname : accountname.baseuri/sharename/objectname final int shareIndex = usePathStyleUris ? 2 : 1; if (pathSegments.length - 1 <= shareIndex) { // legal file addresses cannot end with or before the sharename throw new IllegalArgumentException(String.format("Invalid file address '%s'.", resourceAddress)); } else { // in a legal file address the lowest level is the filename return pathSegments[pathSegments.length - 1]; } }public static String getContainerNameFromUri(final URI resourceAddress, final boolean usePathStyleUris) { return getResourceNameFromUri(resourceAddress, usePathStyleUris, String.format("Invalid blob address '%s', missing container information", resourceAddress)); }public static String getCanonicalPathFromCredentials(final StorageCredentials credentials, final String absolutePath) { final String account = credentials.getAccountName(); if (account == null) { final String errorMessage = SR.CANNOT_CREATE_SAS_FOR_GIVEN_CREDENTIALS; throw new IllegalArgumentException(errorMessage); } final StringBuilder builder = new StringBuilder("/"); builder.append(account); builder.append(absolutePath); return builder.toString(); }public static String getBlobNameFromURI(final URI inURI, final boolean usePathStyleUris) throws URISyntaxException { return Utility.safeRelativize(new URI(getContainerURI(new StorageUri(inURI), usePathStyleUris).getPrimaryUri() .toString().concat("/")), inURI); }public static URI appendPathToSingleUri(final URI uri, final String relativeUri, final String separator) throws URISyntaxException { if (uri == null) { return null; } if (relativeUri == null || relativeUri.isEmpty()) { return uri; } if (uri.getPath().length() == 0 && relativeUri.startsWith(separator)) { return new URI(uri.getScheme(), uri.getAuthority(), relativeUri, uri.getRawQuery(), uri.getRawFragment()); } final StringBuilder pathString = new StringBuilder(uri.getPath()); if (uri.getPath().endsWith(separator)) { pathString.append(relativeUri); } else { pathString.append(separator); pathString.append(relativeUri); } return new URI(uri.getScheme(), uri.getAuthority(), pathString.toString(), uri.getQuery(), uri.getFragment()); }@Override public final CloudFileShare getShare() throws StorageException, URISyntaxException { if (this.share == null) { final StorageUri shareUri = PathUtility.getShareURI(this.getStorageUri(), this.fileServiceClient.isUsePathStyleUris()); this.share = new CloudFileShare(shareUri, this.fileServiceClient.getCredentials()); } return this.share; }protected static String getParentNameFromURI(final StorageUri resourceAddress, final CloudFileShare share) throws URISyntaxException { Utility.assertNotNull("resourceAddress", resourceAddress); Utility.assertNotNull("share", share); String delimiter = "/"; String shareName = share.getName() + delimiter; String relativeURIString = Utility.safeRelativize(share.getStorageUri().getPrimaryUri(), resourceAddress.getPrimaryUri()); if (relativeURIString.endsWith(delimiter)) { relativeURIString = relativeURIString.substring(0, relativeURIString.length() - delimiter.length()); } String parentName; if (Utility.isNullOrEmpty(relativeURIString)) { // Case 1 /[Delimiter]*? => / // Parent of share is share itself parentName = null; } else { final int lastDelimiterDex = relativeURIString.lastIndexOf(delimiter); if (lastDelimiterDex < 0) { // Case 2 // // Parent of a Directory is Share parentName = ""; } else { // Case 3 ///[/]* // Parent of CloudFile is CloudFileDirectory parentName = relativeURIString.substring(0, lastDelimiterDex); if (parentName != null && parentName.equals(shareName)) { parentName = ""; } } } return parentName; }+��d%��D���Xm�7�~�¤�lDE�'�������B+gw6qocomor��wfl�K.�j���vg�g�yKc���C)*�e-�M!�?�UrYï�EaAz�7�צ�]a�k�N���/$�Y���Ko�^ �ɵ��\\��/<>��߬���������]�.��:!u) 4��k����*^[�]q ����NT��=��#vʯ���zq��v!�*��F��lQD�%� �CZ��[@Lŏ�|�F��� �_ڝr������Uh�7,.���2�.I��� ��kLU���P1h�WN��D��y���Iz� Uo�—T��=�fgS6�J=��@Ѕ�A��!�� �qL�%T?�M����zr��X�������_y�!�ɱ����$>P�Ⱥhk�K���R�>b�ӭ�^�=|2�*�L�'ƿ����]"�}r�ט�(½׽�z�M~�g�o�\4��0(h�[��f�\�1��ν�܋��p��λ���z�V�czr�~��H�� +S�HU�-N>G�#<�����u�9�q�E�똅��p�PqL�S�+�/�!J*�;c�^ȥi}���Ipw g.ղ��9D�nK(��kؙ�A�"G 9c���*%Dv�.�F��\�y8x�f����ƹ#v�8<�sJS˂'�1�}�@�v�4z��)��(C�s;��b߇��ԡ�<=7�e��b��]I�m��y�q���L��h7��c@v μ< )Ӗ�4—��$���[��sŽ ɶJ�Jv68�~���y��"?r`6�<�g]O��7ܼ��3�?���# Tﺕ��v�1�E�%R#G���e6܃z���J���u�?����#.%H�fq9�����/��!���Z6p4�1�(���V�g��GH�nF�8�T�Q����W�'ty�zȲ[��kb�'�l �v���g�{�6��3t� �,��z2��[=y*&ܘӧ�y����Kh۩[ǝ���2��n��Js^r�O�2�6�3!Ц� $�;� �,�� P�v����t�VXU��ㄯI3=֮��'=ߘe�BW�@������P��5 ?P �|G��!��7Zx�k���������/.^v k(���+�`UL�:��|6�����+ڈrG�9� ���q��K�%��5>���O��ȯ���d�1u"�\�+ԧq �Dk��݁™T�����| 3;Y��%�)�+u-�/�6=�=^F�M�UWSYB](^�d,f�h7l�m�q-szt�uw�x z�{8}�~0����/��>�#�������!��*��0���ݘ����s�z������ �/�"����� �b����ߵ�������5�ԼԽ:���q��D�2��.��L�>���;�=���U���m����]�_�+��BA�� �R[��2%B�� �!�#D%G&�';)h.�2u35U6G79;�<{>;@�C�E.G0I�J�M�N�O�PzRDT�URV\l^va�b�dxeh�i�j4k�k�lfnGqls�sXt�tpu4v�v�w/x�x�y6|�}�~g�g���0�‰#�܋ݍ��p�t���5�J�J����2�l�B��������q�˾�O�Q�3���N���Y������"�������n�����"�n�����l�k����6�6GX��� � � � ��^/�J ��� "E#V$�%�+*-�1�2h3?4�6F8�:�;�=�@�E�H�M@NO'P�QeUV;X�Y�\�_�`�b�cDd�elf!gi k�l p5qs�sv}w z[|-}~�O�݀�s�ʄ3�ąD�����ޑT�~�������ݙI�(�̞5���L�ީ�������i���_�,�9����^�V�N������#�����b�v�G��������y�������@��?�����T�����������z���X��w q � � � �xSzYr���V !j$[%�&�'?)P+=-J/N2�4867o9�;s=�?,@3A)B�BMC6D�D�EhF�HDKLO�OVQ�R�TV�V�W�X�Y�[ _�ce�g�hjMk'm nnp�v0wy z�z�{}ŀW�ąˆL���ڑܒ/���њS�̡��������J�����^� �ŵռ��p���y��S�r� �����!���F�h�?���R�������>�����K�Z�+����R�� �)������T�_��׌��%���@/R8'�/� .@8XЍ`A�� ^�y 넔TJ`zvt9f�b4�vH��)��5� ���S���e�>JR���=.���ZT^u���u�߮F��uS����3�1�O���=o�c-R�\�衧Lh � �1xj���_�protected String getDirectoryPath(File directory, File entry) { String relativePath; if (entry.equals(directory)) { relativePath = "/"; } else { String filePath = entry.getAbsolutePath(); String directoryPath = directory.getAbsolutePath(); relativePath = filePath.substring(directoryPath.length()).replace(File.separator, "/"); } return relativePath; }protected Boolean getBooleanProperty(String name, Boolean defaultValue) { Object value = properties.get(name); return value != null ? Boolean.valueOf(value.toString()) : defaultValue; }protected String getStringProperty(String name, String defaultValue) { Object value = properties.get(name); return value != null ? value.toString() : defaultValue; }protected Class getTypeParameter(Class expectedSuperClass, int genericTypeParameterIndex) { Class thisClass = this.getClass(); if (!thisClass.getSuperclass().equals(expectedSuperClass)) { throw new IllegalStateException("Cannot determine type argument of " + thisClass.getName()); } Type genericSuperclass = thisClass.getGenericSuperclass(); Type typeParameter = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[genericTypeParameterIndex]; if (typeParameter instanceof ParameterizedType) { return (Class) ((ParameterizedType) typeParameter).getRawType(); } return (Class) typeParameter; }@Nullable public Date getDateOfBirthEnd() { if (birthDayEnd == null || birthMonthEnd == null || birthYearEnd == null) { return null; } GregorianCalendar calendar = new GregorianCalendar(birthYearEnd, birthMonthEnd, birthDayEnd); return calendar.getTime(); }@NotNull private String getEncodedAuthorization() { try { return "Basic " + DatatypeConverter.printBase64Binary(apiKey.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }@NotNull public Candidate retrieveCandidate(@NotNull final String id) { Candidate candidate = restAdapter.retrieveCandidate(id); candidate.setAdapter(restAdapter); return candidate; }@NotNull public Person retrievePerson(@NotNull final String id) { Person person = restAdapter.retrievePerson(id); person.setAdapter(restAdapter); return person; }public Candidate setAddress(@NotNull final Address address) { this.addressStreet1 = address.getStreet1(); this.addressStreet2 = address.getStreet2(); this.addressCity = address.getCity(); this.addressSubdivision = address.getSubdivision(); this.addressPostalCode = address.getPostalCode(); this.addressCountryCode = address.getCountryCode(); return this; }@NotNull public Candidate setDateOfBirth(@Nullable final Date dateOfBirth) { if (dateOfBirth == null) { this.dateOfBirth = null; return this; } this.dateOfBirth = new Date(dateOfBirth.getTime()); return this; }public PaginatedResult searchWatchlists(EntityType entityType, Double similarityThreshold) { Map queryOptions = new HashMap(); queryOptions.put("candidate_id", getId()); if (entityType != null) { queryOptions.put("match_type", String.valueOf(entityType)); } if (similarityThreshold != null) { queryOptions.put("similarity_threshold", String.valueOf(similarityThreshold)); } WatchlistSearchResults results = restAdapter.searchWatchlists(queryOptions); //wrap the result's data with PaginatedResult to make v5.0 transition simpler return new PaginatedResult(results.getMatches(), results.getCount(), false); }public List getRevisionHistory() { List candidates = restAdapter.getCandidateHistory(getId()); for (Candidate candidate : candidates) { candidate.setAdapter(restAdapter); } return Collections.unmodifiableList(candidates); }@Nullable public Date getIncorporationDate() { if (incorporationDay == null || incorporationMonth == null || incorporationYear == null) { return null; } GregorianCalendar calendarDay = new GregorianCalendar(incorporationYear, incorporationMonth, incorporationDay); return calendarDay.getTime(); }@NotNull public Address getAddress() { Address addressObject = new Address(addressStreet1, addressStreet2, addressCity, addressSubdivision, addressPostalCode, addressCountryCode); return addressObject; }@NotNull public Date getDateOfBirth() { GregorianCalendar calendar = new GregorianCalendar(birthYear, birthMonth, birthDay); return calendar.getTime(); }public QuestionSet retrieveQuestionSet(@NotNull final String questionSetId) { QuestionSet questionSet = restAdapter.retrieveQuestionSet(questionSetId); questionSet.setAdapter(restAdapter); return questionSet; }public QuestionSet createQuestionSet(long timeLimit) { Map queryOptions = new HashMap(); queryOptions.put("person_id", getId()); queryOptions.put("time_limit", String.valueOf(timeLimit)); QuestionSet questionSet = restAdapter.createQuestionSet(queryOptions); questionSet.setAdapter(restAdapter); return questionSet; }@Nullable public Address getAddress() { return new Address(addressStreet1, addressStreet2, addressCity, addressState, addressPostalCode, addressCountryCode); }@NotNull public String[] getMatchingInfo() { if (matchingInfo == null) { return new String[0]; } return Arrays.copyOf(matchingInfo, matchingInfo.length); }public void addAnswer(int questionId, int answerId) { QuestionAnswerPair answerPair = new QuestionAnswerPair(questionId, answerId); answers.add(answerPair); }public boolean accepts(String path) { boolean result; if (includeFilePatterns != null) { result = matches(path, includeFilePatterns); } else { result = true; } if (excludeFilePatterns != null) { result = result && !matches(path, excludeFilePatterns); } return result; }public D digest(InputStream stream, DigestOperation digestOperation) throws IOException { DigestInputStream digestInputStream = new DigestInputStream(stream, md5Digest); D md5Descriptor = digestOperation.execute(digestInputStream); String md5 = DatatypeConverter.printHexBinary(md5Digest.digest()); md5Descriptor.setMd5(md5); return md5Descriptor; }@NotNull public void score(@NotNull final AnswerSet answers) { QuestionSet scoredSet = restAdapter.scoreQuestionSet(getId(), answers); expired = scoredSet.isExpired(); score = scoredSet.getScore(); }@Nullable public static BlockscoreError getBlockscoreError(@NotNull final RetrofitError cause) { Object rawError = cause.getBodyAs(BlockscoreError.class); if (rawError instanceof BlockscoreError) { return (BlockscoreError) rawError; } else { return null; } }@Deprecated protected D toFileDescriptor(Descriptor descriptor, Class type, String path, ScannerContext context) { if (descriptor == null) { D result = context.getStore().create(type); result.setFileName(path); return result; } return migrateOrCast(descriptor, type, context); }@Nullable public ResultStrength getAddressRisk() { if (addressRisk == null) { return null; } return ResultStrength.toEnum(addressRisk.toLowerCase()); }@Override public OutputStream receiveUpload(String filename, String MIMEType) { FileOutputStream fos; // Output stream to write to try { file = File.createTempFile("upload", filename.substring(filename.lastIndexOf('.'))); // Open the file for writing. fos = new FileOutputStream(getFile()); } catch (FileNotFoundException ex) { // Error while opening the file. Not reported here. LOG.log(Level.SEVERE, null, ex); return null; } catch (IOException ex) { // Error while opening the file. Not reported here. LOG.log(Level.SEVERE, null, ex); return null; } return fos; // Return the output stream to write to }private static void walkComponentTree(Component c, Consumer visitor) { visitor.accept(c); if (c instanceof HasComponents) { for (Component child : ((HasComponents) c)) { walkComponentTree(child, visitor); } } }private void refreshWorkflow() { Graph graph = new Graph(((Workflow) workflows.getValue()) .getWorkflowName(), Graph.DIGRAPH); nodes.values().forEach(node -> { graph.addNode(node); }); edges.values().forEach(edge -> { graph.addEdge(edge.getKey(), edge.getValue().getDest()); }); diagram.drawGraph(graph); selected = null; updateControls(); }private void displayWorkflow(Workflow w) { Graph graph = new Graph(w.getWorkflowName(), Graph.DIGRAPH); nodes.clear(); //Create the nodes w.getWorkflowStepList().forEach(step -> { addStep(step, graph); //Now add the links step.getSourceTransitions().forEach(t -> { addStep(t.getWorkflowStepSource(), graph); addStep(t.getWorkflowStepTarget(), graph); Subgraph.Edge edge = graph.addEdge(nodes.get(t.getWorkflowStepSource() .getWorkflowStepPK().getId()), nodes.get(t.getWorkflowStepTarget() .getWorkflowStepPK().getId())); edge.setParam("label", TRANSLATOR.translate(t.getTransitionName())); //Workaround https://github.com/pontusbostrom/VaadinGraphvizComponent/issues/9 edge.setDest(nodes.get(t.getWorkflowStepTarget() .getWorkflowStepPK().getId())); edges.put(TRANSLATOR.translate(t.getTransitionName()), new AbstractMap.SimpleEntry<>( nodes.get(t.getWorkflowStepSource() .getWorkflowStepPK().getId()), edge)); }); }); diagram.drawGraph(graph); }public static DataEntry getNumericField(String name, Float min, Float max) { DataEntry de = new DataEntry(); de.setEntryName(name); DataEntryType det = DataEntryTypeServer.getType("type.numeric.name"); de.setDataEntryPropertyList(getDefaultProperties(det)); de.setDataEntryType(det); for (DataEntryProperty dep : de.getDataEntryPropertyList()) { if (dep.getPropertyName().equals("property.min") && min != null) { //Set minimum dep.setPropertyValue(min.toString()); } if (dep.getPropertyName().equals("property.max") && max != null) { //Set minimum dep.setPropertyValue(max.toString()); } } return de; }public static DataEntry getBooleanField(String name) { DataEntry de = new DataEntry(); de.setEntryName(name); DataEntryType det = DataEntryTypeServer.getType("type.boolean.name"); de.setDataEntryPropertyList(getDefaultProperties(det)); de.setDataEntryType(det); return de; }public static DataEntry getStringField(String name, String expected, boolean matchCase) { DataEntry de = new DataEntry(); DataEntryType det = DataEntryTypeServer.getType("type.string.name"); de.setEntryName(name); de.setDataEntryPropertyList(getDefaultProperties(det)); de.setDataEntryType(det); if (expected != null) { getProperty(de, "property.expected.result") .setPropertyValue(expected); getProperty(de, "property.match.case") .setPropertyValue(matchCase ? "true" : "false"); } return de; }@SuppressWarnings("unchecked") public static VmSetting getSetting(String s) { PARAMETERS.clear(); PARAMETERS.put("setting", s); result = namedQuery("VmSetting.findBySetting", PARAMETERS); if (result.isEmpty()) { return null; } else { return (VmSetting) result.get(0); } }public static IssueType getType(String typename) { IssueType result = null; for (IssueType type : new IssueTypeJpaController(DataBaseManager .getEntityManagerFactory()).findIssueTypeEntities()) { if (type.getTypeName().equals(typename)) { result = type; break; } } return result; }@Override public int write2DB() throws VMException { try { VmIdJpaController controller = new VmIdJpaController( getEntityManagerFactory()); VmId vmId; if (getId() == null) { vmId = new VmId(); update(vmId, this); controller.create(vmId); setId(vmId.getId()); } else { vmId = getEntity(); update(vmId, this); controller.edit(vmId); } update(); return getId(); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); throw new VMException(ex); } }public RequirementSpecNodeServer addSpecNode(String name, String description, String scope) throws Exception { RequirementSpecNodeServer sns = new RequirementSpecNodeServer( new RequirementSpecJpaController( getEntityManagerFactory()) .findRequirementSpec(getRequirementSpecPK()), name, description, scope); sns.write2DB(); getRequirementSpecNodeList().add( new RequirementSpecNodeJpaController( getEntityManagerFactory()) .findRequirementSpecNode(sns.getRequirementSpecNodePK())); write2DB(); return sns; }@Override public void customize(Session session) throws Exception { JNDIConnector connector; // Initialize session customizer DataSource dataSource; try { Context context = new InitialContext(); if (null == context) { throw new VMException("Context is null"); } connector = (JNDIConnector) session.getLogin().getConnector(); // possible CCE // Lookup this new dataSource dataSource = (DataSource) context.lookup(JNDI_DATASOURCE_NAME); connector.setDataSource(dataSource); // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in the COMPOSITE_NAME_LOOKUP being set // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set connector.setLookupType(JNDIConnector.STRING_LOOKUP); // if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe JNDIConnector writeConnector = (JNDIConnector) session.getLogin().getConnector(); writeConnector.setLookupType(JNDIConnector.STRING_LOOKUP); JNDIConnector readConnector = (JNDIConnector) ((DatabaseLogin) ((ServerSession) session) .getReadConnectionPool().getLogin()).getConnector(); readConnector.setLookupType(JNDIConnector.STRING_LOOKUP); // Set the new connection on the session session.getLogin().setConnector(connector); } catch (Exception e) { LOG.log(Level.SEVERE, JNDI_DATASOURCE_NAME, e); } }public void addHistory(History history) { if (getHistoryList() == null) { setHistoryList(new ArrayList<>()); } getHistoryList().add(history); }public void update(Versionable target, Versionable source) { target.setDirty(source.getDirty()); target.setMajorVersion(source.getMajorVersion()); target.setMidVersion(source.getMidVersion()); target.setMinorVersion(source.getMinorVersion()); target.setModifierId(source.getModifierId()); target.setReason(source.getReason()); target.setModificationTime(source.getModificationTime()); target.setHistoryList(source.getHistoryList()); try { target.updateHistory(); } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getLocalizedMessage(), ex); } }private List getVisibleProperties(OneToMany oneToMany) { return getViewPropertiesExcludingField(oneToMany.referenceBean, oneToMany.referenceProperty.name); }public List getReferenceProperties(Bean bean) { List result = new ArrayList<>(); for (int i = 0; i < bean.cardinality; i++) { Property property = bean.properties.get(i); result.addAll(property.viewProperties); } return result; }public Bean findBean(String tableOriginalName) { for (Package myPackage : this.packages) { for (Bean bean : myPackage.beans) { if (bean.table.originalName.equals(tableOriginalName)) { return bean; } } } throw new BeanNotFoundException("invalid table reference : " + tableOriginalName); }public Table findTable(String tableName) { if (tableName == null) { return null; } if (tableName.isEmpty()) { return null; } for (Package myPackage : this.packages) { for (Table table : myPackage.tables) { if (table.originalName.equals(tableName)) { return table; } } } throw new TableNotFoundException("Invalid table reference : " + tableName); }protected final void writeNotOverridableContent() throws IOException { String content = getNotOverridableContent(); writeLine(fileType.getSpecificCodeStartMark()); write(content); writeLine(fileType.getSpecificCodeEndMark()); }private final String getNotOverridableContent() throws IOException { if (Files.exists(filePath)) { List lines = Files.readAllLines(filePath, fileType.getEncoding()); boolean isNotOverridable = false; StringWriter notOverridableContentWriter = new StringWriter(); for (String line : lines) { if (line.contains(fileType.getSpecificCodeStartMark())) { isNotOverridable = true; } else if (line.contains(fileType.getSpecificCodeEndMark())) { isNotOverridable = false; } else { if (isNotOverridable) { notOverridableContentWriter.append(line + SKIP_LINE); } } } return notOverridableContentWriter.toString(); } return ""; }@XmlTransient public List getAllPackages() { List result = new ArrayList<>(); if (packages != null) { for (PackageMetaData pack : packages) { result.addAll(getPackages(pack)); } } return result; }public List getInsertColumnList() { List result = new ArrayList<>(); List tempColumnList = new ArrayList<>(); for (Column currentColumn:this.columns) { if (currentColumn.referenceTable != null) { tempColumnList = currentColumn.referenceTable.getFindColumnList(); for (Column tempColumn : tempColumnList) { Column column = new Column(); column.name = currentColumn.name.replace("_ID", "_").replace("_id", "_") + tempColumn.name; column.dataType = tempColumn.dataType; column.nullable = currentColumn.nullable; result.add(column); } } else { Column column = new Column(); column.name = currentColumn.name; column.dataType = currentColumn.dataType; column.nullable = currentColumn.nullable; result.add(column); } } return result; }public List getFindColumnList() { List findColumnList = new ArrayList(); List tempColumnList = new ArrayList(); for (int i = 1; i <= this.cardinality; i++) { if (this.columns.get(i).referenceTable != null) { tempColumnList = this.columns.get(i).referenceTable.getFindColumnList(); for (int j = 0; j < tempColumnList.size(); j++) { Column column = new Column(); column.name = columns.get(i).name.replace("_ID", "_").replace("_id", "_") + tempColumnList.get(j).name; column.dataType = tempColumnList.get(j).dataType; column.nullable = this.columns.get(i).nullable; findColumnList.add(column); } } else { Column column = new Column(); column.name = columns.get(i).name; column.dataType = columns.get(i).dataType; column.nullable = this.columns.get(i).nullable; findColumnList.add(column); } } return findColumnList; }private com.github.fge.jsonschema.main.JsonSchema getValidator() throws ProcessingException { if (validator == null) { synchronized (this) { if (validator == null) { ValidationConfigurationBuilder cfgBuilder = ValidationConfiguration.newBuilder(); cfgBuilder.addLibrary("http://brutusin.org/json/json-schema-spec", DraftV3Library.get()); validator = JsonSchemaFactory.newBuilder().setValidationConfiguration(cfgBuilder.freeze()).freeze().getJsonSchema(getNode()); } } } return validator; }public static void main(String[] args) throws Throwable { try { Class initialClass; // make it independent - get class name & method from props/manifest initialClass = Thread.currentThread().getContextClassLoader().loadClass("kg.apc.cmdtools.PluginsCMD"); Object instance = initialClass.newInstance(); Method startup = initialClass.getMethod("processParams", (new String[0]).getClass()); Object res = startup.invoke(instance, new Object[]{args}); int rc = (Integer) res; if (rc != 0) { System.exit(rc); } } catch (Throwable e) { if (e.getCause() != null) { System.err.println("ERROR: " + e.getCause().toString()); System.err.println("*** Problem's technical details go below ***"); System.err.println("Home directory was detected as: " + jarDirectory); throw e.getCause(); } else { System.err.println("Home directory was detected as: " + jarDirectory); throw e; } } }protected void init(Context context) { LayoutInflater.from(context).inflate(R.layout.fake_search_view, this, true); wrappedEditText = (EditText) findViewById(R.id.wrapped_search); wrappedEditText.addTextChangedListener(this); wrappedEditText.setOnEditorActionListener(this); }protected void closeMBeanServerConnection(String childName) { MBeanConnectionInfo connInfo = connections.get(childName); if (connInfo != null && connInfo.connector != null) { try { connInfo.connector.close(); } catch (IOException e) { logger.log(Level.FINE, "Failed to close JMXConnector", e); } connInfo.connector = null; } }protected MBeanServerConnection getMBeanServerConnection(String childName) { MBeanConnectionInfo connInfo = connections.get(childName); if (connInfo == null) { connInfo = new MBeanConnectionInfo(); connections.put(childName, connInfo); } long childPid = main.getFirstJavaChildPid(childName); if (childPid > 0 && childPid != connInfo.childPid && connInfo.connector != null) { try { connInfo.connector.close(); } catch (IOException e) { logger.log(Level.FINE, "Failed to close JMXConnector", e); } connInfo.connector = null; connInfo.server = null; } if (childPid > 0) { try { if (connInfo.connector == null) { connInfo.connector = DeployerControl.getJMXConnector(childPid); } if (connInfo.connector != null && connInfo.server == null) { connInfo.server = connInfo.connector.getMBeanServerConnection(); connInfo.childPid = childPid; } } catch (IOException e) { logger.log(Level.FINE, "Failed to get JMX connection", e); try { connInfo.connector.close(); } catch (Exception e2) { logger.log(Level.FINE, "Failed to close JMXConnector", e2); } connInfo.connector = null; connInfo.server = null; } } return connInfo.server; }public void initialize(Map> eventHandlers, URI uri) { this.eventHandlers = eventHandlers; EventListener listener = new EventListener(uri); executorService.submit(listener); logger.fine("Started event listener"); }private void checkLine() { String endStr = new String(buf, count - LINE_SEPERATOR.length(), LINE_SEPERATOR.length(), charset); if (LINE_SEPERATOR.equals(endStr)) { flush(); } }protected void doMain(String... args) { properties = new MergeableProperties(); properties.putAll(System.getProperties()); for (String arg : args) { properties.merge(arg); } // Read event handling configuration Map> eventHandlers = new LinkedHashMap<>(); MergeableProperties allProperties = properties.getPrefixed("willow-event-handler.handlers"); int i = 0; while (true) { MergeableProperties handlerProperties = allProperties.getPrefixed("[" + i++ + "]"); if (handlerProperties.isEmpty()) { break; } String handlerClassName = handlerProperties.getProperty("handler"); String eventClassName = handlerProperties.getProperty("event"); try { EventHandler eventHandler = (EventHandler) injector.getInstance(Class.forName(handlerClassName)); MergeableProperties beanProperties = handlerProperties.getPrefixed("properties"); for (String propertyName : beanProperties.stringPropertyNames()) { String propertyValue = beanProperties.getProperty(propertyName); BeanUtils.setProperty(eventHandler, propertyName, propertyValue); } List eventHandlersForType = eventHandlers.get(eventClassName); if (eventHandlersForType == null) { eventHandlersForType = new ArrayList<>(); eventHandlers.put(eventClassName, eventHandlersForType); } eventHandlersForType.add(eventHandler); } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException e) { logger.log(Level.SEVERE, "Error instantiating handler", e); System.exit(1); } } if (eventHandlers .isEmpty()) { logger.info("No event handlers configured. Exiting."); System.exit(0); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { Main.this.stop(); } }); // Start polling events String uri = properties.getProperty("willow-event-handler.eventsUri"); try { logger.info("Initializing event poller"); eventPoller.initialize(eventHandlers, new URI(uri)); } catch (URISyntaxException e) { logger.log(Level.SEVERE, "Invalid URI: " + uri, e); System.exit(1); } }protected Module[] getModules() { Module[] modules = { new WireModule(new EventHandlerModule(), new SpaceModule(new URLClassSpace(Main.class.getClassLoader()))) }; return modules; }protected static void main(Main main, String... args) { main.getInjector().getInstance(main.getMainClass()).doMain(args); }public void onOperationFinished(final SimpleOperation.Result result) { if (result.isSuccessful()) { mData = result.getOutput(); showData(); } else { mTextOutput.setText(result.getErrorMessage()); } }@NonNull final ChronosOperationResult runSync( @NonNull final ChronosOperation operation, final boolean broadcastResult) { final ChronosOperationResult result = createEmptyResult(operation, broadcastResult); silentRun(operation, result); mEventBus.post(result); return result; }final int runAsync(@NonNull final ChronosOperation operation, final boolean broadcastResult) { final ChronosOperationResult result = createEmptyResult(operation, broadcastResult); final int id = result.getId(); synchronized (ChronosService.this) { RunningOperationStorage.getInstance().operationStarted(id, operation, mExecutorService.submit(new Runnable() { @Override public void run() { silentRun(operation, result); mEventBus.post(result); synchronized (ChronosService.this) { RunningOperationStorage.getInstance().operationFinished(id); } } })); } return id; }@NonNull @Contract(pure = true) private ChronosOperationResult createEmptyResult( @NonNull final ChronosOperation operation, final boolean broadcastResult) { final ChronosOperationResult operationResult; final Class> resultClass = operation .getResultClass(); try { operationResult = resultClass.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Can't create a new instance of " + resultClass.getName()); } catch (IllegalAccessException e) { throw new RuntimeException(resultClass.getName() + " constructor is not accessible"); } operationResult.setId(mLastOperationId.incrementAndGet()); operationResult.setOperation(operation); operationResult.setBroadcast(broadcastResult); return operationResult; }private static void silentRun(@NonNull final ChronosOperation operation, @NonNull final ChronosOperationResult operationResult) { try { final Output output = operation.run(); operationResult.setOutput(output); } catch (Exception e) { operationResult.setException(e); } }@Contract(pure = true) synchronized final boolean isOperationCancelled(final int id) { return mCancelledOperations.contains(Integer.valueOf(id)); }synchronized final void cancelAll(final boolean mayInterrupt) { for (final Integer key : mRunningOperations.keySet()) { cancel(key, mayInterrupt, false); } mRunningOperations.clear(); }synchronized final void operationStarted(final int id, @NonNull final ChronosOperation operation, @NonNull final Future future ) { mRunningOperations.put(id, new RunningOperation(operation, future)); }private synchronized boolean cancel(final int id, final boolean mayInterrupt, final boolean removeOperation) { final RunningOperation runningOperation = mRunningOperations.get(id); if (runningOperation != null) { if (removeOperation) { mRunningOperations.remove(id); } mCancelledOperations.add(id); return runningOperation.cancel(mayInterrupt); } else { return false; } }private void logd(@NonNull final String message) { if (LOG_ENABLED) { Log.d(LOG_TAG, this.toString() + " " + message); } }@SuppressWarnings("TryWithIdenticalCatches") private void deliverResult(@NonNull final ChronosOperationResult operationResult, @NonNull final String methodName, final boolean warnIfNoCallback) { final Class listenerClass = mServiceListener.getClass(); final Method[] listenerMethods = listenerClass.getMethods(); Method callbackMethod = null; final Class resultClass = operationResult.getClass(); for (Method method : listenerMethods) { if (isCallback(method, resultClass, methodName)) { callbackMethod = method; try { callbackMethod.invoke(mServiceListener, operationResult); } catch (IllegalAccessException e) { Log.w(LOG_TAG, Log.getStackTraceString(e)); } catch (InvocationTargetException e) { Log.w(LOG_TAG, Log.getStackTraceString(e)); } } } if (warnIfNoCallback && callbackMethod == null) { Log.w(LOG_TAG, "Operation result (id=" + operationResult.getId() + "; class=" + operationResult .getClass().getName() + ") was obtained, but there is no method in " + mServiceListener + " to get it" ); Log.w(LOG_TAG, "Method should look like"); Log.w(LOG_TAG, "public void " + methodName + "(" + resultClass.getName() + " result) {}" ); } }private void deliverResult(@NonNull final OperationDelivery operationDelivery) { logd("deliver delivery " + operationDelivery); switch (operationDelivery.getDeliveryMode()) { case NORMAL: deliverResult(operationDelivery.getResult(), Chronos.OWN_CALLBACK_METHOD_NAME, true); break; case BROADCAST: deliverResult(operationDelivery.getResult(), Chronos.BROADCAST_CALLBACK_METHOD_NAME, false); break; default: break; } }private void storeResult(@NonNull final OperationDelivery operationDelivery) { logd("store delivery " + operationDelivery); mStoredResults.add(new SoftReference>(operationDelivery)); }private void onOperationFinished(@NonNull final OperationDelivery operationResult) { logd("onOperationFinished " + operationResult); switch (mState) { case PAUSED: storeResult(operationResult); break; case RESUMED: deliverResult(operationResult); break; default: throw new IllegalStateException("Unknown state: " + mState); } }@Contract(pure = true) public final boolean isRunning(@NonNull final String tag) { final Integer id = mTaggedRequests.get(tag); //noinspection SimplifiableIfStatement if (id != null) { return isRunning(id); } else { return false; } }public final boolean cancel(@NonNull final String tag, final boolean mayInterrupt) { final Integer id = mTaggedRequests.get(tag); //noinspection SimplifiableIfStatement if (id != null) { return cancel(id, mayInterrupt); } else { return false; } }public final boolean cancel(final int id, final boolean mayInterrupt) { //noinspection SimplifiableIfStatement if (mUntaggedRequests.contains(id) || mTaggedRequests.containsValue(id)) { return RunningOperationStorage.getInstance().cancel(id, mayInterrupt); } else { return false; } }public final int invoke(@NonNull final ChronosOperation operation, @NonNull final String tag, final boolean broadcastResult) { logd("invoking tagged operation, tag=" + tag); final Integer savedId = mTaggedRequests.get(tag); if (savedId != null && isRunning(savedId)) { logd("operation with tag=" + tag + " is running, do nothing"); return savedId; } logd("operation with tag=" + tag + " is not running, start it"); final int id = ChronosService.getInstance().runAsync(operation, broadcastResult); mTaggedRequests.put(tag, id); return id; }public final int invoke(@NonNull final ChronosOperation operation, final boolean broadcastResult) { logd("invoking untagged operation"); final int id = ChronosService.getInstance().runAsync(operation, broadcastResult); mUntaggedRequests.add(id); return id; }@SuppressWarnings("unused") public final void onEventMainThread(@Nullable final ChronosOperationResult operationResult) { if (operationResult == null) { //somehow the bus delivered us a null object, it should be ignored return; } final int operationId = operationResult.getId(); DeliveryMode deliveryMode = null; if (!RunningOperationStorage.getInstance().isOperationCancelled(operationId)) { if (mTaggedRequests.containsValue(operationId)) { deliveryMode = DeliveryMode.NORMAL; } else if (mUntaggedRequests.contains(operationResult.getId())) { mUntaggedRequests.remove(Integer.valueOf(operationId)); deliveryMode = DeliveryMode.NORMAL; } else if (operationResult.isBroadcast()) { deliveryMode = DeliveryMode.BROADCAST; } } if (deliveryMode != null) { final OperationDelivery operationDelivery = new OperationDelivery<>(operationResult, deliveryMode); logd("operation delivery: " + operationDelivery); onOperationFinished(operationDelivery); } }public final void onResume(@NonNull final Object serviceListener) { logd("onResume"); mServiceListener = serviceListener; mState = State.RESUMED; if (!mStoredResults.isEmpty()) { logd("has undelivered results"); final List>> oldResults = new ArrayList<>( mStoredResults); mStoredResults.clear(); for (SoftReference> result : oldResults) { final OperationDelivery delivery = result.get(); if (delivery != null) { deliverResult(delivery); } } logd("no more undelivered results"); } else { logd("has no undelivered results"); } }@Contract(pure = true) private static boolean isCallback(@NonNull final Method method, @NonNull final Class resultClass, @NonNull final String methodName) { if (method.getName().equals(methodName)) { if (method.getReturnType() == Void.TYPE) { final Class[] parameters = method.getParameterTypes(); if (parameters.length == 1 && parameters[0].isAssignableFrom(resultClass)) { return true; } } } return false; }@NonNull public static ChronosOperationResult run( @NonNull final ChronosOperation operation) { return ChronosService.getInstance().runSync(operation, false); }@NonNull public final synchronized ChronosListener getListener(final int id) { ChronosListener chronosListener = mListeners.get(id); if (chronosListener == null) { chronosListener = new ChronosListener(id); mListeners.put(id, chronosListener); } return chronosListener; }public void addAlias(String key, String value) { this.aliases.put( notNull(key, "Key must not be null"), notNull(value, "Value must not be null") ); }public void addAliases(Map aliases) { notNull(aliases, "Aliases must not be null"); for (Map.Entry entry : aliases.entrySet()) { addAlias(entry.getKey(), entry.getValue()); } }public String render(String template, Map model) { try { Invocable invocable = (Invocable) engine; return (String) invocable.invokeFunction("render", template, model, partials); } catch (ScriptException ex) { throw new NashornException(ex); } catch (NoSuchMethodException ex) { throw new NashornException(ex); } }public static InputStream getFirstAvailableStream(Collection names) { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(IOUtils.class.getClassLoader()); for (String name : names) { try { InputStream stream = getInputStreamWithResolver(resolver, name); if (stream != null) { return stream; } } catch (MustacheIOException ex) { // Go to the next test } } throw new MustacheIOException("Unable to locate one of: " + names); }public static InputStream getStream(String name) { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(IOUtils.class.getClassLoader()); InputStream stream = getInputStreamWithResolver(resolver, name); // Not Found if (stream == null) { throw new MustacheIOException("Unable to locate {}" + name); } return stream; }@SuppressWarnings("unchecked") public static T getAnnotationValue(AnnotationMetadata importingClassMetadata, Class annotationClass, String name, T defaultValue) { Map attributes = importingClassMetadata.getAnnotationAttributes(annotationClass.getName()); return attributes != null && attributes.containsKey(name) ? (T) attributes.get(name) : defaultValue; }public static boolean isPresent(String klass) { hasText(klass, "Class name must not be empty"); try { Class.forName(klass); return true; } catch (Exception ex) { return false; } }public Map getLayoutMappings() { String mappingsValues = environment.getProperty("mustache.layoutMappings", MustacheSettings.LAYOUT_MAPPINGS).trim(); if (mappingsValues.isEmpty()) { return emptyMap(); } Map mappings = new HashMap(); String[] values = mappingsValues.split(";"); if (values.length > 0) { for (String value : values) { String val = value == null ? "" : value.trim(); if (val.isEmpty()) { continue; } String[] mapping = val.split(":"); if (mapping.length != 2) { throw new IllegalArgumentException("Mapping must use [viewName]:[layout] format!"); } mappings.put(mapping[0].trim(), mapping[1].trim()); } } return unmodifiableMap(mappings); }public static ScriptEngine getEngine(Collection scripts) { ScriptEngine engine = getEngine(); for (InputStream script : scripts) { evaluate(engine, script); } return engine; }@SuppressWarnings("unchecked") public Map getPartials() { final View view = this.getView(); if (view != null && view instanceof MustacheView) { MustacheView mustacheView = (MustacheView) view; return mustacheView.getAliases(); } else { final Object object = getModelMap().get(MustacheSettings.PARTIALS_KEY); if (object != null && !(object instanceof Map)) { throw new MustachePartialsMappingException(); } final Map map; if (object == null) { map = new HashMap(); } else { map = (Map) object; } return map; } }public final void setClosable(final boolean closable) { this.closable = closable; if (closable) { closeButton.setVisibility(View.VISIBLE); textView.setPadding(textView.getPaddingLeft(), textView.getPaddingTop(), 0, textView.getPaddingBottom()); } else { closeButton.setVisibility(View.GONE); textView.setPadding(textView.getPaddingLeft(), textView.getPaddingTop(), getResources().getDimensionPixelSize(R.dimen.chip_horizontal_padding), textView.getPaddingBottom()); } }public final void setColor(@ColorInt final int color) { this.color = color; getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN); }public final void removeCloseListener(@NonNull final CloseListener listener) { Condition.INSTANCE.ensureNotNull(listener, "The listener may not be null"); listeners.remove(listener); }public final void addCloseListener(@NonNull final CloseListener listener) { Condition.INSTANCE.ensureNotNull(listener, "The listener may not be null"); listeners.add(listener); }private void obtainCloseIcon(@NonNull final TypedArray typedArray) { Drawable icon = typedArray.getDrawable(R.styleable.Chip_closeButtonIcon); if (icon != null) { setCloseButtonIcon(icon); } }private void obtainClosable(@NonNull final TypedArray typedArray) { setClosable(typedArray.getBoolean(R.styleable.Chip_closable, false)); }private void obtainIcon(@NonNull final TypedArray typedArray) { setIcon(typedArray.getDrawable(R.styleable.Chip_android_icon)); }private void obtainColor(@NonNull final TypedArray typedArray) { int defaultColor = ContextCompat.getColor(getContext(), R.color.chip_color_light); setColor(typedArray.getColor(R.styleable.Chip_android_color, defaultColor)); }private void obtainTextColor(@NonNull final TypedArray typedArray) { int defaultColor = ContextCompat.getColor(getContext(), R.color.chip_text_color_light); setTextColor(typedArray.getColor(R.styleable.Chip_android_textColor, defaultColor)); }private void obtainText(@NonNull final TypedArray typedArray) { setText(typedArray.getText(R.styleable.Chip_android_text)); }private void handleSavedInstanceState(@Nullable final Bundle savedInstanceState) { if (savedInstanceState != null) { floatingActionButtonsVisible = savedInstanceState.getBoolean(FLOATING_ACTION_BUTTONS_VISIBLE_EXTRA); int visibility = floatingActionButtonsVisible ? View.VISIBLE : View.INVISIBLE; smallFloatingActionButton.setVisibility(visibility); normalFloatingActionButton.setVisibility(visibility); largeFloatingActionButton.setVisibility(visibility); } }private Chip.CloseListener createChipCloseListener() { return new Chip.CloseListener() { @Override public void onChipClosed(@NonNull final Chip chip) { chip.setVisibility(View.GONE); Toast.makeText(MainActivity.this, R.string.chip_closed_toast, Toast.LENGTH_SHORT) .show(); } }; }private void initializeChips() { Chip closableChipLight = findViewById(R.id.chip_closable_light); closableChipLight.addCloseListener(createChipCloseListener()); Chip closableChipDark = findViewById(R.id.chip_closable_dark); closableChipDark.addCloseListener(createChipCloseListener()); Chip closableIconChipLight = findViewById(R.id.chip_icon_closable_light); closableIconChipLight.addCloseListener(createChipCloseListener()); Chip closableIconChipDark = findViewById(R.id.chip_icon_closable_dark); closableIconChipDark.addCloseListener(createChipCloseListener()); }private OnClickListener createHideFloatingActionButtonsListener() { return new OnClickListener() { @Override public void onClick(final View v) { int visibility = floatingActionButtonsVisible ? View.INVISIBLE : View.VISIBLE; smallFloatingActionButton.setVisibility(visibility, true); normalFloatingActionButton.setVisibility(visibility, true); largeFloatingActionButton.setVisibility(visibility, true); floatingActionButtonsVisible = !floatingActionButtonsVisible; } }; }private void initializeHideFloatingActionButtonsButton() { Button button = findViewById(R.id.hide_floating_action_buttons); button.setOnClickListener(createHideFloatingActionButtonsListener()); }private OnClickListener createFloatingActionButtonListener() { return new OnClickListener() { @Override public void onClick(final View v) { Toast toast = Toast.makeText(MainActivity.this, R.string.floating_action_button_toast, Toast.LENGTH_SHORT); toast.show(); } }; }private void initializeFloatingActionButtons() { smallFloatingActionButton = findViewById(R.id.floating_action_button_small); smallFloatingActionButton.setOnClickListener(createFloatingActionButtonListener()); normalFloatingActionButton = findViewById(R.id.floating_action_button_normal); normalFloatingActionButton.setOnClickListener(createFloatingActionButtonListener()); largeFloatingActionButton = findViewById(R.id.floating_action_button_large); largeFloatingActionButton.setOnClickListener(createFloatingActionButtonListener()); }private AnimatorListener createSweepAnimatorListener() { return new AnimatorListener() { @Override public void onAnimationStart(final Animator animation) { } @Override public void onAnimationEnd(final Animator animation) { } @Override public void onAnimationCancel(final Animator animation) { } @Override public void onAnimationRepeat(final Animator animation) { appearing = !appearing; if (appearing) { currentGlobalAngleOffset = (currentGlobalAngleOffset + MIN_SWEEP_ANGLE * 2) % MAX_DEGREES; } } }; }private Property createSweepProperty() { return new Property(Float.class, "arc") { @Override public Float get(final CircularProgressDrawable object) { return currentSweepAngle; } @Override public void set(final CircularProgressDrawable object, final Float value) { currentSweepAngle = value; invalidateSelf(); } }; }private void initializeSweepAnimator() { sweepAnimator = ObjectAnimator .ofFloat(this, createSweepProperty(), MAX_DEGREES - MIN_SWEEP_ANGLE * 2); sweepAnimator.setInterpolator(new DecelerateInterpolator()); sweepAnimator.setDuration(SWEEP_ANIMATION_DURATION); sweepAnimator.setRepeatMode(ValueAnimator.RESTART); sweepAnimator.setRepeatCount(ValueAnimator.INFINITE); sweepAnimator.addListener(createSweepAnimatorListener()); }private Property createAngleProperty() { return new Property(Float.class, "angle") { @Override public Float get(final CircularProgressDrawable object) { return currentGlobalAngle; } @Override public void set(final CircularProgressDrawable object, final Float value) { currentGlobalAngle = value; invalidateSelf(); } }; }private void initializeAngleAnimator() { angleAnimator = ObjectAnimator.ofFloat(this, createAngleProperty(), MAX_DEGREES); angleAnimator.setInterpolator(new LinearInterpolator()); angleAnimator.setDuration(ANGLE_ANIMATION_DURATION); angleAnimator.setRepeatMode(ValueAnimator.RESTART); angleAnimator.setRepeatCount(ValueAnimator.INFINITE); }private void initializePaint() { paint = new Paint(); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(getThickness()); paint.setColor(getColor()); }private void obtainThickness(@NonNull final TypedArray typedArray) { int defaultThickness = getContext().getResources() .getDimensionPixelSize(R.dimen.circular_progress_bar_thickness_normal); thickness = typedArray .getDimensionPixelSize(R.styleable.CircularProgressBar_android_thickness, defaultThickness); }public final void setSize(@NonNull final Size size) { Condition.INSTANCE.ensureNotNull(size, "The size may not be null"); this.size = size; adaptShadow(); adaptImageButtonSize(); requestLayout(); }private AnimatorListener createVisibilityAnimatorListener(final int visibility) { return new AnimatorListener() { @Override public void onAnimationStart(final Animator animation) { if (visibility == View.VISIBLE) { FloatingActionButton.super.setVisibility(visibility); } } @Override public void onAnimationRepeat(final Animator animation) { } @Override public void onAnimationEnd(final Animator animation) { FloatingActionButton.super.setVisibility(visibility); visibilityAnimator = null; } @Override public void onAnimationCancel(final Animator animation) { visibilityAnimator = null; } }; }private void animateVisibility(final int visibility, final long duration) { if (visibilityAnimator != null) { visibilityAnimator.cancel(); } AnimatorListener listener = createVisibilityAnimatorListener(visibility); float targetScale = visibility == View.VISIBLE ? 1 : 0; long animationDuration = Math.round(Math.abs(getScaleX() - targetScale) * duration); Interpolator interpolator = new AccelerateDecelerateInterpolator(); visibilityAnimator = animate().setInterpolator(interpolator).scaleX(targetScale).scaleY(targetScale) .setDuration(animationDuration).setListener(listener); }private int getPixelSize() { if (getSize() == Size.NORMAL) { return getResources().getDimensionPixelSize(R.dimen.floating_action_button_size_normal); } else if (getSize() == Size.SMALL) { return getResources().getDimensionPixelSize(R.dimen.floating_action_button_size_small); } else { return getResources().getDimensionPixelSize(R.dimen.floating_action_button_size_large); } }private Drawable createBackgroundDrawable(@ColorInt final int color) { OvalShape shape = new OvalShape(); ShapeDrawable drawable = new ShapeDrawable(shape); drawable.getPaint().setColor(color); return drawable; }private Drawable createDisabledBackgroundDrawable() { Drawable drawable = createBackgroundDrawable(getColor()); Drawable hoverDrawable = createBackgroundDrawable(getDisabledColor()); return new LayerDrawable(new Drawable[]{drawable, hoverDrawable}); }private Drawable createPressedBackgroundDrawable() { Drawable drawable = createBackgroundDrawable(getColor()); Drawable hoverDrawable = createBackgroundDrawable(getPressedColor()); return new LayerDrawable(new Drawable[]{drawable, hoverDrawable}); }private Drawable createActivatedBackgroundDrawable() { Drawable drawable = createBackgroundDrawable(getColor()); Drawable hoverDrawable = createBackgroundDrawable(getActivatedColor()); return new LayerDrawable(new Drawable[]{drawable, hoverDrawable}); }private Drawable createStateListBackgroundDrawable() { StateListDrawable drawable = new StateListDrawable(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { drawable.addState(new int[]{android.R.attr.state_enabled, android.R.attr.state_pressed}, createPressedBackgroundDrawable()); } drawable.addState(new int[]{android.R.attr.state_enabled, android.R.attr.state_activated}, createActivatedBackgroundDrawable()); drawable.addState(new int[]{android.R.attr.state_enabled}, createBackgroundDrawable(getColor())); drawable.addState(new int[]{}, createDisabledBackgroundDrawable()); return drawable; }@SuppressLint("NewApi") private void adaptImageButtonBackground() { Drawable background = createStateListBackgroundDrawable(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Drawable rippleDrawable = new RippleDrawable( new ColorStateList(new int[][]{{}}, new int[]{getPressedColor()}), background, null); ViewUtil.setBackground(imageButton, rippleDrawable); } else { ViewUtil.setBackground(imageButton, background); } }private void adaptImageButtonSize() { int pixelSize = getPixelSize(); LayoutParams layoutParams = (LayoutParams) imageButton.getLayoutParams(); layoutParams.width = pixelSize; layoutParams.height = pixelSize; imageButton.setLayoutParams(layoutParams); imageButton.requestLayout(); }private void adaptShadow() { if (getSize() == Size.NORMAL) { setBackgroundResource(R.drawable.floating_action_button_shadow_normal); } else if (getSize() == Size.SMALL) { setBackgroundResource(R.drawable.floating_action_button_shadow_small); } else { setBackgroundResource(R.drawable.floating_action_button_shadow_large); } }private void obtainVisibilityAnimationDuration(@NonNull final TypedArray typedArray) { int defaultAnimationDuration = getResources() .getInteger(R.integer.floating_action_button_visibility_animation_duration); int duration = typedArray .getInteger(R.styleable.FloatingActionButton_visibilityAnimationDuration, defaultAnimationDuration); setVisibilityAnimationDuration(duration); }private void obtainIcon(@NonNull final TypedArray typedArray) { Drawable icon = typedArray.getDrawable(R.styleable.FloatingActionButton_android_icon); setIcon(icon); }private void obtainDisabledColor(@NonNull final TypedArray typedArray) { int defaultDisabledColor = ContextCompat.getColor(getContext(), R.color.floating_action_button_disabled_color); disabledColor = typedArray .getColor(R.styleable.FloatingActionButton_disabledColor, defaultDisabledColor); }private void obtainPressedColor(@NonNull final TypedArray typedArray) { int defaultPressedColor = getControlHighlightColor(); pressedColor = typedArray .getColor(R.styleable.FloatingActionButton_pressedColor, defaultPressedColor); }private void obtainActivatedColor(@NonNull final TypedArray typedArray) { int defaultActivatedColor = getControlActivatedColor(); activatedColor = typedArray .getColor(R.styleable.FloatingActionButton_activatedColor, defaultActivatedColor); }private void obtainColor(@NonNull final TypedArray typedArray) { int defaultColor = ThemeUtil.getColor(getContext(), R.attr.colorAccent); color = typedArray.getColor(R.styleable.FloatingActionButton_android_color, defaultColor); }private void obtainSize(@NonNull final TypedArray typedArray) { Size defaultSize = Size.NORMAL; size = Size.fromValue( typedArray.getInt(R.styleable.FloatingActionButton_size, defaultSize.getValue())); }public static StorageKey serializableKey(String keyName){ return new StorageKey<>(keyName, Serializable.class); }public static StorageKey isSerializableKey(String keyName){ return new StorageKey<>(keyName, IsSerializable.class); }@Deprecated public static StorageKey objectKey(String keyName){ return new StorageKey<>(keyName, Object.class); }public void remove(StorageKey key) { String data = storage.getItem(key.name()); storage.removeItem(key.name()); T value = cache.remove(key); fireEvent(StorageChangeEvent.ChangeType.REMOVE, key, null, value, null, data); }public void put(StorageKey key, T value) throws SerializationException, StorageQuotaExceededException { if(value == null){ throw new NullPointerException(); } try { String data = StorageUtils.serialize(key.getClazz(), value); // Update store and cache String oldData = storage.getItem(key.name()); storage.setItem(key.name(), data); T oldValue = cache.put(key, value); fireEvent(StorageChangeEvent.ChangeType.PUT, key, value, oldValue, data, oldData); } catch (JavaScriptException e) { String msg = e.getMessage(); if (msg != null && msg.contains("QUOTA") && msg.contains("DOM")) { throw new StorageQuotaExceededException(key, e); } throw e; } }public boolean containsKey(StorageKey key) { return storage.getItem(key.name()) != null; }public void clear() { storage.clear(); cache.clear(); fireEvent(StorageChangeEvent.ChangeType.CLEAR, null, null, null, null, null); }public static StorageExt getSessionStorage() { if (sessionStorage == null && Storage.isSessionStorageSupported()) { sessionStorage = new StorageExt(Storage.getSessionStorageIfSupported()); } return sessionStorage; }public static StorageExt getLocalStorage() { if (localStorage == null && Storage.isLocalStorageSupported()) { localStorage = new StorageExt(Storage.getLocalStorageIfSupported()); } return localStorage; }protected TemporalAccessor getFormattableObject(Object value, Locale locale, TimeZone timeZone, MustacheTagInfo tagInfo) { if (value instanceof TemporalAccessor) { return (TemporalAccessor) value; } else if (value instanceof Date) { return LocalDateTime.ofInstant(((Date) value).toInstant(), timeZone.toZoneId()); } else if (value instanceof Calendar) { return LocalDateTime.ofInstant(((Calendar) value).toInstant(), timeZone.toZoneId()); } else if (value instanceof Number) { return LocalDateTime.ofInstant( Instant.ofEpochMilli(((Number) value).longValue()), timeZone.toZoneId()); } else { throw valueNotAFormattableObject(value, tagInfo); } }public void invalidateFragments(final String keyPart) { if (fragments == null || keyPart == null) { return; } fragments.invalidate(fragmentKey -> fragmentKey.getKey().contains(keyPart)); }static List> readSegmentLinesBeforeRendering( AbstractContainerSegment container) { List> lines = new ArrayList<>(); List currentLine = new ArrayList<>(); for (Segment segment : container) { if (!SegmentType.LINE_SEPARATOR.equals(segment.getType())) { currentLine.add(segment); } else { // New line separator - flush the line currentLine.add(segment); lines.add(currentLine); currentLine = new ArrayList<>(); } } // Add the last line manually - there is no line separator to trigger // flush if (!currentLine.isEmpty()) { lines.add(currentLine); } return lines; }public static void registerHelper(ConfigurationExtensionBuilder builder, String name, Helper helper) { Checker.checkArgumentsNotNull(builder, name, helper); try { builder.registerHelper(name, helper); } catch (IllegalArgumentException ignored) { } }public static void registerHelpers(ConfigurationExtensionBuilder builder, Map helpers) { Checker.checkArgumentsNotNull(builder, helpers); for (Entry entry : helpers.entrySet()) { registerHelper(builder, entry.getKey(), entry.getValue()); } }static Field findField(Class clazz, String name) { checkArgumentNotNull(clazz); checkArgumentNotNull(name); Field found = null; for (Field field : SecurityActions.getFields(clazz)) { if (field.getName().equals(name)) { found = field; } } LOGGER.debug("Field {} {}found on type: {}", name, found != null ? "" : "not ", clazz.getName()); return found; }private void flush() { try { parent.append(future.get(60, TimeUnit.SECONDS).collect(this)); parent.append(buffer); if (parent instanceof AsyncAppendable) { ((AsyncAppendable) parent).flush(); } } catch (Exception e) { throw new MustacheException( MustacheProblem.RENDER_ASYNC_PROCESSING_ERROR, e); } }public static Builder decorate(Class delegateType) { return decorate(o -> (delegateType.isAssignableFrom(Decorator.unwrap(o).getClass()))); }static Iterator splitHelperName(String name, Segment segment) { boolean stringLiteral = false; boolean arrayLiteral = false; boolean space = false; List parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < name.length(); i++) { if (name.charAt(i) == ' ') { if (!space) { if (!stringLiteral && !arrayLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } space = true; } else { buffer.append(name.charAt(i)); } } } else { if (!arrayLiteral && Strings.isStringLiteralSeparator(name.charAt(i))) { stringLiteral = !stringLiteral; } else if (!stringLiteral && Strings.isListLiteralStart(name.charAt(i))) { arrayLiteral = true; } else if (!stringLiteral && Strings.isListLiteralEnd(name.charAt(i))) { arrayLiteral = false; } space = false; buffer.append(name.charAt(i)); } } if (buffer.length() > 0) { if (stringLiteral || arrayLiteral) { throw new MustacheException( MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE, "Unterminated string or array literal detected: %s", segment); } parts.add(buffer.toString()); } return parts.iterator(); }private RootSegmentBase validate() { ContainerSegmentBase root = containerStack.peekFirst(); if (!(root instanceof RootSegmentBase)) { throw new MustacheException( MustacheProblem.COMPILE_INVALID_TEMPLATE, "Incorrect last container segment on the stack: %s", containerStack.peekFirst().toString(), line); } return (RootSegmentBase) root; }private void addSegment(SegmentBase segment) { containerStack.peekFirst().addSegment(segment); LOGGER.trace("Add {}", segment); }private void push(ContainerSegmentBase container) { containerStack.addFirst(container); LOGGER.trace("Push {} [name: {}]", container.getType(), container.getContent()); }private ComputingCache> buildSourceCache() { return buildCache("Source", key -> Optional.ofNullable(locateAndRead(key)), (key, cause) -> LOGGER.debug("Removed template source from cache [templateId: {}, cause: {}]", key, cause)); }protected void append(Options options, CharSequence sequence) { TextSupport textSupport = this.textSupport; if (textSupport == null || isUnescapeVariable(options)) { options.append(sequence); } else { try { textSupport.appendEscapedHtml(sequence.toString(), options.getAppendable()); } catch (IOException e) { throw new MustacheException(MustacheProblem.RENDER_IO_ERROR, e); } } }public static String capitalizeFully(String text, Character delimiter) { if (isEmpty(text)) { return text; } text = text.toLowerCase(); boolean capitalizeNext = true; StringBuilder builder = new StringBuilder(); for (int i = 0; i < text.length(); i++) { final char ch = text.charAt(i); if (delimiter.equals(ch)) { capitalizeNext = true; builder.append(ch); } else if (capitalizeNext) { builder.append(Character.toTitleCase(ch)); capitalizeNext = false; } else { builder.append(ch); } } return builder.toString(); }public MustacheEngineBuilder addContextConverter(ContextConverter converter) { checkArgumentNotNull(converter); checkNotBuilt(); this.contextConverters.add(converter); return this; }public MustacheEngineBuilder addValueConverter(ValueConverter converter) { checkArgumentNotNull(converter); checkNotBuilt(); this.valueConverters.add(converter); return this; }public MustacheEngineBuilder registerCallback( EngineBuiltCallback callback) { checkArgumentNotNull(callback); checkNotBuilt(); this.engineReadyCallbacks.add(callback); return this; }public MustacheEngineBuilder addResolver(Resolver resolver) { checkArgumentNotNull(resolver); checkNotBuilt(); this.resolvers.add(resolver); return this; }public MustacheEngineBuilder addTemplateLocator(TemplateLocator locator) { checkArgumentNotNull(locator); checkNotBuilt(); this.templateLocators.add(locator); return this; }public synchronized MustacheEngine build() { MustacheEngine engine = new DefaultMustacheEngine(this); for (EngineBuiltCallback callback : engineReadyCallbacks) { callback.engineBuilt(engine); } BuildInfo buildInfo = BuildInfo.load(); LOGGER.info("Engine built {} ({})", buildInfo.getVersion(), buildInfo.getTimestampDate()); LOGGER.debug("Engine configuration: {}", engine.getConfiguration().getInfo()); isBuilt = true; return engine; }@SuppressWarnings("unchecked") public static T unwrap(T instance) { return instance instanceof Decorator ? unwrap(((Decorator) instance).delegate) : instance; }public static Decorator decorate(T delegate, Map> mappings, String delegateKey, Configuration configuration) { return IterableDecorator.isIterable(delegate) ? new IterableDecorator<>(delegate, ImmutableMap.copyOf(mappings), delegateKey, configuration) : new Decorator<>(delegate, ImmutableMap.copyOf(mappings), delegateKey, configuration); }public static Pattern newMustacheTagPattern(Configuration configuration) { StringBuilder regex = new StringBuilder(); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.START_DELIMITER))); regex.append(".*?"); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.END_DELIMITER))); return Pattern.compile(regex.toString()); }private static List> readSegmentLines( ContainerSegmentBase container) { List> lines = new ArrayList<>(); // Add the last line manually - there is no line separator to trigger // flush lines.add(readSegmentLines(lines, null, container)); return lines; }private String extractContent(MustacheTagType tagType, String buffer) { switch (tagType) { case VARIABLE: return buffer.trim(); case UNESCAPE_VARIABLE: return (buffer.charAt(0) == ((String) EngineConfigurationKey.START_DELIMITER .getDefaultValue()).charAt(0) ? buffer.substring(1, buffer.length() - 1).trim() : buffer.substring(1).trim()); case SECTION: case INVERTED_SECTION: case PARTIAL: case EXTEND: case EXTEND_SECTION: case SECTION_END: case NESTED_TEMPLATE: case COMMENT: return buffer.substring(1).trim(); case DELIMITER: return buffer.trim(); default: return null; } }private void flushTag() { state = State.TEXT; handler.tag(deriveTag(buffer.toString())); delimiterIdx = 0; clearBuffer(); }private void lineSeparatorFound(String lineSeparator) { flushText(); flushLineSeparator(lineSeparator); line++; state = State.TEXT; separatorIdx = 0; }static MemberKey newInstance(Object contextObject, String name) { if (contextObject instanceof Class) { Class clazz = (Class) contextObject; if (clazz.isEnum() && ("values".equals(name) || Reflections.isConstantName(clazz, name))) { // Special handling for enums - allows to access values() and constants return new MemberKey(clazz, name); } } return new MemberKey(contextObject.getClass(), name); }public void setHref(String href) { if (href.contains("%7B")) { try { href = URLDecoder.decode(href, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } this.href = new UriTemplate(href); }private void guaranteeHasAllTargets(TrafficSource trafficSource, TargetGroup targetGroup, Collection targets, Collection baragonAgents) { Collection targetDescriptions = new HashSet<>(); for (BaragonAgentMetadata agent : baragonAgents) { try { if ((trafficSource.getRegisterBy() == RegisterBy.INSTANCE_ID && agent.getEc2().getInstanceId().isPresent()) || (trafficSource.getRegisterBy() == RegisterBy.PRIVATE_IP && agent.getEc2().getPrivateIp().isPresent())) { String id = trafficSource.getRegisterBy() == RegisterBy.INSTANCE_ID ? agent.getEc2().getInstanceId().get() : agent.getEc2().getPrivateIp().get(); if (agentShouldRegisterInTargetGroup(id, targets)) { targetDescriptions.add(new TargetDescription() .withId(id)); LOG.info("Will register agent {} to target in group {}", agent, targetGroup); } else { LOG.debug("Agent {} is already registered", agent); } } } catch (Exception exn) { LOG.error("Could not create request to register agent {} due to error", agent, exn); exceptionNotifier.notify(exn, ImmutableMap.of("agent", agent.toString())); } } if (targetDescriptions.isEmpty()) { LOG.debug("No new instances to register with target group"); } else { try { RegisterTargetsRequest registerTargetsRequest = new RegisterTargetsRequest() .withTargetGroupArn(targetGroup.getTargetGroupArn()) .withTargets(targetDescriptions); elbClient.registerTargets(registerTargetsRequest); LOG.info("Registered targets {} onto target group {}", targetDescriptions, targetGroup); } catch (AmazonClientException acexn) { LOG.error("Failed to register targets {} onto target group {}", targetDescriptions, targetGroup); exceptionNotifier.notify(acexn, ImmutableMap.of( "targets", targetDescriptions.toString(), "targetGroup", targetGroup.toString())); } } }private void guaranteeSameVPC(TargetGroup targetGroup, Collection agents, Collection loadBalancers) { String vpcId = targetGroup.getVpcId(); for (BaragonAgentMetadata agent : agents) { if (agent.getEc2().getVpcId().isPresent()) { if (! agent.getEc2().getVpcId().get().equals(vpcId)) { LOG.error("Agent {} not on same VPC as its target group {}", agent, targetGroup); throw new IllegalStateException(String.format("Agent %s not on same VPC as its target group %s", agent, targetGroup)); } } else { LOG.error("Agent {} not assigned to a VPC", agent); throw new IllegalStateException(String.format("Agent %s not assigned to a VPC", agent)); } } for (LoadBalancer loadBalancer : loadBalancers) { if (!vpcId.equals(loadBalancer.getVpcId())) { LOG.error("Load balancer {} on different VPC from target group {}", loadBalancer, targetGroup); throw new IllegalStateException(String.format("Load balancer %s on different VPC from target group %s", loadBalancer, targetGroup)); } } }private void deregisterRemovableTargets(TrafficSource trafficSource, BaragonGroup baragonGroup, TargetGroup targetGroup, Collection agents, Collection targets) { Collection removableTargets = listRemovableTargets(trafficSource, baragonGroup, targets, agents); for (TargetDescription removableTarget : removableTargets) { try { if (configuration.isPresent() && !configuration.get().isRemoveLastHealthyEnabled() && isLastHealthyInstance(removableTarget, targetGroup)) { LOG.info("Will not de-register target {} because it is last healthy instance in {}", removableTarget, targetGroup); } else { elbClient.deregisterTargets(new DeregisterTargetsRequest() .withTargetGroupArn(targetGroup.getTargetGroupArn()) .withTargets(removableTarget)); LOG.info("De-registered target {} from target group {}", removableTarget, targetGroup); } } catch (AmazonClientException acexn) { LOG.error("Could not de-register target {} from target group {} due to error", removableTarget, targetGroup, acexn); exceptionNotifier.notify(acexn, ImmutableMap .of("targetGroup", targetGroup.getTargetGroupName())); } } }private void guaranteeRegistered(TrafficSource trafficSource, TargetGroup targetGroup, Collection targets, Collection baragonAgents, Collection loadBalancers) { /* - Check that load balancers, baragon agents, target groups are on same VPC - Check that load balancers, targets are on same subnet (== AZ) - Check that all baragon agents are associated with a target on target group - Check that load balancers has listeners, rules to make talk to target group */ if (configuration.isPresent() && configuration.get().isCheckForCorrectVpc()) { guaranteeSameVPC(targetGroup, baragonAgents, loadBalancers); } guaranteeAzEnabled(baragonAgents, loadBalancers); guaranteeHasAllTargets(trafficSource, targetGroup, targets, baragonAgents); //guaranteeListenersPresent(targetGroup, loadBalancers); }public Collection getQueuedRequests() { final String uri = String.format(REQUEST_FORMAT, getBaseUrl()); return getCollection(uri, "queued requests", QUEUED_REQUEST_COLLECTION); }public Optional getRequest(String requestId) { final String uri = String.format(REQUEST_ID_FORMAT, getBaseUrl(), requestId); return getSingle(uri, "request", requestId, BaragonResponse.class); }public Collection getOccupiedBasePaths(String loadBalancerGroupName) { final String requestUri = String.format(LOAD_BALANCER_ALL_BASE_PATHS_FORMAT, getBaseUrl(), loadBalancerGroupName); return getCollection(requestUri, "occupied base paths", STRING_COLLECTION); }public Collection getLoadBalancerGroups() { final String requestUri = String.format(LOAD_BALANCER_FORMAT, getBaseUrl()); return getCollection(requestUri, "load balancer groups", STRING_COLLECTION); }public Collection getGlobalState() { final String uri = String.format(STATE_FORMAT, getBaseUrl()); return getCollection(uri, "global state", BARAGON_SERVICE_STATE_COLLECTION); }public Optional getBaragonServiceStatus(String baseUrl) { final String uri = String.format(STATUS_FORMAT, baseUrl); return getSingle(uri, "status", "", BaragonServiceStatus.class); }@Override public boolean invalidateIfNecessary(BaragonRequest request) { if (request.getLoadBalancerService().getEdgeCacheDomains().isEmpty()) { return false; } try { boolean allSucceeded = true; for (String edgeCacheDNS : request.getLoadBalancerService().getEdgeCacheDomains()) { List matchingZones = getCloudflareZone(edgeCacheDNS); if (matchingZones.isEmpty()) { LOG.warn("`edgeCacheDNS` was defined on the request, but no matching Cloudflare Zone was found!"); return false; } for (CloudflareZone matchingZone : matchingZones) { String zoneId = matchingZone.getId(); Optional matchingDnsRecord = getCloudflareDnsRecord(edgeCacheDNS, zoneId); if (!matchingDnsRecord.isPresent()) { LOG.warn("`edgeCacheDNS` was defined on the request, but no matching Cloudflare DNS Record was found!"); return false; } if (!matchingDnsRecord.get().isProxied()) { LOG.warn("`edgeCacheDNS` was defined on the request, but {} is not a proxied DNS record!", edgeCacheDNS); return false; } String cacheTag = String.format( edgeCacheConfiguration.getIntegrationSettings().get("cacheTagFormat"), request.getLoadBalancerService().getServiceId() ); LOG.debug("Sending cache purge request against {} for {} to Cloudflare...", matchingDnsRecord.get().getName(), cacheTag); allSucceeded = cf.purgeEdgeCache(zoneId, Collections.singletonList(cacheTag)) && allSucceeded; } } return allSucceeded; } catch (CloudflareClientException e) { LOG.error("Unable to invalidate Cloudflare cache for request {}", request, e); return false; } }public void logoutAndClearState() { if (client != null && client.isConnected()) { logout(); client.disconnect(); } activity = null; client = null; }void connectAndRequestGoogleAccount(int signInRequestCode, int errorResolutionRequestCode) { if (client.isConnected()) { requestGoogleAccount(signInRequestCode); } else if (!client.isConnecting()) { this.signInRequestCode = signInRequestCode; this.errorResolutionRequestCode = errorResolutionRequestCode; client.connect(); } }Dialog getErrorDialog(int errorCode, int requestCode) { final Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(activity, errorCode, requestCode); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { resolvingError = false; } }); return dialog; }public String createToken(Map data, TokenOptions options) { if ((data == null || data.size() == 0) && (options == null || (!options.isAdmin() && !options.isDebug()))) { throw new IllegalArgumentException("TokenGenerator.createToken: data is empty and no options are set. This token will have no effect on Firebase."); } JSONObject claims = new JSONObject(); try { claims.put("v", TOKEN_VERSION); claims.put("iat", new Date().getTime() / 1000); boolean isAdminToken = (options != null && options.isAdmin()); validateToken("TokenGenerator.createToken", data, isAdminToken); if (data != null && data.size() > 0) { claims.put("d", new JSONObject(data)); } // Handle options if (options != null) { if (options.getExpires() != null) { claims.put("exp", options.getExpires().getTime() / 1000); } if (options.getNotBefore() != null) { claims.put("nbf", options.getNotBefore().getTime() / 1000); } // Only add these claims if they're true to avoid sending them over the wire when false. if (options.isAdmin()) { claims.put("admin", options.isAdmin()); } if (options.isDebug()) { claims.put("debug", options.isDebug()); } } } catch (JSONException e) { throw new RuntimeException(e); } String token = computeToken(claims); if (token.length() > 1024) { throw new IllegalArgumentException("TokenGenerator.createToken: Generated token is too long. The token cannot be longer than 1024 bytes."); } return token; }private Date copyDate(Date date) { return (date != null) ? new Date(date.getTime()) : null; }public static String encode(JSONObject claims, String secret) { String encodedHeader = getCommonHeader(); String encodedClaims = encodeJson(claims); String secureBits = new StringBuilder(encodedHeader).append(TOKEN_SEP).append(encodedClaims).toString(); String sig = sign(secret, secureBits); return new StringBuilder(secureBits).append(TOKEN_SEP).append(sig).toString(); }public Stubbing createStubbing(final Charset defaultEncoding, final int defaultStatus, final MultiMap defaultHeaders) { return new Stubbing(defaultEncoding, defaultStatus, defaultHeaders); }static void addEncoding(final Request.Builder builder, final HttpExchange httpExchange) { final String contentType = httpExchange.getRequestHeaders().getFirst("Content-Type"); if (contentType != null) { final Matcher matcher = CHARSET_PATTERN.matcher(contentType); if (matcher.matches()) { try { builder.encoding(Charset.forName(matcher.group(1))); } catch (UnsupportedCharsetException e) { //just ignore, fallback encoding will be used instead } } } }public List getValues(final String key) { Validate.notEmpty(key, "name cannot be empty"); @SuppressWarnings("unchecked") final List result = (List) values.get(key.toLowerCase()); return result == null || result.isEmpty() ? null : new ArrayList(result); }public String getValue(final String key) { Validate.notEmpty(key, "key cannot be empty"); final List allValues = this.getValues(key); return allValues != null ? allValues.get(0) : null; }public void receivedTimes(final Matcher nrRequestsPredicate) { Validate.notNull(nrRequestsPredicate, "predicate cannot be null"); this.requestManager.evaluateVerification(predicates, nrRequestsPredicate); }public void addDefaultHeader(final String name, final String value) { Validate.notEmpty(name, "header name cannot be empty"); Validate.notNull(value, "header value cannot be null, use an empty string instead"); this.checkConfigurable(); this.defaultHeaders.put(name, value); }public void register(Session session, int ops) throws ClosedChannelException { if (sessions.containsKey(session.getID())) { throw new IllegalStateException("Altready registered session"); } SelectionKey selKey; try { selKey = session.getChannel().register(selector, ops, session); } catch (ClosedChannelException e) { Logger.error("Error while register channel to selector. {}", session, e); throw e; } session.setSelectionKey(selKey); }public void loopProcess() { for (Session session : sessions.values()) { long timeMillis = System.currentTimeMillis(); try { session.callbackOnLoop(timeMillis); } catch (Exception e) { Logger.error("Exception occurs while callbackOnLoop on {}", session, e); } } }public void ioProcess() { int numberOfKeys; try { numberOfKeys = selector.select(selectTimeout); } catch (IOException e) { Logger.error("Selector.select error.", e); return; } if (0 == numberOfKeys) { return; } Iterator keyIter = selector.selectedKeys().iterator(); while (keyIter.hasNext()) { SelectionKey key = keyIter.next(); Session session = (Session) key.attachment(); long timeMillis = System.currentTimeMillis(); try { if (key.isValid() && key.isReadable()) { long start = System.currentTimeMillis(); session.callbackRead(key, timeMillis); long end = System.currentTimeMillis(); Statistics.updateNioRead(end - start); } if (key.isValid() && key.isWritable()) { long start = System.currentTimeMillis(); session.callbackWrite(key, timeMillis); long end = System.currentTimeMillis(); Statistics.updateNioWrite(end - start); } if (key.isValid() && key.isAcceptable()) { session.callbackAccept(key, timeMillis); } if (key.isValid() && key.isConnectable()) { session.callbackConnect(key, timeMillis); } } catch (CancelledKeyException e) { Logger.warn("Closed connection {}", session, e); } catch (ClosedChannelException e) { Logger.warn("Closed connection {}", session, e); } catch (IOException e) { Logger.warn("Closed connection {}", session, e); } catch (Exception e) { Logger.error("Exception occurs on {}", session, e); } keyIter.remove(); } }public ElapsedTime process() { try { long start = System.currentTimeMillis(); ioProcess(); long ioDone = System.currentTimeMillis(); loopProcess(); long end = System.currentTimeMillis(); return new ElapsedTime(start, ioDone, end); } catch (Exception e) { Logger.error("-ERR error occurs in hbMain", e); } return null; }public void shutdown() throws IOException { try { selector.close(); } catch (IOException e) { Logger.error("Close nio event selector fail.", e); throw e; } }public void getrange(byte[] key, long startOffset, long endOffset) { sendCommand(Command.GETRANGE, key, RedisProtocol.toByteArray(startOffset), RedisProtocol.toByteArray(endOffset)); }public void getbit(byte[] key, long offset) { sendCommand(Command.GETBIT, key, RedisProtocol.toByteArray(offset)); }public void configSet(final byte[] parameter, final byte[] value) { sendCommand(Command.CONFIG, Keyword.SET.raw, parameter, value); }public void slaveofNoOne() { sendCommand(Command.SLAVEOF, Keyword.NO.raw, Keyword.ONE.raw); }public void zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max, final int offset, final int count) { sendCommand(Command.ZRANGEBYSCORE, key, min, max, Keyword.LIMIT.raw, RedisProtocol.toByteArray(offset), RedisProtocol.toByteArray(count), Keyword.WITHSCORES.raw); }public void zrangeByScore(final byte[] key, final byte[] min, final byte[] max) { sendCommand(Command.ZRANGEBYSCORE, key, min, max); }public void zaddBinary(final byte[] key, Map scoreMembers) { ArrayList args = new ArrayList(scoreMembers.size() * 2 + 1); args.add(key); for (Map.Entry entry : scoreMembers.entrySet()) { args.add(RedisProtocol.toByteArray(entry.getKey())); args.add(entry.getValue()); } byte[][] argsArray = new byte[args.size()][]; args.toArray(argsArray); sendCommand(Command.ZADD, argsArray); }public void incrBy(final byte[] key, final long integer) { sendCommand(Command.INCRBY, key, RedisProtocol.toByteArray(integer)); }public void decrBy(final byte[] key, final long integer) { sendCommand(Command.DECRBY, key, RedisProtocol.toByteArray(integer)); }public void expireAt(final byte[] key, final long millisecondsTimestamp) { sendCommand(Command.EXPIREAT, key, RedisProtocol.toByteArray(millisecondsTimestamp)); }private byte[][] joinParameters(byte[] first, byte[][] rest) { byte[][] result = new byte[rest.length + 1][]; result[0] = first; for (int i = 0; i < rest.length; i++) { result[i + 1] = rest[i]; } return result; }public static void checkPermission(String path, LockType type) throws MgmtZooKeeperException { if (znodePermission.get() != null) { znodePermission.get().checkPermission(path, type); } }public void setquorum(PartitionGroupServer master, int q, String quorumMembers) throws MgmtSetquorumException, MgmtSmrCommandException { master.setQuorum(q, quorumMembers); }String toExecuteInfo(final int tryCount, final long startedTime, final GatewayServer server, final RedisCluster redis) { final StringBuilder sb = new StringBuilder(); final long executedTime = System.currentTimeMillis() - startedTime; sb.append("time=").append(executedTime).append(", "); sb.append("retry=").append(tryCount).append(", "); sb.append("gateway=").append(server); if (redis != null) { sb.append(", ").append("connect=").append(redis.connectInfo()); } return sb.toString(); }public synchronized void stop() { state = State.STOP; dispatchEvent(LeaderElectionEventType.STOP_START); logger.info("Stopping leader election support"); if (leaderOffer != null) { try { zooKeeper.delete(leaderOffer.getNodePath(), -1); logger.info("Removed leader offer {}", leaderOffer.getNodePath()); } catch (InterruptedException e) { becomeFailed(e); } catch (KeeperException e) { becomeFailed(e); } } dispatchEvent(LeaderElectionEventType.STOP_COMPLETE); }private Set getTupledSet() { List membersWithScores = client.getMultiBulkReply(); Set set = new LinkedHashSet(); Iterator iterator = membersWithScores.iterator(); while (iterator.hasNext()) { set.add(new Tuple(iterator.next(), Double.valueOf(iterator.next()))); } return set; }public void sync() { if (this.client == null) { return; } List unformatted = null; try { unformatted = this.client.getAll(); } catch (Exception e) { this.brokenResource = true; throw new GatewayException("gateway=" + this.server + ", connect=" + this.redis.connectInfo(), e); } if (unformatted == null) { return; } for (Object o : unformatted) { try { generateResponse(o); } catch (Exception ignored) { } } }public void set(final String key, final String value) { set(SafeEncoder.encode(key), SafeEncoder.encode(value)); }public static int parsePort(final String address) { int sp = address.indexOf(":"); if (sp == -1 && sp + 1 >= address.length()) { throw new IllegalArgumentException("not found port '" + address + "'"); } try { return Integer.parseInt(address.substring(sp + 1, address.length()).trim()); } catch (NumberFormatException nfe) { throw new IllegalArgumentException("bad port number '" + address + "'"); } }public static String parseHost(final String address) { int ep = address.indexOf(":"); if (ep == -1 || ep == 0) { throw new IllegalArgumentException("invalid address '" + address + "'"); } return address.substring(0, ep).trim(); }public static List asListFromDomain(final String domainAddress) { if (domainAddress == null) { throw new IllegalArgumentException("domain address must not be null"); } GatewayAddress domain = new GatewayAddress(0, domainAddress); InetAddress[] addresses; try { addresses = InetAddress.getAllByName(domain.getHost()); } catch (Exception e) { throw new IllegalArgumentException("invalid domain '" + domain + "' " + e.getMessage()); } List list = new ArrayList(); int id = 1; for (InetAddress address : addresses) { list.add(new GatewayAddress(id++, address.getHostAddress(), domain.getPort())); } return list; } Map> deserializeHashSet(Map> entries) { // connection in pipeline/multi mode if (entries == null) { return null; } Map> map = new LinkedHashMap>(entries.size()); for (Map.Entry> entry : entries.entrySet()) { map.put((HK) deserializeHashKey(entry.getKey()), (Set) deserializeValues(entry.getValue())); } return map; } Map> deserializeHashList(Map> entries) { // connection in pipeline/multi mode if (entries == null) { return null; } Map> map = new LinkedHashMap>(entries.size()); for (Map.Entry> entry : entries.entrySet()) { map.put((HK) deserializeHashKey(entry.getKey()), (List) deserializeHashValues(entry.getValue())); } return map; }@SuppressWarnings("unchecked") Map deserializeHashMap(Map entries) { // connection in pipeline/multi mode if (entries == null) { return null; } Map map = new LinkedHashMap(entries.size()); for (Map.Entry entry : entries.entrySet()) { map.put((HK) deserializeHashKey(entry.getKey()), (HV) deserializeHashValue(entry.getValue())); } return map; }@SuppressWarnings("unchecked") List deserializeHashValues(List rawValues) { return SerializationUtils.deserialize(rawValues, hashValueSerializer()); }@SuppressWarnings("unchecked") Set deserializeHashKeys(Set rawKeys) { return SerializationUtils.deserialize(rawKeys, hashKeySerializer()); }@SuppressWarnings("unchecked") Set> deserializeTupleValues(Set rawValues) { Set> set = new LinkedHashSet>(rawValues.size()); for (Tuple rawValue : rawValues) { set.add(new DefaultTypedTuple(valueSerializer().deserialize(rawValue.getValue()), rawValue.getScore())); } return set; }@SuppressWarnings("unchecked") byte[] rawHashKey(HK hashKey) { Assert.notNull(hashKey, "non null hash key required"); return hashKeySerializer().serialize(hashKey); }@SuppressWarnings("unchecked") byte[] rawKey(Object key) { Assert.notNull(key, "non null key required"); return keySerializer().serialize(key); }private Set getBinaryTupledSet() { List membersWithScores = client.getBinaryMultiBulkReply(); Set set = new LinkedHashSet(); if (membersWithScores == null) { return set; } Iterator iterator = membersWithScores.iterator(); if (iterator == null) { return set; } while (iterator.hasNext()) { set.add(new Tuple(iterator.next(), Double.valueOf(SafeEncoder.encode(iterator.next())))); } return set; }@SuppressWarnings("unchecked") public static List getBinaryMultiBulkReply(byte[] input) { return (List) RedisProtocol.read( new RedisInputStream(new ByteArrayInputStream(input))); }public static Generator createOrthogonal() { return () -> { final SecureRandom rng = new SecureRandom(); final double r0c0 = 1.0; final double r0c1 = 0.0; final double r0c2 = 0.0; final double r0c3 = rng.nextDouble(); final double r1c0 = 0.0; final double r1c1 = 1.0; final double r1c2 = 0.0; final double r1c3 = rng.nextDouble(); final double r2c0 = 0.0; final double r2c1 = 0.0; final double r2c2 = 1.0; final double r2c3 = rng.nextDouble(); final double r3c0 = 0.0; final double r3c1 = 0.0; final double r3c2 = 0.0; final double r3c3 = 1.0; return Matrix4x4D.of( r0c0, r0c1, r0c2, r0c3, r1c0, r1c1, r1c2, r1c3, r2c0, r2c1, r2c2, r2c3, r3c0, r3c1, r3c2, r3c3); }; }public R findBy(ClassFileScanConfiguration scanConfig, SearchCriteria criteria) { scanConfig = scanConfig.createCopy(); criteria = criteria.createCopy(); C context = createContext(scanConfig, criteria); criteria.init(this.classHelper, context.pathMemoryClassLoader, this.memberFinder, this.pathHelper); scanConfig.init(); fileSystemHelper.scan( scanConfig.toScanConfiguration(context, this) ); Collection skippedClassesNames = context.getSkippedClassNames(); if (!skippedClassesNames.isEmpty()) { logWarn("Skipped classes count: {}", skippedClassesNames.size()); } return resultSupplier.apply(context); }public static double determinant3x3( final double r0c0, final double r0c1, final double r0c2, final double r1c0, final double r1c1, final double r1c2, final double r2c0, final double r2c1, final double r2c2) { double sum = 0.0; sum += r0c0 * ((r1c1 * r2c2) - (r1c2 * r2c1)); sum -= r0c1 * ((r1c0 * r2c2) - (r1c2 * r2c0)); sum += r0c2 * ((r1c0 * r2c1) - (r1c1 * r2c0)); return sum; }private boolean hasPublicEmptyConstructor(DeclaredType type) { Element element = type.asElement(); List containing = element.getEnclosedElements(); for (Element e : containing) { if (e.getKind() == ElementKind.CONSTRUCTOR) { ExecutableElement c = (ExecutableElement) e; if ((c.getParameters() == null || c.getParameters().isEmpty()) && c.getModifiers() .contains(javax.lang.model.element.Modifier.PUBLIC)) { return true; } } } return false; }private boolean isPublicClass(DeclaredType type) { Element element = type.asElement(); return element.getModifiers().contains(javax.lang.model.element.Modifier.PUBLIC); }private void generateWriteToParcel(JavaWriter jw, String originClass, List fields) throws IOException { jw.beginMethod("void", "writeToParcel", EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), originClass, PARAM_SOURCE, "Parcel", PARAM_PARCEL, "int", PARAM_FLAGS); for (ParcelableField field : fields) { FieldCodeGen gen = field.getCodeGenerator(); if (gen == null) { // Already checked before, but let's check it again ProcessorMessage.error(field.getElement(), "The field %s is not Parcelable or of unsupported type. Use a @%s", field.getFieldName(), Bagger.class.getSimpleName() + " to provide your own serialisation mechanism"); throw new IOException("Unparcelable Field " + field.getFieldName()); } jw.emitEmptyLine(); gen.generateWriteToParcel(field, jw); } jw.endMethod(); }public static String getBinaryName(Elements elementUtils, TypeElement type) throws IOException { String packageName = getPackageName(elementUtils, type); String qualifiedName = type.getQualifiedName().toString(); if (packageName.length() > 0) { return packageName + '.' + qualifiedName.substring(packageName.length() + 1).replace('.', '$'); } else { return qualifiedName.replace('.', '$'); } }public static String getPackageName(Elements elementUtils, TypeElement type) throws IOException { PackageElement pkg = elementUtils.getPackageOf(type); if (!pkg.isUnnamed()) { return pkg.getQualifiedName().toString(); } else { return ""; // Default package } }public static Class isTypeOf(TypeMirror type, List> classList) { for (Class c : classList) { if (isTypeOf(type, c)) { return c; } } return null; }public static boolean isTypeOf(TypeMirror type, Class clazz) { return type.toString().equals(clazz.getCanonicalName()); }private boolean isClass(Element element) { if (element.getKind() == ElementKind.CLASS) { if (element.getModifiers().contains(Modifier.ABSTRACT)) { ProcessorMessage.error(element, "Element %s is annotated with @%s but is an abstract class. " + "Abstract classes can not be annotated. Annotate the concrete class " + "that implements all abstract methods with @%s", element.getSimpleName(), ParcelablePlease.class.getSimpleName(), ParcelablePlease.class.getSimpleName()); return false; } if (element.getModifiers().contains(Modifier.PRIVATE)) { ProcessorMessage.error(element, "The private class %s is annotated with @%s. " + "Private classes are not supported because of lacking visibility.", element.getSimpleName(), ParcelablePlease.class.getSimpleName()); return false; } // Ok, its a valid class return true; } else { ProcessorMessage.error(element, "Element %s is annotated with @%s but is not a class. Only Classes are supported", element.getSimpleName(), ParcelablePlease.class.getSimpleName()); return false; } }private void makeClassImplementParcelable(PsiElementFactory elementFactory, JavaCodeStyleManager styleManager) { final PsiClassType[] implementsListTypes = psiClass.getImplementsListTypes(); final String implementsType = "android.os.Parcelable"; for (PsiClassType implementsListType : implementsListTypes) { PsiClass resolved = implementsListType.resolve(); // Already implements Parcelable, no need to add it if (resolved != null && implementsType.equals(resolved.getQualifiedName())) { return; } } PsiJavaCodeReferenceElement implementsReference = elementFactory.createReferenceFromText(implementsType, psiClass); PsiReferenceList implementsList = psiClass.getImplementsList(); if (implementsList != null) { styleManager.shortenClassReferences(implementsList.add(implementsReference)); } }public void generate() { PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiClass.getProject()); JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(psiClass.getProject()); // Clear any previous clearPrevious(); // Implements parcelable makeClassImplementParcelable(elementFactory, styleManager); // @ParcelablePlease Annotation addAnnotation(elementFactory, styleManager); // Creator PsiField creatorField = elementFactory.createFieldFromText(generateCreator(), psiClass); // Describe contents method PsiMethod describeContentsMethod = elementFactory.createMethodFromText(generateDescribeContents(), psiClass); // Method for writing to the parcel PsiMethod writeToParcelMethod = elementFactory.createMethodFromText(generateWriteToParcel(), psiClass); styleManager.shortenClassReferences( psiClass.addBefore(describeContentsMethod, psiClass.getLastChild())); styleManager.shortenClassReferences( psiClass.addBefore(writeToParcelMethod, psiClass.getLastChild())); styleManager.shortenClassReferences(psiClass.addBefore(creatorField, psiClass.getLastChild())); }private void findAndRemoveMethod(String methodName, String... arguments) { // Maybe there's an easier way to do this with mClass.findMethodBySignature(), but I'm not an expert on Psi* PsiMethod[] methods = psiClass.findMethodsByName(methodName, false); for (PsiMethod method : methods) { PsiParameterList parameterList = method.getParameterList(); if (parameterList.getParametersCount() == arguments.length) { boolean shouldDelete = true; PsiParameter[] parameters = parameterList.getParameters(); for (int i = 0; i < arguments.length; i++) { if (!parameters[i].getType().getCanonicalText().equals(arguments[i])) { shouldDelete = false; } } if (shouldDelete) { method.delete(); } } } }private PsiClass getPsiClassFromContext(AnActionEvent e) { PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE); Editor editor = e.getData(PlatformDataKeys.EDITOR); if (psiFile == null || editor == null) { return null; } int offset = editor.getCaretModel().getOffset(); PsiElement element = psiFile.findElementAt(offset); return PsiTreeUtil.getParentOfType(element, PsiClass.class); }private void emitModifiers(Set modifiers) throws IOException { if (modifiers.isEmpty()) { return; } // Use an EnumSet to ensure the proper ordering if (!(modifiers instanceof EnumSet)) { modifiers = EnumSet.copyOf(modifiers); } for (Modifier modifier : modifiers) { out.append(modifier.toString()).append(' '); } }public static String type(Class raw, String... parameters) { if (parameters.length == 0) { return raw.getCanonicalName(); } if (raw.getTypeParameters().length != parameters.length) { throw new IllegalArgumentException(); } StringBuilder result = new StringBuilder(); result.append(raw.getCanonicalName()); result.append("<"); result.append(parameters[0]); for (int i = 1; i < parameters.length; i++) { result.append(", "); result.append(parameters[i]); } result.append(">"); return result.toString(); }public JavaWriter endMethod() throws IOException { Scope popped = scopes.pop(); // support calling a constructor a "method" to support the legacy code if (popped == Scope.NON_ABSTRACT_METHOD || popped == Scope.CONSTRUCTOR) { indent(); out.write("}\n"); } else if (popped != Scope.ABSTRACT_METHOD) { throw new IllegalStateException(); } return this; }private JavaWriter emitAnnotationValue(Object value) throws IOException { if (value instanceof Object[]) { out.write("{"); boolean firstValue = true; scopes.push(Scope.ANNOTATION_ARRAY_VALUE); for (Object o : ((Object[]) value)) { if (firstValue) { firstValue = false; out.write("\n"); } else { out.write(",\n"); } indent(); out.write(o.toString()); } popScope(Scope.ANNOTATION_ARRAY_VALUE); out.write("\n"); indent(); out.write("}"); } else { out.write(value.toString()); } return this; }public JavaWriter emitSingleLineComment(String comment, Object... args) throws IOException { indent(); out.write("// "); out.write(String.format(comment, args)); out.write("\n"); return this; }public JavaWriter endType() throws IOException { popScope(Scope.TYPE_DECLARATION, Scope.INTERFACE_DECLARATION); types.pop(); indent(); out.write("}\n"); return this; }public JavaWriter beginInitializer(boolean isStatic) throws IOException { indent(); if (isStatic) { out.write("static"); out.write(" {\n"); } else { out.write("{\n"); } scopes.push(Scope.INITIALIZER); return this; }public String compressType(String type) { StringBuilder sb = new StringBuilder(); if (this.packagePrefix == null) { throw new IllegalStateException(); } Matcher m = TYPE_PATTERN.matcher(type); int pos = 0; while (true) { boolean found = m.find(pos); // Copy non-matching characters like "<". int typeStart = found ? m.start() : type.length(); sb.append(type, pos, typeStart); if (!found) { break; } // Copy a single class name, shortening it if possible. String name = m.group(0); String imported = importedTypes.get(name); if (imported != null) { sb.append(imported); } else if (isClassInPackage(name, packagePrefix)) { String compressed = name.substring(packagePrefix.length()); if (isAmbiguous(compressed)) { sb.append(name); } else { sb.append(compressed); } } else if (isClassInPackage(name, "java.lang.")) { sb.append(name.substring("java.lang.".length())); } else { sb.append(name); } pos = m.end(); } return sb.toString(); }public JavaWriter emitPackage(String packageName) throws IOException { if (this.packagePrefix != null) { throw new IllegalStateException(); } if (packageName.isEmpty()) { this.packagePrefix = ""; } else { out.write("package "); out.write(packageName); out.write(";\n\n"); this.packagePrefix = packageName + "."; } return this; }public static TypeMirror hasGenericsTypeArgumentOf(Element element, String typeToCheck, Elements elements, Types types) { if (element.asType().getKind() != TypeKind.DECLARED || !(element.asType() instanceof DeclaredType)) { ProcessorMessage.error(element, "The field %s in %s doesn't have generic type arguments!", element.getSimpleName(), element.asType().toString()); } DeclaredType declaredType = (DeclaredType) element.asType(); List typeArguments = declaredType.getTypeArguments(); if (typeArguments.isEmpty()) { ProcessorMessage.error(element, "The field %s in %s doesn't have generic type arguments!", element.getSimpleName(), element.asType().toString()); } if (typeArguments.size() > 1) { ProcessorMessage.error(element, "The field %s in %s has more than 1 generic type argument!", element.getSimpleName(), element.asType().toString()); } // Ok it has a generic argument, check if this extends Parcelable TypeMirror argument = typeArguments.get(0); if (typeToCheck != null) { if (!isOfType(argument, typeToCheck, elements, types)) { ProcessorMessage.error(element, "The fields %s generic type argument is not of type %s! (in %s )", element.getSimpleName(), typeToCheck, element.asType().toString()); } } // everything is like expected return argument; }public static TypeMirror getWildcardType(String type, String elementType, Elements elements, Types types) { TypeElement arrayList = elements.getTypeElement(type); TypeMirror elType = elements.getTypeElement(elementType).asType(); return types.getDeclaredType(arrayList, types.getWildcardType(elType, null)); }public boolean hasToFetchAd(int position, int fetchingAdsCount){ int adIndex = getAdIndex(position); int firstAdPos = getOffsetValue(); return position >= firstAdPos && adIndex >= 0 && adIndex < getLimitOfAds() && adIndex >= fetchingAdsCount; }public boolean isAdAvailable(int position, int fetchedAdsCount) { if(fetchedAdsCount == 0) return false; int adIndex = getAdIndex(position); int firstAdPos = getOffsetValue(); return position >= firstAdPos && adIndex >= 0 && adIndex < getLimitOfAds() && adIndex < fetchedAdsCount; }public int getAdIndex(int position) { int index = -1; if(position >= getOffsetValue()) index = (position - getOffsetValue()) / (getNoOfDataBetweenAds()+1); //Log.d("POSITION", "index " + index + " for position " + position); return index; }public int getOriginalContentPosition(int position, int fetchedAdsCount, int sourceItemsCount) { int noOfAds = getAdsCountToPublish(fetchedAdsCount, sourceItemsCount); // No of spaces for ads in the dataset, according to ad placement rules int adSpacesCount = (getAdIndex(position) + 1); int originalPosition = position - Math.min(adSpacesCount, noOfAds); //Log.d("POSITION", position + " is originally " + originalPosition); return originalPosition; }public int getAdsCountToPublish(int fetchedAdsCount, int sourceItemsCount){ if(fetchedAdsCount <= 0 || getNoOfDataBetweenAds() <= 0) return 0; int expected = 0; if(sourceItemsCount > 0 && sourceItemsCount >= getOffsetValue()+1) expected = (sourceItemsCount - getOffsetValue()) / getNoOfDataBetweenAds() + 1; expected = Math.max(0, expected); expected = Math.min(fetchedAdsCount, expected); return Math.min(expected, getLimitOfAds()); }protected synchronized AdRequest getAdRequest() { AdRequest.Builder adBldr = new AdRequest.Builder(); for (String id : getTestDeviceIds()) { adBldr.addTestDevice(id); } return adBldr.build(); }private synchronized void onFailedToLoad(AdView adView, int errorCode) { Log.i(TAG, "onAdFailedToLoad " + errorCode); mFetchFailCount++; mNoOfFetchedAds = Math.max(mNoOfFetchedAds - 1, 0); //Since Fetch Ad is only called once without retries //hide ad row / rollback its count if still not added to list mPrefetchedAds.remove(adView); onAdFailed(mNoOfFetchedAds - 1, errorCode, adView); }public synchronized AdView getAdForIndex(int adPos) { if(adPos >= 0 && mPrefetchedAds.size() > adPos) return mPrefetchedAds.get(adPos); return null; }private boolean canUseThisAd(NativeAd adNative) { if (adNative != null) { NativeAd.Image logoImage = null; CharSequence header = null, body = null; if (adNative instanceof NativeContentAd) { NativeContentAd ad = (NativeContentAd) adNative; logoImage = ad.getLogo(); header = ad.getHeadline(); body = ad.getBody(); } else if (adNative instanceof NativeAppInstallAd) { NativeAppInstallAd ad = (NativeAppInstallAd) adNative; logoImage = ad.getIcon(); header = ad.getHeadline(); body = ad.getBody(); } if (!TextUtils.isEmpty(header) && !TextUtils.isEmpty(body)) { return true; } } return false; }public WebSocketClient newClient(final URI url, final WebSocketCallback callback) { ClientBootstrap bootstrap = new ClientBootstrap(socketChannelFactory); String protocol = url.getScheme(); if (!protocol.equals("ws") && !protocol.equals("wss")) { throw new IllegalArgumentException("Unsupported protocol: " + protocol); } final WebSocketClientHandler clientHandler = new WebSocketClientHandler(bootstrap, url, callback); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", new HttpResponseDecoder()); pipeline.addLast("encoder", new HttpRequestEncoder()); pipeline.addLast("ws-handler", clientHandler); return pipeline; } }); return clientHandler; }@Override public void flush() throws TTransportException { ChannelBuffer flush = ChannelBuffers.dynamicBuffer(); flush.writeBytes(output); channel.write(flush).awaitUninterruptibly(); }@Override public int read(final byte[] output, final int offset, final int length) throws TTransportException { int read = 0; int index = offset; int space = length - offset; while (space > 0) { byte aByte = readAsynchrously(); output[index] = aByte; space--; index++; read++; } return read; }private static final int find(boolean skipBlocks, String s, char toFind, int from) { int open = 0; boolean escaping = false; for (int i = from; i < s.length(); i++) { if (escaping) { escaping = false; continue; } char c = s.charAt(i); if (c == '\\') { escaping = true; continue; } if ((open == 0) && (c == toFind)) { return i; } else if (skipBlocks && (c == '{')) { open++; } else if (skipBlocks && (c == '}')) { open--; } } return -1; }protected final StackMapType[] calculate_live_stack_types(OperandStack stack) { int ss = stack.size(); StackMapType[] stack_map_types = new StackMapType[ss]; for (int ii = 0; ii < ss; ii++) { stack_map_types[ii] = generate_StackMapType_from_Type(stack.peek(ss - ii - 1)); } return stack_map_types; }protected final InstructionList build_il(Instruction... instructions) { InstructionList il = new InstructionList(); for (Instruction inst : instructions) { append_inst(il, inst); } return il; }private void print_il(InstructionHandle start, String label) { if (debug_instrument.enabled()) { print_stack_map_table(label); InstructionHandle tih = start; while (tih != null) { debug_instrument.log("inst: %s %n", tih); if (tih.hasTargeters()) { for (InstructionTargeter it : tih.getTargeters()) { debug_instrument.log("targeter: %s %n", it); } } tih = tih.getNext(); } } }protected final void insert_at_method_start(MethodGen mg, InstructionList new_il) { // Ignore methods with no instructions InstructionList il = mg.getInstructionList(); if (il == null) { return; } insert_before_handle(mg, il.getStart(), new_il, false); }public void set(@IndexFor({"loc_arr", "os_arr"}) int offset, Frame f) { OperandStack os = f.getStack(); // logger.info ("stack[" + offset + "] = " + toString(os)); loc_arr[offset] = (LocalVariables) (f.getLocals().clone()); os_arr[offset] = (OperandStack) (os.clone()); }public static Type[] postpendToArray(Type[] types, Type newType) { if (types.length == Integer.MAX_VALUE) { throw new Error("array " + types + " is too large to extend"); } Type[] newTypes = new Type[types.length + 1]; System.arraycopy(types, 0, newTypes, 0, types.length); newTypes[types.length] = newType; return newTypes; }public static Class typeToClass(Type type) { String classname = typeToClassgetname(type); try { return ReflectionPlume.classForName(classname); } catch (Exception e) { throw new RuntimeException("can't find class for " + classname, e); } }public static void resetLocalsToFormals(MethodGen mg) { // Get the parameter types and names. @SuppressWarnings("nullness" // The annotation arguments might not be initialized yet. // Since the arguments are not executed at run time, there is no null pointer exception. ) Type @SameLen({"argTypes", "mg.getArgumentTypes()"}) [] argTypes = mg.getArgumentTypes(); @SuppressWarnings("nullness" // The annotation arguments might not be initialized yet. // Since the arguments are not executed at run time, there is no null pointer exception. ) String @SameLen({"argTypes", "argNames", "mg.getArgumentTypes()", "mg.getArgumentNames()"}) [] argNames = mg.getArgumentNames(); // Remove any existing locals mg.setMaxLocals(0); mg.removeLocalVariables(); // Add a local for the instance variable (this) if (!mg.isStatic()) { mg.addLocalVariable("this", new ObjectType(mg.getClassName()), null, null); } // Add a local for each parameter for (int ii = 0; ii < argNames.length; ii++) { mg.addLocalVariable(argNames[ii], argTypes[ii], null, null); } // Reset the current number of locals so that when other locals // are added they get added at the correct offset. mg.setMaxLocals(); return; }public static String getConstantString(ConstantPool pool, int index) { Constant c = pool.getConstant(index); assert c != null : "Bad index " + index + " into pool"; if (c instanceof ConstantUtf8) { return ((ConstantUtf8) c).getBytes(); } else if (c instanceof ConstantClass) { ConstantClass cc = (ConstantClass) c; return cc.getBytes(pool) + " [" + cc.getNameIndex() + "]"; } else { throw new Error("unexpected constant " + c + " of class " + c.getClass()); } }public static void addToStart(MethodGen mg, InstructionList newList) { // Add the code before the first instruction InstructionList il = mg.getInstructionList(); InstructionHandle oldStart = il.getStart(); InstructionHandle newStart = il.insert(newList); // Move any LineNumbers and local variables that currently point to // the first instruction to include the new instructions. Other // targeters (branches, exceptions) should not include the new code. if (oldStart.hasTargeters()) { // getTargeters() returns non-null because hasTargeters => true for (InstructionTargeter it : oldStart.getTargeters()) { if ((it instanceof LineNumberGen) || (it instanceof LocalVariableGen)) { it.updateTarget(oldStart, newStart); } } } mg.setMaxStack(); mg.setMaxLocals(); }static void dumpMethods(ClassGen gen) { System.out.printf("Class %s methods:%n", gen.getClassName()); for (Method m : gen.getMethods()) { System.out.printf(" %s%n", m); } }public static void dumpStackTrace() { StackTraceElement[] ste = Thread.currentThread().getStackTrace(); // [0] is getStackTrace // [1] is dumpStackTrace if (ste.length < 3) { System.out.println("No stack trace information available"); } else { StackTraceElement caller = ste[2]; System.out.printf( "%s.%s (%s line %d)", caller.getClassName(), caller.getMethodName(), caller.getFileName(), caller.getLineNumber()); for (int ii = 3; ii < ste.length; ii++) { System.out.printf(" [%s line %d]", ste[ii].getFileName(), ste[ii].getLineNumber()); } System.out.printf("%n"); } }public static void checkMgens(final ClassGen gen) { if (skipChecks) { return; } Method[] methods = gen.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; // System.out.println ("Checking method " + method + " in class " // + gen.getClassName()); checkMgen(new MethodGen(method, gen.getClassName(), gen.getConstantPool())); } // Diagnostic output if (false) { dumpStackTrace(); dumpMethods(gen); } }public static void checkMgen(MethodGen mgen) { if (skipChecks) { return; } try { mgen.toString(); // ensure it can be formatted without exceptions mgen.getLineNumberTable(mgen.getConstantPool()); InstructionList ilist = mgen.getInstructionList(); if (ilist == null || ilist.getStart() == null) { return; } CodeExceptionGen[] exceptionHandlers = mgen.getExceptionHandlers(); for (CodeExceptionGen gen : exceptionHandlers) { assert ilist.contains(gen.getStartPC()) : "exception handler " + gen + " has been forgotten in " + mgen.getClassName() + "." + mgen.getName(); } MethodGen nmg = new MethodGen(mgen.getMethod(), mgen.getClassName(), mgen.getConstantPool()); nmg.getLineNumberTable(mgen.getConstantPool()); } catch (Throwable t) { Error e = new Error( String.format( "failure while checking method %s.%s%n", mgen.getClassName(), mgen.getName()), t); e.printStackTrace(); throw e; } }public static String attributeNameToString(Attribute a) { ConstantPool pool = a.getConstantPool(); int conIndex = a.getNameIndex(); Constant c = pool.getConstant(conIndex); String attName = ((ConstantUtf8) c).getBytes(); return attName; }public static String instructionListToString(InstructionList il, ConstantPoolGen pool) { StringBuilder out = new StringBuilder(); for (Iterator i = il.iterator(); i.hasNext(); ) { InstructionHandle handle = i.next(); out.append(handle.getInstruction().toString(pool.getConstantPool()) + "\n"); } return out.toString(); }static String accessFlagsToString(Method m) { int flags = m.getAccessFlags(); StringBuilder buf = new StringBuilder(); // Note that pow is a binary mask for the flag (= 2^i). for (int i = 0, pow = 1; i <= Const.MAX_ACC_FLAG; i++) { if ((flags & pow) != 0) { if (buf.length() > 0) { buf.append(" "); } if (i < Const.ACCESS_NAMES_LENGTH) { buf.append(Const.getAccessName(i)); } else { buf.append(String.format("ACC_BIT(%x)", pow)); } } pow <<= 1; } return buf.toString(); }protected final StackTypes bcel_calc_stack_types(MethodGen mg) { StackVer stackver = new StackVer(); VerificationResult vr; try { vr = stackver.do_stack_ver(mg); } catch (Throwable t) { System.out.printf("Warning: StackVer exception for %s.%s%n", mg.getClassName(), mg.getName()); System.out.printf("Exception: %s%n", t); System.out.printf("Method is NOT instrumented%n"); return null; } if (vr != VerificationResult.VR_OK) { System.out.printf( "Warning: StackVer failed for %s.%s: %s%n", mg.getClassName(), mg.getName(), vr); System.out.printf("Method is NOT instrumented%n"); return null; } assert vr == VerificationResult.VR_OK : " vr failed " + vr; return stackver.get_stack_types(); } protected final Type generate_Type_from_StackMapType(StackMapType smt) { switch (smt.getType()) { case Const.ITEM_Integer: case Const.ITEM_Bogus: // not sure about this; reresents 'top'? return Type.INT; case Const.ITEM_Float: return Type.FLOAT; case Const.ITEM_Double: return Type.DOUBLE; case Const.ITEM_Long: return Type.LONG; case Const.ITEM_Object: return Type.OBJECT; default: Thread.dumpStack(); assert false : "Invalid StackMapType: " + smt + smt.getType(); throw new RuntimeException("Invalid StackMapType: " + smt + smt.getType()); } }protected final StackMapType generate_StackMapType_from_Type(Type t) { switch (t.getType()) { case Const.T_BOOLEAN: case Const.T_CHAR: case Const.T_BYTE: case Const.T_SHORT: case Const.T_INT: return new StackMapType(Const.ITEM_Integer, -1, pool.getConstantPool()); case Const.T_FLOAT: return new StackMapType(Const.ITEM_Float, -1, pool.getConstantPool()); case Const.T_DOUBLE: return new StackMapType(Const.ITEM_Double, -1, pool.getConstantPool()); case Const.T_LONG: return new StackMapType(Const.ITEM_Long, -1, pool.getConstantPool()); case Const.T_ARRAY: case Const.T_OBJECT: return new StackMapType( Const.ITEM_Object, pool.addClass(typeToClassGetName(t)), pool.getConstantPool()); // UNKNOWN seems to be used for Uninitialized objects. // The second argument to the constructor should be the code offset // of the corresponding 'new' instruction. Just using 0 for now. case Const.T_UNKNOWN: return new StackMapType(Const.ITEM_NewObject, 0, pool.getConstantPool()); default: throw new RuntimeException("Invalid type: " + t + t.getType()); } }@SuppressWarnings("signature") // conversion routine protected static @ClassGetName String typeToClassGetName(Type t) { if (t instanceof ObjectType) { return ((ObjectType) t).getClassName(); } else if (t instanceof BasicType) { // Use reserved keyword for basic type rather than signature to // avoid conflicts with user defined types. return t.toString(); } else { // Array type: just convert '/' to '.' return t.getSignature().replace('/', '.'); } }protected final void create_new_stack_map_attribute(MethodGen mgen) throws IOException { if (!needStackMap) { return; } if (stack_map_table == empty_stack_map_table) { return; } print_stack_map_table("Final"); // Build new StackMapTable attribute StackMap map_table = new StackMap(pool.addUtf8("StackMapTable"), 0, null, pool.getConstantPool()); map_table.setStackMap(stack_map_table); mgen.addCodeAttribute(map_table); }protected final void print_stack_map_table(String prefix) { debug_instrument.log("%nStackMap(%s) %s items:%n", prefix, stack_map_table.length); running_offset = -1; // no +1 on first entry for (int i = 0; i < stack_map_table.length; i++) { running_offset = stack_map_table[i].getByteCodeOffset() + running_offset + 1; debug_instrument.log("@%03d %s %n", running_offset, stack_map_table[i]); } }@EnsuresNonNull({"stack_map_table"}) protected final void set_current_stack_map_table(MethodGen mgen, int java_class_version) { smta = (StackMap) get_stack_map_table_attribute(mgen); if (smta != null) { // get a deep copy of the original StackMapTable. stack_map_table = ((StackMap) (smta.copy(smta.getConstantPool()))).getStackMap(); needStackMap = true; debug_instrument.log( "Attribute tag: %s length: %d nameIndex: %d%n", smta.getTag(), smta.getLength(), smta.getNameIndex()); // Delete existing stack map - we'll add a new one later. mgen.removeCodeAttribute(smta); } else { stack_map_table = empty_stack_map_table; if (java_class_version > Const.MAJOR_1_6) { needStackMap = true; } } print_stack_map_table("Original"); }protected final void update_uninitialized_NEW_offsets(InstructionList il) { il.setPositions(); for (Map.Entry e : uninitialized_NEW_map.entrySet()) { InstructionHandle ih = e.getKey(); int old_offset = e.getValue().intValue(); int new_offset = ih.getPosition(); if (old_offset != new_offset) { update_NEW_object_stack_map_entries(old_offset, new_offset); e.setValue(new_offset); } } }private final void update_NEW_object_stack_map_entries(int old_offset, int new_offset) { for (StackMapEntry smte : stack_map_table) { int frame_type = smte.getFrameType(); if ((frame_type >= Const.SAME_LOCALS_1_STACK_ITEM_FRAME && frame_type <= Const.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) || (frame_type >= Const.APPEND_FRAME && frame_type <= Const.APPEND_FRAME_MAX) || (frame_type == Const.FULL_FRAME)) { if (smte.getNumberOfLocals() > 0) { for (StackMapType smt : smte.getTypesOfLocals()) { if (smt.getType() == Const.ITEM_NewObject) { if (old_offset == smt.getIndex()) { smt.setIndex(new_offset); } } } } if (smte.getNumberOfStackItems() > 0) { for (StackMapType smt : smte.getTypesOfStackItems()) { if (smt.getType() == Const.ITEM_NewObject) { if (old_offset == smt.getIndex()) { smt.setIndex(new_offset); } } } } } } }protected final void build_unitialized_NEW_map(InstructionList il) { uninitialized_NEW_map.clear(); il.setPositions(); for (StackMapEntry smte : stack_map_table) { int frame_type = smte.getFrameType(); if ((frame_type >= Const.SAME_LOCALS_1_STACK_ITEM_FRAME && frame_type <= Const.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) || (frame_type >= Const.APPEND_FRAME && frame_type <= Const.APPEND_FRAME_MAX) || (frame_type == Const.FULL_FRAME)) { if (smte.getNumberOfLocals() > 0) { for (StackMapType smt : smte.getTypesOfLocals()) { if (smt.getType() == Const.ITEM_NewObject) { int i = smt.getIndex(); uninitialized_NEW_map.put(il.findHandle(i), i); } } } if (smte.getNumberOfStackItems() > 0) { for (StackMapType smt : smte.getTypesOfStackItems()) { if (smt.getType() == Const.ITEM_NewObject) { int i = smt.getIndex(); uninitialized_NEW_map.put(il.findHandle(i), i); } } } } } }protected final @IndexOrLow("stack_map_table") int find_stack_map_index_after(int offset) { running_offset = -1; // no +1 on first entry for (int i = 0; i < stack_map_table.length; i++) { running_offset = running_offset + stack_map_table[i].getByteCodeOffset() + 1; if (running_offset > offset) { return i; } // try next map entry } // no such entry found return -1; }protected final int find_stack_map_index_before(int offset) { number_active_locals = initial_locals_count; running_offset = -1; // no +1 on first entry for (int i = 0; i < stack_map_table.length; i++) { running_offset = running_offset + stack_map_table[i].getByteCodeOffset() + 1; if (running_offset >= offset) { if (i == 0) { // reset offset to previous running_offset = -1; return -1; } else { // back up offset to previous running_offset = running_offset - stack_map_table[i].getByteCodeOffset() - 1; // return previous return i - 1; } } // Update number of active locals based on this StackMap entry. int frame_type = stack_map_table[i].getFrameType(); if (frame_type >= Const.APPEND_FRAME && frame_type <= Const.APPEND_FRAME_MAX) { number_active_locals += frame_type - 251; } else if (frame_type >= Const.CHOP_FRAME && frame_type <= Const.CHOP_FRAME_MAX) { number_active_locals -= 251 - frame_type; } else if (frame_type == Const.FULL_FRAME) { number_active_locals = stack_map_table[i].getNumberOfLocals(); } // All other frame_types do not modify locals. } if (stack_map_table.length == 0) { return -1; } else { return stack_map_table.length - 1; } }protected final StackMapEntry find_stack_map_equal(int offset) { running_offset = -1; // no +1 on first entry for (int i = 0; i < stack_map_table.length; i++) { running_offset = stack_map_table[i].getByteCodeOffset() + running_offset + 1; if (running_offset > offset) { throw new RuntimeException("Invalid StackMap offset 1"); } if (running_offset == offset) { return stack_map_table[i]; } // try next map entry } // no offset matched throw new RuntimeException("Invalid StackMap offset 2"); }@Pure protected final @Nullable Attribute get_local_variable_type_table_attribute(MethodGen mgen) { for (Attribute a : mgen.getCodeAttributes()) { if (is_local_variable_type_table(a)) { return a; } } return null; }@Pure protected final @Nullable Attribute get_stack_map_table_attribute(MethodGen mgen) { for (Attribute a : mgen.getCodeAttributes()) { if (is_stack_map_table(a)) { return a; } } return null; }@Pure protected final String get_attribute_name(Attribute a) { int con_index = a.getNameIndex(); Constant c = pool.getConstant(con_index); String att_name = ((ConstantUtf8) c).getBytes(); return att_name; }protected String[] add_string(String[] arr, String new_string) { String[] new_arr = new String[arr.length + 1]; for (int ii = 0; ii < arr.length; ii++) { new_arr[ii] = arr[ii]; } new_arr[arr.length] = new_string; return new_arr; }boolean execute( InstructionContext ic, Frame inFrame, ArrayList executionPredecessors, InstConstraintVisitor icv, ExecutionVisitor ev) { stack_types.set(ic.getInstruction().getPosition(), inFrame); return ic.execute(inFrame, executionPredecessors, icv, ev); }private String getIndentString() { assert enabled; if (indentString == null) { for (int i = indentStrings.size(); i <= indentLevel; i++) { indentStrings.add(indentStrings.get(i - 1) + INDENT_STR_ONE_LEVEL); } indentString = indentStrings.get(indentLevel); } return indentString; }public void logStackTrace() { if (enabled) { Throwable t = new Throwable(); t.fillInStackTrace(); StackTraceElement[] ste_arr = t.getStackTrace(); for (int ii = 2; ii < ste_arr.length; ii++) { StackTraceElement ste = ste_arr[ii]; System.out.printf("%s %s%n", getIndentString(), ste); } } }private void syntaxError(String msg, int index) { // FIXME: this is clearly not a sensible approach throw new SyntacticException(msg, entry, new ConfigFile.Attribute.Span(null,index,index)); }public List scan() { ArrayList tokens = new ArrayList<>(); pos = 0; while (pos < input.length()) { char c = input.charAt(pos); if (Character.isDigit(c)) { tokens.add(scanNumericConstant()); } else if (c == '"') { tokens.add(scanStringConstant()); } else if (c == '\'') { tokens.add(scanCharacterConstant()); } else if (isOperatorStart(c)) { tokens.add(scanOperator()); } else if (Character.isLetter(c) || c == '_') { tokens.add(scanIdentifier()); } else if (Character.isWhitespace(c)) { scanWhiteSpace(tokens); } else { syntaxError("unknown token encountered",pos); } } return tokens; }private void resolvePackageDependencies() throws IOException { // FIXME: should produce a wy.lock file? Configuration.Schema buildSchema = environment.getBuildSchema(); // Global root is where all dependencies will be stored Path.Root repository = getRepositoryRoot(); // Dig out all the defined dependencies List deps = configuration.matchAll(Trie.fromString("dependencies/**")); // Resolve each dependencies and add to project roots for (int i = 0; i != deps.size(); ++i) { Path.ID dep = deps.get(i); // Get dependency name String name = dep.get(1); // Get version string UTF8 version = configuration.get(UTF8.class, dep); // Construct path to the config file Trie root = Trie.fromString(name + "-v" + version); // Attempt to resolve it. if (!repository.exists(root, ZipFile.ContentType)) { // TODO: employ a package resolver here // FIXME: handle better error handling. throw new RuntimeException("missing dependency \"" + name + "-" + version + "\""); } else { // Extract entry for ZipFile Path.Entry zipfile = repository.get(root, ZipFile.ContentType); // Construct root repesenting this ZipFile Path.Root pkgRoot = new ZipFileRoot(zipfile, environment.getContentRegistry()); // Extract configuration from package Path.Entry entry = pkgRoot.get(Trie.fromString("wy"),ConfigFile.ContentType); if(entry == null) { throw new RuntimeException("corrupt package (missing wy.toml) \"" + name + "-" + version + "\""); } else { ConfigFile pkgcfg = pkgRoot.get(Trie.fromString("wy"),ConfigFile.ContentType).read(); // Construct a package representation of this root. Build.Package pkg = new Package(pkgRoot,pkgcfg.toConfiguration(buildSchema)); // Add a relative ZipFile root project.getPackages().add(pkg); } } } }public Path.Root getRepositoryRoot() throws IOException { Path.Root root = environment.getGlobalRoot().createRelativeRoot(REPOSITORY_PATH); // TODO: create repository if it doesn't exist. return root; }public static Command.Descriptor DESCRIPTOR(List descriptors) { return new Command.Descriptor() { @Override public Schema getConfigurationSchema() { // TODO Auto-generated method stub return null; } @Override public List getOptionDescriptors() { return Arrays.asList( Command.OPTION_FLAG("verbose", "generate verbose information about the build", false), Command.OPTION_FLAG("brief", "generate brief output for syntax errors", false)); } @Override public Command initialise(Command environment, Configuration configuration) { return new WyProject((WyMain) environment, configuration, System.out, System.err); } @Override public String getName() { return "wy"; } @Override public String getDescription() { return "Command-line interface for the Whiley Compiler Collection"; } @Override public List getCommands() { return descriptors; } }; }public static Trie fromString(Path.ID id) { if(id instanceof Trie) { return ((Trie)id); } Trie r = ROOT; for(int i=0;i!=id.size();++i) { r = r.append(id.get(i)); } return r; }protected Pair readItems() throws IOException { // first, write magic number checkHeader(); // second, determine number of items int size = in.read_uv(); // third, determine the root item int root = in.read_uv(); // Bytecode[] items = new Bytecode[size]; // third, read abstract syntactic items for (int i = 0; i != items.length; ++i) { items[i] = readItem(); } // return new Pair<>(root, constructItems(items)); }private void inspectBinaryFile(byte[] bytes) { for (int i = 0; i < bytes.length; i += width) { out.print(String.format("0x%04X ", i)); // Print out databytes for (int j = 0; j < width; ++j) { if(j+i < bytes.length) { out.print(String.format("%02X ", bytes[i+j])); } else { out.print(" "); } } // for (int j = 0; j < width; ++j) { if(j+i < bytes.length) { char c = (char) bytes[i+j]; if(c >= 32 && c < 128) { out.print(c); } else { out.print("."); } } } // out.println(); } }private void inspect(Path.Entry entry, Content.Type ct, boolean garbage) throws IOException { Object o = entry.read(); if (o instanceof SyntacticHeap) { new SyntacticHeapPrinter(new PrintWriter(out), garbage).print((SyntacticHeap) o); } else { inspectBinaryFile(readAllBytes(entry.inputStream())); } }public Path.Entry getEntry(String file, Content.Type ct) throws IOException { // Strip suffix file = file.replace("." + ct.getSuffix(), ""); // Determine path id Path.ID id = Trie.fromString(file); // Get the file from the repository root return project.getParent().getLocalRoot().get(id, ct); }private Content.Type getContentType(String file) { List> cts = project.getParent().getContentTypes(); for (int i = 0; i != cts.size(); ++i) { Content.Type ct = cts.get(i); String suffix = "." + ct.getSuffix(); if (file.endsWith(suffix)) { return ct; } } // Default is just a binary file return Content.BinaryFile; }private static SyntacticItem substitute(SyntacticItem item, SyntacticItem from, SyntacticItem to, Map mapping) { SyntacticItem sItem = mapping.get(item); if (sItem != null) { // We've previously substituted this item already to produce a // potentially updated item. Therefore, simply return that item to // ensure the original aliasing structure of the ancestor(s) is // properly preserved. return sItem; } else if (item == from) { // We've matched the item being replaced, therefore return the item // to which it is being replaced. return to; } else { SyntacticItem nItem = item; // We need to recursively descend into children of this item looking // for the item to replace. The challenge here is that we need to // ensure the original item is preserved as is if there is no // change. SyntacticItem[] children = item.getAll(); // Initially, this will alias children. In the event of a child // which is actually updated, then this will refer to a new array. // That will be the signal that we need to create a new item to // return. SyntacticItem[] nChildren = children; if (children != null) { for (int i = 0; i != children.length; ++i) { SyntacticItem child = children[i]; // Check for null, since we don't want to try and substitute // into null. if (child != null) { // Perform the substitution in the given child SyntacticItem nChild = substitute(child, from, to, mapping); // Check whether anything was actually changed by the // substitution. if (nChild != child && children == nChildren) { // Yes, the child changed and we haven't already // cloned the children array. Hence, we'd better // clone it now to make sure that the original item // is preserved. nChildren = Arrays.copyOf(children, children.length); } nChildren[i] = nChild; } } // Now, clone the original item if necessary. This is only // necessary if the children array as been updated in some way. if (children != nChildren) { // Create the new item which, at this point, will be // detached. nItem = item.clone(nChildren); } } mapping.put(item, nItem); return nItem; } }@Override public T getAncestor(SyntacticItem child, Class kind) { // FIXME: this could be optimised a *lot* if (kind.isInstance(child)) { return (T) child; } else { for (int i = 0; i != syntacticItems.size(); ++i) { SyntacticItem parent = syntacticItems.get(i); for (int j = 0; j != parent.size(); ++j) { // Don't follow cross-references if (parent.get(j) == child && !(parent instanceof AbstractCompilationUnit.Ref)) { // FIXME: this is not specifically efficient. It would // be helpful if SyntacticItems actually contained // references to their parent items. T tmp = getAncestor(parent, kind); if (tmp != null) { return tmp; } } } } // no match return null; } }@Override public T getParent(SyntacticItem child, Class kind) { // FIXME: this could be optimised a *lot* for (int i = 0; i != syntacticItems.size(); ++i) { SyntacticItem parent = syntacticItems.get(i); if(kind.isInstance(parent)) { for(int j=0;j!=parent.size();++j) { if(parent.get(j) == child) { return (T) parent; } } } } // no match return null; }private static Map splitConfig(String str) { HashMap options = new HashMap<>(); String[] splits = str.split(","); for (String s : splits) { String[] p = s.split("="); options.put(p[0], parseValue(p[1])); } return options; }public static Map parseOptions(List args, OptArg... options) { HashMap result = new HashMap<>(); HashMap optmap = new HashMap<>(); for(OptArg opt : options) { if(opt.defaultValue != null) { result.put(opt.option, opt.defaultValue); } optmap.put(opt.option, opt); optmap.put(opt.shortForm, opt); } Iterator iter = args.iterator(); while(iter.hasNext()) { String arg = iter.next(); if (arg.startsWith("-")) { arg = arg.substring(1,arg.length()); OptArg opt = optmap.get(arg); if(opt != null) { // matched iter.remove(); // remove option from args list Kind k = opt.argument; if(k != null) { String param = iter.next(); iter.remove(); k.process(opt.option,param,result); } else { result.put(opt.option,null); } } else { throw new RuntimeException("unknown command-line option: -" + arg); } } } return result; }private boolean ready(Build.Task task) { // FIXME: this is not a great solution in the long run for several reasons. // Firstly, its possible that a given source will be rebuilt in the near future // as a result of some other task and we should be waiting for that. Path.Entry target = task.getTarget(); for(Path.Entry s : task.getSources()) { if(s.lastModified() > target.lastModified()) { return true; } } return false; }public void outputSourceError(PrintStream output, boolean brief) { Attribute.Span span; if (entry == null || element == null) { output.println("syntax error: " + getMessage()); return; } else if(element instanceof Attribute.Span) { span = (Attribute.Span) element; } else { SyntacticHeap parent = element.getHeap(); span = parent.getParent(element,Attribute.Span.class); } // EnclosingLine enclosing = (span == null) ? null : readEnclosingLine(entry, span); if(enclosing == null) { output.println("syntax error: " + getMessage()); } else if(brief) { printBriefError(output,entry,enclosing,getMessage()); } else { printFullError(output,entry,enclosing,getMessage()); } }private void activateModules(URLClassLoader loader) { for (int i = 0; i != modules.size(); ++i) { Descriptor module = modules.get(i); try { Class c = loader.loadClass(module.getActivator()); Module.Activator self = (Module.Activator) c.newInstance(); Module instance = self.start(context); instances.put(c, instance); logger.logTimedMessage("Activated module " + module.getId() + " (v" + module.getVersion() + ")", 0, 0); } catch (Exception e) { e.printStackTrace(); } } }public void start() { // Construct the URLClassLoader which will be used to load // classes within the modules. URL[] urls = new URL[modules.size()]; for(int i=0;i!=modules.size();++i) { urls[i] = modules.get(i).getLocation(); } URLClassLoader loader = new URLClassLoader(urls); // Third, active the modules. This will give them the opportunity to // register whatever extensions they like. activateModules(loader); }public T getInstance(Class module) { return (T) instances.get(module); }private static Configuration readConfigFile(String name, String dir, Configuration.Schema... schemas) throws IOException { DirectoryRoot root = new DirectoryRoot(dir, BOOT_REGISTRY); Path.Entry config = root.get(Trie.fromString(name), ConfigFile.ContentType); if (config == null) { return Configuration.EMPTY; } try { // Read the configuration file ConfigFile cf = config.read(); // Construct configuration according to given schema return cf.toConfiguration(Configuration.toCombinedSchema(schemas)); } catch (SyntacticException e) { e.outputSourceError(System.out, false); System.exit(-1); return null; } }private static String determineLocalRoot() throws IOException { // Determine current working directory File dir = new File("."); // Traverse up the directory hierarchy while (dir != null && dir.exists() && dir.isDirectory()) { File wyf = new File(dir + File.separator + "wy.toml"); if (wyf.exists()) { return dir.getPath(); } // Traverse back up the directory hierarchy looking for a suitable directory. dir = dir.getParentFile(); } // If we get here then it means we didn't find a root, therefore just use // current directory. return "."; }private static String determineSystemRoot() throws IOException { String whileyhome = System.getenv("WHILEYHOME"); if (whileyhome == null) { System.err.println("error: WHILEYHOME environment variable not set"); System.exit(-1); } return whileyhome; }private void activateDefaultPlugins(Configuration global) { // Determine the set of install plugins List plugins = global.matchAll(Trie.fromString("plugins/*")); // start modules for (Path.ID id : plugins) { UTF8 activator = global.get(UTF8.class, id); try { Class c = Class.forName(activator.toString()); Module.Activator instance = (Module.Activator) c.newInstance(); instance.start(context); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }private void createTemplateExtensionPoint() { context.create(Command.Descriptor.class, new Module.ExtensionPoint() { @Override public void register(Command.Descriptor command) { commandDescriptors.add(command); } }); }public Configuration.Schema getBuildSchema() { Configuration.Schema[] schemas = new Configuration.Schema[buildPlatforms.size() + 1]; schemas[0] = LOCAL_CONFIG_SCHEMA; for (int i = 0; i != buildPlatforms.size(); ++i) { wybs.lang.Build.Platform platform = buildPlatforms.get(i); schemas[i + 1] = platform.getConfigurationSchema(); } return Configuration.toCombinedSchema(schemas); }public static > int compareTo(T[] lhs, T[] rhs) { if(lhs.length != rhs.length) { return lhs.length - rhs.length; } else { for(int i=0;i!=lhs.length;++i) { int r = lhs[i].compareTo((S) rhs[i]); if(r != 0) { return r; } } return 0; } }public static > int isSortedAndUnique(T[] children) { int r = 0; for (int i = 1; i < children.length; ++i) { int c = children[i - 1].compareTo(children[i]); if (c == 0) { // Duplicate found, though still could be in sorted order. r = 1; } else if (c > 0) { // NOT in sorted order return -1; } } // All good return r; }public static > T[] sortAndRemoveDuplicates(T[] children) { int r = isSortedAndUnique(children); switch (r) { case 0: // In this case, the array is already sorted and no duplicates were // found. return children; case 1: // In this case, the array is already sorted, but duplicates were // found return ArrayUtils.sortedRemoveDuplicates(children); default: // In this case, the array is not sorted and may or may not // contain duplicates. children = Arrays.copyOf(children, children.length); Arrays.sort(children); return ArrayUtils.sortedRemoveDuplicates(children); } }public static int[] toIntArray(Collection items) { int[] result = new int[items.size()]; int i = 0; for (Integer v : items) { result[i++] = v; } return result; }public static String[] toStringArray(Collection items) { String[] result = new String[items.size()]; int i = 0; for(String s : items) { result[i++] = s; } return result; }public static void addAll(T[] lhs, Collection rhs) { for(int i=0;i!=lhs.length;++i) { rhs.add(lhs[i]); } }public static T[] append(Class type, T lhs, T... rhs) { T[] rs = (T[]) Array.newInstance(type, rhs.length+1); System.arraycopy(rhs, 0, rs, 1, rhs.length); rs[0] = lhs; return rs; }public static int[] append(int[] lhs, int[] rhs) { int[] rs = java.util.Arrays.copyOf(lhs, lhs.length + rhs.length); System.arraycopy(rhs, 0, rs, lhs.length, rhs.length); return rs; }public static int[] append(int first, int second, int[] rhs) { int[] rs = new int[rhs.length+2]; rs[0] = first; rs[1] = second; System.arraycopy(rhs, 0, rs, 2, rhs.length); return rs; }public static int[] append(int lhs, int[] rhs) { int[] rs = new int[rhs.length+1]; rs[0] = lhs; System.arraycopy(rhs, 0, rs, 1, rhs.length); return rs; }@Override public T getAncestor(Class kind) { return parent.getAncestor(this, kind); }@Override public List getParents(Class kind) { return parent.getParents(this, kind); }@Override public T getParent(Class kind) { return parent.getParent(this, kind); }private static List extractSyntacticMarkers(Path.Entry... binaries) throws IOException { List annotated = new ArrayList<>(); // for (Path.Entry binary : binaries) { Object o = binary.read(); // If the object in question can be decoded as a syntactic heap then we can look // for syntactic messages. if (o instanceof SyntacticHeap) { SyntacticHeap h = (SyntacticHeap) o; extractSyntacticMarkers(h.getRootItem(), annotated, new BitSet()); } } // return annotated; }private static void printSyntacticMarkers(PrintStream output, Collection> sources, SyntacticItem.Marker marker) { // Path.Entry source = getSourceEntry(sources,marker.getSource()); // Span span = marker.getTarget().getAncestor(AbstractCompilationUnit.Attribute.Span.class); // Read the enclosing line so we can print it EnclosingLine line = readEnclosingLine(source, span); // Sanity check we found it if(line != null) { // print the error message output.println(source.location() + ":" + line.lineNumber + ": " + marker.getMessage()); // Finally print the line highlight printLineHighlight(output, line); } else { output.println(source.location() + ":?: " + marker.getMessage()); } }public static void printSyntacticMarkers(PrintStream output, Collection> sources, Path.Entry target) throws IOException { // Extract all syntactic markers from entries in the build graph List items = extractSyntacticMarkers(target); // For each marker, print out error messages appropriately for (int i = 0; i != items.size(); ++i) { // Log the error message printSyntacticMarkers(output, sources, items.get(i)); } }public void write_un(int bits, int n) throws IOException { int mask = 1; for(int i=0;i> 24) & 0xFF); write_u8((w >> 16) & 0xFF); write_u8((w >> 8) & 0xFF); write_u8(w & 0xFF); }@Override public void write(int i) throws IOException { if(count == 0) { output.write(i & 0xFF); } else { write_un(i & 0xFF,8); } }private Content.Filter createFilter(String filter) { String[] split = filter.split("\\."); // Content.Type contentType = getContentType(split[1]); // return Content.filter(split[0], contentType); }private byte[] readFileContents(Path.Entry file) throws IOException { InputStream in = file.inputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; // Read bytes in max 1024 chunks byte[] data = new byte[1024]; // Read all bytes from the input stream while ((nRead = in.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } // Done buffer.flush(); return buffer.toByteArray(); }private ZipFile createZipFile(List> files) throws IOException { // The set of known paths HashSet paths = new HashSet<>(); // The zip file we're creating ZipFile zf = new ZipFile(); // Add each file to zip file for (int i = 0; i != files.size(); ++i) { Path.Entry file = files.get(i); // Extract path addPaths(file.id().parent(),paths,zf); // Construct filename for given entry String filename = file.id().toString() + "." + file.contentType().getSuffix(); // Extract bytes representing entry byte[] contents = readFileContents(file); zf.add(new ZipEntry(filename), contents); } // return zf; }private static int determineCommandNameWidth(List descriptors) { int max = 0; for (Command.Descriptor d : descriptors) { max = Math.max(max, d.getName().length()); } return max; }protected void printUsage() { List descriptors = project.getParent().getCommandDescriptors(); // out.println("usage: wy [--verbose] command [] []"); out.println(); int maxWidth = determineCommandNameWidth(descriptors); out.println("Commands:"); for (Command.Descriptor d : descriptors) { out.print(" "); out.print(rightPad(d.getName(), maxWidth)); out.println(" " + d.getDescription()); } out.println(); out.println("Run `wy help COMMAND` for more information on a command"); }private static Object parseData(String str) { if (str.equals("true")) { return true; } else if (str.equals("false")) { return false; } else if (Character.isDigit(str.charAt(0))) { // number return Integer.parseInt(str); } else { return str; } }protected Command.Template parse(Command.Descriptor root, String[] args, int index) { ArrayList options = new ArrayList<>(); ArrayList arguments = new ArrayList<>(); // Command.Template sub = null; while (index < args.length) { String arg = args[index]; if (isLongOption(arg)) { options.add(parseLongOption(root, args[index])); } else if (isCommand(arg, root.getCommands())) { Command.Descriptor cmd = getCommandDescriptor(arg, root.getCommands()); sub = parse(cmd, args, index + 1); break; } else { arguments.add(arg); } index = index + 1; } // Command.Options optionMap = new OptionsMap(options, root.getOptionDescriptors()); // return new ConcreteTemplate(root, optionMap, arguments, sub); }public List scan() throws Error { ArrayList tokens = new ArrayList<>(); int pos = 0; while (pos < input.length()) { int start = pos; for (int i = 0; i != rules.length; ++i) { Rule rule = rules[i]; int left = input.length() - pos; if (left >= rule.lookahead()) { Token t = rule.match(input, pos); if (t != null) { tokens.add(t); pos = pos + t.text.length(); break; // restart rule application loop } } } if(pos == start) { throw new Error("unrecognised token encountered (" + input.charAt(pos) + ")",pos); } } return tokens; }protected String parseString(String v) { /* * Parsing a string requires several steps to be taken. First, we need * to strip quotes from the ends of the string. */ v = v.substring(1, v.length() - 1); StringBuffer result = new StringBuffer(); // Second, step through the string and replace escaped characters for (int i = 0; i < v.length(); i++) { if (v.charAt(i) == '\\') { if (v.length() <= i + 1) { throw new RuntimeException("unexpected end-of-string"); } else { char replace = 0; int len = 2; switch (v.charAt(i + 1)) { case 'b': replace = '\b'; break; case 't': replace = '\t'; break; case 'n': replace = '\n'; break; case 'f': replace = '\f'; break; case 'r': replace = '\r'; break; case '"': replace = '\"'; break; case '\'': replace = '\''; break; case '\\': replace = '\\'; break; case 'u': len = 6; // unicode escapes are six digits long, // including "slash u" String unicode = v.substring(i + 2, i + 6); replace = (char) Integer.parseInt(unicode, 16); // unicode i = i + 5; break; default: throw new RuntimeException("unknown escape character"); } result = result.append(replace); i = i + 1; } } else { result = result.append(v.charAt(i)); } } return result.toString(); }private boolean isLineSpace(Token token) { return token.kind == Token.Kind.Indent || token.kind == Token.Kind.LineComment; }private void checkNotEof() { skipWhiteSpace(); if (index >= tokens.size()) { if (index > 0) { syntaxError("unexpected end-of-file", tokens.get(index - 1)); } else { // I believe this is actually dead-code, since checkNotEof() // won't be called before at least one token is matched. throw new SyntacticException("unexpected end-of-file", file.getEntry(), null); } } }public static Filter or(final Filter f1, final Filter f2) { return new Filter() { @Override public boolean matches(Path.ID id, Content.Type ct) { return f1.matches(id, ct) || f2.matches(id, ct); } @Override public boolean matchesSubpath(Path.ID id) { return f1.matchesSubpath(id) || f2.matchesSubpath(id); } @Override public String toString() { return f1.toString() + "|" + f2.toString(); } }; }public static Filter filter(final Path.Filter filter, final Content.Type contentType) { return new Filter() { @Override public boolean matches(Path.ID id, Content.Type ct) { return ct == contentType && filter.matches(id); } @Override public boolean matchesSubpath(Path.ID id) { return filter.matchesSubpath(id); } @Override public String toString() { return filter.toString(); } }; }@Deprecated public EmbeddedTomcat addContextEnvironmentAndResourceFromFile(String contextFile) { try { setContextFile(new File(contextFile).toURI().toURL()); } catch (MalformedURLException e) { throw new RuntimeException(e); } return this; }public EmbeddedTomcat setContextFile(String contextFile) { try { this.contextFileURL = new File(contextFile).toURI().toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } return this; }public EmbeddedTomcat setContextPath(String contextPath) { if (contextPath == null || !contextPath.equals("") && !contextPath.startsWith("/")) { throw new IllegalArgumentException( "contextPath must be the empty string \"\" or a path starting with /"); } this.contextPath = contextPath; return this; }private void writeByChunk(final byte[] bytes) throws IOException { final int chunkSize = this.chunkSize; if (bytes.length == 0) { return; } if (chunkSize < bytes.length && chunkSize > 0) { int remaining = bytes.length; int offset = 0; while (remaining > 0) { if (chunkSize < remaining) { os.write(bytes, offset, chunkSize); remaining -= chunkSize; offset += chunkSize; } else { os.write(bytes, offset, remaining); remaining = 0; } } } else { os.write(bytes); } }public String getChildText() { final List children = getChildren(); if (children.size() > 0) { final StringBuilder builder = new StringBuilder(); for (final AbstractHtml child : children) { builder.append(child.toHtmlString()); } return builder.toString(); } return ""; }public static Stream buildAllAttributesStream( final boolean parallel, final AbstractHtml... fromTags) { final Stream attributesStream = getAllNestedChildrenIncludingParent( parallel, fromTags).filter(tag -> tag.getAttributes() != null) .map(tag -> { return tag.getAttributes(); }).flatMap(attributes -> attributes.stream()); return attributesStream; }public boolean exists(final AbstractAttribute attribute) throws NullValueException { if (attribute == null) { throw new NullValueException("attribute cannot be null"); } for (final AbstractHtml ownerTag : attribute.getOwnerTags()) { if (browserPage.contains(ownerTag)) { return true; } } return false; }public boolean exists(final AbstractHtml tag) throws NullValueException, InvalidTagException { if (tag == null) { throw new NullValueException("tag cannot be null"); } if (NoTag.class.isAssignableFrom(tag.getClass())) { throw new InvalidTagException( "classes like NoTag.class cannot be used to find tags as it's not a logical tag in behaviour."); } return browserPage.contains(tag); }public static Collection findAllAttributes( final boolean parallel, final AbstractHtml... fromTags) throws NullValueException { if (fromTags == null) { throw new NullValueException("fromTags cannot be null"); } final Collection locks = getReadLocks(fromTags); for (final Lock lock : locks) { lock.lock(); } try { return getAllNestedChildrenIncludingParent(parallel, fromTags) .filter(tag -> tag.getAttributes() != null).map(tag -> { return tag.getAttributes(); }).flatMap(attributes -> attributes.stream()) .collect(Collectors.toSet()); } finally { for (final Lock lock : locks) { lock.unlock(); } } }public Stream buildAllAttributesStream( final boolean parallel) { final Stream attributesStream = buildAllTagsStream( parallel).filter(tag -> tag.getAttributes() != null) .map(tag -> { return tag.getAttributes(); }).flatMap(attributes -> attributes.stream()); return attributesStream; }public Collection findAllAttributes( final boolean parallel) { final Collection locks = getReadLocks(rootTags); for (final Lock lock : locks) { lock.lock(); } try { return buildAllAttributesStream(parallel) .collect(Collectors.toSet()); } finally { for (final Lock lock : locks) { lock.unlock(); } } }public AbstractHtml findOneTagByAttribute( final AbstractAttribute attribute) { if (attribute == null) { throw new NullValueException("attribute cannot be null"); } for (final AbstractHtml ownerTag : attribute.getOwnerTags()) { if (browserPage.contains(ownerTag)) { return ownerTag; } } return null; }public Collection findTagsByAttribute( final AbstractAttribute attribute) throws NullValueException { if (attribute == null) { throw new NullValueException("attribute cannot be null"); } final Collection tags = new HashSet<>(); for (final AbstractHtml ownerTag : attribute.getOwnerTags()) { if (browserPage.contains(ownerTag)) { tags.add(ownerTag); } } return tags; }Map getCssPropertiesAsMap(final boolean rebuild) { if (rebuild || !loadedOnce) { synchronized (cssProperties) { if (rebuild || !loadedOnce) { cssProperties.clear(); load(cssProperties); loadedOnce = true; setModified(true); } } } return cssPropertiesAsMap; }public boolean contains(final CssProperty cssProperty) { final long stamp = lock.readLock(); try { return cssProperties.contains(cssProperty); } finally { lock.unlockRead(stamp); } }public void removeAllCssProperties() { final long stamp = lock.writeLock(); try { cssProperties.clear(); abstractCssPropertyClassObjects.clear(); super.removeAllFromAttributeValueMap(); } finally { lock.unlockWrite(stamp); } }public static ByteBuffer merge(final ByteBuffer... dataArray) { int totalCapacity = 0; for (final ByteBuffer data : dataArray) { totalCapacity += data.capacity(); } final ByteBuffer wholeData = ByteBuffer.allocate(totalCapacity); for (final ByteBuffer data : dataArray) { wholeData.put(data); } wholeData.flip(); return wholeData; }public void setValue(final UUID uuid) { if (uuid != null) { super.setAttributeValue(uuid.toString()); this.uuid = uuid; } }public Border setBorderStyle(final BorderStyle borderStyle) { if (borderStyle == BorderStyle.INITIAL || borderStyle == BorderStyle.INHERIT) { throw new InvalidValueException("the given borderStyle cannot be " + borderStyle.getCssValue()); } final StringBuilder cssValueBuilder = new StringBuilder(); if (borderWidthValue != null) { cssValueBuilder.append(borderWidthValue).append(' '); } if (borderStyle != null) { cssValueBuilder.append(borderStyle.getCssValue()).append(' '); } if (borderColorCssValues != null) { cssValueBuilder.append(borderColorCssValues.getValue()).append(' '); } final String trimmedCssValue = StringBuilderUtil .getTrimmedString(cssValueBuilder).toString(); cssValue = trimmedCssValue.isEmpty() ? INHERIT : trimmedCssValue; this.borderStyle = borderStyle; if (getStateChangeInformer() != null) { getStateChangeInformer().stateChanged(this); } return this; }protected final void setNonceForWffScript(final String value) { if (autoremoveWffScript) { throw new InvalidUsageException( "Cannot remove while autoremoveWffScript is set as true. Please do setAutoremoveWffScript(false)"); } if (value != null) { if (nonceForWffScriptTag == null) { nonceForWffScriptTag = new Nonce(value); if (wffScriptTagId != null) { final AbstractHtml[] ownerTags = wffScriptTagId .getOwnerTags(); if (ownerTags.length > 0) { final AbstractHtml wffScript = ownerTags[0]; wffScript.addAttributes(nonceForWffScriptTag); } } } else { nonceForWffScriptTag.setValue(value); } } else { if (wffScriptTagId != null && nonceForWffScriptTag != null) { final AbstractHtml[] ownerTags = wffScriptTagId.getOwnerTags(); if (ownerTags.length > 0) { final AbstractHtml wffScript = ownerTags[0]; wffScript.removeAttributes(nonceForWffScriptTag); } } nonceForWffScriptTag = null; } }public final TagRepository getTagRepository() { if (tagRepository == null && rootTag != null) { synchronized (this) { if (tagRepository == null) { tagRepository = new TagRepository(ACCESS_OBJECT, this, tagByWffId, rootTag); } } } return tagRepository; }public final void removeFromContext(final boolean enable, final On... ons) { for (final On on : ons) { if (On.TAB_CLOSE.equals(on)) { removeFromBrowserContextOnTabClose = enable; } else if (On.INIT_REMOVE_PREVIOUS.equals(on)) { removePrevFromBrowserContextOnTabInit = enable; } } }public final void removeWebSocketPushListener(final String sessionId) { final WebSocketPushListener removed = sessionIdWsListeners .remove(sessionId); wsListeners.remove(removed); wsListener = wsListeners.peek(); }public final void addWebSocketPushListener(final String sessionId, final WebSocketPushListener wsListener) { sessionIdWsListeners.put(sessionId, wsListener); wsListeners.push(wsListener); this.wsListener = wsListener; if (pushQueueOnNewWebSocketListener) { pushWffBMBytesQueue(); } }protected void replaceAllInAttributeValueSet(final boolean updateClient, final String... attrValues) { if (attrValues != null) { final Collection allValues = new ArrayDeque<>(); for (final String attrValue : attrValues) { if (attrValue != null) { allValues.addAll(extractValues(attrValue)); } } super.replaceAllInAttributeValueSet(updateClient, allValues); } }@Override protected void setAttributeValue(final boolean updateClient, final String value) { if (value != null) { final Collection allValues = extractValues(value); super.replaceAllInAttributeValueSet(updateClient, allValues); } }public boolean insertBefore(final AbstractHtml... abstractHtmls) { if (parent == null) { throw new NoParentException("There must be a parent for this tag."); } final Lock lock = sharedObject.getLock(ACCESS_OBJECT).writeLock(); boolean result = false; try { lock.lock(); final AbstractHtml[] removedParentChildren = parent.children .toArray(new AbstractHtml[parent.children.size()]); result = insertBefore(removedParentChildren, abstractHtmls); } finally { lock.unlock(); } final PushQueue pushQueue = sharedObject.getPushQueue(ACCESS_OBJECT); if (pushQueue != null) { pushQueue.push(); } return result; }public final String getOpeningTag() { if (isRebuild() || isModified()) { final Lock lock = sharedObject.getLock(ACCESS_OBJECT).writeLock(); try { lock.lock(); buildOpeningTag(true); } finally { lock.unlock(); } } return openingTag; }public boolean containsChild(final AbstractHtml childTag) { final Lock lock = sharedObject.getLock(ACCESS_OBJECT).readLock(); try { lock.lock(); return children.contains(childTag); } finally { lock.unlock(); } }public int getChildrenSize() { final Lock lock = sharedObject.getLock(ACCESS_OBJECT).readLock(); try { lock.lock(); return children.size(); } finally { lock.unlock(); } }public AbstractHtml getFirstChild() { // this block must be synchronized otherwise may get null or // ConcurrentModificationException // the test cases are written to check its thread safety and can be // reproduce by uncommenting this synchronized block, checkout // AbstractHtmlTest class for it. // synchronized (children) { // // } // it's been replaced with locking final Lock lock = sharedObject.getLock(ACCESS_OBJECT).readLock(); try { lock.lock(); // this must be most efficient because the javadoc of findFirst says // "This is a short-circuiting terminal operation." // return (T) children.stream().findFirst().orElse(null); // but as per CodePerformanceTest.testPerformanceOfFindFirst // the below is faster final Iterator iterator = children.iterator(); if (iterator.hasNext()) { return iterator.next(); } return null; } finally { lock.unlock(); } }public AbstractHtml[] getChildrenAsArray() { final Lock lock = sharedObject.getLock(ACCESS_OBJECT).readLock(); try { lock.lock(); return children.toArray(new AbstractHtml[children.size()]); } finally { lock.unlock(); } }private void initInConstructor() { htmlStartSB = new StringBuilder(tagName == null ? 0 : tagName.length() + 2 + ((attributes == null ? 0 : attributes.length) * 16)); htmlEndSB = new StringBuilder( tagName == null ? 16 : tagName.length() + 3); }private void markOwnerTag(final AbstractAttribute[] attributes) { if (attributes == null) { return; } for (final AbstractAttribute abstractAttribute : attributes) { abstractAttribute.setOwnerTag(this); } }public AbstractAttribute getAttributeByName(final String attributeName) { final Lock lock = sharedObject.getLock(ACCESS_OBJECT).readLock(); AbstractAttribute result = null; try { lock.lock(); if (attributesMap != null) { result = attributesMap.get(attributeName); } } finally { lock.unlock(); } return result; }private void initAttributes(final AbstractAttribute... attributes) { if (attributes == null || attributes.length == 0) { return; } // initial capacity must be greater than 1 instead of 1 // because the load factor is 0.75f // possible initial attributes on a tag may be maximum 8 // they may be id, name, class, value, style, onchange, placeholder attributesMap = new ConcurrentHashMap<>(8); for (final AbstractAttribute attribute : attributes) { attributesMap.put(attribute.getAttributeName(), attribute); } this.attributes = new AbstractAttribute[attributesMap.size()]; attributesMap.values().toArray(this.attributes); }public void appendChildren(final Collection children) { boolean listenerInvoked = false; final Lock lock = sharedObject.getLock(ACCESS_OBJECT).writeLock(); try { lock.lock(); final Collection movedOrAppended = new ArrayDeque<>( children.size()); for (final AbstractHtml child : children) { final AbstractHtml previousParent = child.parent; addChild(child, false); final ChildMovedEvent event = new ChildMovedEvent( previousParent, this, child); movedOrAppended.add(event); } final ChildTagAppendListener listener = sharedObject .getChildTagAppendListener(ACCESS_OBJECT); if (listener != null) { listener.childrendAppendedOrMoved(movedOrAppended); listenerInvoked = true; } } finally { lock.unlock(); } if (listenerInvoked) { final PushQueue pushQueue = sharedObject .getPushQueue(ACCESS_OBJECT); if (pushQueue != null) { pushQueue.push(); } } }public boolean removeChild(final AbstractHtml child) { boolean listenerInvoked = false; final Lock lock = sharedObject.getLock(ACCESS_OBJECT).writeLock(); boolean removed = false; try { lock.lock(); removed = children.remove(child); if (removed) { // making child.parent = null inside the below method. initNewSharedObjectInAllNestedTagsAndSetSuperParentNull(child); final ChildTagRemoveListener listener = sharedObject .getChildTagRemoveListener(ACCESS_OBJECT); if (listener != null) { listener.childRemoved( new ChildTagRemoveListener.Event(this, child)); listenerInvoked = true; } } } finally { lock.unlock(); } if (listenerInvoked) { final PushQueue pushQueue = sharedObject .getPushQueue(ACCESS_OBJECT); if (pushQueue != null) { pushQueue.push(); } } return removed; }public boolean removeChildren(final Collection children) { final Lock lock = sharedObject.getLock(ACCESS_OBJECT).writeLock(); boolean result = false; try { lock.lock(); result = this.children.removeAll(children); } finally { lock.unlock(); } final PushQueue pushQueue = sharedObject.getPushQueue(ACCESS_OBJECT); if (pushQueue != null) { pushQueue.push(); } return result; }protected void addInnerHtmls(final boolean updateClient, final AbstractHtml... innerHtmls) { boolean listenerInvoked = false; final Lock lock = sharedObject.getLock(ACCESS_OBJECT).writeLock(); try { lock.lock(); final AbstractHtml[] removedAbstractHtmls = children .toArray(new AbstractHtml[children.size()]); children.clear(); initNewSharedObjectInAllNestedTagsAndSetSuperParentNull( removedAbstractHtmls); final InnerHtmlAddListener listener = sharedObject .getInnerHtmlAddListener(ACCESS_OBJECT); if (listener != null && updateClient) { final InnerHtmlAddListener.Event[] events = new InnerHtmlAddListener.Event[innerHtmls.length]; int index = 0; for (final AbstractHtml innerHtml : innerHtmls) { AbstractHtml previousParentTag = null; if (innerHtml.parent != null && innerHtml.parent.sharedObject == sharedObject) { previousParentTag = innerHtml.parent; } addChild(innerHtml, false); events[index] = new InnerHtmlAddListener.Event(this, innerHtml, previousParentTag); index++; } listener.innerHtmlsAdded(this, events); listenerInvoked = true; } else { for (final AbstractHtml innerHtml : innerHtmls) { addChild(innerHtml, false); } } } finally { lock.unlock(); } if (listenerInvoked) { final PushQueue pushQueue = sharedObject .getPushQueue(ACCESS_OBJECT); if (pushQueue != null) { pushQueue.push(); } } }public void removeAllChildren() { boolean listenerInvoked = false; final Lock lock = sharedObject.getLock(ACCESS_OBJECT).writeLock(); try { lock.lock(); final AbstractHtml[] removedAbstractHtmls = children .toArray(new AbstractHtml[children.size()]); children.clear(); initNewSharedObjectInAllNestedTagsAndSetSuperParentNull( removedAbstractHtmls); final ChildTagRemoveListener listener = sharedObject .getChildTagRemoveListener(ACCESS_OBJECT); if (listener != null) { listener.allChildrenRemoved(new ChildTagRemoveListener.Event( this, removedAbstractHtmls)); listenerInvoked = true; } } finally { lock.unlock(); } if (listenerInvoked) { final PushQueue pushQueue = sharedObject .getPushQueue(ACCESS_OBJECT); if (pushQueue != null) { pushQueue.push(); } } }public static String strip(final String s) { int first; int last; for (first = 0; first < s.length(); first++) { if (!Character.isWhitespace(s.charAt(first))) { break; } } for (last = s.length(); last > first; last--) { if (!Character.isWhitespace(s.charAt(last - 1))) { break; } } return s.substring(first, last); }public static boolean containsWhitespace(final String string) { for (int i = 0; i < string.length(); i++) { if (Character.isWhitespace(string.charAt(i))) { return true; } } return false; }public static String[] cloneArray(final String[] inputArray) { final String[] array = new String[inputArray.length]; System.arraycopy(inputArray, 0, array, 0, inputArray.length); return array; }public static String getFirstSubstring(final String inputString, final String startingWith, final String endingWith) { if (!inputString.contains(startingWith) || !inputString.contains(endingWith)) { return null; } final int startIndex = inputString.indexOf(startingWith); if (!((startIndex + 1) < inputString.length())) { return null; } final int endIndex = inputString.indexOf(endingWith, startIndex + 1) + 1; if (startIndex > endIndex || startIndex < 0 || endIndex < 0) { return null; } return inputString.substring(startIndex, endIndex); }public static void loadAllTagClasses() { final Map> unloadedClasses = new HashMap<>(); for (final Entry> entry : tagClassByTagNameTmp .entrySet()) { try { Class.forName(entry.getValue().getName()); } catch (final ClassNotFoundException e) { unloadedClasses.put(entry.getKey(), entry.getValue()); if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.warning("Could not load tag class " + entry.getValue().getName()); } } } tagClassByTagNameTmp.clear(); if (unloadedClasses.size() > 0) { tagClassByTagNameTmp.putAll(unloadedClasses); } else { tagClassByTagNameTmp = null; } }public void setA(final float a) { if (a < 0 || a > 1) { throw new InvalidValueException( "a paramater accept values only from 0 to 255."); } this.a = a; rgba = "rgba(" + r + ", " + g + ", " + b + ", " + a + ")"; if (getStateChangeInformer() != null) { getStateChangeInformer().stateChanged(this); } }public void setB(final int b) { if (b < 0 || b > 255) { throw new InvalidValueException( "b paramater accept values only from 0 to 255."); } this.b = b; rgba = "rgba(" + r + ", " + g + ", " + b + ", " + a + ")"; if (getStateChangeInformer() != null) { getStateChangeInformer().stateChanged(this); } }public void setG(final int g) { if (g < 0 || g > 255) { throw new InvalidValueException( "g paramater accept values only from 0 to 255."); } this.g = g; rgba = "rgba(" + r + ", " + g + ", " + b + ", " + a + ")"; if (getStateChangeInformer() != null) { getStateChangeInformer().stateChanged(this); } }public void setR(final int r) { if (r < 0 || r > 255) { throw new InvalidValueException( "r paramater accept values only from 0 to 255."); } this.r = r; rgba = "rgba(" + r + ", " + g + ", " + b + ", " + a + ")"; if (getStateChangeInformer() != null) { getStateChangeInformer().stateChanged(this); } }public boolean containsValidRegEx() { try { java.util.regex.Pattern.compile(super.getAttributeValue()); return true; } catch (final PatternSyntaxException e) { // NOP } return false; }public void addValueChangeListener( final AttributeValueChangeListener valueChangeListener) { if (valueChangeListeners == null) { synchronized (this) { if (valueChangeListeners == null) { valueChangeListeners = new LinkedHashSet<>(); } } } valueChangeListeners.add(valueChangeListener); }protected void removeAllFromAttributeValueSet() { final Collection sharedObjects = getSharedObjects(); boolean listenerInvoked = false; final Collection writeLocks = lockAndGetWriteLocks(); try { getAttributeValueSet().clear(); setModified(true); invokeValueChangeListeners(sharedObjects); listenerInvoked = true; } finally { for (final Lock lock : writeLocks) { lock.unlock(); } } pushQueues(sharedObjects, listenerInvoked); }protected void removeAllFromAttributeValueSet( final Collection values) { final Collection sharedObjects = getSharedObjects(); boolean listenerInvoked = false; final Collection writeLocks = lockAndGetWriteLocks(); try { final boolean removedAll = getAttributeValueSet().removeAll(values); if (removedAll) { setModified(true); invokeValueChangeListeners(sharedObjects); listenerInvoked = true; } } finally { for (final Lock lock : writeLocks) { lock.unlock(); } } pushQueues(sharedObjects, listenerInvoked); }protected void addAllToAttributeValueSet(final Collection values) { if (values != null) { final Collection sharedObjects = getSharedObjects(); boolean listenerInvoked = false; final Collection writeLocks = lockAndGetWriteLocks(); try { final boolean added = getAttributeValueSet().addAll(values); if (added) { setModified(true); invokeValueChangeListeners(sharedObjects); listenerInvoked = true; } } finally { for (final Lock lock : writeLocks) { lock.unlock(); } } pushQueues(sharedObjects, listenerInvoked); } }protected boolean addToAttributeValueSet(final String value) { final Collection sharedObjects = getSharedObjects(); boolean listenerInvoked = false; final Collection writeLocks = lockAndGetWriteLocks(); try { final boolean added = getAttributeValueSet().add(value); if (added) { setModified(true); invokeValueChangeListeners(sharedObjects); listenerInvoked = true; } } finally { for (final Lock lock : writeLocks) { lock.unlock(); } } pushQueues(sharedObjects, listenerInvoked); return listenerInvoked; }protected boolean removeFromAttributeValueMap(final String key, final String value) { final Collection sharedObjects = getSharedObjects(); final Collection writeLocks = lockAndGetWriteLocks(); boolean listenerInvoked = false; try { final boolean removed = getAttributeValueMap().remove(key, value); if (removed) { setModified(true); invokeValueChangeListeners(sharedObjects); listenerInvoked = true; } } finally { for (final Lock lock : writeLocks) { lock.unlock(); } } pushQueues(sharedObjects, listenerInvoked); return listenerInvoked; }private void pushQueues( final Collection sharedObjects, final boolean listenerInvoked) { if (listenerInvoked) { for (final AbstractHtml5SharedObject sharedObject : sharedObjects) { final PushQueue pushQueue = sharedObject .getPushQueue(ACCESS_OBJECT); if (pushQueue != null) { pushQueue.push(); } } } }protected boolean removeFromAttributeValueMapByKeys(final String... keys) { final Collection sharedObjects = getSharedObjects(); boolean listenerInvoked = false; final Collection writeLocks = lockAndGetWriteLocks(); boolean result = false; try { final Map valueMap = getAttributeValueMap(); if (nullableAttrValueMapValue) { for (final String key : keys) { result = valueMap.containsKey(key); if (result) { break; } } } for (final String key : keys) { final String previous = valueMap.remove(key); if (previous != null) { result = true; } } if (result) { setModified(true); invokeValueChangeListeners(sharedObjects); listenerInvoked = true; } } finally { for (final Lock lock : writeLocks) { lock.unlock(); } } pushQueues(sharedObjects, listenerInvoked); return result; }protected boolean addAllToAttributeValueMap(final Map map) { if (map != null && map.size() > 0) { final Collection sharedObjects = getSharedObjects(); boolean listenerInvoked = false; final Collection writeLocks = lockAndGetWriteLocks(); try { getAttributeValueMap().putAll(map); setModified(true); invokeValueChangeListeners(sharedObjects); listenerInvoked = true; } finally { for (final Lock lock : writeLocks) { lock.unlock(); } } pushQueues(sharedObjects, listenerInvoked); return listenerInvoked; } return false; }private void invokeValueChangeListeners( final Collection sharedObjects) { for (final AbstractHtml5SharedObject sharedObject : sharedObjects) { final AttributeValueChangeListener valueChangeListener = sharedObject .getValueChangeListener(ACCESS_OBJECT); if (valueChangeListener != null) { // ownerTags should not be modified in the consuming // part, here // skipped it making unmodifiable to gain // performance final AttributeValueChangeListener.Event event = new AttributeValueChangeListener.Event( this, ownerTags); valueChangeListener.valueChanged(event); } } if (valueChangeListeners != null) { for (final AttributeValueChangeListener listener : valueChangeListeners) { final AttributeValueChangeListener.Event event = new AttributeValueChangeListener.Event( this, Collections.unmodifiableSet(ownerTags)); listener.valueChanged(event); } } }protected boolean addToAttributeValueMap(final String key, final String value) { final Collection sharedObjects = getSharedObjects(); boolean listenerInvoked = false; final Collection writeLocks = lockAndGetWriteLocks(); try { final Map attributeValueMap = getAttributeValueMap(); final String previousValue = attributeValueMap.put(key, value); if (!Objects.equals(previousValue, value)) { setModified(true); invokeValueChangeListeners(sharedObjects); listenerInvoked = true; } } finally { for (final Lock lock : writeLocks) { lock.unlock(); } } pushQueues(sharedObjects, listenerInvoked); return listenerInvoked; }private void addInWffIdMap(final AbstractHtml tag) { final Deque> childrenStack = new ArrayDeque<>(); // passed 2 instead of 1 because the load factor is 0.75f final Set initialSet = new HashSet<>(2); initialSet.add(tag); childrenStack.push(initialSet); Set children; while ((children = childrenStack.poll()) != null) { for (final AbstractHtml child : children) { final DataWffId wffIdAttr = child.getDataWffId(); if (wffIdAttr != null) { tagByWffId.put(wffIdAttr.getValue(), child); } final Set subChildren = child .getChildren(accessObject); if (subChildren != null && subChildren.size() > 0) { childrenStack.push(subChildren); } } } }public void removeChild(final String child) { final StringBuilder htmlMiddleSB = getHtmlMiddleSB(); final String sb = htmlMiddleSB.toString(); final String replaced = sb.replace(child, ""); final int lastIndex = htmlMiddleSB.length() - 1; htmlMiddleSB.delete(0, lastIndex); htmlMiddleSB.append(replaced); }private void publishEvent(String name, Object event) { assert(hasEventBusses()); EventBus eventBus = getEventBus(name); if (eventBus == null) { throw new RuntimeException("Unknown event bus name: " + name); } eventBus.publish(event); }private void publishEvent(Object event) { assert(hasEventBusses()); for (EventBus eventBus : eventBusses.values()) { eventBus.publish(event); } }private void processEvent(final Object event) { System.out.println("Processing event: " + event.toString()); for (final EventHandler handler : getConsumersFor(event.getClass())) { EVENT_EXECUTOR.execute(new Runnable(){ @Override public void run() { try { handler.handle(event); } catch(Exception e) { e.printStackTrace(); if (shouldReRaiseOnError) { System.out.println("Event handler failed. Re-publishing event: " + event.toString()); eventQueue.publish(event); } } } }); } }public Iterator iterator() { final Iterator iterator = values.iterator(); return new Iterator() { public boolean hasNext() { return iterator.hasNext(); } public org.jmxtrans.agent.util.json.JsonValue next() { return iterator.next(); } public void remove() { throw new UnsupportedOperationException(); } }; }public List values() { return Collections.unmodifiableList(values); }public org.jmxtrans.agent.util.json.JsonValue get(int index) { return values.get(index); }public JsonArray set(int index, org.jmxtrans.agent.util.json.JsonValue value) { if (value == null) { throw new NullPointerException("value is null"); } values.set(index, value); return this; }public JsonArray add(org.jmxtrans.agent.util.json.JsonValue value) { if (value == null) { throw new NullPointerException("value is null"); } values.add(value); return this; }@Deprecated public static JsonArray readFrom(String string) { return org.jmxtrans.agent.util.json.JsonValue.readFrom(string).asArray(); }@Nonnull public static String getVersionInfo() { Package pkg = JmxTransAgent.class.getPackage(); if (pkg == null) { return "jmxtrans-agent"; } else { return pkg.getImplementationTitle() + ": " + pkg.getImplementationVersion(); } }protected String resolvePlaceholder(String property, String defaultValue) throws IllegalStateException { // "graphite.host" -> "GRAPHITE_HOST" String environmentVariableStyleProperty = property.toUpperCase(); environmentVariableStyleProperty = environmentVariableStyleProperty.replaceAll("\\.", "_"); String result; if (externalProperties.containsKey(property)) { result = externalProperties.get(property); } else if (System.getProperties().containsKey(property)) { result = System.getProperty(property); } else if (System.getenv().containsKey(property)) { result = System.getenv(property); } else if (System.getenv().containsKey(environmentVariableStyleProperty)) { result = System.getenv(environmentVariableStyleProperty); } else if (defaultValue != null) { result = defaultValue; } else { throw new IllegalStateException("Property '" + property + "' not found in System properties nor in Environment variables"); } return result; }public Iterator iterator() { final Iterator namesIterator = names.iterator(); final Iterator valuesIterator = values.iterator(); return new Iterator() { public boolean hasNext() { return namesIterator.hasNext(); } public Member next() { String name = namesIterator.next(); org.jmxtrans.agent.util.json.JsonValue value = valuesIterator.next(); return new Member(name, value); } public void remove() { throw new UnsupportedOperationException(); } }; }public org.jmxtrans.agent.util.json.JsonValue get(String name) { if (name == null) { throw new NullPointerException("name is null"); } int index = indexOf(name); return index != -1 ? values.get(index) : null; }@Deprecated public static JsonObject readFrom(String string) { return org.jmxtrans.agent.util.json.JsonValue.readFrom(string).asObject(); }public static String getString(Map settings, String name, String defaultValue) { if (settings.containsKey(name)) { return settings.get(name); } else { return defaultValue; } }public static org.jmxtrans.agent.util.json.JsonValue parse(String string) { if (string == null) { throw new NullPointerException("string is null"); } DefaultHandler handler = new DefaultHandler(); new JsonParser(handler).parse(string); return handler.getValue(); }public static org.jmxtrans.agent.util.json.JsonObject object() { return new org.jmxtrans.agent.util.json.JsonObject(); }public static org.jmxtrans.agent.util.json.JsonValue value(String string) { return string == null ? NULL : new JsonString(string); }@Nonnull public static String abbreviate(String str, int max) { if (str == null) { return ""; } else if (str.length() <= max) { return str; } else { return str.substring(0, max - 3) + "..."; } }public static long gcd(List l) { if (l.isEmpty()) { throw new IllegalArgumentException("List must contain at least one element"); } BigInteger gcd = BigInteger.valueOf(l.get(0)); for (Long num : l.subList(1, l.size())) { gcd = gcd.gcd(BigInteger.valueOf(num)); } return gcd.longValue(); }@Override public boolean exists() { // Try file existence: can we find the file in the file system? try { return getFile().exists(); } catch (IoRuntimeException ex) { // Fall back to stream existence: can we open the stream? try { try (InputStream is = getInputStream()) { return true; } } catch (Throwable isEx) { return false; } } }public static GeometryType getGeometryType(int code) { // Look at the last 2 digits to find the geometry type code int geometryTypeCode = code % 1000; GeometryType geometryType = null; switch (geometryTypeCode) { case 0: geometryType = GeometryType.GEOMETRY; break; case 1: geometryType = GeometryType.POINT; break; case 2: geometryType = GeometryType.LINESTRING; break; case 3: geometryType = GeometryType.POLYGON; break; case 4: geometryType = GeometryType.MULTIPOINT; break; case 5: geometryType = GeometryType.MULTILINESTRING; break; case 6: geometryType = GeometryType.MULTIPOLYGON; break; case 7: geometryType = GeometryType.GEOMETRYCOLLECTION; break; case 8: geometryType = GeometryType.CIRCULARSTRING; break; case 9: geometryType = GeometryType.COMPOUNDCURVE; break; case 10: geometryType = GeometryType.CURVEPOLYGON; break; case 11: geometryType = GeometryType.MULTICURVE; break; case 12: geometryType = GeometryType.MULTISURFACE; break; case 13: geometryType = GeometryType.CURVE; break; case 14: geometryType = GeometryType.SURFACE; break; case 15: geometryType = GeometryType.POLYHEDRALSURFACE; break; case 16: geometryType = GeometryType.TIN; break; case 17: geometryType = GeometryType.TRIANGLE; break; default: throw new SFException( "Unsupported Geometry code for type retrieval: " + code); } return geometryType; }public static int getCode(GeometryType geometryType) { int code; switch (geometryType) { case GEOMETRY: code = 0; break; case POINT: code = 1; break; case LINESTRING: code = 2; break; case POLYGON: code = 3; break; case MULTIPOINT: code = 4; break; case MULTILINESTRING: code = 5; break; case MULTIPOLYGON: code = 6; break; case GEOMETRYCOLLECTION: code = 7; break; case CIRCULARSTRING: code = 8; break; case COMPOUNDCURVE: code = 9; break; case CURVEPOLYGON: code = 10; break; case MULTICURVE: code = 11; break; case MULTISURFACE: code = 12; break; case CURVE: code = 13; break; case SURFACE: code = 14; break; case POLYHEDRALSURFACE: code = 15; break; case TIN: code = 16; break; case TRIANGLE: code = 17; break; default: throw new SFException( "Unsupported Geometry Type for code retrieval: " + geometryType); } return code; }public static int getCode(Geometry geometry) { int code = getCode(geometry.getGeometryType()); if (geometry.hasZ()) { code += 1000; } if (geometry.hasM()) { code += 2000; } return code; }public static void writeTriangle(ByteWriter writer, Triangle triangle) throws IOException { writer.writeInt(triangle.numRings()); for (LineString ring : triangle.getRings()) { writeLineString(writer, ring); } }public static void writeTIN(ByteWriter writer, TIN tin) throws IOException { writer.writeInt(tin.numPolygons()); for (Polygon polygon : tin.getPolygons()) { writeGeometry(writer, polygon); } }public static void writePolyhedralSurface(ByteWriter writer, PolyhedralSurface polyhedralSurface) throws IOException { writer.writeInt(polyhedralSurface.numPolygons()); for (Polygon polygon : polyhedralSurface.getPolygons()) { writeGeometry(writer, polygon); } }public static void writeCurvePolygon(ByteWriter writer, CurvePolygon curvePolygon) throws IOException { writer.writeInt(curvePolygon.numRings()); for (Curve ring : curvePolygon.getRings()) { writeGeometry(writer, ring); } }public static void writeCompoundCurve(ByteWriter writer, CompoundCurve compoundCurve) throws IOException { writer.writeInt(compoundCurve.numLineStrings()); for (LineString lineString : compoundCurve.getLineStrings()) { writeGeometry(writer, lineString); } }public static void writeCircularString(ByteWriter writer, CircularString circularString) throws IOException { writer.writeInt(circularString.numPoints()); for (Point point : circularString.getPoints()) { writePoint(writer, point); } }public static void writeGeometryCollection(ByteWriter writer, GeometryCollection geometryCollection) throws IOException { writer.writeInt(geometryCollection.numGeometries()); for (Geometry geometry : geometryCollection.getGeometries()) { writeGeometry(writer, geometry); } }public static void writeMultiPolygon(ByteWriter writer, MultiPolygon multiPolygon) throws IOException { writer.writeInt(multiPolygon.numPolygons()); for (Polygon polygon : multiPolygon.getPolygons()) { writeGeometry(writer, polygon); } }public static void writeMultiLineString(ByteWriter writer, MultiLineString multiLineString) throws IOException { writer.writeInt(multiLineString.numLineStrings()); for (LineString lineString : multiLineString.getLineStrings()) { writeGeometry(writer, lineString); } }public static void writeMultiPoint(ByteWriter writer, MultiPoint multiPoint) throws IOException { writer.writeInt(multiPoint.numPoints()); for (Point point : multiPoint.getPoints()) { writeGeometry(writer, point); } }public static void writePolygon(ByteWriter writer, Polygon polygon) throws IOException { writer.writeInt(polygon.numRings()); for (LineString ring : polygon.getRings()) { writeLineString(writer, ring); } }public static void writeLineString(ByteWriter writer, LineString lineString) throws IOException { writer.writeInt(lineString.numPoints()); for (Point point : lineString.getPoints()) { writePoint(writer, point); } }public static void writePoint(ByteWriter writer, Point point) throws IOException { writer.writeDouble(point.getX()); writer.writeDouble(point.getY()); if (point.hasZ()) { writer.writeDouble(point.getZ()); } if (point.hasM()) { writer.writeDouble(point.getM()); } }public static void writeGeometry(ByteWriter writer, Geometry geometry) throws IOException { // Write the single byte order byte byte byteOrder = writer.getByteOrder() == ByteOrder.BIG_ENDIAN ? (byte) 0 : (byte) 1; writer.writeByte(byteOrder); // Write the geometry type integer writer.writeInt(GeometryCodes.getCode(geometry)); GeometryType geometryType = geometry.getGeometryType(); switch (geometryType) { case GEOMETRY: throw new SFException("Unexpected Geometry Type of " + geometryType.name() + " which is abstract"); case POINT: writePoint(writer, (Point) geometry); break; case LINESTRING: writeLineString(writer, (LineString) geometry); break; case POLYGON: writePolygon(writer, (Polygon) geometry); break; case MULTIPOINT: writeMultiPoint(writer, (MultiPoint) geometry); break; case MULTILINESTRING: writeMultiLineString(writer, (MultiLineString) geometry); break; case MULTIPOLYGON: writeMultiPolygon(writer, (MultiPolygon) geometry); break; case GEOMETRYCOLLECTION: case MULTICURVE: case MULTISURFACE: writeGeometryCollection(writer, (GeometryCollection) geometry); break; case CIRCULARSTRING: writeCircularString(writer, (CircularString) geometry); break; case COMPOUNDCURVE: writeCompoundCurve(writer, (CompoundCurve) geometry); break; case CURVEPOLYGON: writeCurvePolygon(writer, (CurvePolygon) geometry); break; case CURVE: throw new SFException("Unexpected Geometry Type of " + geometryType.name() + " which is abstract"); case SURFACE: throw new SFException("Unexpected Geometry Type of " + geometryType.name() + " which is abstract"); case POLYHEDRALSURFACE: writePolyhedralSurface(writer, (PolyhedralSurface) geometry); break; case TIN: writeTIN(writer, (TIN) geometry); break; case TRIANGLE: writeTriangle(writer, (Triangle) geometry); break; default: throw new SFException("Geometry Type not supported: " + geometryType); } }public static Triangle readTriangle(ByteReader reader, boolean hasZ, boolean hasM) { Triangle triangle = new Triangle(hasZ, hasM); int numRings = reader.readInt(); for (int i = 0; i < numRings; i++) { LineString ring = readLineString(reader, hasZ, hasM); triangle.addRing(ring); } return triangle; }public static TIN readTIN(ByteReader reader, boolean hasZ, boolean hasM) { TIN tin = new TIN(hasZ, hasM); int numPolygons = reader.readInt(); for (int i = 0; i < numPolygons; i++) { Polygon polygon = readGeometry(reader, Polygon.class); tin.addPolygon(polygon); } return tin; }public static PolyhedralSurface readPolyhedralSurface(ByteReader reader, boolean hasZ, boolean hasM) { PolyhedralSurface polyhedralSurface = new PolyhedralSurface(hasZ, hasM); int numPolygons = reader.readInt(); for (int i = 0; i < numPolygons; i++) { Polygon polygon = readGeometry(reader, Polygon.class); polyhedralSurface.addPolygon(polygon); } return polyhedralSurface; }public static CurvePolygon readCurvePolygon(ByteReader reader, boolean hasZ, boolean hasM) { CurvePolygon curvePolygon = new CurvePolygon(hasZ, hasM); int numRings = reader.readInt(); for (int i = 0; i < numRings; i++) { Curve ring = readGeometry(reader, Curve.class); curvePolygon.addRing(ring); } return curvePolygon; }public static CompoundCurve readCompoundCurve(ByteReader reader, boolean hasZ, boolean hasM) { CompoundCurve compoundCurve = new CompoundCurve(hasZ, hasM); int numLineStrings = reader.readInt(); for (int i = 0; i < numLineStrings; i++) { LineString lineString = readGeometry(reader, LineString.class); compoundCurve.addLineString(lineString); } return compoundCurve; }public static CircularString readCircularString(ByteReader reader, boolean hasZ, boolean hasM) { CircularString circularString = new CircularString(hasZ, hasM); int numPoints = reader.readInt(); for (int i = 0; i < numPoints; i++) { Point point = readPoint(reader, hasZ, hasM); circularString.addPoint(point); } return circularString; }public static GeometryCollection readGeometryCollection( ByteReader reader, boolean hasZ, boolean hasM) { GeometryCollection geometryCollection = new GeometryCollection( hasZ, hasM); int numGeometries = reader.readInt(); for (int i = 0; i < numGeometries; i++) { Geometry geometry = readGeometry(reader, Geometry.class); geometryCollection.addGeometry(geometry); } return geometryCollection; }public static MultiPolygon readMultiPolygon(ByteReader reader, boolean hasZ, boolean hasM) { MultiPolygon multiPolygon = new MultiPolygon(hasZ, hasM); int numPolygons = reader.readInt(); for (int i = 0; i < numPolygons; i++) { Polygon polygon = readGeometry(reader, Polygon.class); multiPolygon.addPolygon(polygon); } return multiPolygon; }public static MultiLineString readMultiLineString(ByteReader reader, boolean hasZ, boolean hasM) { MultiLineString multiLineString = new MultiLineString(hasZ, hasM); int numLineStrings = reader.readInt(); for (int i = 0; i < numLineStrings; i++) { LineString lineString = readGeometry(reader, LineString.class); multiLineString.addLineString(lineString); } return multiLineString; }public static MultiPoint readMultiPoint(ByteReader reader, boolean hasZ, boolean hasM) { MultiPoint multiPoint = new MultiPoint(hasZ, hasM); int numPoints = reader.readInt(); for (int i = 0; i < numPoints; i++) { Point point = readGeometry(reader, Point.class); multiPoint.addPoint(point); } return multiPoint; }public static Polygon readPolygon(ByteReader reader, boolean hasZ, boolean hasM) { Polygon polygon = new Polygon(hasZ, hasM); int numRings = reader.readInt(); for (int i = 0; i < numRings; i++) { LineString ring = readLineString(reader, hasZ, hasM); polygon.addRing(ring); } return polygon; }public static LineString readLineString(ByteReader reader, boolean hasZ, boolean hasM) { LineString lineString = new LineString(hasZ, hasM); int numPoints = reader.readInt(); for (int i = 0; i < numPoints; i++) { Point point = readPoint(reader, hasZ, hasM); lineString.addPoint(point); } return lineString; }public static Point readPoint(ByteReader reader, boolean hasZ, boolean hasM) { double x = reader.readDouble(); double y = reader.readDouble(); Point point = new Point(hasZ, hasM, x, y); if (hasZ) { double z = reader.readDouble(); point.setZ(z); } if (hasM) { double m = reader.readDouble(); point.setM(m); } return point; }public static GeometryTypeInfo readGeometryType(ByteReader reader) { // Read the single byte order byte byte byteOrderValue = reader.readByte(); ByteOrder byteOrder = byteOrderValue == 0 ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; reader.setByteOrder(byteOrder); // Read the geometry type unsigned integer long unsignedGeometryTypeCode = reader.readUnsignedInt(); // Check for 2.5D geometry types boolean hasZ = false; if (unsignedGeometryTypeCode > WKB25D) { hasZ = true; unsignedGeometryTypeCode -= WKB25D; } int geometryTypeCode = (int) unsignedGeometryTypeCode; // Determine the geometry type GeometryType geometryType = GeometryCodes .getGeometryType(geometryTypeCode); // Determine if the geometry has a z (3d) or m (linear referencing // system) value if (!hasZ) { hasZ = GeometryCodes.hasZ(geometryTypeCode); } boolean hasM = GeometryCodes.hasM(geometryTypeCode); GeometryTypeInfo geometryInfo = new GeometryTypeInfo(geometryTypeCode, geometryType, hasZ, hasM); return geometryInfo; }@Override public void report(Metric metric) throws ReportingException { KairosMetricConverter kairosMetricConverter = new KairosMetricConverter(); try { kairosMetricConverter.add(metric); } catch (KairosMetricConversionException e) { throw new ReportingException(e); } this.sendMetric(kairosMetricConverter.convert()); }protected void sendMetric(MetricBuilder metricBuilder) throws ReportingException { try { HttpClient client = new HttpClient("http://" + this.server + ":" + this.port); Response response = client.pushMetrics(metricBuilder); //check if response is ok if (response.getStatusCode() / 100 != 2) { LOGGER.error("Kairos DB reported error. Status code: " + response.getStatusCode()); LOGGER.error("Error message: " + response.getErrors()); throw new ReportingException(); } else { LOGGER.debug("Kairos DB returned OK. Status code: " + response.getStatusCode()); } client.shutdown(); } catch (MalformedURLException | URISyntaxException e) { throw new ConfigurationException(e); } catch (IOException e) { LOGGER.error("Could not request KairosDB.", e); throw new ReportingException(e); } }@Override public Map getServerConfig() { final Map config = new HashMap(); config.put(LDAPServer.ROOT, rootDn); if (objectClasses != null) { config.put(LDAPServer.OBJECT_CLASSES, objectClasses.split(",")); } config.put(LDAPServer.WORK_DIR, new File(outputDirectory, serverType)); if (ldifFile != null) { config.put(LDAPServer.LDIF_FILE, ldifFile); } config.put(LDAPServer.LDAP_PORT, ldapPort); config.put(LDAPServer.AUTH_DN, authDn); config.put(LDAPServer.PASSWD, passwd); return config; }@Override public String getServerType() { if (serverType.startsWith("dependency-")) { return serverType.substring(11); } if (serverType.startsWith("gav-")) { int index = serverType.indexOf("-", 4); if (index > 0) { return serverType.substring(4, index); } } return serverType; }public void printEntry(final Entry entry) throws IOException { final ByteStringBuffer buffer = new ByteStringBuffer(); buffer.append("\t\t"); buffer.append(eol); final String[] values = entry.getAttributeValues("objectclass"); if (values != null) { buffer.append("\t\t\t"); buffer.append(eol); for (final String value : values) { buffer.append("\t\t\t\t"); buffer.append(value); buffer.append(""); buffer.append(eol); } buffer.append("\t\t\t"); buffer.append(eol); } for (final Attribute attribute : entry.getAttributes()) { final String name = attribute.getName(); if (!name.equals("objectclass")) { buffer.append("\t\t\t"); buffer.append(eol); for (final String value : attribute.getValues()) { buffer.append("\t\t\t\t"); buffer.append(value); buffer.append(""); buffer.append(eol); } buffer.append("\t\t\t"); buffer.append(eol); } } buffer.append("\t\t"); buffer.append(eol); ldifOutputStream.write(buffer.toByteArray()); }@Override public void stop(final Logger logger) { logger.logInfo("Stopping OpenDJ server"); if (listener != null) { listener.close(); } logger.logInfo("Stopped OpenDJ server"); }@Override public void start(final Logger logger) { try { logger.logInfo("Starting OpenDJ server"); final MemoryBackend backend; if (getLdifFile() == null) { backend = new MemoryBackend(); } else { final InputStream inputStream = new FileInputStream(getLdifFile()); final LDIFEntryReader reader = new LDIFEntryReader(inputStream); backend = new MemoryBackend(reader); } final ServerConnectionFactory connectionHandler = Connections.newServerConnectionFactory(backend); final LDAPListenerOptions options = new LDAPListenerOptions().setBacklog(4096); listener = new LDAPListener("localhost", getServerPort(), connectionHandler, options); logger.logInfo("Started OpenDJ server"); } catch (final IOException e) { logger.logError("Error starting OpenDJ server", e); } }private void createRoot(final Partition partition) throws Exception { try { service.getAdminSession().lookup(partition.getSuffixDn()); } catch (final LdapNameNotFoundException e) { final LdapDN dn = new LdapDN(getRoot()); final String dc = getRoot().substring(3, getRoot().indexOf(',')); final ServerEntry entry = service.newEntry(dn); entry.add("objectClass", "top", "domain", "extensibleObject"); entry.add("dc", dc); service.getAdminSession().add(entry); } }@Override public void stop(final Logger logger) { try { logger.logInfo("Stopping ApacheDS server"); server.stop(); service.shutdown(); logger.logInfo("Stopped ApacheDS server"); } catch (final Exception e) { logger.logError("Error stopping ApacheDS server", e); } }@Override public void start(final Logger logger) { try { logger.logInfo("Starting ApacheDS server"); service = new DefaultDirectoryService(); final List list = new ArrayList(); list.add(new NormalizationInterceptor()); list.add(new AuthenticationInterceptor()); list.add(new ReferralInterceptor()); // list.add( new AciAuthorizationInterceptor() ); // list.add( new DefaultAuthorizationInterceptor() ); list.add(new ExceptionInterceptor()); // list.add( new ChangeLogInterceptor() ); list.add(new OperationalAttributeInterceptor()); // list.add( new SchemaInterceptor() ); list.add(new SubentryInterceptor()); // list.add( new CollectiveAttributeInterceptor() ); // list.add( new EventInterceptor() ); // list.add( new TriggerInterceptor() ); // list.add( new JournalInterceptor() ); service.setInterceptors(list); service.setWorkingDirectory(getWorkingDirectory()); final JdbmPartition partition = new JdbmPartition(); partition.setId("rootPartition"); partition.setSuffix(getRoot()); service.addPartition(partition); service.setExitVmOnShutdown(false); service.setShutdownHookEnabled(false); service.getChangeLog().setEnabled(false); service.setDenormalizeOpAttrsEnabled(true); server = new LdapServer(); server.setDirectoryService(service); server.setTransports(new TcpTransport(getServerPort())); service.startup(); server.start(); createRoot(partition); loadLdifFile(); logger.logInfo("Started ApacheDS server"); } catch (final Exception e) { logger.logError("Error starting ApacheDS server e"); } }public void execute() throws MojoExecutionException { if (!isSkip()){ final LDAPConnection connection = connect(); try { for (final Source source : sources) { try { getLog().info("Processing input source: " + source); final FormatHandler handler = getFormatHandler(source); if (handler == null) { getLog().warn("No handler for input source: " + source); } else { final InputStream inputStream = source.open(); if (inputStream == null) { if (!this.continueOnError) { throw new MojoExecutionException("Cannot open source for reading: " + source); } else { getLog().warn("Skipping source that could not be opened for reading: " + source); } } else { try { handler.load(connection, source.open(), continueOnError, this); } finally { inputStream.close(); } } } } catch (final IOException e) { if (!this.continueOnError) { throw new MojoExecutionException("Error closing input source: " + source, e); } else { this.getLog().warn("Ignoring error closing input source: " + source, e); } } } } finally { connection.close(); } } }public LDIFChangeRecord nextRecord() { if (entryIterator.hasNext()) { try { final Node entryNode = entryIterator.next(); final String dn = entryNode.valueOf("@dn"); final List attributes = new ArrayList(); final List objectClassList = (List) objectClassXPath.selectNodes(entryNode); final String[] objectClasses = new String[objectClassList.size()]; for (int j = 0; j < objectClasses.length; ++j) { objectClasses[j] = objectClassList.get(j).getStringValue(); } attributes.add(new Attribute("objectclass", objectClasses)); for (final Node attributeNode : (List) attrXPath.selectNodes(entryNode)) { final String attributeName = attributeNode.valueOf("@name"); final List attributeValueNodes = (List) attrValueXPath.selectNodes(attributeNode); switch (attributeValueNodes.size()) { case 0: break; case 1: { final String attributeValue = attributeValueNodes.get(0).getStringValue(); attributes.add(new Attribute(attributeName, attributeValue)); break; } default: { final String[] attributeValues = new String[attributeValueNodes.size()]; for (int j = 0; j < attributeValueNodes.size(); ++j) { attributeValues[j] = attributeValueNodes.get(j).getStringValue(); } attributes.add(new Attribute(attributeName, attributeValues)); break; } } } return new LDIFAddChangeRecord(dn, attributes); } catch (final JaxenException e) { return null; } } else { return null; } }@Override public void stop(final Logger logger) { logger.logInfo("Stopping UnboundID server"); server.shutDown(true); logger.logInfo("Stopped UnboundID server"); }@Override public void start(final Logger logger) { try { logger.logInfo("Starting UnboundID server"); final InMemoryListenerConfig listenerConfig = InMemoryListenerConfig.createLDAPConfig("default", getServerPort()); final InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(new DN(getRoot())); config.setListenerConfigs(listenerConfig); if (getAuthDn() != null) { config.addAdditionalBindCredentials(getAuthDn(), getPasswd()); } server = new InMemoryDirectoryServer(config); String[] objectClasses = getObjectClasses(); if (objectClasses == null) { objectClasses = DEFAULT_ROOT_OBJECT_CLASSES; } server.add(new Entry(getRoot(), new Attribute("objectclass", objectClasses))); if (getLdifFile() != null) { final InputStream in = new FileInputStream(getLdifFile()); try { final LDIFReader reader = new LDIFReader(in); server.importFromLDIF(false, reader); } finally { in.close(); } } server.startListening(); logger.logInfo("Started UnboundID server"); } catch (final LDAPException e) { e.printStackTrace(); logger.logError("Could not launch embedded UnboundID directory server", e); } catch (final IOException e) { e.printStackTrace(); logger.logError("Could not launch embedded UnboundID directory server", e); } }@Override public void configure(final String name, final Object value, final Logger logger) { if (ROOT.equals(name)) { if (value instanceof String) { root = (String) value; logger.logInfo("Configured root DN for directory server: " + root); } } else if (OBJECT_CLASSES.equals(name)) { if (value instanceof String[]) { objectClasses = (String[]) value; logger.logInfo("Configured object classes for root DN: " + objectClasses); } } else if (AUTH_DN.equals(name)) { if (value instanceof String) { authDn = (String) value; logger.logInfo("Configured admin identity for directory server: " + authDn); } } else if (PASSWD.equals(name)) { if (value instanceof String) { passwd = (String) value; logger.logInfo("Configured admin credentials for directory server: " + passwd); } } else if (WORK_DIR.equals(name)) { if (value instanceof File) { workingDirectory = (File) value; logger.logInfo("Configured working directory for directory server: " + workingDirectory); } } else if (LDIF_FILE.equals(name)) { if (value instanceof File) { ldifFile = (File) value; logger.logInfo("Configured LDIF seed data source for directory server: " + ldifFile); } } else if (LDAP_PORT.equals(name)) { if (value instanceof Integer) { serverPort = (Integer) value; logger.logInfo("Configured TCP port for directory server: " + serverPort); } } }@Override protected FormatReader openReader(final InputStream inputStream, final FormatLogger logger) { try { return new DSMLFormatReader(inputStream); } catch (final DocumentException e) { logger.logError("Error parsing DSML file", e); } catch (final JaxenException e) { logger.logError("Error processing DSML file", e); } catch (final IOException e) { logger.logError("Error reading DSML file", e); } return null; }@Override protected FormatWriter createWriter(final OutputStream outputStream, final FormatLogger logger) { try { return new DSMLFormatWriter(outputStream); } catch (final IOException e) { logger.logError("Could not create and intialise the DSML writer", e); } return null; }private String getServerType(final PlexusConfiguration configuration) { final Pattern pattern = Pattern.compile("\\$\\{[A-Za-z0-9\\._]+\\}"); for (final PlexusConfiguration cfg : configuration.getChildren()) { if (cfg.getName().equals(SERVER_TYPE_ATTRIBUTE)) { if (pattern.matcher(cfg.getValue()).matches()) { return DEFAULT_SERVER_TYPE_VALUE; } else { return cfg.getValue(); } } } return DEFAULT_SERVER_TYPE_VALUE; }private Artifact getServerArtifact(final String serverType) throws ComponentConfigurationException { if (serverType.startsWith("gav-")) { int index = serverType.indexOf("-", 4); if (index > 0) { String[] gav = serverType.substring(index + 1).split(":"); if (gav.length == 3) { return repositorySystem.createArtifact( gav[0], gav[1], gav[2], "runtime", "jar" ); } } throw new ComponentConfigurationException("Invalid server type: " + serverType); } else { return repositorySystem.createArtifact( DEFAULT_GROUP_ID, MessageFormat.format(DEFAULT_ARTIFACT_ID_FORMAT, serverType), getClass().getPackage().getImplementationVersion(), "runtime", "jar"); } }private Collection getServerDependencies(final String serverType, final ExpressionEvaluator expressionEvaluator) throws ComponentConfigurationException { try { final MavenProject project = (MavenProject) expressionEvaluator.evaluate("${project}"); final String localRepo = (String) expressionEvaluator.evaluate("${settings.localRepository}"); final ArtifactRepository localRepository = repositorySystem.createLocalRepository(new File(localRepo)); final RepositoryRequest repositoryRequest = new DefaultRepositoryRequest(); repositoryRequest.setRemoteRepositories(project.getRemoteArtifactRepositories()); repositoryRequest.setLocalRepository(localRepository); final ArtifactResolutionRequest request = new ArtifactResolutionRequest(repositoryRequest); request.setArtifact(getServerArtifact(serverType)); request.setResolveTransitively(true); final ArtifactResolutionResult result = repositorySystem.resolve(request); if (result.isSuccess()) { return result.getArtifacts(); } boolean first = true; final StringBuilder builder = new StringBuilder("Cannot resolve dependencies: ["); for (final Artifact artifact : result.getMissingArtifacts()) { if (!first) { builder.append(','); } else { first = false; } builder.append(artifact.getGroupId()); builder.append(':'); builder.append(artifact.getArtifactId()); builder.append(':'); builder.append(artifact.getVersion()); } builder.append("]"); throw new ComponentConfigurationException(builder.toString()); } catch (final ExpressionEvaluationException e) { throw new ComponentConfigurationException("Error evaluating expression", e); } catch (final InvalidRepositoryException e) { throw new ComponentConfigurationException("Error resolving local repository", e); } }private List buildURLs(final Collection classpathElements) throws ComponentConfigurationException { final List urls = new ArrayList(classpathElements.size()); for (final Artifact classpathElement : classpathElements) { try { final URL url = classpathElement.getFile().toURI().toURL(); urls.add(url); } catch (final MalformedURLException e) { throw new ComponentConfigurationException("Unable to access project dependency: " + classpathElement, e); } } return urls; }private void addServerDependenciesToClassRealm(final String serverType, final ExpressionEvaluator expressionEvaluator, final ClassRealm containerRealm) throws ComponentConfigurationException { final Collection classpathElements = getServerDependencies(serverType, expressionEvaluator); if (classpathElements != null) { for (final URL url : buildURLs(classpathElements)) { containerRealm.addURL(url); } } }@Override public void configureComponent(final Object component, final PlexusConfiguration configuration, final ExpressionEvaluator expressionEvaluator, final ClassRealm containerRealm, final ConfigurationListener listener) throws ComponentConfigurationException { final String serverType = getServerType(configuration); if (!serverType.startsWith("dependency-")) { addServerDependenciesToClassRealm(serverType, expressionEvaluator, containerRealm); } converterLookup.registerConverter(new ClassRealmConverter(containerRealm)); final ObjectWithFieldsConverter converter = new ObjectWithFieldsConverter(); converter.processConfiguration(converterLookup, component, containerRealm, configuration, expressionEvaluator, listener); }public final void execute() throws MojoExecutionException { final File outputFile = new File(outputDirectory, filename); if (outputDirectory.exists() || outputDirectory.mkdirs()) { try { final OutputStream outputStream = new FileOutputStream(outputFile); try { final LDAPConnection connection = connect(); try { final FormatHandler handler = getFormatHandler(); if (handler != null) { handler.dump(connection, searchBase, searchFilter, outputStream, this); } } finally { connection.close(); } } finally { try { outputStream.close(); } catch (final IOException e) { } } } catch (final FileNotFoundException e) { } } }public final void dump(final LDAPInterface connection, final String base, final String filter, final OutputStream outputStream, final FormatLogger logger) { final FormatWriter ldapWriter = createWriter(outputStream, logger); if (ldapWriter == null) { logger.logError("Error creating writer for output stream"); } else { try { try { final SearchRequest request = new SearchRequest(base, SearchScope.SUB, Filter.create(filter)); final SearchResult result = connection.search(request); if (result.getResultCode() == ResultCode.SUCCESS) { final List entries = result.getSearchEntries(); if (entries != null) { for (final SearchResultEntry entry : entries) { ldapWriter.printEntry(entry); } } else { logger.logInfo("Search did not return any directory entries"); } } else { logger.logError("Search operation failed"); } } catch (final LDAPException e) { logger.logError("Error searching the LDAP directory", e); } finally { ldapWriter.close(); } } catch (final IOException e) { logger.logError("Error writing directory entry to the output stream", e); } } }public final void load(final LDAPInterface connection, final InputStream inputStream, final boolean ignoreErrors, final FormatLogger logger) { final FormatReader reader = openReader(inputStream, logger); if (reader != null) { try { boolean keepReading = true; do { try { final LDIFChangeRecord record = reader.nextRecord(); if (record == null) { keepReading = false; } else { record.processChange(connection); } } catch (final LDIFException e) { if (!ignoreErrors || !e.mayContinueReading()) { logger.logError("Error parsing directory entry read from the input stream", e); keepReading = false; } } catch (final LDAPException e) { if (!ignoreErrors) { logger.logError("Error loading directory entry into the LDAP directory server", e); keepReading = false; } } } while (keepReading); } catch (final IOException e) { logger.logError("I/O error reading directory entry from input stream", e); } finally { try { reader.close(); } catch (final IOException e) { logger.logError("I/O error closing the input stream reader", e); } } } }public void printEntry(final Entry entry) throws IOException { if (entry != null) { final ByteStringBuffer buffer = new ByteStringBuffer(); entry.toLDIF(buffer, 77); if (!first) { ldifOutputStream.write(eol); } else { first = false; } ldifOutputStream.write(buffer.toByteArray()); } }@Override public boolean addTransaction(SIPTransaction transaction) { if(transaction instanceof ServerTransaction) { isLatestTxServer = true; } else { isLatestTxServer = false; } return super.addTransaction(transaction); }�s�<=y*�������EC�O Y s F V��$���{c��;M$L& *p/1�1�5�9<@6DTG�J=M�P+Wo_�ac�c�d�fNhqBr�sQt�x�y�}�O���ї����6�B�����6�Ǿ"���I�_�$�,�A�;�/���������������Q�.�Q���e�X�����j�0���n! � ����"�#�%�/~2�9�@B�CcH�KBV�\la.f�g>r�{�|x}z~~�߁��;�C���И���0�ڡ�����үñ8�d�k�W���%���������'���������T���$�!�*�H4B �  $q&^"d#�$�%�(t*�+�,..1/64 7;�>�?�E�M�NTU�VX[ ]�`�b�hKn�vy�~�:�H�͏S��H�������[�X�����_���������q���y����8���|���5�����L�o��������y�)������R�D���g�X������a�2����S<F�{� HU�F@w+�q "�#r'C()*�,l.x14�4�6D7h8�8?;�>�E'I�K6MEN�O�P�Q=S'U:V(^�^�c�d�e-f�g�h�io�o�s�t�u�v�w�x�y{zC{�|�B�����W�ֈ��G���b�r��c�+���ߚ�Μ��s�!�6�ˢ���Ҭ��O�'�Դj�3��`�q�������D�����o�8������� �w�>���x�F������Y�D������� ��������k�C���s�W������� � � �/�k�������r��1�����public MemorySize add(MemorySize other) { if(other == null) throw new NullPointerException(); if(getSizeUnit() == other.getSizeUnit()) return new MemorySize(getSize() + other.getSize(), getSizeUnit()); return new MemorySize(getSizeInBytes() + other.getSizeInBytes(), SizeUnit.BYTE); }public MemorySize truncate(SizeUnit sizeUnit) { if (getSizeUnit() == sizeUnit) return this; long sizeInBytes = getSizeInBytes(); if (sizeInBytes >= sizeUnit.getBytesCount()) { return new MemorySize(sizeInBytes / sizeUnit.getBytesCount(), sizeUnit); } else { return ZERO_SIZES.get(sizeUnit); } }@Override public int compareTo(Timespan timespan) { if(timespan.getTimeUnit() == getTimeUnit()) return LangUtils.compare(getDuration(), timespan.getDuration()); else return LangUtils.compare(getDurationInMilliseconds(), timespan.getDurationInMilliseconds()); }public String getAsString(EnumSet timeUnits) { StringBuilder sb = new StringBuilder(); EnumMap canonicalTimespans = getAsTimespans(timeUnits); for(TimeUnit timeUnit : TIME_UNIT_ORDER) { if(canonicalTimespans.containsKey(timeUnit)) { long duration = canonicalTimespans.get(timeUnit).getDuration(); if(duration > 0) { sb.append(duration).append(timeUnit.getDisplayChar()); } } } if(sb.length() == 0) { sb.append(0); if(timeUnits.contains(getTimeUnit())) sb.append(getTimeUnit().getDisplayChar()); } return sb.toString(); }public static Properties loadProperties(Reader reader) throws IOException { if(reader == null) return null; Properties properties = new Properties(); properties.load(reader); return properties; }public static Properties loadProperties(File file) throws IOException { if(file == null) return null; FileReader reader = new FileReader(file); try { return loadProperties(reader); } finally { reader.close(); } }public static > EnumSet toEnumSet(Class clazz, T... ts) { if(ts == null) return null; EnumSet res = EnumSet.noneOf(clazz); for(T t : ts) { res.add(t); } return res; }public static T[] reverse(T[] array) { if(array == null) return array; int s = 0; int e = array.length - 1; while(s < e) { // swap index e and s T tmp = array[e]; array[e] = array[s]; array[s] = tmp; s++; e--; } return array; }public static LeafResource create(Resource resource) { try { // if we can access the file then there is no reason to decorate it... resource.getFile(); return new LeafResourceImpl(resource); } catch(IOException e) { return new LocalCacheLeafResource(resource); } }public static String decodeString(Codec codec, String s) throws Codec.CannotDecodeException { try { return new String(codec.decode(s), "UTF-8"); } catch(UnsupportedEncodingException ex) { // shouldn't happen throw new RuntimeException(ex); } }public static String encodeString(OneWayCodec codec, String s) { try { return codec.encode(s.getBytes("UTF-8")); } catch(UnsupportedEncodingException ex) { // shouldn't happen throw new RuntimeException(ex); } }public RAMDirectory mkdir(String name) throws IOException { RAMEntry entry = getEntry(name); if(entry instanceof RAMDirectory) { RAMDirectory ramDirectory = (RAMDirectory) entry; return ramDirectory; } else { if(entry == null) { RAMDirectory directory = new RAMDirectory(_clock, name); return (RAMDirectory) add(directory); } else { throw new IOException("File exists: " + name); } } }public RAMEntry add(RAMEntry entry) { touch(); _directoryContent.put(entry.name(), entry); return entry; }public static long toEndTime(Clock clock, Object timeout) { Timespan t = toTimespan(timeout); if(t == null) return 0; if(clock == null) clock = SystemClock.INSTANCE; if(t.getDurationInMilliseconds() == 0) return 0; return t.futureTimeMillis(clock); }public static String indentBlock(String block, Indent indent) { StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new StringReader(block)); String line; try { while((line = br.readLine()) != null) sb.append(indent).append(line).append('\n'); } catch(IOException ex) { // on a String ? I doubt... } return sb.toString(); }@Override public void addTag(String tagName, int value, Map attributes) { addTag(tagName, String.valueOf(value), attributes); }@Override public void addTag(String tagName, int value, String attrName, String attrValue) { addTag(tagName, String.valueOf(value), attrName, attrValue); }public String getElapsedTime() { StringBuilder sb = new StringBuilder("Time: "); sb.append(this.tick()); sb.append(" ms"); return sb.toString(); }public long tick() { long tick = _clock.currentTimeMillis(); long diff = tick - _tick; _tick = tick; return diff; }public static ExternalCommand execute(File workingDirectory, String command, String... args) throws IOException, InterruptedException { try { return executeWithTimeout(workingDirectory, command, 0, args); } catch (TimeoutException e) { // Can't happen! throw new IllegalStateException(MODULE + ".execute: Unexpected timeout occurred!"); } }public static ExternalCommand start(String... commands) throws IOException { ExternalCommand ec = new ExternalCommand(new ProcessBuilder(commands)); ec.start(); return ec; }public static ExternalCommand create(List commands) { ExternalCommand ec = new ExternalCommand(new ProcessBuilder(commands)); return ec; }public void start() throws IOException { _process = _processBuilder.start(); _out = new InputReader(new BufferedInputStream(_process.getInputStream())); _err = new InputReader(new BufferedInputStream(_process.getErrorStream())); _out.start(); _err.start(); }public static Resource create(File file) { try { String path = file.getCanonicalPath(); if(file.isDirectory()) path = PathUtils.addTrailingSlash(path); return create(new File("/"), path); } catch(IOException e) { throw new IllegalArgumentException("invalid file " + file, e); } }@Override public Resource chroot(String relativePath) { return _resourceProvider.chroot((InternalResource) createRelative(relativePath)); }@Override public InternalResource[] list(InternalResource resource, final ResourceFilter filter) throws IOException { final List resources = new ArrayList(); String path = PathUtils.addTrailingSlash(resource.getPath()); if(doList(path, new ResourceFilter() { @Override public boolean accept(Resource resource) { boolean res = filter.accept(resource); if(res) resources.add(resource); return res; } })) { return resources.toArray(new InternalResource[resources.size()]); } else return null; }@Override public InternalResource chroot(InternalResource resource) { String path = resource.getPath(); // when it is a directory, we simply use the provided resource if(resource.isDirectory()) { return doCreateResourceProvider(path).getRootResource(); } else { // when not a directory, we do a chroot to the parent and then we return the resource // that points to it return (InternalResource) resource.chroot("..").createRelative(resource.getFilename()); } }public static ResourceInfo extractInfo(URL url) throws IOException { URLConnection urlConnection = url.openConnection(); urlConnection.setDoInput(true); urlConnection.setDoOutput(false); urlConnection.setUseCaches(false); urlConnection.connect(); InputStream is = urlConnection.getInputStream(); try { return new StaticInfo(urlConnection.getContentLength(), urlConnection.getLastModified()); } finally { is.close(); } }private void addAttributes(Map attributes) { if(attributes == null) return; Iterator iter = attributes.keySet().iterator(); while(iter.hasNext()) { String attrName = (String) iter.next(); Object attrValue = attributes.get(attrName); if(attrValue != null) addAttribute(attrName, attrValue.toString()); } }private void addAttribute(String attrName, String attrValue) { if(attrName == null) return; _xml.append(' '); _xml.append(attrName).append("=\""); _xml.append(XMLUtils.xmlEncode(attrValue)).append('"'); }@Override public void addEmptyTag(String tagName, Map attributes) { _xml.append('<').append(tagName); addAttributes(attributes); _xml.append(" />"); }@Override public void waitForShutdown(Object timeout) throws InterruptedException, IllegalStateException, TimeoutException { if(!_shutdown) throw new IllegalStateException("call shutdown first"); pendingCallsCount.waitForCounter(timeout); }public static String removeTrailingSlash(String path) { if(path.endsWith("/")) return path.substring(0, path.length() - 1); else return path; }public static String getStackTrace(Throwable th) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); th.printStackTrace(pw); return sw.toString(); }public static boolean convertToBoolean(Object o) { if(o == null) return false; if(o instanceof Boolean) { return (Boolean) o; } return convertToBoolean(o.toString()); }public static Object createShutdownProxy(Object o, Class[] interfaces, Shutdown shutdown) { if(interfaces == null) interfaces = ReflectUtils.extractAllInterfaces(o); return Proxy.newProxyInstance(o.getClass().getClassLoader(), interfaces, new ShutdownProxy(o, shutdown)); }@Override public Object invoke(Object o, Method method, Object[] objects) throws Throwable { // throws ShutdownRequestedException when in shutdown mode _shutdown.startCall(); try { return method.invoke(_object, objects); } catch(InvocationTargetException e) { Throwable th = e.getTargetException(); try { throw th; } catch(Exception ex) { throw ex; } catch(Throwable throwable) { log.error(method.toString(), throwable); throw throwable; } } finally { _shutdown.endCall(); } }public String[] replaceParameter(String name, String value) { Map map = getMap(); String[] v = map.put(name, new String[] { value }); rebuildQuery(); return v; }private void rebuildQuery() { Map map = getMap(); // reset query instance and re-populate it again _query.setLength(0); for (String key : map.keySet()) { String[] parameters = map.get(key); for (String param : parameters) { addQueryParameter(key, param); } } }public void addQuery(Query query) { if(query == null) return; try { if(!query.getEncoding().equals(getEncoding())) throw new RuntimeException("TODO"); addQuery(query.getQuery(), false); } catch(URISyntaxException e) { // shouldn't happen since a query is already properly formatted throw new RuntimeException(e); } }private void validateQuery(String query) throws URISyntaxException { if(query.length() == 0) return; Iterator iter = SS.splitToIterator(query); while(iter.hasNext()) { String s = iter.next(); if(s.length() > 0) { int idx = s.indexOf('='); if(idx == -1) throw new URISyntaxException(query, "missing equal sign in " + s); if(s.lastIndexOf('=') != idx) throw new URISyntaxException(query, "extra equal sign in " + s); } } }public void addQuery(URI uri) { try { addQuery(uri.getRawQuery(), false); } catch(URISyntaxException e) { // should not happen! throw new RuntimeException(e); } }public void addIndexedParameter(String name, int value, int index) { addParameter(getIndexedParamName(name, index), value); }public void addParameters(Map parameters) { for(Map.Entry entry : parameters.entrySet()) { addParameters(entry.getKey(), entry.getValue()); } }private void addQueryParameter(String name, String value) { if(_query.length() > 0) _query.append('&'); _query.append(encode(name)); _query.append('='); _query.append(encode(value)); }@Override public String getParameter(String name) { String[] params = getParameterValues(name); if(params == null) return null; return params[0]; }public static URL addQueryParameter(URL url, String name, String value) { URLBuilder ub = createFromURL(url); ub.addQueryParameter(name, value); return ub; }public static URLBuilder createFromPath(String path) { URLBuilder res = new URLBuilder(); res.setPath(path); return res; }public void reset() { _scheme = null; _userInfo = null; _host = null; _port = -1; _path = null; _query = new QueryBuilder(); _fragment = null; _escapeFragment = true; }private static OneWayMessageDigestCodec createWellKnownInstance(String algorithm, String password, OneWayCodec codec) { try { return new OneWayMessageDigestCodec(algorithm, password, codec); } catch(NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch(CloneNotSupportedException e) { throw new RuntimeException(e); } }@SuppressWarnings("unchecked") public static String computeSignature(Method m) { StringBuilder sb = new StringBuilder(); sb.append(m.getName()).append('('); Class[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { if(i > 0) sb.append(','); Class parameterType = parameterTypes[i]; sb.append(parameterType.getName()); } sb.append(')'); return sb.toString(); }public static Class forName(Class clazz, ClassLoader classLoader) throws ClassNotFoundException, LinkageError { if(clazz == null) return null; if(classLoader == null) { classLoader = getDefaultClassLoader(); } if(clazz.getClassLoader() == null || clazz.getClassLoader().equals(classLoader)) return clazz; else return forName(clazz.getName(), classLoader); }@SuppressWarnings("unchecked") public static Object getProxiedObject(Object proxy) { if(Proxy.isProxyClass(proxy.getClass())) { InvocationHandler invocationHandler = Proxy.getInvocationHandler(proxy); if(invocationHandler instanceof ObjectProxy) { ObjectProxy objectProxy = (ObjectProxy) invocationHandler; // recursively fetch the proxy return getProxiedObject(objectProxy.getProxiedObject()); } else return proxy; } else return proxy; }public static File createTempDirectory(String namespace, String name) throws IOException { File dir = File.createTempFile(namespace, ""); if(dir.exists()) deleteFile(dir); createNewDirectory(dir); File tempDir = new File(dir, name); createNewDirectory(tempDir); return tempDir.getCanonicalFile(); }public static boolean deleteFile(File file) throws IOException { if(!file.exists()) return false; File[] files = file.listFiles(); if(files != null) { for(int i = 0; i < files.length; i++) { File childFile = files[i]; if(childFile.equals(file)) continue; if(childFile.isDirectory()) deleteFile(childFile); else childFile.delete(); } } return file.delete(); }@Override public void addOpeningTag(String tagName, Map attributes) { _xml.addXML(_indent.toString()); _xml.addOpeningTag(tagName, attributes); _xml.addXML("\n"); _indent.inc(); }@Override public void addEmptyTag(String tagName) { _xml.addXML(_indent.toString()); _xml.addEmptyTag(tagName); _xml.addXML("\n"); }@Override public void addClosingTag(String tagName) { _indent.dec(); _xml.addXML(_indent.toString()); _xml.addClosingTag(tagName); _xml.addXML("\n"); }public boolean confirmRequest(String targetUID, String password) throws GeneralSecurityException, WrongPassphraseException { SQLiteDatabase db = getWritableDatabase(); String table = RelationshipEntry.TABLE_PERSON_AUTH; String[] columns = { RelationshipEntry.COLUMN_TKN, RelationshipEntry.COLUMN_REQUEST_STATUS, RelationshipEntry.COLUMN_PASSWORD }; String selection = RelationshipEntry.COLUMN_USER_UUID + " = ? "; String[] selectionArgs = { targetUID }; String groupBy = null; String having = null; String orderBy = null; String limit = null; Cursor c = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); if (c.moveToNext()) { String token = c.getString(c.getColumnIndex(RelationshipEntry.COLUMN_TKN)); String decryptedTkn = TokenCipher.decryptToken(token, password); if (decryptedTkn != null) { return commitConfirmation(targetUID, password, decryptedTkn); } else { return false; } } return false; }public int entryExistsFor(String userUID) { String selection = RelationshipEntry.COLUMN_USER_UUID + " = ?"; String[] selectionArgs = { userUID }; String[] columns = { RelationshipEntry.COLUMN_REQUEST_STATUS }; SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(RelationshipEntry.TABLE_PERSON_AUTH, columns, selection, selectionArgs, /* groupBy */null, /* having */null, /* orderBy */ null); if (cursor.moveToNext()) { return cursor.getInt(cursor.getColumnIndex(RelationshipEntry.COLUMN_REQUEST_STATUS)); } cursor.close(); return REQUEST_NOT_EXIST; }public boolean createEntryForReceivedRequest(ContactRequest fr) { String user_uuid = fr.getUserIdentifier(); String receive_token = fr.getAccessToken(); int request_status = REQUEST_PENDING; if (insertNewEntry(user_uuid, receive_token, request_status)) { return true; } return false; }public String createEntryForSentRequest(String targetUid, String password) throws GeneralSecurityException { // TODO Add it back later // if (entryExistsFor(targetUid) != REQUEST_NOT_EXIST) { // return ; // } String user_uuid = targetUid; String token = new IdentifierGenerator().generateAccessToken(); int request_status = REQUEST_ACCEPTED; insertNewEntry(user_uuid, token, request_status); return TokenCipher.encryptToken(token, password); }public PersonAuth getPersonAuthFrom(String receivedTkn) { if (receivedTkn.equals("")) { return PersonAuth.getPublicAuth(); } String selection = RelationshipEntry.COLUMN_TKN + " = ? AND " + RelationshipEntry.COLUMN_REQUEST_STATUS + " = ?"; String[] selectionArgs = { receivedTkn, Integer.toString(REQUEST_ACCEPTED) }; String[] columns = { RelationshipEntry.COLUMN_USER_UUID }; SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(RelationshipEntry.TABLE_PERSON_AUTH, columns, selection, selectionArgs, /* groupBy */null, /* having */null, /* orderBy */ null); PersonAuth auth; if (cursor.moveToNext()) { String uniqueIdentifier = cursor.getString(cursor.getColumnIndex(RelationshipEntry.COLUMN_USER_UUID)); auth = generatePermissionFor(uniqueIdentifier, db); } else { auth = PersonAuth.getPublicAuth(); } cursor.close(); return auth; }public static E onMainThread(Class callbackInterface, final E callback) { Utils.notNull(callbackInterface, "callbackInterface must not be null"); Utils.notNull(callback, "callback must not be null"); final Handler handler = new Handler(Looper.getMainLooper()); final String tag = callback.getClass().getSimpleName(); Object proxy = Proxy.newProxyInstance(callbackInterface.getClassLoader(), new Class[] { callbackInterface }, new InvocationHandler() { @Override public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { handler.post(new Runnable() { @Override public void run() { try { method.invoke(callback, args); } catch (IllegalAccessException e) { Log.e(tag, "Error executing method " + method.getName() + " on main thread.", e); } catch (IllegalArgumentException e) { Log.e(tag, "Error executing method " + method.getName() + " on main thread.", e); } catch (InvocationTargetException e) { Log.e(tag, "Error executing method " + method.getName() + " on main thread.", e); } } }); return null; } }); return callbackInterface.cast(proxy); }public static NodeList getNodeList(final String xml, final String xpathExpression) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException { final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); final DocumentBuilder builder = domFactory.newDocumentBuilder(); final Document doc = builder.parse(xml); final XPath xpath = XPathFactory.newInstance().newXPath(); final XPathExpression expr = xpath.compile(xpathExpression); final Object result = expr.evaluate(doc, XPathConstants.NODESET); final NodeList nodes = (NodeList)result; return nodes; }public BaseInfo getBaseInfo(SPFPersona persona) { ProfileFieldContainer pfc = getProfileFieldBulk(persona, ProfileField.IDENTIFIER, ProfileField.DISPLAY_NAME); return new BaseInfo(pfc.getFieldValue(ProfileField.IDENTIFIER), pfc.getFieldValue(ProfileField.DISPLAY_NAME)); }public ProfileFieldContainer getProfileFieldBulk(PersonAuth auth, SPFPersona persona, String[] fields) { return mProfileTable.getProfileFieldBulk(persona, fields, auth); }public SPFPerson lookup(String identifier) { boolean isReachable = mSearchInterface.lookup(identifier); if (isReachable) { return new SPFPerson(identifier); } else { return null; } }public void stopAllSearches() { mTagToId.clear(); String[] queryIds = mCallbacks.keySet().toArray(new String[]{}); mCallbacks.clear(); for (String queryId : queryIds) { mSearchInterface.stopSearch(queryId); } }public void stopSearch(int tag) { String queryId = mTagToId.get(tag); mTagToId.delete(tag); if (queryId != null && mCallbacks.remove(queryId) != null) { mSearchInterface.stopSearch(queryId); } }public boolean isModified() { for (String key : mStatus.keySet()) { FieldStatus status = getStatus(key); if (status == FieldStatus.DELETED || status == FieldStatus.MODIFIED) { return true; } } return false; }public E getFieldValue(ProfileField field) { if (field == null) { throw new NullPointerException(); } String val = mFields.getString(field.getIdentifier()); return val == null ? null : ProfileFieldConverter.forField(field).fromStorageString(val); }public void connect() { if (!mMiddleware.isConnected()) { mMiddleware.connect(); } if (!mNotificationManager.isRunning()) { mNotificationManager.start(); } if (mAdvertiseManager.isAdvertisingEnabled()) { mMiddleware.registerAdvertisement(mAdvertiseManager.generateAdvProfile().toJSON(), 10000); } }public void addClientIfNotPresent(DeviceGuiElement device) { boolean add = true; for (DeviceGuiElement element : clients) { if (element != null && element.getName().equals(device.getName()) && element.getAddress().equals(device.getAddress())) { add = false; //already in the list } } if (add) { clients.add(device); } }void onMessageReceived(final WfdMessage msg) { threadPool.execute(new Runnable() { @Override public void run() { if (msg.getReceiverId().equals(myIdentifier)) { handle(msg); } else { route(msg); } } }); }public SPFPersona getPersonaOf(String appIdentifier) { SQLiteDatabase db = mRegistryTable.getReadableDatabase(); String table = Contract.TABLE_NAME; String[] columns = { Contract.COLUMN_PERSONA }; String selection = Contract.COLUMN_APP_IDENTIFIER + " = ? "; String[] selectionArgs = { appIdentifier }; String groupBy = null; String having = null; String orderBy = null; Cursor c = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy); if (c.moveToNext()) { String persona = c.getString(c.getColumnIndex(Contract.COLUMN_PERSONA)); return new SPFPersona(persona); } c.close(); return SPFPersona.DEFAULT; }public boolean unregisterApplication(String appIdentifier) { String where = Contract.COLUMN_APP_IDENTIFIER + " = ?"; String[] whereArgs = { appIdentifier }; if (mRegistryTable.getWritableDatabase().delete(Contract.TABLE_NAME, where, whereArgs) == 0) { return false; } if (SPF.get().getServiceRegistry().unregisterAllServicesOfApp(appIdentifier)) { Intent i = new Intent(DEREGISTRATION_INTENT); i.putExtra(DEREGISTERED_APP, appIdentifier); mContext.sendBroadcast(i); return true; } return false; }public String registerApplication(AppDescriptor descriptor, SPFPersona persona) { String token = mTokenGenerator.generateAccessToken(); ContentValues cv = new ContentValues(); cv.put(Contract.COLUMN_APP_NAME, descriptor.getAppName()); cv.put(Contract.COLUMN_ACCESS_TOKEN, token); cv.put(Contract.COLUMN_APP_IDENTIFIER, descriptor.getAppIdentifier()); cv.put(Contract.COLUMN_PERMISSION_CODE, descriptor.getPermissionCode()); cv.put(Contract.COLUMN_PERSONA, persona.getIdentifier()); SQLiteDatabase db = mRegistryTable.getWritableDatabase(); if (db.insert(Contract.TABLE_NAME, null, cv) == -1) { return null; // TODO handle insertion error } return token; }AppAuth getAppAuthorizationByAppId(String appId) { String where = Contract.COLUMN_APP_IDENTIFIER + " = ?"; String args[] = { appId }; Cursor c = mRegistryTable.getReadableDatabase().query(Contract.TABLE_NAME, null, where, args, null, null, null); AppAuth auth = null; if (c.moveToFirst()) { auth = appAuthFromCursor(c); } c.close(); return auth; }public boolean registerService(SPFServiceDescriptor descriptor) { String appId = descriptor.getAppIdentifier(); String serviceName = descriptor.getServiceName(); for (String verb : descriptor.getConsumedVerbs()) { if (!registerServiceInternal(verb, serviceName, appId)) { return false; } Log.v(TAG, "Registered service as Activity consumer: " + descriptor.getServiceName()); } return true; }boolean removePersona(SPFPersona persona) { SQLiteDatabase db = getWritableDatabase(); if (persona.getIdentifier().equals("default")) { return false; } String table = Contract.TABLE_PERSONAS; String selection = Contract.COLUMN_PERSONA + " = ?"; String[] selectionArgs = { persona.getIdentifier() }; if (db.delete(table, selection, selectionArgs) > 0) { deleteFieldsOf(persona, db); deleteVisibilityOf(persona, db); } return true; }boolean addPersona(SPFPersona persona) { SQLiteDatabase db = getWritableDatabase(); String table = Contract.TABLE_PERSONAS; String nullColumnHack = null; ContentValues values = new ContentValues(); values.put(Contract.COLUMN_PERSONA, persona.getIdentifier()); if (db.insert(table, nullColumnHack, values) > 0) { // copy the unique identifier ProfileFieldContainer pfc = getProfileFieldBulk(SPFPersona.getDefault(), ProfileField.IDENTIFIER); String id = pfc.getFieldValue(ProfileField.IDENTIFIER); if (setValue(ProfileField.IDENTIFIER.getIdentifier(), id, persona.getIdentifier())) { addCircleToFieldsInternal(DefaultCircles.PUBLIC, ProfileField.IDENTIFIER, persona, db); addCircleToFieldsInternal(DefaultCircles.PUBLIC, ProfileField.DISPLAY_NAME, persona, db); return true; } else { removePersona(persona); return false; } } return false; }public void refreshTriggers(List triggers2) { triggers.clear(); for (SPFTrigger trg : triggers2) { triggers.put(trg.getId(), trg); } }protected void handleError(SPFError err) { if (err.codeEquals(SPFError.TOKEN_NOT_VALID_ERROR_CODE)) { AccessTokenManager.get(mContext).invalidateToken(); } mCallback.onError(err); }public void disconnect() { try { mContext.unbindService(mConnection); } catch (Exception e) { Log.w(getClass().getSimpleName(), "Exception unbinding from service: ", e); } }private static , I extends IInterface> void bindToService(final Context context, final Descriptor descriptor, final ConnectionCallback callback) { Intent intent = new Intent(); intent.setComponent(SPFInfo.getSPFServiceComponentName()); intent.setAction(descriptor.getActionName()); ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder binder) { I service = descriptor.castInterface(binder); C instance = descriptor.createInstance(context, service, this, callback); callback.onServiceReady(instance); } @Override public void onServiceDisconnected(ComponentName name) { callback.onDisconnect(); } }; if (!context.bindService(intent, connection, Context.BIND_AUTO_CREATE)) { callback.onError(new SPFError(SPFError.SPF_NOT_INSTALLED_ERROR_CODE)); } }protected static , I extends IInterface> void load(final Context context, final Descriptor descriptor, final ConnectionCallback callback) { Utils.notNull(context, "context must not be null"); Utils.notNull(descriptor, "context must not be null"); if (AccessTokenManager.get(context).hasToken()) { bindToService(context, descriptor, callback); } else { AccessTokenManager.get(context).requireAccessToken(context, new AccessTokenManager.RegistrationCallback() { @Override public void onRegistrationSuccessful() { Log.d("Component" , "Access Toekn: " + descriptor); bindToService(context, descriptor, callback); } @Override public void onRegistrationError(SPFError errorMsg) { callback.onError(errorMsg); } }); } }public static String toJsonQuietly(final T object) { try { return ObjectToJsonExtensions.toJson(object); } catch (final JsonProcessingException e) { log.log(Level.SEVERE, "An error occured when converting object to String.\nGiven object:" + object.toString() + "\n", e); } return null; }private void writeToBuffer() throws SAXException { if (stringBuilder == null) { return; } final String string = stringBuilder.toString().trim(); write(string); stringBuilder = null; }private void insertNewLine() throws SAXException { try { writer.write(System.getProperty("line.separator")); } catch (final IOException e) { throw new SAXException("I/O error", e); } }public void shutdown() { synchronized (this) { if (mShutdown) { return; } for (AppServiceProxy p : mProxies.values()) { if (p.isConnected()) { mContext.unbindService(p); mProxies.remove(p); } } mShutdown = true; } }public void onRefresh() { mViewContainer.removeAllViews(); for (ProfileField field : mFieldsToShow) { View child = mParent.createViewFor(field, mViewContainer); mViewContainer.addView(child); } }public List getSelectedIndicies() { List selection = new LinkedList(); for (int i = 0; i < mItems.length; ++i) { if (mSelection[i]) { selection.add(i); } } return selection; }public List getSelectedStrings() { List selection = new LinkedList(); for (int i = 0; i < mItems.length; ++i) { if (mSelection[i]) { selection.add(mItems[i]); } } return selection; }public void setSelection(int[] selectedIndicies) { for (int index : selectedIndicies) { if (index >= 0 && index < mSelection.length) { mSelection[index] = true; } else { throw new IllegalArgumentException("Index " + index + " is out of bounds."); } } refreshDisplayValue(); }public void setSelection(String[] selection) { for (String sel : selection) { for (int j = 0; j < mItems.length; ++j) { if (mItems[j].equals(sel)) { mSelection[j] = true; } } } refreshDisplayValue(); }public InvocationResponse invokeMethod(InvocationRequest request) { String methodName = request.getMethodName(); if (!mMethodIndex.containsKey(methodName)) { String msg = String.format(ErrorMsg.METHOD_NOT_FOUND, methodName, mServiceDescriptor.getServiceName()); return InvocationResponse.error(msg); } Method m = mMethodIndex.get(methodName); Object[] params; try { params = deserializeParameters(request.getPayload(), m.getGenericParameterTypes()); } catch (ServiceInvocationException e) { return InvocationResponse.error("Error deserializing parameters:" + e.getMessage()); } try { Object result = m.invoke(mImplementation, params); String json = GsonHelper.gson.toJson(result); return InvocationResponse.result(json); } catch (IllegalAccessException e) { return InvocationResponse.error(e); } catch (IllegalArgumentException e) { return InvocationResponse.error(ErrorMsg.ILLEGAL_ARGUMENT); } catch (InvocationTargetException e) { return InvocationResponse.error(e.getCause()); } }public String addAttribute(final String name, final String value) { if (getAttributes() == null) { this.attributes = MapFactory.newLinkedHashMap(); } return getAttributes().put(name, value); }private void startRegistration() { // Create a string map containing information about your service. Map mRecordMap = new HashMap<>(); mRecordMap.put(Configuration.PORT, Integer.toString(mPort)); mRecordMap.put(Configuration.IDENTIFIER, myIdentifier); // Service information. Pass it an instance name, service type // Configuration.SERVICE_REG_TYPE , and the map containing // information other devices will want once they connect to this one. WifiP2pDnsSdServiceInfo mInfo = WifiP2pDnsSdServiceInfo.newInstance( Configuration.SERVICE_INSTANCE + myIdentifier, Configuration.SERVICE_REG_TYPE, mRecordMap); // Add the local service, sending the service info, network channel, // and listener that will be used to indicate success or failure of // the request. mManager.addLocalService(mChannel, mInfo, new CustomizableActionListener( this.mContext, TAG, "Added Local Service", null, "Failed to add a service", "Failed to add a service", true)); //important: sets true to get detailed message when this method fails }public void start() { this.mHandlerThread = new HandlerThread("notification-handler-thread"); this.mHandlerThread.start(); this.mHandler = new SPFNotificationHandler(mHandlerThread.getLooper()); mHandler.postSetup(this); isRunning = true; }public boolean deleteTrigger(long id, String appPackageName) { boolean success = mTriggerTable.deleteTrigger(id, appPackageName); if (success) { if (mHandler != null) mHandler.postRemoveTrigger(id); } return success; }public long saveTrigger(SPFTrigger trigger, String appPackageName) { trigger = mTriggerTable.saveTrigger(trigger, appPackageName); if (trigger != null) { if (mHandler != null) mHandler.postAddTrigger(trigger); return trigger.getId(); } else { return -1; } }public void setTags(List tags) { this.tags.clear(); removeAllViews(); for (String tag : tags) { addTag(tag); } }public void addTag(String tag) { TagBubble tb = new TagBubble(getContext()); tb.setText(tag); tb.setEditable(editable); tb.setOnRemoveTagListener(bubbleClickListener); tags.add(tag.toString()); addView(tb); }public static String toJson(final T object, final boolean newMapper) throws JsonProcessingException { final ObjectMapper mapper = ObjectMapperFactory.getObjectMapper(newMapper); final String json = mapper.writeValueAsString(object); return json; }public void handleCrop(int resultCode, Intent result) { if (resultCode == Activity.RESULT_OK) { Uri uri = Crop.getOutput(result); resultView.setImageURI(uri); InputStream inputStream = null; try { inputStream = new FileInputStream(uri.getPath()); Bitmap myBitmap = BitmapFactory.decodeStream(inputStream); myBitmap = Bitmap.createScaledBitmap(myBitmap, 130, 130, false); mContainer.setFieldValue(ProfileField.PHOTO, myBitmap); showPicture(myBitmap); } catch (FileNotFoundException e) { Log.e(TAG, "handleCrop FileInputStream-file not found from uri.getpath", e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Log.e(TAG, "handleCrop closing input stream error", e); } } } } else if (resultCode == Crop.RESULT_ERROR) { Toast.makeText(this.getActivity(), Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show(); } }public void beginCrop(Uri source) { Uri destination = Uri.fromFile(new File(this.getActivity().getCacheDir(), "cropped")); Crop.of(source, destination).asSquare().start(this.getActivity()); }private void onProfileDataAvailable() { Log.d(TAG, "onProfileDataAvailable"); mFactory = new ProfileFieldViewFactory(getActivity(), mMode, mCurrentPersona, mContainer); String[] mPageTitles = this.getResources().getStringArray(R.array.profileedit_fragments_titles); tabLayout.removeAllTabs(); tabLayout.addTab(tabLayout.newTab().setText(mPageTitles[0].toUpperCase(Locale.getDefault()))); tabLayout.addTab(tabLayout.newTab().setText(mPageTitles[1].toUpperCase(Locale.getDefault()))); tabLayout.addTab(tabLayout.newTab().setText(mPageTitles[2].toUpperCase(Locale.getDefault()))); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); ProfilePagerAdapter mPagerAdapter = new ProfilePagerAdapter(getChildFragmentManager(), mMode, tabLayout.getTabCount()); mViewPager.setAdapter(mPagerAdapter); mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); if (mMode != Mode.SELF) { showPicture(mContainer.getFieldValue(ProfileField.PHOTO)); } else { if (getActivity() instanceof MainActivity) { ((MainActivity) getActivity()).onPhotoReady(mContainer.getFieldValue(ProfileField.PHOTO)); } else if (getActivity() instanceof ProfileViewActivity) { //TODO implement this // ((ProfileViewActivity) getActivity()).onPhotoReady(mContainer.getFieldValue(ProfileField.PHOTO)); } } // Refresh field fragments mPagerAdapter.onRefresh(); }public static ProfileFragment createViewSelfProfileFragment() { Bundle b = new Bundle(); b.putInt(EXTRA_VIEW_MODE, Mode.SELF.ordinal()); ProfileFragment fragment = new ProfileFragment(); fragment.setArguments(b); return fragment; }public void broadcastEvent(final int code, final Bundle payload) { if (SPFConfig.DEBUG) { Log.d(TAG, "Broadcasting event " + code + " with payload " + payload); } for (final OnEventListener listener : mEventListeners) {//TODO is it thread safe? mHandler.post(new Runnable() { @Override public void run() { listener.onEvent(code, payload); } }); } }public static synchronized void initialize(Context context, int goIntent, boolean isAutonomous, ProximityMiddleware.Factory factory) { if (context == null || factory == null) { throw new NullPointerException("Arguments cannot be null"); } SPF.initialize(context, goIntent, isAutonomous, factory); sInstance = new SPFContext(); }private void killScheduler() { if (scheduler != null) { WfdLog.d(TAG, "scheduler killed"); scheduler.shutdown(); scheduler = null; } }public String getFriendlyNameOfField(ProfileField field) { String name = getStringFromResource(PROFILE_FIELD_PREFIX + field.getIdentifier()); if(name == null){ return field.getIdentifier(); } return name; }private void setContentViewWithMinimalElements() { // Set data in the RemoteViews programmatically contentView.setImageViewResource(R.id.imageView, R.drawable.ic_launcher); contentView.setTextViewText(R.id.title_text_notification, getResources().getString(R.string.notification_title)); contentView.setTextViewText(R.id.message_notification, getResources().getString(R.string.notification_text)); }public String toXml() { final String lqSimpleName = this.getClass().getSimpleName().toLowerCase(); final Map> aliases = new HashMap<>(); aliases.put(lqSimpleName, this.getClass()); return ObjectToXmlExtensions.toXmlWithXStream(this, aliases); }public final void sendNotification(String uniqueIdentifier, SPFActionSendNotification action) { if (uniqueIdentifier == null || action == null) { throw new NullPointerException(); } String actionJSON = action.toJSON(); sendNotification(uniqueIdentifier, actionJSON); }private View createStandardEditView(ProfileField field, E currentValue, FieldValueListener listener, ViewGroup container) { View result = mInflater.inflate(R.layout.profileedit_field_standard, container, false); String friendlyName = mHelper.getFriendlyNameOfField(field); ((TextView) result.findViewById(R.id.profileedit_field_identifier)).setText(friendlyName); EditText editText = (EditText) result.findViewById(R.id.profileedit_field_value); editText.addTextChangedListener(new OnEditorActionAdapter<>(listener, field)); if (currentValue != null) { editText.setText(mHelper.convertToFriendlyString(field, currentValue)); } setUpCircleView(result, field, listener); return result; }@SuppressWarnings("unchecked") private View createTagView(TagProfileField field, String[] currentValue, FieldValueListener listener, ViewGroup container, boolean editable) { View result = mInflater.inflate(editable ? R.layout.profileedit_field_tag : R.layout.profileview_tag_field, container, false); String friendlyName = mHelper.getFriendlyNameOfField(field); ((TextView) result.findViewById(R.id.profileedit_field_identifier)).setText(friendlyName); TagsPicker picker = (TagsPicker) result.findViewById(R.id.profileedit_tags_picker); picker.setEditable(editable); if (currentValue != null) { picker.setInitialTags(Arrays.asList(currentValue)); } if (editable) { picker.setChangeListener(new OnChangeListenerAdapter(field, (FieldValueListener) listener)); } setUpCircleView(result, (ProfileField) field, listener); return result; }@SuppressWarnings("unchecked") private View createDateView(final DateProfileField field, Date currentValue, final FieldValueListener listener, ViewGroup container) { View result = mInflater.inflate(R.layout.profileedit_field_date, container, false); String friendlyName = mHelper.getFriendlyNameOfField(field); ((TextView) result.findViewById(R.id.profileedit_field_identifier)).setText(friendlyName); String dateToShow; if (currentValue == null) { dateToShow = "Click to edit"; } else { dateToShow = mHelper.convertToFriendlyString(field, currentValue); } final TextView dateTextView = (TextView) result.findViewById(R.id.profileedit_field_date_text); dateTextView.setText(dateToShow); dateTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar today = GregorianCalendar.getInstance(); int year = today.get(Calendar.YEAR); int monthOfYear = today.get(Calendar.MONTH); int dayOfMonth = today.get(Calendar.DAY_OF_MONTH); OnDateSetListener callBack = new OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { GregorianCalendar cal = new GregorianCalendar(year, monthOfYear, dayOfMonth); Date newDate = new Date(cal.getTimeInMillis()); String newDateString = mHelper.convertToFriendlyString(field, newDate); dateTextView.setText(newDateString); listener.onFieldValueChanged(field, newDate); } }; DatePickerDialog dialog = new DatePickerDialog(mContext, callBack, year, monthOfYear, dayOfMonth); dialog.show(); } }); setUpCircleView(result, (ProfileField) field, (FieldValueListener) listener); return result; }private View createSpinner(MultipleChoicheProfileField field, E currentValue, FieldValueListener listener, ViewGroup container) { View result = mInflater.inflate(R.layout.profileedit_field_multiplechoiche, container, false); String friendlyName = mHelper.getFriendlyNameOfField(field); ((TextView) result.findViewById(R.id.profileedit_field_identifier)).setText(friendlyName); Spinner spinner = (Spinner) result.findViewById(R.id.profileedit_field_multiple_value); ArrayAdapter adapter = new ArrayAdapter(mContext, android.R.layout.simple_list_item_1, field.getChoiches()); spinner.setAdapter(adapter); int index = indexOf(field.getChoiches(), currentValue); if (index >= 0) { spinner.setSelection(index, false); } spinner.setOnItemSelectedListener(new OnItemSelectedAdapter(field, listener, adapter)); setUpCircleView(result, field, listener); return result; }private View createStandardDisplayView(ProfileField field, E currentValue, ViewGroup viewContainer) { View result = mInflater.inflate(R.layout.profileview_field_listelement, viewContainer, false); String friendlyFieldName = mHelper.getFriendlyNameOfField(field); ((TextView) result.findViewById(R.id.profile_field_key)).setText(friendlyFieldName); String fieldValue = mHelper.convertToFriendlyString(field, currentValue); ((TextView) result.findViewById(R.id.profile_field_value)).setText(fieldValue); setUpCircleView(result, field, null); return result; }public static void connect(final Context context, final ConnectionListener listener) { Component.load(context, DESCRIPTOR, asBase(listener)); }void stopAllSearches(String appIdentifier) { List qinfos; synchronized (queries) { qinfos = new ArrayList(queries.values()); } for (QueryInfo queryInfo : qinfos) { if (queryInfo.getAppName().equals(appIdentifier)) { stopSearch(queryInfo); } } }void stopSearch(String queryId) { QueryInfo info = queries.get(queryId); if(info != null){ stopSearch(info); } }void onInstanceLost(String uniqueIdentifier) { log(TAG, "instance lost " + uniqueIdentifier); List queriesIds = results.get(uniqueIdentifier); if (queriesIds == null) { return; } for (String queryId : queriesIds) { String[] args = new String[2]; args[0] = queryId; args[1] = uniqueIdentifier; Message msg = handler.obtainMessage(SearchMessages.RESULT_LOST, args); log(TAG, "sending message RESULT_LOST to handler for queryId: " + queryId); handler.sendMessage(msg); } }private String generateQueryId(QueryInfo queryInfo) { String queryId = SPF.get().getUniqueIdentifier() + (++id); queryInfo.setQueryId(queryId); return queryId; }public void unregisterService(Class serviceInterface) { Utils.notNull(serviceInterface, "serviceInterface must not be null"); ServiceValidator.validateInterface(serviceInterface, ServiceValidator.TYPE_PUBLISHED); ServiceInterface svcInterface = serviceInterface.getAnnotation(ServiceInterface.class); SPFServiceDescriptor svcDesc = ServiceInterface.Convert.toServiceDescriptor(svcInterface); String token = getAccessToken(); try { SPFError error = new SPFError(); getService().unregisterService(token, svcDesc, error); if (!error.isOk()) { handleError(error); } } catch (RemoteException e) { catchRemoteException(e); } }public InvocationResponse dispatchInvocation(InvocationRequest request) { String appName = request.getAppName(); String serviceName = request.getServiceName(); String componentName = mServiceTable.getComponentForService(appName, serviceName); if (componentName == null) { return InvocationResponse.error("Application " + appName + " doesn't have a service named " + serviceName); } AppServiceProxy proxy = mCommunicationAgent.getProxy(componentName); if (proxy == null) { return InvocationResponse.error("Cannot bind to service"); } try { return proxy.executeService(request); } catch (Throwable t) { Log.e("ServiceRegistry", "Error dispatching invocation: ", t); return InvocationResponse.error("Internal error: " + t.getMessage()); } }public boolean matches(String queryJSON) { QueryContainer queryContainer; try { queryContainer = QueryContainer.fromJSON(queryJSON); } catch (JSONException e) { return false; } SPFQuery query = queryContainer.getQuery(); String callerApp = queryContainer.getCallerAppId(); String userUID = queryContainer.getUserUID(); return analyzeWith(query, callerApp, userUID); }public static String newTag(final String tagname, final String value, final Map attributes) { final StringBuilder xmlTag = new StringBuilder(); xmlTag.append("<").append(tagname); if (attributes != null && !attributes.isEmpty()) { xmlTag.append(" "); int count = 1; for (final Map.Entry attributte : attributes.entrySet()) { xmlTag.append(attributte.getKey()); xmlTag.append("="); xmlTag.append("\"").append(attributte.getValue()).append("\""); if (count != attributes.size()) { xmlTag.append(" "); } count++; } } xmlTag.append(">"); xmlTag.append(value); xmlTag.append(""); return xmlTag.toString(); }private static T loadObject(final InputStream is) throws IOException { final String xmlString = ReadFileExtensions.inputStream2String(is); final T object = XmlToObjectExtensions.toObjectWithXStream(xmlString); return object; }public static void logCall(String tag, String methodName, Object... args) { if (SPFConfig.DEBUG) { Log.d(tag, "method call: " + methodName + "(" + (args != null ? TextUtils.join(",", args) : "") + ")"); } }private void checkCurrentThread(String methodName) { if (Looper.myLooper() == Looper.getMainLooper()) { Log.w(TAG, String.format(WRONG_THREAD_MSG, mServiceDescriptor.getServiceName(), methodName)); } }public Object invokeMethod(String methodName, Object[] args, Type retType) throws ServiceInvocationException { checkCurrentThread(methodName); Utils.notNull(methodName); Utils.notNull(args); // Let the target prepare the arguments if needed mInvocationTarget.prepareArguments(args); // Serialize arguments String payload = GsonHelper.gson.toJson(args); InvocationRequest request = new InvocationRequest(mServiceDescriptor.getAppIdentifier(), mServiceDescriptor.getServiceName(), methodName, payload); // Let the target perform the execution InvocationResponse response = mInvocationTarget.executeService(request); // Analyze the response if (!response.isResult()) { throw new ServiceInvocationException(response.getErrorMessage()); } else if (retType.equals(void.class)) { return null; } else { return GsonHelper.gson.fromJson(response.getPayload(), retType); } }public static String toJson(final String xmlString, final Map> aliases) { final Object object = XmlToObjectExtensions.toObjectWithXStream(xmlString); final XStream xstream = new XStream(new JettisonMappedXmlDriver()); if (aliases != null) { for (final Map.Entry> alias : aliases.entrySet()) { xstream.alias(alias.getKey(), alias.getValue()); } } final String json = xstream.toXML(object); return json; }@SuppressWarnings("unchecked") public static T toObjectWithXStream(XStream xstream, final String xmlString, final Map> aliases) { if (xstream == null) { xstream = new XStream(); } if (aliases != null) { for (final Map.Entry> alias : aliases.entrySet()) { xstream.alias(alias.getKey(), alias.getValue()); } } return (T)xstream.fromXML(xmlString); }public static T toObjectWithXStream(final String xmlString, final Map> aliases) { return toObjectWithXStream(null, xmlString, aliases); }public AppAuth validateAccess(String accessToken, Permission permission) throws TokenNotValidException, PermissionDeniedException { AppAuth appAuth; if (accessToken == null) { throw new TokenNotValidException(); } appAuth = mAppRegistry.getAppAuthorization(accessToken); if ((appAuth.getPermissionCode() & permission.getCode()) == 0) { throw new PermissionDeniedException(); } return appAuth; }SPFTrigger getTrigger(long triggerId, String appPackageName) { String where = Contract._ID + " = ? AND " + Contract.COLUMN_APP_IDENTIFIER + " = ?"; String[] whereArgs = { Long.toString(triggerId), appPackageName }; Cursor c = getReadableDatabase().query(Contract.TABLE_NAME, null, where, whereArgs, null, null, null); if (!c.moveToFirst()) { return null; } SPFTrigger t = triggerFromCursor(c); c.close(); return t; }boolean deleteTrigger(long id, String appPackageName) { String where = Contract.COLUMN_APP_IDENTIFIER + " = ? AND " + Contract._ID + " = ?"; String[] whereArgs = { appPackageName, Long.toString(id) }; int count = getReadableDatabase().delete(Contract.TABLE_NAME, where, whereArgs); return count > 0; }boolean deleteAllTriggerOf(String appPackageName) { String where = Contract.COLUMN_APP_IDENTIFIER + " = ?"; String[] whereArgs = { appPackageName }; int c = getReadableDatabase().delete(Contract.TABLE_NAME, where, whereArgs); return c > 0; }List getAllTriggers(String appIdentifier) { String where = Contract.COLUMN_APP_IDENTIFIER + " = ?"; String[] whereArgs = { appIdentifier }; Cursor c = getReadableDatabase().query(Contract.TABLE_NAME, null, where, whereArgs, null, null, null); List triggers = new ArrayList(); while (c.moveToNext()) { triggers.add(triggerFromCursor(c)); } c.close(); return triggers; }@Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent == null) { return START_STICKY; } String action = intent.getAction(); if (ACTION_START_FOREGROUND.equals(action)) { if (!SPF.get().isConnected()) { SPF.get().connect(); } SPF.get().notifyProximityStatus(false); //false because it's starting startInForeground(); Log.d(TAG, "Started in foreground"); } else if (ACTION_STOP_FOREGROUND.equals(action)) { //notify to the middleware that i killed the proximity service SPF.get().notifyProximityStatus(true); //true because it's killing stopForeground(true); mIsStartedForeground = false; Log.d(TAG, "Foreground stopped"); } return START_STICKY; }public WiFiP2pService getServiceByDevice(WifiP2pDevice device) { if (device == null) { return null; } WfdLog.d(TAG, "groupownerdevice passed to getServiceByDevice: " + device.deviceName + ", " + device.deviceAddress); WfdLog.d(TAG, "servicelist size: " + serviceList.size()); for (WiFiP2pService element : serviceList) { WfdLog.d(TAG, "element in list: " + element.getDevice().deviceName + ", " + element.getDevice().deviceAddress); WfdLog.d(TAG, "element passed : " + device.deviceName + ", " + device.deviceAddress); if (element.getDevice().deviceAddress.equals(device.deviceAddress)) { WfdLog.d(TAG, "getServiceByDevice if satisfied : " + device.deviceAddress + ", " + element.getDevice().deviceAddress); return element; } } WfdLog.d(TAG, "servicelist size: " + serviceList.size()); return null; }public void addServiceIfNotPresent(WiFiP2pService service) { WfdLog.d(TAG, "addServiceIfNotPresent BEGIN, with size = " + serviceList.size()); if (service == null) { WfdLog.e(TAG, "Service is null, returning..."); return; } boolean add = true; for (WiFiP2pService element : serviceList) { if (element != null && element.getDevice().equals(service.getDevice()) && element.getInstanceName().equals(service.getInstanceName())) { add = false; //already in the list } } if (add) { serviceList.add(service); } WfdLog.d(TAG, "addServiceIfNotPresent END, with size = " + serviceList.size()); }public String toXmlString() { final StringBuilder buffer = new StringBuilder(); buffer.append("<"); buffer.append(getName()); Optional attr = TagExtensions.attributesToString(getAttributes()); if (attr.isPresent()) { buffer.append(attr.get()); } if (isEndTag()) { buffer.append(">"); buffer.append(getContent()); if (getChildren() != null && !getChildren().isEmpty()) { for (final SimpleTag child : getChildren()) { buffer.append(child.toXmlString()); } } buffer.append(""); } else { buffer.append("/>"); } return buffer.toString(); }public StringBuilder toVelocityTemplate() { final StringBuilder buffer = new StringBuilder(); buffer.append("<"); buffer.append("${").append(getName()).append(".name}\n"); if (getAttributes() != null && !getAttributes().isEmpty()) { buffer.append(" #foreach(" + "$attribute in $").append(getName()) .append(".attributes.keySet()" + ")\n"); buffer.append("$attribute=\"$").append(getName()) .append(".getAttributes().get($attribute)\"\n"); buffer.append(" #end\n"); } buffer.append("#if(${").append(getName()).append(".endTag})>${").append(getName()) .append(".content}\n"); if (getChildren() != null && !getChildren().isEmpty()) { buffer.append("#foreach($").append(getChildren().get(0).getName()).append(" in $") .append(getName()).append(".children)\n"); for (final SimpleTag child : getChildren()) { buffer.append(child.toVelocityTemplate().toString()); } buffer.append("#end\n"); } buffer.append("\n"); buffer.append("#else />\n" + "#end\n"); return buffer; }public String removeAttribute(final String name) { if (getAttributes() != null) { getAttributes().remove(name); } return null; }public boolean addChild(final SimpleTag child) { if (getChildren() == null) { setChildren(ListFactory.newArrayList()); } return getChildren().add(child); }public static boolean validateSchema(final String SchemaUrl, final String XmlDocumentUrl) throws SAXException, ParserConfigurationException, IOException { System.setProperty(DOCUMENT_BUILDER_FACTORY_KEY, DOCUMENT_BUILDER_FACTORY_VALUE); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setAttribute(SCHEMA_LANGUAGE_KEY, HTTP_WWW_W3_ORG_2001_XML_SCHEMA); factory.setAttribute(SCHEMA_SOURCE_KEY, SchemaUrl); final DocumentBuilder builder = factory.newDocumentBuilder(); final ValidatorHandler handler = new ValidatorHandler(); builder.setErrorHandler(handler); builder.parse(XmlDocumentUrl); if (handler.isValid()) { return false; } return true; }public static void validateSchema(final File xsd, final File xml, final ErrorHandler errorHandler) throws SAXException, ParserConfigurationException, IOException { final Schema schemaXSD = getSchema(xsd, errorHandler); // Create a Validator capable of validating XML files according to my custom schema. final Validator validator = schemaXSD.newValidator(); // parse the XML DOM tree againts the stricter XSD schema validator.validate(getDOMSource(xml, errorHandler)); }public static Document parse(final File xml, final ErrorHandler errorHandler) throws SAXException, ParserConfigurationException, IOException { final DocumentBuilderFactory factory = getDocumentBuilderFactory(xml.getName()); final DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); return builder.parse(xml); }public static Schema getSchema(final File xsd, final ErrorHandler errorHandler) throws SAXException { // Create a new instance for an XSD-aware SchemaFactory final SchemaFactory schemaFactory = SchemaFactory .newInstance(HTTP_WWW_W3_ORG_2001_XML_SCHEMA); // Set the ErrorHandler implementation. schemaFactory.setErrorHandler(errorHandler); // get the custom xsd schema that describes // the required format for my XML files. return schemaFactory.newSchema(xsd); }public static DOMSource getDOMSource(final File xml, final ErrorHandler errorHandler) throws SAXException, ParserConfigurationException, IOException { return new DOMSource(parse(xml, errorHandler)); }public static DocumentBuilderFactory getDocumentBuilderFactory(final String schema) { System.setProperty(DOCUMENT_BUILDER_FACTORY_KEY, DOCUMENT_BUILDER_FACTORY_VALUE); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setAttribute(SCHEMA_LANGUAGE_KEY, HTTP_WWW_W3_ORG_2001_XML_SCHEMA); factory.setAttribute(SCHEMA_SOURCE_KEY, schema); return factory; }public void setChangeListener(OnChangeListener listener) { changeListener = listener; if (changeListener != null) { // add a listener to TagViewer for removed tags events tv.setOnRemovedTagListener(new TagsViewer.OnRemovedListener() { @Override public void onRemovedTag(String tag) { notifyChangeListener(); } }); } }public RemoteProfile getProfileOf(SPFPerson p) { if (p == null) { throw new NullPointerException(); } return new RemoteProfile(p, mInterface); }void initStartedLoaders() { LoaderManager lm = operatorContext.loaderManager; SparseArray listenersMap = this.listenersMap; int count = listenersMap.size(); for (int i = 0; i < count; i++) { int loaderId = listenersMap.keyAt(i); Loader loader = lm.getLoader(loaderId); if (loader != null && loader.isStarted()) { LoaderCookies cookies = listenersMap.valueAt(i); boolean notInit = (cookies.options & LoaderCookies.ALREADY_INIT) == 0; if (notInit) { Utils.initLoader( operatorContext, loaderId, STUB_PROVIDER, (cookies.options & LoaderCookies.DESTROY_ON_FINISH) == LoaderCookies.DESTROY_ON_FINISH, this ); } } } }public static CursorConverter> listConverter(final CursorConverter converter) { return new ListConverter<>(converter); }public boolean isSameSession() { String sessionId = sessionIdProvider.get(); if (callbackStartSessionId == null) { return sessionId == null; } return callbackStartSessionId.equals(sessionId); }private List getAcceptedContentTypes() { Annotation consumesAnnotation = referencedMethod.getAnnotation(Consumes.class); if (null == consumesAnnotation) consumesAnnotation = referencedClass.getAnnotation(Consumes.class); final List acceptedContentTypes = Lists.newArrayList(); if (null != consumesAnnotation) { for (final String cts : ((Consumes)consumesAnnotation).value()) { try { acceptedContentTypes.add(ContentType.valueOf(cts)); } catch (IllegalArgumentException e) { } } } return acceptedContentTypes; }public String buildMaxLen() { List criteria = this.getCriteria(); if (criteria != null) { for (Criterion criterion : criteria) { if (criterion instanceof MaxLength) { return AttributeUtils.buildSingleAttribute("maxlength", Integer.toString(((MaxLength) criterion).getMaxLength())); } } } return ""; }protected String buildAllAttributes(TagAttributes tagAttributes, MessageSource messageSource, boolean html5Validation) { StringBuilder allAttribs = new StringBuilder(); allAttribs.append(AttributeUtils.buildAttributes(tagAttributes)); allAttribs.append(getElementId()); allAttribs.append(getTabIndexTag()); if (html5Validation) { allAttribs.append(buildRequiredAttribute()); allAttribs.append(buildFcRequiredMessage(messageSource)); } allAttribs.append(buildSizeAttribute()); // help-text if (!StringUtils.isEmpty(helpText)) { allAttribs.append( AttributeUtils.buildAttributes(new TagAttributes("aria-describedby", parent.getConfig().getFormBuilder().getHelpBlockId(this)))); } return allAttribs.toString(); }@Deprecated public static SelectInput build(String name, LinkedHashMap possibleNames) { SelectInput si = SelectInput.build(name); si.setPossibleValues(possibleNames); return si; }public static ApplicationContext registerAppContext(String embeddedWebContext, ApplicationContext appContext) { return appContextMap.put(embeddedWebContext, appContext); }public String getElement(String name) { return formBuilder.generateHtmlForElement(fc.firstRun, fc.config.getProperties(), form.getElement(name), this.form.isHtml5Validation()); }public String getCompleteRenderedInput(InputElementStructure inputStruct, FormCheckerElement elem, boolean firstRun) { StringBuilder elemHtml = new StringBuilder(); Wrapper elementWrapper = getWrapperForElem(elem, firstRun); elemHtml.append(elementWrapper.start); elemHtml.append(inputStruct.getErrors()); Wrapper labelWrapper = getWrapperForLabel(elem); elemHtml.append(labelWrapper.start).append(inputStruct.getLabel()).append(labelWrapper.end); Wrapper inputWrapper = getWrapperForInput(elem); elemHtml.append(inputWrapper.start); elemHtml.append(inputStruct.getInput()); elemHtml.append(inputStruct.getHelp()); elemHtml.append(inputWrapper.end); elemHtml.append(elementWrapper.end); return elemHtml.toString(); }String generateHtmlForElement(boolean firstRun, MessageSource messageSource, FormCheckerElement elem, boolean html5Validation) { InputElementStructure inputStruct = new InputElementStructure(); // errors ValidationResult vr = getErrors(elem, firstRun); if (!vr.isValid()) { inputStruct.setErrors(formatError(messageSource.getMessage(vr))); } // label boolean displayLabel = !StringUtils.isEmpty(elem.getDescription()); if (displayLabel) { inputStruct.setLabel(getLabelForElement(elem, getLabelAttributes(elem), firstRun)); } // input tag Map attribs = new LinkedHashMap<>(); addAttributesToInputFields(attribs, elem); inputStruct.setInput(elem.getInputTag(attribs, messageSource, html5Validation)); // help tag if (!StringUtils.isEmpty(elem.getHelpText())) { inputStruct.setHelp(getHelpTag(elem.getHelpText(), elem)); } return getCompleteRenderedInput(inputStruct, elem, firstRun); }@Deprecated final public String generateGenericForm(String formAction, boolean firstRun, FormCheckerForm form, Request req, FormCheckerConfig config) { return this.generateGenericForm(formAction, firstRun, form, req, config.properties); }private void sortTabIndexes() { int tabIndex = 100; for (FormCheckerElement elem : form.getElements()) { elem.setTabIndex(tabIndex); tabIndex = elem.getLastTabIndex(); tabIndex++; } }public String getLabelForElement(FormCheckerElement e, Map attribs) { return config.getFormBuilder().getLabelForElement(e, new TagAttributes(attribs), firstRun); }public void deleteAllLocal() { if (localCache != null) { try { localCache.deleteAll(); } catch (Exception e) { throw e instanceof CacheException ? (CacheException) e : new CacheException(e); } } }@Override public void deleteAll() { try { if (localCache != null) { localCache.deleteAll(); } if (remoteCache != null) { remoteCache.deleteAll(); } } catch (Exception e) { throw e instanceof CacheException ? (CacheException) e : new CacheException(e); } }public void deleteLocal(String key) { if (localCache != null) { try { localCache.delete(key); } catch (Exception e) { throw e instanceof CacheException ? (CacheException) e : new CacheException(e); } } }@Override public void delete(String key) { try { if (localCache != null) { localCache.delete(key); } if (remoteCache != null) { remoteCache.delete(key); } } catch (Exception e) { throw e instanceof CacheException ? (CacheException) e : new CacheException(e); } }@Override public void set(String key, Object entry, long expireAfterWrite, long expireAfterAccess) { try { if (localCache != null) { localCache.set(key, entry, expireAfterWrite, expireAfterAccess); } if (remoteCache != null) { remoteCache.set(key, entry, expireAfterWrite, expireAfterAccess); } } catch (Exception e) { throw e instanceof CacheException ? (CacheException) e : new CacheException(e); } }protected Properties getCacheProperties(String name) { return cacheProperties != null ? cacheProperties.get(name) : null; }protected String calcCacheKey(String key) { switch (keyMode) { case HASH: case MONOPOLISTIC: return key; case NAMESPACE: return getName() + ":" + key; default: throw new IllegalStateException("Invalid key mode: " + keyMode); } }protected String getCacheProperty(String key) { return cacheProps != null ? cacheProps.getProperty(key) : null; }public AbstractCache setCacheProperties(Properties cacheProps) { this.cacheProps = cacheProps != null ? new Properties(cacheProps) : new Properties(); return this; }public AbstractCache init() { /* * Parse custom property: capacity */ long oldCapacity = this.capacity; try { String entry = getCacheProperty(CACHE_PROP_CAPACITY); if (entry != null) { this.capacity = Long.parseLong(entry); } } catch (Exception e) { this.capacity = oldCapacity; LOGGER.warn(e.getMessage(), e); } if (capacity < -1) { setCapacity(-1); } /* * Parse custom property: expire-after-access */ long oldExpireAfterAccess = this.expireAfterAccess; try { String entry = getCacheProperty(CACHE_PROP_EXPIRE_AFTER_ACCESS); if (entry != null) { this.expireAfterAccess = Long.parseLong(entry); } } catch (Exception e) { this.expireAfterAccess = oldExpireAfterAccess; LOGGER.warn(e.getMessage(), e); } if (expireAfterAccess < -1) { setExpireAfterAccess(-1); } /* * Parse custom property: expire-after-write */ long oldExpireAfterWrite = this.expireAfterWrite; try { String entry = getCacheProperty(CACHE_PROP_EXPIRE_AFTER_WRITE); if (entry != null) { this.expireAfterWrite = Long.parseLong(entry); } } catch (Exception e) { this.expireAfterWrite = oldExpireAfterWrite; LOGGER.warn(e.getMessage(), e); } if (expireAfterWrite < -1) { setExpireAfterWrite(-1); } return this; }public static Object tryClone(Object toBeCloned) { if (toBeCloned == null) { return null; } Object clonedObj = null; if (toBeCloned instanceof Cloneable) { try { Method method = Object.class.getDeclaredMethod("clone"); method.setAccessible(true); clonedObj = method.invoke(toBeCloned); } catch (Exception e) { if (e instanceof CloneNotSupportedException) { clonedObj = toBeCloned; } else { throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } } } else { clonedObj = toBeCloned; } return clonedObj; }protected void refreshTTL(String key, CacheEntry ce) { final String KEY = calcCacheKey(key); final long TTL = ce.getExpireAfterAccess(); try (ShardedJedis jedis = getJedis()) { if (TTL > 0) { if (keyMode == KeyMode.HASH) { jedis.expire(getName(), (int) TTL); } else { jedis.expire(SafeEncoder.encode(KEY), (int) TTL); } } } catch (Exception e) { throw e instanceof CacheException ? (CacheException) e : new CacheException(e); } }public boolean touch() { if (expireAfterAccess > 0) { long now = System.currentTimeMillis(); if (lastAccessTimestampMs + LAST_ACCESS_THRESHOLD_MS < now) { lastAccessTimestampMs = now; return true; } } return false; }public static boolean rootElementMatches(FileResource fileResource, String path, String expectedRootElement) throws IOException { try (InputStream stream = fileResource.createStream()) { XMLStreamReader reader = factory.createXMLStreamReader(stream); while (reader.hasNext()) { int event = reader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: String rootElement = reader.getLocalName(); return expectedRootElement.equals(rootElement); } } } catch (XMLStreamException e) { LOGGER.warn("Cannot parse XML file '{}'.", path); } return false; }private Map buildHierarchyParameters(final List parents, final List children) { final MultiMap parameters = new MultiMap<>(); if (parents != null) { for (final String parent : parents) { parameters.put("parents", parent); } } if (children != null) { for (final String child : children) { parameters.put("children", child); } } return parameters; }private void fillDimensionProvider(final boolean _updateDim) { final DimensionProvider provider = getDimensionProvider(); final Iterator currentIter = provider.getRoots(); final List dims = getDimensions(); if (_updateDim && dims.isEmpty()) { provider.getRootList().clear(); } else { Collections.sort(dims, new Comparator() { @Override public int compare(final Dimension _arg0, final Dimension _arg1) { final String dim0 = DBProperties.getProperty(DimensionPanel.class.getName() + "." + _arg0.getKey()); final String dim1 = DBProperties.getProperty(DimensionPanel.class.getName() + "." + _arg1.getKey()); return dim0.compareTo(dim1); } }); final Iterator newDimsIter = dims.iterator(); while (currentIter.hasNext()) { final DimTreeNode current = currentIter.next(); if (newDimsIter.hasNext()) { final Dimension newDim = newDimsIter.next(); if (!newDim.getKey().equals(((Dimension) current.getValue()).getKey())) { currentIter.remove(); } else if (_updateDim) { current.update(newDim.getValues()); } } } // add new ones while (newDimsIter.hasNext()) { final DimTreeNode node = new DimTreeNode().setValue(newDimsIter.next()); provider.getRootList().add(node); } } }private boolean dimFilterApplied(final List _nodes) { final List nodes = _nodes == null ? getDimensionProvider().getRootList() : _nodes; boolean ret = false; for (final DimTreeNode node : nodes) { if (node.getStatus() != null) { ret = true; break; } ret = dimFilterApplied(node.getChildren()); if (ret) { break; } } return ret; }private List getExcluded() { final List ret = new ArrayList<>(); for (final DimTreeNode node : getDimensionProvider().getRootList()) { ret.addAll(node.getExcluded()); } return ret; }protected String getQuery() { final StringBuilder ret = new StringBuilder(); try { final String clazzname; if (EFapsSystemConfiguration.get().containsAttributeValue("org.efaps.kernel.index.QueryBuilder")) { clazzname = EFapsSystemConfiguration.get().getAttributeValue("org.efaps.kernel.index.QueryBuilder"); } else { clazzname = "org.efaps.esjp.admin.index.LucenceQueryBuilder"; } final Class clazz = Class.forName(clazzname, false, EFapsClassLoader.getInstance()); final Object obj = clazz.newInstance(); final Method method = clazz.getMethod("getQuery4DimValues", String.class, List.class, List.class); final Object newQuery = method.invoke(obj, getCurrentQuery(), getIncluded(), getExcluded()); ret.append(newQuery); } catch (final EFapsException | ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) { IndexSearch.LOG.error("Catched", e); ret.append(getCurrentQuery()); } return ret.toString(); }public static File print(final UIGrid _uiGrid) { File ret = null; final String clazzName = Configuration.getAttribute(ConfigAttribute.GRIDPRINTESJP); try { UIGrid.LOG.debug("Print method executed for {}", _uiGrid); final Class clazz = Class.forName(clazzName, false, EFapsClassLoader.getInstance()); final EventExecution event = (EventExecution) clazz.newInstance(); final Parameter param = new Parameter(); param.put(ParameterValues.PARAMETERS, Context.getThreadContext().getParameters()); param.put(ParameterValues.CLASS, _uiGrid); final Return retu = event.execute(param); if (retu != null) { ret = (File) retu.get(ReturnValues.VALUES); } } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) { UIGrid.LOG.error("Catched", e); } catch (final EFapsException e) { UIGrid.LOG.error("Catched", e); } return ret; }public GridRow getRow4Id(final String _rowId) throws EFapsException { final String[] rowIds = _rowId.split("-"); GridRow row = null; for (final String id : rowIds) { if (row == null) { row = getValues().get(Integer.parseInt(id)); } else { row = row.getChildren().get(Integer.parseInt(id)); } } return row; }public boolean isDateFilter(final IFilter _filter) throws EFapsException { final boolean ret; final Field field = Field.get(_filter.getFieldId()); // Explicitly set UIProvider if (field.getUIProvider() != null && (field.getUIProvider() instanceof DateTimeUI || field .getUIProvider() instanceof DateUI)) { ret = true; } else { final Attribute attr = getType().getAttribute(field.getAttribute()); if (attr == null) { ret = false; } else { final IUIProvider uiProvider = attr.getAttributeType().getUIProvider(); ret = uiProvider instanceof DateTimeUI || uiProvider instanceof DateUI; } } return ret; }public String getTitle() { String title = ""; try { final String key = getCommand().getTargetTitle() == null ? getCommand().getName() + ".Title" : getCommand().getTargetTitle(); title = DBProperties.getProperty(key); if (title != null && getCallInstance() != null) { final PrintQuery print = new PrintQuery(getCallInstance()); final ValueParser parser = new ValueParser(new StringReader(title)); final ValueList list = parser.ExpressionString(); list.makeSelect(print); if (print.execute()) { title = list.makeString(getCallInstance(), print, TargetMode.VIEW); } // Administration if (Configuration.getAttributeAsBoolean(Configuration.ConfigAttribute.SHOW_OID) && Context.getThreadContext() .getPerson() .isAssigned(Role.get(UUID .fromString("1d89358d-165a-4689-8c78-fc625d37aacd")))) { title = title + " " + getCallInstance().getOid(); } } } catch (final EFapsException | ParseException e) { throw new RestartResponseException(new ErrorPage(new EFapsException(this.getClass(), "", "Error reading the Title"))); } return title; }@Override public AbstractCommand getCommand() throws CacheReloadException { AbstractCommand cmd = Command.get(getCmdUUID()); if (cmd == null) { cmd = Menu.get(getCmdUUID()); } return cmd; }protected IFilter getFilter4Field(final Field _field) { final IFilter ret; switch (_field.getFilter().getType()) { case STATUS: case PICKLIST: ret = new ListFilter(_field.getId()); break; case FREETEXT: case FORM: ret = new MapFilter(_field.getId()); break; case CLASSIFICATION: ret = new ClassificationFilter(_field.getId()); break; case NONE: default: ret = new IFilter() { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; @Override public long getFieldId() { return _field.getId(); } }; break; } return ret; }@SuppressWarnings("unchecked") protected List getInstances() throws EFapsException { final List returns = getEventObject().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.INSTANCE, getCallInstance(), ParameterValues.CALL_INSTANCE, getCallInstance(), ParameterValues.PARAMETERS, Context.getThreadContext().getParameters(), ParameterValues.CLASS, this, ParameterValues.OTHERS, this.filterList); List ret = null; if (returns.size() < 1) { throw new EFapsException(UIGrid.class, "getInstanceList"); } else { final Object result = returns.get(0).get(ReturnValues.VALUES); if (result instanceof List) { ret = (List) result; } } return ret; }protected GridCell getCell(final GridColumn _column, final UIValue _uiValue, final Object _sortValue, final Map _fields) throws EFapsException { JSField jsField; if (_fields.containsKey(_uiValue.getField().getId())) { jsField = _fields.get(_uiValue.getField().getId()); } else { jsField = new JSField(_uiValue); final IComponentFactory fact = jsField.getFactory(); if (fact == null) { _fields.put(_uiValue.getField().getId(), null); jsField = null; } else { _fields.put(_uiValue.getField().getId(), jsField); if (fact instanceof DateUIFactory) { _column.setDataType("date"); } else if (fact instanceof DateTimeUIFactory) { _column.setDataType("datetime"); } else if (fact instanceof DecimalUIFactory || fact instanceof NumberUIFactory) { _column.setDataType("number"); } else if (fact instanceof BooleanUIFactory) { _column.setDataType("enum"); @SuppressWarnings("unchecked") final Map enumValues = (Map) _uiValue.getReadOnlyValue(TargetMode.VIEW); _column.setEnumValues(enumValues.keySet()); } } } final String value; if (jsField == null) { value = ""; } else { jsField.setValue(_uiValue); value = jsField.getFactory().getStringValue(jsField); } return new GridCell().setValue(value) .setSortValue(_sortValue) .setFieldConfig(_column.getFieldConfig()); }public void removeFilter(final UITableHeader _uiTableHeader) { this.filters.remove(_uiTableHeader.getFieldName()); final UITableHeader orig = getHeader4Id(_uiTableHeader.getFieldId()); if (orig != null) { orig.setFilterApplied(false); } storeFilters(); }private void storeFilters() { final Map sessFilter = new HashMap<>(); for (final Entry entry : this.filters.entrySet()) { sessFilter.put(entry.getKey(), entry.getValue()); } try { Context.getThreadContext().setSessionAttribute(getCacheKey(UITable.UserCacheKey.FILTER), sessFilter); } catch (final EFapsException e) { UITable.LOG.error("Error storing Filtermap for Table called by Command with UUID: {}", getCommandUUID(), e); } }private List getStatus4Type(final Type _type) throws CacheReloadException { final List ret = new ArrayList<>(); final StatusGroup grp = Status.get(_type.getUUID()); if (grp != null) { ret.addAll(grp.values()); } else { for (final Type type : _type.getChildTypes()) { ret.addAll(getStatus4Type(type)); } } return ret; }public List getFilterPickList(final UITableHeader _uitableHeader) throws EFapsException { final List ret = new ArrayList<>(); for (final UIRow rowmodel : this.values) { for (final IFilterable cell : rowmodel.getCells()) { if (cell.belongsTo(_uitableHeader.getFieldId())) { final String value = cell.getPickListValue(); if (!ret.contains(value)) { ret.add(value); } break; } } } Collections.sort(ret); return ret; }public TableFilter getFilter(final UITableHeader _uitableHeader) throws EFapsException { TableFilter ret = this.filters.get(_uitableHeader.getFieldName()); if (ret != null && ret.getUiTableHeader() == null) { ret = new TableFilter(_uitableHeader); this.filters.put(_uitableHeader.getFieldName(), ret); } return ret; }public void addFilterClassifcation(final UITableHeader _uitableHeader, final UIClassification _uiClassification) throws EFapsException { final TableFilter filter = new TableFilter(_uitableHeader, _uiClassification); this.filters.put(_uitableHeader.getFieldName(), filter); final UITableHeader orig = getHeader4Id(_uitableHeader.getFieldId()); if (orig != null) { orig.setFilterApplied(true); } storeFilters(); }public void addFilterList(final UITableHeader _uitableHeader, final Set _list) { final TableFilter filter = new TableFilter(_uitableHeader, _list); this.filters.put(_uitableHeader.getFieldName(), filter); final UITableHeader orig = getHeader4Id(_uitableHeader.getFieldId()); if (orig != null) { orig.setFilterApplied(true); } storeFilters(); }@SuppressWarnings("unchecked") protected List getInstanceList() throws EFapsException { // get the filters that must be applied against the database final IFilterList filterList = new FilterList(); final Iterator> iter = this.filters.entrySet().iterator(); this.filterTempCache.clear(); while (iter.hasNext()) { final Entry entry = iter.next(); if (entry.getValue().getUiTableHeader() == null || entry.getValue().getUiTableHeader() != null && entry.getValue().getUiTableHeader().getFilter().getBase().equals(FilterBase.DATABASE)) { filterList.add(entry.getValue().getFilter()); } this.filterTempCache.put(entry.getKey(), entry.getValue()); iter.remove(); } final List ret = getCommand().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.INSTANCE, getInstance(), ParameterValues.PARAMETERS, Context.getThreadContext().getParameters(), ParameterValues.CLASS, this, ParameterValues.OTHERS, filterList); List lists = null; if (ret.size() < 1) { throw new EFapsException(UITable.class, "getInstanceList"); } else { lists = (List) ret.get(0).get(ReturnValues.VALUES); } return lists; }private void initialise() throws EFapsException { final AbstractCommand command = getCommand(); if (command == null) { setShowCheckBoxes(false); } else { // set target table if (command.getTargetTable() != null) { setTableUUID(command.getTargetTable().getUUID()); if (Context.getThreadContext().containsSessionAttribute(getCacheKey(UITable.UserCacheKey.FILTER))) { @SuppressWarnings("unchecked") final Map sessfilter = (Map) Context.getThreadContext() .getSessionAttribute(getCacheKey(UITable.UserCacheKey.FILTER)); for (final Field field : command.getTargetTable().getFields()) { if (sessfilter.containsKey(field.getName())) { final TableFilter filter = sessfilter.get(field.getName()); filter.setHeaderFieldId(field.getId()); this.filters.put(field.getName(), filter); } } } else { // add the filter here, if it is a required filter or a default value is set, that must be // applied against the database for (final Field field : command.getTargetTable().getFields()) { if (field.hasAccess(getMode(), getInstance(), getCommand(), getInstance()) && (field.getFilter().isRequired() || field.getFilter().getDefaultValue() != null && !field.getFilter().getDefaultValue().isEmpty()) && field.getFilter().getBase().equals(FilterBase.DATABASE)) { this.filters.put(field.getName(), new TableFilter(field.getId())); } } } } // set default sort if (command.getTargetTableSortKey() != null) { setSortKeyInternal(command.getTargetTableSortKey()); setSortDirection(command.getTargetTableSortDirection()); } setEnforceSorted("true".equalsIgnoreCase(command.getProperty("TargetEnforceSorted"))); setShowCheckBoxes(command.isTargetShowCheckBoxes()); // get the User specific Attributes if exist overwrite the defaults try { if (Context.getThreadContext().containsUserAttribute( getCacheKey(UITable.UserCacheKey.SORTKEY))) { setSortKeyInternal(Context.getThreadContext().getUserAttribute( getCacheKey(UITable.UserCacheKey.SORTKEY))); } if (Context.getThreadContext().containsUserAttribute( getCacheKey(UITable.UserCacheKey.SORTDIRECTION))) { setSortDirection(SortDirection.getEnum(Context.getThreadContext() .getUserAttribute(getCacheKey(UITable.UserCacheKey.SORTDIRECTION)))); } } catch (final EFapsException e) { // we don't throw an error because this are only Usersettings UITable.LOG.error("error during the retrieve of UserAttributes", e); } } }private CharSequence getSubMenues(final Instance _instance) throws EFapsException { HelpServlet.LOG.debug("Reading Submenues for OID: {}", _instance.getOid()); final StringBuilder ret = new StringBuilder(); final QueryBuilder queryBldr = new QueryBuilder(Type.get("Admin_Help_Menu2Menu")); queryBldr.addWhereAttrEqValue("FromLink", _instance.getId()); final MultiPrintQuery multi = queryBldr.getPrint(); multi.addSelect("linkto[ToLink].attribute[Name]", "linkto[ToLink].oid"); multi.execute(); final Map subs = new TreeMap(); while (multi.next()) { final String name = multi.getSelect("linkto[ToLink].attribute[Name]"); final String oid = multi.getSelect("linkto[ToLink].oid"); final PrintQuery print = new PrintQuery(oid); print.addSelect("linkfrom[Admin_Help_Menu2Wiki#FromLink].linkto[ToLink].attribute[Name]"); print.execute(); String link = ""; final Object links = print .getSelect("linkfrom[Admin_Help_Menu2Wiki#FromLink].linkto[ToLink].attribute[Name]"); if (links instanceof List) { for (final Object alink : (List) links) { link = link + ":" + alink; } } else { link = (String) links; } HelpServlet.LOG.debug(" Submenue '{}' with OID: {}", name, print.getCurrentInstance().getOid()); final StringBuilder menu = new StringBuilder() .append("
  • ") .append(DBProperties.getProperty(name + ".Label")).append("
  • ") .append(getSubMenues(print.getCurrentInstance())); subs.put(multi.getCurrentInstance().getId(), menu.toString()); } if (!subs.isEmpty()) { ret.append("
      "); for (final String sub : subs.values()) { ret.append(sub).append("\n"); } ret.append("
    "); } return ret; }private String getMenu() throws EFapsException { HelpServlet.LOG.debug("Reading Main Help Menu"); final StringBuilder ret = new StringBuilder(); ret.append("
      "); final QueryBuilder queryBldr = new QueryBuilder(Type.get("Admin_Help_Menu")); // Admin_Help_MainMenu queryBldr.addWhereAttrEqValue("UUID", "dead549e-5cc6-49f9-9a79-8e33aa139f6d"); final MultiPrintQuery multi = queryBldr.getPrint(); multi.addAttribute("Name"); multi.addSelect("linkfrom[Admin_Help_Menu2Wiki#FromLink].linkto[ToLink].attribute[Name]"); multi.execute(); if (multi.next()) { final String name = multi.getAttribute("Name"); String link = ""; final Object links = multi .getSelect("linkfrom[Admin_Help_Menu2Wiki#FromLink].linkto[ToLink].attribute[Name]"); if (links instanceof List) { for (final Object alink : (List) links) { link = link + ":" + alink; } } else { link = (String) links; } ret.append("
    • ").append(DBProperties.getProperty(name + ".Label")) .append("
    • "); ret.append(getSubMenues(multi.getCurrentInstance())); } ret.append("
    "); return ret.toString(); }@Override protected void doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException { String fileName = _req.getRequestURI(); fileName = fileName.substring(fileName.lastIndexOf('/') + 1); try { final Person pers = Context.getThreadContext().getPerson(); if (pers != null) { final File file = getFile(pers.getId(), fileName); if (file != null && file.exists()) { _resp.setContentType(getServletContext().getMimeType(file.getName())); _resp.setContentLength((int) file.length()); _resp.setDateHeader("Last-Modified", System.currentTimeMillis()); _resp.setDateHeader("Expires", System.currentTimeMillis()); _resp.addHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); _resp.setHeader("Cache-Control", "max-age=10"); final FileInputStream input = new FileInputStream(file); IOUtils.copy(input, _resp.getOutputStream()); } } } catch (final EFapsException e) { FileServlet.LOG.error("EFapsException", e); throw new ServletException(e); } catch (final IOException e) { FileServlet.LOG.error("IOException", e); throw new ServletException(e); } }public static DateTimeFormatter getDateTimeFormatter() throws EFapsException { final String formatStr = Configuration.getAttribute(Configuration.ConfigAttribute.FORMAT_DATETIME); final DateTimeFormatter ret; if (formatStr.matches("^[S,M,L,F,-]{2}$")) { ret = DateTimeFormat.forStyle(formatStr); } else { ret = DateTimeFormat.forPattern(formatStr); } return ret.withLocale(Context.getThreadContext().getLocale()); }@SuppressWarnings("unchecked") @Override public Iterator> getChoices(final String _input) { final List> retList = new ArrayList>(); try { final AbstractUIPageObject pageObject = (AbstractUIPageObject) getPage().getDefaultModelObject(); final Map uiID2Oid = pageObject == null ? null : pageObject.getUiID2Oid(); final List returns = this.autoComplete.getAutoCompletion(_input, uiID2Oid); for (final Return aReturn : returns) { final Object ob = aReturn.get(ReturnValues.VALUES); if (ob instanceof List) { retList.addAll((Collection>) ob); } } } catch (final EFapsException e) { AutoCompleteComboBox.LOG.error("Error in getChoice()", e); } return retList.iterator(); }protected void initialize(final IModel _model, final EFapsContentReference _reference, final String _label) { final ButtonLink link; if (_model == null) { link = new ButtonLink<>("button"); } else { link = new ButtonLink<>("button", _model); } add(link); link.add(new ButtonImage("icon", _reference)); link.add(new Label("label", _label == null ? "" : _label)); }@Override protected void respond(final AjaxRequestTarget _target) { final StringValue horizontal = getComponent().getRequest().getRequestParameters().getParameterValue( AjaxStorePositionBehavior.PARAMETER_HORIZONTALPOSITION); final StringValue verticalTmp = getComponent().getRequest().getRequestParameters().getParameterValue( AjaxStorePositionBehavior.PARAMETER_VERTICALPOSITION); if (!horizontal.isNull()) { Configuration.setAttribute(ConfigAttribute.SPLITTERPOSHORIZONTAL, horizontal.toString()); } if (!verticalTmp.isNull()) { Configuration.setAttribute(ConfigAttribute.SPLITTERPOSVERTICAL, verticalTmp.toString()); } }public boolean isVisible() { initialize(); boolean ret = false; try { ret = this.snipplet.isVisible(); } catch (final EFapsBaseException e) { EsjpInvoker.LOG.error("EFapsException", e); } return ret; }public static FieldConfiguration getSimFieldConfig(final String _fieldName) { final Field field = new Field(0, "", _fieldName); final FieldConfiguration ret = new FieldConfiguration(0) { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; @Override public Field getField() { return field; } }; return ret; }public boolean isTableField() { boolean ret = false; try { ret = getField().getCollection() instanceof Table; } catch (final CacheReloadException e) { LOG.error("CacheReloadException", e); } return ret; }public String evalLabel(final UIValue _uiValue, final Instance _fieldInst) throws CacheReloadException { final String key; if (getField().getLabel() == null) { if (_uiValue != null && _uiValue.getAttribute() != null) { if (_fieldInst != null && _fieldInst.isValid() && _fieldInst.getType() .getAttribute(_uiValue.getAttribute().getName()) != null) { key = _fieldInst.getType().getAttribute(_uiValue.getAttribute().getName()).getLabelKey(); } else if (_uiValue.getInstance() != null && _uiValue.getInstance().getType() .getAttribute(_uiValue.getAttribute().getName()) != null) { key = _uiValue.getInstance().getType().getAttribute(_uiValue.getAttribute().getName()) .getLabelKey(); } else { key = _uiValue.getAttribute().getLabelKey(); } } else { key = FieldConfiguration.class.getName() + ".NoLabel"; } } else { key = getField().getLabel(); } this.label = DBProperties.getProperty(key); return this.label; }public int getWidthWeight() { int ret = 1; if (!isFixedWidth() && hasProperty(UIFormFieldProperty.WIDTH)) { ret = Integer.valueOf(getProperty(UIFormFieldProperty.WIDTH)); } return ret; }private void addBehaviors() { if (this.uiField.getFieldConfiguration().getField().hasEvents(EventType.UI_FIELD_UPDATE)) { final List events = this.uiField.getFieldConfiguration().getField().getEvents(EventType.UI_FIELD_UPDATE); String eventName = "change"; for (final EventDefinition event : events) { eventName = event.getProperty("Event") == null ? "change" : event.getProperty("Event"); } add(new AjaxFieldUpdateBehavior(eventName, Model.of(this.uiField), false) { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; @Override protected void onSubmit(final AjaxRequestTarget _target) { // add the previous value as a parameter final DropDownOption option = (DropDownOption) getDefaultModelObject(); try { if (option != null) { Context.getThreadContext().getParameters().put( getFieldConfig().getName() + "_eFapsPrevious", new String[] { option.getValue() }); } } catch (final EFapsException e) { DropDownField.LOG.error("EFapsException", e); } super.onSubmit(_target); DropDownField.this.converted = false; updateModel(); DropDownField.this.converted = false; } }); } add(new AttributeAppender("style", "text-align:" + getFieldConfig().getAlign(), ";")); // add the width only if not in a table if (getFieldConfig().hasProperty(UIFormFieldProperty.WIDTH) && !getFieldConfig().isTableField()) { add(new AttributeAppender("style", "width:" + getFieldConfig().getWidth(), ";")); } }public List executeEvents(final EventType _eventType, final Object... _objectTuples) throws EFapsException { List ret = new ArrayList<>(); final AbstractCommand command; if (this.callingCmdUUID == null) { command = this.getCommand(); } else { command = getCallingCommand(); } if (command.hasEvents(_eventType)) { final Parameter param = new Parameter(); if (_objectTuples != null) { // add all parameters for (int i = 0; i < _objectTuples.length; i += 2) { if (i + 1 < _objectTuples.length && _objectTuples[i] instanceof ParameterValues) { param.put((ParameterValues) _objectTuples[i], _objectTuples[i + 1]); } } } param.put(ParameterValues.PARAMETERS, Context.getThreadContext().getParameters()); if (getInstance() != null) { final String[] contextoid = { getInstanceKey() }; Context.getThreadContext().getParameters().put("oid", contextoid); param.put(ParameterValues.CALL_INSTANCE, getInstance()); param.put(ParameterValues.INSTANCE, getInstance()); } ret = command.executeEvents(_eventType, param); } return ret; }public AbstractCommand getCallingCommand() throws CacheReloadException { AbstractCommand cmd = null; if (getCallingCommandUUID() != null) { cmd = Command.get(getCallingCommandUUID()); if (cmd == null) { cmd = Menu.get(getCallingCommandUUID()); } } return cmd; }protected void initialize(final UUID _commandUUID, final String _openerId) throws CacheReloadException { this.openerId = _openerId; if (_commandUUID != null) { final AbstractCommand command = getCommand(_commandUUID); this.cmdUUID = command.getUUID(); setMode(command.getTargetMode()); this.target = command.getTarget(); this.submit = command.isSubmit(); if (command.getTargetSearch() != null && !(this instanceof UIMenuItem)) { this.callingCmdUUID = this.cmdUUID; this.cmdUUID = command.getTargetSearch().getDefaultCommand().getUUID(); setMode(TargetMode.SEARCH); if (command.hasEvents(EventType.UI_COMMAND_EXECUTE)) { this.submit = true; } } } }private static Cache getCache() { // before the first use the Entity used for indexing must be added if (!((EmbeddedCacheManager) InfinispanCache.get().getContainer()).cacheExists(RegistryManager.SESSIONCACHE)) { final Configuration config = ((EmbeddedCacheManager) InfinispanCache.get().getContainer()) .getCacheConfiguration(RegistryManager.SESSIONCACHE); final ConfigurationBuilder bldr = new ConfigurationBuilder().read(config); bldr.indexing().addIndexedEntity(UserSession.class); ((EmbeddedCacheManager) InfinispanCache.get().getContainer()).undefineConfiguration( RegistryManager.SESSIONCACHE); ((EmbeddedCacheManager) InfinispanCache.get().getContainer()).defineConfiguration( RegistryManager.SESSIONCACHE, bldr.build()); } return InfinispanCache.get().getIgnReCache(RegistryManager.SESSIONCACHE); }public static IWebSocketConnection getConnection4Session(final String _sessionId) { IWebSocketConnection ret = null; if (RegistryManager.getCache().containsKey(_sessionId)) { final UserSession userSession = RegistryManager.getCache().get(_sessionId); if (userSession.getConnectionKey() != null) { final IWebSocketConnectionRegistry registry = WebSocketSettings.Holder.get(EFapsApplication.get()) .getConnectionRegistry(); ret = registry.getConnection(EFapsApplication.get(), userSession.getSessionId(), userSession.getConnectionKey()); } } return ret; }public static List getConnections4User(final String _login) { final List ret = new ArrayList<>(); final SearchManager searchManager = Search.getSearchManager(RegistryManager.getCache()); final QueryBuilder qbldr = searchManager.buildQueryBuilderForClass(UserSession.class).get(); final CacheQuery query = searchManager.getQuery(qbldr.keyword().onField("userName").matching(_login) .createQuery()); try (ResultIterator iter = query.iterator()) { while (iter.hasNext()) { final UserSession userSession = (UserSession) iter.next(); if (userSession.getConnectionKey() != null) { final IWebSocketConnectionRegistry registry = WebSocketSettings.Holder.get(EFapsApplication.get()) .getConnectionRegistry(); final IWebSocketConnection conn = registry.getConnection(EFapsApplication.get(), userSession .getSessionId(), userSession.getConnectionKey()); if (conn != null) { ret.add(conn); } } } } return ret; }public static Set getUsers() { final Set ret = new HashSet<>(); for (final UserSession userSession : RegistryManager.getCache().values()) { ret.add(userSession.getUserName()); } return ret; }public static void removeUserSession(final String _sessionId) { if (RegistryManager.getCache().containsKey(_sessionId)) { RegistryManager.registerLogout4History( RegistryManager.getCache().get(_sessionId).getUserName(), _sessionId); RegistryManager.getCache().remove(_sessionId); } }public static void invalidateSession(final String _sessionId) { if (RegistryManager.getCache().containsKey(_sessionId)) { RegistryManager.getCache().get(_sessionId).markInvalid(); } }public static void addMsgConnection(final String _sessionId, final IKey _key) { if (RegistryManager.getCache().containsKey(_sessionId)) { RegistryManager.getCache().get(_sessionId).setConnectionKey(_key); } RegistryManager.LOG.debug("Added Message Connection for Session: {}", _sessionId); }public static void registerActivity(final EFapsSession _session) { if (_session.isLogedIn() && RegistryManager.getCache().containsKey(_session.getId())) { final UserSession userSession = RegistryManager.getCache().get(_session.getId()); if (userSession.isInvalidated()) { _session.invalidate(); } else { userSession.registerActivity(); } } }public static void registerUserSession(final String _userName, final String _sessionId) { if (EFapsApplication.getMaxInactiveInterval() > 0) { RegistryManager.getCache().put(_sessionId, new UserSession().setUserName(_userName).setSessionId(_sessionId), -1, TimeUnit.MINUTES, EFapsApplication.getMaxInactiveInterval() + 600, TimeUnit.SECONDS); } else { RegistryManager.getCache().put(_sessionId, new UserSession().setUserName(_userName).setSessionId(_sessionId)); } RegistryManager.registerLogin4History(_userName, _sessionId); }@Override public void onEndRequest(final RequestCycle _cycle) { final EFapsSession session = getEFapsSession(_cycle.getRequest()); if (session != null) { session.closeContext(); } EFapsRequestCycleListener.LOG.debug("End of Request."); }@Override public void onBeginRequest(final RequestCycle _cycle) { final EFapsSession session = getEFapsSession(_cycle.getRequest()); if (session != null) { session.openContext(); RegistryManager.registerActivity(session); } EFapsRequestCycleListener.LOG.debug("Begin of Request."); }private EFapsSession getEFapsSession(final Request _request) { final ISessionStore sessionStore = WebApplication.get().getSessionStore(); final EFapsSession session = (EFapsSession) sessionStore.lookup(_request); return session; }@Override public void onClick() { Instance instance = null; final AbstractUIField uiField = super.getModelObject(); if (uiField.getInstanceKey() != null) { Menu menu = null; try { instance = uiField.getInstance(); menu = Menu.getTypeTreeMenu(instance.getType()); } catch (final EFapsException e) { throw new RestartResponseException(new ErrorPage(e)); } if (menu == null) { final Exception ex = new Exception("no tree menu defined for type " + instance.getType().getName()); throw new RestartResponseException(new ErrorPage(ex)); } Page page; try { page = new ContentContainerPage(menu.getUUID(), uiField.getInstanceKey(), getPage() instanceof StructurBrowserPage); } catch (final EFapsException e) { page = new ErrorPage(e); } this.setResponsePage(page); } }@Override protected void onComponentTag(final ComponentTag _tag) { _tag.setName("a"); super.onComponentTag(_tag); onComponentTagInternal(_tag); }public static void removePages4Session(final String _sessionId) { final AdvancedCache cache = InfinispanCache.get().getIgnReCache( InfinispanPageStore.PAGECACHE); final QueryFactory queryFactory = Search.getQueryFactory(cache); final Query query = queryFactory.from(StoredPage.class).having("sessionId").eq(_sessionId).build(); query.list().forEach(storedPage -> cache.remove(storedPage.getSessionId() + "::" + storedPage .getPage().getPageId())); }public boolean requeryLabel() { boolean ret = false; try { String labelTmp = DBProperties.getProperty(getCommand().getLabel()); if (getInstance() != null) { final ValueParser parser = new ValueParser(new StringReader(labelTmp)); final ValueList list = parser.ExpressionString(); if (list.getExpressions().size() > 0) { final PrintQuery print = new PrintQuery(getInstance()); list.makeSelect(print); if (print.execute()) { labelTmp = list.makeString(getInstance(), print, getMode()); } } } ret = !labelTmp.equals(this.label); this.label = labelTmp; } catch (final EFapsException e) { throw new RestartResponseException(new ErrorPage(e)); } catch (final ParseException e) { throw new RestartResponseException(new ErrorPage(e)); } return ret; }private void initialize() throws CacheReloadException { final AbstractCommand command = super.getCommand(); this.image = command.getIcon(); this.reference = command.getReference(); this.askUser = command.isAskUser(); this.windowHeight = command.getWindowHeight(); this.windowWidth = command.getWindowWidth(); this.defaultSelected = command.isDefaultSelected(); this.description = ""; this.submitSelectedRows = command.getSubmitSelectedRows(); requeryLabel(); try { if (command instanceof AbstractMenu) { for (final AbstractCommand subCmd : ((AbstractMenu) command).getCommands()) { if (subCmd != null && subCmd.hasAccess(getMode(), getInstance())) { if (subCmd.getTargetMode().equals(TargetMode.SEARCH)) { final UISearchItem child = new UISearchItem(subCmd.getUUID(), getInstanceKey()); child.setParent(this); this.children.add(child); } else { final UIMenuItem child = new UIMenuItem(subCmd.getUUID(), getInstanceKey()); child.setParent(this); this.children.add(child); try { if (Context.getThreadContext().containsSessionAttribute(child.getCacheKey())) { final Boolean expandTmp = (Boolean) Context.getThreadContext().getSessionAttribute( child.getCacheKey()); child.setExpanded(expandTmp); } } catch (final EFapsException e) { UIMenuItem.LOG.error("Error retrieving Session info for UIMenuItem called by Command " + "with UUID: {}", getCommandUUID(), e); } } } } } if (Configuration.getAttributeAsBoolean(ConfigAttribute.USER_MENUACT) && UUID.fromString(Configuration.getAttribute(ConfigAttribute.USER_MENUMENU)).equals( getCommandUUID())) { for (final String key : UsageRegistry.getKeyList()) { addChild4Key(key); } } } catch (final EFapsException e) { throw new RestartResponseException(new ErrorPage(e)); } }public String getTypeImage() throws EFapsException { String ret = null; if (getInstance() != null) { final Image imageTmp = Image.getTypeIcon(getInstance().getType()); if (imageTmp != null) { ret = imageTmp.getName(); } } return ret; }private boolean hasAccess2Menu(final AbstractUIField _uiField) throws EFapsException { final Menu menu = Menu.getTypeTreeMenu(_uiField.getInstance().getType()); return menu != null && menu.hasAccess(_uiField.getParent().getMode(), _uiField.getInstance()) && (!((AbstractUIPageObject) _uiField.getParent()).getAccessMap().containsKey( _uiField.getInstance()) || ((AbstractUIPageObject) _uiField.getParent()).getAccessMap().containsKey( _uiField.getInstance()) && ((AbstractUIPageObject) _uiField.getParent()).getAccessMap().get( _uiField.getInstance())); }private boolean isCheckOut(final AbstractUIField _uiField) { return StringUtils.containsIgnoreCase(_uiField.getFieldConfiguration().getField().getReference(), HRef.CHECKOUT.toString()); }public static Set of(final ResourceType first, final ResourceType... rest) { final Set set = new HashSet<>(); set.add(first); set.addAll(Arrays.asList(rest)); return set; }public static Set complementOf(final Set resourceTypes) { final Set set = allOf(); set.removeAll(resourceTypes); return set; }@Override public void init(final FilterConfig _filterConfig) throws ServletException { super.init(_filterConfig); final String root = "/" + _filterConfig.getServletContext().getServletContextName() + "/"; this.notLoggedInForward = "/" + _filterConfig.getInitParameter(TransactionFilter.INIT_PARAM_URL_LOGIN_PAGE); if (this.notLoggedInForward == null || this.notLoggedInForward.length() == 0) { throw new ServletException("Init parameter " + "'" + TransactionFilter.INIT_PARAM_URL_LOGIN_PAGE + "' not defined"); } this.exludeUris.add((root + this.notLoggedInForward).replaceAll("//+", "/")); this.exludeUris.add((root + "/servlet/login").replaceAll("//+", "/")); final ServiceLoader serviceLoaderLogins = ServiceLoader.load(ILoginProvider.class); for (final ILoginProvider loginProvider : serviceLoaderLogins) { LOG.info("[TransactionFilter] registered: {}", loginProvider); this.loginProviders .add(loginProvider); } }private void showDialog(final AjaxRequestTarget _target, final String _key, final boolean _isSniplett, final boolean _goOnButton) { final ModalWindowContainer modal = ((AbstractContentPage) getPage()).getModal(); modal.setInitialWidth(350); modal.setInitialHeight(200); modal.setPageCreator(new ModalWindow.PageCreator() { private static final long serialVersionUID = 1L; @Override public Page createPage() { return new DialogPage(((AbstractContentPage) getPage()).getPageReference(), _key, _isSniplett, _goOnButton); } }); if (_goOnButton) { modal.setWindowClosedCallback(new WindowClosedCallback() { private static final long serialVersionUID = 1L; @Override public void onClose(final AjaxRequestTarget _target) { if (AjaxSubmitCloseButton.this.validated) { _target.appendJavaScript(getExecuteScript()); } } }); } modal.show(_target); }private List getFormPanels() { AjaxSubmitCloseButton.LOG.trace("entering getFormPanels"); final List ret = new ArrayList<>(); final Iterator iterator = getForm().iterator(); while (iterator.hasNext()) { final Object object = iterator.next(); if (object instanceof WebMarkupContainer) { final Iterator iterator2 = ((WebMarkupContainer) object).iterator(); while (iterator2.hasNext()) { final Object object2 = iterator2.next(); if (object2 instanceof FormPanel) { ret.add((FormPanel) object2); } } } } return ret; }private boolean checkForRequired(final AjaxRequestTarget _target) { AjaxSubmitCloseButton.LOG.trace("entering checkForRequired"); boolean ret = true; if (!(getForm().getParent().getDefaultModel() instanceof TableModel)) { final IRequestParameters parameters = getRequest().getRequestParameters(); final List panels = getFormPanels(); for (final FormPanel panel : panels) { for (final Entry entry : panel.getRequiredComponents().entrySet()) { final StringValue value = parameters.getParameterValue(entry.getKey()); if (value.isNull() || value.isEmpty()) { final Label label = entry.getValue(); label.add(AttributeModifier.replace("class", "eFapsFormLabelRequiredForce")); _target.add(label); ret = false; } } } if (!ret) { showDialog(_target, "MandatoryDialog", false, false); } } return ret; }private boolean validateForm(final AjaxRequestTarget _target, final Map _other, final List _classifications) throws EFapsException { AjaxSubmitCloseButton.LOG.trace("entering validateForm"); boolean ret = true; if (!this.validated) { final TargetMode mode; if (getForm().getPage().getDefaultModelObject() instanceof IModeObject) { mode = ((IModeObject) getForm().getPage().getDefaultModelObject()).getMode(); } else { mode = TargetMode.UNKNOWN; } final List tuplets = new ArrayList<>(); tuplets.add(ParameterValues.OTHERS); tuplets.add(_other); tuplets.add(ParameterValues.ACCESSMODE); tuplets.add(mode); if (getPage().getDefaultModelObject() instanceof AbstractUIPageObject) { tuplets.add(ParameterValues.OIDMAP4UI); tuplets.add(((AbstractUIPageObject) getForm().getPage().getDefaultModelObject()).getUiID2Oid()); } if (_classifications.size() > 0) { tuplets.add(ParameterValues.CLASSIFICATIONS); tuplets.add(_classifications); } final List returns = ((ICmdUIObject) getPage().getDefaultModelObject()) .executeEvents(EventType.UI_VALIDATE, tuplets.toArray()); boolean goOn = true; boolean sniplett = false; String key = ""; for (final Return oneReturn : returns) { if (oneReturn.get(ReturnValues.VALUES) != null || oneReturn.get(ReturnValues.SNIPLETT) != null) { if (oneReturn.get(ReturnValues.VALUES) != null) { key = key + (String) oneReturn.get(ReturnValues.VALUES); } else { key = key + (String) oneReturn.get(ReturnValues.SNIPLETT); sniplett = true; } ret = false; if (oneReturn.get(ReturnValues.TRUE) == null) { goOn = false; } } else { if (oneReturn.get(ReturnValues.TRUE) == null) { ret = false; // that is the case if it is wrong configured! } } } if (!ret) { showDialog(_target, key, sniplett, goOn); } } return ret; }private boolean evalFormElement(final AjaxRequestTarget _target, final StringBuilder _html, final UIForm _uiform) throws EFapsException { AjaxSubmitCloseButton.LOG.trace("entering evalFormElement"); boolean ret = true; for (final Element element : _uiform.getElements()) { if (element.getType().equals(ElementType.FORM)) { final FormElement formElement = (FormElement) element.getElement(); for (final Iterator uiRowIter = formElement.getRowModels(); uiRowIter.hasNext();) { for (final IUIElement object : uiRowIter.next().getValues()) { } } } else if (element.getType().equals(ElementType.SUBFORM)) { final UIFieldForm uiFieldForm = (UIFieldForm) element.getElement(); final boolean tmp = evalFormElement(_target, _html, uiFieldForm); ret = ret ? tmp : ret; } else if (element.getType().equals(ElementType.TABLE)) { final UIFieldTable uiFieldTable = (UIFieldTable) element.getElement(); final List headers = uiFieldTable.getHeaders(); for (final UIRow uiRow : uiFieldTable.getValues()) { uiRow.getUserinterfaceId(); final Iterator headerIter = headers.iterator(); for (final IFilterable filterable : uiRow.getCells()) { headerIter.next(); } } } } return ret; }private boolean validateFieldValues(final AjaxRequestTarget _target) throws EFapsException { AjaxSubmitCloseButton.LOG.trace("entering validateFieldValues"); boolean ret = true; final ICmdUIObject uiobject = (ICmdUIObject) getPage().getDefaultModelObject(); final StringBuilder html = new StringBuilder(); html.append("
    "); if (uiobject instanceof UIForm) { final UIForm uiform = (UIForm) uiobject; ret = evalFormElement(_target, html, uiform); } if (!ret) { html.append("
    "); showDialog(_target, html.toString(), true, false); } return ret; }@Override public void onError(final AjaxRequestTarget _target) { final FeedbackCollector collector = new FeedbackCollector(getForm().getPage()); final List msgs = collector.collect(); final ErrorMessageResource msgResource = new ErrorMessageResource(); final StringBuilder html = new StringBuilder() .append(""); for (final FeedbackMessage msg : msgs) { if (!(msg.getReporter() instanceof Form)) { if (msg.getReporter() instanceof AutoCompleteComboBox) { final StringBuilder js = new StringBuilder() .append("domClass.add(dom.byId('").append(msg.getReporter().getMarkupId()) .append("').parentNode, 'invalid');"); _target.prependJavaScript(DojoWrapper.require(js, DojoClasses.dom, DojoClasses.domClass)); } else { msg.getReporter().add(AttributeModifier.append("class", "invalid")); _target.add(msg.getReporter()); } } Serializable warn = null; if (msg.getMessage() instanceof ValidationErrorFeedback) { // look if a message was set warn = ((ValidationErrorFeedback) msg.getMessage()).getMessage(); // still no message, create one if (warn == null) { warn = ((ValidationErrorFeedback) msg.getMessage()).getError().getErrorMessage(msgResource); } } else { warn = String.valueOf(msg.getMessage()); } html.append(""); if (msg.getReporter() instanceof IFieldConfig) { html.append(""); } else { html.append(""); } msg.getReporter().getFeedbackMessages().clear(); } html.append("
    ") .append(((IFieldConfig) msg.getReporter()).getFieldConfig().getLabel()) .append(":") .append(warn).append("") .append(warn).append("
    "); showDialog(_target, html.toString(), true, false); // after every commit the fieldset must be reseted getForm().getPage().visitChildren(SetDataGrid.class, (_setDataGrid, _visit) -> { final UIFieldSet fieldSet = (UIFieldSet) _setDataGrid.getDefaultModelObject(); fieldSet.resetIndex(); }); getForm().getPage().visitChildren(DropDownField.class, (_dropDown, _visit) -> ((DropDownField) _dropDown).setConverted(false)); }private boolean convertFieldValues(final AjaxRequestTarget _target) throws EFapsException { AjaxSubmitCloseButton.LOG.trace("entering convertFieldValues"); final EFapsRequestParametersAdapter parameters = (EFapsRequestParametersAdapter) getRequest() .getRequestParameters(); final FormContainer frmContainer = (FormContainer) getForm(); for (final IValueConverter converter : frmContainer.getValueConverters()) { converter.convertValue(parameters); } return true; }private boolean convertDateFieldValues(final AjaxRequestTarget _target) throws EFapsException { AjaxSubmitCloseButton.LOG.trace("entering convertDateFieldValues"); boolean ret = true; final StringBuilder html = new StringBuilder(); html.append(""); final EFapsRequestParametersAdapter parameters = (EFapsRequestParametersAdapter) getRequest().getRequestParameters(); final Set names = parameters.getParameterNames(); for (final DateTimePanel datepicker : ((FormContainer) getForm()).getDateComponents()) { if (names.contains(datepicker.getDateFieldName())) { final List date = parameters.getParameterValues(datepicker.getDateFieldName()); final List hour = parameters.getParameterValues(datepicker.getHourFieldName()); final List minute = parameters.getParameterValues(datepicker.getMinuteFieldName()); final List ampm = parameters.getParameterValues(datepicker.getAmPmFieldName()); ret = datepicker.validate(date, hour, minute, ampm, html); if (ret) { parameters.setParameterValues(datepicker.getFieldName(), datepicker.getDateAsString(date, hour, minute, ampm)); } else { break; } } } if (!ret) { html.append("
    "); showDialog(_target, html.toString(), true, false); } return ret; }@Override public MarkupContainer add(final Component... _childs) { MarkupContainer ret = null; for (final Component child : _childs) { if (child instanceof HtmlHeaderContainer) { ret = add2Page(child); } else { ret = body.add(_childs); } } return ret; }@SuppressWarnings("unchecked") protected void addComponents(final FormContainer _form) throws EFapsException { this.form = _form; add(new KeepAliveBehavior()); // set the title for the Page add2Page(new Label("pageTitle", DBProperties.getProperty("Logo.Version.Label"))); add(new SetMessageStatusBehavior()); add(this.modal); final AbstractUIObject uiObject = (AbstractUIObject) super.getDefaultModelObject(); add(new HeadingPanel("titel", Model.of(new UIHeading(uiObject.getTitle())))); IModel model = null; if (uiObject.getMode() == TargetMode.SEARCH && uiObject.getCallingCommandUUID() != null && uiObject instanceof UIForm) { model = Model.of(new UISearchItem(uiObject.getCallingCommand() .getTargetSearch().getUUID())); } else if (uiObject.getCommand().getTargetMenu() != null) { model = Model.of(new UIMenuItem(uiObject.getCommand().getTargetMenu() .getUUID(), uiObject.getInstanceKey())); } add(new MenuBarPanel("menu", model)); add(new HelpLink("help", Model.of(uiObject.getCommand().getId()))); final WebMarkupContainer footerpanel; if (uiObject.isCreateMode() || uiObject.isEditMode() || uiObject.isSearchMode() || uiObject.isOpenedByPicker()) { footerpanel = new FooterPanel("footer", (IModel) getDefaultModel(), this.modalWindow); } else { footerpanel = new WebMarkupContainer("footer"); footerpanel.setVisible(false); } add(footerpanel); }public static IModel getModel(final Long _cmdId, final Instance _instance) { return Model.of(UICmdObject.get(_cmdId).setInstance(_instance)); }public QueryRequestBuilder addIndexes(final ResourceIdentifier index0, final ResourceIdentifier... indexes) { this.indexes.add(index0); this.indexes.addAll(Arrays.asList(indexes)); return this; }public final void logout() { if (this.sessionAttributes.containsKey(UserAttributesSet.CONTEXTMAPKEY)) { try { UsageRegistry.store(); ((UserAttributesSet) this.sessionAttributes.get(UserAttributesSet.CONTEXTMAPKEY)).storeInDb(); AccessCache.clean4Person(Context.getThreadContext().getPersonId()); } catch (final EFapsException e) { EFapsSession.LOG.error("Error on logout", e); } finally { this.sessionAttributes.clear(); removeAttribute(EFapsSession.LOGIN_ATTRIBUTE_NAME); invalidate(); } } closeContext(); this.userName = null; }public final void login() { final IRequestParameters paras = RequestCycle.get().getRequest().getRequestParameters(); final StringValue name = paras.getParameterValue("name"); final StringValue pwd = paras.getParameterValue("password"); if (checkLogin(name.toString(), pwd.toString())) { this.userName = name.toString(); // on login a valid Context for the User must be opened to ensure that the // session attributes that depend on the user are set correctly before any // further requests are made (e.g. setting the current company openContext(); setAttribute(EFapsSession.LOGIN_ATTRIBUTE_NAME, this.userName); RegistryManager.registerUserSession(this.userName, getId()); } else { this.userName = null; this.sessionAttributes.clear(); } }private boolean lazyLogin() { boolean ret = false; final HttpServletRequest httpRequest = ((ServletWebRequest) RequestCycle.get().getRequest()) .getContainerRequest(); final HttpSession httpSession = httpRequest.getSession(false); if (httpSession != null && !(httpSession instanceof HttpSessionCopy)) { for (final ILoginProvider loginProvider : EFapsApplication.get().getLoginProviders()) { this.userName = loginProvider.login(httpSession); if (this.userName != null) { break; } } if (this.userName != null) { openContext(); try { setAttribute(EFapsSession.LOGIN_ATTRIBUTE_NAME, this.userName); this.sessionAttributes.put(UserAttributesSet.CONTEXTMAPKEY, new UserAttributesSet( this.userName)); } catch (final EFapsException e) { EFapsSession.LOG.error("Problems with setting UserAttribues.", e); } RegistryManager.registerUserSession(this.userName, getId()); ret = true; RequestCycle.get().setResponsePage(GatherInfoPage.class); } } return ret; }public boolean isLogedIn() { boolean ret = false; if (this.userName != null) { ret = true; } else if (!isSessionInvalidated()) { ret = lazyLogin(); } return ret; }public IExecutionBridge getBridge4Job(final String _jobName, final boolean _prune) { IExecutionBridge ret = null; for (final IExecutionBridge bridge : this.executionBridges) { if (bridge.getJobName().equals(_jobName)) { ret = bridge; if (_prune && ret.isFinished()) { this.executionBridges.remove(ret); } break; } } return ret; }public Iterator getJobsPage(final int _start, final int _size) { final int min = Math.min(_size, this.executionBridges.size()); return new ArrayList<>(this.executionBridges.subList(_start, min)).iterator(); }public synchronized void pruneFinishedTasks() { final ArrayList nonFinishedBridges = new ArrayList<>(); for (final IExecutionBridge bridge: this.executionBridges) { if (!bridge.isFinished()) { nonFinishedBridges.add(bridge); } } this.executionBridges = nonFinishedBridges; }private String getLabel(final ICmdUIObject _cmdObject, final String _keytype) throws EFapsException { final String ret; if (DBProperties.hasProperty(_cmdObject.getCommand().getName() + ".Button." + _keytype)) { ret = DBProperties.getProperty(_cmdObject.getCommand().getName() + ".Button." + _keytype); } else { ret = DBProperties.getProperty("default.Button." + _keytype); } return ret; }private AbstractCommand getCommand(final UUID _uuid) throws CacheReloadException { AbstractCommand cmd = Command.get(_uuid); if (cmd == null) { cmd = Menu.get(_uuid); if (cmd == null) { cmd = Search.get(_uuid); } } return cmd; }public String getRenderedContent(final String _script, final Map _uiID2Oid) throws EFapsException { this.executionStatus = UICmdField.ExecutionStatus.RENDER; final StringBuilder snip = new StringBuilder(); final List returns = executeEvents(_script, _uiID2Oid); for (final Return oneReturn : returns) { if (oneReturn.contains(ReturnValues.SNIPLETT)) { snip.append(oneReturn.get(ReturnValues.SNIPLETT)); } } this.executionStatus = null; return snip.toString(); }public List executeEvents(final Object _others, final Map _uiID2Oid) throws EFapsException { if (this.executionStatus == null) { this.executionStatus = ExecutionStatus.EXECUTE; } final List ret = executeEvents(EventType.UI_FIELD_CMD, _others, _uiID2Oid); if (this.executionStatus == ExecutionStatus.EXECUTE) { this.executionStatus = null; } return ret; }private DataTable getDataTable(final IndexSearch _indexSearch) { final List> columns = new ArrayList<>(); columns.add(new AbstractColumn(new Model<>("")) { private static final long serialVersionUID = 1L; @Override public void populateItem(final Item> _cellItem, final String _componentId, final IModel _rowModel) { _cellItem.add(new Link(_componentId, _rowModel)); } }); if (_indexSearch.getSearch() == null || _indexSearch.getSearch().getResultFields().isEmpty()) { columns.add(new PropertyColumn(new Model<>(""), "text")); } else { for (final Entry> entry : _indexSearch.getSearch().getResultFields() .entrySet()) { columns.add(new ResultColumn(_indexSearch.getSearch().getResultLabel().get(entry.getKey()), entry .getValue())); } } final DataTable ret = new DataTable<>("table", columns, _indexSearch .getDataProvider(), _indexSearch.getSearch() == null ? 100 : _indexSearch.getSearch().getNumHits()); ret.addTopToolbar(new HeadersToolbar<>(ret, null)); return ret; }@Override public final void bind(final Component _hostComponent) { Args.notNull(_hostComponent, "hostComponent"); if (this.component != null) { throw new IllegalStateException("this kind of handler cannot be attached to " + "multiple components; it is already attached to component " + this.component + ", but component " + _hostComponent + " wants to be attached too"); } this.component = _hostComponent; this.component.setOutputMarkupId(true); }public void requeryLabel() { try { final ValueParser parser = new ValueParser(new StringReader(this.valueLabel)); final ValueList valList = parser.ExpressionString(); final PrintQuery print = new PrintQuery(getInstance()); valList.makeSelect(print); if (print.execute()) { setLabel(valList.makeString(getInstance(), print, getMode()).toString()); } } catch (final EFapsException e) { throw new RestartResponseException(new ErrorPage(e)); } catch (final ParseException e) { throw new RestartResponseException(new ErrorPage(e)); } }public void executeListener(final ExecutionStatus _status, final Map _uiID2Oid) { setExecutionStatus(_status); try { getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.INSTANCE, getInstance(), ParameterValues.CLASS, this, ParameterValues.OIDMAP4UI, _uiID2Oid); } catch (final EFapsException e) { throw new RestartResponseException(new ErrorPage(e)); } }protected boolean checkForAllowChildren(final Instance _instance) { setExecutionStatus(UIStructurBrowser.ExecutionStatus.ALLOWSCHILDREN); try { final List ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.INSTANCE, _instance, ParameterValues.CLASS, this); return ret.isEmpty() ? false : ret.get(0).get(ReturnValues.TRUE) != null; } catch (final EFapsException e) { throw new RestartResponseException(new ErrorPage(e)); } }public void checkHideColumn4Row() { setExecutionStatus(UIStructurBrowser.ExecutionStatus.CHECKHIDECOLUMN4ROW); try { getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.INSTANCE, getInstance(), ParameterValues.CLASS, this); } catch (final EFapsException e) { throw new RestartResponseException(new ErrorPage(e)); } }protected void sortModel() { setExecutionStatus(UIStructurBrowser.ExecutionStatus.SORT); try { getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.CLASS, this); if (getSortDirection() == SortDirection.DESCENDING) { Collections.reverse(this.children); } } catch (final EFapsException e) { throw new RestartResponseException(new ErrorPage(e)); } }@SuppressWarnings("unchecked") protected void expand(final boolean _expand) { try { // only if the element was opened the first time e.g. reload etc. if ((isRoot() || _expand) && (Context.getThreadContext().containsSessionAttribute(getCacheKey()) || this.forceExpanded)) { final Map sessMap = (Map) Context .getThreadContext().getSessionAttribute(getCacheKey()); for (final UIStructurBrowser uiChild : this.children) { if (isForceExpanded() || sessMap == null || sessMap.containsKey(uiChild.getInstanceKey())) { final Boolean expandedTmp = sessMap == null || isForceExpanded() ? true : sessMap.get(uiChild.getInstanceKey()); if (expandedTmp != null && expandedTmp && uiChild.isParent()) { uiChild.setExecutionStatus(UIStructurBrowser.ExecutionStatus.ADDCHILDREN); final List ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.INSTANCE, uiChild.getInstance(), ParameterValues.CLASS, uiChild); final Map map = (Map) ret.get(0).get( ReturnValues.VALUES); uiChild.setExpanded(true); uiChild.add2ExpandedBrowsers(uiChild); if (uiChild.getTableUUID() == null) { uiChild.executeTree(map, true); } else { uiChild.executeTreeTable(map, true); } } } } } } catch (final EFapsException e) { UIStructurBrowser.LOG.error("Error retreiving Session info for StruturBrowser from Command with UUID: {}", getCommandUUID(), e); } }protected void initialise() throws EFapsException { final AbstractCommand command = getCommand(); if (command != null && command.getTargetTable() != null) { setTableUUID(command.getTargetTable().getUUID()); this.browserFieldName = command.getTargetStructurBrowserField(); setShowCheckBoxes(command.isTargetShowCheckBoxes()); } else if (getInstance() != null) { final String tmplabel = Menu.getTypeTreeMenu(getInstance().getType()).getLabel(); this.valueLabel = DBProperties.getProperty(tmplabel); } // set default sort if (command.getTargetTableSortKey() != null) { setSortKeyInternal(command.getTargetTableSortKey()); setSortDirection(command.getTargetTableSortDirection()); } // get the User specific Attributes if exist overwrite the defaults try { if (Context.getThreadContext().containsUserAttribute( getCacheKey(UITable.UserCacheKey.SORTKEY))) { setSortKeyInternal(Context.getThreadContext().getUserAttribute( getCacheKey(UITable.UserCacheKey.SORTKEY))); } if (Context.getThreadContext().containsUserAttribute( getCacheKey(UITable.UserCacheKey.SORTDIRECTION))) { setSortDirection(SortDirection.getEnum(Context.getThreadContext() .getUserAttribute(getCacheKey(UITable.UserCacheKey.SORTDIRECTION)))); } } catch (final EFapsException e) { // we don't throw an error because this are only Usersettings UIStructurBrowser.LOG.error("error during the retrieve of UserAttributes", e); } }protected UIStructurBrowser getNewStructurBrowser(final Instance _instance, final UIStructurBrowser _strucBrwsr) throws EFapsException { final UUID uuid; if (_strucBrwsr.getTable() == null) { uuid = Menu.getTypeTreeMenu(_instance.getType()).getUUID(); } else { uuid = _strucBrwsr.getCommandUUID(); } final UIStructurBrowser ret = new UIStructurBrowser(uuid, _instance == null ? null : _instance.getKey(), false, _strucBrwsr.getSortDirection()); ret.setParentBrws(this); ret.setLevel(getLevel() + 1); return ret; }public static CharSequence getHelp(final long _cmdId) { CharSequence ret; try { final Class clazz = Class.forName(Configuration.getAttribute(Configuration.ConfigAttribute.HELPSNIPPROV), false, EFapsClassLoader.getInstance()); final IHelpProvider provider = (IHelpProvider) clazz.newInstance(); ret = provider.getHelp(_cmdId); } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException | EFapsBaseException e) { HelpUtil.LOG.error("ClassNotFoundException", e); ret = ""; } return ret; }private void addChildren(final UIClassification _uiClass, final boolean _force) { if (_force || _uiClass.isExpanded()) { getModelObject().add(_uiClass); for (final UIClassification child : _uiClass.getChildren()) { addChildren(child, _force); } } }public void addNewRow() throws EFapsException { final UIFieldSetRow row = new UIFieldSetRow(this); this.rows.add(row); for (final UIFieldSetColHeader header : getHeaders()) { final UIValue uiValue = UIValue .get(Field.get(header.getFieldId()), Attribute.get(header.getAttrId()), null); final UIFieldSetValue cellSetValue = new UIFieldSetValue(getParent(), null, this, uiValue); row.add(cellSetValue); } }public int getIndex(final String _inputName) { Integer ret = 0; if (this.indexes.containsKey(_inputName)) { ret = this.indexes.get(_inputName) + 1; } this.indexes.put(_inputName, ret); return ret; }public void addValue(final Instance _rowInstance, final UIFieldSetValue _uiFieldSetValue) { this.instKey2row.get(_rowInstance.getKey()).add(_uiFieldSetValue); }@Override protected void onEvent(final AjaxRequestTarget _target) { final ModalWindowContainer modal = getComponent().getPage().visitChildren(ModalWindowContainer.class, new ModalVisitor()); modal.show(_target); }@Override public Page createPage() { Page ret = null; try { final String instKey = this.uiObject.getInstance() == null ? null : this.uiObject.getInstance().getKey(); if (this.uiObject.getCommand().getTargetTable() == null) { final UIForm uiform = new UIForm(this.uiObject.getCommand().getUUID(), instKey) .setPagePosition(this.pagePosition); uiform.setPicker(this.uiObject); if (!uiform.isInitialized()) { uiform.execute(); } if (uiform.getElements().isEmpty()) { ret = new DialogPage(this.modalWindow.getPage().getPageReference(), uiform.getCommand().getName() + ".InvalidInstance", false, false); } else { if (this.uiObject.getCommand().isSubmit()) { final IRequestParameters parameters = RequestCycle.get().getRequest().getRequestParameters(); uiform.setSelected(parameters.getParameterValues("selectedRow")); } ret = new FormPage(Model.of(uiform), this.modalWindow, this.modalWindow.getPage() .getPageReference()); } } else { if (this.uiObject.getCommand().getTargetStructurBrowserField() == null) { final UITable uitable = new UITable(this.uiObject.getCommand().getUUID(), instKey) .setPagePosition(this.pagePosition); uitable.setPicker(this.uiObject); ret = new TablePage(Model.of(uitable), this.modalWindow, this.modalWindow.getPage() .getPageReference()); } else { final UIStructurBrowser uiPageObject = new UIStructurBrowser(this.uiObject.getCommand().getUUID(), instKey); uiPageObject.setPicker(this.uiObject); ret = new StructurBrowserPage(Model.of(uiPageObject), this.modalWindow, this.modalWindow.getPage().getPageReference()); } } } catch (final EFapsException e) { ret = new ErrorPage(e); } return ret; }public static CharSequence getDataReloadJS(final UIGrid _uiGrid) throws EFapsException { final StringBuilder js = new StringBuilder() .append("var grid = registry.byId('grid');\n") .append("var items = ").append(GridXComponent.getDataJS(_uiGrid)); final StringBuilder dialogJs = new StringBuilder(); if (!_uiGrid.isColumnsUpToDate()) { // lazy setting of data type when first time data _uiGrid.setColumnsUpToDate(true); js.append("array.forEach(grid.structure, function(entry){\n"); for (final GridColumn column : _uiGrid.getColumns()) { if (column.getDataType() != null) { js.append("if ('").append(column.getField().getId()).append("'== entry.id) {\n") .append("entry.dataType='").append(column.getDataType()).append("';\n") .append("entry.comparator = grid.comparators.").append(column.getDataType()).append(";\n") .append("}\n"); } if (_uiGrid.getFilterList().stream() .filter(filter -> filter.getFieldId() == column.getField().getId()) .findFirst().isPresent()) { // to prevent jumping of the modal filter dialog, close and open it final String varName = RandomUtil.randomAlphabetic(4); dialogJs.append("var ").append(varName) .append(" = registry.byId('").append("fttd_" + column.getField().getId()).append("');\n") .append("if (").append(varName).append(" && !(").append(varName) .append(".domNode.offsetHeight == 0 && ") .append(varName).append(".domNode.offsetWidth == 0)) {\n") .append(varName).append(".onBlur();\n") .append("var nl = query(\".gridxHeaderMenuBtn\", dom.byId('grid-") .append(column.getField().getId()).append("'));\n") .append("nl[0].click();\n") .append("}\n"); } } js.append("});\n") .append("grid.setColumns(grid.structure);\n") .append(dialogJs); } js.append("grid.model.clearCache();\n") .append("grid.model.store.setData(items);\n") .append("grid.body.refresh();\n"); return DojoWrapper.require(js, DojoClasses.registry, DojoClasses.array, DojoClasses.dom, DojoClasses.query); }public static CharSequence getDataJS(final UIGrid _uiGrid) throws EFapsException { final StringBuilder ret = new StringBuilder().append(" [\n"); int i = 0; for (final GridRow row : _uiGrid.getValues()) { if (i > 0) { ret.append(",\n"); } ret.append(getRowJS(row, String.valueOf(i))); i++; } ret.append("]\n"); return ret; }protected CharSequence getSubMenu(final AbstractMenu _menu, final String _parent) throws EFapsException { final String var = RandomUtil.randomAlphabetic(4); final StringBuilder js = new StringBuilder(); js.append("var ").append(var).append(" = new DropDownMenu({});\n"); final UIGrid uiGrid = (UIGrid) getDefaultModelObject(); for (final AbstractCommand child : _menu.getCommands()) { if (child.hasAccess(uiGrid.getCommand().getTargetMode(), uiGrid.getInstance())) { if (child instanceof AbstractMenu) { js.append(getSubMenu((AbstractMenu) child, var)); } else { js.append(var).append(".addChild(") .append(getMenuItem(child, false)) .append(");\n"); } } } js.append(_parent).append(".addChild(new PopupMenuBarItem({\n") .append("label: \"").append(StringEscapeUtils.escapeEcmaScript(_menu.getLabelProperty())).append("\",\n") .append(" popup: ").append(var).append("\n") .append(" }));\n"); return js; }protected CharSequence getMenu(final Set _dojoClasses) throws EFapsException { final StringBuilder ret = new StringBuilder(); final UIGrid uiGrid = (UIGrid) getDefaultModelObject(); if (!(uiGrid instanceof UIFieldGrid) && uiGrid.getCommand().getTargetMenu() != null) { Collections.addAll(_dojoClasses, DojoClasses.MenuBar, DojoClasses.DropDownMenu, DojoClasses.MenuItem, DojoClasses.PopupMenuBarItem, DojoClasses.MenuBarItem); ret.append("var pMenuBar = new MenuBar({});\n"); for (final AbstractCommand child : uiGrid.getCommand().getTargetMenu().getCommands()) { if (child.hasAccess(uiGrid.getCommand().getTargetMode(), uiGrid.getInstance())) { if (child instanceof AbstractMenu) { ret.append(getSubMenu((AbstractMenu) child, "pMenuBar")); } else { ret.append("pMenuBar.addChild(").append(getMenuItem(child, true)).append(");\n"); } } } } return ret; }protected CharSequence getPrintMenuItems(final Set _dojoClasses) { final StringBuilder ret = new StringBuilder(); Collections.addAll(_dojoClasses, DojoClasses.MenuItem); final PrintBehavior printBehavior = (PrintBehavior) getBehavior(PrintBehavior.class); final String[] mimes = new String[] {"PDF", "XLS"}; for (final String mime : mimes) { if (ret.length() > 0) { ret.append(","); } ret.append("new MenuItem({\n") .append("label: \"").append(mime).append("\",\n") .append("iconClass:\"eFapsMenuIcon eFapsMenuIcon").append(mime.toUpperCase()).append("\",\n") .append("onClick: function(event) {\n") .append("var g = registry.byId('grid');\n") .append("var sr = g.select.row.getSelected();\n") .append("if (sr.length == 0) {\n") .append("array.forEach(g.rows(), function (_item, _id) {\n") .append("sr[_id] = _item.id;\n") .append("});\n") .append("}\n") .append("var cm = [];\n") .append("array.forEach(g.columns(), function (_item, _id) {\n") .append("cm[_id] = _item.id;\n") .append("});\n") .append(printBehavior.getCallbackFunctionBody( CallbackParameter.resolved("MIME", "\"" + mime + "\""), CallbackParameter.explicit("sr"), CallbackParameter.explicit("cm"))) .append("}\n") .append("})\n"); } return ret; }protected CharSequence getPersistenceScript(final UIGrid _uiGrid) throws EFapsException { final StringBuilder ret = new StringBuilder(); ret.append("persistGet: function(_key) {"); if (Context.getThreadContext().containsUserAttribute(_uiGrid.getCacheKey(CacheKey.GRIDX))) { final Set colIds = _uiGrid.getColumns() .stream() .map(col -> col.getField().getId()) .collect(Collectors.toSet()); boolean add = true; final JSONObject json = new JSONObject(new JSONTokener(Context.getThreadContext().getUserAttribute( _uiGrid.getCacheKey(CacheKey.GRIDX)))); final JSONArray columnsArray = json.getJSONArray("column"); for (int i = 0; i < columnsArray.length(); i++) { final JSONObject colObj = (JSONObject) columnsArray.get(i); final Long colid = colObj.getLong("id"); if (!colIds.contains(colid)) { add = false; break; } } if (add && !json.isNull("filterBar")) { final JSONObject filterBar = json.getJSONObject("filterBar"); if (!filterBar.isNull("conditions")) { final JSONArray conditionsArray = filterBar.getJSONArray("conditions"); for (int i = 0; i < conditionsArray.length(); i++) { final JSONObject colObj = (JSONObject) conditionsArray.get(i); if (colObj.has("colId")) { final Long colid = colObj.optLong("colId"); if (colid > 0 && !colIds.contains(colid)) { add = false; break; } } } } } if (add) { ret.append("return ").append(json.toString()); } } ret.append("},\n") .append("persistPut: function(_key, _value, _options) {\n") .append(" var value;") .append(" if(_value && lang.isObject(_value)){\n") .append(" value = json.toJson(_value);\n") .append(" }else{\n") .append(" value = {expires: -1};\n") .append(" }\n") .append("top.eFaps.persistUserAttr('") .append(_uiGrid.getCacheKey(CacheKey.GRIDX)).append("', value);") .append("},\n"); return ret; }@Override public void onRequest(final AjaxRequestTarget _target) { final UICmdField uiObject = (UICmdField) getDefaultModelObject(); final StringBuilder snip = new StringBuilder(); try { final AbstractUIPageObject pageObject = (AbstractUIPageObject) getPage().getDefaultModelObject(); final Map uiID2Oid = pageObject == null ? null : pageObject.getUiID2Oid(); final List returns = uiObject.executeEvents(null, uiID2Oid); for (final Return oneReturn : returns) { if (oneReturn.contains(ReturnValues.SNIPLETT)) { snip.append(oneReturn.get(ReturnValues.SNIPLETT)); } } } catch (final EFapsException e) { throw new RestartResponseException(new ErrorPage(e)); } _target.appendJavaScript(snip.toString()); }protected boolean checkLogin(final String _name, final String _passwd) { boolean loginOk = false; Context context = null; try { context = Context.begin(); boolean ok = false; try { if (this.loginHandler.checkLogin(_name, _passwd) != null) { loginOk = true; } ok = true; } finally { if (ok && Context.isTMActive()) { Context.commit(); } else { if (Context.isTMMarkedRollback()) { AbstractAuthenticationFilter.LOG.error("transaction is marked to roll back"); } else { AbstractAuthenticationFilter.LOG.error("transaction manager in undefined status"); } Context.rollback(); } } } catch (final EFapsException e) { AbstractAuthenticationFilter.LOG.error("could not check name and password", e); } finally { context.close(); } return loginOk; }@Override protected void doFilter(final HttpServletRequest _request, final HttpServletResponse _response, final FilterChain _chain) throws IOException, ServletException { if (isLoggedIn(_request)) { _chain.doFilter(_request, _response); } else { doAuthenticate(_request, _response, _chain); } }@Override public void init(final FilterConfig _filterConfig) throws ServletException { super.init(_filterConfig); try { this.loginHandler = new LoginHandler(AppAccessHandler.getApplicationKey()); } catch (final EFapsException e) { AbstractAuthenticationFilter.LOG.error("AppAccessHandler", e); } }private void resetSetCounter() { if (getPage().getDefaultModelObject() instanceof UIForm) { for (final Element element : ((UIForm) getPage().getDefaultModelObject()).getElements()) { if (element.getType().equals(ElementType.FORM)) { final Iterator iter = ((UIForm.FormElement) element.getElement()).getRowModels(); while (iter.hasNext()) { final FormRow row = iter.next(); for (final IUIElement uiElement : row.getValues()) { if (uiElement instanceof UIFieldSet) { ((UIFieldSet) uiElement).resetIndex(); } } } } else if (element.getType().equals(ElementType.SUBFORM)) { for (final Element nElement : ((UIFieldForm) element.getElement()).getElements()) { if (nElement.getType().equals(ElementType.FORM)) { final Iterator iter = ((UIForm.FormElement) nElement.getElement()).getRowModels(); while (iter.hasNext()) { final FormRow row = iter.next(); for (final IUIElement uiElement : row.getValues()) { if (uiElement instanceof UIFieldSet) { ((UIFieldSet) uiElement).resetIndex(); } } } } } } } } }@Override protected boolean handleMultiPart() { final boolean ret = super.handleMultiPart(); try { if (isMultiPart() && getRequest() instanceof MultipartServletWebRequest) { for (final Entry> entry : ((MultipartServletWebRequest) getRequest()).getFiles() .entrySet()) { int i = -1; if (entry.getValue().size() > 1) { i = 0; } for (final FileItem fileItem : entry.getValue()) { final String key = i > -1 ? entry.getKey() + "_" + i : entry.getKey(); final FileParameter parameter = new FileParameter(key, fileItem); Context.getThreadContext().getFileParameters().put(key, parameter); if (i > -1) { i++; } } } final Map parameters = new HashMap<>(); final IRequestParameters reqPara = getRequest().getRequestParameters(); for (final String name : reqPara.getParameterNames()) { final List values = reqPara.getParameterValues(name); final String[] valArray = new String[values.size()]; int i = 0; for (final StringValue value : values) { valArray[i] = value.toString(); i++; } parameters.put(name, valArray); } Context.getThreadContext().getParameters().putAll(parameters); } } catch (final EFapsException e) { throw new RestartResponseAtInterceptPageException(new ErrorPage(e)); } return ret; }@Override protected void onComponentTag(final ComponentTag _tag) { if (this.actionUrl == null) { this.actionUrl = urlFor(getRequestCycle().getActiveRequestHandler()).toString(); } super.onComponentTag(_tag); if (getPage().getDefaultModelObject() != null) { // only on SearchMode we want normal submit, in any other case we // use AjaxSubmit if (getPage().getDefaultModelObject() instanceof AbstractUIObject && !((AbstractUIObject) getPage().getDefaultModelObject()).isSearchMode()) { //_tag.put("onSubmit", "return false;"); _tag.put("action", ""); } } }@Override @SuppressWarnings("checkstyle:illegalcatch") public void onClick(final AjaxRequestTarget _target) { Instance instance = null; try { if (this.target.equals(ScriptTarget.TOP)) { final PageReference reference = ((AbstractContentPage) getPage()).getCalledByPageReference(); if (reference != null) { final UIMenuItem menuItem = (UIMenuItem) ((ContentContainerPage) reference.getPage()).getMenuTree() .getSelected().getDefaultModelObject(); final RecentObjectLink link = new RecentObjectLink(menuItem); if (link != null) { ((EFapsSession) getSession()).addRecent(link); } } } final AbstractUIField uiField = super.getModelObject(); if (uiField.getInstanceKey() != null) { Menu menu = null; try { instance = uiField.getInstance(); menu = Menu.getTypeTreeMenu(instance.getType()); } catch (final Exception e) { if (menu == null) { throw new EFapsException(LoadInTargetAjaxLink.class, "NoTreeMenu", instance); } } final ContentContainerPage page = new ContentContainerPage(menu.getUUID(), uiField.getInstanceKey(), uiField.getParent() instanceof UIStructurBrowser); final CharSequence url = urlFor(new RenderPageRequestHandler(new PageProvider(page))); // touch the page to ensure that the pagemanager stores it to be accessible getSession().getPageManager().touchPage(page); final StringBuilder js = new StringBuilder() .append(this.target.key).append(".dijit.registry.byId(\"").append("mainPanel") .append("\").set(\"content\", dojo.create(\"iframe\",{") .append("\"id\": \"").append(MainPage.IFRAME_ID) .append("\",\"src\": \"./wicket/").append(url) .append("\",\"style\": \"border: 0; width: 100%; height: 99%\"") .append("}));"); _target.appendJavaScript(js); } } catch (final EFapsException e) { throw new RestartResponseException(new ErrorPage(e)); } }public void destroy() { log.debug("Shutting down executor service"); executorService.shutdown(); try { if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) { log.debug("Timed out waiting for executor service to die, calling shutdownNow"); executorService.shutdownNow(); } } catch (final InterruptedException e) { log.debug("Interrupted waiting for executor service to die, calling shutdownNow"); executorService.shutdownNow(); } }@Override protected void onAfterRender() { super.onAfterRender(); final IDateListener container = this.findParent(IDateListener.class); if (container != null) { container.addDateComponent(this); } }public List getDateList(final List _date, final List _hour, final List _minute, final List _ampm) throws EFapsException { final List ret = new ArrayList<>(); if (_date != null) { Iterator hourIter = null; Iterator minuteIter = null; Iterator ampmIter = null; if (_hour != null) { hourIter = _hour.iterator(); } if (_minute != null) { minuteIter = _minute.iterator(); } if (_ampm != null) { ampmIter = _ampm.iterator(); } for (final StringValue date : _date) { if (!date.isNull() && !date.isEmpty()) { final DateTimeFormatter fmt = DateTimeFormat.forPattern( this.converter.getDatePattern(Context.getThreadContext().getLocale())) .withChronology(Context.getThreadContext().getChronology()); fmt.withLocale(getLocale()); final MutableDateTime mdt = fmt.parseMutableDateTime(date.toString()); if (hourIter != null) { final StringValue hourStr = hourIter.next(); final int hour = Integer.parseInt(hourStr.toString("0")); mdt.setHourOfDay(hour); if (ampmIter != null) { final StringValue ampmStr = ampmIter.next(); if ("am".equals(ampmStr.toString("am"))) { if (hour == 12) { mdt.setHourOfDay(0); } } else { if (hour != 12) { mdt.setHourOfDay(hour + 12); } } } if (minuteIter != null) { final StringValue minuteStr = minuteIter.next(); final int minute = Integer.parseInt(minuteStr.toString("0")); mdt.setMinuteOfHour(minute); } } ret.add(mdt.toDateTime()); } } } return ret; }public List getDateAsString(final List _date, final List _hour, final List _minute, final List _ampm) throws EFapsException { final List ret = new ArrayList<>(); final List dates = getDateList(_date, _hour, _minute, _ampm); for (final DateTime date : dates) { final DateTimeFormatter isofmt = ISODateTimeFormat.dateTime(); ret.add(StringValue.valueOf(date.toString(isofmt))); } return ret; }@Override protected void onAfterRender() { super.onAfterRender(); if (getDefaultModel() != null) { final UITableHeader headermodel = (UITableHeader) getDefaultModelObject(); headermodel.setMarkupId(this.getMarkupId()); } }protected Component getEditableComp(final String _wicketId, final AbstractUIField _uiField) throws EFapsException { Component ret = null; switch (_uiField.getFieldConfiguration().getUIType()) { case SNIPPLET: if (!_uiField.getFieldConfiguration().isHideLabel()) { _uiField.getFieldConfiguration().evalLabel(_uiField.getValue(), _uiField.getInstance()); } final String html = String.valueOf(_uiField.getValue().getEditValue( _uiField.getParent().getMode())); ret = new SnippletField(_wicketId, Model.of(html), _uiField); break; case DROPDOWN: final List choices = DropDownOption.getChoices(_uiField.getValue() .getEditValue(_uiField.getParent().getMode())); ret = new DropDownField(_wicketId, Model.of(_uiField), choices); break; case RADIO: final List radios = RadioOption.getChoices(_uiField.getValue() .getEditValue(_uiField.getParent().getMode())); ret = new RadioField(_wicketId, Model.of(_uiField), radios); break; case CHECKBOX: final List checkBoxes = CheckBoxOption.getChoices(_uiField, _uiField.getValue().getEditValue(_uiField.getParent().getMode())); ret = new CheckBoxField(_wicketId, Model.of(_uiField), checkBoxes); break; case BUTTON: ret = new AjaxPickerButton(_wicketId, Model.of(_uiField)); break; case NUMBER: ret = new NumberField(_wicketId, Model.of(_uiField), _uiField.getFieldConfiguration()); break; case UPLOAD: ret = new UploadField(_wicketId, Model.of(_uiField), false); break; case UPLOADMULTIPLE: ret = new UploadField(_wicketId, Model.of(_uiField), true); break; default: break; } return ret; }public static String getLabel(final String _cmdName, final String _keytype) { final String ret; if (DBProperties.hasProperty(_cmdName + ".Button." + _keytype)) { ret = DBProperties.getProperty(_cmdName + ".Button." + _keytype); } else { ret = DBProperties.getProperty("default.Button." + _keytype); } return ret; }public void setDefault(final UUID _selectCmdUUID) { final UIMenuItem menuItem = getProvider().getRoots().next(); menuItem.setHeader(true); boolean hasDefault = false; for (final UIMenuItem childItem : menuItem.getChildren()) { if (_selectCmdUUID == null && childItem.isDefaultSelected() || _selectCmdUUID != null && _selectCmdUUID.equals(childItem.getCommandUUID())) { hasDefault = true; childItem.setSelected(true); } } if (!hasDefault) { menuItem.setSelected(true); } expand(menuItem); expandChildren(menuItem); }@Override public void renderHead(final Component _component, final IHeaderResponse _response) { super.renderHead(_component, _response); _response.render(RequireHeaderItem.forClasses(DojoClasses.DnDSource, DojoClasses.parser)); if (this.type == DnDBehavior.BehaviorType.SOURCE) { final StringBuilder js = new StringBuilder() .append("var nSrc = new dojo.dnd.Source(dom.byId('").append(_component.getMarkupId(true)).append("'),") .append("{ accept: ['" + this.dndType + "']});") .append(" aspect.after(nSrc,\"onDrop\", function(){\n") .append(this.appendJavaScript) .append("\n});"); _response.render(OnDojoReadyHeaderItem.forScript(DojoWrapper.require(js, DojoClasses.aspect, DojoClasses.dom, DojoClasses.DnDSource))); } }@Override public void onComponentTag(final Component _component, final ComponentTag _tag) { super.onComponentTag(_component, _tag); if (this.type == DnDBehavior.BehaviorType.ITEM) { String value = "dojoDndItem "; if (_tag.getAttribute("class") != null) { value += _tag.getAttribute("class"); } _tag.put("dndType", this.dndType); _tag.put("class", value); } }@Override public void run() { try { log.debug("About to check status for jobId {}", jobId); final JobStatus jobStatus; if (tokenProxy != null) { jobStatus = jobService.getJobStatus(tokenProxy, jobId); } else { jobStatus = jobService.getJobStatus(jobId); } final Status jobStatusStatus = jobStatus.getStatus(); if (jobStatusStatus == Status.FINISHED || jobStatusStatus == Status.FAILED) { for (final Action action : jobStatus.getActions()) { final Status status = action.getStatus(); if (status == Status.FINISHED) { log.debug("Found a finished action, calling callback"); callback.success(action.getResult()); } else if (status == Status.FAILED) { log.debug("Found a failed action, calling callback"); for (final HodError error : action.getErrors()) { log.debug("Error callback called with: {}", error); callback.error(error.getErrorCode()); } } } } else if (timeout != null && timeout.isBefore(LocalDateTime.now())) { callback.timeout(); log.debug("Timeout callback called"); } else { log.debug("Not finished or failed, retrying"); // we got a status successfully, so reset the counter tries.set(0); executorService.schedule(this, WAIT_SECONDS, TimeUnit.SECONDS); } } catch (final HodErrorException e) { log.error("Error retrieving job status for jobId: {}", jobId); log.error("Cause:", e); if (DO_NOT_RETRY_CODES.contains(e.getErrorCode())) { log.error("Unrecoverable error, will not retry"); callback.error(e.getErrorCode()); } else if (tries.get() >= MAX_TRIES) { log.error("Max retries reached, will not retry"); callback.error(e.getErrorCode()); } else { log.error("Retrying"); tries.incrementAndGet(); executorService.schedule(this, WAIT_SECONDS, TimeUnit.SECONDS); } } catch (final RuntimeException e) { log.error("Error retrieving job status for jobId: {}", jobId); log.error("Cause:", e); callback.handleException(e); } }protected void onComponentTagInternal(final ComponentTag _tag) { _tag.put("name", getConfig().getName()); _tag.append("style", "text-align:" + getConfig().getAlign(), ";"); }@Override protected List getEvents(final EventType _eventType) { return Field.get(this.fieldId).getEvents(_eventType); }InputStream parseResponse(final TokenProxy tokenProxy, final Response response) { checkRefresh(tokenProxy, response); try { return response.getBody().in(); } catch (final IOException e) { throw new RuntimeException(e); } } T unsafeParseResponse(final TokenProxy tokenProxy, final JavaType type, final Response response) { checkRefresh(tokenProxy, response); try { return objectMapper.readValue(response.getBody().in(), type); } catch (final IOException e) { throw new RuntimeException(e); } } T parseResponse(final TokenProxy tokenProxy, final TypeReference typeReference, final Response response) { return unsafeParseResponse(tokenProxy, objectMapper.getTypeFactory().constructType(typeReference), response); } T parseResponse(final TokenProxy tokenProxy, final Class clazz, final Response response) { return unsafeParseResponse(tokenProxy, objectMapper.constructType(clazz), response); }public static EmbeddedLink getDashboardLink(final String _instanceKey, final String _identifier) { final EmbeddedLink ret = new EmbeddedLink(_instanceKey); ret.setTagHtml(TAG.DASHBOARD.getHtml()); ret.setIdentifier(_identifier); return ret; }@Override protected void onRender() { final IMarkupFragment markup = getMarkup(); if (markup == null) { throw new MarkupException("Markup not found. Component: " + toString()); } final MarkupStream markupStream = new MarkupStream(markup); // Get mutable copy of next tag final ComponentTag openTag = markupStream.getTag(); final ComponentTag tag = openTag.mutable(); // Call any tag handler onComponentTag(tag); // If we're an openclose tag if (!tag.isOpenClose() && !tag.isOpen()) { // We were something other than or markupStream.throwMarkupException("Method renderComponent called on bad markup element: " + tag); } if (tag.isOpenClose() && openTag.isOpen()) { markupStream.throwMarkupException("You can not modify a open tag to open-close: " + tag); } markupStream.next(); getMarkupSourcingStrategy().onComponentTagBody(this, markupStream, tag); }@Override public void onComponentTagBody(final MarkupStream _markupStream, final ComponentTag _openTag) { setEscapeModelStrings(false); String value = getDefaultModelObjectAsString(getDefaultModelObject()); // if the value contains the EFAPSTMPTAG all tags from this component // will be moved to the subcomponent if (value != null && value.contains(IUserInterface.EFAPSTMPTAG)) { final StringBuilder tagBldr = new StringBuilder(); final List behaviors = getBehaviors(); final ComponentTag tmpTag = new ComponentTag(_openTag); for (final Behavior behavior : behaviors) { behavior.onComponentTag(this, tmpTag); } final IValueMap map = tmpTag.getAttributes(); for (final Entry entry : map.entrySet()) { final String key = entry.getKey(); if (!"wicket:id".equals(key)) { tagBldr.append(" ").append(key).append("=\"").append(entry.getValue()).append("\" "); } } // if no id is given add the id here if (!map.containsKey("id")) { tagBldr.append(" id=\"").append(getMarkupId()).append("\" "); } value = value.replace(IUserInterface.EFAPSTMPTAG, tagBldr); } super.replaceComponentTagBody(_markupStream, _openTag, value); }public static List getUIUserSessions() { final List ret = new ArrayList<>(); final Collection userSessions = RegistryManager.getUserSessions(); for (final UserSession userSession : userSessions) { ret.add(new UIUserSession(userSession.getUserName(), userSession.getSessionId(), userSession .getLastActivity())); } return ret; }private void initKeepAlive() { if (!this.keepAlive) { this.keepAlive = true; final KeepAliveTask keepAliveTask = new KeepAliveTask(EFapsApplication.get().getApplicationKey()); final Timer timer = new Timer(true); // every two minutes timer.scheduleAtFixedRate(keepAliveTask, 0 * 1000, Configuration.getAttributeAsInteger(ConfigAttribute.WEBSOCKET_KASP) * 1000); } }public void sendKeepAlive(final Application _application) { final long reference = new Date().getTime(); final ConcurrentMap sessionId2key = _application.getMetaData(ConnectionRegistry.SESSION2KEY); final ConcurrentMap keepalive = _application.getMetaData(ConnectionRegistry.KEEPALIVE); if (keepalive != null) { for (final Entry entry : keepalive.entrySet()) { if (reference - entry.getValue() > Configuration.getAttributeAsInteger(ConfigAttribute.WEBSOCKET_KATH) * 1000) { final IKey key = sessionId2key.get(entry.getKey()); if (key != null) { final IWebSocketConnectionRegistry registry = WebSocketSettings.Holder.get( _application).getConnectionRegistry(); final IWebSocketConnection conn = registry.getConnection(_application, entry.getKey(), key); if (conn != null) { try { conn.sendMessage(KeepAliveBehavior.MSG); ConnectionRegistry.LOG.debug("Send KeepAlive for Session: {}", entry.getKey()); } catch (final IOException e) { ConnectionRegistry.LOG.error("Catched error", e); } } } } } } }protected CharSequence getCallBackScript(final String _url) { final StringBuilder js = new StringBuilder() .append("baseWindow.withDoc(top.dojo.doc, function () {\n") .append("var node = dom.byId('downloadFrame');\n") .append("if (node == null) {\n") .append("node = domConstruct.place('