�����    �   huggingface�{"info": {"features": {"id": {"dtype": "string", "_type": "Value"}, "text": {"dtype": "string", "_type": "Value"}, "dataset_id": {"dtype": "string", "_type": "Value"}}}}p4���� dataset_id��������text���� id����  ��<   �� ��$�,�,�x<+n<��<��<�P�<hB���%,3;BJRYagnv}����������������� &-4<DKRYahow~�����������������  (/7>ELT[cjry������������������ '/7?FMU]elt|������������������$,3;CKS[agov~����������������� !(/6>EMT[aiqy������������������&-5=DKSZahpw�����������������  '/6=EMU]elsz������������������ !(/7?FMT[biqx�����������������   " * 2 : A H P W ^ e l s z � � � � � � � � � � � � � � � � �    ( / 6 = D K R Y ` h p w ~ � � � � � � � � � � � � � � � � �    ! ( 0 7 ? G N V ^ f m u | � � � � � � � � � � � � � � � � �      ' . 6 > E L T \ c j q y � � � � � � � � � � � � � � � � � �    ! ( 0 7 ? G N V ^ f n v } � � � � � � � � � � � � � � � � �  #+29@HOW_fnv|����������������� "*19AIPX_gnv}����������������� !(08?FMT\ckrz~����������������&-4;CJRZbiqy����������������� #+2:BJQY`hpv~����������������� ")07>DLT\dkrz����������������� $+3;CKRZ`flt{����������������� "*29@GNV]ckrz����������������� '.6>FNU]elt|�����������������#+2:AIQYahpx�����������������&.5=EMU\dlt|����������������� !(/7>EMU\ciqy������������������  (/6>ELSZbipw����������������� #+19AIPX_gow~����������������� "*2:BIQYaipx�������������������$16664157204719013620554650800953675879918318365927213519726685742018311815120751717648597107481998107168071750109180238844615846627809765519431203634090266163501383390956554557429962156250751845038415608991120222113431367692641160681530989581962288417971623142830485398739355425461371261190672681684781279767128846981939376480789954172909808144917845879742941144097521329085187215363076167179367292953236655091415514767351441886096251569503111551355346384166276789419473197417111421521741145657096140146540351053187619142881756862038510069634631053479269585591260781918072016199080631428211235281299452812547678540656613835723758369947178211976902334128921871307718079409130111128738063846244121073696812331437210895812113542682128625743999842705123867331831042969135847348781597914426538759074770581991914513874724200581461618679369195788029583170909701155097415550662585978018622405198276325047964481990211807925334650412966903537481415072110601753129244481460738112791110986462810845265679818151992825314915470939451589916467346238936613568448230854858606621136269622737151527936012182061195376171147026714656369980999238487109114899445245164069681722762045446691236054516434188749621713380188524437715765261895304069397476118741933866599716757103411308265015440146165355663982001592536618623202154560016725693474874019516494820677174005135596237178921221208255860137176916513053173131211831716270411429476716860037911051383384215902288193103919186558456998011329153947103010253020175000621715954979090652382605446146572049743815127177489694343580108804801848401819394056327615118706028106216929046910124963816674256802158816154772669307134874478042467129600693528782868222419549139162466211564217085694133448564042758163442611942001241864250546641489805018783586192379131005751711269917297231282343241790122414807792331915113801535666210102192837852130892501922593314892714121171611138496091824837233614202722731638271291701821276138061805104368851059094115263694129095868015851073870815119331423523316666367526680220971758000696393955663234013450309597858043576517588011279032456875051851121367662918826737512172690721154566168373266584726713464787152467889784067168045501603195810951954876855011512750118675211857288415813349467590916191849153228646748440197479573841851197254351665007964877361084752611633361172880516071292179006901042018612169713179880494689544449957617948377164642984499425961858673608972379027053815972284189226611751624712099583122579181736569174108845793115540345153847431745382210418067957119410712931197460581774284092094871133242773510561132908711298605392630716178235181680934130333577033899665970886638335061316834442671251066714211029217891550590210511764250165943822444398198676924171306265573973819261751526144480061500591119413666272895117043966165606322583563145008917246364177587281487410805777195330514530257326739219209248799196517646829182551072587385149520421353814315494439288057115686385108969119337697165471807675376138960688897304694430469332894511481467423119477670640426334684072196191652924218369420199896396882223144725932796270126991041150982840896671180316883530811133279917318511689758463111471706774913570279602778832937332789113184682101546948818559780932809329788730467355548010504034188386596542511715413917002145199532681891579157504721579345714942707158746922659858931143297244733030365991358147823627310084115017446339760152645481893741814170611901424811954025182587471963441713562106950295210801222095195107712521140455016118905200021131409464499195968382807107950771524721436453881048581510929570179784901108254466058678063806501203103626021754840182076631556669048163136493892622366710452685120465519453902124425167747737109495461941161295043613112253911235157851641066693126530171526582260887753336291917301019131342151747311032037443751413638359141653482787267179671961245198417863949143022411993640382885821079395684417771187632718360608179515663569500165500065320192154308251509122139566855661450699731314629149197465161505280965457848045202184729107575673924487813902279536186775294271370814110393181970552792434381153687773237219957076491977616637955197655848824095180059481416466830164706686480193654293861371218749634381741618791536248811983068686141003571186173429990197158857491971802155126515723654141328029478361148783721504684811628245142646184176818163908911930991115182966380406711395571153168019873183105783121035259479699437638261378016580522271742512712372593190511609603692132045561976246329723541993452210039361178491361631878917923389694985213218317124435601896897615210676140004741569772416671033180495385684021176899487452092921480170391941174199014735659108709442826719175938781208685016715442744868219030961628240612749877110051542877411714751411959117129777823819668132985681556645811533326178198741840476728714955400721168683652590581703522325061702483519699821353928290747631237144183238521319006110327393195143163095701420987823246878579610152753170947741013086815723147474361479333931797761713799441151619551243582519614693255300911341265142167076092903333645130939461927158455645701981213617800790182452701870771612216796122252801644595718967043387101617443606390164019676300172839121747863917945733175547215482552436440750610247790152667036079568159106581573404717457849241622018809883654754916063519245847184647861858884114596578718586593729471483147613112337135444639380123109868833447931221980312599923191002431541391210297198623026253391859575424424743911487462709256041105313262773607593012684074181889354909586935356171589301478977411162399131766613864007141410461534688970115459774351102057837697124179219831635781213605743141174021488511916061996364201189137130396737029869177411161228043618029630157422771603686129422381599791558693511272413917001599198271662942760118666491490360111264709143859775859532173339421525221119945709194353091520343212603151644079712429614938350659037071372802569192981192273681228815001621265620967120511225349181187621456943814648492151799221926268022854771018837713819588108489466461779141502691461015179063571331433512036316116201261598553917838839539043310031892196960389810317201764577802335436571960811215238763351405314140196894784817053242145717732602247136416621344671314587831166417534031158165710051223742517847875200451815479997112475191319591087335361192339845131801976539512730671002612118343753737414074734174538491587318919114141497305317563261113794718588769158157711829176988891785361616745079117302283533031139471831777610817969536440075771635323033621994551318243463189951416588481276415780966488308198217214129860111088756581685194544287013121017670518719587195226042604521195375117652734359960578885041863472027188631435394163621901806705846916472882600197648346040919496144224410996240799161563505041514696644481280961051848316266457793571476061261631601392437259947153148613171834815691102731027364436454469069261617258517414794158777099591885116545581008728167273931404920817298222148105191416748498011239518416116052163361267236948162440215011092143391951305185616128675113731041682871734759425395321217798754781094150198146703122187426567941710026717159019106172862451456119730595909970477533110389859498833519444438159974841195857618984757121520201027848318454564156446442845840135440921833903811820997147617695527382192720251234337015322653531467860375343941174105505181805273393635999474310748449476723348912358569530740477786667162371094738467262672856792991870773625955781032337166600809497368m�#�'�*�,d@�F�G�bqtς��0�ɠI����8��b#�2T6�=�>?�B3H�I�Pa�mto��$�ڎs� �����`�)�Q�)K-�19�?{Zyk�r�����ӈ���d������o�sU �/P2�F�i{��s�6���J�k�k���n���$`02*679����)�����;����������T&(5;�@JD�GzN�T�U�V_�i�z����b� �,�N�P�pc-�-�3�K�NNdoz�K�.���0��� �^������� 5L;"@dC�P�[�\:^�_�`�d�kݶ�������l��� J�,� _ e � y � ~ �< 4C �F �P oa �c ,n sq x� �� �� � x� � �� �� �� :� �� � � � � �M �N �c p |y �{ R� o� �� B� � � �! : ;B �k �o ]} �} �� �� b� �� �" 2% G2 3 �? �q �� G� _� �� �� � � � � �: �M 3R �S �X ��"�&*�TU[�f�t?�i����C������� �.�1Y@`Nct� �G�d���"�����k�!�<x���Q�i��������v� ��x����������{���������(O,f9�; B�N#RMU�`�sMw���l�h�-����T���<�s���j������� 2���!:4N�Q�W)]�_ڠȳ���Y�W���)���� � %i�^�ޮ�����_��;>>�@kE�NZ�_#k�np�pI�ӄo������n�����O�M���-�Y�T�c�B��� Z�DfG�a%^��-���x�^����Vkg�-^H�z��Q�H�����N�P���z��M������� U  mv�%z�������Y�o����1�h� V"*67�f�tC~)���V�|������\�w�� ���:�>@HAFfuzV}dR�^�h��������26�H�J`Ya�u��c�n�6�D�a���G�����:�����=�ȑ7�]�������?�a � � � i+ �� (� s� C!�=!KP!�q!�v!@{! �!��!p�!R�!f�!�!��!">"E "h"�""�%"�z"{�"\�"+#~#�#JA#�D#�H#y]#m#�o#{q#�s#��#o�#7�##�#��#4�#��# �#��#��#��#2;$rL$LT$N^$�c$�j$�n$+z$V�$��$��$1�$�$��$P�$��$/�$��$��$�$�$c%�%{%�%�%* %sP%Td%�o%��%u�%��%V�%��%��%�%��%��%��%��% &�&�& .&X&�^&�`&�c&Ed&�&ݑ&��&��&ۨ&�&��&��&�&��&�'�'�'�'�"'�&'�('�E'ZP'Y['R�'˙'¡'9�'8�'��'��'x�'��'�( (�((} (�)(�?(�M(�c(/h(�(d�(��(!�(��(b)>b)�k)�q)0t)S})��)��)0�)��)=�)��)�)r�)��)� *ñ*�*��*��*��*-�*S�*o +�0+�7+ :+�=+�>+WB+wK+�P+�i+�+X�+��+��+!",�8, ;,F=,_>,�@,�\,��,��,8�,+�,C-�-�-0.-I0-4?-C-�-�.�.�.%.�.�..�A.F. P.5T.�U.sZ.d].�f.�i.w.iz.$�.s�.c�.��.j�.5�.��.-�.�:/sb/�i/�t/,�/��/�/�/��/.�/��/w�/� 0�0 �0t)1�.1�/1�B1�C1�L1*O1�W1�\1M]1�a1�b1�k1 1�1&�1��1Y�1�1c2 2�"2(i2^q2*s2~t2L�2'�2��2V�2��2��2��2��2N�28�2��2��2/�2?363�,3�43�73�C3�H3EO3�P3�Q3�W3FY3�[3�_3�3k�3b�3Ө3b�3o�3+�3�3��3��3�3��3b�3��3��3�4D4�+4�F4QQ4�W4�Z4�]4�l4Wq4ʯ4H�45#5�.5 H5�Y5/v5$w5�54�5$�5��5n�5�5Ľ5��5��5��5��5g�5��5Q�5��5�5��5�6� 6i6�n6�w6�y6B�6��6y�6t�6�6�6B�6��6˹6�6�6_�6��6��6��6�7Q7/7�g7�i7wr7ev7m�7ׄ7��7�7U�7p�7\�7��7b�7��758�898C8& 8-(8�18�38�78fC8RQ8x8�8��8��8b�8V�8��83�8��8��8��8��8��8 �8��9�9<�9��92�9 �9��9:�:�:v_:�o:0v:��:Ƅ:W�:Q�:��:��:+�:1�:��:��:�:��:��:��:�:��:z�:,�:z�:��: �:��:� ;�;K;�4;�=;{S;6];u_;hh;�x;�;f�;��;'�;��;��;��;��;�<2<7<�U<,Y<uY<,g<�i<+n</* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.cloudtrace.v2beta1.model; /** * Describes a sink used to export traces to a BigQuery dataset. The sink must be created within a * project. * *

This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Trace API. For a detailed explanation see: * https://developers.google.com/api-client-library/java/google-http-java-client/json *

* * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class TraceSink extends com.google.api.client.json.GenericJson { /** * Required. The canonical sink resource name, unique within the project. Must be of the form: * * project/[PROJECT_NUMBER]/traceSinks/[SINK_ID]. * * E.g.: * * `"projects/12345/traceSinks/my-project-trace-sink"`. * * Sink identifiers are limited to 256 characters and can include only the following characters: * upper and lower-case alphanumeric characters, underscores, hyphens, and periods. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * Required. The export destination. * The value may be {@code null}. */ @com.google.api.client.util.Key private OutputConfig outputConfig; /** * Output only. A service account name for exporting the data. This field is set by sinks.create * and sinks.update. The service account will need to be granted write access to the destination * specified in the output configuration, see [Granting access for a resource](/iam/docs/granting- * roles-to-service-accounts#granting_access_to_a_service_account_for_a_resource). To create * tables and write data this account will need the dataEditor role. Read more about roles in the * [BigQuery documentation](https://cloud.google.com/bigquery/docs/access- * control#permissions_and_roles). E.g.: * * "" * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String writerIdentity; /** * Required. The canonical sink resource name, unique within the project. Must be of the form: * * project/[PROJECT_NUMBER]/traceSinks/[SINK_ID]. * * E.g.: * * `"projects/12345/traceSinks/my-project-trace-sink"`. * * Sink identifiers are limited to 256 characters and can include only the following characters: * upper and lower-case alphanumeric characters, underscores, hyphens, and periods. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Required. The canonical sink resource name, unique within the project. Must be of the form: * * project/[PROJECT_NUMBER]/traceSinks/[SINK_ID]. * * E.g.: * * `"projects/12345/traceSinks/my-project-trace-sink"`. * * Sink identifiers are limited to 256 characters and can include only the following characters: * upper and lower-case alphanumeric characters, underscores, hyphens, and periods. * @param name name or {@code null} for none */ public TraceSink setName(java.lang.String name) { this.name = name; return this; } /** * Required. The export destination. * @return value or {@code null} for none */ public OutputConfig getOutputConfig() { return outputConfig; } /** * Required. The export destination. * @param outputConfig outputConfig or {@code null} for none */ public TraceSink setOutputConfig(OutputConfig outputConfig) { this.outputConfig = outputConfig; return this; } /** * Output only. A service account name for exporting the data. This field is set by sinks.create * and sinks.update. The service account will need to be granted write access to the destination * specified in the output configuration, see [Granting access for a resource](/iam/docs/granting- * roles-to-service-accounts#granting_access_to_a_service_account_for_a_resource). To create * tables and write data this account will need the dataEditor role. Read more about roles in the * [BigQuery documentation](https://cloud.google.com/bigquery/docs/access- * control#permissions_and_roles). E.g.: * * "service-00000001@" * @return value or {@code null} for none */ public java.lang.String getWriterIdentity() { return writerIdentity; } /** * Output only. A service account name for exporting the data. This field is set by sinks.create * and sinks.update. The service account will need to be granted write access to the destination * specified in the output configuration, see [Granting access for a resource](/iam/docs/granting- * roles-to-service-accounts#granting_access_to_a_service_account_for_a_resource). To create * tables and write data this account will need the dataEditor role. Read more about roles in the * [BigQuery documentation](https://cloud.google.com/bigquery/docs/access- * control#permissions_and_roles). E.g.: * * "service-0000" * @param writerIdentity writerIdentity or {@code null} for none */ public TraceSink setWriterIdentity(java.lang.String writerIdentity) { this.writerIdentity = writerIdentity; return this; } @Override public TraceSink set(String fieldName, Object value) { return (TraceSink) super.set(fieldName, value); } @Override public TraceSink clone() { return (TraceSink) super.clone(); } } package cn.xpbootcamp.gilded_rose; import org.joda.time.LocalDate; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class BackstagePassTest { @Test public void shouldHaveBackstagetPass() { String listedDate = "2020-03-21"; String showDate = "2020-04-01"; BackstagePass backstagePass = new BackstagePass(10, 10, listedDate, showDate); assertEquals(10, backstagePass.getQuality()); assertEquals(10, backstagePass.getSellIn()); assertEquals(listedDate, backstagePass.getListedDate()); } @Test public void shouldUpdateSellInAndQualityWhenShowTimePassed() { String showDate = new LocalDate().minusDays(1).toString(); String listedDate = new LocalDate().minusDays(3).toString(); String today = new LocalDate().toString(); BackstagePass backstagePass = new BackstagePass(10, 10, listedDate, showDate); backstagePass.updateQualityAndSellIn(); assertEquals(0, backstagePass.getQuality()); assertEquals(13, backstagePass.getSellIn()); assertEquals(today, backstagePass.getListedDate()); } @Test public void shouldUpdateSellInAndQualityWhenMoreThanTenDaysToShowTime(){ String showDate = new LocalDate().plusDays(15).toString(); String listedDate = new LocalDate().minusDays(1).toString(); String today = new LocalDate().toString(); BackstagePass backstagePass = new BackstagePass(10, 10, listedDate, showDate); backstagePass.updateQualityAndSellIn(); assertEquals(11, backstagePass.getQuality()); assertEquals(11, backstagePass.getSellIn()); assertEquals(today, backstagePass.getListedDate()); } @Test public void shouldUpdateSellInAndQualityWhenTenDaysToShowTime(){ String showDate = new LocalDate().plusDays(10).toString(); String listedDate = new LocalDate().minusDays(1).toString(); String today = new LocalDate().toString(); BackstagePass backstagePass = new BackstagePass(10, 10, listedDate, showDate); backstagePass.updateQualityAndSellIn(); assertEquals(12, backstagePass.getQuality()); assertEquals(11, backstagePass.getSellIn()); assertEquals(today, backstagePass.getListedDate()); } @Test public void shouldUpdateSellInAndQualityWhenFiveDaysToShowTime(){ String showDate = new LocalDate().plusDays(5).toString(); String listedDate = new LocalDate().minusDays(1).toString(); String today = new LocalDate().toString(); BackstagePass backstagePass = new BackstagePass(10, 10, listedDate, showDate); backstagePass.updateQualityAndSellIn(); assertEquals(13, backstagePass.getQuality()); assertEquals(11, backstagePass.getSellIn()); assertEquals(today, backstagePass.getListedDate()); } } open-hand/hzero-boot-parent1-10 package org.hzero.boot.imported.infra.mapper; import java.util.Date; import java.util.List; import org.apache.ibatis.annotations.Param; import org.hzero.boot.imported.domain.entity.Import; import io.choerodon.mybatis.common.BaseMapper; /** * Mapper * * @author 2018-12-19 14:57:57 */ public interface ImportMapper extends BaseMapper { /** * 查询导入记录 * * @param tenantId 租户 * @param templateCode 模板编码 * @param creationDateFrom 创建时间从 * @param creationDateTo 创建时间至 * @return 导入记录 */ List listImport(@Param("tenantId") Long tenantId, @Param("templateCode") String templateCode, @Param("creationDateFrom") Date creationDateFrom, @Param("creationDateTo") Date creationDateTo); } 0 import com.littlejenny.gulimall.auth.GuliAuth15000Main; import com.littlejenny.gulimall.auth.constants.AuthConstants; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) @SpringBootTest(classes = {GuliAuth15000Main.class}) public class RedisTest { @Autowired private RedisTemplate template; @Test public void redis(){ System.out.println(template); } @Autowired AuthConstants constants; } common/src/main/java/com/jim/androidarchiteture/common/viewutil/ViewUtils.java package com.jim.androidarchiteture.common.viewutil; import android.content.Context; import android.view.LayoutInflater; import android.view.View; /** * Created by Administrator on 2015/6/5. */ public class ViewUtils { public static View getItemView(Context context, int resource) { LayoutInflater inflater = LayoutInflater.from(context); return inflater.inflate(resource, null); } public static void getColor(Context context, int color) { } } package ru.investflow.android.chat; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import org.jetbrains.annotations.NotNull; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import ru.investflow.android.chat.util.AppUtils; import ru.investflow.android.chat.util.ThreadUtils; public class Messenger { public interface SendCallback { void onSuccess(); void onError(String message); void onCanceled(); } public static void sendMessage(@NotNull Context ctx, @NotNull String text, @NotNull SendCallback callback) { String login = AppSettings.getLogin(); String passwordHash = AppSettings.getPasswordHash(); if (TextUtils.isEmpty(login) || TextUtils.isEmpty(passwordHash)) { sendWithLoginDialog(ctx, text, callback); } else { sendMessage(text, login, passwordHash, callback); } } private static void sendMessage(final String text, final String login, final String passwordHash, final SendCallback callback) { ThreadUtils.runOnBackgroundThread(new Runnable() { @Override public void run() { _sendMessage(text, login, passwordHash, callback); } }); } public static void sendWithLoginDialog(@NotNull Context ctx, final String text, final SendCallback callback) { @SuppressLint("InflateParams") final View prompt = LayoutInflater.from(ctx).inflate(R.layout.login_dialog, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctx); alertDialogBuilder.setView(prompt); alertDialogBuilder.setTitle("Вход"); alertDialogBuilder.setCancelable(false).setPositiveButton("ОК", new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int id) { EditText loginField = (EditText) prompt.findViewById(R.id.login_name); EditText passwordField = (EditText) prompt.findViewById(R.id.login_password); String login = loginField.getText().toString(); String password = passwordField.getText().toString(); String passwordHash = AppUtils.md5(password); if (TextUtils.isEmpty(login) || TextUtils.isEmpty(password)) { return; } AppSettings.setLoginAndPasswordHash(login, passwordHash); sendMessage(text, login, passwordHash, callback); } }); alertDialogBuilder.setNegativeButton("Отмена", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); callback.onCanceled(); } }); alertDialogBuilder.show(); } public static void _sendMessage(String text, String login, String passwordHash, SendCallback callback) { try { String urlParameters = "login=" + encode(login) + "&password=" + + "&message=" + encode(text); URL url = new URL(AppConstants.INVESTFLOW_RU + "/api/chat/send?" + urlParameters); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setInstanceFollowRedirects(false); conn.setUseCaches(false); Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); StringBuilder response = new StringBuilder(); for (int c; (c = in.read()) >= 0; ) { response.append((char) c); } JSONObject json = new JSONObject(response.toString()); if (json.optBoolean("success", false)) { callback.onSuccess(); return; } String error = json.optString("error", ""); if ("1".equals(error) || "2".equals(error)) { callback.onError("Ошибка: неверное имя пользователя или пароль!"); AppSettings.resetLoginAndPassword(); } else if ("3".equals(error)) { callback.onError("Ошибка: попытка отправить пустое сообщение!"); } else { callback.onError("Ошибка: " + json.toString()); } } catch (Exception e) { callback.onError("Ошибка: " + e.getMessage()); } } private static String encode(String text) throws UnsupportedEncodingException { return URLEncoder.encode(text, "UTF-8"); } } Celebrate-future/tomee /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomee.microprofile.tck.opentracing; import org.apache.cxf.jaxrs.client.spec.ClientBuilderImpl; import org.apache.johnzon.jaxrs.JohnzonProvider; import org.apache.johnzon.mapper.Mapper; import org.apache.johnzon.mapper.MapperBuilder; import org.eclipse.microprofile.opentracing.tck.tracer.TestSpanTree; import java.util.Collections; /** * CXF does not scan for @Provider in ClientBuilder, so when we receive the server payload, we can't deserialize it * with Johnzon */ public class MicroProfileOpenTracingClientBuilder extends ClientBuilderImpl { public MicroProfileOpenTracingClientBuilder() { super(); final Mapper mapper = new MapperBuilder() .setFailOnUnknownProperties(false) .build(); register(new JohnzonProvider(mapper, Collections.emptyList())); } } package io.github.cemartin01.graphmapper.graphql.schema; import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target(ElementType.METHOD) public @interface GraphQLSchemaBasedTest { } /* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package corba.codebase; import test.Test; import corba.framework.*; import java.util.*; import java.io.*; import com.sun.corba.ee.spi.orb.ORB; public class CodeBaseTest extends CORBATest { public static final String VALUE_DIR = "values"; public static final String STUBTIE_DIR = "stubtie"; public static final String[] VALUES = new String[] { "TestValue.java" }; protected void doTest() throws Throwable { if (test.Test.useJavaSerialization()) { return; } // Generate stubs and ties in the STUBTIE_DIR off of // the main output directory. String stubTieDir = (new File(Options.getOutputDirectory() + STUBTIE_DIR + File.separator)).getAbsolutePath(); String valueDir = (new File(Options.getOutputDirectory() + VALUE_DIR + File.separator)).getAbsolutePath(); String oldOutputDir = Options.getOutputDirectory(); Options.setRMICClasses(new String[] { "corba.codebase.Server" }); Options.addRMICArgs("-nolocalstubs -iiop -keep -g"); Options.setOutputDirectory(stubTieDir); compileRMICFiles(); // Also generate a Serializable in a different directory // to test value code downloading Options.setJavaFiles(VALUES); Options.setOutputDirectory(valueDir); compileJavaFiles(); Options.setOutputDirectory(oldOutputDir); String oldClasspath = Options.getClasspath(); String cpWithAllClasses = stubTieDir + File.pathSeparator + valueDir + File.pathSeparator + Options.getClasspath(); Controller orbd = createORBD(); orbd.start(); int webServerPort = Options.getUnusedPort().getValue(); Controller webServer = createWebServer(oldOutputDir, webServerPort); webServer.start(); Options.setClasspath(oldClasspath); // Add the special RMI property for code downloading. // NOTE: Unless it ends in a slash, the RMI code assumes // it is a jar file! Properties serverProps = Options.getServerProperties(); Properties clientProps = Options.getClientProperties(); String baseURL = "http://localhost:" + webServerPort + "/"; String fullCodeBase = baseURL + STUBTIE_DIR + "/ " + baseURL + VALUE_DIR + "/"; // First test code downloading where the client downloads the // stub and value classes serverProps.put("java.rmi.server.codebase", fullCodeBase); testDownloading(cpWithAllClasses, oldClasspath, false); // Now test code downloading where the server downloads the // value classes // Note: Giving server only the codebase so it can download // the Tie. It will get the info for how to download the // valuetype from the client. serverProps.put("java.rmi.server.codebase", baseURL + STUBTIE_DIR + "/"); clientProps.put("java.rmi.server.codebase", fullCodeBase); testDownloading(cpWithAllClasses, oldClasspath, true); orbd.stop(); webServer.stop(); } void testDownloading(String fullClasspath, String shortClasspath, boolean serverDownloading) throws Exception { Controller server, client; Properties clientProps = Options.getClientProperties(); if (serverDownloading) { clientProps.put(Tester.SERVER_DOWNLOADING_FLAG, "true"); Options.setClasspath(shortClasspath); server = createServer("corba.codebase.Server", "server_dl"); Options.setClasspath(fullClasspath); client = createClient("corba.codebase.Client", "client_reg"); } else { Options.setClasspath(fullClasspath); server = createServer("corba.codebase.Server", "server_reg"); Options.setClasspath(shortClasspath); client = createClient("corba.codebase.Client", "client_dl"); Options.setClasspath(fullClasspath); } Test.dprint("Testing code downloading by the " + (serverDownloading ? "server" : "client")); server.start(); client.start( ); // Note that the test framework will handle reporting if the overall // test failed since it will check the exit codes of the client and // server controllers during cleanup if (client.waitFor(120000) == Controller.SUCCESS) Test.dprint("PASSED"); else Test.dprint("FAILED"); client.stop(); server.stop(); } public Controller createWebServer(String webRootDirectory, int webServerPort) throws Exception { Test.dprint("Creating WebServer object..."); Controller executionStrategy; if (debugProcessNames.contains("WebServer")) executionStrategy = new DebugExec(); else executionStrategy = new ExternalExec(); Properties props = Options.getServerProperties() ; int emmaPort = EmmaControl.setCoverageProperties( props ) ; String args[] = new String[] { "-port", "" + webServerPort, "-docroot", webRootDirectory }; FileOutputDecorator exec = new FileOutputDecorator(executionStrategy); Hashtable extra = new Hashtable(1); // Make sure that starting the web server controller waits until the web server is ready extra.put(ExternalExec.HANDSHAKE_KEY, "Ready."); exec.initialize("corba.codebase.WebServer", "WebServer", props, null, args, Options.getReportDirectory() + "webserver.out.txt", Options.getReportDirectory() + "webserver.err.txt", extra, emmaPort ) ; controllers.add(exec); return exec; } } 1000+ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.remote; import java.io.IOException; import java.net.URI; import java.util.HashMap; import java.util.Map; import org.apache.nifi.remote.protocol.CommunicationsSession; public class Peer implements Communicant { private final PeerDescription description; private final CommunicationsSession commsSession; private final String url; private final String clusterUrl; private final Map penaltyExpirationMap = new HashMap<>(); private boolean closed = false; public Peer(final PeerDescription description, final CommunicationsSession commsSession, final String peerUrl, final String clusterUrl) { this.description = description; this.commsSession = commsSession; this.url = peerUrl; this.clusterUrl = clusterUrl; try { // Parse peerUrl to validate it. new URI(peerUrl); } catch (final Exception e) { throw new IllegalArgumentException("Invalid URL: " + peerUrl); } } public PeerDescription getDescription() { return description; } @Override public String getUrl() { return url; } public String getClusterUrl() { return clusterUrl; } public CommunicationsSession getCommunicationsSession() { return commsSession; } public void close() throws IOException { this.closed = true; // Consume the InputStream so that it doesn't linger on the Peer's outgoing socket buffer try { commsSession.getInput().consume(); } finally { commsSession.close(); } } /** * Penalizes this peer for the given destination only for the provided * number of milliseconds * * @param destinationId id of destination * @param millis period of time to penalize peer */ public void penalize(final String destinationId, final long millis) { final Long currentPenalty = penaltyExpirationMap.get(destinationId); final long proposedPenalty = System.currentTimeMillis() + millis; if (currentPenalty == null || proposedPenalty > currentPenalty) { penaltyExpirationMap.put(destinationId, proposedPenalty); } } public boolean isPenalized(final String destinationId) { final Long currentPenalty = penaltyExpirationMap.get(destinationId); return (currentPenalty != null && currentPenalty > System.currentTimeMillis()); } public boolean isClosed() { return closed; } @Override public String getHost() { return description.getHostname(); } @Override public int hashCode() { return 8320 + url.hashCode(); } @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (!(obj instanceof Peer)) { return false; } final Peer other = (Peer) obj; return this.url.equals(other.url); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Peer[url=").append(url); if (closed) { sb.append(",CLOSED"); } sb.append("]"); return sb.toString(); } @Override public int getPort() { return description.getPort(); } @Override public String getDistinguishedName() { return commsSession.getUserDn(); } @Override public String createTransitUri(String sourceFlowFileIdentifier) { return commsSession.createTransitUri(url, sourceFlowFileIdentifier); } } /* * Created on 2012/02/15 * Copyright (c) 2010-2012, . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Wei-ju Wu nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.zmpp.glulx; import org.zmpp.glk.Glk; class GlkIOSystem extends IOSystem { private Glk glk; public GlkIOSystem(GlulxVM vm, Glk glk, int rock) { super(vm, rock); this.glk = glk; } public int id() { return 2; } public void streamChar(char c) { glk.put_char(c); } public void streamUniChar(int c) { glk.put_char_uni(c); } // streamstr actions public StreamStrState handleChar8(char c, boolean inBetween, int currentStreamByte, int currentStreamBit) { glk.put_char(c); return StreamStrState.Continue; } public StreamStrState handleChar32(int c, boolean inBetween, int currentStreamByte, int currentStreamBit) { glk.put_char_uni(c); return StreamStrState.Continue; } public StreamStrState handleHuffmanCString(int nodeAddr, int currentStreamByte, int currentStreamBit, boolean inBetween) { int cstrAddr = nodeAddr + 1; int currentChar = vm.memByteAt(cstrAddr); while (currentChar != 0) { streamChar((char) currentChar); cstrAddr++; currentChar = vm.memByteAt(cstrAddr); } return StreamStrState.Continue; } public StreamStrState handleHuffmanUnicodeString(int nodeAddr, int currentStreamByte, int currentStreamBit, boolean inBetween) { int uniCStrAddr = nodeAddr + 1; int currentChar = vm.memIntAt(uniCStrAddr); while (currentChar != 0) { streamChar((char) (currentChar & 0xffff)); uniCStrAddr += 4; currentChar = vm.memIntAt(uniCStrAddr); } return StreamStrState.Continue; } } package com.java110.community.dao; import com.java110.utils.exception.DAOException; import java.util.List; import java.util.Map; public interface IRoomRenovationRecordServiceDao { /** * 保存 装修记录信息 * * @param info * @throws DAOException DAO异常 */ void saveRoomRenovationRecordInfo(Map info) throws DAOException; /** * 查询装修记录信息(instance过程)(与文件表关联) * 根据bId 查询装修记录信息 * * @param info bId 信息 * @return 装修记录信息 * @throws DAOException DAO异常 */ List getRoomRenovationRecordsInfo(Map info) throws DAOException; /** * 查询装修记录 * * @param info * @return * @throws DAOException */ List findRoomRenovationRecordsInfo(Map info); /** * 查询装修记录总数(与文件表关联) * * @param info 装修记录信息 * @return 装修记录数量 */ int queryRoomRenovationRecordsCount(Map info); /** * 查询装修记录数 * * @param info * @return */ int getRoomRenovationRecordsCount(Map info); /** * 修改装修记录信息 * * @param info * @return */ void updateRoomRenovationRecordInfo(Map info); } 1-10 // Author: () package com.google.libwebm.mkvmuxer; import com.google.libwebm.Common; public abstract class IMkvWriter extends Common { public static IMkvWriter newMkvWriter(long nativePointer) { IMkvWriter mkvWriter = null; int type = getType(nativePointer); if (type == 1) { mkvWriter = new MkvWriter(nativePointer); } return mkvWriter; } public abstract void elementStartNotify(long elementId, long position); public abstract long position(); public abstract int position(long position); public abstract boolean seekable(); public abstract int write(byte[] buffer); protected IMkvWriter() { super(); } protected IMkvWriter(long nativePointer) { super(nativePointer); } private static native int getType(long jMkvReader); } /* * Copyright 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xin.recyclerview.sample.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.xin.recyclerview.OnItemClickListener; import com.xin.recyclerview.OnItemMenuClickListener; import com.xin.recyclerview.SwipeMenu; import com.xin.recyclerview.SwipeMenuBridge; import com.xin.recyclerview.SwipeMenuCreator; import com.xin.recyclerview.SwipeMenuItem; import com.xin.recyclerview.SwipeRecyclerView; import com.xin.recyclerview.sample.R; import com.xin.recyclerview.sample.adapter.MainAdapter; import com.xin.recyclerview.widget.DefaultItemDecoration; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; /** *

* Menu和ViewPager结合的演示,Fragment。 *

* Created by on 2016/8/12. */ public class MenuFragment extends Fragment { private SwipeRecyclerView mRecyclerView; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_menu, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { mRecyclerView = view.findViewById(R.id.recycler_view); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); mRecyclerView.addItemDecoration( new DefaultItemDecoration(ContextCompat.getColor(getContext(), R.color.divider_color))); mRecyclerView.setOnItemClickListener(mItemClickListener); mRecyclerView.setSwipeMenuCreator(mSwipeMenuCreator); mRecyclerView.setOnItemMenuClickListener(mItemMenuClickListener); MainAdapter menuAdapter = new MainAdapter(getContext()); mRecyclerView.setAdapter(menuAdapter); List dataList = new ArrayList<>(); for (int i = 0; i < 30; i++) { dataList.add("我是第" + i + "个。"); } menuAdapter.notifyDataSetChanged(dataList); } /** * RecyclerView的Item点击监听。 */ private OnItemClickListener mItemClickListener = new OnItemClickListener() { @Override public void onItemClick(View itemView, int position) { Toast.makeText(getContext(), "第" + position + "个", Toast.LENGTH_SHORT).show(); } }; /** * RecyclerView的Item中的Menu点击监听。 */ private OnItemMenuClickListener mItemMenuClickListener = new OnItemMenuClickListener() { @Override public void onItemClick(SwipeMenuBridge menuBridge, int position) { menuBridge.closeMenu(); int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。 int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。 if (direction == SwipeRecyclerView.RIGHT_DIRECTION) { Toast.makeText(getContext(), "list第" + position + "; 右侧菜单第" + menuPosition, Toast.LENGTH_SHORT).show(); } else if (direction == SwipeRecyclerView.LEFT_DIRECTION) { Toast.makeText(getContext(), "list第" + position + "; 左侧菜单第" + menuPosition, Toast.LENGTH_SHORT).show(); } } }; /** * 菜单创建器,在Item要创建菜单的时候调用。 */ private SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() { @Override public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int position) { int width = getResources().getDimensionPixelSize(R.dimen.dp_70); // 1. MATCH_PARENT 自适应高度,保持和Item一样高; // 2. 指定具体的高,比如80; // 3. WRAP_CONTENT,自身高度,不推荐; int height = ViewGroup.LayoutParams.MATCH_PARENT; SwipeMenuItem addItem = new SwipeMenuItem(getContext()).setBackground(R.drawable.selector_green) .setImage(R.drawable.ic_action_add) .setWidth(width) .setHeight(height); swipeLeftMenu.addMenuItem(addItem); // 添加菜单到左侧。 SwipeMenuItem closeItem = new SwipeMenuItem(getContext()).setBackground(R.drawable.selector_green) .setImage(R.drawable.ic_action_close) .setWidth(width) .setHeight(height); swipeRightMenu.addMenuItem(closeItem); // 添加菜单到右侧。 } }; }package ca.quickheaven.ocjp.gencol.vo; public class ShippableCrate implements Shippable { public void ship(Object t) { } } package urlshortener.bangladeshgreen.safeQueue; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import urlshortener.bangladeshgreen.domain.URISafe; import urlshortener.bangladeshgreen.repository.URISafeRepository; import java.util.Date; import java.util.List; /** * Class for periodic check of the shorten URIs * It's scheduled and when it runs, obtains all the outdated links from the DB, checking all again. * It checks the URIs by inserting again the URIs in the queue. */ public class SafePeriodicCheck { // Interval that sets when a URI has to be checked again (1h) private final long interval = 3600*1000; @Autowired private RabbitTemplate rabbitTemplate; @Autowired private URISafeRepository safeRepository; // One hour of delay (for checking "all" URIs) @Scheduled(fixedDelay = 3600000L) public void send() { Date now = new Date(); now.setTime(now.getTime()-interval); List list = safeRepository.findByDateLessThan(now.getTime()); for(URISafe uri : list) { this.rabbitTemplate.convertAndSend("safeQueue",uri.getTarget()); } } }package org.apereo.portal.portlets.layout.dlm.remoting; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collections; import java.util.Set; import javax.naming.Name; import org.apereo.portal.EntityIdentifier; import org.apereo.portal.IBasicEntity; import org.apereo.portal.groups.GroupsException; import org.apereo.portal.groups.IEntityGroup; import org.apereo.portal.groups.IGroupMember; import org.apereo.portal.groups.IIndividualGroupService; import org.apereo.portal.layout.dlm.remoting.GroupListHelperImpl; import org.apereo.portal.layout.dlm.remoting.JsonEntityBean; import org.apereo.portal.portlet.om.IPortletDefinition; import org.apereo.portal.portlets.groupselector.EntityEnum; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class GroupListHelperImplTest { @Mock private IEntityGroup entityGroup; @Mock private IGroupMember groupMember; @Before public void setup() throws Exception { entityGroup = Mockito.mock(IEntityGroup.class); groupMember = Mockito.mock(IGroupMember.class); MockitoAnnotations.initMocks(this); } @Test public void testGetEntityTypesForGroupTypeGroup() { GroupListHelperImpl helper = new GroupListHelperImpl(); Set res = helper.getEntityTypesForGroupType(EntityEnum.GROUP.name()); assertEquals(2, res.size()); assertTrue(res.contains(EntityEnum.GROUP.name())); assertTrue(res.contains(EntityEnum.PERSON.toString())); } @Test public void testGetEntityTypesForGroupTypeCategory() { GroupListHelperImpl helper = new GroupListHelperImpl(); Set res = helper.getEntityTypesForGroupType(EntityEnum.CATEGORY.name()); assertEquals(2, res.size()); assertTrue(res.contains(EntityEnum.CATEGORY.name())); assertTrue(res.contains(EntityEnum.PORTLET.toString())); } @Test(expected = IllegalArgumentException.class) public void testGetEntityTypesForGroupTypePerson() { GroupListHelperImpl helper = new GroupListHelperImpl(); Set res = helper.getEntityTypesForGroupType(EntityEnum.PERSON.name()); } @Test(expected = IllegalArgumentException.class) public void testGetEntityTypesForGroupTypePortlet() { GroupListHelperImpl helper = new GroupListHelperImpl(); Set res = helper.getEntityTypesForGroupType(EntityEnum.PORTLET.name()); } @Test(expected = IllegalArgumentException.class) public void testGetEntityForPrincipalNull() { GroupListHelperImpl helper = new GroupListHelperImpl(); helper.getEntityForPrincipal(null); } @Test(expected = IllegalArgumentException.class) public void testGetPrincipalForEntityNull() { GroupListHelperImpl helper = new GroupListHelperImpl(); helper.getPrincipalForEntity(null); } @Test(expected = IllegalArgumentException.class) public void testSearchEntityNull() { GroupListHelperImpl helper = new GroupListHelperImpl(); helper.search(null, "asdf"); } @Test(expected = IllegalArgumentException.class) public void testGetEntityNull() { GroupListHelperImpl helper = new GroupListHelperImpl(); helper.getEntity(null, "asdf", true); } @Test(expected = IllegalArgumentException.class) public void testGetEntityTypeNull() { GroupListHelperImpl helper = new GroupListHelperImpl(); helper.getEntityType(null); } @Test public void testGetEntityTypePortlet() { GroupListHelperImpl helper = new GroupListHelperImpl(); IGroupMember mocked = manuallyMockGroupMember(IPortletDefinition.class); EntityEnum ee = helper.getEntityType(mocked); assertEquals("portlet", ee.toString()); } @Test public void testGetEntityTypeCategory() { GroupListHelperImpl helper = new GroupListHelperImpl(); MockedGroupMemberEntityGroup mocked = new MockedGroupMemberEntityGroup(IPortletDefinition.class); EntityEnum ee = helper.getEntityType(mocked); assertEquals("category", ee.toString()); } @Test(expected = IllegalArgumentException.class) public void testGetPrincipalForEntityTypeIsNull() { GroupListHelperImpl helper = new GroupListHelperImpl(); Mockito.when(entityGroup.getKey()).thenReturn("test-key"); Mockito.when(entityGroup.getName()).thenReturn("test-name"); Mockito.when(entityGroup.getCreatorID()).thenReturn("test-cid"); Mockito.when(entityGroup.getDescription()).thenReturn("test-desc"); JsonEntityBean jeb = new JsonEntityBean(entityGroup, EntityEnum.PORTLET); EntityEnum ee = null; jeb.setEntityType(ee); helper.getPrincipalForEntity(jeb); } @Test(expected = IllegalArgumentException.class) public void testLookupEntityNameNull() { GroupListHelperImpl helper = new GroupListHelperImpl(); helper.lookupEntityName(null); } @Test(expected = IllegalArgumentException.class) public void testLookupEntityNameTypeIsNull() { GroupListHelperImpl helper = new GroupListHelperImpl(); Mockito.when(entityGroup.getKey()).thenReturn("test-key"); Mockito.when(entityGroup.getName()).thenReturn("test-name"); Mockito.when(entityGroup.getCreatorID()).thenReturn("test-cid"); Mockito.when(entityGroup.getDescription()).thenReturn("test-desc"); JsonEntityBean jeb = new JsonEntityBean(entityGroup, EntityEnum.PORTLET); EntityEnum ee = null; jeb.setEntityType(ee); helper.lookupEntityName(jeb); } @Test(expected = IllegalArgumentException.class) public void testPopulateChildrenBeanNull() { GroupListHelperImpl helper = new GroupListHelperImpl(); helper.lookupEntityName(null); } @Test(expected = IllegalArgumentException.class) public void testGetEntityByGroupMemberNull() { GroupListHelperImpl helper = new GroupListHelperImpl(); helper.getEntity(null); } @Test public void testGetEntityBeansNull() { GroupListHelperImpl helper = new GroupListHelperImpl(); assertEquals(Collections.EMPTY_LIST, helper.getEntityBeans(null)); } @Test public void testGetEntityBeansEmpty() { GroupListHelperImpl helper = new GroupListHelperImpl(); assertEquals(Collections.EMPTY_LIST, helper.getEntityBeans(new ArrayList())); } private IGroupMember manuallyMockGroupMember(Class leafType) { return new IGroupMember() { @Override public Set getAncestorGroups() throws GroupsException { return null; } @Override public Set getParentGroups() throws GroupsException { return null; } @Override public String getKey() { return null; } @Override public Class getLeafType() { return leafType; } @Override public Class getType() { return null; } @Override public EntityIdentifier getUnderlyingEntityIdentifier() { return null; } @Override public boolean isDeepMemberOf(IEntityGroup group) throws GroupsException { return false; } @Override public boolean isGroup() { return false; } @Override public boolean isMemberOf(IEntityGroup group) throws GroupsException { return false; } @Override public IEntityGroup asGroup() { return null; } @Override public EntityIdentifier getEntityIdentifier() { return null; } }; } class MockedGroupMemberEntityGroup implements IGroupMember, IEntityGroup { Class leafType; public MockedGroupMemberEntityGroup(Class leafType) { this.leafType = leafType; } @Override public boolean hasMembers() throws GroupsException { return false; } @Override public boolean contains(IGroupMember gm) throws GroupsException { return false; } @Override public boolean deepContains(IGroupMember gm) throws GroupsException { return false; } @Override public Set getChildren() throws GroupsException { return null; } @Override public Set getDescendants() throws GroupsException { return null; } @Override public void addChild(IGroupMember gm) throws GroupsException {} @Override public void delete() throws GroupsException {} @Override public String getCreatorID() { return null; } @Override public String getDescription() { return null; } @Override public String getLocalKey() { return null; } @Override public String getName() { return null; } @Override public Name getServiceName() { return null; } @Override public boolean isEditable() throws GroupsException { return false; } @Override public void removeChild(IGroupMember gm) throws GroupsException {} @Override public void setCreatorID(String userID) {} @Override public void setDescription(String name) {} @Override public void setName(String name) throws GroupsException {} @Override public void update() throws GroupsException {} @Override public void updateMembers() throws GroupsException {} @Override public void setLocalGroupService(IIndividualGroupService groupService) throws GroupsException {} @Override public Set getAncestorGroups() throws GroupsException { return null; } @Override public Set getParentGroups() throws GroupsException { return null; } @Override public String getKey() { return null; } @Override public Class getLeafType() { return leafType; } @Override public Class getType() { return null; } @Override public EntityIdentifier getUnderlyingEntityIdentifier() { return null; } @Override public boolean isDeepMemberOf(IEntityGroup group) throws GroupsException { return false; } @Override public boolean isGroup() { return false; } @Override public boolean isMemberOf(IEntityGroup group) throws GroupsException { return false; } @Override public IEntityGroup asGroup() { return null; } @Override public EntityIdentifier getEntityIdentifier() { return null; } } } ph-jo/runelite import net.runelite.mapping.Export; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("ae") @Implements("MapIconReference") public class MapIconReference { @ObfuscatedName("pn") @ObfuscatedSignature( signature = "Ldk;" ) @Export("soundSystem1") static AbstractSoundSystem soundSystem1; @ObfuscatedName("pp") @ObfuscatedGetter( intValue = 97023161 ) static int field590; @ObfuscatedName("r") static int[] field588; @ObfuscatedName("ed") @ObfuscatedGetter( intValue = 1986808927 ) @Export("baseY") static int baseY; @ObfuscatedName("g") @ObfuscatedGetter( intValue = 1245105361 ) @Export("areaId") public int areaId; @ObfuscatedName("e") @ObfuscatedSignature( signature = "Lio;" ) public Coordinates field586; @ObfuscatedName("b") @ObfuscatedSignature( signature = "Lio;" ) public Coordinates field591; @ObfuscatedSignature( signature = "(ILio;Lio;)V" ) public MapIconReference(int var1, Coordinates var2, Coordinates var3) { this.areaId = var1; this.field586 = var2; this.field591 = var3; } @ObfuscatedName("e") @ObfuscatedSignature( signature = "(CII)I", garbageValue = "-1225648066" ) public static int method761(char var0, int var1) { int var2 = var0 << 4; if(Character.isUpperCase(var0) || Character.isTitleCase(var0)) { var0 = Character.toLowerCase(var0); var2 = (var0 << 4) + 1; } return var2; } @ObfuscatedName("fa") @ObfuscatedSignature( signature = "(IB)V", garbageValue = "-42" ) static void method759(int var0) { if(var0 == -1 && !Client.field1085) { class46.method684(); } else if(var0 != -1 && var0 != Client.field1084 && Client.field1083 != 0 && !Client.field1085) { ISAACCipher.method3902(2, class7.indexTrack1, var0, 0, Client.field1083, false); } Client.field1084 = var0; } @ObfuscatedName("ig") @ObfuscatedSignature( signature = "(IIIILjava/lang/String;I)V", garbageValue = "-1118013517" ) static void method760(int var0, int var1, int var2, int var3, String var4) { Widget var5 = class44.getWidgetChild(var1, var2); if(var5 != null) { if(var5.onOpListener != null) { ScriptEvent var6 = new ScriptEvent(); var6.widget = var5; var6.field779 = var0; var6.string = var4; var6.objs = var5.onOpListener; class71.method1203(var6); } boolean var8 = true; if(var5.contentType > 0) { var8 = NetWriter.method2140(var5); } if(var8) { if(DecorativeObject.method3163(class1.getWidgetClickMask(var5), var0 - 1)) { PacketNode var7; if(var0 == 1) { var7 = AbstractSoundSystem.method2350(ClientPacket.field2460, Client.field911.field1460); var7.packetBuffer.putInt(var1); var7.packetBuffer.putShort(var2); var7.packetBuffer.putShort(var3); Client.field911.method2135(var7); } if(var0 == 2) { var7 = AbstractSoundSystem.method2350(ClientPacket.field2458, Client.field911.field1460); var7.packetBuffer.putInt(var1); var7.packetBuffer.putShort(var2); var7.packetBuffer.putShort(var3); Client.field911.method2135(var7); } if(var0 == 3) { var7 = AbstractSoundSystem.method2350(ClientPacket.field2386, Client.field911.field1460); var7.packetBuffer.putInt(var1); var7.packetBuffer.putShort(var2); var7.packetBuffer.putShort(var3); Client.field911.method2135(var7); } if(var0 == 4) { var7 = AbstractSoundSystem.method2350(ClientPacket.field2380, Client.field911.field1460); var7.packetBuffer.putInt(var1); var7.packetBuffer.putShort(var2); var7.packetBuffer.putShort(var3); Client.field911.method2135(var7); } if(var0 == 5) { var7 = AbstractSoundSystem.method2350(ClientPacket.field2394, Client.field911.field1460); var7.packetBuffer.putInt(var1); var7.packetBuffer.putShort(var2); var7.packetBuffer.putShort(var3); Client.field911.method2135(var7); } if(var0 == 6) { var7 = AbstractSoundSystem.method2350(ClientPacket.field2461, Client.field911.field1460); var7.packetBuffer.putInt(var1); var7.packetBuffer.putShort(var2); var7.packetBuffer.putShort(var3); Client.field911.method2135(var7); } if(var0 == 7) { var7 = AbstractSoundSystem.method2350(ClientPacket.field2419, Client.field911.field1460); var7.packetBuffer.putInt(var1); var7.packetBuffer.putShort(var2); var7.packetBuffer.putShort(var3); Client.field911.method2135(var7); } if(var0 == 8) { var7 = AbstractSoundSystem.method2350(ClientPacket.field2390, Client.field911.field1460); var7.packetBuffer.putInt(var1); var7.packetBuffer.putShort(var2); var7.packetBuffer.putShort(var3); Client.field911.method2135(var7); } if(var0 == 9) { var7 = AbstractSoundSystem.method2350(ClientPacket.field2455, Client.field911.field1460); var7.packetBuffer.putInt(var1); var7.packetBuffer.putShort(var2); var7.packetBuffer.putShort(var3); Client.field911.method2135(var7); } if(var0 == 10) { var7 = AbstractSoundSystem.method2350(ClientPacket.field2387, Client.field911.field1460); var7.packetBuffer.putInt(var1); var7.packetBuffer.putShort(var2); var7.packetBuffer.putShort(var3); Client.field911.method2135(var7); } } } } } @ObfuscatedName("jm") @ObfuscatedSignature( signature = "(Liz;II)I", garbageValue = "-2067500032" ) static final int method758(Widget var0, int var1) { if(var0.dynamicValues != null && var1 < var0.dynamicValues.length) { try { int[] var2 = var0.dynamicValues[var1]; int var3 = 0; int var4 = 0; byte var5 = 0; while(true) { int var6 = var2[var4++]; int var7 = 0; byte var8 = 0; if(var6 == 0) { return var3; } if(var6 == 1) { var7 = Client.boostedSkillLevels[var2[var4++]]; } if(var6 == 2) { var7 = Client.realSkillLevels[var2[var4++]]; } if(var6 == 3) { var7 = Client.skillExperiences[var2[var4++]]; } int var9; Widget var10; int var11; int var12; if(var6 == 4) { var9 = var2[var4++] << 16; var9 += var2[var4++]; var10 = UnitPriceComparator.getWidget(var9); var11 = var2[var4++]; if(var11 != -1 && (!NetWriter.getItemDefinition(var11).isMembers || Client.isMembers)) { for(var12 = 0; var12 < var10.itemIds.length; ++var12) { if(var11 + 1 == var10.itemIds[var12]) { var7 += var10.itemQuantities[var12]; } } } } if(var6 == 5) { var7 = class237.clientVarps[var2[var4++]]; } if(var6 == 6) { var7 = class248.field3007[Client.realSkillLevels[var2[var4++]] - 1]; } if(var6 == 7) { var7 = class237.clientVarps[var2[var4++]] * 100 / 46875; } if(var6 == 8) { var7 = class265.localPlayer.combatLevel; } if(var6 == 9) { for(var9 = 0; var9 < 25; ++var9) { if(class248.field3002[var9]) { var7 += Client.realSkillLevels[var9]; } } } if(var6 == 10) { var9 = var2[var4++] << 16; var9 += var2[var4++]; var10 = UnitPriceComparator.getWidget(var9); var11 = var2[var4++]; if(var11 != -1 && (!NetWriter.getItemDefinition(var11).isMembers || Client.isMembers)) { for(var12 = 0; var12 < var10.itemIds.length; ++var12) { if(var11 + 1 == var10.itemIds[var12]) { var7 = 999999999; break; } } } } if(var6 == 11) { var7 = Client.energy; } if(var6 == 12) { var7 = Client.weight; } if(var6 == 13) { var9 = class237.clientVarps[var2[var4++]]; int var13 = var2[var4++]; var7 = (var9 & 1 << var13) != 0?1:0; } if(var6 == 14) { var9 = var2[var4++]; var7 = VarCString.getVarbit(var9); } if(var6 == 15) { var8 = 1; } if(var6 == 16) { var8 = 2; } if(var6 == 17) { var8 = 3; } if(var6 == 18) { var7 = (class265.localPlayer.x >> 7) + ClientPacket.baseX; } if(var6 == 19) { var7 = (class265.localPlayer.y >> 7) + baseY; } if(var6 == 20) { var7 = var2[var4++]; } if(var8 == 0) { if(var5 == 0) { var3 += var7; } if(var5 == 1) { var3 -= var7; } if(var5 == 2 && var7 != 0) { var3 /= var7; } if(var5 == 3) { var3 *= var7; } var5 = 0; } else { var5 = var8; } } } catch (Exception var14) { return -1; } } else { return -2; } } @ObfuscatedName("kd") @ObfuscatedSignature( signature = "(Liz;I)Z", garbageValue = "1934268057" ) static boolean method762(Widget var0) { return var0.isHidden; } } package ukim.mk.finki.konstantin.bogdanoski.wp.service; import ukim.mk.finki.konstantin.bogdanoski.wp.model.Pizza; import ukim.mk.finki.konstantin.bogdanoski.wp.model.PizzaOrder; import java.util.List; /** * @author () */ public interface OrderService extends BaseEntityCrudService { public List findByPizza(Pizza pizza); public void deleteByPizza(Pizza pizza); } package dreamlee.com.leelibrary; import android.support.v7.app.AlertDialog; import android.widget.TextView; import android.widget.Toast; import com.butterknife.Butterknife; import com.butterknife.Unbinder; import com.butterknife.annotations.BindView; import com.butterknife.annotations.OnClick; import zero.anytime.com.baselibrary.mvc.BaseActivity; public class SecondeActivity extends BaseActivity { Unbinder mUnbinder; @Override protected void initData() { mUnbinder = Butterknife.bind(this); getSupportFragmentManager().beginTransaction() .add(R.id.fragment, Fragment1.newInstance("hello world"), "f1") //.addToBackStack("fname") .commit(); } @Override protected void initView() { } @Override protected void initTitle() { } @Override protected void setContentView() { setContentView(R.layout.activity_second); } } package li.cil.bedrockores.common.world; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntObjectHashMap; import li.cil.bedrockores.common.config.Constants; import li.cil.bedrockores.common.config.Settings; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkGenerator; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.ChunkProviderServer; import net.minecraftforge.event.world.ChunkDataEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.relauncher.Side; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.WeakHashMap; public enum Retrogen { INSTANCE; // --------------------------------------------------------------------- // private static final String BEDROCK_ORES_TAG = Constants.MOD_ID; private static final String GENERATED_TAG = "generated"; private final TIntObjectMap> worldGenPending = new TIntObjectHashMap<>(3); private final TIntObjectMap> worldGenComplete = new TIntObjectHashMap<>(3); private final Map worldToChunkGenerator = new WeakHashMap<>(3); private final Object lock = new Object(); // --------------------------------------------------------------------- // public void clear() { worldGenPending.clear(); worldGenComplete.clear(); worldToChunkGenerator.clear(); } boolean markChunkGenerated(final int dimension, final int chunkX, final int chunkZ) { return put(worldGenComplete, dimension, new ChunkPos(chunkX, chunkZ)); } // --------------------------------------------------------------------- // @SubscribeEvent public void handleChunkLoadEvent(final ChunkDataEvent.Load event) { final int dimension = event.getWorld().provider.getDimension(); final ChunkPos chunkPos = event.getChunk().getPos(); if (event.getData().getCompoundTag(BEDROCK_ORES_TAG).getBoolean(GENERATED_TAG)) { markChunkGenerated(dimension, chunkPos.x, chunkPos.z); // Store for next save. return; } put(worldGenPending, dimension, chunkPos); } @SubscribeEvent public void handleChunkSaveEvent(final ChunkDataEvent.Save event) { final int dimension = event.getWorld().provider.getDimension(); final ChunkPos chunkPos = event.getChunk().getPos(); if (!isComplete(dimension, chunkPos)) { return; } final NBTTagCompound compound = event.getData().getCompoundTag(BEDROCK_ORES_TAG); compound.setBoolean(GENERATED_TAG, true); event.getData().setTag(BEDROCK_ORES_TAG, compound); } @SubscribeEvent public void tickEnd(final TickEvent.WorldTickEvent event) { if (Settings.retrogenSpeed < 1) { return; } if (event.side != Side.SERVER) { return; } final World world = event.world; final int dimension = world.provider.getDimension(); if (event.phase == TickEvent.Phase.END) { final Set pending = worldGenPending.get(dimension); if (pending == null) { return; } final IChunkProvider chunkProvider = world.getChunkProvider(); IChunkGenerator chunkGenerator = worldToChunkGenerator.get(world); if (chunkGenerator == null) { if (chunkProvider instanceof ChunkProviderServer) { chunkGenerator = ((ChunkProviderServer) chunkProvider).chunkGenerator; } else { chunkGenerator = world.provider.createChunkGenerator(); } worldToChunkGenerator.put(world, chunkGenerator); } final Iterable chunks = ImmutableList.copyOf(Iterables.limit(pending, Settings.retrogenSpeed)); for (final ChunkPos chunkPos : chunks) { // Seeding chunk RNG, see GameRegistry.generateWorld. final int chunkX = chunkPos.x; final int chunkZ = chunkPos.z; final long worldSeed = world.getSeed(); final Random random = new Random(worldSeed); final long xSeed = random.nextLong() >> 2 + 1L; final long zSeed = random.nextLong() >> 2 + 1L; final long chunkSeed = (xSeed * chunkX + zSeed * chunkZ) ^ worldSeed; random.setSeed(chunkSeed); WorldGeneratorBedrockOre.INSTANCE.generate(random, chunkX, chunkZ, world, chunkGenerator, chunkProvider); pending.remove(chunkPos); } if (pending.isEmpty()) { worldGenPending.remove(dimension); } } } // --------------------------------------------------------------------- // private boolean put(final TIntObjectMap> map, final int dimension, final ChunkPos chunkPos) { synchronized (lock) { Set complete = map.get(dimension); if (complete == null) { complete = new HashSet<>(128); map.put(dimension, complete); } return complete.add(chunkPos); } } private boolean isComplete(final int dimension, final ChunkPos chunkPos) { synchronized (lock) { final Set complete = worldGenComplete.get(dimension); return complete != null && complete.contains(chunkPos); } } }package grondag.xblocks.block; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.item.ItemPlacementContext; import net.minecraft.state.StateManager.Builder; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import grondag.fermion.modkeys.api.ModKeys; import grondag.xm.api.connect.species.Species; import grondag.xm.api.connect.species.SpeciesFunction; import grondag.xm.api.connect.species.SpeciesMode; import grondag.xm.api.connect.species.SpeciesProperty; public class SpeciesBlock extends Block { public SpeciesBlock(Settings settings) { super(settings); } @Override protected void appendProperties(Builder builder) { super.appendProperties(builder); builder.add(SpeciesProperty.SPECIES); } private final SpeciesFunction speciesFunc = SpeciesProperty.speciesForBlock(this); @Override public BlockState getPlacementState(ItemPlacementContext context) { final Direction onFace = context.getSide(); final BlockPos onPos = context.getBlockPos().offset(onFace.getOpposite()); final SpeciesMode mode = (context.getPlayer().isSneaking() || ModKeys.isSuperPressed(context.getPlayer())) ? SpeciesMode.COUNTER_MOST : SpeciesMode.MATCH_MOST; final int species = Species.speciesForPlacement(context.getWorld(), onPos, onFace, mode, speciesFunc); return getDefaultState().with(SpeciesProperty.SPECIES, species); } } websocket/src/main/java/io/basc/framework/websocket/adapter/AbstractWebSocketSession.java package io.basc.framework.websocket.adapter; import io.basc.framework.lang.Nullable; import io.basc.framework.logger.Logger; import io.basc.framework.logger.LoggerFactory; import io.basc.framework.messageing.BinaryMessage; import io.basc.framework.messageing.FragmentMessage; import io.basc.framework.messageing.Message; import io.basc.framework.messageing.TextMessage; import io.basc.framework.util.Assert; import io.basc.framework.websocket.CloseStatus; import io.basc.framework.websocket.PingMessage; import io.basc.framework.websocket.PongMessage; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public abstract class AbstractWebSocketSession implements NativeWebSocketSession { protected static final Logger logger = LoggerFactory.getLogger(NativeWebSocketSession.class); private final Map attributes = new ConcurrentHashMap(); @Nullable private T nativeSession; /** * Create a new instance and associate the given attributes with it. * * @param attributes * the attributes from the HTTP handshake to associate with the * WebSocket session; the provided attributes are copied, the * original map is not used. */ public AbstractWebSocketSession(@Nullable Map attributes) { if (attributes != null) { this.attributes.putAll(attributes); } } public Map getAttributes() { return this.attributes; } public T getNativeSession() { Assert.state(this.nativeSession != null, "WebSocket session not yet initialized"); return this.nativeSession; } @SuppressWarnings("unchecked") @Nullable public R getNativeSession(@Nullable Class requiredType) { return (requiredType == null || requiredType.isInstance(this.nativeSession) ? (R) this.nativeSession : null); } public void initializeNativeSession(T session) { Assert.notNull(session, "WebSocket session must not be null"); this.nativeSession = session; } protected final void checkNativeSessionInitialized() { Assert.state(this.nativeSession != null, "WebSocket session is not yet initialized"); } @SuppressWarnings("rawtypes") protected boolean isLast(Message message){ if(message instanceof FragmentMessage){ return ((FragmentMessage) message).isLast(); } return true; } public final void sendMessage(Message message) throws IOException { checkNativeSessionInitialized(); if (logger.isTraceEnabled()) { logger.trace("Sending " + message + ", " + this); } if (message instanceof TextMessage) { sendTextMessage((TextMessage) message); } else if (message instanceof BinaryMessage) { sendBinaryMessage((BinaryMessage) message); } else if (message instanceof PingMessage) { sendPingMessage((PingMessage) message); } else if (message instanceof PongMessage) { sendPongMessage((PongMessage) message); } else { throw new IllegalStateException("Unexpected WebSocketMessage type: " + message); } } protected abstract void sendTextMessage(TextMessage message) throws IOException; protected abstract void sendBinaryMessage(BinaryMessage message) throws IOException; protected abstract void sendPingMessage(PingMessage message) throws IOException; protected abstract void sendPongMessage(PongMessage message) throws IOException; public final void close() throws IOException { close(CloseStatus.NORMAL); } public final void close(CloseStatus status) throws IOException { checkNativeSessionInitialized(); if (logger.isDebugEnabled()) { logger.debug("Closing " + this); } closeInternal(status); } protected abstract void closeInternal(CloseStatus status) throws IOException; public String toString() { if (this.nativeSession != null) { return getClass().getSimpleName() + "[id=" + getId() + ", uri=" + getUri() + "]"; } else { return getClass().getSimpleName() + "[nativeSession=null]"; } } } hfuchshuber/turtlesrc/front_end/view_modules/variableViewer/Variable.java package front_end.view_modules.variableViewer; import javafx.beans.property.SimpleStringProperty; class Variable { private final SimpleStringProperty myName; private final SimpleStringProperty myValue; Variable (String aName, Number aValue) { myName = new SimpleStringProperty(aName); myValue = new SimpleStringProperty(aValue.toString()); } SimpleStringProperty getNameProperty () { return myName; } SimpleStringProperty getValueProperty () { return myValue; } String getName () { return myName.get(); } void setName (String aName) { myName.set(aName); } String getValue () { return myValue.get(); } void setValue (Number aValue) { myValue.set(aValue.toString()); } } /** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version * 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package org.apache.storm.redis.trident.state; import java.io.Serializable; import java.util.List; /** * KeyFactory defines conversion of state key (which could be compounded) -> Redis key. */ public interface KeyFactory extends Serializable { /** * Converts state key to Redis key. * @param key state key * @return Redis key */ String build(List key); /** * Default Key Factory. */ class DefaultKeyFactory implements KeyFactory { /** * {@inheritDoc} *

* Currently DefaultKeyFactory returns just first element of list. * * @param key state key * @return Redis key * @throws RuntimeException when key is compound key * @see KeyFactory#build(List) */ @Override public String build(List key) { if (key.size() != 1) { throw new RuntimeException("Default KeyFactory does not support compound keys"); } return (String) key.get(0); } } } 0 package com.example.demo.issue.vo; import lombok.Data; import java.util.List; /** * @author * @date 2021/10/27 */ @Data public class PageResult { private List list; private Pagination pagination; } 1-10 package com.wolfo.database; public interface PfEndPointWrapperRepository extends PfEndPointWrapperCrud, PfEndPointWrapperJpa{ } package com.example.cinema.blImpl.sales; import com.example.cinema.bl.sales.ConsumptionService; import com.example.cinema.testpack.CinemaTest; import com.example.cinema.vo.ConsumptionVO; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public class ConsumptionServiceImplTest extends CinemaTest { @Autowired ConsumptionServiceImpl consumptionServiceImpl; @Test public void getConsumptionByUserId() { List preList = (ArrayList)consumptionServiceImpl.getConsumptionByUserId(12).getContent(); consumptionServiceImpl.insertConsumptionItem(12,250,50,3,new ArrayList<>(),0); List list = (ArrayList)consumptionServiceImpl.getConsumptionByUserId(12).getContent(); Assert.assertEquals(preList.size()+1,list.size()); } }package com.jive.sip.processor.uri; import java.util.Optional; import com.jive.sip.parsers.core.ByteParserInput; import com.jive.sip.parsers.core.ParserUtils; import com.jive.sip.processor.uri.parsers.TelUriParser; import com.jive.sip.uri.api.SipUri; import com.jive.sip.uri.api.SipUriVisitor; import com.jive.sip.uri.api.TelUri; import com.jive.sip.uri.api.TelUriVisitor; import com.jive.sip.uri.api.Uri; public class TelUriExtractor implements SipUriVisitor, TelUriVisitor { private static final TelUriExtractor INSTANCE = new TelUriExtractor(); public static TelUriExtractor getInstance() { return INSTANCE; } @Override public TelUri visit(final Uri unknown) { return null; } @Override public TelUri visit(final TelUri uri) { return uri; } @Override public TelUri visit(final SipUri uri) { if (!uri.getUserParameter().equals(Optional.of("phone"))) { return null; } final String tel = uri.getUsername().orElse(null); if (tel == null) { return null; } final ByteParserInput is = ByteParserInput.fromString(tel); final TelUri value = ParserUtils.read(is, TelUriParser.TEL); if (is.remaining() == 0) { return value; } throw new RuntimeException(String.format("Invalid tel URI in SIP-URI: %s", tel)); } } content/control_flow/defer-finally.java10-100 void write(String fileName, String text) { File file = new File(fileName); PrintWriter writer; try { file.createNewFile(); writer = new PrintWriter(file) writer.println(text); } catch (IOException e) { throw new RuntimeException(e); } finally { writer.close(); // finally always executes at the end } }/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.qa.form; import java.io.*; public class VisualDevelopmentUtil { public static String JAVA_VERSION = System.getProperty("java.version"); public static String readFromFile(String filename) throws IOException { File f = new File(filename); int size = (int) f.length(); int bytes_read = 0; FileInputStream in = new FileInputStream(f); byte[] data = new byte [size]; while(bytes_read < size) bytes_read += in.read(data, bytes_read, size-bytes_read); return new String(data); } public static void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } } package cc.duduhuo.dialog.smartisan; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; /** * =======================================================
* Author: liying -
* Date: 2017/5/13 14:07
* Version: 1.0
* Description: TwoOptionsDialog
* Remark:
* ======================================================= */ public class TwoOptionsDialog extends AlertDialog { private TextView mTvTitle; private TextView mTvCancel; private TextView mTvOp1; private TextView mTvOp2; private String mTitle = ""; private String mCancel = ""; private String mOp1 = ""; private String mOp2 = ""; private OnSelectListener mListener; TwoOptionsDialog(@NonNull Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ddh_sm_dialog_two_options); findViews(); Window window = getWindow(); window.setBackgroundDrawableResource(android.R.color.transparent); window.setGravity(Gravity.BOTTOM); window.setWindowAnimations(R.style.ddh_sm_BottomDialogStyle); } private void findViews() { mTvTitle = (TextView) findViewById(R.id.tvTitle); mTvCancel = (TextView) findViewById(R.id.tvCancel); mTvOp1 = (TextView) findViewById(R.id.tvOp1); mTvOp2 = (TextView) findViewById(R.id.tvOp2); } /** * Set the dialog title * * @param title dialog title * @return This dialog instance */ public TwoOptionsDialog setTitle(String title) { this.mTitle = title; return this; } /** * Set cancel button text * * @param cancel cancel buttton text * @return This dialog instance */ public TwoOptionsDialog setCancelButtonText(String cancel) { this.mCancel = cancel; return this; } /** * Set the text of the first item * * @param op1 the text of the first item * @return This dialog instance */ public TwoOptionsDialog setOp1Text(String op1) { this.mOp1 = op1; return this; } /** * Set the text of the second item * * @param op2 the text of the second item * @return This dialog instance */ public TwoOptionsDialog setOp2Text(String op2) { this.mOp2 = op2; return this; } @Override public void show() { super.show(); if (!TextUtils.isEmpty(mTitle)) { mTvTitle.setText(mTitle); } if (!TextUtils.isEmpty(mCancel)) { mTvCancel.setText(mCancel); } mTvOp1.setText(mOp1); mTvOp2.setText(mOp2); mTvCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); mTvOp1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mListener != null) { mListener.onOp1(); } } }); mTvOp2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mListener != null) { mListener.onOp2(); } } }); getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); } public void setOnSelectListener(OnSelectListener listener) { this.mListener = listener; } public interface OnSelectListener { /** Select the first option */ void onOp1(); /** Select the second option */ void onOp2(); } } berndruecker/camunda-interactive-lab package com.camunda.demo.lab.interactive; import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat; import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareTests.execute; import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareTests.job; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.test.Deployment; import org.camunda.bpm.engine.variable.VariableMap; import org.camunda.bpm.engine.variable.Variables; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpMethod; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.NONE, // properties = { // "camunda.bpm.job-execution.enabled=false", // "camunda.bpm.auto-deployment-enabled=false" }) public class InteractiveLabTest { @Autowired private ProcessEngine camunda; @Autowired private RestTemplate restTemplate; private MockRestServiceServer mockRestServer; @Before public void setup() throws Exception { mockRestServer = MockRestServiceServer.createServer(restTemplate); } @Test @Deployment(resources = {"interactive-lab-solution.bpmn" }) public void testTick() { RuntimeService runtimeService = camunda.getRuntimeService(); mockRestServer .expect(requestTo("http://localhost:8080" + "/rest/engine/default/message/")) // .andExpect(method(HttpMethod.POST)) .andExpect(jsonPath("$.messageName", is("Message_IHaveDoneIt_Test"))) .andExpect(jsonPath("$.correlationKeys.event.value", is("test"))) .andExpect(jsonPath("$.correlationKeys.group.value", is("a"))) .andExpect(jsonPath("$.processVariables.name.value", is("bernd"))) .andRespond(withSuccess()); VariableMap variables = Variables // .putValue("host", "http://localhost:8080") // .putValue("event", "test") // .putValue("name", "bernd") // .putValue("group", "a") // .putValue("message", "Message_IHaveDoneIt_Test"); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("interactive-lab-participant", variables); assertThat(processInstance).job(); // safe point for retry behavior execute(job()); assertThat(processInstance).isEnded(); } } XmobiTea-Family/ezyfox-server package com.tvd12.ezyfoxserver.request; public class EzySimpleRequestAppRequest extends EzySimpleRequest implements EzyRequestAppRequest { private static final long serialVersionUID = 5909672063016351418L; @Override protected EzyRequestAppParams newParams() { return new EzySimpleRequestAppParams(); } } package io.slingr.endpoints.dendi; import io.slingr.endpoints.HttpEndpoint; import io.slingr.endpoints.exceptions.EndpointException; import io.slingr.endpoints.exceptions.ErrorCode; import io.slingr.endpoints.framework.annotations.*; import io.slingr.endpoints.services.AppLogs; import io.slingr.endpoints.services.HttpService; import io.slingr.endpoints.services.exchange.Parameter; import io.slingr.endpoints.services.rest.RestMethod; import io.slingr.endpoints.utils.Json; import io.slingr.endpoints.ws.exchange.FunctionRequest; import io.slingr.endpoints.ws.exchange.WebServiceRequest; import io.slingr.endpoints.ws.exchange.WebServiceResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.UUID; /** *

Sample endpoint * *

Created by lefunes on 01/12/16. */ @SlingrEndpoint(name = "dendi") public class DendiEndpoint extends HttpEndpoint { private static final Logger logger = LoggerFactory.getLogger(DendiEndpoint.class); @ApplicationLogger private AppLogs appLogger; @EndpointProperty private String apiUrl; @EndpointProperty private String apiToken; @EndpointProperty private String webhooksToken; public DendiEndpoint() { } @Override public String getApiUri(){ return this.apiUrl; } @Override public void endpointStarted() { //Dendi expects the Authorization header with "Token+whitespace+token" so we pass it like this httpService().setupAuthenticationHeader("Token"," "+this.apiToken); // the loggers, endpoint properties, data stores, etc. are initialized at this point. the endpoint is ready to be used logger.info("Endpoint is started"); } @Override public void endpointStopped(String cause) { logger.info(String.format("Endpoint is stopping - cause [%s]", cause)); } @EndpointFunction(name = "_get") public Json get(FunctionRequest request) { try { // continue with the default processor return defaultGetRequest(request); } catch (EndpointException restException) { throw restException; } } @EndpointFunction(name = "_put") public Json put(FunctionRequest request) { try { // continue with the default processor return defaultPutRequest(request); } catch (EndpointException restException) { throw restException; } } @EndpointFunction(name = "_post") public Json post(FunctionRequest request) { try { // continue with the default processor return defaultPostRequest(request); } catch (EndpointException restException) { throw restException; } } @EndpointFunction(name = "_delete") public Json delete(FunctionRequest request) { try { // continue with the default processor return defaultDeleteRequest(request); } catch (EndpointException restException) { throw restException; } } @EndpointFunction(name = "_getReportFile") public Json getReportFile(Json pdfInfo) throws IOException { List responseItems = pdfInfo.jsons("results"); if (responseItems.size()>1) { throw EndpointException.permanent(ErrorCode.ARGUMENT,"The API returned more than one order for the parameters provided. This method is intended for fetching only one report."); } Json reportEntity = responseItems.get(0); List reportsList = reportEntity.jsons("reports"); String reportUrl = reportsList.get(reportsList.size()-1).string("pdf_file"); String fileName = "report-" + reportEntity.string("code") + ".pdf"; HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(reportUrl); InputStream is = null; String status = "ok"; int statusCode = 200; boolean hasFile = true; Json fileJson = Json.map(); try { HttpResponse response = httpClient.execute(get); if (response.getStatusLine().getStatusCode() != 200) { status = "fail"; statusCode = response.getStatusLine().getStatusCode(); if (response.getEntity() == null || response.getEntity().getContentType() == null /*|| !StringUtils.equals(response.getEntity().getContentType().getValue(), "application/xml")*/) { hasFile = false; } } if (hasFile) { is = response.getEntity().getContent(); ContentType contentType = ContentType.getOrDefault(response.getEntity()); String mimeType = contentType.getMimeType(); appLogger.info(String.format("Starting upload of pdf report [%s]", fileName)); fileJson = files().upload(fileName, is, mimeType); appLogger.info(String.format("Report was upload successfully as [%s]", fileName)); } else { appLogger.warn(String.format("Report was not received. Status code [%s]", response.getStatusLine().getStatusCode())); } } catch (IOException e) { String ERROR_MESSAGE = "Error to fetch report file"; logger.error(ERROR_MESSAGE, e); appLogger.error(ERROR_MESSAGE, e); throw EndpointException.permanent(ErrorCode.GENERAL,ERROR_MESSAGE); } finally { IOUtils.closeQuietly(is); } return fileJson; } @EndpointWebService(path = "/orders", methods = {RestMethod.POST}) private WebServiceResponse processWebhook(WebServiceRequest request) { Json requestHeaders = request.getHeaders(); String webhookAuthToken = requestHeaders.string("authorization"); if (!StringUtils.equals(this.webhooksToken,webhookAuthToken)) { appLogger.error("[Dendi LIS] Received a Webhook but token was invalid, it has been discarded"); throw EndpointException.permanent(ErrorCode.GENERAL,"Webhook received but token was invalid. It has been discarded."); }; events().send("webhooks", HttpService.defaultWebhookConverter(request)); return new WebServiceResponse(); } } package Projeto.security; import javax.persistence.Id; public class AccountCredentials { @Id private Long id; private String email; private String senha; public String getCpf() { return email; } public void setCpf(String cpf) { this.email = cpf; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } } lokimax/analytical-hierarchy-process package de.x132.common.business.transfer; import java.util.ArrayList; import java.util.List; /** * Beinhaltet eine Liste der einzelnen Resultate. * * @author * */ public class SolvingResultDTO { /** * Lieste der einfachen Resultate. */ private List singleResults; public SolvingResultDTO(){ this.singleResults = new ArrayList<>(); } /** * Liefert die Liste der Resultate. * @return Liste der Resultate */ public List getSingleResults() { return singleResults; } /** * Setzt die Liste der Resultate. * @param singleResults der Einzelnen Resultate. */ public void setSingleResults(List singleResults) { this.singleResults = singleResults; } /** * Fügt mehrere Resultate hinzu. * @param results */ public void addAll(List results){ this.singleResults.addAll(results); } } /* * Copyright (c) 2018-present, iQIYI, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.qiyi.video.svg.dispatcher.service; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import org.qiyi.video.svg.Andromeda; import org.qiyi.video.svg.backup.EmergencyHandler; import org.qiyi.video.svg.backup.IEmergencyHandler; import org.qiyi.video.svg.bean.BinderBean; import org.qiyi.video.svg.log.Logger; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Created by wangallen on 2018/1/8. */ public class ServiceDispatcher implements IServiceDispatcher { private static final String TAG = "Andromeda"; private IEmergencyHandler emergencyHandler; public ServiceDispatcher() { emergencyHandler = new EmergencyHandler(); } private Map remoteBinderCache = new ConcurrentHashMap<>(); @Override public BinderBean getTargetBinderLocked(String serviceCanonicalName) throws RemoteException { Log.d(TAG, "ServiceDispatcher-->getTargetBinderLocked,serivceName:" + serviceCanonicalName + ",pid:" + android.os.Process.myPid() + ",thread:" + Thread.currentThread().getName()); BinderBean bean = remoteBinderCache.get(serviceCanonicalName); if (null == bean) { return null; } else { return bean; } } @Override public void registerRemoteServiceLocked(final String serviceCanonicalName, String processName, IBinder binder) throws RemoteException { Log.d(TAG, "ServiceDispatcher-->registerRemoteServiceLocked,serviceCanonicalName:" + serviceCanonicalName + ",pid:" + android.os.Process.myPid() + ",thread:" + Thread.currentThread().getName()); if (binder != null) { binder.linkToDeath(new IBinder.DeathRecipient() { @Override public void binderDied() { Logger.d("ServiceDispatcher-->binderDied,serviceCanonicalName:" + serviceCanonicalName); BinderBean bean = remoteBinderCache.remove(serviceCanonicalName); //实际上这里是还没实现线程同步,但是并不会影响执行结果,所以其实下面这句就没有同步的必要。 if (bean != null) { emergencyHandler.handleBinderDied(Andromeda.getAppContext(), bean.getProcessName()); } } }, 0); remoteBinderCache.put(serviceCanonicalName, new BinderBean(binder, processName)); Logger.d("ServiceDispatcher-->registerRemoteServiceLocked(),binder is not null"); } else { Log.d(TAG, "ServiceDispatcher-->registerRemoteServiceLocked(),binder is null"); } } @Override public void removeBinderCacheLocked(String serviceCanonicalName) { remoteBinderCache.remove(serviceCanonicalName); } } /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.usecases; import java.net.URI; import java.util.Vector; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import javax.jms.MessageConsumer; import junit.framework.Test; import org.apache.activemq.JmsMultipleBrokersTestSupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.region.policy.PolicyEntry; import org.apache.activemq.broker.region.policy.PolicyMap; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.network.NetworkConnector; import org.apache.activemq.util.MessageIdList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Assert; /** * This test demonstrates and verifies the behaviour of a network bridge when it * forwards a message to a queue that is full and producer flow control is * enabled. *
* The expected behaviour is that the bridge will stop forwarding messages to * the full queue once the associated demand consumer's prefetch is full, but * will continue to forward messages to the other queues that are not full. *
* In actuality, a message that is sent asynchronously to a local queue, * but blocked by producer flow control on the remote queue, will stop the * bridge from forwarding all subsequent messages, even those destined for * remote queues that are not full. In the same scenario, but with a message * that is sent synchronously to the local queue, the bridge continues * forwarding messages to remote queues that are not full. *
* This test demonstrates the differing behaviour via the following scenario: *

    *
  • broker0, designated as the local broker, produces messages to two shared * queues *
  • broker1, designated as the remote broker, has two consumers: the first * consumes from one of the shared queues as fast as possible, the second * consumes from the other shared queue with an artificial processing delay for * each message *
  • broker0 forwards messages to broker1 over a TCP-based network bridge * with a demand consumer prefetch of 1 *
  • broker1's consumers have a prefetch of 1 *
  • broker1's "slow consumer" queue has a memory limit that triggers * producer flow control once the queue contains a small number of messages *
* In this scenario, since broker1's consumers have a prefetch of 1, the "slow * consumer" queue will quickly become full and trigger producer flow control. * The "fast consumer" queue is unlikely to become full. Since producer flow * control on the "slow consumer" queue should not affect the "fast consumer" * queue, the expectation is that the fast consumer in broker1 will finish * processing all its messages well ahead of the slow consumer. *
* The difference between expected and actual behaviour is demonstrated by * changing the messages produced by broker0 from persistent to non-persistent. * With persistent messages, broker0 dispatches synchronously and the expected * behaviour is observed (i.e., the fast consumer on broker1 is much faster than * the slow consumer). With non-persistent messages, broker0 dispatches * asynchronously and the expected behaviour is not observed (i.e., the * fast consumer is only marginally faster than the slow consumer). *
* Since the expected behaviour may be desirable for both persistent and * non-persistent messages, this test also demonstrates an enhancement to the * network bridge configuration: isAlwaysSendSync. When false the * bridge operates as originally observed. When true, the bridge * operates with the same behaviour as was originally observed with persistent * messages, for both persistent and non-persistent messages. *
* https://issues.apache.org/jira/browse/AMQ-3331 * * @author schow */ public class NetworkBridgeProducerFlowControlTest extends JmsMultipleBrokersTestSupport { // Protect against hanging test. private static final long MAX_TEST_TIME = 120000; private static final Log LOG = LogFactory.getLog(NetworkBridgeProducerFlowControlTest.class); // Combo flag set to true/false by the test framework. public boolean persistentTestMessages; public boolean networkIsAlwaysSendSync; private Vector exceptions = new Vector(); public static Test suite() { return suite(NetworkBridgeProducerFlowControlTest.class); } public void initCombosForTestFastAndSlowRemoteConsumers() { addCombinationValues("persistentTestMessages", new Object[]{new Boolean(true), new Boolean(false)}); addCombinationValues("networkIsAlwaysSendSync", new Object[]{new Boolean(true), new Boolean(false)}); } @Override protected void setUp() throws Exception { setAutoFail(true); setMaxTestTime(MAX_TEST_TIME); super.setUp(); } /** * This test is parameterized by {@link #persistentTestMessages}, which * determines whether the producer on broker0 sends persistent or * non-persistent messages, and {@link #networkIsAlwaysSendSync}, which * determines how the bridge will forward both persistent and non-persistent * messages to broker1. * * @see #initCombosForTestFastAndSlowRemoteConsumers() */ public void testFastAndSlowRemoteConsumers() throws Exception { final int NUM_MESSAGES = 100; final long TEST_MESSAGE_SIZE = 1024; final long SLOW_CONSUMER_DELAY_MILLIS = 100; // Consumer prefetch is disabled for broker1's consumers. final ActiveMQQueue SLOW_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".slow.shared?consumer.prefetchSize=1"); final ActiveMQQueue FAST_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".fast.shared?consumer.prefetchSize=1"); // Start a local and a remote broker. createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker0&persistent=false&useJmx=true")); BrokerService remoteBroker = createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker1&persistent=false&useJmx=true")); // Set a policy on the remote broker that limits the maximum size of the // slow shared queue. PolicyEntry policyEntry = new PolicyEntry(); policyEntry.setMemoryLimit(5 * TEST_MESSAGE_SIZE); PolicyMap policyMap = new PolicyMap(); policyMap.put(SLOW_SHARED_QUEUE, policyEntry); remoteBroker.setDestinationPolicy(policyMap); // Create an outbound bridge from the local broker to the remote broker. // The bridge is configured with the remoteDispatchType enhancement. NetworkConnector nc = bridgeBrokers("broker0", "broker1"); nc.setAlwaysSyncSend(networkIsAlwaysSendSync); nc.setPrefetchSize(1); startAllBrokers(); waitForBridgeFormation(); // Send the test messages to the local broker's shared queues. The // messages are either persistent or non-persistent to demonstrate the // difference between synchronous and asynchronous dispatch. persistentDelivery = persistentTestMessages; sendMessages("broker0", FAST_SHARED_QUEUE, NUM_MESSAGES); sendMessages("broker0", SLOW_SHARED_QUEUE, NUM_MESSAGES); // Start two asynchronous consumers on the remote broker, one for each // of the two shared queues, and keep track of how long it takes for // each of the consumers to receive all the messages. final CountDownLatch fastConsumerLatch = new CountDownLatch(NUM_MESSAGES); final CountDownLatch slowConsumerLatch = new CountDownLatch(NUM_MESSAGES); final long startTimeMillis = System.currentTimeMillis(); final AtomicLong fastConsumerTime = new AtomicLong(); final AtomicLong slowConsumerTime = new AtomicLong(); Thread fastWaitThread = new Thread() { @Override public void run() { try { fastConsumerLatch.await(); fastConsumerTime.set(System.currentTimeMillis() - startTimeMillis); } catch (InterruptedException ex) { exceptions.add(ex); Assert.fail(ex.getMessage()); } } }; Thread slowWaitThread = new Thread() { @Override public void run() { try { slowConsumerLatch.await(); slowConsumerTime.set(System.currentTimeMillis() - startTimeMillis); } catch (InterruptedException ex) { exceptions.add(ex); Assert.fail(ex.getMessage()); } } }; fastWaitThread.start(); slowWaitThread.start(); createConsumer("broker1", FAST_SHARED_QUEUE, fastConsumerLatch); MessageConsumer slowConsumer = createConsumer("broker1", SLOW_SHARED_QUEUE, slowConsumerLatch); MessageIdList messageIdList = brokers.get("broker1").consumers.get(slowConsumer); messageIdList.setProcessingDelay(SLOW_CONSUMER_DELAY_MILLIS); fastWaitThread.join(); slowWaitThread.join(); assertTrue("no exceptions on the wait threads:" + exceptions, exceptions.isEmpty()); LOG.info("Fast consumer duration (ms): " + fastConsumerTime.get()); LOG.info("Slow consumer duration (ms): " + slowConsumerTime.get()); // Verify the behaviour as described in the description of this class. if (networkIsAlwaysSendSync) { Assert.assertTrue(fastConsumerTime.get() < slowConsumerTime.get() / 10); } else { Assert.assertEquals(persistentTestMessages, fastConsumerTime.get() < slowConsumerTime.get() / 10); } } public void testSendFailIfNoSpaceDoesNotBlockQueueNetwork() throws Exception { // Consumer prefetch is disabled for broker1's consumers. final ActiveMQQueue SLOW_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".slow.shared?consumer.prefetchSize=1"); final ActiveMQQueue FAST_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".fast.shared?consumer.prefetchSize=1"); doTestSendFailIfNoSpaceDoesNotBlockNetwork(SLOW_SHARED_QUEUE, FAST_SHARED_QUEUE); } public void testSendFailIfNoSpaceDoesNotBlockTopicNetwork() throws Exception { // Consumer prefetch is disabled for broker1's consumers. final ActiveMQTopic SLOW_SHARED_TOPIC = new ActiveMQTopic(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".slow.shared?consumer.prefetchSize=1"); final ActiveMQTopic FAST_SHARED_TOPIC = new ActiveMQTopic(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".fast.shared?consumer.prefetchSize=1"); doTestSendFailIfNoSpaceDoesNotBlockNetwork(SLOW_SHARED_TOPIC, FAST_SHARED_TOPIC); } public void doTestSendFailIfNoSpaceDoesNotBlockNetwork(ActiveMQDestination slowDestination, ActiveMQDestination fastDestination) throws Exception { final int NUM_MESSAGES = 100; final long TEST_MESSAGE_SIZE = 1024; final long SLOW_CONSUMER_DELAY_MILLIS = 100; // Start a local and a remote broker. createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker0&persistent=false&useJmx=true")); BrokerService remoteBroker = createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker1&persistent=false&useJmx=true")); remoteBroker.getSystemUsage().setSendFailIfNoSpace(true); // Set a policy on the remote broker that limits the maximum size of the // slow shared queue. PolicyEntry policyEntry = new PolicyEntry(); policyEntry.setMemoryLimit(5 * TEST_MESSAGE_SIZE); PolicyMap policyMap = new PolicyMap(); policyMap.put(slowDestination, policyEntry); remoteBroker.setDestinationPolicy(policyMap); // Create an outbound bridge from the local broker to the remote broker. // The bridge is configured with the remoteDispatchType enhancement. NetworkConnector nc = bridgeBrokers("broker0", "broker1"); nc.setAlwaysSyncSend(true); nc.setPrefetchSize(1); startAllBrokers(); waitForBridgeFormation(); // Start two asynchronous consumers on the remote broker, one for each // of the two shared queues, and keep track of how long it takes for // each of the consumers to receive all the messages. final CountDownLatch fastConsumerLatch = new CountDownLatch(NUM_MESSAGES); final CountDownLatch slowConsumerLatch = new CountDownLatch(NUM_MESSAGES); final long startTimeMillis = System.currentTimeMillis(); final AtomicLong fastConsumerTime = new AtomicLong(); final AtomicLong slowConsumerTime = new AtomicLong(); Thread fastWaitThread = new Thread() { @Override public void run() { try { fastConsumerLatch.await(); fastConsumerTime.set(System.currentTimeMillis() - startTimeMillis); } catch (InterruptedException ex) { exceptions.add(ex); Assert.fail(ex.getMessage()); } } }; Thread slowWaitThread = new Thread() { @Override public void run() { try { slowConsumerLatch.await(); slowConsumerTime.set(System.currentTimeMillis() - startTimeMillis); } catch (InterruptedException ex) { exceptions.add(ex); Assert.fail(ex.getMessage()); } } }; fastWaitThread.start(); slowWaitThread.start(); createConsumer("broker1", fastDestination, fastConsumerLatch); MessageConsumer slowConsumer = createConsumer("broker1", slowDestination, slowConsumerLatch); MessageIdList messageIdList = brokers.get("broker1").consumers.get(slowConsumer); messageIdList.setProcessingDelay(SLOW_CONSUMER_DELAY_MILLIS); // Send the test messages to the local broker's shared queues. The // messages are either persistent or non-persistent to demonstrate the // difference between synchronous and asynchronous dispatch. persistentDelivery = false; sendMessages("broker0", fastDestination, NUM_MESSAGES); sendMessages("broker0", slowDestination, NUM_MESSAGES); fastWaitThread.join(TimeUnit.SECONDS.toMillis(60)); slowWaitThread.join(TimeUnit.SECONDS.toMillis(60)); assertTrue("no exceptions on the wait threads:" + exceptions, exceptions.isEmpty()); LOG.info("Fast consumer duration (ms): " + fastConsumerTime.get()); LOG.info("Slow consumer duration (ms): " + slowConsumerTime.get()); assertTrue("fast time set", fastConsumerTime.get() > 0); assertTrue("slow time set", slowConsumerTime.get() > 0); // Verify the behaviour as described in the description of this class. Assert.assertTrue(fastConsumerTime.get() < slowConsumerTime.get() / 10); } }package edu.miracosta.cs220; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * SymbolTable.java - The class for managing symbols and their respective address. * * INSTANCE VARIABLES: * * - symbolTable (hash-map): Stores the predefined symbols (and their addresses), as well as any added symbols. * - reservedSymbols (String[]): An array holding predefined symbols to be loaded into the symbolTable hash-map. * - reservedSymbolRegisters (int[]): An array holding the register locations of predefined symbols to be loaded * into the symbolTable hash-map. * * METHODS: * * - Full constructor: Initializes the predefined symbols/registers into the symbolTable hash-map. * - addEntry: Adds entry if not already defined and returns true, false otherwise (symbol exists/has invalid name). * - contains: Returns true if the symbol is defined within the symbolTable hash-map, false otherwise. * - getAddress: Returns the address corresponding to the symbol argument given. * - isValidName: Returns true if the symbol argument has a valid name, false otherwise. * * Author: */ class SymbolTable { private static final Map symbolTable = new HashMap <> (); private static final String [] reservedSymbols = { "SP", "LCL", "ARG", "THIS", "THAT", "SCREEN", "KBD" }; private static final int [] reservedSymbolRegisters = { 0, 1, 2, 3, 4, 16384, 24576 }; /** * Full constructor, initializes the symbol table hash-map with all pre-defined symbols. */ SymbolTable () { for (int i = 0; i < 16; i++) symbolTable.put (("R" + i), i); for (int i = 0; i < reservedSymbols.length; i++) symbolTable.put (reservedSymbols [i], reservedSymbolRegisters [i]); } /** * Adds a symbol/address pair to the symbol table hash-map (if not already defined, and symbol has valid name). * @param symbolToBeAdded The symbol to be added. * @param indexToAddTheSymbolAt The register number. */ void addSymbol(String symbolToBeAdded, int indexToAddTheSymbolAt) { if (isValidSymbolName(symbolToBeAdded)) { symbolTable.put(symbolToBeAdded, indexToAddTheSymbolAt); } } /** * Determines if the symbol argument is located in the symbol table. * @param symbolToBeChecked The symbol to be checked for existence. * @return True if the symbol is in the symbol table, false otherwise. */ boolean contains(String symbolToBeChecked) { return symbolTable.containsKey(symbolToBeChecked); } /** * Returns the address of valid symbol arguments. * @param symbolToBeCheckedForAddress The symbol to be checked for an address. * @return Returns the symbol argument's address if it is in the symbol table, null otherwise. */ int getAddress(String symbolToBeCheckedForAddress) { return symbolTable.getOrDefault(symbolToBeCheckedForAddress, null); } /** * Determines if the symbol argument has a valid name. Valid names will begin with the choice of lower/uppercase * letters, period, underscore, or dollar sign. Subsequent characters follow the same rule with the addition of * numbers. * @param symbolToBeCheckedForValidName The symbol to be checked for name validity. * @return True if the symbol has a valid name, false otherwise. */ private static boolean isValidSymbolName(String symbolToBeCheckedForValidName) { Pattern validNamePattern = Pattern.compile("[a-zA-Z_.$][a-zA-Z0-9_.$]*"); Matcher validNameChecker = validNamePattern.matcher(symbolToBeCheckedForValidName); return validNameChecker.matches(); } } RepeatedFixes/model/org/eclipse/cdt/core/model/tests/IntegratedCModelTest.java /******************************************************************************* * Copyright (c) 2005, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.model.tests; import java.io.FileInputStream; import java.io.FileNotFoundException; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.IPDOMManager; import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.testplugin.CProjectHelper; import org.eclipse.cdt.core.testplugin.CTestPlugin; import org.eclipse.cdt.core.testplugin.util.BaseTestCase; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; /** * @author bnicolle */ public abstract class IntegratedCModelTest extends BaseTestCase { private ICProject fCProject; private IFile sourceFile; private NullProgressMonitor monitor; private boolean structuralParse = false; public IntegratedCModelTest() { super(); } /** * @param name */ public IntegratedCModelTest(String name) { super(name); } /** * @return the subdirectory (from the plugin root) containing the required * test sourcefile (plus a trailing slash) */ abstract public String getSourcefileSubdir(); /** * @return the name of the test source-file */ abstract public String getSourcefileResource(); @Override public void setUp() throws Exception { monitor = new NullProgressMonitor(); fCProject= CProjectHelper.createCCProject("TestProject1", "bin", IPDOMManager.ID_FAST_INDEXER); sourceFile = fCProject.getProject().getFile( getSourcefileResource() ); if (!sourceFile.exists()) { try{ FileInputStream fileIn = new FileInputStream( CTestPlugin.getDefault().getFileInPlugin(new Path(getSourcefileSubdir() + getSourcefileResource()))); sourceFile.create(fileIn,false, monitor); } catch (CoreException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } waitForIndexer(fCProject); } @Override protected void tearDown() { CProjectHelper.delete(fCProject); } protected ITranslationUnit getTU() throws CModelException { ITranslationUnit tu = (ITranslationUnit)CoreModel.getDefault().create(sourceFile); CCorePlugin.getDefault().setStructuralParseMode(isStructuralParse()); // parse the translation unit to get the elements tree // Force the parsing now to do this in the right ParseMode. tu.close(); tu.open(new NullProgressMonitor()); CCorePlugin.getDefault().setStructuralParseMode(false); return tu; } /** * @return Returns the structuralParse. */ public boolean isStructuralParse() { return structuralParse; } /** * @param structuralParse The structuralParse to set. */ public void setStructuralParse(boolean structuralParse) { this.structuralParse = structuralParse; } } 1-10 package com.jusfoun.domain; import com.jusfoun.bean.RoleExtension; import org.springframework.security.core.GrantedAuthority; import java.io.Serializable; /** * Created by liutiyang on 2017/5/24. */ public class RoleDomain extends RoleExtension implements Serializable, GrantedAuthority { private static final long serialVersionUID = -5166971395270023298L; @Override public String getAuthority() { return getPermissionName(); } } /* * Copyright 2015-2018 Micro Focus or one of its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hpe.caf.services.job.api; import java.lang.reflect.Field; import java.util.Collections; import java.util.Map; public final class TestUtil { public static void setSystemEnvironmentFields(Map newenv) throws Exception { Class[] classes = Collections.class.getDeclaredClasses(); // Get map view of the current system environment. Map env = System.getenv(); for(Class cl : classes) { if("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { Field field = cl.getDeclaredField("m"); field.setAccessible(true); Object obj = field.get(env); Map map = (Map) obj; map.clear(); map.putAll(newenv); } } } } AlgorithmsDatastructuresAndProbability/src/datastructures/WeightedDirectedGraph.java1-10 package datastructures; import java.util.LinkedList; public class WeightedDirectedGraph implements Graph{ LinkedList[] adjList; //Stores the connections in the graph LinkedList edgeList; //Stores the edges of the graph /** * Constructor * @param n size of the graph (amount of vertices) */ @SuppressWarnings("unchecked") public WeightedDirectedGraph(int n) { adjList = new LinkedList[n]; edgeList = new LinkedList(); for(int i = 0; i(); } } /** * Get the size of this graph by vertices * @return int that stores the amount of vertices in the graph */ @Override public int getVertexCount() { return adjList.length; } /** * Get all the edges of this graph as a list * @return LinkedList of edges */ @Override public LinkedList getEdgeList() { LinkedList out = new LinkedList(); for(Edge e: edgeList) { out.add(e.clone()); } return out; } /** * Find all neighbours of x * @param x the vertex we want the neighbours from * @return a LinkedList of neighbour vertices */ @Override public LinkedList getNeighbors(int x) { LinkedList out = new LinkedList(); for(GraphConnection c: adjList[x]) { out.add(c.target); } return out; } /** * Find all connections that go away from x * @param x the vertex we want the neighbours from * @return a LinkedList of neighbour vertices */ public LinkedList getConnections(int x) { return adjList[x]; } /** * Get the size of this graph by edges * @return int that stores the amount of edges in the graph */ @Override public int getEdgeCount() { // TODO Auto-generated method stub return edgeList.size(); } public int getConnectionCost(int x, int y) { for(GraphConnection gc: adjList[x]) { if(gc.getTarget() == y) { return gc.getCost(); } } return 0; } /** * Connect x and y with a directed edge (from x to y) with no cost * @param x one vertex * @param y other vertex */ @Override public void connect(int x, int y) { connect(x,y,0); } /** * Connect x and y with a directed edge (from x to y) * @param x one vertex * @param y other vertex * @param cost how much it should cost to traverse this edge */ public void connect(int x, int y, int cost) { adjList[x].add(new GraphConnection(y,cost)); edgeList.add(new Edge(x,y)); } /** * Disconnect two given nodes by deleting the edge * @param x one vertex * @param y other vertex * @return true if edge was deleted, false if no edge was present */ @Override public boolean disconnect(int x, int y) { // TODO Auto-generated method stub return false; } } 0 public class SongInformation { // Public fields of each song record /** * Song number in the file, one less than in songbook */ public long number; /** * song title in Unicode */ public String title; /** * artist in Unicode */ public String artist; /** * integer value of language code */ public int language; public static final int KOREAN = 0; public static final int CHINESE1 = 1; public static final int CHINESE2 = 2; public static final int TAIWANESE3 = 3 ; public static final int JAPANESE = 4; public static final int RUSSIAN = 5; public static final int THAI = 6; public static final int TAIWANESE7 = 7; public static final int CHINESE8 = 8; public static final int CANTONESE = 9; public static final int ENGLISH = 0x12; public static final int VIETNAMESE = 0x13; public static final int PHILIPPINE = 0x14; public static final int TURKEY = 0x15; public static final int SPANISH = 0x16; public static final int INDONESIAN = 0x17; public static final int MALAYSIAN = 0x18; public static final int PORTUGUESE = 0x19; public static final int FRENCH = 0x20; public static final int INDIAN = 0x21; public static final int BRASIL = 0x22; public static final int CHINESE131 = 131; public static final int ENGLISH146 = 146; public static final int PHILIPPINE148 = 148; public SongInformation(long number, String title, String artist, int language) { this.number = number; this.title = title; this.artist = artist; this.language = language; } public String toString() { return "" + (number+1) + " (" + language + ") \"" + title + "\" " + artist; } public boolean titleMatch(String pattern) { // System.out.println("Pattern: " + pattern); return title.matches("(?i).*" + pattern + ".*"); } public boolean artistMatch(String pattern) { return artist.matches("(?i).*" + pattern + ".*"); } public boolean numberMatch(String pattern) { Long n; try { n = Long.parseLong(pattern) - 1; //System.out.println("Long is " + n); } catch(Exception e) { //System.out.println(e.toString()); return false; } return number == n; } public boolean languageMatch(int lang) { return language == lang; } } package seedu.address.logic.commands; import static org.junit.jupiter.api.Assertions.assertEquals; import static seedu.address.testutil.TypicalPersons.getTypicalAddressBook; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; import seedu.address.model.lineup.Lineup; import seedu.address.model.person.Name; import seedu.address.model.person.Person; import seedu.address.testutil.LineupBuilder; import seedu.address.testutil.TypicalPersons; /** * Contains integration tests (interaction with the Model) and unit tests for * {@code DeleteCommand}. */ public class DeleteCommandTest { private static final Name INVALID_NAME = new Name("RAcHel"); private static final seedu.address.model.lineup.LineupName INVALID_LINEUP_NAME = new seedu.address.model.lineup.LineupName("Not a lineup"); private static final Person VALID_PERSON = TypicalPersons.BENSON; private static final Lineup VALID_LINEUP = new LineupBuilder().build(); private static final Lineup ANOTHER_VALID_LINEUP = new Lineup(new seedu.address.model.lineup.LineupName("Dummy Lineup")); private static final seedu.address.model.lineup.LineupName VALID_LINEUP_NAME = VALID_LINEUP.getLineupName(); private Model model; private Model expectedModel; @BeforeEach public void setUp() { model = new ModelManager(getTypicalAddressBook(), new UserPrefs()); // to be removed after AddressBook can store lineups model.addLineup(VALID_LINEUP); model.putPersonIntoLineup(VALID_PERSON, VALID_LINEUP); model.addLineup(ANOTHER_VALID_LINEUP); expectedModel = new ModelManager(model.getAddressBook(), new UserPrefs()); expectedModel.addLineup(VALID_LINEUP); expectedModel.putPersonIntoLineup(VALID_PERSON, VALID_LINEUP); expectedModel.addLineup(ANOTHER_VALID_LINEUP); } @Test public void execute_deletePerson_success() throws CommandException { expectedModel.deletePerson(expectedModel.getPerson(VALID_PERSON.getName())); CommandResult commandResult = new DeleteCommand(VALID_PERSON.getName()).execute(model); assertEquals(commandResult.getFeedbackToUser(), String.format(DeleteCommand.MESSAGE_DELETE_PERSON_SUCCESS, VALID_PERSON.getName())); } @Test public void execute_deleteLineup_success() throws CommandException { expectedModel.deleteLineup(expectedModel.getLineup(VALID_LINEUP_NAME)); Command command = new DeleteCommand(VALID_LINEUP_NAME); CommandResult commandResult = command.execute(model); assertEquals(commandResult.getFeedbackToUser(), String.format(DeleteCommand.MESSAGE_DELETE_LINEUP_SUCCESS, VALID_LINEUP_NAME)); } @Test public void execute_deletePersonFromLineup_success() throws CommandException { expectedModel.deletePersonFromLineup(model.getPerson(VALID_PERSON.getName()), model.getLineup(VALID_LINEUP_NAME)); CommandResult commandResult = new DeleteCommand(VALID_PERSON.getName(), VALID_LINEUP_NAME).execute(model); assertEquals(commandResult.getFeedbackToUser(), String.format(DeleteCommand.MESSAGE_DELETE_PERSON_FROM_LINEUP_SUCCESS, VALID_LINEUP_NAME, VALID_PERSON.getName())); } @Test public void getExecute_invalidDeletePerson() { Command command = new DeleteCommand(INVALID_NAME); try { command.execute(model); } catch (CommandException e) { assertEquals(DeleteCommand.MESSAGE_NO_SUCH_PERSON, e.getMessage()); } } @Test public void getExecute_invalidDeleteLineup() { Command command = new DeleteCommand(INVALID_LINEUP_NAME); try { command.execute(model); } catch (CommandException e) { assertEquals(DeleteCommand.MESSAGE_NO_SUCH_LINEUP, e.getMessage()); } } @Test public void getExecute_invalidDeletePlayerFromLineup() { Command command = new DeleteCommand(VALID_PERSON.getName(), ANOTHER_VALID_LINEUP.getLineupName()); try { command.execute(model); } catch (CommandException e) { assertEquals(DeleteCommand.MESSAGE_PERSON_NOT_IN_LINEUP, e.getMessage()); } } } marioandre01/micro_services_shopping_api_spring_bootshopping_api/src/main/java/com/mario/backend/shopping/model/Item.java package com.mario.backend.shopping.model; import javax.persistence.Embeddable; import com.mario.backend.dto.ItemDTO; import lombok.Data; // @Embeddable , indicando que ela pode ser embutida em uma entidade. //Uma classe com a anotação @Embeddable não tem vida própria, ela sempre depende de uma entidade, isto é, de uma //classe que tenha a anotação @Entity @Data // gera os gets e sets da classe @Embeddable public class Item { private String productIdentifier; private Float price; // gets and sets public static Item convertToItem(ItemDTO itemDTO) { Item item = new Item(); item.setProductIdentifier( itemDTO.getProductIdentifier()); item.setPrice(itemDTO.getPrice()); return item; } } src/main/java/org/nybatis/core/reflection/serializer/column/ColumnBooleanSerializer.java package org.nybatis.core.reflection.serializer.column; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; import java.util.Map; import org.nybatis.core.db.constant.NullValue; import org.nybatis.core.reflection.Reflector; import org.nybatis.core.util.StringUtil; /** * @author * @since 2017-11-27 */ public class ColumnBooleanSerializer extends JsonSerializer { @Override public void serialize( Boolean value, JsonGenerator generator, SerializerProvider provider ) throws IOException, JsonProcessingException { if( isNull(value) ) { generator.writeString( NullValue.STRING ); } else { generator.writeString( StringUtil.toYn(value) ); } } private boolean isNull( Boolean value ) { return value == NullValue.BOOLEAN; } } package net.minecraft.network.protocol.game; import net.minecraft.core.BlockPos; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.protocol.Packet; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public record ClientboundBlockBreakAckPacket(BlockPos pos, BlockState state, ServerboundPlayerActionPacket.Action action, boolean allGood) implements Packet { /** Unused (probably related to the unused parameter in the constructor) */ private static final Logger LOGGER = LogManager.getLogger(); public ClientboundBlockBreakAckPacket(BlockPos pPos, BlockState pState, ServerboundPlayerActionPacket.Action pAction, boolean pAllGood, String pReason) { this(pPos, pState, pAction, pAllGood); } public ClientboundBlockBreakAckPacket(BlockPos pos, BlockState state, ServerboundPlayerActionPacket.Action action, boolean allGood) { pos = pos.immutable(); this.pos = pos; this.state = state; this.action = action; this.allGood = allGood; } public ClientboundBlockBreakAckPacket(FriendlyByteBuf pBuffer) { this(pBuffer.readBlockPos(), Block.BLOCK_STATE_REGISTRY.byId(pBuffer.readVarInt()), pBuffer.readEnum(ServerboundPlayerActionPacket.Action.class), pBuffer.readBoolean()); } /** * Writes the raw packet data to the data stream. */ public void write(FriendlyByteBuf pBuffer) { pBuffer.writeBlockPos(this.pos); pBuffer.writeVarInt(Block.getId(this.state)); pBuffer.writeEnum(this.action); pBuffer.writeBoolean(this.allGood); } /** * Passes this Packet on to the NetHandler for processing. */ public void handle(ClientGamePacketListener pHandler) { pHandler.handleBlockBreakAck(this); } }package com.getbase.android.db; import static com.google.common.truth.Truth.assertThat; import com.getbase.android.db.cursors.Cursors; import com.getbase.android.db.cursors.SingleRowTransforms; import com.getbase.android.db.provider.Utils; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.ParameterizedRobolectricTestRunner; import org.robolectric.ParameterizedRobolectricTestRunner.Parameters; import org.robolectric.annotation.Config; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; @RunWith(ParameterizedRobolectricTestRunner.class) @Config(manifest = Config.NONE) public class UtilityClassesTest { private Class mKlass; public UtilityClassesTest(Class klass) { mKlass = klass; } @Parameters(name = "{0}") public static Collection data() { return Arrays.asList(new Object[][] { { Cursors.class }, { SingleRowTransforms.class }, { Utils.class }, }); } @Test public void shouldBeWellDefined() throws Exception { assertThat(mKlass.getSuperclass()).isEqualTo(Object.class); assertThat(Modifier.isFinal(mKlass.getModifiers())).isTrue(); assertThat(mKlass.getDeclaredConstructors()).hasLength(1); final Constructor constructor = mKlass.getDeclaredConstructor(); assertThat(constructor.isAccessible()).isFalse(); assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue(); for (final Method method : mKlass.getDeclaredMethods()) { assertThat(Modifier.isStatic(method.getModifiers())).named(method.getName()).isTrue(); } } } znh-wenjuan/tduck-platform/tduck-project/src/main/java/com/tduck/cloud/project/service/impl/ProjectDashboardServiceImpl.java1-10 package com.tduck.cloud.project.service.impl; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.date.DateField; import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.CharUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.google.common.collect.Lists; import com.tduck.cloud.project.entity.UserProjectItemEntity; import com.tduck.cloud.project.entity.UserProjectResultEntity; import com.tduck.cloud.project.entity.enums.ProjectItemTypeEnum; import com.tduck.cloud.project.mapper.ProjectDashboardMapper; import com.tduck.cloud.project.service.ProjectDashboardService; import com.tduck.cloud.project.service.UserProjectItemService; import com.tduck.cloud.project.service.UserProjectResultService; import com.tduck.cloud.project.vo.ProjectReportVO; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.*; import java.util.stream.Collectors; /** * @author : smalljop * @description : * @create : 2020/12/31 14:50 **/ @Service @RequiredArgsConstructor public class ProjectDashboardServiceImpl implements ProjectDashboardService { private final ProjectDashboardMapper projectDashboardMapper; private final UserProjectResultService userProjectResultService; private final UserProjectItemService userProjectItemService; @Override public Collection projectReportSituation(String projectKey) { Set reportSituations = projectDashboardMapper.selectProjectReportSituation(projectKey); Date now = new Date(); List dateTimes = DateUtil.rangeToList(DateUtil.beginOfWeek(now), DateUtil.endOfWeek(now), DateField.DAY_OF_WEEK); dateTimes.forEach(time -> { reportSituations.add(new ProjectReportVO.Situation(time.toString(DatePattern.NORM_DATE_PATTERN), 0)); }); return CollectionUtil.sort(reportSituations, (o1, o2) -> DateUtil.parse(o1.getCreateTime(), DatePattern.NORM_DATE_PATTERN) .isAfter(DateUtil.parse(o2.getCreateTime(), DatePattern.NORM_DATE_PATTERN)) ? 1 : -1); } @Override public Map projectReportPosition(String projectKey) { List reportPositions = projectDashboardMapper.selectProjectReportPosition(projectKey); return reportPositions.stream() .filter(item -> ObjectUtil.isNotNull(CollectionUtil.get(StrUtil.split(item.getSubmitAddress(), CharUtil.DASHED), 0))) .map(item -> { item.setSubmitProvince(CollectionUtil.get(StrUtil.split(item.getSubmitAddress(), CharUtil.DASHED), 0)); return item; }).collect(Collectors.groupingBy(ProjectReportVO.Position::getSubmitProvince, Collectors.summingInt(ProjectReportVO.Position::getCount))); } @Override public List projectReportDevice(String projectKey) { return projectDashboardMapper.selectProjectReportDevice(projectKey); } @Override public List projectReportSource(String projectKey) { return projectDashboardMapper.selectProjectReportSource(projectKey); } @Override public List projectReportAnalysis(String projectKey) { List typeEnumList = Lists.newArrayList( ProjectItemTypeEnum.RADIO, ProjectItemTypeEnum.CHECKBOX, ProjectItemTypeEnum.SELECT ); // 题目 List projectItemList = userProjectItemService.list(new QueryWrapper().lambda().eq(UserProjectItemEntity::getProjectKey, projectKey)); // 结果 List projectResultList = userProjectResultService.list(new QueryWrapper().lambda().select(UserProjectResultEntity::getProcessData).eq(UserProjectResultEntity::getProjectKey, projectKey)); // 标题label与id的对应值 Map formMap = new LinkedHashMap<>(); // 储存标题与可选项 Map> map = new HashMap<>(); for (UserProjectItemEntity userProjectItemEntity : projectItemList) { if (typeEnumList.contains(userProjectItemEntity.getType())) { Map optionMap = new LinkedHashMap<>(); List> options = (List>) userProjectItemEntity.getExpand().get("options"); for (Map option : options) { optionMap.put(option.get("label").toString(), 0); } // 单选框类型 map.put("field" + userProjectItemEntity.getFormItemId(), optionMap); // id and label ProjectReportVO.Analysis analysis = new ProjectReportVO.Analysis(); analysis.setLabel(userProjectItemEntity.getLabel()); analysis.setType(userProjectItemEntity.getType().getDesc()); formMap.put("field" + userProjectItemEntity.getFormItemId(), analysis); } } for (UserProjectResultEntity userProjectResultEntity : projectResultList) { Map processData = userProjectResultEntity.getProcessData(); for (Map.Entry> entry : map.entrySet()) { if (processData.containsKey(entry.getKey())) { // 结果中字段值 处理多选 String[] fieldValues = processData.get(entry.getKey()).toString().split(","); for (int i = 0; i < fieldValues.length; i++) { // 获取问题集合中对应的选项的count Integer count = entry.getValue().get(fieldValues[i]); if (ObjectUtil.isNotNull(count)) { entry.getValue().put(fieldValues[i], count + 1); } } } formMap.get(entry.getKey()).setFieldName(new ArrayList(entry.getValue().keySet())); formMap.get(entry.getKey()).setData(new ArrayList(entry.getValue().values())); formMap.get(entry.getKey()).setMap(entry.getValue()); } } List result = new ArrayList(formMap.values()); return result; } } package com.philips.ai.controllers; import org.junit.Before; import org.junit.BeforeClass; import com.philips.ai.SmartSleepAnalyzerClient; import com.philips.ai.models.SessionDTO; public class SessionControllerTest { String timeStamp; SessionDTO resultDTO; private static String clientId; private static String clientSecret; private final String defaultErrorMessage = "00000:Please verify the provided information is correct."; SmartSleepAnalyzerClient analyzerClient; @BeforeClass public static void setUpBeforeClass() throws Exception { clientId = System.getProperty("clientId"); clientSecret = System.getProperty("clientSecret"); } @Before public void setUp() throws Exception { analyzerClient = new SmartSleepAnalyzerClient(clientId, clientSecret); } /* * //@Test public void testCreateSession() throws Throwable { SessionDTO * resultDTO = createSession(); Assert.assertEquals("testFirstName", * resultDTO.getFirstName()); } * * //@Test public void testCreateSession_ExistingSession() throws Throwable { * SessionDTO resultDTO = createSession(); SessionDTO sessionDTO = new SessionDTO(); * sessionDTO.setSessionKey(resultDTO.getSessionKey()); * sessionDTO.setFirstName("testFirstName"); sessionDTO.setLastName("testLastName"); * sessionDTO.setEmail(""); sessionDTO.setDataKey("testSessionKey"); * * try { analyzerClient.getSession().createSession(sessionDTO); } catch (Exception e) { * Assert.assertEquals("4101:SessionKey \""+ sessionDTO.getSessionKey().toString() * +"\" is already taken", e.getMessage()); } } * * //@Test public void testCreateSession_EmptyCreateSessionDetails() throws * Throwable { SessionDTO sessionDTO = new SessionDTO(); try { * analyzerClient.getSession().createSession(sessionDTO); } catch (Exception e) { * Assert.assertEquals("4101:SessionKey is required", e.getMessage()); } } * * //@Test public void testActivateSession() throws Throwable { SessionDTO resultDTO = * createSession(); SessionDTO sessionDTO = new SessionDTO(); * sessionDTO.setSessionKey(resultDTO.getSessionKey()); * sessionDTO.setEmail(resultDTO.getEmail()); sessionDTO.setDataKey("testSessionKey"); * SessionDTO result = analyzerClient.getSession().activateSession(sessionDTO); * Assert.assertEquals(resultDTO.getId(), result.getId()); * Assert.assertEquals(resultDTO.getLastName(), result.getLastName()); * Assert.assertEquals(resultDTO.getFirstName(), result.getFirstName()); * Assert.assertEquals(resultDTO.getSessionKey(), result.getSessionKey()); * Assert.assertEquals(resultDTO.getEmail(), result.getEmail()); * Assert.assertEquals(resultDTO.getDataKey(), null); * * } * * //@Test public void testcreateSession_InvalidSession() throws Throwable { SessionDTO * sessionDTO = new SessionDTO(); sessionDTO.setId(123456789L); * sessionDTO.setSessionKey("testActivateSession" + new Random().nextLong()); * sessionDTO.setEmail(""); sessionDTO.setDataKey("testSessionKey"); * * try { analyzerClient.getSession().activateSession(sessionDTO); } catch (Exception e) { * Assert.assertEquals("4201:SessionKey and/or DataKey is incorrect.", * e.getMessage()); } } * * //@Test public void testcreateSession_EmptyCreateSessionDetails() throws Throwable * { SessionDTO sessionDTO = new SessionDTO(); try { * analyzerClient.getSession().activateSession(sessionDTO); } catch (Exception e) { * Assert.assertEquals("4201:SessionKey and/or DataKey is incorrect.", * e.getMessage()); } } * * //@Test public void testRetrieve() throws Throwable { try { * analyzerClient.getSession().retrieveActivatedSession(); } catch (Exception e) { * Assert.assertEquals(defaultErrorMessage, e.getMessage()); } } * * //@Test public void testdeactivateSession() throws Throwable { * analyzerClient.getSession().deactivateSession(); } */ /* * private SessionDTO createSession() throws Throwable { SessionDTO sessionDTO = new * SessionDTO(); sessionDTO.setSessionKey("testsession" + new * SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())); * sessionDTO.setFirstName("testFirstName"); sessionDTO.setLastName("testLastName"); * sessionDTO.setEmail(""); sessionDTO.setDataKey("testSessionKey"); * SessionDTO resultDTO = analyzerClient.getSession().createSession(sessionDTO); return * resultDTO; } */ } package comp1110.ass2.gui; import comp1110.ass2.Tiles; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; public class Viewer extends Application { private static final int VIEWER_WIDTH = 1200; private static final int VIEWER_HEIGHT = 700; private static final int MARGIN_X = 100; private static final int PLAY_AREA_X = 250; private static final int GAP_BW = 100; static class DTile extends playerTile { double mouseX, mouseY; public StorageMosaic stoMo; DTile(Tiles t) { super(t); stoMo = new StorageMosaic(); setOnMousePressed(event -> { mouseX = event.getSceneX(); mouseY = event.getSceneY(); }); setOnMouseDragged(event -> { toFront(); double movementX = event.getSceneX() - mouseX; double movementY = event.getSceneY() - mouseY; setLayoutX(getLayoutX() + movementX); setLayoutY(getLayoutY() + movementY); mouseX = event.getSceneX(); mouseY = event.getSceneY(); event.consume(); }); } public StorageMosaic getStoMo() { return stoMo; } } @Override public void start(Stage stage) { DTile d = new DTile(Tiles.O); Group group = new Group(); GroupFactories groupfacs = new GroupFactories(5); group.getChildren().add(d.getStoMo()); group.getChildren().add(groupfacs); group.getChildren().add(d); Scene scene = new Scene(group, VIEWER_WIDTH, VIEWER_HEIGHT); scene.setFill(Color.BISQUE); stage.setScene(scene); stage.show(); } } /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vertx.tests.core.http; import org.testng.annotations.Test; import org.vertx.java.core.Handler; import org.vertx.java.core.SimpleHandler; import org.vertx.java.core.http.HttpClient; import org.vertx.java.core.http.HttpClientRequest; import org.vertx.java.core.http.HttpClientResponse; import org.vertx.java.core.http.HttpServer; import org.vertx.java.core.http.HttpServerRequest; import org.vertx.java.core.http.RouteMatcher; import org.vertx.java.core.internal.VertxInternal; import org.vertx.java.core.logging.Logger; import org.vertx.tests.core.TestBase; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * @author */ public class RouteMatcherTest extends TestBase { private static final Logger log = Logger.getLogger(RouteMatcherTest.class); @Test public void testRouteWithPattern() throws Exception { Map params = new HashMap<>(); params.put("name", "foo"); params.put("version", "v0.1"); testRoute(false, "/:name/:version", params, "/foo/v0.1"); params.clear(); params.put("name", "foo"); params.put("version", "v0.1"); testRoute(false, "modules/:name/:version", params, "modules/foo/v0.1"); params.clear(); params.put("name", "foo"); params.put("version", "v0.1"); testRoute(false, "modules/:name/:version/", params, "modules/foo/v0.1/"); params.clear(); params.put("name", "foo"); params.put("version", "v0.1"); testRoute(false, "modules/:name/:version/whatever", params, "modules/foo/v0.1/whatever"); params.clear(); params.put("name", "foo"); params.put("version", "v0.1"); testRoute(false, "modules/:name/blah/:version/whatever", params, "modules/foo/blah/v0.1/whatever"); params.clear(); params.put("name", "foo"); testRoute(false, "/:name/", params, "/foo/"); } @Test public void testRouteWithRegEx() throws Exception { Map params = new HashMap<>(); params.put("param0", "foo"); params.put("param1", "v0.1"); String regex = "\\/([^\\/]+)\\/([^\\/]+)"; testRoute(true, regex, params, "/foo/v0.1"); } private void testRoute(final boolean regex, final String pattern, final Map params, final String uri) throws Exception { final String host = "localhost"; final int port = 8181; final CountDownLatch latch = new CountDownLatch(1); VertxInternal.instance.go(new Runnable() { public void run() { RouteMatcher matcher = new RouteMatcher(); Handler handler = new Handler() { public void handle(HttpServerRequest req) { assert (req.getParams().size() == params.size()); for (Map.Entry entry : params.entrySet()) { assert (entry.getValue().equals(req.getParams().get(entry.getKey()))); } req.response.end(); } }; if (regex) { matcher.getWithRegEx(pattern, handler); } else { matcher.get(pattern, handler); } final HttpServer server = new HttpServer().requestHandler(matcher).listen(port, host); final HttpClient client = new HttpClient().setPort(port).setHost(host); final HttpClientRequest req = client.get(uri, new Handler() { public void handle(HttpClientResponse resp) { assert (200 == resp.statusCode); server.close(new SimpleHandler() { public void handle() { latch.countDown(); } }); } }); req.end(); } }); azzert(latch.await(5, TimeUnit.SECONDS)); throwAssertions(); } } joinee0208/Algorithm-Guide class Solution { public char firstUniqChar(String s) { int arr[] = new int[26]; for(int i=0;i { public ByteSerialPortData(byte[] data, DataHandleListener requestHandleListener) { this.data = data; dataHandleListener = requestHandleListener; } @Override public byte[] getDataBytes() { return data; } @Override public String toString() { return ByteUtil.toDisplayString(data); } }src/main/java/br/com/projuris/FindCharBody.java package br.com.projuris; public class FindCharBody { private String word; public String getWord() { return word; } public void setWord(String word) { this.word = word; } } /* * Copyright 2016-2020 Talsma ICT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.talsmasoftware.enumerables.jaxrs; import nl.talsmasoftware.enumerables.Enumerable; import org.junit.Test; import java.util.logging.Level; import java.util.logging.Logger; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; import static org.hamcrest.Matchers.stringContainsInOrder; import static org.junit.Assert.fail; public class EnumerableParamConverterTest { private static final TestEnumerable FOURTH = Enumerable.parse(TestEnumerable.class, "4th"); @Test @SuppressWarnings("unchecked") public void testConstructor_nullType() { try { new EnumerableParamConverter(null); fail("Exception expected"); } catch (RuntimeException expected) { assertThat(expected, hasToString(containsString("type is "))); } } @Test public void testFromString() { EnumerableParamConverter converter = new EnumerableParamConverter(TestEnumerable.class); assertThat(converter.fromString("1st"), is(sameInstance(TestEnumerable.FIRST))); assertThat(converter.fromString("2nd"), is(sameInstance(TestEnumerable.SECOND))); assertThat(converter.fromString("3rd"), is(sameInstance(TestEnumerable.THIRD))); assertThat(converter.fromString("4th"), is(equalTo(FOURTH))); assertThat(converter.fromString(null), is(nullValue())); } @Test public void testToString() { EnumerableParamConverter converter = new EnumerableParamConverter(TestEnumerable.class); assertThat(converter.toString(TestEnumerable.FIRST), is(equalTo("1st"))); assertThat(converter.toString(TestEnumerable.SECOND), is(equalTo("2nd"))); assertThat(converter.toString(TestEnumerable.THIRD), is(equalTo("3rd"))); assertThat(converter.toString(FOURTH), is(equalTo("4th"))); assertThat(converter.toString(null), is(nullValue())); } @Test public void testForLoggingErrors() { Logger logger = Logger.getLogger(EnumerableParamConverter.class.getName()); logger.setLevel(Level.FINEST); testFromString(); testToString(); logger.setLevel(Level.INFO); } @Test public void testConverterToString() { assertThat(new EnumerableParamConverter(TestEnumerable.class), hasToString(stringContainsInOrder(asList("EnumerableParamConverter", "TestEnumerable")))); } } Proyecto_Cinerama_Spring/src/java/models/Sala.java package models; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.UpdateOptions; import java.util.ArrayList; import java.util.List; import org.bson.Document; import org.bson.conversions.Bson; public class Sala extends Conexion { private final MongoClient cliente = crearConexion(); private final MongoDatabase database = cliente.getDatabase("dbcinerama"); protected final MongoCollection collection = database.getCollection("salas"); private String id; private String filas; private String columnas; private String butacas; private String cant_butacas; public Sala(String id, String filas, String columnas, String butacas, String cant_butacas) { this.id = id; this.filas = filas; this.columnas = columnas; this.butacas = butacas; this.cant_butacas = cant_butacas; } public Sala() { } public void Insertar(){ Document datos = new Document(); datos.append("_id", this.getId()); datos.append("filas", this.getFilas()); datos.append("columnas", this.getColumnas()); datos.append("butacas", this.getButacas()); datos.append("cant_butacas", this.getCant_butacas()); try{ collection.insertOne(datos); } catch(Exception e){ } } public void Actualizar(){ Document datos = new Document(); datos.append("_id", this.getId()); datos.append("filas", this.getFilas()); datos.append("columnas", this.getColumnas()); datos.append("butacas", this.getButacas()); datos.append("cant_butacas", this.getCant_butacas()); BasicDBObject query = new BasicDBObject(); query.append("_id", this.getId()); Bson newDocument = new Document("$set", datos); try { collection.updateOne(query, newDocument,(new UpdateOptions()).upsert(true)); } catch (Exception e) { } } public Document getSala(String id){ Document pelicula = null; List documentos= this.getListaSalas(); //pelicula = documentos.get(0); for(int i = 0;i getListaSalas(){ List documentos = (List) collection.find().into( new ArrayList()); return documentos; } public String getId() { return id; } public String getFilas() { return filas; } public String getColumnas() { return columnas; } public String getButacas() { return butacas; } public void setId(String id) { this.id = id; } public void setFilas(String filas) { this.filas = filas; } public void setColumnas(String columnas) { this.columnas = columnas; } public void setButacas(String butacas) { this.butacas = butacas; } public int getNroButacas(){ return Integer.valueOf(getFilas())*Integer.valueOf(getColumnas()); } public String getCant_butacas() { return cant_butacas; } public void setCant_butacas(String cant_butacas) { this.cant_butacas = cant_butacas; } } Befrish/jqwik-vavr package de.befrish.jqwik.vavr.providers; import de.befrish.jqwik.vavr.arbitraries.VavrLazyArbitrary; import de.befrish.jqwik.vavr.providers.base.AbstractSingleTypeArbitraryProvider; import io.vavr.Lazy; import net.jqwik.api.Arbitrary; import net.jqwik.api.providers.ArbitraryProvider; import org.kohsuke.MetaInfServices; @MetaInfServices(ArbitraryProvider.class) public class VavrLazyArbitraryProvider extends AbstractSingleTypeArbitraryProvider { @Override protected Class getProvidedType() { return Lazy.class; } @Override protected VavrLazyArbitrary create(final Arbitrary innerArbitrary) { return new VavrLazyArbitrary<>(innerArbitrary); } } public class EntityParticleEmitter { // Failed to decompile, took too long to decompile: net/minecraft/client/particle/EntityParticleEmitter }jiezhang-tlnd/tdq-studio-se // ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.dq.indicators; import java.sql.SQLException; import java.sql.Statement; import org.talend.dataquality.analysis.Analysis; import org.talend.dq.helper.SampleDataUtils; /** * DOC zshen class global comment. Detailled comment */ public class ColumnSetIndicatorEvaluatorWithSampleData extends ColumnSetIndicatorEvaluator { /** * DOC zshen ColumnSetIndicatorEvaluatorWithSampleData constructor comment. * * @param analysis */ public ColumnSetIndicatorEvaluatorWithSampleData(Analysis analysis) { super(analysis); } /* * (non-Javadoc) * * @see org.talend.dq.indicators.Evaluator#createStatement() */ @Override protected Statement createStatement() throws SQLException { return SampleDataUtils.getInstance().getSampleDataStatement(this.analysis); } } package svenhjol.strange; import net.minecraftforge.fml.common.Mod; import svenhjol.meson.Feature; import svenhjol.strange.base.StrangeLoader; import svenhjol.strange.totems.StrangeTotems; @Mod(Strange.MOD_ID) public class Strange { public static final String MOD_ID = "strange"; public Strange() { StrangeLoader.INSTANCE.registerLoader(Strange.MOD_ID).setup( new StrangeTotems() ); } public static boolean hasFeature(Class feature) { return StrangeLoader.INSTANCE.enabledFeatures.containsKey(feature); } } // // $Id$ package com.threerings.bang.game.data.effect; import java.awt.Rectangle; import java.awt.Point; import java.lang.reflect.Array; import java.util.ArrayList; import com.samskivert.util.IntIntMap; import com.threerings.util.MessageBundle; import com.threerings.io.SimpleStreamableObject; import com.threerings.bang.data.StatType; import com.threerings.bang.game.client.EffectHandler; import com.threerings.bang.game.data.BangObject; import com.threerings.bang.game.data.card.Card; import com.threerings.bang.game.data.piece.Piece; import com.threerings.bang.game.data.piece.Unit; import static com.threerings.bang.Log.log; /** * Encapsulates any effect on a piece in the game. All state changes are * communicated through an ordered stream of effects. */ public abstract class Effect extends SimpleStreamableObject implements Cloneable { /** An effect to use when a piece's internal status is updated and it * should be refreshed, but no other visible change will take place. */ public static final String UPDATED = "updated"; /** Provides a mechanism for observing the individual effects that take * place when applying an effect to the board and pieces. */ public static interface Observer { /** * Indicates that the specified piece was added to the board. */ public void pieceAdded (Piece piece); /** * Indicates that the specified piece was affected with the named * effect. The piece's sprite should be updated to reflect the piece's * new internal state after an appropriate visualization has been * displayed. */ public void pieceAffected (Piece piece, String effect); /** * Indicates that the board was affected with the named visual effect. */ public void boardAffected (String effect); /** * Indicates that the specified piece was moved or reoriented. */ public void pieceMoved (Piece piece); /** * Indicates that the piece in question was killed (killed pieces are * not automatically removed; if a piece was removed that will be * reported separately with a call to {@link #pieceRemoved}). * * @param shooter the index of the player that shot the piece, or -1 * if a player was not responsible * @param sidx the index of the piece that was responsible, or -1 if * there was no piece responsible */ public void pieceKilled (Piece piece, int shooter, int sidx); /** * Indicates that the specified piece was removed from the board. */ public void pieceRemoved (Piece piece); /** * Indicates that the card has been added to a player's hand. */ public void cardAdded (Card card); /** * Indicates that a card has been removed from a player's hand. */ public void cardRemoved (Card card); /** * Indicates that a user played a card. */ public void cardPlayed (Card card, Object target); /** * Indicates that the tick was delayed for the specified amount of time * in order to let an effect run its course. */ public void tickDelayed (long extraTime); } /** * Handles a collision that moves and damages a unit. * * @param colliderIdx the index of the user causing the collision, or -1. * @param colliderId the id of the colliding piece, or -1. * @param damage the amount of damage caused by the collision. * * @return true if all went well, false if we failed to collide or do * damage. */ public static boolean collide ( BangObject bangobj, Observer obs, int colliderIdx, int colliderId, int targetId, int damage, int x, int y, String effect) { Piece collider = null; if (colliderId != -1 && (collider = bangobj.pieces.get(colliderId)) == null) { log.warning("Missing colliding piece", "colliderId", colliderId); return false; } Piece target = bangobj.pieces.get(targetId); if (target == null) { log.warning("Missing collision target", "targetId", targetId); return false; } return collide(bangobj, obs, colliderIdx, collider, target, Math.min(100, target.damage + damage), x, y, effect); } /** * Handles a collision that moves and damages a unit. * * @param collider the index of the user causing the collision, or -1. * @param newDamage the new total damage to assign to the damaged piece. * * @return true if all went well, false if we failed to collide or do * damage. */ public static boolean collide ( BangObject bangobj, Observer obs, int colliderIdx, Piece collider, Piece target, int newDamage, int x, int y, String effect) { // move the target to its new coordinates if (target instanceof Unit && (target.x != x || target.y != y)) { int oldDamage = target.damage; target.damage = newDamage; moveAndReport(bangobj, target, x, y, obs); target.damage = oldDamage; } // damage the target if it's still alive if (target.isAlive()) { return damage(bangobj, obs, colliderIdx, collider, target, newDamage, effect); } return true; } /** * Damages the supplied piece by the specified amount, properly removing it * from the board if appropriate and reporting the specified effect. * * @param shooterIdx the index of the player doing the damage or -1 if the * damage was not originated by a player. * @param shooter the piece doing the damage, or null if the * damage wasn't caused by a piece. * @param newDamage the new total damage to assign to the damaged piece. * * @return true if the damage was applied, false if the target was already * dead and we were unable to apply the damage. */ public static boolean damage ( BangObject bangobj, Observer obs, int shooterIdx, Piece shooter, Piece target, int newDamage, String effect) { // sanity check if (!target.isAlive()) { log.warning("Not damaging already dead target", "target", target, "shooter", shooterIdx, "nd", newDamage, "effect", effect); return false; } // effect the actual damage //log.info("Damaging " + target + " -> " + newDamage + "."); target.wasDamaged(newDamage); boolean alive = target.isAlive(); if (!alive) { target.wasKilled(bangobj.tick); // airborn targets must land when they die Point pt = target.maybeCrash(bangobj, shooterIdx); if (pt != null) { moveAndReport(bangobj, target, pt.x, pt.y, obs, false); } } // report that the target was affected reportEffect(obs, target, effect); int sidx = (shooter == null ? -1 : shooter.pieceId); // if the target is not dead, we can stop here if (target.isAlive()) { // if the piece was killed but remained alive for some reason // still report the kill if (!alive) { reportKill(obs, target, shooterIdx, sidx); } return true; } // report that the target was killed reportKill(obs, target, shooterIdx, sidx); // if we're on the server, record the kill if (bangobj.getManager().isManager(bangobj) && target instanceof Unit) { if (shooterIdx != -1) { if (shooter != null && target.owner >= 0) { shooter.didKill(); if (shooter instanceof Unit) { bangobj.stats[shooterIdx].maxStat( StatType.CONSEC_KILLS, ((Unit)shooter).consecKills); } } // record the kill statistics bangobj.stats[shooterIdx].incrementStat(StatType.UNITS_KILLED, 1); } if (target.owner != -1) { bangobj.stats[target.owner].incrementStat(StatType.UNITS_LOST, 1); } } // if the should be removed when killed, do so now if (target.removeWhenDead()) { removeAndReport(bangobj, target, obs); // otherwise reshadow the piece to block all ground travel across } else { int owner = target.owner; target.setOwner(bangobj, -1); bangobj.board.shadowPiece(target); target.setOwner(bangobj, owner); } return true; } /** * All effects should be cloned before distributed to ensure they are * not altered before getting sent to the client. */ public Object clone () { try { return super.clone(); } catch (CloneNotSupportedException cnse) { throw new RuntimeException(cnse); } } /** * Initializes this effect (called only on the server) with the piece that * activated the bonus. */ public void init (Piece piece) { } /** * Returns an array of pieces we must wait for before activating this * effect. The default implementation returns nothing, however, some * effects may require that we wait for a piece to finish animating before * starting but not necessarily block that piece from moving on to the next * animation once this effect's visualization is started. * *

Note: it is not necessary to return any pieces that are already * returned by {@link #getAffectedPieces} as those will automatically be * waited for. */ public int[] getWaitPieces () { return NO_PIECES; } /** * Returns an array of pieces that will be moved by this effect. The * default implementation returns nothing, however, some effects will * cause pieces to move and should be specified here if they may block * the path of another piece. */ public int[] getMovePieces () { return NO_PIECES; } /** * Returns the bounds we must have exclusive access to before activating * this effect. Can return null for no area exclusion. */ public Rectangle[] getBounds (BangObject bangobj) { return null; } /** Returns an array of the ids of all pieces affected by this effect. */ public abstract int[] getAffectedPieces (); /** * Prepares this effect for application. This is executed on the server * before the effect is applied on the server and then distributed to the * client for application there. Effects must not make any * modifications to the game state in prepare as they may be canceled after * calling prepare if {@link #isApplicable} then returns false. They should * simply decide what they're going to do, which pieces they are going to * effect, etc. and then actually effect any changes in {@link #apply} * (which will be called immediately after prepare on the server, with only * an intervening call to {@link #isApplicable}). * * @param dammap a mapping that should be used to record damage done * to a particular player's units (player index -> accumulated * damage). */ public abstract void prepare (BangObject bangobj, IntIntMap dammap); /** * A method only used by effects created by cards that returns true if this * effect will serve its intended purpose or false if the card that caused * the effect should be considered unplayed and the effect cancelled. The * default implementation always assumes applicability. */ public boolean isApplicable () { return true; } /** * Applies this effect to the board and pieces. Any modifications to pieces * or the board should be made directly as this is executed on both the * client and server. Note: effects should always compute and * store the final result of their effects in {@link #prepare} and then * simply apply those results in {@link #apply} rather than do any * computation in {@link #apply} as we cannot rely on the values in the * piece during the apply to be the same as they would be on the server * when the effect is applied. The only truly safe time to inspect the * condition of the affected pieces is during {@link #prepare}. * * @param observer an observer to inform of piece additions, updates and * removals (for display purposes on the client). This may be null. * * @return false if for some reason the effect could not be applied (this * is only used for in the field debugging). */ public abstract boolean apply (BangObject bangobj, Observer observer); /** * Creates an {@link EffectHandler} to manage the (potentially complicated) * visualization of this effect. */ public EffectHandler createHandler (BangObject bangobj) { return new EffectHandler(); } /** * Returns the base amount of damage inflicted on the specified piece * (that is, the amount before it's limited by the piece's remaining * health). */ public int getBaseDamage (Piece piece) { return 0; } /** * Returns a translatable description of the effect to display on the * client, or null for none. * * @param pidx the client's player index */ public String getDescription (BangObject bangobj, int pidx) { return null; } @Override // documentation inherited public String toString () { String cname = getClass().getName(); return cname.substring(cname.lastIndexOf(".")+1) + ":" + super.toString(); } /** A helper function for adding a piece and reporting it. */ protected static void addAndReport ( BangObject bangobj, Piece piece, Observer obs) { Piece added = (Piece)piece.clone(); bangobj.addPieceDirect(added); added.wasAdded(bangobj); if (obs != null) { obs.pieceAdded(added); } } /** A helper function for removing a piece and reporting it. */ protected static void removeAndReport ( BangObject bangobj, Piece piece, Observer obs) { bangobj.removePieceDirect(piece); if (piece.rebuildShadow()) { // removing props requires building the shadow from scratch bangobj.board.shadowPieces(bangobj.getPropPieceIterator(), piece.x, piece.y, piece.getWidth(), piece.getLength()); } if (obs != null) { obs.pieceRemoved(piece); } } /** A helper function for reporting a piece affecting. */ protected static void reportEffect ( Observer obs, Piece piece, String effect) { if (obs != null) { obs.pieceAffected(piece, effect); } } /** A helper function for affecting the board and reporting it. */ protected static void affectBoard ( BangObject bangobj, String effect, boolean persist, Observer obs) { if (persist) { bangobj.boardEffect = effect; } if (obs != null) { obs.boardAffected(effect); } } /** A helper function for moving a piece and reporting it. */ protected static void moveAndReport ( BangObject bangobj, Piece piece, int nx, int ny, Observer obs) { moveAndReport(bangobj, piece, nx, ny, obs, true); } protected static void moveAndReport (BangObject bangobj, Piece piece, int nx, int ny, Observer obs, boolean shadow) { bangobj.board.clearShadow(piece); piece.position(nx, ny); if (shadow) { bangobj.board.shadowPiece(piece); } if (obs != null) { obs.pieceMoved(piece); } } /** A helper function for reporting piece death. */ protected static void reportKill (Observer obs, Piece piece, int shooter, int sidx) { if (obs != null) { obs.pieceKilled(piece, shooter, sidx); } } /** Adds a card and reports it to the observer. */ protected static void addAndReport ( BangObject bangobj, Card card, Observer obs) { bangobj.cards.addDirect(card); if (obs != null) { obs.cardAdded(card); } } /** Removes a card and reports it to the observer. */ protected static void removeAndReport ( BangObject bangobj, Card card, Observer obs) { bangobj.cards.removeDirect(card); if (obs != null) { obs.cardRemoved(card); } } /** Removes a card and reports its being played to the observer. */ protected static void playAndReport ( BangObject bangobj, Card card, Object target, Observer obs) { bangobj.cards.removeDirect(card); if (obs != null) { obs.cardPlayed(card, target); } } /** A helper function for reporting a tick delay. */ protected static void reportDelay (Observer obs, long extraTime) { if (obs != null) { obs.tickDelayed(extraTime); } } /** Concatenates two integer arrays and returns the result. */ protected static int[] concatenate (int[] a1, int[] a2) { int[] result = new int[a1.length + a2.length]; System.arraycopy(a1, 0, result, 0, a1.length); System.arraycopy(a2, 0, result, a1.length, a2.length); return result; } /** Concatenates two generic arrays and returns the result. */ protected static T[] concatenate (T[] a1, T[] a2) { @SuppressWarnings("unchecked") T[] result = (T[])Array.newInstance( a1.getClass().getComponentType(), a1.length + a2.length); System.arraycopy(a1, 0, result, 0, a1.length); System.arraycopy(a2, 0, result, a1.length, a2.length); return result; } /** Returns a translatable string representing the names of the pieces * identified in the piece id array owned by the specified player. */ protected String getPieceNames ( BangObject bangobj, int pidx, int[] pieceIds) { ArrayList names = new ArrayList(); for (int pieceId : pieceIds) { Piece piece = bangobj.pieces.get(pieceId); if (piece != null && piece.owner == pidx) { names.add(piece.getName()); } } int nsize = names.size(); if (nsize == 0) { return null; } else if (nsize == 1) { return names.get(0); } else { return MessageBundle.compose("m.times_" + nsize, names.toArray(new String[nsize])); } } /** Used by {@link #getWaitPieces}. */ protected static final int[] NO_PIECES = new int[0]; } package org.vanilladb.comm.client; import java.io.Serializable; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.logging.log4j.core.config.Configurator; import org.vanilladb.comm.process.ProcessList; import org.vanilladb.comm.protocols.p2pappl.P2pApplicationLayer; import org.vanilladb.comm.protocols.p2pappl.P2pMessage; import org.vanilladb.comm.protocols.p2pappl.P2pMessageListener; import org.vanilladb.comm.view.ProcessType; import org.vanilladb.comm.view.ProcessView; import net.sf.appia.core.Appia; import net.sf.appia.core.AppiaDuplicatedSessionsException; import net.sf.appia.core.AppiaEventException; import net.sf.appia.core.AppiaInvalidQoSException; import net.sf.appia.core.Channel; import net.sf.appia.core.Direction; import net.sf.appia.core.Layer; import net.sf.appia.core.QoS; import net.sf.appia.protocols.tcpcomplete.TcpCompleteLayer; public class VanillaCommClient implements P2pMessageListener, Runnable { private static Logger logger = Logger.getLogger(VanillaCommClient.class.getName()); public static int getServerCount() { return ProcessView.SERVER_COUNT; } public static int getClientCount() { return ProcessView.CLIENT_COUNT; } private VanillaCommClientListener listener; private Channel p2pChannel; public VanillaCommClient(int selfId, VanillaCommClientListener listener) { int globalSelfId = ProcessView.toGlobalId(ProcessType.CLIENT, selfId); this.listener = listener; setupP2pChannel(globalSelfId); // Disable Log4j Logging which is the default logger of Appia Configurator.setRootLevel(org.apache.logging.log4j.Level.OFF); } @Override public void run() { if (logger.isLoggable(Level.INFO)) logger.info("Starts the network service"); Appia.run(); } public void sendP2pMessage(ProcessType receiverType, int receiverId, Serializable message) { try { int globalId = ProcessView.toGlobalId(receiverType, receiverId); P2pMessage p2p = new P2pMessage(message, globalId); p2p.asyncGo(p2pChannel, Direction.DOWN); } catch (AppiaEventException e) { e.printStackTrace(); } } @Override public void onRecvP2pMessage(int senderId, Serializable message) { listener.onReceiveP2pMessage(ProcessView.toProcessType(senderId), ProcessView.toLocalId(senderId), message); } private void setupP2pChannel(int globalSelfId) { try { ProcessList processList = ProcessView.buildAllProcessList(globalSelfId); Layer[] layers = new Layer[] { new TcpCompleteLayer(), new P2pApplicationLayer(this, processList, true) }; QoS qos = new QoS("P2P QoS", layers); p2pChannel = qos.createUnboundChannel("P2P Channel"); p2pChannel.start(); } catch (AppiaInvalidQoSException e) { e.printStackTrace(); } catch (AppiaDuplicatedSessionsException e) { e.printStackTrace(); } } } package io.github.pureza.warbots.collisions; import io.github.pureza.warbots.entities.Wall; import io.github.pureza.warbots.geometry.Point; import io.github.pureza.warbots.geometry.Size; import io.github.pureza.warbots.weaponry.Projectile; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class ProjectileWallCollisionTest { @Test public void projectileHitsWall() { Projectile projectile = mock(Projectile.class); Wall wall = new Wall(Point.pt(1, 1), new Size(1, 1)); ProjectileWallCollision collision = new ProjectileWallCollision(projectile, wall); collision.handle(); verify(projectile).hitStaticEntity(wall); } } package net.sourceforge.kolmafia.request; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sourceforge.kolmafia.RequestLogger; public class LeafletRequest extends GenericRequest { private static final Pattern COMMAND_PATTERN = Pattern.compile("command=([^&]*)"); private static final Pattern RESPONSE_PATTERN = Pattern.compile("(.*?)"); private static final Pattern TCHOTCHKE_PATTERN = Pattern.compile("A ([a-z ]*?) sits on the mantelpiece"); public LeafletRequest() { this(null); } public LeafletRequest(final String command) { super("leaflet.php"); if (command != null) { this.addFormField("command", command); } } public void setCommand(final String command) { this.clearDataFields(); this.addFormField("command", command); } @Override public void processResults() { LeafletRequest.parseResponse(this.getURLString(), this.responseText); } public static final void parseResponse(final String urlString, final String responseText) { Matcher matcher = RESPONSE_PATTERN.matcher(responseText); if (!matcher.find()) { return; } matcher = TCHOTCHKE_PATTERN.matcher(matcher.group(1)); if (matcher.find()) { RequestLogger.updateSessionLog("(You see a " + matcher.group(1) + ")"); } } private static String getCommand(final String urlString) { Matcher matcher = COMMAND_PATTERN.matcher(urlString); if (!matcher.find()) { return null; } return GenericRequest.decodeField(matcher.group(1)); } public static final boolean registerRequest(final String urlString) { if (!urlString.startsWith("leaflet.php")) { return false; } String command = LeafletRequest.getCommand(urlString); if (command == null) { return true; } RequestLogger.updateSessionLog(); RequestLogger.updateSessionLog("Leaflet " + command); return true; } } import java.util.Date; public class DateRange { private final Date start; private final Date end; public DateRange(Date start, Date end) { this.start = start; this.end = end; } public Date getStart() { return start; } public Date getEnd() { return end; } } package com.symphony.bdk.workflow; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.delete; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.ok; import static com.github.tomakehurst.wiremock.client.WireMock.options; import static com.github.tomakehurst.wiremock.client.WireMock.patch; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.symphony.bdk.workflow.custom.assertion.Assertions.assertThat; import static org.junit.jupiter.params.provider.Arguments.arguments; import com.symphony.bdk.workflow.swadl.SwadlParser; import com.symphony.bdk.workflow.swadl.v1.Workflow; import com.github.tomakehurst.wiremock.client.MappingBuilder; import com.github.tomakehurst.wiremock.http.Fault; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import com.github.tomakehurst.wiremock.matching.UrlPattern; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.List; import java.util.stream.Stream; @WireMockTest class ExecuteRequestIntegrationTest extends IntegrationTest { static Stream httpMethods() { return Stream.of( arguments(post(UrlPattern.ANY), "/request/execute-request-successful-POST.swadl.yaml", List.of("executePostRequest", "assertionScript")), arguments(put(UrlPattern.ANY), "/request/execute-request-successful-PUT.swadl.yaml", List.of("executePutRequest", "assertionScript")), arguments(delete(UrlPattern.ANY), "/request/execute-request-successful-DELETE.swadl.yaml", List.of("executeDeleteRequest", "assertionScript")), arguments(patch(UrlPattern.ANY), "/request/execute-request-successful-PATCH.swadl.yaml", List.of("executePatchRequest", "assertionScript")), arguments(options(UrlPattern.ANY), "/request/execute-request-successful-OPTIONS.swadl.yaml", List.of("executeOptionsRequest", "assertionScript")) ); } @ParameterizedTest @MethodSource("httpMethods") void executeRequestSuccessful(MappingBuilder method, String swadlFile, List activitiesToBeExecuted, WireMockRuntimeInfo wmRuntimeInfo) throws Exception { final Workflow workflow = SwadlParser.fromYaml(getClass().getResourceAsStream(swadlFile)); this.putFirstActivityUrl(workflow, wmRuntimeInfo.getHttpBaseUrl() + "/api"); stubFor(method.withHeader("keyOne", equalTo("valueOne")) .withHeader("keyTwo", equalTo("valueTwo,valueThree")) .withRequestBody(equalToJson("{\"key\":\"value\"}")) .willReturn(ok().withHeader("Content-Type", "application/json") .withBody("{\"name\": \"john\"}"))); engine.deploy(workflow); engine.onEvent(messageReceived("/execute")); assertThat(workflow).isExecuted().executed(activitiesToBeExecuted.toArray(new String[0])); } @Test void executeRequestSuccessfulToDelete(WireMockRuntimeInfo wmRuntimeInfo) throws Exception { final Workflow workflow = SwadlParser.fromYaml(getClass().getResourceAsStream("/request/execute-request-successful-HEAD.swadl.yaml")); putFirstActivityUrl(workflow, wmRuntimeInfo.getHttpBaseUrl() + "/api"); stubFor(post(UrlPattern.ANY).withHeader("keyOne", equalTo("valueOne")) .withHeader("keyTwo", equalTo("valueTwo,valueThree")) .withRequestBody(equalToJson("{\"key\":\"value\"}")) .willReturn(ok().withHeader("Content-Type", "application/json") .withBody("{\"name\": \"john\"}"))); engine.deploy(workflow); engine.onEvent(messageReceived("/execute")); assertThat(workflow).isExecuted().executed("executeHeadRequest", "assertionScript"); } @Test void executeGetRequestSuccessful(WireMockRuntimeInfo wmRuntimeInfo) throws Exception { final Workflow workflow = SwadlParser.fromYaml(getClass().getResourceAsStream("/request/execute-request-successful-GET.swadl.yaml")); putFirstActivityUrl(workflow, wmRuntimeInfo.getHttpBaseUrl() + "/api"); stubFor(get(UrlPattern.ANY).withHeader("keyOne", equalTo("valueOne")) .withHeader("keyTwo", equalTo("valueTwo,valueThree")) .willReturn(ok().withHeader("Content-Type", "application/json").withBody("{\"name\": \"john\"}"))); engine.deploy(workflow); engine.onEvent(messageReceived("/execute")); assertThat(workflow).isExecuted().executed("executeGetRequest", "assertionScript"); } @Test void executeRequestException(WireMockRuntimeInfo wmRuntimeInfo) throws Exception { final Workflow workflow = SwadlParser.fromYaml(getClass().getResourceAsStream("/request/execute-request-ioexception.swadl.yaml")); putFirstActivityUrl(workflow, wmRuntimeInfo.getHttpBaseUrl() + "/api"); stubFor(post(UrlPattern.ANY).willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))); engine.deploy(workflow); engine.onEvent(messageReceived("/execute-failed")); assertThat(workflow).as("The workflow fails on runtime exception") .executed("executeGetRequest") .notExecuted("assertionScript"); } @Test void executeRequestEncodeQueryParameters(WireMockRuntimeInfo wmRuntimeInfo) throws Exception { final Workflow workflow = SwadlParser.fromYaml( getClass().getResourceAsStream("/request/execute-request-encode-query-parameters.swadl.yaml")); putFirstActivityUrl(workflow, wmRuntimeInfo.getHttpBaseUrl() + "/api?key1=v 1&key2=value@!$2&key3=value%3"); stubFor(post("/api?key1=v+1&key2=value%40%21%242&key3=value%253") .willReturn(ok().withHeader("Content-Type", "application/json") .withBody("{\"message\": \"ok\"}"))); engine.deploy(workflow); engine.onEvent(messageReceived("/execute")); assertThat(workflow).isExecuted().executed("executeRequestWithQueryParams", "assertionScript"); } @Test void executeRequestNotEncodeQueryParameters(WireMockRuntimeInfo wmRuntimeInfo) throws Exception { final Workflow workflow = SwadlParser.fromYaml( getClass().getResourceAsStream("/request/execute-request-not-encode-query-parameters.swadl.yaml")); putFirstActivityUrl(workflow, wmRuntimeInfo.getHttpBaseUrl() + "/api?key1=value%201&key2=value%402"); stubFor(post(urlEqualTo("/api?key1=value%201&key2=value%402")) .willReturn(ok().withHeader("Content-Type", "application/json") .withBody("{\"message\": \"ok\"}"))); engine.deploy(workflow); engine.onEvent(messageReceived("/execute")); assertThat(workflow).isExecuted().executed("executeRequestWithEncodedQueryParams", "assertionScript"); } @Test void executeRequestEncodeQueryParametersNotExecuted(WireMockRuntimeInfo wmRuntimeInfo) throws Exception { final Workflow workflow = SwadlParser.fromYaml( getClass().getResourceAsStream("/request/execute-request-not-encode-query-parameters-no-response.swadl.yaml")); putFirstActivityUrl(workflow, wmRuntimeInfo.getHttpBaseUrl() + "/api?key1=value%201&key2=value%402"); stubFor(post("/api?key1=v+1&key2=value%40%21%242") .willReturn(ok().withHeader("Content-Type", "application/json") .withBody("{\"message\": \"ok\"}"))); engine.deploy(workflow); engine.onEvent(messageReceived("/execute")); assertThat(workflow).isExecuted().executed("executeRequestWithEncodedQueryParams", "assertionScript"); } private void putFirstActivityUrl(Workflow workflow, String url) { workflow.getFirstActivity() .get() .getActivity() .getVariableProperties() .put("url", url); } } 1-10 package com.github.technoir42.glide.preloader; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import com.google.android.flexbox.FlexboxLayoutManager; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class DefaultVisiblePositionFinderTest { private final DefaultVisiblePositionFinder visiblePositionFinder = new DefaultVisiblePositionFinder(); @Nested @DisplayName("Unsupported LayoutManager") class UnsupportedLayoutManagerTest { @Test @DisplayName("findFirstVisibleItemPosition throws IllegalStateException") void findFirstVisibleItemPosition() { RecyclerView.LayoutManager layoutManager = new MockLayoutManager(); Exception e = assertThrows(IllegalStateException.class, () -> visiblePositionFinder.findFirstVisibleItemPosition(layoutManager)); assertEquals("Unsupported LayoutManager: com.github.technoir42.glide.preloader.MockLayoutManager", e.getMessage()); } @Test @DisplayName("findLastVisibleItemPosition throws IllegalStateException") void findLastVisibleItemPosition() { RecyclerView.LayoutManager layoutManager = new MockLayoutManager(); Exception e = assertThrows(IllegalStateException.class, () -> visiblePositionFinder.findLastVisibleItemPosition(layoutManager)); assertEquals("Unsupported LayoutManager: com.github.technoir42.glide.preloader.MockLayoutManager", e.getMessage()); } } @Nested @DisplayName("LinearLayoutManager") class LinearLayoutManagerTest { @Test void findFirstVisibleItemPosition() { LinearLayoutManager layoutManager = mock(LinearLayoutManager.class); when(layoutManager.findFirstVisibleItemPosition()).thenReturn(42); int result = visiblePositionFinder.findFirstVisibleItemPosition(layoutManager); assertEquals(42, result); } @Test void findLastVisibleItemPosition() { LinearLayoutManager layoutManager = mock(LinearLayoutManager.class); when(layoutManager.findLastVisibleItemPosition()).thenReturn(42); int result = visiblePositionFinder.findLastVisibleItemPosition(layoutManager); assertEquals(42, result); } } @Nested @DisplayName("StaggeredGridLayoutManager") class StaggeredGridLayoutManagerTest { @Test void findFirstVisibleItemPosition() { StaggeredGridLayoutManager layoutManager = mock(StaggeredGridLayoutManager.class); int[] positions = {-1, 0, 1}; when(layoutManager.getSpanCount()).thenReturn(positions.length); when(layoutManager.findFirstVisibleItemPositions(any())).thenAnswer(copyToArgument(positions)); int result = visiblePositionFinder.findFirstVisibleItemPosition(layoutManager); assertEquals(0, result); } @Test void findLastVisibleItemPosition() { StaggeredGridLayoutManager layoutManager = mock(StaggeredGridLayoutManager.class); int[] positions = {-1, 2, 1}; when(layoutManager.getSpanCount()).thenReturn(positions.length); when(layoutManager.findLastVisibleItemPositions(any())).thenAnswer(copyToArgument(positions)); int result = visiblePositionFinder.findLastVisibleItemPosition(layoutManager); assertEquals(2, result); } private Answer copyToArgument(int[] source) { return invocation -> { int[] into = invocation.getArgument(0); System.arraycopy(source, 0, into, 0, source.length); return into; }; } } @Nested @DisplayName("FlexboxLayoutManager") class FlexboxLayoutManagerTest { @Test void findFirstVisibleItemPosition() { FlexboxLayoutManager layoutManager = mock(FlexboxLayoutManager.class); when(layoutManager.findFirstVisibleItemPosition()).thenReturn(42); int result = visiblePositionFinder.findFirstVisibleItemPosition(layoutManager); assertEquals(42, result); } @Test void findLastVisibleItemPosition() { FlexboxLayoutManager layoutManager = mock(FlexboxLayoutManager.class); when(layoutManager.findLastVisibleItemPosition()).thenReturn(42); int result = visiblePositionFinder.findLastVisibleItemPosition(layoutManager); assertEquals(42, result); } } } class MockLayoutManager extends RecyclerView.LayoutManager { @Override public RecyclerView.LayoutParams generateDefaultLayoutParams() { return null; } } 0 /******************************************************************************* * Copyright (c) 2020 Eclipse RDF4J contributors. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.rio.hdt; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.commons.io.input.CountingInputStream; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.RDFHandlerException; import org.eclipse.rdf4j.rio.RDFParseException; import org.eclipse.rdf4j.rio.RioSetting; import org.eclipse.rdf4j.rio.helpers.AbstractRDFParser; /** * RDF parser for HDT v1.0 files. This parser is not thread-safe, therefore its public methods are synchronized. * * Unfortunately the draft specification is not entirely clear and probably slightly out of date, since the open source * reference implementation HDT-It seems to implement a slightly different version. This parser tries to be compatible * with HDT-It 1.0. * * The most important parts are the Dictionaries containing the actual values (S, P, O part of a triple), and the * Triples containing the numeric references to construct the triples. * * Since objects in one triple are often subjects in another triple, these "shared" parts are stored in a shared * Dictionary, which may significantly reduce the file size. * * File structure: * *

 * +---------------------+
 * | Global              |
 * | Header              |
 * | Dictionary (Shared) |
 * | Dictionary (S)      |
 * | Dictionary (P)      |
 * | Dictionary (O)      |    
 * | Triples             |
 * +---------------------+
 * 
* * @author * * @see HDT draft (2015) * @see W3C Member Submission (2011) */ public class HDTParser extends AbstractRDFParser { /** * Creates a new HDTParser that will use a {@link SimpleValueFactory} to create RDF model objects. */ public HDTParser() { super(); } /** * Creates a new HDTParser that will use the supplied ValueFactory to create RDF model objects. * * @param valueFactory A ValueFactory. */ public HDTParser(ValueFactory valueFactory) { super(valueFactory); } @Override public RDFFormat getRDFFormat() { return RDFFormat.HDT; } @Override public Collection> getSupportedSettings() { Set> result = new HashSet<>(); return result; } /** * Implementation of the parse(InputStream, String) method defined in the RDFParser interface. * * @param in The InputStream from which to read the data, must not be null. * @param baseURI The URI associated with the data in the InputStream, must not be null. * @throws IOException If an I/O error occurred while data was read from the InputStream. * @throws RDFParseException If the parser has found an unrecoverable parse error. * @throws RDFHandlerException If the configured statement handler encountered an unrecoverable error. * @throws IllegalArgumentException If the supplied input stream or base URI is null. */ @Override public synchronized void parse(InputStream in, String baseURI) throws IOException, RDFParseException, RDFHandlerException { if (in == null) { throw new IllegalArgumentException("Input stream must not be 'null'"); } if (in instanceof FileInputStream) { // "TODO: use more optimized way to parse the file, eg. filechannel / membuffer" } HDTDictionarySection shared = null; HDTDictionarySection subjects = null; HDTDictionarySection predicates = null; HDTDictionarySection objects = null; HDTTriplesSection section = null; // not using try-with-resources, since the counter is needed in the catch clause (JDK8) CountingInputStream bis = new CountingInputStream(in); try { reportLocation(0, -1); HDTGlobal global = new HDTGlobal(); global.parse(bis); Map globalProps = global.getProperties(); String base = globalProps.getOrDefault(HDTGlobal.GLOBAL_BASEURI, ""); if (!base.isEmpty()) { setBaseURI(base); } reportLocation(bis.getByteCount(), -1); HDTHeader header = new HDTHeader(); header.parse(bis); reportLocation(bis.getByteCount(), -1); new HDTDictionary().parse(bis); long dpos = bis.getByteCount(); reportLocation(dpos, -1); shared = HDTDictionarySectionFactory.parse(bis, "S+O", dpos); shared.parse(bis); dpos = bis.getByteCount(); reportLocation(dpos, -1); subjects = HDTDictionarySectionFactory.parse(bis, "S", dpos); subjects.parse(bis); dpos = bis.getByteCount(); reportLocation(dpos, -1); predicates = HDTDictionarySectionFactory.parse(bis, "P", dpos); predicates.parse(bis); dpos = bis.getByteCount(); reportLocation(dpos, -1); objects = HDTDictionarySectionFactory.parse(bis, "O", dpos); objects.parse(bis); reportLocation(bis.getByteCount(), -1); HDTTriples triples = new HDTTriples(); triples.parse(bis); reportLocation(bis.getByteCount(), -1); section = HDTTriplesSectionFactory.parse(new String(HDTTriples.FORMAT_BITMAP)); section.parse(bis, triples.getOrder()); } catch (IOException ioe) { reportFatalError(ioe.getMessage(), bis.getCount(), -1); } finally { bis.close(); } if (rdfHandler != null) { rdfHandler.startRDF(); } int cnt = 0; int size = shared.size(); while (section.hasNext()) { int[] t = section.next(); byte[] s = getSO(t[0], size, shared, subjects); byte[] p = predicates.get(t[1]); byte[] o = getSO(t[2], size, shared, objects); Statement stmt = valueFactory.createStatement(createSubject(s), createPredicate(p), createObject(o)); if (rdfHandler != null) { rdfHandler.handleStatement(stmt); } } if (rdfHandler != null) { rdfHandler.endRDF(); } } /** * Not supported, since HDT is a binary format. */ @Override public synchronized void parse(Reader reader, String baseURI) throws IOException, RDFParseException, RDFHandlerException { throw new UnsupportedOperationException("HDT is binary, text readers not supported."); } /** * Get part of triple from shared HDT Dictionary or (if not found) from specific HDT Dictionary * * @param pos position * @param size size of shared Dictionary * @param shared shared Dictionary * @param other specific Dictionary * @return subject or object */ private byte[] getSO(int pos, int size, HDTDictionarySection shared, HDTDictionarySection other) throws IOException { return (pos <= size) ? shared.get(pos) : other.get(pos - size); } private boolean isBNodeID(byte[] b) { // HDT-It generates "genid" for blank nodes in RDF/XML return (b[0] == '_' || (b.length > 5 && b[0] == 'g' && b[1] == 'e')); } /** * Create subject IRI or blank node * * @param b byte buffer * @return IRI or blank node */ private Resource createSubject(byte[] b) { String str = new String(b, StandardCharsets.UTF_8); return isBNodeID(b) ? valueFactory.createBNode(str) : valueFactory.createIRI(str); } /** * Create predicate IRI * * @param b byte buffer * @return IRI */ private IRI createPredicate(byte[] b) { return valueFactory.createIRI(new String(b, StandardCharsets.UTF_8)); } /** * Create object (typed) literal, IRI or blank node * * @param b byte buffer * @return literal, IRI or blank node */ private Value createObject(byte[] b) { if (b[0] == '"') { int i = b.length - 1; for (; i > 1 && b[i] != '"'; i--) { if (b[i] == '@') { String lang = new String(b, i + 1, b.length - i - 1, StandardCharsets.US_ASCII); return valueFactory.createLiteral(new String(b, 1, i - 2, StandardCharsets.UTF_8), lang); } else if (b[i] == '^') { IRI datatype = valueFactory .createIRI(new String(b, i + 2, b.length - i - 3, StandardCharsets.US_ASCII)); return valueFactory.createLiteral(new String(b, 1, i - 3, StandardCharsets.UTF_8), datatype); } } return valueFactory.createLiteral(new String(b, 1, i - 1, StandardCharsets.UTF_8)); } String str = new String(b, StandardCharsets.UTF_8); return isBNodeID(b) ? valueFactory.createBNode(str) : valueFactory.createIRI(str); } } /* * =========================================== * Java Pdf Extraction Decoding Access Library * =========================================== * * Project Info: http://www.idrsolutions.com * Help section for developers at http://www.idrsolutions.com/support/ * * (C) Copyright 1997-2015 IDRsolutions and Contributors. * * This file is part of JPedal/JPDF2HTML5 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * --------------- * FunctionContext.java * --------------- */ package com.idrsolutions.pdf.color.shading; import java.awt.Color; import java.awt.PaintContext; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.Raster; import java.awt.image.WritableRaster; import org.jpedal.color.GenericColorSpace; import org.jpedal.function.PDFFunction; import org.jpedal.parser.DecoderOptions; public class FunctionContext implements PaintContext { final GenericColorSpace shadingColorSpace; private float scaling=1f; private final PDFFunction[] function; //private FunctionContext(){} private final int pageHeight; private final boolean colorsReversed; private int xstart,ystart; //private float[] domain; FunctionContext(final int pHeight, final float scaling, final GenericColorSpace shadingColorSpace, final boolean colorsReversed, final PDFFunction[] function){ this.colorsReversed=colorsReversed; this.pageHeight=pHeight; //this.domain=domain; this.shadingColorSpace=shadingColorSpace; this.function = function; this.scaling=scaling; } @Override public void dispose() {} @Override public ColorModel getColorModel() { return ColorModel.getRGBdefault(); } /** * setup the raster with the colors * */ @Override public Raster getRaster(final int xstart, final int ystart, final int w, final int h) { this.xstart=xstart; this.ystart=ystart; //sets up the array of pixel values //WritableRaster raster =getColorModel().createCompatibleWritableRaster(w, h); //create buffer to hold all this data final int[] data = new int[w * h * 4]; //workout color range Color c; //set current calues to default int cr,cg,cb; //y co-ordinates for (int y = 0; y < h; y++) { //x co-ordinates for (int x = 0; x < w; x++) { c= calculateColor(x,y); /** * workout values */ if(colorsReversed){ cr=255-c.getRed(); cg=255-c.getGreen(); cb=255-c.getBlue(); }else{ cr=c.getRed(); cg=c.getGreen(); cb=c.getBlue(); } //set color for the pixel with values final int base = (y * w + x) * 4; data[base] = cr; data[base + 1] = cg; data[base + 2] = cb; data[base + 3] = 255;//(int)(col.getAlpha()); } } //set values final WritableRaster raster = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB).getRaster(); raster.setPixels(0, 0, w, h, data); return raster; } /**workout rgb color*/ private Color calculateColor(final float x, final float y) { final float cx; final float cy; /** *take x and y and pass through conversion with domain values - this gives us xx */ //hack for MAC which is f**king broken if(DecoderOptions.isRunningOnMac){ cx=scaling*(x+xstart); cy=scaling*(y+ystart); }else{ cx=scaling*(x+xstart); cy=scaling*(pageHeight-(y+ystart)); } final float[] values={cx,cy}; final float[] colValues = ShadingFactory.applyFunctions(function,values); /** * this value is converted to a color */ final int count=colValues.length; shadingColorSpace.setColor(colValues,count); return (Color) shadingColorSpace.getColor(); } } import java.util.HashSet; import java.util.Arrays; class Duplicate_Integer_in_array{ // Problem link // https://leetcode.com/problems/find-the-duplicate-number/ public int Approach1(int[] nums,int n){ // Approach 1 is brute force which uses O(1) space and O(N^2) access to memory for(int i=0;i hs=new HashSet<>(); for(int i:nums){ if(hs.contains(i)) return i; hs.add(i); } return -1; } public int Approach3(int[] nums,int n){ // This method requires O(nlogn) time to sort and O(n) time to find the duplicate element Arrays.sort(nums); for(int i=0;i { PlayerInventory inv = it.getInventory(); inv.clear(); inv.setItemInMainHand(is); it.updateInventory(); }); } abstract public void init(); abstract public void clear(); abstract public void sendIntroduction(); abstract public void teleport(); public static String getIntroduction(String line1, String line2) { return "\n§b§m §r §a[§e游戏介绍§a] §b§m \n§a " + line1 + "\n§b " + line2 + "\n§b§m §r\n"; } public void onKnockout(final Player player) { } } package com.dogbuddy.android.code.test.dogsapp.addeditdog; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.FragmentActivity; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.dogbuddy.android.code.test.dogsapp.R; import com.dogbuddy.android.code.test.dogsapp.ViewModelFactory; import com.dogbuddy.android.code.test.dogsapp.util.ActivityUtils; /** * Displays an add or edit dog screen. */ public class AddEditDogActivity extends AppCompatActivity implements AddEditDogNavigator { public static final int REQUEST_CODE = 1; public static final int ADD_EDIT_RESULT_OK = RESULT_FIRST_USER + 1; @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override public void onDogSaved() { setResult(ADD_EDIT_RESULT_OK); finish(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.adddog_act); // Set up the toolbar. Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowHomeEnabled(true); AddEditDogFragment addEditDogFragment = obtainViewFragment(); ActivityUtils.replaceFragmentInActivity(getSupportFragmentManager(), addEditDogFragment, R.id.contentFrame); subscribeToNavigationChanges(); } private void subscribeToNavigationChanges() { AddEditDogViewModel viewModel = obtainViewModel(this); // The activity observes the navigation events in the ViewModel viewModel.getDogUpdatedEvent().observe(this, new Observer() { @Override public void onChanged(@Nullable Void v) { AddEditDogActivity.this.onDogSaved(); } }); } public static AddEditDogViewModel obtainViewModel(FragmentActivity activity) { // Use a Factory to inject dependencies into the ViewModel ViewModelFactory factory = ViewModelFactory.getInstance(activity.getApplication()); return ViewModelProviders.of(activity, factory).get(AddEditDogViewModel.class); } @NonNull private AddEditDogFragment obtainViewFragment() { // View Fragment AddEditDogFragment addEditDogFragment = (AddEditDogFragment) getSupportFragmentManager() .findFragmentById(R.id.contentFrame); if (addEditDogFragment == null) { addEditDogFragment = AddEditDogFragment.newInstance(); // Send the dog ID to the fragment Bundle bundle = new Bundle(); bundle.putString(AddEditDogFragment.ARGUMENT_EDIT_DOG_ID, getIntent().getStringExtra(AddEditDogFragment.ARGUMENT_EDIT_DOG_ID)); addEditDogFragment.setArguments(bundle); } return addEditDogFragment; } } /* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.server.media; import android.annotation.IntDef; import android.annotation.NonNull; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ComponentInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.pm.ServiceInfo; import android.os.Handler; import android.os.UserHandle; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.List; /** * Holds the media button receiver, and also provides helper methods around it. */ final class MediaButtonReceiverHolder { public static final int COMPONENT_TYPE_INVALID = 0; public static final int COMPONENT_TYPE_BROADCAST = 1; public static final int COMPONENT_TYPE_ACTIVITY = 2; public static final int COMPONENT_TYPE_SERVICE = 3; @IntDef(value = { COMPONENT_TYPE_INVALID, COMPONENT_TYPE_BROADCAST, COMPONENT_TYPE_ACTIVITY, COMPONENT_TYPE_SERVICE, }) @Retention(RetentionPolicy.SOURCE) public @interface ComponentType {} private static final String TAG = "PendingIntentHolder"; private static final boolean DEBUG_KEY_EVENT = MediaSessionService.DEBUG_KEY_EVENT; private static final String COMPONENT_NAME_USER_ID_DELIM = ","; private final int mUserId; private final PendingIntent mPendingIntent; private final ComponentName mComponentName; private final String mPackageName; @ComponentType private final int mComponentType; /** * Unflatten from string which is previously flattened string via flattenToString(). *

* It's used to store and restore media button receiver across the boot, by keeping the intent's * component name to the persistent storage. * * @param mediaButtonReceiverInfo previously flattened string via flattenToString() * @return new instance if the string was valid. {@code null} otherwise. */ public static MediaButtonReceiverHolder unflattenFromString( Context context, String mediaButtonReceiverInfo) { if (TextUtils.isEmpty(mediaButtonReceiverInfo)) { return null; } String[] tokens = mediaButtonReceiverInfo.split(COMPONENT_NAME_USER_ID_DELIM); if (tokens == null || (tokens.length != 2 && tokens.length != 3)) { return null; } ComponentName componentName = ComponentName.unflattenFromString(tokens[0]); if (componentName == null) { return null; } int userId = Integer.parseInt(tokens[1]); // Guess component type if the OS version is updated from the older version. int componentType = (tokens.length == 3) ? Integer.parseInt(tokens[2]) : getComponentType(context, componentName); return new MediaButtonReceiverHolder(userId, null, componentName, componentType); } /** * Creates a new instance. * * @param context context * @param userId userId * @param pendingIntent pending intent * @return Can be {@code null} if pending intent was null. */ public static MediaButtonReceiverHolder create(Context context, int userId, PendingIntent pendingIntent) { if (pendingIntent == null) { return null; } ComponentName componentName = (pendingIntent != null && pendingIntent.getIntent() != null) ? pendingIntent.getIntent().getComponent() : null; if (componentName != null) { // Explicit intent, where component name is in the PendingIntent. return new MediaButtonReceiverHolder(userId, pendingIntent, componentName, getComponentType(context, componentName)); } // Implicit intent, where component name isn't in the PendingIntent. Try resolve. PackageManager pm = context.getPackageManager(); Intent intent = pendingIntent.getIntent(); if ((componentName = resolveImplicitServiceIntent(pm, intent)) != null) { return new MediaButtonReceiverHolder( userId, pendingIntent, componentName, COMPONENT_TYPE_SERVICE); } else if ((componentName = resolveManifestDeclaredBroadcastReceiverIntent(pm, intent)) != null) { return new MediaButtonReceiverHolder( userId, pendingIntent, componentName, COMPONENT_TYPE_BROADCAST); } else if ((componentName = resolveImplicitActivityIntent(pm, intent)) != null) { return new MediaButtonReceiverHolder( userId, pendingIntent, componentName, COMPONENT_TYPE_ACTIVITY); } // Failed to resolve target component for the pending intent. It's unlikely to be usable. // However, the pending intent would be still used, just to follow the legacy behavior. Log.w(TAG, "Unresolvable implicit intent is set, pi=" + pendingIntent); String packageName = (pendingIntent != null && pendingIntent.getIntent() != null) ? pendingIntent.getIntent().getPackage() : null; return new MediaButtonReceiverHolder(userId, pendingIntent, packageName != null ? packageName : ""); } private MediaButtonReceiverHolder(int userId, PendingIntent pendingIntent, ComponentName componentName, @ComponentType int componentType) { mUserId = userId; mPendingIntent = pendingIntent; mComponentName = componentName; mPackageName = componentName.getPackageName(); mComponentType = componentType; } private MediaButtonReceiverHolder(int userId, PendingIntent pendingIntent, String packageName) { mUserId = userId; mPendingIntent = pendingIntent; mComponentName = null; mPackageName = packageName; mComponentType = COMPONENT_TYPE_INVALID; } /** * @return the user id */ public int getUserId() { return mUserId; } /** * @return package name that the media button receiver would be sent to. */ @NonNull public String getPackageName() { return mPackageName; } /** * Sends the media key event to the media button receiver. *

* This prioritizes using use pending intent for sending media key event. * * @param context context to be used to call PendingIntent#send * @param keyEvent keyEvent to send * @param resultCode result code to be used to call PendingIntent#send * Ignored if there's no valid pending intent. * @param onFinishedListener callback to be used to get result of PendingIntent#send. * Ignored if there's no valid pending intent. * @param handler handler to be used to call onFinishedListener * Ignored if there's no valid pending intent. * @see PendingIntent#send(Context, int, Intent, PendingIntent.OnFinished, Handler) */ public boolean send(Context context, KeyEvent keyEvent, String callingPackageName, int resultCode, PendingIntent.OnFinished onFinishedListener, Handler handler) { Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); mediaButtonIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent); // TODO: Find a way to also send PID/UID in secure way. mediaButtonIntent.putExtra(Intent.EXTRA_PACKAGE_NAME, callingPackageName); if (mPendingIntent != null) { if (DEBUG_KEY_EVENT) { Log.d(TAG, "Sending " + keyEvent + " to the last known PendingIntent " + mPendingIntent); } try { mPendingIntent.send( context, resultCode, mediaButtonIntent, onFinishedListener, handler); } catch (PendingIntent.CanceledException e) { Log.w(TAG, "Error sending key event to media button receiver " + mPendingIntent, e); return false; } } else if (mComponentName != null) { if (DEBUG_KEY_EVENT) { Log.d(TAG, "Sending " + keyEvent + " to the restored intent " + mComponentName + ", type=" + mComponentType); } mediaButtonIntent.setComponent(mComponentName); UserHandle userHandle = UserHandle.of(mUserId); try { switch (mComponentType) { case COMPONENT_TYPE_ACTIVITY: context.startActivityAsUser(mediaButtonIntent, userHandle); break; case COMPONENT_TYPE_SERVICE: context.startForegroundServiceAsUser(mediaButtonIntent, userHandle); break; default: // Legacy behavior for other cases. context.sendBroadcastAsUser(mediaButtonIntent, userHandle); } } catch (Exception e) { Log.w(TAG, "Error sending media button to the restored intent " + mComponentName + ", type=" + mComponentType, e); return false; } } else { // Leave log, just in case. Log.e(TAG, "Shouldn't be happen -- pending intent or component name must be set"); return false; } return true; } @Override public String toString() { if (mPendingIntent != null) { return "MBR {pi=" + mPendingIntent + ", type=" + mComponentType + "}"; } return "Restored MBR {component=" + mComponentName + ", type=" + mComponentType + "}"; } /** * @return flattened string. Can be empty string if the MBR is created with implicit intent. */ public String flattenToString() { if (mComponentName == null) { // We don't know which component would receive the key event. return ""; } return String.join(COMPONENT_NAME_USER_ID_DELIM, mComponentName.toString(), String.valueOf(mUserId), String.valueOf(mComponentType)); } /** * Gets the type of the component * * @param context context * @param componentName component name * @return A component type */ @ComponentType private static int getComponentType(Context context, ComponentName componentName) { if (componentName == null) { return COMPONENT_TYPE_INVALID; } PackageManager pm = context.getPackageManager(); try { ActivityInfo activityInfo = pm.getActivityInfo(componentName, PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE | PackageManager.GET_ACTIVITIES); if (activityInfo != null) { return COMPONENT_TYPE_ACTIVITY; } } catch (PackageManager.NameNotFoundException e) { } try { ServiceInfo serviceInfo = pm.getServiceInfo(componentName, PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE | PackageManager.GET_SERVICES); if (serviceInfo != null) { return COMPONENT_TYPE_SERVICE; } } catch (PackageManager.NameNotFoundException e) { } // Pick legacy behavior for BroadcastReceiver or unknown. return COMPONENT_TYPE_BROADCAST; } private static ComponentName resolveImplicitServiceIntent(PackageManager pm, Intent intent) { // Flag explanations. // - MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE: // filter apps regardless of the phone's locked/unlocked state. // - GET_SERVICES: Return service return createComponentName(pm.resolveService(intent, PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE | PackageManager.GET_SERVICES)); } private static ComponentName resolveManifestDeclaredBroadcastReceiverIntent( PackageManager pm, Intent intent) { // Flag explanations. // - MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE: // filter apps regardless of the phone's locked/unlocked state. List resolveInfos = pm.queryBroadcastReceivers(intent, PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE); return (resolveInfos != null && !resolveInfos.isEmpty()) ? createComponentName(resolveInfos.get(0)) : null; } private static ComponentName resolveImplicitActivityIntent(PackageManager pm, Intent intent) { // Flag explanations. // - MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE: // Filter apps regardless of the phone's locked/unlocked state. // - MATCH_DEFAULT_ONLY: // Implicit intent receiver should be set as default. Only needed for activity. // - GET_ACTIVITIES: Return activity return createComponentName(pm.resolveActivity(intent, PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE | PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_ACTIVITIES)); } private static ComponentName createComponentName(ResolveInfo resolveInfo) { if (resolveInfo == null) { return null; } ComponentInfo componentInfo; // Code borrowed from ResolveInfo#getComponentInfo(). if (resolveInfo.activityInfo != null) { componentInfo = resolveInfo.activityInfo; } else if (resolveInfo.serviceInfo != null) { componentInfo = resolveInfo.serviceInfo; } else { // We're not interested in content provider. return null; } // Code borrowed from ComponentInfo#getComponentName(). try { return new ComponentName(componentInfo.packageName, componentInfo.name); } catch (IllegalArgumentException | NullPointerException e) { // This may be happen if resolveActivity() end up with matching multiple activities. // see PackageManager#resolveActivity(). return null; } } } package net.zekjur.davsync; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.util.Log; public class NewMediaReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d("davsync", "received pic or video intent"); boolean isNewPic = android.hardware.Camera.ACTION_NEW_PICTURE.equals(intent.getAction()); boolean isNewVid = android.hardware.Camera.ACTION_NEW_VIDEO.equals(intent.getAction()); if (!isNewPic && !isNewVid) return; SharedPreferences preferences = context.getSharedPreferences("net.zekjur.davsync_preferences", Context.MODE_PRIVATE); if (isNewPic && !preferences.getBoolean("auto_sync_camera_pictures", true)) { Log.d("davsync", "automatic camera picture sync is disabled, ignoring"); return; } if (isNewVid && !preferences.getBoolean("auto_sync_camera_videos", true)) { Log.d("davsync", "automatic camera video sync is disabled, ignoring"); return; } boolean syncOnWifiOnly = preferences.getBoolean("auto_sync_on_wifi_only", true); Log.d("davsync", "New picture was taken"); Uri uri = intent.getData(); Log.d("davsync", "picture uri = " + uri); ConnectivityManager cs = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cs.getActiveNetworkInfo(); if (info == null) { return; } // If we have WIFI connectivity, upload immediately boolean isWifi = info.isConnected() && (ConnectivityManager.TYPE_WIFI == info.getType()); if (!syncOnWifiOnly || isWifi) { Log.d("davsync", "Trying to upload " + uri + " immediately (on WIFI)"); Intent ulIntent = new Intent(context, UploadService.class); ulIntent.putExtra(Intent.EXTRA_STREAM, uri); context.startService(ulIntent); } else { Log.d("davsync", "Queueing " + uri + "for later (not on WIFI)"); // otherwise, queue the image for later DavSyncOpenHelper helper = new DavSyncOpenHelper(context); helper.queueUri(uri); } } } package com.baidu.mapapi.map; import android.view.View; import android.view.View.OnClickListener; import com.baidu.platform.comapi.map.D; import com.baidu.platform.comapi.map.e; import com.baidu.platform.comapi.map.i; import com.growingio.android.sdk.agent.VdsAgent; import com.growingio.android.sdk.instrumentation.Instrumented; class k implements View.OnClickListener { k(MapView paramMapView) {} @Instrumented public void onClick(View paramView) { VdsAgent.onClick(this, paramView); paramView = MapView.a(this.a).a().D(); paramView.a += 1.0F; MapView.a(this.a).a().a(paramView, 300); } } /* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/com/baidu/mapapi/map/k.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */package com.comcast.video.dawg.common.security; import org.testng.Assert; import org.testng.annotations.Test; import com.comcast.video.dawg.common.security.jwt.DawgJwtEncoder; import com.comcast.video.dawg.common.security.jwt.DawgCreds; import com.google.common.collect.Sets; import io.jsonwebtoken.SignatureException; public class JwtTest { @Test public void testJwtEncodeAndDecode() { DawgJwtEncoder helper = new DawgJwtEncoder("14C549805A5911368929D139C5C6282E66CE017F8E861C4EAC4D2975269BEA6F"); DawgCreds dawgUser = new DawgCreds("kpears201", "pw", Sets.newHashSet("admin", "house"), Sets.newHashSet("id1")); String jwt = helper.createUserJWT(dawgUser); DawgCreds decoded = helper.decodeJwt(jwt).getCreds(); Assert.assertEquals(decoded.getUserName(), "kpears201"); Assert.assertEquals(decoded.getRoles(), Sets.newHashSet("admin", "house")); Assert.assertEquals(decoded.getDeviceIds(), Sets.newHashSet("id1")); } @Test(expectedExceptions=SignatureException.class) public void testJwtEncodeAndDecodeWithBadKey() { DawgJwtEncoder helper = new DawgJwtEncoder("14C549805A5911368929D139C5C6282E66CE017F8E861C4EAC4D2975269BEA6F"); DawgCreds dawgJwt = new DawgCreds("kpears201", "pw", Sets.newHashSet("admin", "house"), Sets.newHashSet("id1")); String jwt = helper.createUserJWT(dawgJwt); helper = new DawgJwtEncoder("14C549805A5911368929D139C5C6282E66CE017F8E861C4EAC4D2975269BEA60"); helper.decodeJwt(jwt); } } j1046697411/AndroidCommonFramework package org.jzl.android.recyclerview.v3.model; import androidx.annotation.IdRes; public interface IExtractable { E getExtra(@IdRes int key); E getExtra(@IdRes int key, E defValue); void putExtra(@IdRes int key, Object value); boolean hasExtra(@IdRes int key); void removeExtra(@IdRes int key); } package io.payworks.labs.tcpmocker.support; import io.payworks.labs.tcpmocker.TcpServer; import io.payworks.labs.tcpmocker.TcpServerBuilder; import io.payworks.labs.tcpmocker.datahandler.DataHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import static java.util.stream.Collectors.joining; public final class TcpServerFactory { private static final Logger logger = LoggerFactory.getLogger(TcpServerFactory.class); private final TcpServerBuilder serverBuilder; private final DataHandlersLoader dataHandlersLoader; public TcpServerFactory(final TcpServerBuilder serverBuilder, final DataHandlersLoader dataHandlersLoader) { this.serverBuilder = serverBuilder; this.dataHandlersLoader = dataHandlersLoader; } public TcpServer createTcpServer(final int port) { final Map dataHandlersMap = dataHandlersLoader.dataHandlers(); final String dataHandlersList = dataHandlersMap.keySet() .stream() .map(key -> String.format("\t- %s", key)) .collect(joining("\n")); if (dataHandlersMap.isEmpty()) { logger.warn("No Data Handlers!"); } else { logger.info("Data Handlers ({}):\n{}", dataHandlersMap.size(), dataHandlersList); } serverBuilder.withDataHandlers(dataHandlersMap.values()); serverBuilder.withPort(port); final TcpServer server = serverBuilder.build(); logger.info("Server Started (:{})", server.getPort()); return server; } } imperial-qore/jline package StochLib; import java.io.Serializable; import java.util.List; public class StatelessClassSwitcher extends ClassSwitcher implements Serializable { public StatelessClassSwitcher(List jobClasses, Object csMatrix) { super(jobClasses, "StochLib.StatelessClassSwitcher"); } } src/GameData.java /****************************************** * * CS 170-02 * Final Project: An alphabet learning game * for pre-school or first grade kids. ******************************************/ /** * This class accesses the file AlphabetGameData.txt * to process new and existing saved scores. */ import java.awt.Color; import java.awt.Font; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class GameData { private File dataFile; private Map transcript; /** * No-arg constructor. Calls method to read * in player data from the file AlphabetGameData.txt. */ public GameData() throws IOException { // This path may not be right if this isn't run from Eclipse. dataFile = new File("./docs/AlphabetGameData.txt"); // Create TreeMap to hold read-in data. transcript = new TreeMap(); readData(); } /** * Method to read in saved data from the file AlphabetGameData.txt. */ private void readData() throws IOException { String userName, levelStr, scoreStr; int level, score; PlayerRecord tmpRecord; // If the file already exists, read in the contents. if(dataFile.exists() && dataFile.isFile()) { BufferedReader in = new BufferedReader(new FileReader(dataFile)); String line = in.readLine(); while(line != null) { StringTokenizer token = new StringTokenizer(line, "\t"); userName = token.nextToken(); levelStr = token.nextToken(); scoreStr = token.nextToken(); level = Integer.parseInt(levelStr); score = Integer.parseInt(scoreStr); tmpRecord = new PlayerRecord(userName, level, score); transcript.put(userName, tmpRecord); line = in.readLine(); } in.close(); } else { // Create a new file for the student. dataFile.createNewFile(); } } /** * Method to check for duplicate user names. */ public boolean processDuplicate(String name) { boolean duplicate = false; if(transcript.containsKey(name)) { duplicate = true; } return(duplicate); } /** * Method to show a dialog box confirming that player * data was successfully saved. */ public void showRecord(PlayerRecord record) { JLabel msg = new JLabel("The following record has been saved:
" + "Player name: " + record.getUserName() + "
" + "Level: " + record.getLevel() + "
" + "Score: " + record.getScore() + ""); msg.setFont(new Font(msg.getFont().getFontName(), Font.PLAIN, 18)); JOptionPane.showMessageDialog(null,msg,"Record Saved",-1); } /** * Method to update the score of a player already * whose data is alreayd being saved. */ public void updateRecord(String name, int newLevel, int newScore) throws IOException { // Theoretically, the user name "name" will already exist in transcript when // this method is called, but in case it doesn't, silently create a new // record for the player. if(transcript.containsKey(name)) { transcript.get(name).setLevel(newLevel); transcript.get(name).setScore(newScore); resaveTranscript(); showRecord(transcript.get(name)); } else { addRecordCorrection(name, newLevel, newScore); showRecord(transcript.get(name)); } } /** * Method to add a record for a player who should exist * in the data file already, but isn't in there for some * reason. */ public void addRecordCorrection(String name, int level, int score) throws IOException { // This function is specifically for handling problems with finding players // that *should* already exist in the file. // Create the record. PlayerRecord newPlayer = new PlayerRecord(name, level, score); // Add the record to the transcript. transcript.put(name, newPlayer); // Update the transcript file. // Run resaveTranscript() in order to re-sort the file // after a new record has been added. resaveTranscript(); } /** * Method to add a new player to the data file. */ public String addRecord(int level, int score) throws IOException { String userInput = ""; String msg = "Please enter a user name:"; boolean isDuplicate; boolean ok = false; while(!ok) { userInput = getName(msg); if(userInput == "") { // The dialog box was cancelled; do nothing and exit. ok = true; } else { // If this record is a duplicate, show message and get new name. isDuplicate = processDuplicate(userInput); // Otherwise, add the record to transcript. if(!isDuplicate) { // Create the record. PlayerRecord newPlayer = new PlayerRecord(userInput, level, score); // Add the record to the transcript. transcript.put(userInput, newPlayer); // Update the transcript file. // Run resaveTranscript() in order to re-sort the file // after a new record has been added. //addToTranscript(newCourse); resaveTranscript(); showRecord(transcript.get(userInput)); ok = true; } else { msg = "That user name has been taken. Please enter a new name:"; } } } return(userInput); } /** * Method to re-save the data file after a change has * been made to the transcript TreeMap. */ public void resaveTranscript() throws IOException { // Double check that the data file exists. if(dataFile.exists() && dataFile.isFile()) { // Create a temporary text file. File tmpFile = new File("./docs/GameData_tmp.txt"); tmpFile.createNewFile(); // Open connection to the temporary file. PrintWriter out = new PrintWriter(new FileWriter(tmpFile)); // Add in each course. for(PlayerRecord record: transcript.values()) { out.println(record.getUserName() + "\t" + record.getLevel() + "\t" + record.getScore()); } // Close connection to the temporary file. out.close(); // Delete the current data file. dataFile.delete(); // Rename the temporary file. tmpFile.renameTo(dataFile); } else { throw new IOException(); } } /** * Method to show a dialog box showing all saved player * scores. */ public void viewScores() { // Define transcriptCopySorted as a sorted TreeMap. Map transcriptSorted = new TreeMap(new ValueComparator(transcript)); for(PlayerRecord record: transcript.values()) { transcriptSorted.put(record.getUserName(), record); } Collection records = transcript.values(); // "\n %-20s\t%-10s\t%-10s String output = String.format("\n %-20s %-10s %-10s", "Player", "Level", "Score"); for(PlayerRecord r : records) { output += String.format("\n %-20s %-10d %-10d", r.getUserName(), r.getLevel(), r.getScore()); } JTextArea textArea = new JTextArea(output, 23, 60); textArea.setEditable(false); textArea.setOpaque(true); textArea.setTabSize(8); Font font = new Font("Courier", Font.PLAIN, 16); textArea.setFont(font); Color color = Color.WHITE; textArea.setBackground(color); // Include a scrollpane. JScrollPane scrollPane = new JScrollPane(textArea); JOptionPane.showMessageDialog(null,scrollPane,"Scores",-1); } /** * Method to sort player data by score. */ private class ValueComparator implements Comparator { private Map map; public ValueComparator(Map map) { this.map = map; } public int compare(Object keyA, Object keyB) { double valueA = map.get(keyA).getScore(); double valueB = map.get(keyB).getScore(); int result = 0; if(valueA < valueB) { result = -1; } else if(valueA > valueB) { result = 1; } else { result = 0; // the scores are the same // Default to sorting by user name. There can't be ties // in user names because the user name is also the key in the // TreeMap. String strvalueA = (String) keyA; //map.get(keyA).getUserName(); String strvalueB = (String) keyB; //map.get(keyB).getUserName(); result = strvalueA.compareTo(strvalueB); } return result; } } /** * Method to retrieve and validate player name. */ // Method to retrieve and validate a course title. private String getName(String message) { JTextField Jtitle; String title = ""; int option; boolean isValid = false; while(!isValid) { try { Jtitle = new JTextField(); Object[] prompt = { null, message, Jtitle }; option = JOptionPane.showConfirmDialog(null, prompt, "User Name", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if(option == JOptionPane.OK_OPTION) { title = Jtitle.getText(); // Title should contain at least one letter, an underscore, and // at least one digit. if(title == null) { throw new Exception("Error: Please enter a user name."); } title = title.trim(); if(title.equals("")) { throw new Exception("Error: Please enter a user name."); } isValid = true; } else { title = ""; // signal to cancel dialog box return title; } } catch(Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "User Name",JOptionPane.ERROR_MESSAGE); } } return title; } } /** * This class is a child class of the Account class. It represents all the Checking bank account * @author , */ package application; public class Checking extends Account { private boolean directDeposit; /** * The constructor calls the super constructor to intialize the account holder, balance, and * dateOpen fields * @param holder - the profile object that represents a person opening an account * @param balance - the amount that the person initially deposits into the bank * @param dateOpen - the date when the account is being opened */ public Checking(Profile holder, double balance, Date dateOpen) { super(holder, balance, dateOpen); } /** * Checks if direct deposit has been setup for this account * @return true if direct deposit is setup, false otherwise */ public boolean isDirectDeposit() { return directDeposit; } /** * Sets the direct deposit to the passed value * @param directDeposit - whether or not the direct deposit should be setup for this account */ public void setDirectDeposit(boolean directDeposit) { this.directDeposit = directDeposit; } @Override /** * Calculates the monthly interest rate for this account type * @return - the amount of interest for this account type */ public double monthlyInterest() { double interest = 0.0005/12; return interest; } @Override /** * Calculates the monthly fee that the account holder needs to pay for this account * @return - the amount that the account holder needs to pay */ public double monthlyFee() { double fee = 0; if(super.getBalance() < 1500) { if(!directDeposit) { fee = 25; } else { fee = 0; } } return fee; } @Override /** * Checks if the account in the argument is the same as this account, that is * the same person holds both the account and the account are of same type * @param account - the account that needs to be compared with this account * @return - true if the accounts are same, false otherwise */ public boolean equals(Account account) { if((account instanceof Checking) && super.equals(account)) { return true; } else { return false; } } @Override /** * Builds the string representation of this account * @return - the string representation of this account */ public String toString() { String account = "*Checking*"+ super.toString(); if(this.isDirectDeposit()) { account = account + "*direct deposit account*"; } return account; } } 0 package pl.coderstrust.invoices.model.soap.soapconverter; import java.math.BigDecimal; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Component; import pl.coderstrust.invoices.model.Company; import pl.coderstrust.invoices.model.Company.CompanyBuilder; import pl.coderstrust.invoices.model.Invoice; import pl.coderstrust.invoices.model.Invoice.InvoiceBuilder; import pl.coderstrust.invoices.model.InvoiceEntry; import pl.coderstrust.invoices.model.soap.CompanySoap; import pl.coderstrust.invoices.model.soap.EntrySoap; import pl.coderstrust.invoices.model.soap.InvoiceSoap; import pl.coderstrust.invoices.model.soap.Vat; @Component public class ConverterSoap { public InvoiceSoap getInvoiceSoap(Invoice invoice) { InvoiceSoap invoiceSoap = new InvoiceSoap(); invoiceSoap.setId((Long) invoice.getId()); invoiceSoap.setNumber(invoice.getNumber()); invoiceSoap.setIssueDate(convertLocalDate(invoice.getIssueDate())); invoiceSoap.setIssuePlace(invoice.getIssuePlace()); invoiceSoap.setSellDate(convertLocalDate(invoice.getSellDate())); invoiceSoap.setSeller(getCompanySoap(invoice.getSeller())); invoiceSoap.setBuyer(getCompanySoap(invoice.getBuyer())); for (int i = 0; i < invoice.getEntries().size(); i++) { invoiceSoap.getEntries().add(getEntrySoap(invoice.getEntries().get(i))); } return invoiceSoap; } public Invoice getInvoice(InvoiceSoap invoiceSoap) { return new InvoiceBuilder() .id(invoiceSoap.getId()) .number(invoiceSoap.getNumber()) .issueDate(convertStringToLocalDate(invoiceSoap.getIssueDate())) .issuePlace(invoiceSoap.getIssuePlace()) .sellDate(convertStringToLocalDate(invoiceSoap.getSellDate())) .seller(getCompany(invoiceSoap.getSeller())) .buyer(getCompany(invoiceSoap.getBuyer())) .entries(getInvoiceEntriesList(invoiceSoap.getEntries())) .build(); } private CompanySoap getCompanySoap(Company company) { CompanySoap companySoap = new CompanySoap(); companySoap.setId((Long) company.getId()); companySoap.setName(company.getName()); companySoap.setTaxIdentificationNumber(company.getTaxIdentificationNumber()); companySoap.setStreet(company.getStreet()); companySoap.setPostalCode(company.getPostalCode()); companySoap.setTown(company.getTown()); return companySoap; } private EntrySoap getEntrySoap(InvoiceEntry invoicEntry) { EntrySoap entrySoap = new EntrySoap(); entrySoap.setId((Long) invoicEntry.getId()); entrySoap.setProductName(invoicEntry.getProductName()); entrySoap.setAmount(invoicEntry.getAmount()); entrySoap.setPrice(invoicEntry.getPrice()); entrySoap.setVat(getVatSoap(invoicEntry.getVat())); return entrySoap; } private Company getCompany(CompanySoap companySoap) { return new CompanyBuilder() .id(companySoap.getId()) .name(companySoap.getName()) .taxIdentificationNumber(companySoap.getTaxIdentificationNumber()) .street(companySoap.getStreet()) .postalCode(companySoap.getPostalCode()) .town(companySoap.getTown()) .build(); } private List getInvoiceEntriesList(List entrySoap) { List invoiceEntryList = new ArrayList<>(); for (EntrySoap soap : entrySoap) { InvoiceEntry invoiceEntry = new InvoiceEntry(); invoiceEntry.setId(soap.getId()); invoiceEntry.setProductName(soap.getProductName()); invoiceEntry.setAmount(soap.getAmount()); invoiceEntry.setPrice(soap.getPrice()); invoiceEntry.setVat(getVatInvoice(soap.getVat())); invoiceEntry.setVat(getVatInvoice(soap.getVat())); invoiceEntryList.add(invoiceEntry); } return invoiceEntryList; } private pl.coderstrust.invoices.model.Vat getVatInvoice(Vat vat) { return pl.coderstrust.invoices.model.Vat.valueOf(vat.value()); } private Vat getVatSoap(pl.coderstrust.invoices.model.Vat vat) { BigDecimal vatValue = vat.getValue(); if (vatValue.compareTo(BigDecimal.valueOf(0.23)) == 0) { return Vat.valueOf("VAT_23"); } else if (vatValue.compareTo(BigDecimal.valueOf(0.08)) == 0) { return Vat.valueOf("VAT_8"); } else if (vatValue.compareTo(BigDecimal.valueOf(0.05)) == 0) { return Vat.valueOf("VAT_5"); } else if (vatValue.compareTo(BigDecimal.valueOf(0)) == 0) { return Vat.valueOf("VAT_0"); } return null; } public LocalDate convertStringToLocalDate(String date) { return LocalDate.parse(date); } private String convertLocalDate(LocalDate localDate) { return localDate.getYear() + "-" + localDate.getMonthValue() + "-" + localDate.getDayOfMonth(); } } package com.alfanthariq.tts.model; import com.google.gson.annotations.SerializedName; /** * Created by alfanthariq on 12/02/2018. */ public class RiwayatDetail { @SerializedName("id_tts") private int id_tts; @SerializedName("edisi_str") private String edisiStr; @SerializedName("tgl_terbit") private String tglTerbit; @SerializedName("submit_date") private String tglKirim; @SerializedName("skor") private int skor; public RiwayatDetail(int id_tts, String edisiStr, String tglTerbit, String tglKirim, int skor){ this.id_tts = id_tts; this.edisiStr = edisiStr; this.tglTerbit = tglTerbit; this.tglKirim = tglKirim; } public int getId_tts() { return id_tts; } public String getEdisiStr() { return edisiStr; } public String getTglTerbit() { return tglTerbit; } public String getTglKirim() { return tglKirim; } public int getSkor() { return skor; } } nicerloop/cucumber-jvm package io.cucumber.core.feature; import gherkin.ast.ScenarioDefinition; public final class CucumberScenario implements CucumberScenarioDefinition { private final ScenarioDefinition scenarioDefinition; CucumberScenario(ScenarioDefinition scenarioDefinition) { this.scenarioDefinition = scenarioDefinition; } public int getLine() { return scenarioDefinition.getLocation().getLine(); } @Override public CucumberLocation getLocation() { return CucumberLocation.from(scenarioDefinition.getLocation()); } @Override public String getKeyWord() { return scenarioDefinition.getKeyword(); } public String getName() { return scenarioDefinition.getName(); } } /******************************************************************************* * Copyright Duke Comprehensive Cancer Center and SemanticBits * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/c3pr/LICENSE.txt for details. ******************************************************************************/ package edu.duke.cabig.c3pr.webservice.subjectmanagement.impl; import java.util.ArrayList; import java.util.List; import javax.jws.WebService; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.validation.Errors; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import com.semanticbits.querybuilder.AdvancedSearchCriteriaParameter; import edu.duke.cabig.c3pr.constants.ParticipantStateCode; import edu.duke.cabig.c3pr.domain.Identifier; import edu.duke.cabig.c3pr.domain.Participant; import edu.duke.cabig.c3pr.domain.repository.ParticipantRepository; import edu.duke.cabig.c3pr.domain.validator.ParticipantValidator; import edu.duke.cabig.c3pr.exception.ConversionException; import edu.duke.cabig.c3pr.web.participant.ParticipantWrapper; import edu.duke.cabig.c3pr.webservice.common.AdvanceSearchCriterionParameter; import edu.duke.cabig.c3pr.webservice.common.BiologicEntityIdentifier; import edu.duke.cabig.c3pr.webservice.common.Subject; import edu.duke.cabig.c3pr.webservice.converters.JAXBToDomainObjectConverter; import edu.duke.cabig.c3pr.webservice.iso21090.ST; import edu.duke.cabig.c3pr.webservice.subjectmanagement.AdvancedQuerySubjectRequest; import edu.duke.cabig.c3pr.webservice.subjectmanagement.AdvancedQuerySubjectResponse; import edu.duke.cabig.c3pr.webservice.subjectmanagement.CreateSubjectRequest; import edu.duke.cabig.c3pr.webservice.subjectmanagement.CreateSubjectResponse; import edu.duke.cabig.c3pr.webservice.subjectmanagement.DSETSUBJECT; import edu.duke.cabig.c3pr.webservice.subjectmanagement.InvalidStateTransitionExceptionFault; import edu.duke.cabig.c3pr.webservice.subjectmanagement.InvalidStateTransitionExceptionFaultMessage; import edu.duke.cabig.c3pr.webservice.subjectmanagement.InvalidSubjectDataExceptionFault; import edu.duke.cabig.c3pr.webservice.subjectmanagement.InvalidSubjectDataExceptionFaultMessage; import edu.duke.cabig.c3pr.webservice.subjectmanagement.NoSuchSubjectExceptionFault; import edu.duke.cabig.c3pr.webservice.subjectmanagement.NoSuchSubjectExceptionFaultMessage; import edu.duke.cabig.c3pr.webservice.subjectmanagement.QuerySubjectRequest; import edu.duke.cabig.c3pr.webservice.subjectmanagement.QuerySubjectResponse; import edu.duke.cabig.c3pr.webservice.subjectmanagement.SecurityExceptionFaultMessage; import edu.duke.cabig.c3pr.webservice.subjectmanagement.SubjectAlreadyExistsExceptionFault; import edu.duke.cabig.c3pr.webservice.subjectmanagement.SubjectAlreadyExistsExceptionFaultMessage; import edu.duke.cabig.c3pr.webservice.subjectmanagement.SubjectManagement; import edu.duke.cabig.c3pr.webservice.subjectmanagement.UnableToCreateOrUpdateSubjectExceptionFault; import edu.duke.cabig.c3pr.webservice.subjectmanagement.UnableToCreateOrUpdateSubjectExceptionFaultMessage; import edu.duke.cabig.c3pr.webservice.subjectmanagement.UpdateSubjectRequest; import edu.duke.cabig.c3pr.webservice.subjectmanagement.UpdateSubjectResponse; import edu.duke.cabig.c3pr.webservice.subjectmanagement.UpdateSubjectStateRequest; import edu.duke.cabig.c3pr.webservice.subjectmanagement.UpdateSubjectStateResponse; /** * Implementation of the Subject Management web service. * * @see https * ://ncisvn.nci.nih.gov/svn/c3pr/trunk/c3prv2/documentation/design/essn * /SubjectManagement/PSM_SS_Subject_Management.doc * @author dkrylov * */ @WebService(wsdlLocation = "/WEB-INF/wsdl/SubjectManagement.wsdl", targetNamespace = "http://enterpriseservices.nci.nih.gov/SubjectManagementService", endpointInterface = "edu.duke.cabig.c3pr.webservice.subjectmanagement.SubjectManagement", portName = "SubjectManagement", serviceName = "SubjectManagementService") public class SubjectManagementImpl implements SubjectManagement { /** The Constant SUBJECT_DOES_NOT_EXIST. */ private static final String SUBJECT_DOES_NOT_EXIST = "Subject does not exist."; /** The Constant MISSING_EITHER_SUBJECT_IDENTIFIER_OR_NEW_STATE_VALUE. */ private static final String MISSING_EITHER_SUBJECT_IDENTIFIER_OR_NEW_STATE_VALUE = "Missing either subject identifier or new state value."; /** The Constant WRONG_SUBJECT_STATE_VALUE. */ private static final String WRONG_SUBJECT_STATE_VALUE = "Wrong subject state value."; /** The Constant SUBJECT_IS_INACTIVE. */ private static final String SUBJECT_IS_INACTIVE = "Subject is inactive."; /** The Constant SUBJECT_ALREADY_EXISTS. */ private static final String SUBJECT_ALREADY_EXISTS = "Subject already exists."; /** The log. */ private static Log log = LogFactory.getLog(SubjectManagementImpl.class); /** The converter. */ private JAXBToDomainObjectConverter converter; /** The participant validator. */ private ParticipantValidator participantValidator; /** The participant repository. */ private ParticipantRepository participantRepository; /** * Gets the participant repository. * * @return the participant repository */ public ParticipantRepository getParticipantRepository() { return participantRepository; } /** * Sets the participant repository. * * @param participantRepository the new participant repository */ public void setParticipantRepository( ParticipantRepository participantRepository) { this.participantRepository = participantRepository; } /** * Gets the participant validator. * * @return the participant validator */ public ParticipantValidator getParticipantValidator() { return participantValidator; } /** * Sets the participant validator. * * @param participantValidator the new participant validator */ public void setParticipantValidator( ParticipantValidator participantValidator) { this.participantValidator = participantValidator; } /** * Gets the converter. * * @return the converter */ public JAXBToDomainObjectConverter getConverter() { return converter; } /** * Sets the converter. * * @param converter the new converter */ public void setConverter(JAXBToDomainObjectConverter converter) { this.converter = converter; } /* * (non-Javadoc) * * @seeedu.duke.cabig.c3pr.webservice.subjectmanagement.SubjectManagement# * createSubject * (edu.duke.cabig.c3pr.webservice.subjectmanagement.CreateSubjectRequest) */ public CreateSubjectResponse createSubject(CreateSubjectRequest request) throws SecurityExceptionFaultMessage, InvalidSubjectDataExceptionFaultMessage, SubjectAlreadyExistsExceptionFaultMessage, UnableToCreateOrUpdateSubjectExceptionFaultMessage { CreateSubjectResponse response = new CreateSubjectResponse(); try { Subject subject = request.getSubject(); Participant participant = converter.convert(subject, true,false); List existingList = participantRepository .searchByIdentifier(participant.getPrimaryIdentifier()); if (CollectionUtils.isNotEmpty(existingList)) { SubjectAlreadyExistsExceptionFault fault = new SubjectAlreadyExistsExceptionFault(); fault.setMessage(SUBJECT_ALREADY_EXISTS); throw new SubjectAlreadyExistsExceptionFaultMessage( SUBJECT_ALREADY_EXISTS, fault); } final ParticipantWrapper wrapper = new ParticipantWrapper( participant); // validating only participant's basic details as address is not mandatory participantValidator.validateParticipantDetails(wrapper, new ExceptionBasedErrorsImpl(wrapper)); participantRepository.save(participant); response.setSubject(converter.convert(participant)); } catch (ConversionException e) { handleInvalidSubjectData(e); } catch (ParticipantValidationError e) { handleInvalidSubjectData(e); } catch (RuntimeException e) { handleSubjectBackendProblem(e); } return response; } /* * (non-Javadoc) * * @seeedu.duke.cabig.c3pr.webservice.subjectmanagement.SubjectManagement# * querySubject * (edu.duke.cabig.c3pr.webservice.subjectmanagement.QuerySubjectRequest) */ public QuerySubjectResponse querySubject(QuerySubjectRequest request) throws SecurityExceptionFaultMessage, InvalidSubjectDataExceptionFaultMessage { QuerySubjectResponse response = new QuerySubjectResponse(); final Subject subject = request.getSubject(); if (subject != null && subject.getEntity() != null) { try { Participant participant = converter.convert(subject, false, true); List results = new ArrayList( participantRepository.searchByFullExample(participant)); /* * org.apache.commons.collections15.CollectionUtils.filter(results * , new Predicate() { public boolean * evaluate(Participant p) { return * !SubjectStateCode.INACTIVE.getCode * ().equals(p.getStateCode()); } }); */ DSETSUBJECT dsetsubject = new DSETSUBJECT(); response.setSubjects(dsetsubject); for (Participant p : results) { dsetsubject.getItem().add(converter.convert(p)); } } catch (ConversionException e) { handleInvalidSubjectData(e); } } else { handleInvalidSubjectData(new RuntimeException( "Subject data required for search to be performed.")); } return response; } /* * (non-Javadoc) * * @seeedu.duke.cabig.c3pr.webservice.subjectmanagement.SubjectManagement# * advancedQuerySubject * (edu.duke.cabig.c3pr.webservice.subjectmanagement.AdvancedQuerySubjectRequest * ) */ public AdvancedQuerySubjectResponse advancedQuerySubject( AdvancedQuerySubjectRequest parameters) throws SecurityExceptionFaultMessage, InvalidSubjectDataExceptionFaultMessage { AdvancedQuerySubjectResponse response = new AdvancedQuerySubjectResponse(); DSETSUBJECT subjects = new DSETSUBJECT(); response.setSubjects(subjects); try { List advParameters = new ArrayList(); for (AdvanceSearchCriterionParameter param : parameters .getParameters().getItem()) { AdvancedSearchCriteriaParameter advParam = converter .convert(param); advParameters.add(advParam); } List results = new ArrayList( participantRepository.search(advParameters)); for (Participant p : results) { subjects.getItem().add(converter.convert(p)); } } catch (ConversionException e) { handleInvalidSubjectData(e); } return response; } /* * (non-Javadoc) * * @seeedu.duke.cabig.c3pr.webservice.subjectmanagement.SubjectManagement# * updateSubject * (edu.duke.cabig.c3pr.webservice.subjectmanagement.UpdateSubjectRequest) */ public UpdateSubjectResponse updateSubject(UpdateSubjectRequest request) throws SecurityExceptionFaultMessage, InvalidSubjectDataExceptionFaultMessage, NoSuchSubjectExceptionFaultMessage, UnableToCreateOrUpdateSubjectExceptionFaultMessage { UpdateSubjectResponse response = new UpdateSubjectResponse(); try { Subject subject = request.getSubject(); Participant participant = converter.convert(subject, true,false); List existingList = participantRepository .searchByIdentifier(participant.getPrimaryIdentifier()); if (CollectionUtils.isEmpty(existingList)) { handleUnexistentSubject(); } participant = existingList.get(0); if (!ParticipantStateCode.ACTIVE.equals(participant.getStateCode())) { NoSuchSubjectExceptionFault fault = new NoSuchSubjectExceptionFault(); fault.setMessage(SUBJECT_IS_INACTIVE); throw new NoSuchSubjectExceptionFaultMessage( SUBJECT_IS_INACTIVE, fault); } converter.convert(participant, subject,false); final ParticipantWrapper wrapper = new ParticipantWrapper( participant); participantValidator.validateParticipantDetails(wrapper, new ExceptionBasedErrorsImpl(wrapper)); participantRepository.save(participant); response.setSubject(converter.convert(participant)); } catch (ConversionException e) { handleInvalidSubjectData(e); } catch (ParticipantValidationError e) { handleInvalidSubjectData(e); } catch (RuntimeException e) { handleSubjectBackendProblem(e); } return response; } /** * Handle subject backend problem. * * @param e the e * @throws UnableToCreateOrUpdateSubjectExceptionFaultMessage the unable to create or update subject exception fault message */ private void handleSubjectBackendProblem(RuntimeException e) throws UnableToCreateOrUpdateSubjectExceptionFaultMessage { log.error(ExceptionUtils.getFullStackTrace(e)); UnableToCreateOrUpdateSubjectExceptionFault fault = new UnableToCreateOrUpdateSubjectExceptionFault(); fault.setMessage(e.getMessage()); throw new UnableToCreateOrUpdateSubjectExceptionFaultMessage(e .getMessage(), fault); } /** * Handle invalid subject data. * * @param e the e * @throws InvalidSubjectDataExceptionFaultMessage the invalid subject data exception fault message */ private void handleInvalidSubjectData(Exception e) throws InvalidSubjectDataExceptionFaultMessage { log.error(ExceptionUtils.getFullStackTrace(e)); InvalidSubjectDataExceptionFault fault = new InvalidSubjectDataExceptionFault(); fault.setMessage(e.getMessage()); throw new InvalidSubjectDataExceptionFaultMessage(e.getMessage(), fault); } /* * (non-Javadoc) * * @seeedu.duke.cabig.c3pr.webservice.subjectmanagement.SubjectManagement# * updateSubjectState * (edu.duke.cabig.c3pr.webservice.subjectmanagement.UpdateSubjectStateRequest * ) */ public UpdateSubjectStateResponse updateSubjectState( UpdateSubjectStateRequest request) throws SecurityExceptionFaultMessage, InvalidStateTransitionExceptionFaultMessage, NoSuchSubjectExceptionFaultMessage { UpdateSubjectStateResponse response = new UpdateSubjectStateResponse(); BiologicEntityIdentifier entityIdentifier = request .getBiologicEntityIdentifier(); ST newState = request.getNewState(); if (entityIdentifier != null && newState != null) { Identifier id = converter .convert(entityIdentifier); List existingList = participantRepository .searchByIdentifier(id); if (CollectionUtils.isEmpty(existingList)) { handleUnexistentSubject(); } Participant participant = existingList.get(0); ParticipantStateCode stateCode = ParticipantStateCode .getByCode(newState.getValue()); if (stateCode == null) { InvalidStateTransitionExceptionFault fault = new InvalidStateTransitionExceptionFault(); fault.setMessage(WRONG_SUBJECT_STATE_VALUE); throw new InvalidStateTransitionExceptionFaultMessage( WRONG_SUBJECT_STATE_VALUE, fault); } participant.setStateCode(stateCode); participantRepository.save(participant); response.setSubject(converter.convert(participant)); } else { InvalidStateTransitionExceptionFault fault = new InvalidStateTransitionExceptionFault(); fault .setMessage(MISSING_EITHER_SUBJECT_IDENTIFIER_OR_NEW_STATE_VALUE); throw new InvalidStateTransitionExceptionFaultMessage( MISSING_EITHER_SUBJECT_IDENTIFIER_OR_NEW_STATE_VALUE, fault); } return response; } /** * Handle unexistent subject. * * @throws NoSuchSubjectExceptionFaultMessage the no such subject exception fault message */ private void handleUnexistentSubject() throws NoSuchSubjectExceptionFaultMessage { NoSuchSubjectExceptionFault fault = new NoSuchSubjectExceptionFault(); fault.setMessage(SUBJECT_DOES_NOT_EXIST); throw new NoSuchSubjectExceptionFaultMessage(SUBJECT_DOES_NOT_EXIST, fault); } /** * The Class ParticipantValidationError. */ public static final class ParticipantValidationError extends RuntimeException { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new participant validation error. */ public ParticipantValidationError() { super(); // TODO Auto-generated constructor stub } /** * Instantiates a new participant validation error. * * @param message the message * @param cause the cause */ public ParticipantValidationError(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } /** * Instantiates a new participant validation error. * * @param message the message */ public ParticipantValidationError(String message) { super(message); // TODO Auto-generated constructor stub } /** * Instantiates a new participant validation error. * * @param cause the cause */ public ParticipantValidationError(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } } /** * To be able to re-use {@link ParticipantValidator}, we have to provide an * implementation of {@link Errors} because existing ones are not suitable. * * @author dkrylov * */ private static final class ExceptionBasedErrorsImpl implements Errors { /** The participant wrapper. */ private ParticipantWrapper participantWrapper; /** * Instantiates a new exception based errors impl. * * @param participantWrapper the participant wrapper */ public ExceptionBasedErrorsImpl(ParticipantWrapper participantWrapper) { super(); this.participantWrapper = participantWrapper; } /* (non-Javadoc) * @see org.springframework.validation.Errors#addAllErrors(org.springframework.validation.Errors) */ public void addAllErrors(Errors errors) { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.springframework.validation.Errors#getAllErrors() */ public List getAllErrors() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.springframework.validation.Errors#getErrorCount() */ public int getErrorCount() { // TODO Auto-generated method stub return 0; } /* (non-Javadoc) * @see org.springframework.validation.Errors#getFieldError() */ public FieldError getFieldError() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.springframework.validation.Errors#getFieldError(java.lang.String) */ public FieldError getFieldError(String field) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.springframework.validation.Errors#getFieldErrorCount() */ public int getFieldErrorCount() { // TODO Auto-generated method stub return 0; } /* (non-Javadoc) * @see org.springframework.validation.Errors#getFieldErrorCount(java.lang.String) */ public int getFieldErrorCount(String field) { // TODO Auto-generated method stub return 0; } /* (non-Javadoc) * @see org.springframework.validation.Errors#getFieldErrors() */ public List getFieldErrors() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.springframework.validation.Errors#getFieldErrors(java.lang.String) */ public List getFieldErrors(String field) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.springframework.validation.Errors#getFieldType(java.lang.String) */ public Class getFieldType(String field) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.springframework.validation.Errors#getFieldValue(java.lang.String) */ public Object getFieldValue(String field) { try { return PropertyUtils.getProperty(participantWrapper, field); } catch (Exception e) { throw new RuntimeException(e); } } /* (non-Javadoc) * @see org.springframework.validation.Errors#getGlobalError() */ public ObjectError getGlobalError() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.springframework.validation.Errors#getGlobalErrorCount() */ public int getGlobalErrorCount() { // TODO Auto-generated method stub return 0; } /* (non-Javadoc) * @see org.springframework.validation.Errors#getGlobalErrors() */ public List getGlobalErrors() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.springframework.validation.Errors#getNestedPath() */ public String getNestedPath() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.springframework.validation.Errors#getObjectName() */ public String getObjectName() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.springframework.validation.Errors#hasErrors() */ public boolean hasErrors() { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see org.springframework.validation.Errors#hasFieldErrors() */ public boolean hasFieldErrors() { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see org.springframework.validation.Errors#hasFieldErrors(java.lang.String) */ public boolean hasFieldErrors(String field) { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see org.springframework.validation.Errors#hasGlobalErrors() */ public boolean hasGlobalErrors() { // TODO Auto-generated method stub return false; } /* (non-Javadoc) * @see org.springframework.validation.Errors#popNestedPath() */ public void popNestedPath() throws IllegalStateException { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.springframework.validation.Errors#pushNestedPath(java.lang.String) */ public void pushNestedPath(String subPath) { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.springframework.validation.Errors#reject(java.lang.String) */ public void reject(String errorCode) { throw new ParticipantValidationError(errorCode); } /* (non-Javadoc) * @see org.springframework.validation.Errors#reject(java.lang.String, java.lang.String) */ public void reject(String errorCode, String defaultMessage) { throw new ParticipantValidationError(defaultMessage); } /* (non-Javadoc) * @see org.springframework.validation.Errors#reject(java.lang.String, java.lang.Object[], java.lang.String) */ public void reject(String errorCode, Object[] errorArgs, String defaultMessage) { throw new ParticipantValidationError(defaultMessage); } /* (non-Javadoc) * @see org.springframework.validation.Errors#rejectValue(java.lang.String, java.lang.String) */ public void rejectValue(String field, String errorCode) { throw new ParticipantValidationError(errorCode); } /* (non-Javadoc) * @see org.springframework.validation.Errors#rejectValue(java.lang.String, java.lang.String, java.lang.String) */ public void rejectValue(String field, String errorCode, String defaultMessage) { throw new ParticipantValidationError(defaultMessage); } /* (non-Javadoc) * @see org.springframework.validation.Errors#rejectValue(java.lang.String, java.lang.String, java.lang.Object[], java.lang.String) */ public void rejectValue(String field, String errorCode, Object[] errorArgs, String defaultMessage) { throw new ParticipantValidationError(defaultMessage); } /* (non-Javadoc) * @see org.springframework.validation.Errors#setNestedPath(java.lang.String) */ public void setNestedPath(String nestedPath) { // TODO Auto-generated method stub } } } ilya-moskovtsev/imoskovtsevjunior/chapter_004_ood/src/test/java/ru/job4j/isp/MenuTest.java package ru.job4j.isp; import com.google.common.base.Joiner; import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; import java.util.function.Consumer; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; class MenuTest { private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); private final Consumer output = new Consumer<>() { private final PrintStream stdout = new PrintStream(outContent); @Override public void accept(String s) { stdout.println(s); } }; @Test void print() { Menu menu = new Menu( List.of( new MenuItem("task 1", "-", List.of( new MenuItem("sub task 1.1", "-", null), new MenuItem("sub task 1.2", "-", null) )), new MenuItem("task 2", "-", null), new MenuItem("task 3", "-", List.of( new MenuItem("sub task 3.1", "-", List.of( new MenuItem("sub task 3.1.1", "-", null) )) )) ) ); menu.print("-", output); assertThat(outContent.toString(), is(Joiner.on(System.lineSeparator()).join( "- task 1", "-- sub task 1.1", "-- sub task 1.2", "- task 2", "- task 3", "-- sub task 3.1", "---- sub task 3.1.1", "") ) ); } }1-10 /** * copyright * Inubit AG * Schoeneberger Ufer 89 * 10785 Berlin * Germany */ package net.frapu.code.visualization.twf; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import net.frapu.code.visualization.ProcessNode; /** * @author ff * */ public class ErrorConnection extends Connection { public ErrorConnection() { super(); } /** * */ public ErrorConnection(ProcessNode source, ProcessNode target) { super(source,target); } @Override protected synchronized void paintInternal(Graphics g) { setColor(Color.RED); super.paintInternal(g); } @Override protected synchronized void updateCache() { super.updateCache(); routingPointCache.remove(0); Point _p = getSource().getPos(); _p.y += getSource().getSize().height/2; routingPointCache.add(0,_p); } } /** * Created by IntelliJ IDEA. * User: Lennart * Date: 7-mrt-2005 * Time: 7:39:58 */ package com.compomics.mslims.gui.interfaces; import com.compomics.mslims.db.accessors.Project; import com.compomics.mslims.gui.ProjectAnalyzer; import java.sql.Connection; /* * CVS information: * * $Revision: 1.1 $ * $Date: 2005/03/21 14:18:54 $ */ /** * This interface describes the behaviour for a tool that can be called from the ProjectAnalyzer application. * * @author * @version $Id: ProjectAnalyzerTool.java,v 1.1 2005/03/21 14:18:54 lennart Exp $ */ public interface ProjectAnalyzerTool { /** * This method represents the 'command-pattern' design of the ProjectAnalyzerTool. It will actually allow the tool * to run. * * @param aParent ProjectAnalyzer with the parent that launched this tool. * @param aToolName String with the name for the tool. * @param aParameters String with the parameters as stored in the database for this tool. * @param aConn Connection with the DB connection to use. * @param aDBName String with the name of the database we're connected to via 'aConn'. * @param aProject Project with the project we should be analyzing. */ void engageTool(ProjectAnalyzer aParent, String aToolName, String aParameters, Connection aConn, String aDBName, Project aProject); /** * This method should return a meaningful name for the tool. * * @return String with a meaningful name for the tool. */ String getToolName(); /** * This method will be called when the tool should show itself on the foreground and request the focus. */ void setActive(); /** * This method should be called when the tool has to shut down. */ void close(); } hoangthai267/rpg-framework package com.rpg.framework.entity; import java.util.HashMap; import com.couchbase.client.java.document.json.JsonObject; import com.rpg.framework.database.Protocol; import com.rpg.framework.manager.DataManager; import com.rpg.framework.manager.MessageManager; public class User { private int id; private int connectionID; private int occupation; private String name; private int mapID; private double positionX; private double positionY; private int state; private int direction; private int damage; private int defense; private int speed; private int curHP; private int maxHP; private int curMP; private int maxMP; private boolean respawn; private int curEXP; private int maxEXP; private int level; private HashMap questList; private int money; public User() { id = -1; connectionID = -1; respawn = false; questList = new HashMap(); } public void update(double detla) { if(respawn) { respawn = false; curHP = maxHP; curMP = maxMP; positionX = 0.0; positionY = 0.0; MessageManager.getInstance().sendMessage( connectionID, Protocol.MessageType.MESSAGE_RESPAWN_USER_VALUE, Protocol.MessageRespawnUser.newBuilder() .setId(id) .setOccupation(occupation) .setName(name) .setMapID(mapID) .setX(positionX) .setY(positionY) .setMaxHP(maxHP) .setCurHP(curHP) .setMaxMP(maxMP) .setCurMP(curMP) .setDamage(damage) .setDefense(defense) .setSpeed(speed) .build().toByteArray()); } if(curHP <= 0) { respawn = true; MessageManager.getInstance().sendMessage( connectionID, Protocol.MessageType.MESSAGE_KILL_USER_VALUE, Protocol.MessageKillUser.newBuilder().setId(id).build().toByteArray()); } } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getConnectionID() { return connectionID; } public void setConnectionID(int connectionID) { this.connectionID = connectionID; } public int getOccupation() { return occupation; } public void setOccupation(int occupation) { this.occupation = occupation; } public int getMapID() { return mapID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setMapID(int mapID) { this.mapID = mapID; } public double getPositionX() { return positionX; } public void setPositionX(double positionX) { this.positionX = positionX; } public double getPositionY() { return positionY; } public void setPositionY(double positionY) { this.positionY = positionY; } public int getState() { return state; } public void setState(int state) { this.state = state; } public int getDirection() { return direction; } public void setDirection(int direction) { this.direction = direction; } public int getDamage() { return damage; } public void setDamage(int damage) { this.damage = damage; } public int getDefense() { return defense; } public void setDefense(int defense) { this.defense = defense; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public int getCurHP() { return curHP; } public void setCurHP(int curHP) { this.curHP = curHP; } public int getMaxHP() { return maxHP; } public void setMaxHP(int maxHP) { this.maxHP = maxHP; } public int getCurMP() { return curMP; } public void setCurMP(int curMP) { this.curMP = curMP; } public int getMaxMP() { return maxMP; } public void setMaxMP(int maxMP) { this.maxMP = maxMP; } public int getCurEXP() { return curEXP; } public void setCurEXP(int curEXP) { this.curEXP = curEXP; } public int getMaxEXP() { return maxEXP; } public void setMaxEXP(int maxEXP) { this.maxEXP = maxEXP; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public void setPosition(int mapID, double x, double y) { this.mapID = mapID; this.positionX = x; this.positionY = y; } public void gainExp(int exp) { curEXP += exp; if(curEXP > maxEXP) { level += 1; curEXP = 0; maxEXP = maxEXP * 2; setMaxHP(maxHP + 10); setCurHP(maxHP); setMaxMP(maxMP + 10); setCurMP(maxMP); setDamage(damage + 10); setDefense(defense + 10); setSpeed(speed); MessageManager.getInstance().sendMessage(connectionID, Protocol.MessageType.MESSAGE_UP_LEVEL_USER_VALUE, Protocol.MessageUpLevelUser.newBuilder() .setLevel(level) .setCurEXP(curEXP) .setMaxEXP(maxEXP) .setCurHP(curHP) .setMaxHP(maxHP) .setCurMP(curMP) .setMaxMP(maxMP) .setDamage(damage) .setDefense(defense) .build().toByteArray()); JsonObject position = DataManager.getInstance().get("User_" + id + "_Position"); position.put("mapID", mapID); position.put("x", positionX); position.put("y", positionY); JsonObject stats = DataManager.getInstance().get("User_" + id + "_Stats"); stats.put("level", level); stats.put("dame", damage); stats.put("defense", defense); stats.put("speed", speed); JsonObject status = DataManager.getInstance().get("User_" + id + "_Status"); status.put("curHP", curHP); status.put("maxHP", maxHP); status.put("curMP", curMP); status.put("maxMP", maxMP); status.put("curEXP", curEXP); status.put("maxEXP", maxEXP); DataManager.getInstance().set("User_" + id + "_Position", position); DataManager.getInstance().set("User_" + id + "_Stats", stats); DataManager.getInstance().set("User_" + id + "_Status", status); } } public boolean addQuest(int questID, Quest quest) { if(questList.containsKey(questID)) return false; questList.put(questID, quest); return true; } public Quest getQuest(int questID) { return questList.get((Integer)questID); } public boolean removeQuest(int questID, Quest quest) { return questList.remove((Integer)questID, quest); } public void saveData() { JsonObject position = DataManager.getInstance().get("User_" + id + "_Position"); position.put("mapID", mapID); position.put("x", positionX); position.put("y", positionY); JsonObject stats = DataManager.getInstance().get("User_" + id + "_Stats"); stats.put("level", level); stats.put("dame", damage); stats.put("defense", defense); stats.put("speed", speed); JsonObject status = DataManager.getInstance().get("User_" + id + "_Status"); status.put("curHP", curHP); status.put("maxHP", maxHP); status.put("curMP", curMP); status.put("maxMP", maxMP); status.put("curEXP", curEXP); status.put("maxEXP", maxEXP); status.put("money", money); DataManager.getInstance().set("User_" + id + "_Position", position); DataManager.getInstance().set("User_" + id + "_Stats", stats); DataManager.getInstance().set("User_" + id + "_Status", status); } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public void addMoney(int money) { this.money += money; } } src/main/java/chengweiou/universe/blackhole/model/BasicRestCode.java0 package chengweiou.universe.blackhole.model; public enum BasicRestCode implements RestCode { URL_NOT_FOUND, EXISTS, NOT_EXISTS, OK, FAIL, PARAM, UNAUTH, ; } /* * @Descripttion: * @version: * @@Company: None * @Author: * @Date: 2021-04-21 16:48:45 * @LastEditors: * @LastEditTime: 2021-04-22 20:59:56 */ package com.swithun.backend.tools.secret.config.DaoAutenticationProvider; import com.swithun.backend.tools.secret.config.UsernamePasswordAuthenticationToken.TeacherUsernamePasswordAutenticationToken; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.PasswordEncoder; public class TeacherDaoAutenticationProvider extends DaoAuthenticationProvider { /** * @description: 之后由 WebSecurityConfig 来 设置 StudentDaoAutenticationProvider 对应 * JwtStudentUserDetailsService 从数据库加载对象 * TeacherDaoAutenticationProvider 使用 JwtTeacherUserDetailsService * 从数据库加载对象 * @param {PasswordEncoder} passwordEncoder * @param {UserDetailsPasswordService} userDetailsPasswordService * @return {*} */ public TeacherDaoAutenticationProvider(PasswordEncoder passwordEncoder, UserDetailsService userDetailsService) { setPasswordEncoder(passwordEncoder); setUserDetailsService(userDetailsService); } @Override public void setPasswordEncoder(PasswordEncoder passwordEncoder) { super.setPasswordEncoder(passwordEncoder); } @Override public void setUserDetailsService(UserDetailsService userDetailsService) { super.setUserDetailsService(userDetailsService); } /** * @description: 由WebSecurityConfig 来设置 StudentDaoAuthenticationProvider 处理 * StudentDaoAutenticationProvider * TeacherDaoAuthenticationProvider 处理 * TeacherDaoAuthenticationProvider * @param {*} * @return {*} */ @Override public boolean supports(Class authentication) { return TeacherUsernamePasswordAutenticationToken.class.isAssignableFrom(authentication); } }src/test/java/bdv/util/RealBoxSelectionExample.java /*- * #%L * BigDataViewer quick visualization API. * %% * Copyright (C) 2016 - 2021 BigDataViewer developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package bdv.util; import java.util.Random; import net.imglib2.RealInterval; import net.imglib2.RealRandomAccessibleRealInterval; import net.imglib2.img.Img; import net.imglib2.img.array.ArrayImgs; import net.imglib2.realtransform.AffineTransform3D; import net.imglib2.roi.Masks; import net.imglib2.roi.RealMaskRealInterval; import net.imglib2.roi.Regions; import net.imglib2.type.logic.BoolType; import net.imglib2.type.numeric.integer.UnsignedByteType; import net.imglib2.util.Intervals; import net.imglib2.view.IntervalView; import net.imglib2.view.Views; import bdv.tools.boundingbox.BoxSelectionOptions; import bdv.tools.boundingbox.TransformedRealBoxSelectionDialog; public class RealBoxSelectionExample { public static void main( final String[] args ) { System.setProperty( "apple.laf.useScreenMenuBar", "true" ); final Random random = new Random(); final Img< UnsignedByteType > img = ArrayImgs.unsignedBytes( 100, 100, 50 ); img.forEach( t -> t.set( random.nextInt( 128 ) ) ); final AffineTransform3D imageTransform = new AffineTransform3D(); imageTransform.set( 2, 2, 2 ); final Bdv bdv = BdvFunctions.show( img, "image", BdvOptions.options().sourceTransform( imageTransform ) ); final RealInterval initialInterval = Intervals.createMinMaxReal( 30, 30, 30, 80, 80, 80 ); final RealInterval rangeInterval = Intervals.createMinMaxReal( 0, 0, 0, 100, 100, 100 ); final AffineTransform3D boxTransform = new AffineTransform3D(); boxTransform.rotate( 2, 0.5 ); boxTransform.translate( 30, -20, 0 ); final TransformedRealBoxSelectionDialog.Result result = BdvFunctions.selectRealBox( bdv, boxTransform, initialInterval, rangeInterval, BoxSelectionOptions.options() .title( "Select box to fill" ) ); if ( result.isValid() ) { final RealMaskRealInterval imageMask = result.asMask().transform( imageTransform ); final RealRandomAccessibleRealInterval< BoolType > rrai = Masks.toRealRandomAccessibleRealInterval( imageMask ); final IntervalView< BoolType > rai = Views.interval( Views.raster( rrai ), Intervals.smallestContainingInterval( rrai ) ); Regions.sample( Regions.iterable( rai ), Views.extendZero( img ) ).forEach( t -> t.set( 255 ) ); bdv.getBdvHandle().getViewerPanel().requestRepaint(); } } } package com.miotech.kun.dataquality.core.assertion; import com.miotech.kun.dataquality.core.metrics.MetricsCollectedResult; public abstract class VolatilityAssertion extends Assertion { private final ComparisonPeriod comparisonPeriod; public VolatilityAssertion(String expectedType, String expectedValue, ComparisonOperator comparisonOperator, ComparisonPeriod comparisonPeriod) { super(AssertionType.VOLATILITY, comparisonPeriod, comparisonOperator, expectedType, expectedValue); this.comparisonPeriod = comparisonPeriod; } public ComparisonPeriod getComparisonPeriod() { return comparisonPeriod; } public abstract boolean doVolatilityAssert(MetricsCollectedResult currentValue, MetricsCollectedResult benchmarkValue); @Override public boolean doAssert(AssertionSample assertionSample) { MetricsCollectedResult currentValue= (MetricsCollectedResult) assertionSample.getCurrentValue(); MetricsCollectedResult benchmarkValue = (MetricsCollectedResult) assertionSample.getBenchmarkValue(); if (benchmarkValue == null) { return true; } return doVolatilityAssert(currentValue, benchmarkValue); } } /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package vue.debutPartie; import vue.interfaceJeu.InterfaceJeu; import vue.interfaceJeu.FXMLDocumentController; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Slider; import javafx.scene.control.TextField; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.text.Text; import javafx.stage.Stage; import player.Joueur; import modele.Partie; import modele.PartieSolo; /** * FXML Controller class * * @author Calvin */ public class SoloConfigViewController implements Initializable { @FXML private Button btnBack; @FXML private Button btnValider; @FXML private ImageView imgWood; @FXML private Text textTop; @FXML private TextField roundInput; @FXML private Slider targetSlider; @FXML private Slider windSlider; @FXML private Text target0; @FXML private Text target1; @FXML private Text target2; @FXML private Text nbRoundLabel; @FXML private Text targetLabel; @FXML private Text windLabel; @FXML private Text wind0; @FXML private Text wind1; @FXML private Text wind2; @FXML private Text wind3; private static Stage _stage; private Scene _scene; /** * Initializes the controller class. * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { imgWood.setLayoutY(_stage.getHeight()/2-250); imgWood.setLayoutX(_stage.getWidth()/2-205); textTop.setLayoutY(_stage.getHeight()/2-215); textTop.setLayoutX(_stage.getWidth()/2-45); btnValider.setLayoutY(_stage.getHeight()/2+170); btnValider.setLayoutX(_stage.getWidth()/2+35); btnBack.setLayoutY(_stage.getHeight()/2+175); btnBack.setLayoutX(_stage.getWidth()/2-150); roundInput.setLayoutY(_stage.getHeight()/2-100); roundInput.setLayoutX(_stage.getWidth()/2-130); targetSlider.setLayoutY(_stage.getHeight()/2); targetSlider.setLayoutX(_stage.getWidth()/2-130); windSlider.setLayoutY(_stage.getHeight()/2+100); windSlider.setLayoutX(_stage.getWidth()/2-130); target0.setLayoutY(_stage.getHeight()/2+30); target0.setLayoutX(_stage.getWidth()/2-140); target1.setLayoutY(_stage.getHeight()/2+30); target1.setLayoutX(_stage.getWidth()/2-27); target2.setLayoutY(_stage.getHeight()/2+30); target2.setLayoutX(_stage.getWidth()/2+90); nbRoundLabel.setLayoutY(_stage.getHeight()/2-120); nbRoundLabel.setLayoutX(_stage.getWidth()/2-130); targetLabel.setLayoutY(_stage.getHeight()/2-20); targetLabel.setLayoutX(_stage.getWidth()/2-130); windLabel.setLayoutY(_stage.getHeight()/2+80); windLabel.setLayoutX(_stage.getWidth()/2-130); wind0.setLayoutY(_stage.getHeight()/2+130); wind0.setLayoutX(_stage.getWidth()/2-130); wind1.setLayoutY(_stage.getHeight()/2+130); wind1.setLayoutX(_stage.getWidth()/2-60); wind2.setLayoutY(_stage.getHeight()/2+130); wind2.setLayoutX(_stage.getWidth()/2+12); wind3.setLayoutY(_stage.getHeight()/2+130); wind3.setLayoutX(_stage.getWidth()/2+100); roundInput.textProperty().addListener((ObservableValue observable, String oldValue, String newValue) -> { if (!newValue.matches("\\d*")) { roundInput.setText(newValue.replaceAll("[^\\d]", "")); } if(Integer.parseInt(newValue) < 1){ roundInput.setText("1"); } if(Integer.parseInt(newValue) > 25){ roundInput.setText("25"); } }); } public void goBack() { MultiSoloSelectingViewController selectingMenu = new MultiSoloSelectingViewController(); selectingMenu.lancerAccueilView(_stage); } public void startSoloGame() { Joueur joueur = new Joueur("Joueur"); int vent = (int) windSlider.getValue(); int distance = (int) targetSlider.getValue(); int nbVolee = Integer.parseInt(roundInput.getText()); Partie s = new PartieSolo(joueur, nbVolee, vent, distance); try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(InterfaceJeu.class.getResource("FXMLDocument.fxml")); AnchorPane configurationView = (AnchorPane) loader.load(); _scene = new Scene(configurationView); _stage.setScene(_scene); _stage.show(); FXMLDocumentController controller = loader.getController(); controller.initJeu(s); } catch (IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } } public void lancerSoloConfig(Stage stage) { try { _stage = stage; // chargement de la fenetre de Configuration. FXMLLoader loader = new FXMLLoader(); loader.setLocation(this.getClass().getResource("SoloConfigView.fxml")); AnchorPane configurationView = (AnchorPane) loader.load(); _scene = new Scene(configurationView); _scene.getStylesheets().addAll(this.getClass().getResource("styleSelecting.css").toExternalForm()); _stage.setScene(_scene); _stage.show(); } catch (IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } } } iothub-manager/app/com/microsoft/azure/iotsolutions/iothubmanager/services/models/DeviceStatus/DefaultDeviceStatus.java // Copyright (c) Microsoft. All rights reserved. package com.microsoft.azure.iotsolutions.iothubmanager.services.models.DeviceStatus; import com.microsoft.azure.iotsolutions.iothubmanager.services.models.DeviceStatusQueries; import org.apache.commons.lang3.StringUtils; import java.util.HashMap; import java.util.Map; public class DefaultDeviceStatus { public static Map queries = new HashMap() { { put(DeviceStatusQueries.QueryType.APPLIED, "select * from devices where " + "configurations.[[%s]].status = 'Applied'"); put(DeviceStatusQueries.QueryType.SUCCESSFUL, StringUtils.EMPTY); put(DeviceStatusQueries.QueryType.FAILED, StringUtils.EMPTY); } }; }package cn.zyszkj.cloud.kernel.model.request; import lombok.Getter; import lombok.Setter; import java.io.Serializable; /** * @author XuJZ * 远程服务的参数的基类 */ @Getter @Setter public abstract class AbstractBaseRequest implements Serializable { /** * 唯一请求号 */ private String requestNo; /** * 业务节点id */ private String spanId; /** * 当前登录用户的token */ private String token; } src/OOFramework/ExampleClasses/ExampleState.java package OOFramework.ExampleClasses; import OOFramework.statemachine.State; import OOFramework.statemachine.StateID; public class ExampleState extends State { public ExampleState() { super(StateID.ExampleState); } @Override protected void enter() { super.enter(); } @Override protected void checkForStateSwitch() { super.checkForStateSwitch(); } @Override protected void logic() { super.logic(); } @Override protected void leave() { super.leave(); } } package com.restbase.application.rest.controller.interceptor; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import java.util.UUID; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.springframework.test.context.junit4.SpringRunner; import com.restbase.application.constant.Constants; import com.restbase.application.rest.controller.interceptor.MDCInterceptor; @RunWith(SpringRunner.class) public class MDCInterceptorTest { @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Mock private FilterChain filterChain; @InjectMocks @Spy private MDCInterceptor mdcInterceptor; @Test public void shouldCreateARandomTracerBulletIdIfHeaderIsNotSet() throws ServletException, IOException { ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); mdcInterceptor.doFilterInternal(request, response, filterChain); verify(mdcInterceptor).setTracerBullet(captor.capture()); String tracerBulletId = captor.getValue(); assertThat(tracerBulletId).isNotBlank(); } @Test public void shouldCreateARandomTracerBulletIdIfHeaderIsBlank() throws ServletException, IOException { String tracerId = ""; ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); setUpRequestHeader(Constants.TRACER_BULLET_HEADER, tracerId); mdcInterceptor.doFilterInternal(request, response, filterChain); verify(mdcInterceptor).setTracerBullet(captor.capture()); String tracerBulletId = captor.getValue(); assertThat(tracerBulletId).isNotBlank(); assertThat(tracerBulletId).isNotEqualTo(tracerId); } @Test public void shouldUseTracerBulletIdFromHeaderIfSet() throws ServletException, IOException { String tracerId = UUID.randomUUID().toString(); ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); setUpRequestHeader(Constants.TRACER_BULLET_HEADER, tracerId); mdcInterceptor.doFilterInternal(request, response, filterChain); verify(mdcInterceptor).setTracerBullet(captor.capture()); String tracerBulletId = captor.getValue(); assertThat(tracerBulletId).isNotBlank(); assertThat(tracerBulletId).isEqualTo(tracerId); } private void setUpRequestHeader(String headerName, String headerValue){ when(request.getHeader(eq(headerName))).thenReturn(headerValue); } } package name.caiyao.microreader.presenter.impl; import android.content.Context; import android.content.SharedPreferences; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import java.util.ArrayList; import java.util.Collections; import name.caiyao.microreader.R; import name.caiyao.microreader.api.zhihu.ZhihuRequest; import name.caiyao.microreader.bean.UpdateItem; import name.caiyao.microreader.config.Config; import name.caiyao.microreader.presenter.IMainPresenter; import name.caiyao.microreader.ui.fragment.GuokrFragment; import name.caiyao.microreader.ui.fragment.ItHomeFragment; import name.caiyao.microreader.ui.fragment.VideoFragment; import name.caiyao.microreader.ui.fragment.WeixinFragment; import name.caiyao.microreader.ui.fragment.ZhihuFragment; import name.caiyao.microreader.ui.iView.IMain; import name.caiyao.microreader.utils.SharePreferenceUtil; import rx.Observable; import rx.Observer; import rx.Subscriber; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription; /** * Created by 蔡小木 on 2016/4/26 0026. */ public class MainPresenterImpl extends BasePresenterImpl implements IMainPresenter { private ArrayList mFragments; private ArrayList titles; private IMain mIMain; private ArrayList savedChannelList; private SharedPreferences mSharedPreferences; private CompositeSubscription mCompositeSubscription; public MainPresenterImpl(IMain main, Context context) { if (main == null) throw new IllegalArgumentException("main must not be null"); mSharedPreferences = context.getSharedPreferences(SharePreferenceUtil.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); mIMain = main; mFragments = new ArrayList<>(); titles = new ArrayList<>(); savedChannelList = new ArrayList<>(); } @Override public void initMenu(final NavigationView navigationView) { //The application may be doing too much work on its main thread Subscription s = Observable.create(new Observable.OnSubscribe() { @Override public void call(Subscriber subscriber) { savedChannelList.clear(); titles.clear(); Menu menu = navigationView.getMenu(); menu.clear(); mFragments.clear(); String savedChannel = mSharedPreferences.getString(SharePreferenceUtil.SAVED_CHANNEL, null); if (TextUtils.isEmpty(savedChannel)) { Collections.addAll(savedChannelList, Config.Channel.values()); } else { for (String s : savedChannel.split(",")) { savedChannelList.add(Config.Channel.valueOf(s)); } } for (int i = 0; i < savedChannelList.size(); i++) { MenuItem menuItem = menu.add(0, i, 0, savedChannelList.get(i).getTitle()); titles.add(savedChannelList.get(i).getTitle()); menuItem.setIcon(savedChannelList.get(i).getIcon()); menuItem.setCheckable(true); addFragment(savedChannelList.get(i).name()); if (i == 0) { menuItem.setChecked(true); } } subscriber.onNext(true); } }).subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Boolean aBoolean) { navigationView.inflateMenu(R.menu.activity_main_drawer); mIMain.initMenu(mFragments, titles); } }); addSubscription(s); } @Override public void checkUpdate() { Subscription s = ZhihuRequest.getZhihuApi().getUpdateInfo() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onNext(final UpdateItem updateItem) { mIMain.showUpdate(updateItem); } }); addSubscription(s); } private void addFragment(String name) { switch (name) { case "GUOKR": mFragments.add(new GuokrFragment()); break; case "WEIXIN": mFragments.add(new WeixinFragment()); break; case "ZHIHU": mFragments.add(new ZhihuFragment()); break; case "VIDEO": mFragments.add(new VideoFragment()); break; case "IT": mFragments.add(new ItHomeFragment()); break; } } } package com.plaid.client.request; import com.plaid.client.request.common.BaseAccessTokenRequest; /** * Request for the /sandbox/item/reset_login endpoint. * * @see https://plaid.com/docs/api/#managing-item-states */ public class SandboxItemResetLoginRequest extends BaseAccessTokenRequest { public SandboxItemResetLoginRequest(String accessToken) { super(accessToken); } } app/src/main/java/br/com/ceducarneiro/weatherapp/ws/OpenWeatherWS.java package br.com.ceducarneiro.weatherapp.ws; import android.util.Log; import com.fasterxml.jackson.databind.ObjectMapper; import java.net.URL; import java.net.URLEncoder; import java.text.Normalizer; import java.util.List; import java.util.Locale; public class OpenWeatherWS { private static final String URL_BASE = "http://api.openweathermap.org/data/2.5/weather?units=%s&"; private static final String URL_BASE_LIST = "http://api.openweathermap.org/data/2.5/group?units=%s&"; private static final String URL_BY_LATLNG = URL_BASE + "lat=%.16f&lon=%.16f"; private static final String URL_BY_PLACE = URL_BASE + "q=%s,%s"; private static final String URL_BY_IDS = URL_BASE_LIST + "id=%s"; private static OpenWeatherWS instance; private OpenWeatherWS() { } public static synchronized OpenWeatherWS getInstance() { if (instance == null) { instance = new OpenWeatherWS(); } return instance; } public OpenWeather getWeatherByLatLng(String units, double latitude, double longitude) { ObjectMapper mapper = new ObjectMapper(); OpenWeather weather = null; try { String uri = String.format(Locale.US, URL_BY_LATLNG, units, latitude, longitude); URL url = new URL(uri); weather = mapper.readValue(url, OpenWeather.class); if (weather != null && weather.retCode != 200) weather = null; } catch (Exception ignored) { ignored.printStackTrace(); } return weather; } public OpenWeather getWeatherByPlace(String units, String place, String country) { ObjectMapper mapper = new ObjectMapper(); OpenWeather weather = null; try { String uri = String.format(Locale.US, URL_BY_PLACE, units, normalize(place), normalize(country)); URL url = new URL(uri); weather = mapper.readValue(url, OpenWeather.class); if (weather != null && weather.retCode != 200) weather = null; } catch (Exception ignored) { ignored.printStackTrace(); } return weather; } public OpenWeatherList getWeatherByIds(String units, List ids) { ObjectMapper mapper = new ObjectMapper(); OpenWeatherList weathers = null; try { String idsList = ""; for (Long id : ids) { idsList = String.format("%s%s%s", idsList, idsList.length() > 0 ? "," : "", String.valueOf(id)); } String uri = String.format(Locale.US, URL_BY_IDS, units, idsList); URL url = new URL(uri); Log.d("URL", url.getPath()); weathers = mapper.readValue(url, OpenWeatherList.class); } catch (Exception ignored) { ignored.printStackTrace(); } return weathers; } private String normalize(String str) { try { str = Normalizer.normalize(str, Normalizer.Form.NFD); str = str.replaceAll("[^\\p{ASCII}]", ""); str = URLEncoder.encode(str, "UTF-8"); } catch(Exception ignored) { /* Empty */ } return str; } } harness/src/test/java/org/apache/geode/perftest/benchmarks/EmptyBenchmark.java1-10 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geode.perftest.benchmarks; import java.io.Serializable; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.yardstickframework.BenchmarkDriverAdapter; public class EmptyBenchmark extends BenchmarkDriverAdapter implements Serializable { private AtomicInteger invocations = new AtomicInteger(); @Override public boolean test(Map ctx) throws Exception { invocations.incrementAndGet(); return true; } public int getInvocations() { return this.invocations.get(); } @Override public void onException(Throwable e) { e.printStackTrace(); } } package jtoc.test; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.jtoc.InnerTest; import org.jtoc.Post; import org.jtoc.Pre; public class SmallPerson { private String name; private int weight; public void addKgs(int kgs) { inner.addKgsPreCheck(kgs); weight += kgs; innerTest.addKgsPostCheck(kgs); } @Deprecated public void setName(String name){ innerTest.setNamePreCheck(name); if(name == null) {innerTest.setNamePostCheck(name); return;} if(name == ""){ {innerTest.setNamePostCheck(name); return;} } this.name = name; innerTest.setNamePostCheck(name); } String getName(int k) { return innerTest.postName(( (name == null) ? "" : name), k); } ActionListener getCom(){ if(false) return innerTest.getComPostCheck(( null)); this .name = ""; return innerTest.getComPostCheck(( new ActionListener() { public void actionPerformed(ActionEvent event) { System.out.println("At the tone, the time is "); } })); } //@Post(parameters = "k") int testPostWithParas(){ innerTest.testPostWithParasPreCheck(); int k = 3; return k; } public static void main(String[] args) { SmallPerson s = new SmallPerson(); { System.out.println("could work"); } } class InnerTest{} InnerTest test = new InnerTest(); } src/test/java/com/artipie/http/headers/AuthorizationBearerTest.java /* * The MIT License (MIT) Copyright (c) 2020-2021 artipie.com * https://github.com/artipie/http/blob/master/LICENSE.txt */ package com.artipie.http.headers; import org.hamcrest.MatcherAssert; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; /** * Tests for {@link Authorization.Bearer}. * * @since 0.12 */ public final class AuthorizationBearerTest { @Test void shouldHaveExpectedValue() { MatcherAssert.assertThat( new Authorization.Bearer("mF_9.B5f-4.1JqM").getValue(), new IsEqual<>("Bearer mF_9.B5f-4.1JqM") ); } @Test void shouldHaveExpectedToken() { final String token = "123.abc"; MatcherAssert.assertThat( new Authorization.Bearer(token).token(), new IsEqual<>(token) ); } } RuslanIbIsh/movietickets0 package com.iri.movietickets.model.dto; import com.iri.movietickets.model.validator.CustomEmailConstraint; import com.iri.movietickets.model.validator.PasswordsEqualConstraint; @PasswordsEqualConstraint public class UserRequestDto { @CustomEmailConstraint private String email; private String password; private String repeatPassword; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRepeatPassword() { return repeatPassword; } public void setRepeatPassword(String repeatPassword) { this.repeatPassword = Password; } } /* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.core.configurate.typeserialisers; import io.github.nucleuspowered.nucleus.api.text.NucleusTextTemplate; import io.github.nucleuspowered.nucleus.core.services.impl.texttemplatefactory.NucleusTextTemplateImpl; import io.github.nucleuspowered.nucleus.core.services.interfaces.INucleusTextTemplateFactory; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.spongepowered.configurate.ConfigurationNode; import org.spongepowered.configurate.serialize.SerializationException; import org.spongepowered.configurate.serialize.TypeSerializer; import java.lang.reflect.Type; public class NucleusTextTemplateTypeSerialiser implements TypeSerializer { private final INucleusTextTemplateFactory factory; public NucleusTextTemplateTypeSerialiser(final INucleusTextTemplateFactory factory) { this.factory = factory; } @Override public NucleusTextTemplateImpl deserialize(final Type type, final ConfigurationNode value) throws SerializationException { try { return this.factory.createFromAmpersandString(value.getString()); } catch (final Throwable throwable) { throw new SerializationException(throwable); } } @Override public void serialize(final Type type, final NucleusTextTemplate obj, final ConfigurationNode value) throws SerializationException { if (obj != null) { value.set(LegacyComponentSerializer.legacyAmpersand().serialize(obj.asComponent())); } } } package eu.lod2.nlp2rdf.schema.error; import java.util.List; import java.util.Iterator; import com.hp.hpl.jena.ontology.Individual; /** * Interface http://nlp2rdf.lod2.eu/schema/error/Error */ public interface IError extends Individual, eu.lod2.nlp2rdf.schema.IThing { /** * Domain property Fatal * with uri http://nlp2rdf.lod2.eu/schema/error/fatal */ public boolean existsFatal(); public boolean hasFatal(java.lang.Boolean booleanValue); public java.lang.Boolean getFatal(); public void setFatal(java.lang.Boolean booleanValue); public void removeFatal(); /** * Domain property Source * with uri http://nlp2rdf.lod2.eu/schema/error/source */ public boolean existsSource(); public boolean hasSource(java.lang.String stringValue); public int countSource(); public Iterator iterateSource(); public List listSource(); public void addSource(java.lang.String stringValue); public void addAllSource(List stringList); public void removeSource(java.lang.String stringValue); public void removeAllSource(); /** * Domain property Message * with uri http://nlp2rdf.lod2.eu/schema/error/hasMessage */ public boolean existsMessage(); public boolean hasMessage(java.lang.String stringValue); public int countMessage(); public Iterator iterateMessage(); public List listMessage(); public void addMessage(java.lang.String stringValue); public void addAllMessage(List stringList); public void removeMessage(java.lang.String stringValue); public void removeAllMessage(); }54_Letter/java/src/LetterGame.java1000+ public class LetterGame { public static void main(String[] args) { Letter letter = new Letter(); letter.play(); } } package mysso.client.core.handler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by pengyu on 2017/9/4. */ public interface FilterHandler { public boolean handle(HttpServletRequest request, HttpServletResponse response); } package eu.city4age.dashboard.api.pojo.dto.oj; import java.io.Serializable; import java.util.Set; import com.fasterxml.jackson.annotation.JsonView; import eu.city4age.dashboard.api.pojo.json.view.View; public class Serie implements Serializable { /** * */ private static final long serialVersionUID = -398226081290950273L; @JsonView(View.TimeIntervalView.class) String name; @JsonView(View.TimeIntervalView.class) Set items; @JsonView(View.TimeIntervalView.class) String source; @JsonView(View.TimeIntervalView.class) String imgSize = "20px"; @JsonView(View.TimeIntervalView.class) Integer markerSize = 16; @JsonView(View.TimeIntervalView.class) String markerDisplayed = "on"; @JsonView(View.TimeIntervalView.class) String lineType; public Serie(String name, Set items, String source, String imgSize, Integer markerSize, String markerDisplayed, String lineType) { this.name = name; this.items = items; this.source = source; this.imgSize = imgSize; this.markerSize = markerSize; this.markerDisplayed = markerDisplayed; this.lineType = lineType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set getItems() { return items; } public void setItems(Set items) { this.items = items; } public String getImgSize() { return imgSize; } public void setImgSize(String imgSize) { this.imgSize = imgSize; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getLineType() { return lineType; } public void setLineType(String lineType) { this.lineType = lineType; } public String getMarkerDisplayed() { return markerDisplayed; } public void setMarkerDisplayed(String markerDisplayed) { this.markerDisplayed = markerDisplayed; } public Integer getMarkerSize() { return markerSize; } public void setMarkerSize(Integer markerSize) { this.markerSize = markerSize; } } /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.lorengie.logic; /** * Class employee * @author Asus */ public class Employee { private String EmployeeCode; /**Employee code*/ private String EmployeePosition; /**Employee position*/ private String EmployeeName; /**Employee name*/ private int employeeIdentification; /**Employee identification*/ /** * Default constructor */ public Employee() { } /** * * @param EmployeeCode employee code * @param EmployeePosition employee position * @param EmployeeName employee name * @param employeeIdentification employee identification */ public Employee(String EmployeeCode, String EmployeePosition, String EmployeeName, int employeeIdentification) { this.EmployeeCode = EmployeeCode; this.EmployeePosition = EmployeePosition; this.EmployeeName = EmployeeName; this.employeeIdentification = employeeIdentification; } /** * Get employee code * @return employee code */ public String getEmployeeCode() { return EmployeeCode; } /** * Set employee code * @param EmployeeCode employee code */ public void setEmployeeCode(String EmployeeCode) { this.EmployeeCode = EmployeeCode; } /** * Get employee position * @return employee position */ public String getEmployeePosition() { return EmployeePosition; } /** * Set employee position * @param EmployeePosition employee position */ public void setEmployeePosition(String EmployeePosition) { this.EmployeePosition = EmployeePosition; } /** * Get employee name * @return employee name */ public String getEmployeeName() { return EmployeeName; } /** * Set employee name * @param EmployeeName employee name */ public void setEmployeeName(String EmployeeName) { this.EmployeeName = EmployeeName; } /** * Get employee identification * @return employee identification */ public int getEmployeeIdentification() { return employeeIdentification; } /** * Set employee identification * @param employeeIdentification employee identification */ public void setEmployeeIdentification(int employeeIdentification) { this.employeeIdentification = employeeIdentification; } } package com.krystan.mypendelbuch.common; import android.content.ContentValues; import android.content.Context; import com.krystan.mypendelbuch.R; import com.krystan.mypendelbuch.database.AppDbHelper; import com.krystan.mypendelbuch.database.CommuneTableContract; import com.krystan.mypendelbuch.exception.CommuneException; /** * Helper class for dealing with the commune information.
* Basically this class reads the information from the configuration file and writes the information to the database * * @author * @since 12.03.2017 */ public class CommuneHelper { /* -------------------------- * * Private members * -------------------------- */ private Context context; /* -------------------------- * * Private members * -------------------------- */ public CommuneHelper(Context context) { this.context = context; } /* -------------------------- * * Public methods * -------------------------- */ /** * Writes the entries form the UI into the database * * @param work which button was pushed to switch the departure and arrival location * @param privateCar if the commune was driven with the private car * @throws CommuneException when something went wrong in writing the database entry */ public void writeCommuneEntry(boolean work, Boolean privateCar) throws CommuneException { /*Create data bean and read information from configuration file*/ CommuneDataBean dataBean = new CommuneDataBean(context); dataBean.readDefaultSettings(); /*Write information to database*/ String departure; String arrival; if (work == true) { departure = dataBean.getHomeLocation(); arrival = dataBean.getWorkLocation(); } else { departure = dataBean.getWorkLocation(); arrival = dataBean.getHomeLocation(); } writeCommuneEntryInternal(departure, arrival, dataBean.getDefaultDistance(), privateCar); } /** * Writes the entries form the UI into the database * * @param work which button was pushed to switch the departure and arrival location * @param privateCar if the commune was driven with the private car * @param alternativeLocation the alternative location which can be arrival or destination * @param alternativeDistance the alternative distance * @throws CommuneException when something went wrong in writing the database entry */ public void writeCommuneEntry(boolean work, Boolean privateCar, String alternativeLocation, float alternativeDistance) throws CommuneException { /*Create data bean and read information from configuration file*/ CommuneDataBean dataBean = new CommuneDataBean(context); dataBean.readDefaultSettings(); /*Write information to database*/ String departure; String arrival; if (work == true) { departure = alternativeLocation; arrival = dataBean.getWorkLocation(); } else { departure = dataBean.getWorkLocation(); arrival = alternativeLocation; } writeCommuneEntryInternal(departure, arrival, alternativeDistance, privateCar); } /* -------------------------- * * Private methods * -------------------------- */ /** * * @param departure * @param arrival * @param distance * @param privateCar * @throws CommuneException */ private void writeCommuneEntryInternal(String departure, String arrival, float distance, Boolean privateCar) throws CommuneException { /*Fill values*/ ContentValues values = new ContentValues(); values.put(CommuneTableContract.COLUMN_NAME_DEPARTURE_LOCATION, departure); values.put(CommuneTableContract.COLUMN_NAME_ARRIVAL_LOCATION, arrival); values.put(CommuneTableContract.COLUMN_NAME_DISTANCE, distance); values.put(CommuneTableContract.COLUMN_NAME_PRIVATE_CAR, privateCar.toString()); /*Write information to database*/ long returnCode = AppDbHelper.getDbHelper(context).insert(CommuneTableContract.TABLE_NAME, values); if (returnCode <= 0) { throw new CommuneException(context.getString(R.string.DatabaseEntryError)); } } } package cn.skill6.website.service.basic.store; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.skill6.common.entity.enums.FileType; import cn.skill6.common.entity.po.store.StoreFile; import cn.skill6.common.entity.vo.FileAttribute; import cn.skill6.common.entity.vo.ResponseJson; import cn.skill6.common.utility.DateFormat; import cn.skill6.common.utility.RequestParser; import cn.skill6.microservice.basic.store.StoreFileSvc; import cn.skill6.website.config.Skill6Properties; import cn.skill6.website.dao.intf.store.StoreFileDao; import cn.skill6.website.util.storage.FileStoreHandler; /** * 文件存储服务类 * * @author 何明胜 * @version 1.9 * @since 2018年9月3日 下午11:03:31 */ @Service public class StoreFileService implements StoreFileSvc { @Autowired private StoreFileDao storeFileDao; @Autowired private FileStoreHandler fileStoreHandler; @Autowired private Skill6Properties skill6Properties; private String userHomeDir = System.getProperty("user.home"); @Override public ResponseJson uploadFile(HttpServletRequest request, FileType fileType) throws IOException, FileUploadException { String dateFormat = DateFormat.formatDateYMD("yyyy/MM/dd"); String storeParentPath = StringUtils.join(skill6Properties.getFilePath(), dateFormat); FileAttribute fileAttribute = fileStoreHandler.fileUploadHandler(request, userHomeDir, storeParentPath); StoreFile storeFile = new StoreFile(); storeFile.setFileId(Long.valueOf(fileAttribute.getId())); storeFile.setFileName(fileAttribute.getName()); storeFile.setFileUrl(fileAttribute.getUrl()); storeFile.setFileHashCode(fileAttribute.getHashCode()); storeFile.setFileType(fileType); storeFileDao.addFileDownload(storeFile); Map resultMap = new HashMap(5); resultMap.put("information", "上传成功"); StringBuffer contextUrl = RequestParser.parseContextIndex(request); String fileUrl = contextUrl .append("/file/") .append(dateFormat) .append("/") .append(storeFile.getFileId()) .toString(); resultMap.put("file_url", fileUrl); return new ResponseJson(true, resultMap); } @Override public void downloadFileById(Long fileId, HttpServletResponse response) throws IOException { StoreFile storeFile = storeFileDao.findByFileId(fileId); String fileUrl = storeFile.getFileUrl(); fileUrl = StringUtils.join(userHomeDir, fileUrl); String fileName = storeFile.getFileName(); fileStoreHandler.fileDownloadHandler(response, fileUrl, fileName); } } /* Copyright (c) 2014 . All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package it.inaf.android; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class AppsFragment extends ListFragment { ArrayList mItemList; AppListAdapter mAdapter; Callbacks mCallbacks; public interface Callbacks { void onItemSelected(Bundle args); } static class ViewHolder { ImageView image; TextView name; } private class AppListAdapter extends ArrayAdapter { private Context mContext; private ArrayList objects = null; public AppListAdapter(Context context, int textviewid, ArrayList objects) { super(context, textviewid, objects); mContext = context; this.objects = objects; } @Override public int getCount() { return ((null != objects) ? objects.size() : 0); } @Override public long getItemId(int position) { return position; } @Override public AppItem getItem(int position) { return ((null != objects) ? objects.get(position) : null); } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null) { LayoutInflater li = LayoutInflater.from(mContext); convertView = li.inflate(R.layout.app_item, parent, false); holder = new ViewHolder(); holder.image = (ImageView)convertView.findViewById(R.id.apps_list_image); holder.name = (TextView)convertView.findViewById(R.id.apps_list_name); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } AppItem data = objects.get(position); if(data == null) return convertView; holder.name.setText(data.name); holder.image.setTag(data.iconurl); holder.image.setImageResource(R.drawable.empty); INAF.imageLoader.get(data.iconurl, new ImageListener(holder.image)); return convertView; } } @Override public void onAttach(Activity activity) { super.onAttach(activity); // Activities containing this fragment must implement its callbacks. if (!(activity instanceof Callbacks)) { throw new IllegalStateException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState != null) { mItemList = (ArrayList) savedInstanceState.getSerializable("item_list"); } else { mItemList = new ArrayList(); JSONArray json = INAF.loadJson(getActivity(), "json_apps"); int length = json.length(); for (int i = 0; i < length; i++) { try { AppItem appItem = new AppItem(); JSONObject obj = json.getJSONObject(i); appItem.id = obj.getString("id"); appItem.name = obj.getString("name"); appItem.descr = obj.getString("descr"); appItem.authors = obj.getString("authors"); appItem.iconurl = obj.getString("iconurl"); appItem.infourl = obj.getString("infourl"); appItem.iosurl = obj.getString("iosurl"); appItem.androidurl = obj.getString("androidurl"); appItem.price = obj.getString("price"); appItem.lang = obj.getString("lang"); appItem.notes = obj.getString("notes"); mItemList.add(appItem); } catch (JSONException e) { e.printStackTrace(); } } } mAdapter = new AppListAdapter(getActivity(), R.layout.feed_item, mItemList); setListAdapter(mAdapter); } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); AppItem item = mItemList.get(position); Bundle bundle = new Bundle(); bundle.putSerializable("link", item.infourl); mCallbacks.onItemSelected(bundle); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("item_list", mItemList); } } ExiledNarwal28/glo-4003-spamdul package ca.ulaval.glo4003.cars.services.converters; import static ca.ulaval.glo4003.accounts.helpers.AccountMother.createAccountId; import static ca.ulaval.glo4003.cars.helpers.CarDtoBuilder.aCarDto; import static ca.ulaval.glo4003.cars.helpers.LicensePlateMother.createLicensePlate; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.when; import ca.ulaval.glo4003.accounts.domain.AccountId; import ca.ulaval.glo4003.accounts.services.converters.AccountIdConverter; import ca.ulaval.glo4003.cars.domain.Car; import ca.ulaval.glo4003.cars.domain.LicensePlate; import ca.ulaval.glo4003.cars.domain.exceptions.InvalidCarYearException; import ca.ulaval.glo4003.cars.domain.exceptions.InvalidManufacturerException; import ca.ulaval.glo4003.cars.domain.exceptions.InvalidModelException; import ca.ulaval.glo4003.cars.services.dto.CarDto; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class CarConverterTest { @Mock private LicensePlateConverter licensePlateConverter; @Mock private AccountIdConverter accountIdConverter; private CarConverter carConverter; private static final int INVALID_YEAR = 100000; private final LicensePlate licensePlate = createLicensePlate(); private final AccountId accountId = createAccountId(); private final CarDto carDto = aCarDto().withLicensePlate(licensePlate.toString()).build(); @Before public void setUp() { carConverter = new CarConverter(licensePlateConverter); when(licensePlateConverter.convert(licensePlate.toString())).thenReturn(licensePlate); when(accountIdConverter.convert(accountId.toString())).thenReturn(accountId); } @Test public void whenConverting_shouldCarWithLicensePlate() { Car car = carConverter.convert(carDto); assertThat(car.getLicensePlate().toString()).isEqualTo(carDto.licensePlate); } @Test public void whenConverting_shouldCarWithManufacturer() { Car car = carConverter.convert(carDto); assertThat(car.getManufacturer()).isEqualTo(carDto.manufacturer); } @Test public void whenConverting_shouldCarWithModel() { Car car = carConverter.convert(carDto); assertThat(car.getModel()).isEqualTo(carDto.model); } @Test public void whenConverting_shouldCarWithYear() { Car car = carConverter.convert(carDto); assertThat(car.getYear()).isEqualTo(carDto.year); } @Test public void whenConverting_shouldCarWithConsumptionType() { Car car = carConverter.convert(carDto); assertThat(car.getConsumptionType().toString()).isEqualTo(carDto.consumptionType); } @Test(expected = InvalidCarYearException.class) public void givenCarWithInvalidYear_whenConverting_shouldThrowInvalidYearException() { CarDto carDto = aCarDto().withYear(INVALID_YEAR).build(); carConverter.convert(carDto); } @Test(expected = InvalidCarYearException.class) public void givenCarWithNullYear_whenConverting_shouldThrowInvalidYearException() { // The year is parsed to zero when it is fed a null CarDto carDto = aCarDto().withYear(0).build(); carConverter.convert(carDto); } @Test(expected = InvalidManufacturerException.class) public void givenCarWithNullManufacturer_whenConverting_shouldThrowInvalidManufacturerException() { CarDto carDto = aCarDto().withManufacturer(null).build(); carConverter.convert(carDto); } @Test(expected = InvalidModelException.class) public void givenCarWithNullModel_whenConverting_shouldThrowInvalidModelException() { CarDto carDto = aCarDto().withModel(null).build(); carConverter.convert(carDto); } } package com.beyond.popscience.module.home.fragment; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.AppBarLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.OrientationHelper; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.beyond.library.network.Request; import com.beyond.library.network.enity.MSG; import com.beyond.popscience.R; import com.beyond.popscience.frame.base.BaseFragment; import com.beyond.popscience.frame.net.TownRestUsage; import com.beyond.popscience.locationgoods.SearchActivity; import com.beyond.popscience.module.home.UserDetailsActivity; import com.beyond.popscience.module.home.entity.Address; import com.beyond.popscience.module.home.entity.TownUser; import com.bumptech.glide.Glide; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener; import com.scwang.smartrefresh.layout.listener.OnRefreshListener; import com.zhy.adapter.recyclerview.CommonAdapter; import com.zhy.adapter.recyclerview.MultiItemTypeAdapter; import com.zhy.adapter.recyclerview.base.ViewHolder; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; /** * Created by lenovo on 2017/6/23. */ public class TownMemberFragment extends BaseFragment { public static final String EXTRA_ADDRESS_KEY = "address"; /** * 请求简介 */ private final int REQUEST_NEWS_DETAIL_TASK_ID = 101; /** * */ @BindView(R.id.listView) protected RecyclerView recyclerView; @BindView(R.id.refreshLayout) SmartRefreshLayout refreshLayout; Unbinder unbinder; @BindView(R.id.tv_wzc) TextView tvWzc; @BindView(R.id.ll_sarech) LinearLayout llSarech; @Request private TownRestUsage townRestUsage; private List datas = new ArrayList<>(); private CommonAdapter adapter; private int page = 1; public static TownMemberFragment getInstance(Address address) { TownMemberFragment introFragment = new TownMemberFragment(); Bundle bundle = new Bundle(); bundle.putSerializable(EXTRA_ADDRESS_KEY, address); introFragment.setArguments(bundle); return introFragment; } @Override protected int getLayoutResID() { return R.layout.fragment_intro; } @Override public void initUI() { super.initUI(); initListView(); requestNewsDetail(); } @Override public void refreshUI(int taskId, MSG msg) { super.refreshUI(taskId, msg); switch (taskId) { case REQUEST_NEWS_DETAIL_TASK_ID: //新闻详情 if (msg.getIsSuccess()) { List newsDetailContentList = (List) msg.getObj(); if (newsDetailContentList != null) { if (newsDetailContentList.size() <= 0) { Toast.makeText(getActivity(), "-----到底了-----", Toast.LENGTH_SHORT).show(); } else { if (page == 1) { datas.clear(); } datas.addAll(newsDetailContentList); adapter.notifyDataSetChanged(); } } } else { String code = msg.getCode(); if (null != code) { if (code.equals("3")) { recyclerView.setVisibility(View.GONE); tvWzc.setVisibility(View.VISIBLE); } else { Toast.makeText(getActivity(), "-----到底了-----", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getActivity(), "-----到底了-----", Toast.LENGTH_SHORT).show(); } } break; } } /** * 初始化ListView */ private void initListView() { GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2); //设置布局管理器 recyclerView.setLayoutManager(layoutManager); //设置为垂直布局,这也是默认的 layoutManager.setOrientation(OrientationHelper.VERTICAL); adapter = new CommonAdapter(getActivity(), R.layout.item_user, datas) { @Override protected void convert(ViewHolder holder, TownUser townUser, int position) { Glide.with(getActivity()).load(townUser.getAvatar()).into((ImageView) holder.getView(R.id.img)); holder.setText(R.id.contextTxtViewss, townUser.getNickname()); } }; recyclerView.setAdapter(adapter); //解决上下拉刷新冲突问题 TownFragment.appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { if (null != refreshLayout) { if (verticalOffset >= 0) { refreshLayout.setEnableRefresh(true); refreshLayout.setEnableLoadMore(true); } else { refreshLayout.setEnableRefresh(false); refreshLayout.setEnableLoadMore(true); } } } }); refreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh(@NonNull RefreshLayout refreshLayout) { page = 1; requestNewsDetail(); refreshLayout.finishRefresh(); } }); refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() { @Override public void onLoadMore(@NonNull RefreshLayout refreshLayout) { page++; requestNewsDetail(); refreshLayout.finishLoadMore(); } }); adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() { @Override public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) { // Intent intent = new Intent(getActivity(), UserDetailsActivity.class); intent.putExtra("userId", datas.get(position).getUserid()); intent.putExtra("flag", "1"); startActivity(intent); } @Override public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) { return false; } }); } /** * 请求新闻详情 */ private void requestNewsDetail() { if (getArguments() != null) { Address address = (Address) getArguments().getSerializable(EXTRA_ADDRESS_KEY); if (address != null) { String villageId = String.valueOf(address.getId()); if (TextUtils.equals(villageId, "0") && address.getParentAddress() != null) { villageId = String.valueOf(address.getParentAddress().getId()); } if (address.getId() > 5000) { //那就是村 townRestUsage.getTownUser(REQUEST_NEWS_DETAIL_TASK_ID, "2", villageId, page); } else { //那就是镇 townRestUsage.getTownUser(REQUEST_NEWS_DETAIL_TASK_ID, "1", villageId, page); } } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO: inflate a fragment view View rootView = super.onCreateView(inflater, container, savedInstanceState); unbinder = ButterKnife.bind(this, rootView); return rootView; } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } @OnClick(R.id.ll_sarech) public void onViewClicked() { Intent intent=new Intent(getActivity(),SearchActivity.class); intent.putExtra("flag","xiangzhen"); startActivity(intent); } } backend/n2o/n2o-config/src/test/java/net/n2oapp/framework/config/util/CompileUtilTest.java10-100 package net.n2oapp.framework.config.util; import net.n2oapp.framework.api.N2oNamespace; import net.n2oapp.framework.api.metadata.aware.ExtensionAttributesAware; import net.n2oapp.framework.api.metadata.compile.CompileProcessor; import net.n2oapp.framework.config.N2oApplicationBuilder; import net.n2oapp.framework.config.metadata.compile.N2oCompileProcessor; import net.n2oapp.framework.config.test.N2oTestBase; import org.jdom2.Namespace; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class CompileUtilTest extends N2oTestBase { @Override @Before public void setUp() throws Exception { super.setUp(); } @Override protected void configure(N2oApplicationBuilder builder) { super.configure(builder); } @Test public void testNestedAttributes() { final Map map = new LinkedHashMap<>(); CompileProcessor processor = new N2oCompileProcessor(builder.getEnvironment()); ExtensionAttributesAware extAttributes = new ExtensionAttributesAware() { @Override public void setExtAttributes(Map> extAttributes) { } @Override public Map> getExtAttributes() { Map> attrs = new HashMap<>(); attrs.put(new N2oNamespace(Namespace.getNamespace("test")), map); return attrs; } }; map.put("a", "1"); map.put("b-x", "2"); map.put("b-c-x", "3"); map.put("b-c-d-x", "4"); map.put("b-c-d-e-x", "5"); Map result = processor.mapAttributes(extAttributes); assertThat(result.get("a"), is(1)); assertThat(((Map) result.get("b")).get("x"), is(2)); assertThat(((Map) ((Map) result.get("b")).get("c")).get("x"), is(3)); assertThat(((Map) ((Map) ((Map) result.get("b")).get("c")).get("d")).get("x"), is(4)); assertThat(((Map) ((Map) ((Map) ((Map) result.get("b")).get("c")).get("d")).get("e")).get("x"), is(5)); map.clear(); map.put("a", "1"); map.put("a-b", "true"); try { processor.mapAttributes(extAttributes); } catch (IllegalArgumentException e) { //N2oCompileProcessor:365 assertThat(e.getMessage(), is("The result already contains an element with key a")); } map.clear(); map.put("x-x-a", "true"); map.put("x-x", "true"); try { processor.mapAttributes(extAttributes); } catch (IllegalArgumentException e) { //N2oCompileProcessor:370 assertThat(e.getMessage(), is("The result already contains an element with key x")); } } } package com.feeyo.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; /** * 反射公共类 */ public class ReflectUtil { private static final Logger LOG = LoggerFactory.getLogger(ReflectUtil.class); /** * 构造反射类 * */ public static ReflectUtil on(String name) throws ReflectiveOperationException { return on(forName(name)); } /** * 包含 classloader的包装方法 * */ public static ReflectUtil on(String name, ClassLoader classLoader) throws ReflectiveOperationException { return on(forName(name, classLoader)); } /** * 包装方法 * */ public static ReflectUtil on(Class clazz) { return new ReflectUtil(clazz); } /** * 参数是一个Object对象 * */ public static ReflectUtil on(Object object) { return new ReflectUtil(object); } /** * 放回一个可以访问的字段或者方法 * */ public static T setAndGetAccessible(T accessible) { if (accessible == null) { return null; } if (accessible instanceof Member) { Member member = (Member) accessible; if (Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(member.getDeclaringClass().getModifiers())) { return accessible; } } if (!accessible.isAccessible()) { accessible.setAccessible(true); } return accessible; } private final Object object; private final boolean isClass; /** * 构造函数 * */ private ReflectUtil(Class type) { this.object = type; this.isClass = true; } /** * 构造函数 * */ private ReflectUtil(Object object) { this.object = object; this.isClass = false; } /** * 获取对象值 * */ @SuppressWarnings("unchecked") public T get() { return (T) object; } /** * 设置对象值 * */ public ReflectUtil setValue(String name, Object value) throws ReflectiveOperationException { Field field = field0(name); field.set(object, unwrap(value)); return this; } /** * 获取字段值 * */ public T getValue(String name) throws ReflectiveOperationException { return getField(name).get(); } /** * 获取某一个字段值 * */ public ReflectUtil getField(String name) throws ReflectiveOperationException { Field field = field0(name); return on(field.get(object)); } private Field field0(String name) throws ReflectiveOperationException { Class type = type(); try { return type.getField(name); } catch (NoSuchFieldException e) { do { try { return setAndGetAccessible(type.getDeclaredField(name)); } catch (NoSuchFieldException ignore) { LOG.debug("Ignore a NoSuchFieldException"); } type = type.getSuperclass(); } while (type != null); throw e; } } /** * 获取一个类所有字段 * */ public Map getFields() throws ReflectiveOperationException { Map result = new LinkedHashMap(); Class type = type(); do { for (Field field : type.getDeclaredFields()) { if (!isClass ^ Modifier.isStatic(field.getModifiers())) { String name = field.getName(); if (!result.containsKey(name)) result.put(name, getField(name)); } } type = type.getSuperclass(); } while (type != null); return result; } /** * 调用一个无参方法 * */ public ReflectUtil invoke(String name) throws ReflectiveOperationException { return invoke(name, new Object[0]); } /** * 调用一个包含参数的方法 * */ public ReflectUtil invoke(String name, Object... args) throws ReflectiveOperationException { Class[] types = types(args); try { Method method = invokeMethod(name, types); return on(method, object, args); } catch (NoSuchMethodException e) { try { Method method = getSimilarMethod(name, types); return on(method, object, args); } catch (NoSuchMethodException e1) { throw e1; } } } private Method invokeMethod(String name, Class[] types) throws ReflectiveOperationException { Class type = type(); try { return type.getMethod(name, types); } catch (NoSuchMethodException e) { do { try { return type.getDeclaredMethod(name, types); } catch (NoSuchMethodException ignore) { LOG.debug("Ignore a NoSuchMethodException"); } type = type.getSuperclass(); } while (type != null); throw new NoSuchMethodException(); } } private Method getSimilarMethod(String name, Class[] types) throws ReflectiveOperationException { Class type = type(); for (Method method : type.getMethods()) { if (isSimilarSignature(method, name, types)) { return method; } } do { for (Method method : type.getDeclaredMethods()) { if (isSimilarSignature(method, name, types)) { return method; } } type = type.getSuperclass(); } while (type != null); throw new ReflectiveOperationException("No similar method " + name + " with params " + Arrays.toString(types) + " could be found on type " + type() + "."); } private boolean isSimilarSignature(Method possiblyMatchingMethod, String desiredMethodName, Class[] desiredParamTypes) { return possiblyMatchingMethod.getName().equals(desiredMethodName) && isMatch(possiblyMatchingMethod.getParameterTypes(), desiredParamTypes); } /** * 创建一个对象实例 * */ public ReflectUtil newInstance() throws ReflectiveOperationException { return newInstance(new Object[0]); } /** * 创建一个包含参数的对象实例 * */ public ReflectUtil newInstance(Object... args) throws ReflectiveOperationException { Class[] types = types(args); try { Constructor constructor = type().getDeclaredConstructor(types); return on(constructor, args); } catch (NoSuchMethodException e) { for (Constructor constructor : type().getDeclaredConstructors()) { if (isMatch(constructor.getParameterTypes(), types)) { return on(constructor, args); } } throw e; } } private boolean isMatch(Class[] declaredTypes, Class[] actualTypes) { if (declaredTypes.length == actualTypes.length) { for (int i = 0; i < actualTypes.length; i++) { if (actualTypes[i] == NULL.class) { continue; } Class wrapperClass = wrapper(declaredTypes[i]); if (wrapperClass == null) { continue; } if (wrapperClass.isAssignableFrom(wrapper(actualTypes[i]))) { continue; } return false; } return true; } else { return false; } } /** * {@inheritDoc} */ @Override public int hashCode() { return object.hashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj instanceof ReflectUtil) { return object.equals(((ReflectUtil) obj).get()); } return false; } /** * {@inheritDoc} */ @Override public String toString() { return object.toString(); } private static ReflectUtil on(Constructor constructor, Object... args) throws ReflectiveOperationException { Constructor newConstructor = setAndGetAccessible(constructor); if (newConstructor == null) { throw new ReflectiveOperationException("Failed to execute setAndGetAccessible."); } return on(newConstructor.newInstance(args)); } private static ReflectUtil on(Method method, Object object, Object... args) throws ReflectiveOperationException { setAndGetAccessible(method); if (method.getReturnType() == void.class) { method.invoke(object, args); return on(object); } else { return on(method.invoke(object, args)); } } private static Object unwrap(Object object) { if (object instanceof ReflectUtil) { return ((ReflectUtil) object).get(); } return object; } private static Class[] types(Object... values) { if (values == null) { return new Class[0]; } Class[] result = new Class[values.length]; for (int i = 0; i < values.length; i++) { Object value = values[i]; result[i] = value == null ? NULL.class : value.getClass(); } return result; } private static Class forName(String name) throws ReflectiveOperationException { return Class.forName(name); } private static Class forName(String name, ClassLoader classLoader) throws ReflectiveOperationException { return Class.forName(name, true, classLoader); } public Class type() { if (isClass) { return (Class) object; } else { return object.getClass(); } } public static Class wrapper(Class type) { if (type == null) { return null; } if (!type.isPrimitive()) { return type; } return getPrimitiveType(type); } private static Class getPrimitiveType(Class type) { Class x = getNumberType(type); if (x != null) return x; if (boolean.class == type) { return Boolean.class; } Class x1 = getStringType(type); if (x1 != null) return x1; return type; } private static Class getStringType(Class type) { if (byte.class == type) { return Byte.class; } if (char.class == type) { return Character.class; } return null; } private static Class getNumberType(Class type) { if (short.class == type) { return Short.class; } if (int.class == type) { return Integer.class; } if (long.class == type) { return Long.class; } if (double.class == type) { return Double.class; } if (float.class == type) { return Float.class; } return null; } private static class NULL { } } 10-100 /* Copyright (c) 2000-2021, Board of Trustees of Leland Stanford Jr. University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.lockss.plugin.atypon.aaas; import org.htmlparser.Node; import org.htmlparser.NodeFilter; import org.htmlparser.nodes.TagNode; import org.htmlparser.tags.LinkTag; import org.lockss.daemon.PluginException; import org.lockss.plugin.ArchivalUnit; import org.lockss.plugin.atypon.BaseAtyponHtmlLinkRewriterFactory; import org.lockss.rewriter.LinkRewriterFactory; import org.lockss.servlet.ServletUtil.LinkTransform; import org.lockss.util.Logger; import java.io.IOException; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AaasHtmlLinkRewriterFactory implements LinkRewriterFactory { private static final Logger logger = Logger.getLogger(AaasHtmlLinkRewriterFactory.class); /** * This link rewriter adds special processing to substitute a link to show the RIS citation * */ @Override public InputStream createLinkRewriter(String mimeType, ArchivalUnit au, InputStream in, String encoding, String url, LinkTransform xfm) throws PluginException, IOException { return BaseAtyponHtmlLinkRewriterFactory.createLinkRewriter(mimeType, au, in, encoding, url, xfm, new AaasPreFilter(au,url), null); } static class AaasPreFilter implements NodeFilter { /* * Citations * becomes * */ private static final Pattern DOI_URL_PATTERN = Pattern.compile("^(?:https?://.*/)doi/([.0-9]+)/([^/]+)"); private static final String CIT_DOWNLOAD_ACTION = "action/downloadCitation"; private static final String PILL_CITATIONS_ANCHOR = "#pill-citations"; private static final String DOWNLOAD_RIS_TAIL = "&format=ris&include=cit"; private String html_url = null; private ArchivalUnit thisau = null; public AaasPreFilter(ArchivalUnit au, String url) { super(); html_url = url; thisau = au; } public boolean accept(Node node) { // store the value of tgit statuhe link arguments for later reassembly if (node instanceof LinkTag) { Matcher doiMat = DOI_URL_PATTERN.matcher(html_url); // Are we on a page for which this would be pertinent? if (doiMat.find()) { // now do we have a link to #pill-citations String linkval = ((LinkTag) node).getLink(); if (linkval == null) { return false; } if (linkval.contains(PILL_CITATIONS_ANCHOR)) { String newUrl = "/" + CIT_DOWNLOAD_ACTION + "?doi=" + doiMat.group(1) + "/" + doiMat.group(2) + DOWNLOAD_RIS_TAIL; logger.debug3("found a pill citations anchor, rewriting: <" + linkval + "> to: <" + newUrl + ">"); ((TagNode) node).setAttribute("target", "_blank"); ((LinkTag) node).setLink(newUrl); } } } return false; } } } app/src/main/java/com/example/ruok/controller/RegisterController.java1-10 package com.example.ruok.controller; import android.os.AsyncTask; import android.text.TextUtils; import com.example.ruok.MyApplication; import com.example.ruok.constant.Constants; import com.example.ruok.service.JestService; import com.example.ruok.utils.FileUtils; import com.example.ruok.utils.JsonUser; import io.searchbox.client.JestResult; import io.searchbox.core.DocumentResult; /** * @Date 2018-11-26. */ public class RegisterController extends AsyncTask { private Response response; private JsonUser user; public void setResponse(Response response) { this.response = response; } @Override protected JestResult doInBackground(JsonUser... users) { user = users[0]; //设置 id if (TextUtils.isEmpty(user.getId())) { user.setId(System.currentTimeMillis() + ""); } //1. save user to local file FileUtils.getInstance(MyApplication.context).saveUser(user); //2. submit user to es DocumentResult result = null; try { JestService service = JestService.getInstance(); result = service.createIndex(Constants.INDEX_USER, Constants.TYPE_NAME, user); } catch (Exception e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(JestResult jestResult) { super.onPostExecute(jestResult); if (jestResult == null) { response.onSuccess("local register successfully"); } else { if (jestResult.isSucceeded()) { response.onSuccess("Sign up successfully"); } else { response.onSuccess("local register successfully"); } } } } zhou-jered/RapidTSDB package cn.rapidtsdb.tsdb.plugins.func; public interface PreparablePlugin { void prepare(); } /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.accessibility.utils.parsetree; import androidx.annotation.Nullable; import java.util.ArrayList; import java.util.List; class ParseTreeForReferenceNode extends ParseTreeNode { private final ParseTreeNode mReference; private final ParseTreeNode mFunction; ParseTreeForReferenceNode(ParseTreeNode reference, ParseTreeNode function) { if (!reference.canCoerceTo(ParseTree.VARIABLE_REFERENCE)) { throw new IllegalStateException("Only references can be children of 'for_reference'"); } mReference = reference; mFunction = function; } @Override public int getType() { return mFunction.getType(); } @Override public boolean canCoerceTo(@ParseTree.VariableType int type) { return mFunction.canCoerceTo(type); } @Override public boolean resolveToBoolean(ParseTree.VariableDelegate delegate, String logIndent) { ParseTree.VariableDelegate referenceDelegate = mReference.resolveToReference(delegate, logIndent); if (referenceDelegate != null) { boolean result = mFunction.resolveToBoolean(referenceDelegate, logIndent); referenceDelegate.cleanup(); return result; } else { return false; } } @Override public int resolveToInteger(ParseTree.VariableDelegate delegate, String logIndent) { ParseTree.VariableDelegate referenceDelegate = mReference.resolveToReference(delegate, logIndent); if (referenceDelegate != null) { int result = mFunction.resolveToInteger(referenceDelegate, logIndent); referenceDelegate.cleanup(); return result; } else { return 0; } } @Override public double resolveToNumber(ParseTree.VariableDelegate delegate, String logIndent) { ParseTree.VariableDelegate referenceDelegate = mReference.resolveToReference(delegate, logIndent); if (referenceDelegate != null) { double result = mFunction.resolveToNumber(referenceDelegate, logIndent); referenceDelegate.cleanup(); return result; } else { return 0; } } @Override public CharSequence resolveToString(ParseTree.VariableDelegate delegate, String logIndent) { ParseTree.VariableDelegate referenceDelegate = mReference.resolveToReference(delegate, logIndent); if (referenceDelegate != null) { CharSequence result = mFunction.resolveToString(referenceDelegate, logIndent); referenceDelegate.cleanup(); return result; } else { return ""; } } @Override public @Nullable ParseTree.VariableDelegate resolveToReference( ParseTree.VariableDelegate delegate, String logIndent) { ParseTree.VariableDelegate referenceDelegate = mReference.resolveToReference(delegate, logIndent); if (referenceDelegate != null) { ParseTree.VariableDelegate result = mFunction.resolveToReference(referenceDelegate, logIndent); referenceDelegate.cleanup(); return result; } else { return null; } } @Override public List resolveToArray(ParseTree.VariableDelegate delegate, String logIndent) { ParseTree.VariableDelegate referenceDelegate = mReference.resolveToReference(delegate, logIndent); if (referenceDelegate != null) { List result = mFunction.resolveToArray(referenceDelegate, logIndent); referenceDelegate.cleanup(); return result; } else { return new ArrayList<>(); } } @Override public List resolveToChildArray( ParseTree.VariableDelegate delegate, String logIndent) { ParseTree.VariableDelegate referenceDelegate = mReference.resolveToReference(delegate, logIndent); if (referenceDelegate != null) { List result = mFunction.resolveToChildArray(referenceDelegate, logIndent); referenceDelegate.cleanup(); return result; } else { return new ArrayList<>(); } } } healker/BasisDemo package com.lambdademo; public interface LambDemoI { String lambDemo(String parm); } zeratul53/codepath-app4 package com.david.simpletweets.fragments; import android.os.Bundle; import com.david.simpletweets.models.Message; import com.david.simpletweets.models.Message_Table; import com.david.simpletweets.models.User; import com.raizlabs.android.dbflow.sql.language.SQLite; /** * Created by David on 4/2/2017. */ public class MessagesReceivedFragment extends MessagesListFragment { public static MessagesReceivedFragment newInstance(User currentUser) { MessagesReceivedFragment frag = new MessagesReceivedFragment(); Bundle args = new Bundle(); args.putParcelable("currentUser", currentUser); frag.setArguments(args); return frag; } protected void populate(final long oldestId, final boolean refreshing) { super.populate(oldestId, refreshing); if (client.isNetworkAvailable()) { aMessages.showFooterProgressBar(); client.getMessagesReceived(oldestId, populateHandler); } else { showNetworkUnavailableMessage(); //load from db if network not available messages.addAll(SQLite.select() .from(Message.class) .where(Message_Table.recipient_uid.eq(currentUser.getUid())) .orderBy(Message_Table.uid, false) .queryList()); aMessages.notifyItemRangeInserted(0, messages.size()); } } } package org.apache.ofbiz.product.config.service.base; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.apache.ofbiz.common.ExecuteFindService.In; import org.apache.ofbiz.common.ExecuteFindService.Out; import org.apache.ofbiz.common.ExecuteFindService; import java.util.Arrays; import java.util.ArrayList; import java.util.List; import java.util.Collections; import org.apache.commons.collections4.CollectionUtils; import java.util.Optional; import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.condition.EntityConditionList; import org.apache.ofbiz.entity.condition.EntityExpr; import org.apache.ofbiz.entity.condition.EntityOperator; import com.github.yuri0x7c1.uxcrm.util.OfbizUtil; import org.apache.ofbiz.product.config.ConfigOptionProductOption; import org.springframework.beans.factory.annotation.Autowired; import org.apache.ofbiz.product.config.ProductConfigConfig; import org.apache.ofbiz.product.config.ProductConfigProduct; @Slf4j @Component @SuppressWarnings("unchecked") public class ConfigOptionProductOptionBaseService { protected ExecuteFindService executeFindService; @Autowired public ConfigOptionProductOptionBaseService( ExecuteFindService executeFindService) { this.executeFindService = executeFindService; } /** * Count ConfigOptionProductOptions */ public Integer count(EntityConditionList conditions) { In in = new In(); in.setEntityName(ConfigOptionProductOption.NAME); if (conditions == null) { in.setNoConditionFind(OfbizUtil.Y); } else { in.setEntityConditionList(conditions); } Out out = executeFindService.runSync(in); return out.getListSize(); } /** * Find ConfigOptionProductOptions */ public List find(Integer start, Integer number, List orderBy, EntityConditionList conditions) { List entityList = Collections.emptyList(); In in = new In(); in.setEntityName(ConfigOptionProductOption.NAME); if (start == null) { start = OfbizUtil.DEFAULT_FIND_START; } if (number == null) { number = OfbizUtil.DEFAULT_FIND_NUMBER; } in.setOrderByList(orderBy); if (conditions == null) { in.setNoConditionFind(OfbizUtil.Y); } else { in.setEntityConditionList(conditions); } Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = ConfigOptionProductOption.fromValues(out .getListIt().getPartialList(start, number)); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } return entityList; } /** * Find one ConfigOptionProductOption */ public Optional findOne(Object configId, Object configItemId, Object configOptionId, Object sequenceNum, Object productId) { List entityList = null; In in = new In(); in.setEntityName(ConfigOptionProductOption.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays.asList( new EntityExpr("configId", EntityOperator.EQUALS, configId), new EntityExpr("configItemId", EntityOperator.EQUALS, configItemId), new EntityExpr("configOptionId", EntityOperator.EQUALS, configOptionId), new EntityExpr( "sequenceNum", EntityOperator.EQUALS, sequenceNum), new EntityExpr("productId", EntityOperator.EQUALS, productId)), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = ConfigOptionProductOption.fromValues(out .getListIt().getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get config product config config */ public Optional getConfigProductConfigConfig( ConfigOptionProductOption configOptionProductOption) { List entityList = null; In in = new In(); in.setEntityName(ProductConfigConfig.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays.asList( new EntityExpr("configId", EntityOperator.EQUALS, configOptionProductOption.getConfigId()), new EntityExpr("configItemId", EntityOperator.EQUALS, configOptionProductOption.getConfigItemId()), new EntityExpr("configOptionId", EntityOperator.EQUALS, configOptionProductOption.getConfigOptionId()), new EntityExpr("sequenceNum", EntityOperator.EQUALS, configOptionProductOption.getSequenceNum())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = ProductConfigConfig.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get product product config product */ public Optional getProductProductConfigProduct( ConfigOptionProductOption configOptionProductOption) { List entityList = null; In in = new In(); in.setEntityName(ProductConfigProduct.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays.asList( new EntityExpr("configItemId", EntityOperator.EQUALS, configOptionProductOption.getConfigItemId()), new EntityExpr("configOptionId", EntityOperator.EQUALS, configOptionProductOption.getConfigOptionId()), new EntityExpr("productId", EntityOperator.EQUALS, configOptionProductOption.getProductId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = ProductConfigProduct.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } }linven/needsmoredojotests/com/chrisfolger/needsmoredojo/testutil/MockJSExpressionStatement.java package com.chrisfolger.needsmoredojo.testutil; import com.intellij.lang.ASTNode; import com.intellij.lang.javascript.psi.JSExpression; import com.intellij.lang.javascript.psi.impl.JSExpressionStatementImpl; import com.intellij.psi.tree.IElementType; import static org.mockito.Mockito.mock; public class MockJSExpressionStatement extends JSExpressionStatementImpl { private JSExpression expression; public MockJSExpressionStatement(JSExpression expression) { super(mock(IElementType.class)); this.expression = expression; } @Override public JSExpression getExpression() { return expression; } } gothub/bookkeeper /* * This work was created by participants in the DataONE project, and is * jointly copyrighted by participating institutions in DataONE. For * more information on DataONE, see our web site at http://dataone.org. * * Copyright 2019. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.dataone.bookkeeper.jdbi; import org.dataone.bookkeeper.api.Quota; import org.jdbi.v3.sqlobject.config.RegisterBeanMapper; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.customizer.BindBean; import org.jdbi.v3.sqlobject.customizer.BindList; import org.jdbi.v3.sqlobject.statement.GetGeneratedKeys; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.sqlobject.statement.SqlUpdate; import java.util.List; /** * The quota data access interfaces used to create, read, update, and delete * quotas from the database */ @RegisterBeanMapper(Quota.class) public interface QuotaStore { /** The query used to find all quotas */ String SELECT_CLAUSE = "SELECT " + "q.id, " + "q.object, " + "q.name, " + "q.softLimit, " + "q.hardLimit, " + "q.usage, " + "q.unit, " + "q.subscriptionId, " + "q.subject " + "FROM quotas q "; /** The full ordered query */ String SELECT_ALL = SELECT_CLAUSE; /** The query used to find unassigned quotas (i.e. generic product quotas */ String SELECT_UNASSIGNED = SELECT_CLAUSE + "WHERE subscriptionId IS NULL "; /** The query used to find an individual quota */ String SELECT_ONE = SELECT_CLAUSE + "WHERE q.id = :id "; /** The query used to find a quota by subject identifier */ String SELECT_SUBSCRIPTION = SELECT_CLAUSE + "WHERE q.subscriptionId = :subscriptionId "; /** The query used to find a quota by subject identifier */ String SELECT_SUBJECT = SELECT_CLAUSE + "WHERE q.subject = :subject "; /** The query used to find quotas by multiple subject identifiers */ String SELECT_SUBJECTS = SELECT_CLAUSE + "WHERE q.subject IN () "; /** * List all quotas * @return quotas the list of quotas */ @SqlQuery(SELECT_ALL) List listQuotas(); /** * List all unassigned quotas (no subscriptionId) * @return quotas the list of unassigned quotas */ @SqlQuery(SELECT_UNASSIGNED) List listUnassignedQuotas(); /** * Find quotas by quota identifier * @param id the quota identifier * @return quota the quota for the identifier */ @SqlQuery(SELECT_ONE) Quota getQuota(@Bind("id") Integer id); /** * Find quotas by subscription identifier. * * Pass a null subscriptionId to list all product-associated quotas (i.e. not bound to a subscription). * @param subscriptionId the subscription identifier * @return quotas the quotas for the subscriptionId */ @SqlQuery(SELECT_SUBSCRIPTION) List findQuotasBySubscriptionId(@Bind("subscriptionId") Integer subscriptionId); /** * Find quotas by subject identifier * * @param subject the subject identifier (such as an ORCID identifier) * @return quotas the list of quotas for the subject */ @SqlQuery(SELECT_SUBJECT) List findQuotasBySubject(@Bind("subject") String subject); /** * Find quotas by a list of subject identifiers * * @param subjects the subject identifiers list (such as an ORCID identifier) * @return quotas the list of quotas for the subjects */ @SqlQuery(SELECT_SUBJECTS) List findQuotasBySubjects(@BindList("subjects") List subjects); /** * Insert a quota with a given Quota instance * @param quota the quota to insert */ @SqlUpdate("INSERT INTO quotas " + "(object, " + "name, " + "softLimit, " + "hardLimit, " + "unit, " + "subscriptionId, " + "subject) " + "VALUES " + "(:object, " + ":name, " + ":softLimit, " + ":hardLimit, " + ":unit, " + ":subscriptionId, " + ":subject) " + "RETURNING id") @GetGeneratedKeys Integer insert(@BindBean Quota quota); /** * Update a quota for a given id * @param quota the quota to update */ @SqlUpdate("UPDATE quotas " + "SET object = :object, " + "name = :name, " + "softLimit = :softLimit, " + "hardLimit = :hardLimit, " + "unit = :unit, " + "subscriptionId = :subscriptionId, " + "subject = :subject " + "WHERE id = :id " + "RETURNING id") @GetGeneratedKeys Integer update(@BindBean Quota quota); /** * Delete a quota given the quota id * @param id the quota to delete */ @SqlUpdate("DELETE FROM quotas WHERE id = :id") void delete(@Bind("id") Integer id); } umdk/UCDLiveSDK_Android package com.ucloud.ulive.example.utils; import com.ucloud.ulive.UAudioProfile; import com.ucloud.ulive.UCameraProfile; import com.ucloud.ulive.UFilterProfile; import com.ucloud.ulive.UStreamingProfile; import com.ucloud.ulive.UVideoProfile; import com.ucloud.ulive.example.AVOption; public final class StreamProfileUtil { private StreamProfileUtil() { } public static class AVOptionsHolder { public static final int DEFAULT_CAMERA_INDEX = UCameraProfile.CAMERA_FACING_FRONT; public static final int DEFAULT_VIDEOCODEC_TYPE = UVideoProfile.CODEC_MODE_HARD; public static final int DEFAULT_CAPTURE_ORIENTATION = UVideoProfile.ORIENTATION_PORTRAIT; public static final int DEFAULT_VIDEO_BITRATE = UVideoProfile.VIDEO_BITRATE_MEDIUM; public static final int DEFAULT_VIDEO_CAPTURE_FPS = 20; public static final int DEFAULT_CAMERA_FILTER_MODE = UFilterProfile.FilterMode.GPU; public static final int DEFAULT_AUDIO_BITRATE = UAudioProfile.AUDIO_BITRATE_NORMAL; public static final int DEFAULT_AUDIO_CHANNELS = UAudioProfile.CHANNEL_IN_STEREO; public static final int DEFAULT_AUDIO_SAMPLERATE = UAudioProfile.SAMPLE_RATE_44100_HZ; public static final UVideoProfile.Resolution DEFAULT_VIDEO_RESOLUTION = UVideoProfile.Resolution.RATIO_AUTO; public static final int DEFAULT_AUDIO_SOURCE = UAudioProfile.AUDIO_SOURCE_DEFAULT; } public static UStreamingProfile buildDefault() { return build(StreamProfileUtil.AVOptionsHolder.DEFAULT_VIDEO_CAPTURE_FPS, StreamProfileUtil.AVOptionsHolder.DEFAULT_VIDEO_BITRATE, StreamProfileUtil.AVOptionsHolder.DEFAULT_VIDEO_RESOLUTION, StreamProfileUtil.AVOptionsHolder.DEFAULT_VIDEOCODEC_TYPE, StreamProfileUtil.AVOptionsHolder.DEFAULT_CAPTURE_ORIENTATION, StreamProfileUtil.AVOptionsHolder.DEFAULT_AUDIO_BITRATE, StreamProfileUtil.AVOptionsHolder.DEFAULT_AUDIO_CHANNELS, StreamProfileUtil.AVOptionsHolder.DEFAULT_AUDIO_SAMPLERATE, StreamProfileUtil.AVOptionsHolder.DEFAULT_AUDIO_SOURCE, StreamProfileUtil.AVOptionsHolder.DEFAULT_CAMERA_FILTER_MODE, StreamProfileUtil.AVOptionsHolder.DEFAULT_CAMERA_INDEX, null); } public static UStreamingProfile build(AVOption profile) { return build(profile.videoFramerate, profile.videoBitrate, UVideoProfile.Resolution.valueOf(profile.videoResolution), profile.videoCodecType, profile.videoCaptureOrientation, profile.audioBitrate, profile.audioChannels, profile.audioSampleRate, profile.audioSource, profile.videoFilterMode, profile.cameraIndex, profile.streamUrl ); } private static UStreamingProfile build(int fps, int videoBitrate, UVideoProfile.Resolution videoResolution, int videoCodecType, int captureOrientation, int audioBitrate, int audioChannels, int audioSampleRate, int audioSource, int videoRenderMode, int cameraIndex, String streamUrl) { UVideoProfile videoProfile = new UVideoProfile().fps(fps) .bitrate(videoBitrate) //设置初始码率 推荐设置600kbps .minBitrate(UVideoProfile.VIDEO_BITRATE_NORMAL) //设置最低码率 400kbps .maxBitrate(UVideoProfile.VIDEO_BITRATE_HIGH) //设置最高码率 800kbps 当网络发生拥塞, //关于最低、最高码率:(SDK内部会动态调整音视频码率) //1.可自行调整最低码率的值,若最小码率与初始码率相差较小,当网络拥塞时,抗抖动的能力就比较小,整体帧率会较低。 //2.降码率,对音视频的质量肯定有影响,一般推荐设置一个您认为能够接受的最低效果的值,当网络恢复通畅时,内部会逐步稳定提高码率。 //3.若流畅优先,视频码率最低推荐可设置200kbps,画质优先推荐成400kbps (初始码率600kbps的情况),其它您自定义的值也适用。 .resolution(videoResolution) .codecMode(videoCodecType) .captureOrientation(captureOrientation); UAudioProfile audioProfile = new UAudioProfile() .source(audioSource) .bitrate(audioBitrate) //设置初始码率 推荐设置64kbps .minBitrate(UAudioProfile.AUDIO_BITRATE_LOW) //设置最低码率 48kbps .maxBitrate(UAudioProfile.AUDIO_BITRATE_HIGH) //设置最高码率 128kbps .channels(audioChannels) .samplerate(audioSampleRate); UFilterProfile filterProfile = new UFilterProfile().mode(videoRenderMode); UCameraProfile cameraProfile = new UCameraProfile() .setCameraIndex(cameraIndex); return new UStreamingProfile.Builder() .setAudioProfile(audioProfile) .setVideoProfile(videoProfile) .setFilterProfile(filterProfile) .setCameraProfile(cameraProfile) .build(streamUrl); } } /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.optimizer.dataproperties; /** * An enumeration of the the different types of distributing data across partitions or * parallel workers. */ public enum PartitioningProperty { /** * Any possible way of data distribution, including random partitioning and full replication. */ ANY_DISTRIBUTION, /** * A random disjunct (non-replicated) data distribution, where each datum is contained in one partition only. * This is for example the result of parallel scans of data in a file system like HDFS, * or the result of a round-robin data distribution. */ RANDOM_PARTITIONED, /** * A hash partitioning on a certain key. */ HASH_PARTITIONED, /** * A range partitioning on a certain key. */ RANGE_PARTITIONED, /** * A not further specified partitioning on a key (hash-, or range partitioning, or some other scheme even). */ ANY_PARTITIONING, /** *Full replication of the data to each parallel instance. */ FULL_REPLICATION, /** * A forced even re-balancing. All partitions are guaranteed to have almost the same number of records. */ FORCED_REBALANCED, /** * A custom partitioning, accompanied by a {@link org.apache.flink.api.common.functions.Partitioner}. */ CUSTOM_PARTITIONING; /** * Checks, if this property represents in fact a partitioning. That is, * whether this property is not equal to PartitionProperty.FULL_REPLICATION. * * @return True, if this enum constant is unequal to PartitionProperty.FULL_REPLICATION, * false otherwise. */ public boolean isPartitioned() { return this != FULL_REPLICATION && this != FORCED_REBALANCED && this != ANY_DISTRIBUTION; } /** * Checks, if this property represents a full replication. * * @return True, if this enum constant is equal to PartitionProperty.FULL_REPLICATION, * false otherwise. */ public boolean isReplication() { return this == FULL_REPLICATION; } /** * Checks if this property presents a partitioning that is not random, but on a partitioning key. * * @return True, if the data is partitioned on a key. */ public boolean isPartitionedOnKey() { return isPartitioned() && this != RANDOM_PARTITIONED; } /** * Checks, if this property represents a partitioning that is computable. * A computable partitioning can be recreated through an algorithm. If two sets of data are to * be co-partitioned, it is crucial, that the partitioning schemes are computable. *

* Examples for computable partitioning schemes are hash- or range-partitioning. An example for a non-computable * partitioning is the implicit partitioning that exists though a globally unique key. * * @return True, if this enum constant is a re-computable partitioning. */ public boolean isComputablyPartitioned() { return this == HASH_PARTITIONED || this == RANGE_PARTITIONED || this == CUSTOM_PARTITIONING; } } ycj123/Research-ProjectproFL-plugin-2.0.3/org/netbeans/lib/cvsclient/command/annotate/AnnotateLine.java // // Decompiled by Procyon v0.5.36 // package org.netbeans.lib.cvsclient.command.annotate; import java.text.SimpleDateFormat; import java.util.Locale; import java.text.ParseException; import java.util.Date; import java.text.DateFormat; public class AnnotateLine { private static final DateFormat DATE_FORMAT; private String author; private String revision; private Date date; private String dateString; private String content; private int lineNum; public String getAuthor() { return this.author; } public void setAuthor(final String author) { this.author = author; } public String getRevision() { return this.revision; } public void setRevision(final String revision) { this.revision = revision; } public Date getDate() { return this.date; } public String getDateString() { return this.dateString; } public void setDateString(final String s) { this.dateString = s; try { this.date = AnnotateLine.DATE_FORMAT.parse(s); } catch (ParseException ex) { ex.printStackTrace(); } } public String getContent() { return this.content; } public void setContent(final String content) { this.content = content; } public int getLineNum() { return this.lineNum; } public Integer getLineNumInteger() { return new Integer(this.lineNum); } public void setLineNum(final int lineNum) { this.lineNum = lineNum; } static { DATE_FORMAT = new SimpleDateFormat("dd-MMM-yy", Locale.US); } } package com.tech.productmanagement.config; import java.util.Properties; import javafx.beans.NamedArg; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.orm.hibernate5.HibernateTransactionManager; import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.tech.productmanagement.model.AddProduct; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:/properties/persistence.properties" }) public class DBConfig { @Autowired private Environment env; @Bean public HibernateTemplate hibernateTemplate() { return new HibernateTemplate(sessionFactory()); } @Bean public SessionFactory sessionFactory() { LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(getDataSource()); sessionBuilder.addProperties(getHibernateProperties()); sessionBuilder.addAnnotatedClasses(AddProduct.class); sessionBuilder.scanPackages("com.tech.productmanagement.model"); return sessionBuilder.buildSessionFactory(); } @Bean public DataSource getDataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(env.getProperty("db.driverClass")); dataSource.setUrl(env.getProperty("db.connectionURL")); dataSource.setUsername(env.getProperty("db.username")); dataSource.setPassword(env.getProperty("db.password")); return dataSource; } @Bean public HibernateTransactionManager getTransactionManager() { HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactory()); return transactionManager; } /* @Bean public LocalSessionFactoryBean getSessionFactory() { LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean(); factoryBean.setDataSource(getDataSource()); Properties props=new Properties(); props.put("hibernate.show_sql", env.getProperty("hibernate.show_sql")); props.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); factoryBean.setHibernateProperties(getHibernateProperties()); factoryBean.setPackagesToScan("com.zdi.roomreadyservices.model"); //factoryBean.setAnnotatedClasses(User.class); return factoryBean; }*/ @Bean public NamedParameterJdbcTemplate namedParameterJdbcTemplate(){ NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(getDataSource()); return namedParameterJdbcTemplate; } private Properties getHibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.show_sql", "true"); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); properties.put("hibernate.hbm2ddl.auto","none"); properties.put("hibernate.id.new_generator_mappings","false"); return properties; } } common/src/gen/java/org/iobserve/common/record/ObservationPoint.java /*************************************************************************** * Copyright 2019 iObserve Project (https://www.iobserve-devops.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ package org.iobserve.common.record; /** * @author * API compatibility: Kieker 1.15.0 * * @since 1.15 */ public enum ObservationPoint { EVENT_CREATION_TIME(0), DISPATCHER_ENTRY(1), CODE_TO_MODEL_ENTRY(2), CODE_TO_MODEL_EXIT(3), MODEL_UPDATE_ENTRY(4), MODEL_UPDATE_EXIT(5), PRIVACY_WARNER_ENTRY(6), PRIVACY_WARNER_EXIT(7), COMPUTE_PROBE_CONFIGURATION_ENTRY(8), COMPUTE_PROBE_CONFIGURATION_EXIT(9), WHITE_LIST_FILTER_ENTRY(10), WHITE_LIST_FILTER_EXIT(11), PROBE_MODEL_TO_CODE_ENTRY(12), PROBE_MODEL_TO_CODE_EXIT(13), CONTROL_PROBES_ENTRY(14), CONTROL_PROBES_EXIT(15), CONTROL_PROBES_ERROR(16); private int value; private ObservationPoint(final int value) { this.value = value; } public int getValue() { return this.value; } public static ObservationPoint getEnum(final int value) { for (final ObservationPoint type : ObservationPoint.values()) { if (type.getValue() == value) return type; } throw new RuntimeException("Illegal value for ObservationPoint enumeration."); } } package fr.exratio.jme.devkit.properties.component.control; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import com.jme3.anim.AnimClip; import com.jme3.anim.AnimComposer; import com.jme3.anim.tween.action.Action; import fr.exratio.jme.devkit.properties.component.AbstractPropertyEditor; import fr.exratio.jme.devkit.service.JmeEngineService; import fr.exratio.jme.devkit.service.ServiceManager; import java.awt.Insets; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.DefaultBoundedRangeModel; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.SwingUtilities; import javax.swing.Timer; public class AnimComposerEditor extends AbstractPropertyEditor { private final DefaultBoundedRangeModel animTimelineModel = new DefaultBoundedRangeModel(0, 1, 0, 1000); private Timer timer; private JList animationsList; private JButton playButton; private JButton stopButton; private JSlider timeSlider; private JPanel contentPanel; private JSlider speedSlider; private AnimClip animClip; private Action action; public AnimComposerEditor(AnimComposer animComposer) { super(animComposer); } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR * call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { createUIComponents(); contentPanel.setLayout(new GridLayoutManager(4, 2, new Insets(0, 0, 0, 0), -1, -1)); contentPanel.add(timeSlider, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); contentPanel.add(speedSlider, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label1 = new JLabel(); label1.setText("Time"); contentPanel.add(label1, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label2 = new JLabel(); label2.setText("Speed"); contentPanel.add(label2, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1)); contentPanel.add(panel1, new GridConstraints(1, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); playButton.setText("Play"); panel1.add(playButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); stopButton.setText("Stop"); panel1.add(stopButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer1 = new Spacer(); panel1.add(spacer1, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JScrollPane scrollPane1 = new JScrollPane(); contentPanel.add(scrollPane1, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)); scrollPane1.setViewportView(animationsList); } public JComponent $$$getRootComponent$$$() { return contentPanel; } @Override protected AnimComposer computeValue() { return null; } private void createUIComponents() { contentPanel = this; final JmeEngineService engineService = ServiceManager.getService(JmeEngineService.class); timeSlider = new JSlider(); timeSlider.setModel(animTimelineModel); engineService.enqueue(() -> { // fill our list SwingUtilities.invokeLater(() -> { DefaultListModel listModel = new DefaultListModel<>(); listModel.addAll(value.getAnimClips()); animationsList.setModel(listModel); }); }); animationsList = new JList(); animationsList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { final AnimClip selectedClip = animationsList.getSelectedValue(); if (selectedClip != null) { engineService.enqueue(() -> { animClip = selectedClip; SwingUtilities.invokeLater( () -> animTimelineModel.setMaximum((int) (animClip.getLength() * 1000))); }); } } }); speedSlider = new JSlider(); speedSlider.setModel(new DefaultBoundedRangeModel(1000, 250, 0, 2000)); speedSlider.addChangeListener( e -> engineService.enqueue(() -> action.setSpeed(speedSlider.getValue() / 1000f))); timeSlider = new JSlider(); timeSlider.addChangeListener(e -> { if (action != null) { engineService.enqueue( () -> value.setTime(AnimComposer.DEFAULT_LAYER, timeSlider.getValue() / 1000f)); } }); playButton = new JButton(); playButton.addActionListener(e -> engineService.enqueue(() -> { action = value.setCurrentAction(animClip.getName()); action.setSpeed(speedSlider.getValue() / 1000f); })); stopButton = new JButton(); stopButton.addActionListener(e -> engineService.enqueue(() -> action.setSpeed(0))); // create a timer that queries the animation channel time so we can update the time slider position. timer = new Timer(10, e -> engineService.enqueue(() -> { if (animClip != null) { SwingUtilities.invokeLater(() -> { timeSlider.setValue((int) (value.getTime(AnimComposer.DEFAULT_LAYER) * 1000)); }); } })); timer.setRepeats(true); timer.start(); } } /* * Copyright 2019-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gstesis.ddos.api; import org.gstesis.ddos.app.processor.IdsResources; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.onosproject.rest.AbstractWebResource; import org.onlab.packet.IpAddress; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.DELETE; import javax.ws.rs.Path; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.Set; /** * Sample web resource. * implemntacion de los metodos. */ @Path("ids") public class IdsWebResource extends AbstractWebResource { private static final String IP = "ip"; /** * Get hello world greeting. * * @return 200 OK */ @GET @Path("ips") @Produces(MediaType.APPLICATION_JSON) public Response getOrders() { ObjectNode node; ArrayNode ipArray; Set idsResources; idsResources = IdsResources.getInstance().getIpAddressSet(); node = mapper().createObjectNode(); ipArray = mapper().createArrayNode(); idsResources.forEach(ipAddress -> { ipArray.add(ipAddress.toString()); // Add IDS ips }); node.putArray(IP).addAll(ipArray); // add Array to Object return ok(node).build(); } /** * Set enabled IDS ips. * * @param component Ids Ip * @return 200 OK or 500 on error */ @POST @Path("ip/{component}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response addOrderByIp(@PathParam("component") String component) { boolean response; ObjectNode node; IdsResources idsResources; idsResources = IdsResources.getInstance(); response = idsResources.addIpAddres(component.trim()); node = mapper().createObjectNode().put("Response", response); return ok(node).build(); } @DELETE @Path("ip/{component}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response deleteOrderById(@PathParam("component") String component) { boolean response; ObjectNode node; IdsResources idsResources; idsResources = IdsResources.getInstance(); response = idsResources.delIpAddres(component.trim()); node = mapper().createObjectNode().put("Response", response); return ok(node).build(); } } 1-10 package fp.grados.tipos; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; public interface Departamento extends Comparable { String getNombre(); Set getAsignaturas(); Set getProfesores(); void nuevaAsignatura(Asignatura asig); void eliminaAsignatura(Asignatura asig); void nuevoProfesor(Profesor prof); void eliminaProfesor(Profesor prof); void borraTutorias(); void borraTutorias(Categoria c); Boolean existeProfesorAsignado(Asignatura a); Boolean estanTodasAsignaturasAsignadas(); void eliminaAsignacionProfesorado(Asignatura a); SortedMap> getProfesoresPorAsignatura(); SortedMap> getTutoriasPorProfesor(); Profesor getProfesorMaximaDedicacionMediaPorAsignatura(); } package huskymaps.tests; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import huskymaps.StreetMapGraph; import huskymaps.params.RouteRequest; import huskymaps.server.logic.Router; import org.junit.Before; import org.junit.Test; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Arrays; import java.util.List; import static huskymaps.utils.Constants.BASE_DIR_PATH; import static org.junit.Assert.assertEquals; /** Test of the routing part of the assignment. */ public class TestRouter { private static final String REQUEST_FORMAT = BASE_DIR_PATH + "tests/router/request%d.json"; private static final String RESULT_FORMAT = BASE_DIR_PATH + "tests/router/result%d.json"; private static final String LARGE_OSM_DB_PATH = BASE_DIR_PATH + "seattle.osm.gz"; private static final int NUM_TESTS = 10; private boolean initialized = false; private StreetMapGraph graph; private final Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); @Before public void setUp() { if (initialized) { return; } graph = new StreetMapGraph(LARGE_OSM_DB_PATH); initialized = true; } @Test public void testShortestPath() throws IOException { for (int i = 0; i < NUM_TESTS; i += 1) { System.out.println(String.format("Running test: %d", i)); RouteRequest request; try (Reader reader = new FileReader(String.format(REQUEST_FORMAT, i))) { request = gson.fromJson(reader, RouteRequest.class); } List actual = Router.shortestPath(graph, request); List expected; try (Reader reader = new FileReader(String.format(RESULT_FORMAT, i))) { expected = Arrays.asList(gson.fromJson(reader, Long[].class)); } assertEquals("Your results did not match the expected results", expected, actual); } } } 0 package controller.in; import controller.in.reader.AbstractReader; import controller.in.reader.FileReader; import controller.in.reader.StringReader; import controller.in.transformer.AbstractTransformer; import controller.in.transformer.CSVTransformer; import java.io.File; public class FactoryIn { public static AbstractReader getReader(Object input) throws Exception { if (input instanceof File) { return new FileReader((File) input); } if (input instanceof String) { return new StringReader((String) input); } return null; } public static AbstractTransformer getTransformer(FORMAT format) { if (format == FORMAT.CVS) { return new CSVTransformer(";", "\\r?\\n"); } return null; } public enum FORMAT { CVS } } GeorgeJahad/blueflood /* * Copyright 2013 Rackspace * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rackspacecloud.blueflood.eventemitter; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.rackspacecloud.blueflood.concurrent.ThreadPoolBuilder; import com.rackspacecloud.blueflood.io.DiscoveryIO; import com.rackspacecloud.blueflood.types.BasicRollup; import com.rackspacecloud.blueflood.utils.QueryDiscoveryModuleLoader; import com.rackspacecloud.blueflood.utils.Util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.concurrent.*; public class RollupEventEmitter extends Emitter { private static final Logger log = LoggerFactory.getLogger(QueryDiscoveryModuleLoader.class); private static final int numberOfWorkers = 5; public static final String ROLLUP_EVENT_NAME = "rollup".intern(); private static ThreadPoolExecutor eventExecutors; private static final RollupEventEmitter instance = new RollupEventEmitter(); private RollupEventEmitter() { eventExecutors = new ThreadPoolBuilder() .withName("RollupEventEmitter ThreadPool") .withCorePoolSize(numberOfWorkers) .withMaxPoolSize(numberOfWorkers) .withUnboundedQueue() .build(); } public static RollupEventEmitter getInstance() { return instance; } @Override public Future emit(final String event, final RollupEvent... eventPayload) { //TODO: This hack will go away after Kafka Serializer is made generic Future emitFuture = null; if(eventPayload[0].getRollup() instanceof BasicRollup && super.hasListeners(ROLLUP_EVENT_NAME)) { emitFuture = eventExecutors.submit(new Callable() { @Override public Future call() { if (Util.shouldUseESForUnits()) { QueryDiscoveryModuleLoader.loadDiscoveryModule(); final DiscoveryIO discoveryIO = QueryDiscoveryModuleLoader.getDiscoveryInstance(); // TODO: Sync for now, but we will have to make it async eventually Lists.transform(Arrays.asList(eventPayload), new Function() { @Override public RollupEvent apply(RollupEvent event) { String unit; try { unit = discoveryIO.search(event.getLocator().getTenantId(), event.getLocator().getMetricName()).get(0).getUnit(); } catch (Exception e) { log.warn("Exception encountered while getting units out of ES : %s", e.getMessage()); unit = Util.UNKNOWN; } event.setUnit(unit); return event; } }); } return RollupEventEmitter.super.emit(event, eventPayload); } }); } return emitFuture; } } package org.opendatadiscovery.oddplatform.config; import org.opendatadiscovery.oddplatform.auth.CognitoOidcLogoutSuccessHandler; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.security.config.Customizer; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.oauth2.client.oidc.web.server.logout.OidcClientInitiatedServerLogoutSuccessHandler; import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler; import org.springframework.security.web.server.util.matcher.PathPatternParserServerWebExchangeMatcher; @Configuration @ConditionalOnProperty(value = "auth.type", havingValue = "OAUTH2") public class OAuthSecurityConfiguration { private final Boolean cognitoEnabled; private final String clientId; private final String logoutUrl; public OAuthSecurityConfiguration( @Value("${cognito.enabled}") final Boolean cognitoEnabled, @Value("${spring.security.oauth2.client.registration.cognito.client-id:}") final String clientId, @Value("${cognito.logoutUrl:}") final String logoutUrl) { this.cognitoEnabled = cognitoEnabled; this.clientId = clientId; this.logoutUrl = logoutUrl; } @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public SecurityWebFilterChain securityWebFilterChainOauth2ResourceServer(final ServerHttpSecurity http, final ReactiveClientRegistrationRepository repo) { final ServerLogoutSuccessHandler logoutHandler = cognitoEnabled ? new CognitoOidcLogoutSuccessHandler(logoutUrl, clientId) : new OidcClientInitiatedServerLogoutSuccessHandler(repo); return http .cors().and() .csrf().disable() .securityMatcher(new PathPatternParserServerWebExchangeMatcher("/ingestion/**")) .authorizeExchange(e -> e .pathMatchers("/ingestion/entities").permitAll() .pathMatchers("/actuator/**").permitAll() .pathMatchers("/**").authenticated()) .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::jwt) .logout() .logoutSuccessHandler(logoutHandler) .and() .build(); } @Bean public SecurityWebFilterChain securityWebFilterChainOauth2Client(final ServerHttpSecurity http, final ReactiveClientRegistrationRepository repo) { final ServerLogoutSuccessHandler logoutHandler = cognitoEnabled ? new CognitoOidcLogoutSuccessHandler(logoutUrl, clientId) : new OidcClientInitiatedServerLogoutSuccessHandler(repo); return http .cors().and() .csrf().disable() .securityMatcher(new PathPatternParserServerWebExchangeMatcher("/**")) .authorizeExchange(e -> e .pathMatchers("/health", "/favicon.ico").permitAll() .pathMatchers("/**").authenticated()) .oauth2Login(Customizer.withDefaults()) .logout() .logoutSuccessHandler(logoutHandler) .and() .build(); } } SheriffBariev/abariev package ru.job4j.loop; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; /** * Шахматная доска. * @author . * @since 28.09.2017 */ public class BoardTest { /** * Test board 3x3. */ @Test public void whenPaintBoardWithWidthThreeAndHeightThreeThenStringWithThreeColsAndThreeRows() { Board board = new Board(); String result = board.paint(3, 3); final String line = System.getProperty("line.separator"); String expected = String.format("x x\n x \nx x\n", line, line, line); assertThat(result, is(expected)); } /** * Test board 5x4. */ @Test public void whenPaintBoardWithWidthFiveAndHeightFourThenStringWithFiveColsAndFourRows() { Board board = new Board(); String outcome = board.paint(5, 4); final String line = System.getProperty("line.separator"); String expected = String.format("x x x\n x x \nx x x\n x x \n", line, line, line, line); assertThat(outcome, is(expected)); } } backend/src/main/java/com/darass/comment/service/CommentService.java package com.darass.comment.service; import com.darass.comment.domain.Comment; import com.darass.comment.domain.CommentLike; import com.darass.comment.domain.CommentStat; import com.darass.comment.domain.Comments; import com.darass.comment.domain.SortOption; import com.darass.comment.dto.CommentCreateRequest; import com.darass.comment.dto.CommentDeleteRequest; import com.darass.comment.dto.CommentReadRequest; import com.darass.comment.dto.CommentReadRequestByPagination; import com.darass.comment.dto.CommentReadRequestBySearch; import com.darass.comment.dto.CommentReadRequestInProject; import com.darass.comment.dto.CommentReadSecretCommentRequest; import com.darass.comment.dto.CommentResponse; import com.darass.comment.dto.CommentResponses; import com.darass.comment.dto.CommentStatRequest; import com.darass.comment.dto.CommentStatResponse; import com.darass.comment.dto.CommentUpdateRequest; import com.darass.comment.repository.CommentCountStrategyFactory; import com.darass.comment.repository.CommentRepository; import com.darass.commentalarm.domain.CommentAlarm; import com.darass.commentalarm.domain.CommentAlarmMachine; import com.darass.commentalarm.domain.CommentAlarmType; import com.darass.commentalarm.repository.CommentAlarmRepository; import com.darass.exception.ExceptionWithMessageAndCode; import com.darass.project.domain.Project; import com.darass.project.repository.ProjectRepository; import com.darass.user.domain.GuestUser; import com.darass.user.domain.User; import com.darass.user.dto.UserResponse; import com.darass.user.repository.UserRepository; import java.time.LocalTime; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @RequiredArgsConstructor @Transactional @Service public class CommentService { private final CommentRepository commentRepository; private final ProjectRepository projectRepository; private final UserRepository userRepository; private final CommentAlarmRepository commentAlarmRepository; private final CommentCountStrategyFactory commentCountStrategyFactory; private final CommentAlarmMachine commentAlarmMachine; public CommentResponse save(User user, CommentCreateRequest commentRequest) { if (!user.isLoginUser()) { user = saveGuestUser(commentRequest); user.setUserType("GuestUser"); } Project project = findProjectBySecretKey(commentRequest); if (Objects.isNull(commentRequest.getParentId())) { return saveComment(user, commentRequest, project); } return saveSubComment(user, commentRequest, project); } @Transactional(readOnly = true) public CommentResponses findAllCommentsByUrlAndProjectKey(User user, CommentReadRequest request) { Comments comments = new Comments(commentRepository .findByUrlAndProjectSecretKeyAndParentId(request.getUrl(), request.getProjectKey(), null, SortOption.getMatchedSort(request.getSortOption()))); Project project = projectRepository.findBySecretKey(request.getProjectKey()) .orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_PROJECT::getException); comments.handleSecretComments(user, project.getAdminUserId()); return new CommentResponses(comments.totalCommentWithSubComment(), 1, comments.getComments().stream() .map(comment -> CommentResponse.of(comment, UserResponse.of(comment.getUser()))) .collect(Collectors.toList())); } @Transactional(readOnly = true) public CommentResponses findAllCommentsByUrlAndProjectKeyUsingPagination(CommentReadRequestByPagination request) { int pageBasedIndex = request.getPage() - 1; try { Page comments = commentRepository .findByUrlAndProjectSecretKeyAndParentId(request.getUrl(), request.getProjectKey(), null, PageRequest.of(pageBasedIndex, request.getSize(), SortOption.getMatchedSort(request.getSortOption()))); return new CommentResponses(new Comments(comments.toList()).totalCommentWithSubComment(), comments.getTotalPages(), comments.stream() .map(comment -> CommentResponse.of(comment, UserResponse.of(comment.getUser()))) .collect(Collectors.toList())); } catch (IllegalArgumentException e) { throw ExceptionWithMessageAndCode.PAGE_NOT_POSITIVE_EXCEPTION.getException(); } } @Transactional(readOnly = true) public CommentResponses findAllCommentsInProject( CommentReadRequestInProject request) { int pageBasedIndex = request.getPage() - 1; try { Page comments = commentRepository .findByProjectSecretKeyAndCreatedDateBetween( request.getProjectKey(), request.getStartDate().atTime(LocalTime.MIN), request.getEndDate().atTime(LocalTime.MAX), PageRequest.of(pageBasedIndex, request.getSize(), SortOption.getMatchedSort(request.getSortOption())) ); return new CommentResponses(comments.getTotalElements(), comments.getTotalPages(), comments.stream() .map(comment -> CommentResponse.of(comment, UserResponse.of(comment.getUser()))) .collect(Collectors.toList())); } catch (IllegalArgumentException e) { throw ExceptionWithMessageAndCode.PAGE_NOT_POSITIVE_EXCEPTION.getException(); } } @Transactional(readOnly = true) public CommentResponses findAllCommentsInProjectUsingSearch( CommentReadRequestBySearch request) { int pageBasedIndex = request.getPage() - 1; try { Page comments = commentRepository .findByProjectSecretKeyAndContentContainingAndCreatedDateBetween( request.getProjectKey(), request.getKeyword(), request.getStartDate().atTime(LocalTime.MIN), request.getEndDate().atTime(LocalTime.MAX), PageRequest.of(pageBasedIndex, request.getSize(), SortOption.getMatchedSort(request.getSortOption())) ); return new CommentResponses(comments.getTotalElements(), comments.getTotalPages(), comments.stream() .map(comment -> CommentResponse.of(comment, UserResponse.of(comment.getUser()))) .collect(Collectors.toList())); } catch (IllegalArgumentException e) { throw ExceptionWithMessageAndCode.PAGE_NOT_POSITIVE_EXCEPTION.getException(); } } public void updateComment(Long id, User user, CommentUpdateRequest request) { user = findRegisteredUser(user, request.getGuestUserId(), request.getGuestUserPassword()); Comment comment = findCommentById(id); validateCommentUpdatableOrReadableByUser(user, comment); comment.changeContent(request.getContent()); comment.changeSecretStatus(request.isSecret()); commentRepository.save(comment); } public void delete(Long id, User user, CommentDeleteRequest request) { user = findRegisteredUser(user, request.getGuestUserId(), request.getGuestUserPassword()); Comment comment = findCommentById(id); User adminUser = comment.getProject().getUser(); validateCommentDeletableByUser(user, adminUser, comment); commentRepository.deleteById(id); if (comment.isSubComment()) { Comment parent = comment.getParent(); parent.deleteSubComment(id); } } public void toggleLike(Long id, User user) { Comment comment = commentRepository.findById(id) .orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_COMMENT::getException); if (comment.isLikedByUser(user)) { comment.deleteCommentLikeByUser(user); return; } sendCommentLikeAlarm(comment, CommentAlarmType.CREATE_COMMENT_LIKE, user); comment.addCommentLike(CommentLike.builder() .comment(comment) .user(user) .build()); } public CommentStatResponse giveStat(CommentStatRequest request) { List commentStats = commentCountStrategyFactory.findStrategy(request.getPeriodicity()) .calculateCount(request.getProjectKey(), request.getStartDate().atTime(LocalTime.MIN), request.getEndDate().atTime(LocalTime.MAX)); return new CommentStatResponse(commentStats); } public CommentResponse readSecretComment(Long id, User user, CommentReadSecretCommentRequest request) { user = findRegisteredUser(user, request.getGuestUserId(), request.getGuestUserPassword()); Comment comment = findCommentById(id); validateCommentUpdatableOrReadableByUser(user, comment); return CommentResponse.of(comment, UserResponse.of(user)); } private void validateCommentUpdatableOrReadableByUser(User user, Comment comment) { if (comment.isCommentWriter(user)) { return; } throw ExceptionWithMessageAndCode.UNAUTHORIZED_FOR_COMMENT.getException(); } private void validateCommentDeletableByUser(User user, User adminUser, Comment comment) { if (user.isSameUser(adminUser) || comment.isCommentWriter(user)) { return; } throw ExceptionWithMessageAndCode.UNAUTHORIZED_FOR_COMMENT.getException(); } private Comment findCommentById(Long id) { return commentRepository.findById(id) .orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_COMMENT::getException); } private User findRegisteredUser(User user, Long guestUserId, String guestUserPassword) { if (!user.isLoginUser()) { user = userRepository.findById(guestUserId) .orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_USER::getException); validateGuestUser(user, guestUserPassword); } return user; } private void validateGuestUser(User user, String password) { if (!user.isValidGuestPassword(password)) { throw ExceptionWithMessageAndCode.INVALID_GUEST_PASSWORD.getException(); } } private User saveGuestUser(CommentCreateRequest commentRequest) { User user = GuestUser.builder() .nickName(commentRequest.getGuestNickName()) .password(commentRequest.getGuestPassword()) .build(); return userRepository.saveAndFlush(user); } private Project findProjectBySecretKey(CommentCreateRequest commentRequest) { return projectRepository.findBySecretKey(commentRequest.getProjectSecretKey()) .orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_PROJECT::getException); } private CommentResponse saveComment(User user, CommentCreateRequest commentRequest, Project project) { Comment comment = Comment.builder() .user(user) .content(commentRequest.getContent()) .project(project) .url(commentRequest.getUrl()) .secret(commentRequest.isSecret()) .build(); sendCommentAlarm(comment, CommentAlarmType.CREATE_COMMENT, project.getUser()); return CommentResponse.of(commentRepository.save(comment), UserResponse.of(comment.getUser())); } private CommentResponse saveSubComment(User user, CommentCreateRequest commentRequest, Project project) { Comment parentComment = commentRepository.findById(commentRequest.getParentId()) .orElseThrow(ExceptionWithMessageAndCode.NOT_FOUND_COMMENT::getException); validateSubCommentable(parentComment); Comment comment = Comment.builder() .user(user) .content(commentRequest.getContent()) .project(project) .url(commentRequest.getUrl()) .parent(parentComment) .secret(commentRequest.isSecret()) .build(); sendCommentAlarm(comment, CommentAlarmType.CREATE_SUB_COMMENT, parentComment.getUser()); return CommentResponse.of(commentRepository.save(comment), UserResponse.of(comment.getUser())); } private void sendCommentAlarm(Comment comment, CommentAlarmType commentAlarmType, User receiver) { if (comment.isCommentWriter(receiver)) { return; } CommentAlarm commentAlarm = comment.createCommentAlarm(commentAlarmType, receiver); commentAlarmRepository.save(commentAlarm); commentAlarmMachine.sendMessage(commentAlarm); } private void sendCommentLikeAlarm(Comment comment, CommentAlarmType commentAlarmType, User sender) { if (comment.isCommentWriter(sender)) { return; } CommentAlarm commentAlarm = comment.createCommentLikeAlarm(commentAlarmType, sender); commentAlarmRepository.save(commentAlarm); commentAlarmMachine.sendMessage(commentAlarm); } private void validateSubCommentable(Comment parentComment) { if (parentComment.isSubComment()) { throw ExceptionWithMessageAndCode.INVALID_SUB_COMMENT_INDEX.getException(); } } }cufir-s-ecore/src/main/java/org/cufir/s/ecore/iso20022/analysis/SemanticMarkupAnalysis.java1-10 package org.cufir.s.ecore.iso20022.analysis; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.apache.commons.beanutils.BeanUtils; import org.cufir.s.ecore.bean.EcoreSemanticMarkup; import org.cufir.s.ecore.iso20022.SemanticMarkup; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.xmi.XMIResource; /** * 解析SemanticMarkup */ public class SemanticMarkupAnalysis { // EcoreSemanticMarkup private static List items = new ArrayList(); /** * 解析SemanticMarkup * @param uuid * @param objType * @param ups * @param resource */ public static void parse(String uuid, String objType,EList ups,XMIResource resource) { for(SemanticMarkup c:ups) { EcoreSemanticMarkup po=new EcoreSemanticMarkup(); try { BeanUtils.copyProperties(po, c); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } String cuuid=resource.getID(c); po.setId(cuuid); po.setObjId(uuid); po.setObjType(objType); po.setCreateUser("Import"); po.setIsfromiso20022("1"); if(c.getElements()!=null && !c.getElements().isEmpty()) { SemanticMarkupElementAnalysis.parse(cuuid, c.getElements(), resource); } items.add(po); } } public static List getItems() { return items; } public static void clear() { items.clear(); } } package com.cotemig.SpringBDController.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cotemig.SpringBDController.model.Cargo; import com.cotemig.SpringBDController.repository.CargoRepository; @Service public class CargoServiceImpl implements CargoService { @Autowired CargoRepository CargoRepository; @Override public Optional getById(Integer id) { return CargoRepository.findById(id); } @Override public List getAll() { return CargoRepository.findAll(); } @Override public void deleteAll() { CargoRepository.deleteAll(); } @Override public void deleteById(Integer id) { CargoRepository.deleteById(id); } @Override public void updateById(Integer id, Cargo cargo) { Optional getCargo = getById(id); getCargo.get().setNome(cargo.getNome()); getCargo.get().setSalario(cargo.getSalario()); CargoRepository.save(cargo); } @Override public void update(Cargo cargo) { CargoRepository.save(cargo); } @Override public void insert(Cargo cargo) { CargoRepository.save(cargo); } }package com.hrym.app.service; import com.hrym.rpc.app.dao.model.VO.DateVO; import com.hrym.rpc.app.util.Result; import java.util.List; /** * Created by hrym13 on 2017/12/26. */ public interface TcalendarMgrService { /** * 日历显示 * @param page * @param rows * @return */ Result findAllTcalend(Integer page,Integer rows); /** * 日历修改 * @param tcalendar * @return */ Result updateAllTcalend(DateVO tcalendar); /** * 日历添加 * @param tcalendar * @return */ Result insertAllTcalend(DateVO tcalendar); /** * 删除 * @param Id * @return */ Result deleteAllTcalend(Integer Id); /** * 根据ID查找内容 * @param Id * @return */ DateVO FindTcalendById(Integer Id); } tws-api/src/main/java/com/ib/client/OrderState.java /* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved. This code is subject to the terms * and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */ package com.ib.client; public class OrderState { private String m_status; private String m_initMargin; private String m_maintMargin; private String m_equityWithLoan; private double m_commission; private double m_minCommission; private double m_maxCommission; private String m_commissionCurrency; private String m_warningText; // Get public double commission() { return m_commission; } public double maxCommission() { return m_maxCommission; } public double minCommission() { return m_minCommission; } public OrderStatus status() { return OrderStatus.get(m_status); } public String getStatus() { return m_status; } public String commissionCurrency() { return m_commissionCurrency; } public String equityWithLoan() { return m_equityWithLoan; } public String initMargin() { return m_initMargin; } public String maintMargin() { return m_maintMargin; } public String warningText() { return m_warningText; } // Set public void commission(double v) { m_commission = v; } public void commissionCurrency(String v) { m_commissionCurrency = v; } public void equityWithLoan(String v) { m_equityWithLoan = v; } public void initMargin(String v) { m_initMargin = v; } public void maintMargin(String v) { m_maintMargin = v; } public void maxCommission(double v) { m_maxCommission = v; } public void minCommission(double v) { m_minCommission = v; } public void status(OrderStatus v) { m_status = ( v == null ) ? null : v.name(); } public void status(String v) { m_status = v; } public void warningText(String v) { m_warningText = v; } OrderState() { this (null, null, null, null, 0.0, 0.0, 0.0, null, null); } OrderState(String status, String initMargin, String maintMargin, String equityWithLoan, double commission, double minCommission, double maxCommission, String commissionCurrency, String warningText) { m_status = status; m_initMargin = initMargin; m_maintMargin = maintMargin; m_equityWithLoan = equityWithLoan; m_commission = commission; m_minCommission = minCommission; m_maxCommission = maxCommission; m_commissionCurrency = commissionCurrency; m_warningText = warningText; } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null) return false; OrderState state = (OrderState)other; if (m_commission != state.m_commission || m_minCommission != state.m_minCommission || m_maxCommission != state.m_maxCommission) { return false; } if (Util.StringCompare(m_status, state.m_status) != 0 || Util.StringCompare(m_initMargin, state.m_initMargin) != 0 || Util.StringCompare(m_maintMargin, state.m_maintMargin) != 0 || Util.StringCompare(m_equityWithLoan, state.m_equityWithLoan) != 0 || Util.StringCompare(m_commissionCurrency, state.m_commissionCurrency) != 0) { return false; } return true; } } package top.yokey.shopnc.base; import android.graphics.Bitmap; import android.os.Environment; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * 文件管理 * * @author MapStory * @ qq 1002285057 * @ project https://gitee.com/MapStory/ShopNc-Android */ @SuppressWarnings("ALL") public class BaseFileClient { private static volatile BaseFileClient instance; private String packName; public static BaseFileClient get() { if (instance == null) { synchronized (BaseFileClient.class) { if (instance == null) { instance = new BaseFileClient(); } } } return instance; } public void init(String packName) { this.packName = packName; createCachePath(); createImagePath(); createDownPath(); } public boolean hasSDCard() { String str = Environment.getExternalStorageState(); return str.equals(Environment.MEDIA_MOUNTED); } public String getRootPath() { if (hasSDCard()) { return Environment.getExternalStorageDirectory().getAbsolutePath() + "/"; } else { return Environment.getDataDirectory().getAbsolutePath() + "/data/"; } } public String getDataPath() { return getRootPath() + "/Android/data/" + packName + "/"; } public String getDownPath() { return getDataPath() + "down/"; } public String getCachePath() { return getDataPath() + "cache/"; } public String getImagePath() { return getDataPath() + "image/"; } public void createImagePath() { File file = new File(getImagePath()); if (!file.exists()) { file.mkdirs(); } } public void createCachePath() { File file = new File(getCachePath()); if (!file.exists()) { file.mkdirs(); } } public void createDownPath() { File file = new File(getDownPath()); if (!file.exists()) { file.mkdirs(); } } public File createImage(String name, Bitmap bitmap) { String path = getImagePath() + name + ".jpg"; try { File file = new File(path); if (file.exists()) { file.delete(); } FileOutputStream fileOutputStream; file.createNewFile(); fileOutputStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); return file; } catch (IOException e) { e.printStackTrace(); return null; } } } 1-10 package cn.fql.account.dao.mapper; import cn.fql.account.model.domain.AcctType; import tk.mybatis.mapper.common.Mapper; public interface AcctTypeMapper extends Mapper { }1-10 package com.iluwatar.visitor; /** * * Sergeant * */ public class Sergeant extends Unit { public Sergeant(Unit... children) { super(children); } @Override public void accept(UnitVisitor visitor) { visitor.visitSergeant(this); super.accept(visitor); } @Override public String toString() { return "sergeant"; } } package com.polygraphene.alvr; public interface NALParser { int getNalListSize(); // Wait next NAL and return. // If notifyWaitingThread was called, interrupt call and return null. NAL waitNal(); NAL getNal(); void recycleNal(NAL nal); void flushNALList(); void notifyWaitingThread(); void clearStopped(); } package net; import net.minecraft.client.stream.Metadata; public class m7 { public static String b(Metadata var0) { return var0.func_152810_c(); } public static String a(Metadata var0) { return var0.func_152809_a(); } public static String c(Metadata var0) { return var0.func_152806_b(); } } package com.mdroid.view.recyclerView.stickyHeader; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; /** * The adapter to assist the {@link StickyHeaderDecoration} in creating and binding the header * views. * * @param the header view holder */ public interface StickyHeaderAdapter { /** * Returns the header id for the item at the given position. * * @param position the item position * @return the header id */ long getHeaderId(int position); /** * Creates a new header ViewHolder. * * @param parent the header's view parent * @return a view holder for the created view */ T onCreateHeaderViewHolder(ViewGroup parent); /** * Updates the header view to reflect the header data for the given position * * @param viewholder the header view holder * @param position the header's item position */ void onBindHeaderViewHolder(T viewholder, int position); boolean isSkip(int position); }aries/common/common-transaction/src/main/java/org/aries/tx/participant/Participant.java package org.aries.tx.participant; import org.aries.tx.exception.SystemException; import org.aries.tx.exception.WrongStateException; import org.aries.tx.vote.Vote; /** * The Participant interface. */ public interface Participant { /** * Perform any work necessary to allow it to either commit or rollback * the work performed by the Web service under the scope of the * transaction. The implementation is free to do whatever it needs to in * order to fulfill the implicit contract between it and the coordinator. * * @return an indication of whether it can prepare or not. * @see Vote */ public Vote prepare() throws WrongStateException, SystemException; /** * The participant should make permanent the work that it controls. */ public void commit() throws WrongStateException, SystemException; /** * The participant should undo the work that it controls. The participant * will then return an indication of whether or not it succeeded. */ public void rollback() throws WrongStateException, SystemException; /** * During recovery the participant can enquire as to the status of the * transaction it was registered with. If that transaction is no longer * available (has rolled back) then this operation will be invoked by the * coordination service. */ public void unknown() throws SystemException; /** * During recovery the participant can enquire as to the status of the * transaction it was registered with. If an error occurs (e.g., the * transaction service is unavailable) then this operation will be invoked. */ void error() throws SystemException; } package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import org.firstinspires.ftc.robotcontroller.internal.FtcRobotControllerActivity; import org.opencv.android.CameraBridgeViewBase; import org.opencv.bioinspired.Retina; import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.MatOfDouble; import org.opencv.core.MatOfInt; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import org.opencv.imgproc.Moments; import java.util.ArrayList; import java.util.List; @TeleOp(name="Some Linear OpMode", group="OpMode") public class testing extends LinearOpMode implements CameraBridgeViewBase.CvCameraViewListener2{ Retina retina; @Override public void runOpMode() { // Initialize hardware code goes here waitForStart(); startOpenCV(this); while (opModeIsActive()) { // Do stuff } stopOpenCV(); } @Override public void onCameraViewStarted(int width, int height) { retina = Retina.create(new Size(320,180)); retina.setup(); retina.clearBuffers(); } @Override public void onCameraViewStopped() { } @Override public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) { Mat input = inputFrame.rgba().clone(); Imgproc.resize(input, input, new Size(320, (int) Math.round((320/input.size().width)*input.size().height))); inputFrame.rgba().release(); inputFrame.gray().release(); retina.applyFastToneMapping(input,input); Mat yuv = new Mat(); Imgproc.cvtColor(input,yuv,Imgproc.COLOR_BGR2YUV); Mat uChan = new Mat(); Core.extractChannel(yuv,uChan,1); Mat b = new Mat(); Imgproc.medianBlur(uChan,uChan,9); //Imgproc.filter2D(uChan,uChan,-1,Imgproc.getStructuringElement(Imgproc.MORPH_RECT,new Size(1,1))); //showResult(b); //showResult(uChan); Mat a = new Mat(); Imgproc.threshold(uChan,a,145,255,Imgproc.THRESH_BINARY); //Defines all Mats that will be used in the program Mat lab = new Mat(); Mat labThreshBinary = new Mat(); Mat labThreshOtsu = new Mat(); Mat labThresh = new Mat(); Mat hsv = new Mat(); Mat hChan = new Mat(); Mat bChan = new Mat(); //Converts input from RGB color format to Lab color format, then extracts the b channel //Lab is based on the opponent color model, and the b channel represents the blue-yellow axis, so it will be useful in finding yellow colors Imgproc.cvtColor(input,lab,Imgproc.COLOR_RGB2Lab); Core.extractChannel(lab,bChan,2); //Removes used images from memory to avoid overflow crashes lab.release(); /*Thresholds the b channel in two different ways to get a binary filter (correct or not correct) for all detected yellow pixels The binary threshold selects all pixels with a b value above 145 The Otsu threshold does the same thing as the binary threshold, but tries to dynamically select the threshold value (the value above which a pixel is considered yellow) to divide the image by contrast. The binary threshold is very inclusive, for reasons that will become clear later*/ double stdm1[] = calcStdDevMean(bChan); Imgproc.threshold(bChan,labThreshBinary,160,255,Imgproc.THRESH_BINARY); Imgproc.threshold(bChan,labThreshOtsu,0,255,Imgproc.THRESH_OTSU); //showResult(labThreshBinary); /*Otsu threshold will usually do a good job of segmenting the cubes from the rest of the image (as they contrast heavily with the background), but does not function well when there are no cubes in the image, as the optimal contrast threshold will not necessarily be filtering for yellow. The binary threshold, however, is not affected by the absence of the cubes, and so by performing a bitwise and of the images, we keep only the area where both thresholds agree, which accounts for times when the cube is not in the image while keeping the otsu threshold's power*/ Core.bitwise_and(labThreshBinary,labThreshOtsu,labThresh); //showResult(labThreshBinary); //showResult(labThreshOtsu); //Removes used images from memory to avoid overflow crashes bChan.release(); labThreshBinary.release(); labThreshOtsu.release(); //Converts input from RGB color format to HSV color format, then extracts the h channel //HSV stands for hue, saturation, value. We are only interested in the h channel, which stores color information //Because of its division of color into a separate channel, HSV format is resistant to lighting changes and so is good for color filtering Imgproc.cvtColor(input,hsv,Imgproc.COLOR_RGB2HSV_FULL); Core.extractChannel(hsv,hChan,0); Mat sChan = new Mat(); Core.extractChannel(hsv,sChan,1); Mat temp = new Mat(hChan.size(),hChan.type(),new Scalar(50.59)); Mat temp2 = new Mat(); Core.absdiff(hChan,temp,temp2); Core.bitwise_not(temp2,temp2); Core.bitwise_and(temp2,sChan,temp2); Imgproc.medianBlur(temp2,temp2,9); //showResult(temp2); double stdm2[] = calcStdDevMean(temp2); Core.MinMaxLocResult minMaxLocResult = Core.minMaxLoc(temp2); Imgproc.circle(input,minMaxLocResult.maxLoc,10,new Scalar(0,0,0),-1); //Imgproc.adaptiveThreshold(temp2,temp2,255,Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C,Imgproc.THRESH_BINARY,13,0); //showResult(temp2); //Imgproc.threshold(temp2,temp2,0.75*minMaxLocResult.maxVal,255,Imgproc.THRESH_OTSU); //showResult(sChan); //showResult(labThresh); //Core.bitwise_and(temp2,labThresh,labThresh); //showResult(temp2); //showResult(labThresh); Core.bitwise_and(labThresh,a,labThresh); //showResult(labThresh); //showResult(temp2); Imgproc.morphologyEx(labThresh,labThresh,Imgproc.MORPH_CLOSE,Imgproc.getStructuringElement(Imgproc.MORPH_RECT,new Size(5,5))); //Masks image so that the only h regions detected are those that were also detected by the Lab otsu and binary thresholds Mat masked = new Mat(); Core.bitwise_and(hChan,labThresh,masked); //Removes used images from memory to avoid overflow crashes hsv.release(); hChan.release(); /*Computes the distance transform of the Lab image threshold and then does a binary threshold of that The distance transform sorts pixels by their distance from the nearest black pixel. Larger distance means a higher value This is done here in order to reduce noise, which will have a small distance from black pixels*/ Mat distanceTransform = new Mat(); Mat thresholded = new Mat(); Imgproc.distanceTransform(labThresh,distanceTransform,Imgproc.DIST_L2,3); distanceTransform.convertTo(distanceTransform,CvType.CV_8UC1); Mat msk = new Mat(); Imgproc.threshold(distanceTransform,msk,0,255,Imgproc.THRESH_BINARY); double stdm[] = calcStdDevMean(distanceTransform,msk); Imgproc.threshold(distanceTransform,thresholded,stdm[1]/stdm[0],255,Imgproc.THRESH_BINARY); //showResult(thresholded); //showResult(thresholded); //Removes used images from memory to avoid overflow crashes distanceTransform.release(); //Performs a gaussian blur on the threshold to help eliminate remaining high frequency noise Imgproc.GaussianBlur(thresholded,thresholded,new Size(3,3),0); //Finds all detected blobs in the thresholded distance transform and finds their centers List centerShapes = new ArrayList<>(); Imgproc.findContours(thresholded,centerShapes,new Mat(),Imgproc.RETR_EXTERNAL,Imgproc.CHAIN_APPROX_SIMPLE); thresholded.release(); List centers = new ArrayList<>(); for(MatOfPoint shape : centerShapes) { Moments moments = Imgproc.moments(shape); centers.add(new Point(moments.m10/moments.m00,moments.m01/moments.m00)); shape.release(); } //Removes used images from memory to avoid overflow crashes //labThresh.release(); //Imgproc.bilateralFilter(masked,dst,5,5,5); //Imgproc.GaussianBlur(labThresh,labThresh,new Size(5,5),0); //Calculates the median value of the image double med = getMedianNonZero(masked); //Dynamically calculates the best parameters for the Canny edge detector to find the edges of all of the detected shapes //Edges are represented as a binary image, with "on" pixels along the edge and "off" pixels everywhere else Mat edges = new Mat(); double sigma = 0.33; Imgproc.Canny(masked,edges,(int) Math.round(Math.max(0,(1-sigma)*med)),(int) Math.round(Math.min(255,1+sigma)*med)); //showResult(masked); //Enhances edge information Imgproc.dilate(edges,edges,Imgproc.getStructuringElement(Imgproc.MORPH_CROSS,new Size(2,2)),new Point(),1); //showResult(edges); //Turns edges into a list of shapes List contours = new ArrayList<>(); Imgproc.findContours(edges,contours,new Mat(),Imgproc.RETR_LIST,Imgproc.CHAIN_APPROX_SIMPLE); //showResult(edges); //Removes used images from memory to avoid overflow crashes edges.release(); MatOfPoint bestContour = new MatOfPoint(); double maxMean = 0; int detected = 0; List usedx = new ArrayList<>(); List usedy = new ArrayList<>(); //Loops through the list of shapes (contours) and finds the ones most likely to be a cube for (int i = 0; i < contours.size(); i++) { //Approximates the shape to smooth out excess edges MatOfPoint2f approx = new MatOfPoint2f(); double peri = Imgproc.arcLength(new MatOfPoint2f(contours.get(i).toArray()), true); Imgproc.approxPolyDP(new MatOfPoint2f(contours.get(i).toArray()), approx, 0.1 * peri, true); //0.1 is a detail factor, higher factor = lower detail, lower factor = higher detail MatOfPoint approxMop = new MatOfPoint(approx.toArray()); //Calculates a convex hull of the shape, covering up any dents MatOfPoint convex = hull(approxMop); //Does a simple size check to eliminate extremely small contours if (Imgproc.contourArea(approxMop) > 100) { //Checks if one of the distance transform centers is contained within the shape //Imgproc.putText(input,"1",new Point(box.x, box.y), Imgproc.FONT_HERSHEY_COMPLEX, 1, new Scalar(0, 0, 0), 3); Point center = getCenter(approxMop); if (containsPoint(approx,centers) && !(usedx.contains(center.x) && usedy.contains(center.y))) { usedx.add(center.x); usedy.add(center.y); Rect box = Imgproc.boundingRect(convex); Mat roi = temp2.submat(box); double[] sm = calcStdDevMean(roi); if(sm[1] > maxMean) { bestContour = new MatOfPoint(convex.toArray()); maxMean = sm[1]; } } } //Removes used images from memory to avoid overflow crashes contours.get(i).release(); approx.release(); approxMop.release(); } if(!bestContour.empty()) { List g = new ArrayList<>(); g.add(bestContour); Imgproc.drawContours(input, g, -1, new Scalar(0, 255, 0), 1); } //Removes used images from memory to avoid overflow crashes masked.release(); //Empties the cosmic garbage can System.gc(); Mat returnImage = labThresh; Imgproc.resize(returnImage,returnImage,new Size(1280,720)); return returnImage; } //Check if polygon contains any point in a list of points. True if polygon contains any point in the list, false otherwise private boolean containsPoint(MatOfPoint2f polygon, List points) { boolean inPolygon = false; for(Point p : points) { if(Imgproc.pointPolygonTest(polygon, p, false) >= 0) { //returns value > 0 if in polygon, 0 if on the edge of the polygon, and < 0 if outside the polygon inPolygon = true; } } return inPolygon; } private Point getCenter(MatOfPoint c) { Moments m = Imgproc.moments(c); return new Point(m.m10/m.m00,m.m01/m.m00); } //Calculates rectangle completely inside the shape private Rect calcBox(MatOfPoint c) { //Calculates center of the shape Moments m = Imgproc.moments(c); Point center = new Point(m.m10/m.m00,m.m01/m.m00); //Gets list of the shape's corners List corners = c.toList(); //Finds the smallest distance from the center to one of the corners double minDst = Integer.MAX_VALUE; double dst; for(Point p : corners) { dst = dist(center,p); minDst = dst < minDst ? dist(center,p) : minDst; //min distance equals the distance between the center and the current corner if the distance is less than the previous min distance } //Calculate and return rectangle coordinates assuming the rectangle is inside a circle of radius minDst return new Rect(new Point(Math.round(center.x-minDst/Math.sqrt(2)),(int) Math.round(center.y-minDst/Math.sqrt(2))),new Point(Math.round(center.x+minDst/Math.sqrt(2)),(int) Math.round(center.y+minDst/Math.sqrt(2)))); } private double getMedianNonZero(Mat input) { //Turns image into a single row of pixels Mat rowMat = input.reshape(0,1); //Sort pixel values from least to greatest Mat sorted = new Mat(); Core.sort(rowMat,sorted,Core.SORT_ASCENDING); double sum = 0; int idx = 0; int loops = 0; while(sum == 0 && loops < sorted.cols() && opModeIsActive()) { sum+=sorted.get(0,loops)[0]; idx+=sorted.get(0,loops)[0] > 0 ? 1 : 0; loops++; } //Calculates median of the image. Median is the middle value of the row of sorted pixels. If there are two middle pixels, the median is their average. double median = (sum != 0 ) ? ((sorted.size().width-idx) % 2 == 1 ? sorted.get(0,(int) Math.floor(idx+((sorted.size().width-idx)/2)))[0] : (sorted.get(0,(int) (idx+(sorted.size().width-idx)/2)-1)[0]+sorted.get(0,(int) (idx+(sorted.size().width-idx)/2))[0])/2) : 0; //Removes used images from memory to avoid overflow crashes rowMat.release(); sorted.release(); return median; } //Calculates standard deviation and mean of an image. Output is a constant list of doubles with the following format: {standard deviation, mean} private double[] calcStdDevMean(Mat input) { assert input.channels() == 1: "input must only have 1 channel"; //Makes sure image is only 1 channel (ex: black and white) //Calculates image mean and standard deviation MatOfDouble std = new MatOfDouble(); MatOfDouble mean = new MatOfDouble(); Core.meanStdDev(input,mean,std); double[] output = new double[] {std.get(0,0)[0],mean.get(0,0)[0]}; //Removes used images from memory to avoid overflow crashes std.release(); mean.release(); //returns output data with the following format: {standard deviation, mean} return output; } private double[] calcStdDevMean(Mat input, Mat mask) { assert input.channels() == 1: "input must only have 1 channel"; //Makes sure image is only 1 channel (ex: black and white) //Calculates image mean and standard deviation MatOfDouble std = new MatOfDouble(); MatOfDouble mean = new MatOfDouble(); Core.meanStdDev(input,mean,std,mask); double[] output = new double[] {std.get(0,0)[0],mean.get(0,0)[0]}; //Removes used images from memory to avoid overflow crashes std.release(); mean.release(); //returns output data with the following format: {standard deviation, mean} return output; } //Gets the median value of the image private double getMedian(Mat input) { //Turns image into a single row of pixels Mat rowMat = input.reshape(0,1); //Sort pixel values from least to greatest Mat sorted = new Mat(); Core.sort(rowMat,sorted,Core.SORT_ASCENDING); //Calculates median of the image. Median is the middle value of the row of sorted pixels. If there are two middle pixels, the median is their average. double median = sorted.size().width % 2 == 1 ? sorted.get(0,(int) Math.floor(sorted.size().width/2))[0] : (sorted.get(0,(int) (sorted.size().width/2)-1)[0]+sorted.get(0,(int) sorted.size().width/2)[0])/2; //Removes used images from memory to avoid overflow crashes rowMat.release(); sorted.release(); return median; } //Calculates distance between two points private double dist(Point a, Point b) { return(Math.sqrt(Math.pow(a.x-b.x,2)+Math.pow(a.y-b.y,2))); //distance formula } //Calculates convex hull of a shape private MatOfPoint hull(MatOfPoint mopIn) { //mop = MatOfPoint //Calculates indexes of convex points on the shape MatOfInt hull = new MatOfInt(); Imgproc.convexHull(mopIn, hull, false); //Creates output shape to store convex points MatOfPoint mopOut = new MatOfPoint(); mopOut.create((int)hull.size().height,1,CvType.CV_32SC2); //Selects all convex points (at the calculated hull indices) and adds them to the output shape for(int i = 0; i < hull.size().height ; i++) { int index = (int)hull.get(i, 0)[0]; double[] point = new double[] { mopIn.get(index, 0)[0], mopIn.get(index, 0)[1] }; mopOut.put(i, 0, point); } //Removes used images from memory to avoid overflow crashes hull.release(); return mopOut; } public void startOpenCV(CameraBridgeViewBase.CvCameraViewListener2 cameraViewListener) { FtcRobotControllerActivity.turnOnCameraView.obtainMessage(1, cameraViewListener).sendToTarget(); } public void stopOpenCV() { FtcRobotControllerActivity.turnOffCameraView.obtainMessage().sendToTarget(); } }package com.prado.cerveja.controller; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.prado.cerveja.controller.page.PageWrapper; import com.prado.cerveja.model.Estilo; import com.prado.cerveja.repository.Estilos; import com.prado.cerveja.repository.filter.EstiloFilter; import com.prado.cerveja.service.CadastroEstiloService; import com.prado.cerveja.service.exception.NomeEstiloJaCadastradoException; @Controller @RequestMapping(value="/estilo") public class EstilosController { @Autowired private CadastroEstiloService cadastroEstiloService; @Autowired private Estilos estilos; @RequestMapping("/novo") public ModelAndView novo(Estilo estilo){ ModelAndView mv = new ModelAndView("estilo/CadastroEstilo"); return mv; } @RequestMapping(value = "/novo", method = RequestMethod.POST) public ModelAndView cadastra(@Valid Estilo estilo, BindingResult result, Model model, RedirectAttributes attributes){ if(result.hasErrors()){ return novo(estilo); } try { cadastroEstiloService.salvar(estilo); } catch (NomeEstiloJaCadastradoException e) { result.rejectValue("nome", e.getMessage(), e.getMessage()); return novo(estilo); } attributes.addFlashAttribute("mensagem", "Estilo salvo com sucesso!"); return new ModelAndView("redirect:/estilo/novo"); } @RequestMapping( method = RequestMethod.POST, consumes= {MediaType.APPLICATION_JSON_VALUE}) public @ResponseBody ResponseEntity salvar(@RequestBody @Valid Estilo estilo, BindingResult result ){ if (result.hasErrors()) { return ResponseEntity.badRequest().body(result.getFieldError("nome").getDefaultMessage()); } estilo = cadastroEstiloService.salvar(estilo); return ResponseEntity.ok(estilo); } @RequestMapping public ModelAndView pesquisar(EstiloFilter estilofilter, BindingResult result, @PageableDefault(size = 2) Pageable pageable, HttpServletRequest httpServletRequest){ ModelAndView mv = new ModelAndView("estilo/PesquisaEstilo"); PageWrapper pageWrapper = new PageWrapper<>(estilos.filtrar(estilofilter, pageable), httpServletRequest); mv.addObject("pagina", pageWrapper); return mv; } } /** */ package org.mobadsl.semantic.model.moba; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * * A representation of the model object 'Constraintable'. * * *

* The following features are supported: *

*
    *
  • {@link org.mobadsl.semantic.model.moba.MobaConstraintable#getConstraints Constraints}
  • *
* * @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaConstraintable() * @model interface="true" abstract="true" * @generated */ public interface MobaConstraintable extends EObject { /** * Returns the value of the 'Constraints' containment reference list. * The list contents are of type {@link org.mobadsl.semantic.model.moba.MobaConstraint}. * *

* If the meaning of the 'Constraints' containment reference list isn't clear, * there really should be more of a description here... *

* * @return the value of the 'Constraints' containment reference list. * @see org.mobadsl.semantic.model.moba.MobaPackage#getMobaConstraintable_Constraints() * @model containment="true" * @generated */ EList getConstraints(); } // MobaConstraintable TlsAttacker/TLS-AttackerTLS/src/main/java/de/anonymous/nds/tlsattacker/tls/constants/HeartbeatByteLength.java /** * TLS-Attacker - Anonymous submission * * Licensed under Apache License 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package anonymous.tlsattacker.tls.constants; /** * @author anonymous anonymous <> */ public class HeartbeatByteLength { /** * payload length field */ public static final int PAYLOAD_LENGTH = 2; } 0 package com.example.iamatourist; import android.graphics.Bitmap; import android.location.Location; import java.sql.Time; import java.util.ArrayList; import java.util.Date; public class Image { private String title; private String desc; private Bitmap photo; private ArrayList tags = new ArrayList<>(); private boolean fav; private Date date; private Date time; private String location; public Image() { this.fav = false; } public Image(String title, String desc, Bitmap photo, ArrayList tags) { this.fav = false; this.title = title; this.desc = desc; this.photo = photo; this.tags = tags; } public Image(Bitmap photo, Date date, Date time, String location) { this.fav = false; this.photo = photo; this.date = date; this.time = time; this.location = location; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public boolean isFav() { return fav; } public void setFav(boolean f) { fav = f; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public Bitmap getPhoto() { return photo; } public void setPhoto(Bitmap photo) { this.photo = photo; } public ArrayList getTags() { return tags; } public void setTags(ArrayList tags) { this.tags = tags; } public void addTag(String tag) { tags.add(tag); } public void removeTag(String tag) { if (this.hasTag(tag)) { tags.remove(tag); } } public String getTagAt(Integer pos) { return tags.get(pos); } public boolean hasTag(String tag) { return tags.contains(tag); } } package com.deltabase.everphase.api.event; public @interface EventBusSubscriber { } mbiarnes/dashboard-builder /** * Copyright (C) 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.dashboard.ui.panel.export; import org.apache.commons.lang3.StringUtils; import org.jboss.dashboard.commons.xml.XMLNode; import org.jboss.dashboard.ui.taglib.formatter.Formatter; import org.jboss.dashboard.ui.taglib.formatter.FormatterException; import org.jboss.dashboard.users.UserStatus; import org.jboss.dashboard.workspace.export.ExportSessionInfo; import org.jboss.dashboard.workspace.export.ExportVisitor; import org.jboss.dashboard.workspace.export.structure.ImportResult; import org.jboss.dashboard.security.BackOfficePermission; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; public class RenderImportPreviewFormatter extends Formatter { /** * Perform the required logic for this Formatter. Inside, the methods * setAttribute and renderFragment are intended to be used to generate the * output and set parameters for this output. * Method getParameter is intended to retrieve input parameters by name. *

* Exceptions are to be catched inside the method, and not to be thrown, normally, * formatters could use a error fragment to be displayed when an error happens * in displaying. But if the error is unexpected, it can be wrapped inside a * FormatterException. * * @param request user request * @param response response to the user * @throws org.jboss.dashboard.ui.taglib.formatter.FormatterException * in case of an unexpected exception. */ public void service(HttpServletRequest request, HttpServletResponse response) throws FormatterException { ExportSessionInfo sessionInfo = ((ExportDriver) getDriver()).getSessionInfo(); ImportResult[] results = sessionInfo.getImportResult(); if (results == null) { renderFragment("fatalError"); } else if (results.length == 0) { renderFragment("empty"); } else { renderFragment("outputStart"); boolean anyError = false; for (int i = 0; i < results.length; i++) { ImportResult result = results[i]; if (!renderImportResult(result, i)) anyError = true; } if (!anyError) renderFragment("importButton"); renderFragment("outputEnd"); } } protected boolean renderImportResult(ImportResult result, int index) { Exception error = result.getException(); List warnings = result.getWarnings(); List warningArguments = result.getWarningArguments(); setAttribute("entryName", result.getEntryName()); renderFragment("entryStart"); if (result.hasErrors()) { setAttribute("errorMessage", error.getMessage()); setAttribute("exception", error); renderFragment("errors"); } else { renderElementsInEntry(result, index); if (warnings != null && !warnings.isEmpty()) { renderFragment("warningOutputStart"); for (int j = 0; j < warnings.size(); j++) { String warningKey = (String) warnings.get(j); Object[] warningKeyArguments = (Object[]) warningArguments.get(j); setAttribute("warning", warningKey); setAttribute("arguments", warningKeyArguments); renderFragment("warningOutput"); } renderFragment("warningOutputEnd"); } } renderFragment("entryEnd"); return !result.hasErrors(); } protected void renderElementsInEntry(ImportResult result, int index) { XMLNode node = result.getRootNode(); List children = node.getChildren(); if (children == null || children.isEmpty()) { renderFragment("emptyEntry"); } else { renderFragment("entryElementsOutputStart"); BackOfficePermission createPerm = BackOfficePermission.newInstance(null, BackOfficePermission.ACTION_CREATE_WORKSPACE); boolean canCreate = UserStatus.lookup().hasPermission(createPerm); int j = 0; for (XMLNode childNode : children) { setAttribute("inputName", ExportDriver.IMPORT_PREFFIX + index + " " + j++); if (childNode.getObjectName().equals(ExportVisitor.WORKSPACE)) { if (canCreate) { setAttribute("entryElementName", getWorkspaceName( childNode )); renderFragment("workspaceEntryElement"); } } else if (childNode.getObjectName().equals(ExportVisitor.RESOURCE)) { setAttribute("entryElementName", childNode.getAttributes().getProperty("id")); renderFragment("resourceEntryElement"); } else { setAttribute("entryElementName", childNode.getObjectName()); renderFragment("entryElement"); } } renderFragment("entryElementsOutputEnd"); } } private String getWorkspaceName(XMLNode childNode) { String currentLocale = getLocaleManager().getCurrentLang(); String ws_id = childNode.getAttributes().getProperty( "id" ); String ws_title = null; String ws_name = null; for (XMLNode child : childNode.getChildren()) { if ( "param".equalsIgnoreCase( child.getObjectName() ) ) { String lang = child.getAttributes().getProperty( "lang" ); if ( StringUtils.isBlank( lang ) || !lang.equalsIgnoreCase( currentLocale ) ) continue; String key = child.getAttributes().getProperty( "name" ); String value = child.getAttributes().getProperty( "value" ); if ( "title".equalsIgnoreCase( key ) ) { ws_title = value; } else if ( "name".equalsIgnoreCase( key ) ) { ws_name = value; } } } // Preferably return the title, if none is available, the name and only last the id return StringUtils.isNotBlank( ws_title ) ? ws_title : ( StringUtils.isNotBlank( ws_name ) ? ws_name : ws_id ); } } package com.example.NCEPU.Student.Query; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.net.http.SslError; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.webkit.CookieManager; import android.webkit.SslErrorHandler; import android.webkit.WebChromeClient; import android.webkit.WebResourceRequest; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageButton; import android.widget.LinearLayout; import com.example.NCEPU.MainActivity; import com.example.NCEPU.R; import java.util.Map; import static com.example.NCEPU.Student.Query.QueryFragment.dip2px; public class DailyActivity extends AppCompatActivity { private ImageButton imageButton; private LinearLayout ly_back; private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_daily); imageButton = findViewById(R.id.ib_back_day); ly_back = findViewById(R.id.ly_back_day); imageButton.setOnClickListener(v -> onBackPressed()); setHeight(); webView = findViewById(R.id.daily_reporting); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setDomStorageEnabled(true); webView.getSettings().setBlockNetworkImage(false); webView.getSettings().setSupportZoom(true); webView.getSettings().setBuiltInZoomControls(true); //以下两条设置可以使页面适应手机屏幕的分辨率,完整的显示在屏幕上 //设置是否使用WebView推荐使用的窗口 webView.getSettings().setUseWideViewPort(true); //设置WebView加载页面的模式 webView.getSettings().setLoadWithOverviewMode(true); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } webView.setWebViewClient(new DailyActivity.MyWebViewClient()); webView.setWebChromeClient(new DailyActivity.MyWebChromeClient()); SharedPreferences sharedPreferences = getSharedPreferences("user_info", Context.MODE_PRIVATE); String id = sharedPreferences.getString("id", ""); String url = "https://app.ncepu.edu.cn/ncov/wap/default/index"; Map cookies_in = MainActivity.connectJWGL.cookies_innet; Map cookies = MainActivity.connectJWGL.cookies; String in = "_astraeus_session=" + cookies_in.get("_astraeus_session"); in += ";_webvpn_key=" + cookies_in.get("_webvpn_key"); in += ";webvpn_username=" + cookies_in.get("webvpn_username"); String out = "JSESSIONID=" + cookies.get("JSESSIONID"); System.out.println("huge"); System.out.println(in); System.out.println(out); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(true); // cookieManager.setCookie(url, in); // cookieManager.setCookie(url, out); // cookieManager.setCookie(url, "_astraeus_session=" + cookies_in.get("_astraeus_session")); // cookieManager.setCookie(url, "_webvpn_key=" + cookies_in.get("_webvpn_key")); // cookieManager.setCookie(url, "webvpn_username=" + cookies_in.get("webvpn_username")); // cookieManager.setCookie(url, "JSESSIONID=" + cookies.get("JSESSIONID")); // String CookieStr = cookieManager.getCookie(url); // System.out.println("huge"); // System.out.println(CookieStr); webView.loadUrl(url); } private void setHeight() { SharedPreferences sharedPreferences = getSharedPreferences("user_info", Context.MODE_PRIVATE); float pagerHeight = sharedPreferences.getInt("pager", 0); LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams)ly_back.getLayoutParams(); linearParams.height = dip2px(this, (float) (pagerHeight * 0.062)); ly_back.setLayoutParams(linearParams); linearParams = (LinearLayout.LayoutParams)imageButton.getLayoutParams(); linearParams.height = dip2px(this, (float) (pagerHeight * 0.0325)); linearParams.width = dip2px(this, (float) (pagerHeight * 0.0279)); imageButton.setLayoutParams(linearParams); } class MyWebViewClient extends WebViewClient { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { view.loadUrl(request.getUrl().toString()); return true; } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); Log.d("WebView","onPageStarted..."); } @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); imgReset(); Log.d("WebView","onPageFinished..."); //mWvMain.loadUrl("javascript:alert('hello')"); //mWvMain.evaluateJavascript("javascript:alert('hello')",null); } public void imgReset() { webView.loadUrl("javascript:(function(){" + "var obj = document.getElementsByTagName('img'); " + "for(var i=0;i1-10 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.resourcemanager.active; import org.apache.flink.runtime.clusterframework.types.ResourceID; import org.apache.flink.runtime.clusterframework.types.ResourceIDRetrievable; import java.util.Collection; /** Callback interfaces for handling resource events from external resource managers. */ public interface ResourceEventHandler { /** * Notifies that workers of previous attempt have been recovered from the external resource * manager. * * @param recoveredWorkers Collection of worker nodes, in the deployment specific type. */ void onPreviousAttemptWorkersRecovered(Collection recoveredWorkers); /** * Notifies that the worker has been terminated. * *

See also {@link ResourceManagerDriver#requestResource}. * * @param resourceId Identifier of the terminated worker. * @param diagnostics Diagnostic message about the worker termination. */ void onWorkerTerminated(ResourceID resourceId, String diagnostics); /** * Notifies that an error has occurred that the process cannot proceed. * * @param exception Exception that describes the error. */ void onError(Throwable exception); } /* * Copyright 2020 InfAI (CC SES) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.junit.Assert; import org.junit.Test; import java.text.ParseException; public class IntervalTest { @Test public void testOpenInt() throws ParseException { Interval interval = new Interval("(0, 8)"); Assert.assertTrue(interval.check(1)); Assert.assertTrue(interval.check(2)); Assert.assertTrue(interval.check(3)); Assert.assertTrue(interval.check(4)); Assert.assertTrue(interval.check(5)); Assert.assertTrue(interval.check(6)); Assert.assertTrue(interval.check(7)); Assert.assertFalse(interval.check(-1)); Assert.assertFalse(interval.check(0)); Assert.assertFalse(interval.check(8)); Assert.assertFalse(interval.check(9)); } @Test public void testOpen2Int() throws ParseException { Interval interval = new Interval("]0, 8["); Assert.assertTrue(interval.check(1)); Assert.assertTrue(interval.check(2)); Assert.assertTrue(interval.check(3)); Assert.assertTrue(interval.check(4)); Assert.assertTrue(interval.check(5)); Assert.assertTrue(interval.check(6)); Assert.assertTrue(interval.check(7)); Assert.assertFalse(interval.check(-1)); Assert.assertFalse(interval.check(0)); Assert.assertFalse(interval.check(8)); Assert.assertFalse(interval.check(9)); } @Test public void testClosedInt() throws ParseException { Interval interval = new Interval("[0, 8]"); Assert.assertTrue(interval.check(0)); Assert.assertTrue(interval.check(1)); Assert.assertTrue(interval.check(2)); Assert.assertTrue(interval.check(3)); Assert.assertTrue(interval.check(4)); Assert.assertTrue(interval.check(5)); Assert.assertTrue(interval.check(6)); Assert.assertTrue(interval.check(7)); Assert.assertTrue(interval.check(8)); Assert.assertFalse(interval.check(-1)); Assert.assertFalse(interval.check(9)); } @Test public void testClosedFloat() throws ParseException { Interval interval = new Interval("[1.3, 2.4]"); Assert.assertEquals(interval.check(0), false); Assert.assertEquals(interval.check(1), false); Assert.assertEquals(interval.check(1.2), false); Assert.assertEquals(interval.check(1.3), true); Assert.assertEquals(interval.check(1.4), true); Assert.assertEquals(interval.check(2), true); Assert.assertEquals(interval.check(2.4), true); Assert.assertEquals(interval.check(2.5), false); Assert.assertEquals(interval.check(3), false); Assert.assertEquals(interval.check(4), false); Assert.assertEquals(interval.check(5), false); } @Test public void testOpenFloat() throws ParseException { Interval interval = new Interval("(1.3, 2.4)"); Assert.assertEquals(interval.check(0), false); Assert.assertEquals(interval.check(1), false); Assert.assertEquals(interval.check(1.2), false); Assert.assertEquals(interval.check(1.3), false); Assert.assertEquals(interval.check(1.4), true); Assert.assertEquals(interval.check(2), true); Assert.assertEquals(interval.check(2.4), false); Assert.assertEquals(interval.check(2.5), false); Assert.assertEquals(interval.check(3), false); Assert.assertEquals(interval.check(4), false); Assert.assertEquals(interval.check(5), false); } @Test public void testOpen2Float() throws ParseException { Interval interval = new Interval("]1.3, 2.4["); Assert.assertEquals(interval.check(0), false); Assert.assertEquals(interval.check(1), false); Assert.assertEquals(interval.check(1.2), false); Assert.assertEquals(interval.check(1.3), false); Assert.assertEquals(interval.check(1.4), true); Assert.assertEquals(interval.check(2), true); Assert.assertEquals(interval.check(2.4), false); Assert.assertEquals(interval.check(2.5), false); Assert.assertEquals(interval.check(3), false); Assert.assertEquals(interval.check(4), false); Assert.assertEquals(interval.check(5), false); } @Test public void testOpenInfinity() throws ParseException { Interval interval = new Interval("(*, *)"); Assert.assertEquals(interval.check(0), true); Assert.assertEquals(interval.check(1), true); Assert.assertEquals(interval.check(1.2), true); Assert.assertEquals(interval.check(1.3), true); Assert.assertEquals(interval.check(1.4), true); Assert.assertEquals(interval.check(2), true); Assert.assertEquals(interval.check(2.4), true); Assert.assertEquals(interval.check(2.5), true); Assert.assertEquals(interval.check(3), true); Assert.assertEquals(interval.check(4), true); Assert.assertEquals(interval.check(5), true); } @Test public void testOpen2Infinity() throws ParseException { Interval interval = new Interval("]*, *["); Assert.assertEquals(interval.check(0), true); Assert.assertEquals(interval.check(1), true); Assert.assertEquals(interval.check(1.2), true); Assert.assertEquals(interval.check(1.3), true); Assert.assertEquals(interval.check(1.4), true); Assert.assertEquals(interval.check(2), true); Assert.assertEquals(interval.check(2.4), true); Assert.assertEquals(interval.check(2.5), true); Assert.assertEquals(interval.check(3), true); Assert.assertEquals(interval.check(4), true); Assert.assertEquals(interval.check(5), true); } @Test public void testClosedInfinity() throws ParseException { Interval interval = new Interval("[*, *]"); Assert.assertEquals(interval.check(0), true); Assert.assertEquals(interval.check(1), true); Assert.assertEquals(interval.check(1.2), true); Assert.assertEquals(interval.check(1.3), true); Assert.assertEquals(interval.check(1.4), true); Assert.assertEquals(interval.check(2), true); Assert.assertEquals(interval.check(2.4), true); Assert.assertEquals(interval.check(2.5), true); Assert.assertEquals(interval.check(3), true); Assert.assertEquals(interval.check(4), true); Assert.assertEquals(interval.check(5), true); } } Agilicus/incubator-druid /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.timeline; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.druid.java.util.common.DateTimes; import org.apache.druid.java.util.common.Intervals; import org.apache.druid.timeline.partition.ImmutablePartitionHolder; import org.apache.druid.timeline.partition.IntegerPartitionChunk; import org.apache.druid.timeline.partition.OvershadowableInteger; import org.apache.druid.timeline.partition.PartitionHolder; import org.joda.time.Interval; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; /** */ public class VersionedIntervalTimelineTest extends VersionedIntervalTimelineTestBase { @Before public void setUp() { timeline = makeStringIntegerTimeline(); } @Test public void testFindEntryWithOverlap() { add("2011-01-01/2011-01-10", "1", 1); add("2011-01-02/2011-01-05", "2", 1); Assert.assertEquals( new ImmutablePartitionHolder<>(new PartitionHolder<>(makeSingle("1", 1))), timeline.findEntry(Intervals.of("2011-01-02T02/2011-01-04"), "1") ); } // 1|----| // 1|----| @Test(expected = UnsupportedOperationException.class) public void testOverlapSameVersionThrowException() { add("2011-01-01/2011-01-10", "1", 1); add("2011-01-05/2011-01-15", "1", 3); } // 2|----| // 2|----| // 1|----| // 1|----| @Test public void testOverlapSameVersionIsOkay() { add("2011-01-01/2011-01-10", "1", 1); add("2011-01-01/2011-01-10", "2", 2); add("2011-01-01/2011-01-10", "2", 3); add("2011-01-01/2011-01-10", "1", 4); assertValues( Collections.singletonList( createExpected("2011-01-01/2011-01-10", "2", 2) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-10")) ); } // 1|----|----| // 2|----| @Test public void testOverlapSecondBetween() { add("2011-01-01/2011-01-10", "1", 1); add("2011-01-10/2011-01-20", "1", 2); add("2011-01-05/2011-01-15", "2", 3); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-05", "1", 1), createExpected("2011-01-05/2011-01-15", "2", 3), createExpected("2011-01-15/2011-01-20", "1", 2) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 2|----| // 1|----|----| @Test public void testOverlapFirstBetween() { add("2011-01-05/2011-01-15", "2", 3); add("2011-01-01/2011-01-10", "1", 1); add("2011-01-10/2011-01-20", "1", 2); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-05", "1", 1), createExpected("2011-01-05/2011-01-15", "2", 3), createExpected("2011-01-15/2011-01-20", "1", 2) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 1|----| // 2|----| @Test public void testOverlapFirstBefore() { add("2011-01-01/2011-01-10", "1", 1); add("2011-01-05/2011-01-15", "2", 3); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-05", "1", 1), createExpected("2011-01-05/2011-01-15", "2", 3) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-15")) ); } // 2|----| // 1|----| @Test public void testOverlapFirstAfter() { add("2011-01-05/2011-01-15", "2", 3); add("2011-01-01/2011-01-10", "1", 1); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-05", "1", 1), createExpected("2011-01-05/2011-01-15", "2", 3) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-15")) ); } // 1|----| // 2|----| @Test public void testOverlapSecondBefore() { add("2011-01-05/2011-01-15", "1", 3); add("2011-01-01/2011-01-10", "2", 1); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-10", "2", 1), createExpected("2011-01-10/2011-01-15", "1", 3) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-15")) ); } // 2|----| // 1|----| @Test public void testOverlapSecondAfter() { add("2011-01-01/2011-01-10", "2", 3); add("2011-01-05/2011-01-15", "1", 1); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-10", "2", 3), createExpected("2011-01-10/2011-01-15", "1", 1) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-15")) ); } // 1|----------| // 2|----| @Test public void testOverlapFirstLarger() { add("2011-01-01/2011-01-20", "1", 2); add("2011-01-05/2011-01-15", "2", 3); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-05", "1", 2), createExpected("2011-01-05/2011-01-15", "2", 3), createExpected("2011-01-15/2011-01-20", "1", 2) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 2|----| // 1|----------| @Test public void testOverlapSecondLarger() { add("2011-01-05/2011-01-15", "2", 3); add("2011-01-01/2011-01-20", "1", 2); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-05", "1", 2), createExpected("2011-01-05/2011-01-15", "2", 3), createExpected("2011-01-15/2011-01-20", "1", 2) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 1|----|-----| // 2|-------| @Test public void testOverlapSecondPartialAlign() { add("2011-01-01/2011-01-10", "1", 1); add("2011-01-10/2011-01-20", "1", 2); add("2011-01-01/2011-01-15", "2", 3); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-15", "2", 3), createExpected("2011-01-15/2011-01-20", "1", 2) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 2|-------| // 1|----|-----| @Test public void testOverlapFirstPartialAlign() { add("2011-01-01/2011-01-15", "2", 3); add("2011-01-01/2011-01-10", "1", 1); add("2011-01-10/2011-01-20", "1", 2); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-15", "2", 3), createExpected("2011-01-15/2011-01-20", "1", 2) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 1|-------| // 2|------------| // 3|---| @Test public void testOverlapAscending() { add("2011-01-01/2011-01-10", "1", 1); add("2011-01-05/2011-01-20", "2", 2); add("2011-01-03/2011-01-06", "3", 3); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-03", "1", 1), createExpected("2011-01-03/2011-01-06", "3", 3), createExpected("2011-01-06/2011-01-20", "2", 2) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 3|---| // 2|------------| // 1|-------| @Test public void testOverlapDescending() { add("2011-01-03/2011-01-06", "3", 3); add("2011-01-05/2011-01-20", "2", 2); add("2011-01-01/2011-01-10", "1", 1); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-03", "1", 1), createExpected("2011-01-03/2011-01-06", "3", 3), createExpected("2011-01-06/2011-01-20", "2", 2) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 2|------------| // 3|---| // 1|-------| @Test public void testOverlapMixed() { add("2011-01-05/2011-01-20", "2", 2); add("2011-01-03/2011-01-06", "3", 3); add("2011-01-01/2011-01-10", "1", 1); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-03", "1", 1), createExpected("2011-01-03/2011-01-06", "3", 3), createExpected("2011-01-06/2011-01-20", "2", 2) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 1|-------------| // 2|--------| // 3|-----| @Test public void testOverlapContainedAscending() { add("2011-01-01/2011-01-20", "1", 1); add("2011-01-02/2011-01-10", "2", 2); add("2011-01-02/2011-01-06", "3", 3); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-02", "1", 1), createExpected("2011-01-02/2011-01-06", "3", 3), createExpected("2011-01-06/2011-01-10", "2", 2), createExpected("2011-01-10/2011-01-20", "1", 1) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 3|-----| // 2|--------| // 1|-------------| @Test public void testOverlapContainedDescending() { add("2011-01-02/2011-01-06", "3", 3); add("2011-01-02/2011-01-10", "2", 2); add("2011-01-01/2011-01-20", "1", 1); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-02", "1", 1), createExpected("2011-01-02/2011-01-06", "3", 3), createExpected("2011-01-06/2011-01-10", "2", 2), createExpected("2011-01-10/2011-01-20", "1", 1) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 2|--------| // 3|-----| // 1|-------------| @Test public void testOverlapContainedmixed() { add("2011-01-02/2011-01-10", "2", 2); add("2011-01-02/2011-01-06", "3", 3); add("2011-01-01/2011-01-20", "1", 1); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-02", "1", 1), createExpected("2011-01-02/2011-01-06", "3", 3), createExpected("2011-01-06/2011-01-10", "2", 2), createExpected("2011-01-10/2011-01-20", "1", 1) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 1|------|------|----| // 2|-----| @Test public void testOverlapSecondContained() { add("2011-01-01/2011-01-07", "1", 1); add("2011-01-07/2011-01-15", "1", 2); add("2011-01-15/2011-01-20", "1", 3); add("2011-01-10/2011-01-13", "2", 4); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-07", "1", 1), createExpected("2011-01-07/2011-01-10", "1", 2), createExpected("2011-01-10/2011-01-13", "2", 4), createExpected("2011-01-13/2011-01-15", "1", 2), createExpected("2011-01-15/2011-01-20", "1", 3) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 2|-----| // 1|------|------|----| @Test public void testOverlapFirstContained() { add("2011-01-10/2011-01-13", "2", 4); add("2011-01-01/2011-01-07", "1", 1); add("2011-01-07/2011-01-15", "1", 2); add("2011-01-15/2011-01-20", "1", 3); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-07", "1", 1), createExpected("2011-01-07/2011-01-10", "1", 2), createExpected("2011-01-10/2011-01-13", "2", 4), createExpected("2011-01-13/2011-01-15", "1", 2), createExpected("2011-01-15/2011-01-20", "1", 3) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 1|----|----| // 2|---------| @Test public void testOverlapSecondContainsFirst() { add("2011-01-01/2011-01-20", "1", 1); add("2011-01-01/2011-01-10", "2", 2); add("2011-01-10/2011-01-20", "2", 3); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-10", "2", 2), createExpected("2011-01-10/2011-01-20", "2", 3) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 2|---------| // 1|----|----| @Test public void testOverlapFirstContainsSecond() { add("2011-01-10/2011-01-20", "2", 3); add("2011-01-01/2011-01-20", "1", 1); add("2011-01-01/2011-01-10", "2", 2); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-10", "2", 2), createExpected("2011-01-10/2011-01-20", "2", 3) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 1|----| // 2|----| // 3|----| @Test public void testOverlapLayeredAscending() { add("2011-01-01/2011-01-10", "1", 1); add("2011-01-05/2011-01-15", "2", 2); add("2011-01-15/2011-01-25", "3", 3); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-05", "1", 1), createExpected("2011-01-05/2011-01-15", "2", 2), createExpected("2011-01-15/2011-01-25", "3", 3) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-25")) ); } // 3|----| // 2|----| // 1|----| @Test public void testOverlapLayeredDescending() { add("2011-01-15/2011-01-25", "3", 3); add("2011-01-05/2011-01-15", "2", 2); add("2011-01-01/2011-01-10", "1", 1); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-05", "1", 1), createExpected("2011-01-05/2011-01-15", "2", 2), createExpected("2011-01-15/2011-01-25", "3", 3) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-25")) ); } // 2|----| |----| // 1|-------------| @Test public void testOverlapV1Large() { add("2011-01-01/2011-01-15", "1", 1); add("2011-01-03/2011-01-05", "2", 2); add("2011-01-13/2011-01-20", "2", 3); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-03", "1", 1), createExpected("2011-01-03/2011-01-05", "2", 2), createExpected("2011-01-05/2011-01-13", "1", 1), createExpected("2011-01-13/2011-01-20", "2", 3) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 2|-------------| // 1|----| |----| @Test public void testOverlapV2Large() { add("2011-01-01/2011-01-15", "2", 1); add("2011-01-03/2011-01-05", "1", 2); add("2011-01-13/2011-01-20", "1", 3); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-15", "2", 1), createExpected("2011-01-15/2011-01-20", "1", 3) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 1|-------------| // 2|----| |----| @Test public void testOverlapV1LargeIsAfter() { add("2011-01-03/2011-01-20", "1", 1); add("2011-01-01/2011-01-05", "2", 2); add("2011-01-13/2011-01-17", "2", 3); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-05", "2", 2), createExpected("2011-01-05/2011-01-13", "1", 1), createExpected("2011-01-13/2011-01-17", "2", 3), createExpected("2011-01-17/2011-01-20", "1", 1) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 2|----| |----| // 1|-------------| @Test public void testOverlapV1SecondLargeIsAfter() { add("2011-01-13/2011-01-17", "2", 3); add("2011-01-01/2011-01-05", "2", 2); add("2011-01-03/2011-01-20", "1", 1); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-05", "2", 2), createExpected("2011-01-05/2011-01-13", "1", 1), createExpected("2011-01-13/2011-01-17", "2", 3), createExpected("2011-01-17/2011-01-20", "1", 1) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 1|-----------| // 2|----| |----| @Test public void testOverlapV1FirstBetween() { add("2011-01-03/2011-01-17", "1", 1); add("2011-01-01/2011-01-05", "2", 2); add("2011-01-15/2011-01-20", "2", 3); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-05", "2", 2), createExpected("2011-01-05/2011-01-15", "1", 1), createExpected("2011-01-15/2011-01-20", "2", 3) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 2|----| |----| // 1|-----------| @Test public void testOverlapV1SecondBetween() { add("2011-01-01/2011-01-05", "2", 2); add("2011-01-15/2011-01-20", "2", 3); add("2011-01-03/2011-01-17", "1", 1); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-05", "2", 2), createExpected("2011-01-05/2011-01-15", "1", 1), createExpected("2011-01-15/2011-01-20", "2", 3) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } // 4|---| // 3|---| // 2|---| // 1|-------------| @Test public void testOverlapLargeUnderlyingWithSmallDayAlignedOverlays() { add("2011-01-01/2011-01-05", "1", 1); add("2011-01-03/2011-01-04", "2", 2); add("2011-01-04/2011-01-05", "3", 3); add("2011-01-05/2011-01-06", "4", 4); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-03", "1", 1), createExpected("2011-01-03/2011-01-04", "2", 2), createExpected("2011-01-04/2011-01-05", "3", 3), createExpected("2011-01-05/2011-01-06", "4", 4) ), timeline.lookup(Intervals.of("0000-01-01/3000-01-01")) ); } // |----3---||---1---| // |---2---| @Test public void testOverlapCausesNullEntries() { add("2011-01-01T12/2011-01-02", "3", 3); add("2011-01-02/3011-01-03", "1", 1); add("2011-01-01/2011-01-02", "2", 2); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-01T12", "2", 2), createExpected("2011-01-01T12/2011-01-02", "3", 3), createExpected("2011-01-02/3011-01-03", "1", 1) ), timeline.lookup(Intervals.of("2011-01-01/3011-01-03")) ); } // 1|----| |----| // 2|------| |------| // 3|------------------| @Test public void testOverlapOvershadowedThirdContains() { add("2011-01-03/2011-01-06", "1", 1); add("2011-01-09/2011-01-12", "1", 2); add("2011-01-02/2011-01-08", "2", 3); add("2011-01-10/2011-01-16", "2", 4); add("2011-01-01/2011-01-20", "3", 5); assertValues( Sets.newHashSet( createExpected("2011-01-02/2011-01-08", "2", 3), createExpected("2011-01-10/2011-01-16", "2", 4), createExpected("2011-01-03/2011-01-06", "1", 1), createExpected("2011-01-09/2011-01-12", "1", 2) ), timeline.findFullyOvershadowed() ); } // 2|------|------| // 1|-------------| // 3|-------------| @Test public void testOverlapOvershadowedAligned() { add("2011-01-01/2011-01-05", "2", 1); add("2011-01-05/2011-01-10", "2", 2); add("2011-01-01/2011-01-10", "1", 3); add("2011-01-01/2011-01-10", "3", 4); assertValues( Sets.newHashSet( createExpected("2011-01-01/2011-01-05", "2", 1), createExpected("2011-01-05/2011-01-10", "2", 2), createExpected("2011-01-01/2011-01-10", "1", 3) ), timeline.findFullyOvershadowed() ); } // 2|----| |-----| // 1|---------| // 3|-----------| @Test public void testOverlapOvershadowedSomeComplexOverlapsCantThinkOfBetterName() { add("2011-01-01/2011-01-05", "2", 1); add("2011-01-10/2011-01-15", "2", 2); add("2011-01-03/2011-01-12", "1", 3); add("2011-01-01/2011-01-10", "3", 4); assertValues( Sets.newHashSet( createExpected("2011-01-03/2011-01-12", "1", 3), createExpected("2011-01-01/2011-01-05", "2", 1) ), timeline.findFullyOvershadowed() ); } @Test public void testOverlapAndRemove() { add("2011-01-01/2011-01-20", "1", 1); add("2011-01-10/2011-01-15", "2", 2); timeline.remove(Intervals.of("2011-01-10/2011-01-15"), "2", makeSingle("2", 2)); assertValues( Collections.singletonList( createExpected("2011-01-01/2011-01-20", "1", 1) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } @Test public void testOverlapAndRemove2() { add("2011-01-01/2011-01-20", "1", 1); add("2011-01-10/2011-01-20", "2", 2); add("2011-01-20/2011-01-30", "3", 4); timeline.remove(Intervals.of("2011-01-10/2011-01-20"), "2", makeSingle("2", 2)); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-20", "1", 1), createExpected("2011-01-20/2011-01-30", "3", 4) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-30")) ); } @Test public void testOverlapAndRemove3() { add("2011-01-01/2011-01-20", "1", 1); add("2011-01-02/2011-01-03", "2", 2); add("2011-01-10/2011-01-14", "2", 3); timeline.remove(Intervals.of("2011-01-02/2011-01-03"), "2", makeSingle("2", 2)); timeline.remove(Intervals.of("2011-01-10/2011-01-14"), "2", makeSingle("2", 3)); assertValues( Collections.singletonList( createExpected("2011-01-01/2011-01-20", "1", 1) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } @Test public void testOverlapAndRemove4() { add("2011-01-01/2011-01-20", "1", 1); add("2011-01-10/2011-01-15", "2", 2); add("2011-01-15/2011-01-20", "2", 3); timeline.remove(Intervals.of("2011-01-15/2011-01-20"), "2", makeSingle("2", 3)); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-10", "1", 1), createExpected("2011-01-10/2011-01-15", "2", 2), createExpected("2011-01-15/2011-01-20", "1", 1) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } @Test public void testOverlapAndRemove5() { add("2011-01-01/2011-01-20", "1", 1); add("2011-01-10/2011-01-15", "2", 2); timeline.remove(Intervals.of("2011-01-10/2011-01-15"), "2", makeSingle("2", 2)); add("2011-01-01/2011-01-20", "1", 1); assertValues( Collections.singletonList( createExpected("2011-01-01/2011-01-20", "1", 1) ), timeline.lookup(Intervals.of("2011-01-01/2011-01-20")) ); } @Test public void testRemoveNothingBacking() { add("2011-01-01/2011-01-05", "1", 1); add("2011-01-05/2011-01-10", "2", 2); add("2011-01-10/2011-01-15", "3", 3); add("2011-01-15/2011-01-20", "4", 4); timeline.remove(Intervals.of("2011-01-15/2011-01-20"), "4", makeSingle("4", 4)); assertValues( Arrays.asList( createExpected("2011-01-01/2011-01-05", "1", 1), createExpected("2011-01-05/2011-01-10", "2", 2), createExpected("2011-01-10/2011-01-15", "3", 3) ), timeline.lookup(new Interval(DateTimes.EPOCH, DateTimes.MAX)) ); } @Test public void testOvershadowingHigherVersionWins1() { add("2011-04-01/2011-04-03", "1", 2); add("2011-04-03/2011-04-06", "1", 3); add("2011-04-06/2011-04-09", "1", 4); add("2011-04-01/2011-04-09", "2", 1); assertValues( ImmutableSet.of( createExpected("2011-04-01/2011-04-03", "1", 2), createExpected("2011-04-03/2011-04-06", "1", 3), createExpected("2011-04-06/2011-04-09", "1", 4) ), timeline.findFullyOvershadowed() ); } @Test public void testOvershadowingHigherVersionWins2() { add("2011-04-01/2011-04-09", "1", 1); add("2011-04-01/2011-04-03", "2", 2); add("2011-04-03/2011-04-06", "2", 3); add("2011-04-06/2011-04-09", "2", 4); assertValues( ImmutableSet.of( createExpected("2011-04-01/2011-04-09", "1", 1) ), timeline.findFullyOvershadowed() ); } @Test public void testOvershadowingHigherVersionWins3() { add("2011-04-01/2011-04-03", "1", 2); add("2011-04-03/2011-04-06", "1", 3); add("2011-04-09/2011-04-12", "1", 4); add("2011-04-01/2011-04-12", "2", 1); assertValues( Sets.newHashSet( createExpected("2011-04-01/2011-04-03", "1", 2), createExpected("2011-04-03/2011-04-06", "1", 3), createExpected("2011-04-09/2011-04-12", "1", 4) ), timeline.findFullyOvershadowed() ); } @Test public void testOvershadowingHigherVersionWins4() { add("2011-04-03/2011-04-06", "1", 3); add("2011-04-06/2011-04-09", "1", 4); add("2011-04-01/2011-04-09", "2", 1); assertValues( ImmutableSet.of( createExpected("2011-04-03/2011-04-06", "1", 3), createExpected("2011-04-06/2011-04-09", "1", 4) ), timeline.findFullyOvershadowed() ); } @Test public void testOvershadowingHigherVersionNeverOvershadowedByLower1() { add("2011-04-01/2011-04-09", "1", 1); add("2011-04-03/2011-04-06", "2", 3); add("2011-04-06/2011-04-09", "2", 4); assertValues( ImmutableSet.of(), timeline.findFullyOvershadowed() ); } @Test public void testOvershadowingHigherVersionNeverOvershadowedByLower2() { add("2011-04-01/2011-04-09", "1", 1); add("2011-04-01/2011-04-03", "2", 2); add("2011-04-06/2011-04-09", "2", 4); assertValues( ImmutableSet.of(), timeline.findFullyOvershadowed() ); } @Test public void testOvershadowingHigherVersionNeverOvershadowedByLower3() { add("2011-04-01/2011-04-09", "1", 1); add("2011-04-01/2011-04-03", "2", 2); add("2011-04-03/2011-04-06", "2", 3); assertValues( ImmutableSet.of(), timeline.findFullyOvershadowed() ); } @Test public void testOvershadowingHigherVersionNeverOvershadowedByLower4() { add("2011-04-01/2011-04-09", "2", 1); add("2011-04-01/2011-04-03", "3", 2); add("2011-04-03/2011-04-06", "4", 3); add("2011-04-03/2011-04-06", "1", 3); assertValues( ImmutableSet.of( createExpected("2011-04-03/2011-04-06", "1", 3) ), timeline.findFullyOvershadowed() ); } @Test public void testOvershadowingHigherVersionNeverOvershadowedByLower5() { add("2011-04-01/2011-04-12", "2", 1); add("2011-04-01/2011-04-03", "3", 2); add("2011-04-06/2011-04-09", "4", 3); add("2011-04-09/2011-04-12", "1", 3); add("2011-04-03/2011-04-06", "1", 3); assertValues( Sets.newHashSet( createExpected("2011-04-03/2011-04-06", "1", 3), createExpected("2011-04-09/2011-04-12", "1", 3) ), timeline.findFullyOvershadowed() ); } @Test public void testOvershadowingSameIntervalHighVersionWins() { add("2011-04-01/2011-04-09", "1", 1); add("2011-04-01/2011-04-09", "9", 2); add("2011-04-01/2011-04-09", "2", 3); assertValues( Sets.newHashSet( createExpected("2011-04-01/2011-04-09", "2", 3), createExpected("2011-04-01/2011-04-09", "1", 1) ), timeline.findFullyOvershadowed() ); } @Test public void testOvershadowingSameIntervalSameVersionAllKept() { add("2011-04-01/2011-04-09", "1", 1); add("2011-04-01/2011-04-09", "9", 2); add("2011-04-01/2011-04-09", "2", 3); add("2011-04-01/2011-04-09", "9", 4); assertValues( Sets.newHashSet( createExpected("2011-04-01/2011-04-09", "2", 3), createExpected("2011-04-01/2011-04-09", "1", 1) ), timeline.findFullyOvershadowed() ); } @Test public void testNotFoundReturnsEmpty() { add("2011-04-01/2011-04-09", "1", 1); Assert.assertTrue(timeline.lookup(Intervals.of("1970/1980")).isEmpty()); } /** https://github.com/apache/druid/issues/3010 */ @Test public void testRemoveIncompleteKeepsComplete() { add("2011-04-01/2011-04-02", "1", IntegerPartitionChunk.make(null, 1, 0, new OvershadowableInteger("1", 0, 77))); add("2011-04-01/2011-04-02", "1", IntegerPartitionChunk.make(1, null, 1, new OvershadowableInteger("1", 1, 88))); add("2011-04-01/2011-04-02", "2", IntegerPartitionChunk.make(null, 1, 0, new OvershadowableInteger("2", 0, 99))); assertValues( ImmutableList.of( createExpected("2011-04-01/2011-04-02", "1", Arrays.asList( IntegerPartitionChunk.make(null, 1, 0, new OvershadowableInteger("1", 0, 77)), IntegerPartitionChunk.make(1, null, 1, new OvershadowableInteger("1", 1, 88)) ) ) ), timeline.lookup(Intervals.of("2011-04-01/2011-04-02")) ); add("2011-04-01/2011-04-02", "3", IntegerPartitionChunk.make(null, 1, 0, new OvershadowableInteger("3", 0, 110))); assertValues( ImmutableList.of( createExpected("2011-04-01/2011-04-02", "1", Arrays.asList( IntegerPartitionChunk.make(null, 1, 0, new OvershadowableInteger("1", 0, 77)), IntegerPartitionChunk.make(1, null, 1, new OvershadowableInteger("1", 1, 88)) ) ) ), timeline.lookup(Intervals.of("2011-04-01/2011-04-02")) ); assertValues( Sets.newHashSet( createExpected("2011-04-01/2011-04-02", "2", Collections.singletonList( IntegerPartitionChunk.make(null, 1, 0, new OvershadowableInteger("2", 0, 99)) ) ) ), timeline.findFullyOvershadowed() ); checkRemove(); assertValues( ImmutableList.of( createExpected("2011-04-01/2011-04-02", "1", Arrays.asList( IntegerPartitionChunk.make(null, 1, 0, new OvershadowableInteger("1", 0, 77)), IntegerPartitionChunk.make(1, null, 1, new OvershadowableInteger("1", 1, 88)) ) ) ), timeline.lookup(Intervals.of("2011-04-01/2011-04-02")) ); } @Test public void testIsOvershadowedWithNonOverlappingSegmentsInTimeline() { add("2011-04-05/2011-04-07", "1", makeSingle("1", 1)); add("2011-04-07/2011-04-09", "1", makeSingle("1", 1)); add("2011-04-15/2011-04-17", "1", makeSingle("1", 1)); add("2011-04-17/2011-04-19", "1", makeSingle("1", 1)); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-03"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-05"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-06"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-07"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-08"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-09"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-10"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-30"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-06"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-07"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-08"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-09"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-06"), "1", new OvershadowableInteger("1", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-07"), "1", new OvershadowableInteger("1", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-08"), "1", new OvershadowableInteger("1", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-09"), "1", new OvershadowableInteger("1", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-06"), "2", new OvershadowableInteger("2", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-07"), "2", new OvershadowableInteger("2", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-08"), "2", new OvershadowableInteger("2", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-09"), "2", new OvershadowableInteger("2", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-07"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-08"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-09"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-10"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-30"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-07/2011-04-08"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-07/2011-04-09"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-07/2011-04-10"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-07/2011-04-30"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-08/2011-04-09"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-08/2011-04-10"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-08/2011-04-30"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-09/2011-04-10"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-09/2011-04-15"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-09/2011-04-17"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-09/2011-04-19"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-09/2011-04-30"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-15/2011-04-16"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-15/2011-04-17"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-15/2011-04-18"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-15/2011-04-19"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-15/2011-04-20"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-15/2011-04-30"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-19/2011-04-20"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-21/2011-04-22"), "0", new OvershadowableInteger("0", 0, 1))); } @Test public void testIsOvershadowedWithOverlappingSegmentsInTimeline() { add("2011-04-05/2011-04-09", "11", makeSingle("11", 1)); add("2011-04-07/2011-04-11", "12", makeSingle("12", 1)); add("2011-04-15/2011-04-19", "12", makeSingle("12", 1)); add("2011-04-17/2011-04-21", "11", makeSingle("11", 1)); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-03"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-05"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-06"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-07"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-08"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-09"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-10"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-11"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-01/2011-04-30"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-06"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-07"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-08"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-09"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-10"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-11"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-06"), "12", new OvershadowableInteger("12", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-07"), "12", new OvershadowableInteger("12", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-08"), "12", new OvershadowableInteger("12", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-09"), "12", new OvershadowableInteger("12", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-10"), "12", new OvershadowableInteger("12", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-11"), "12", new OvershadowableInteger("12", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-06"), "13", new OvershadowableInteger("13", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-07"), "13", new OvershadowableInteger("13", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-08"), "13", new OvershadowableInteger("13", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-09"), "13", new OvershadowableInteger("13", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-10"), "13", new OvershadowableInteger("13", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-11"), "13", new OvershadowableInteger("13", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-12"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-15"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-16"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-17"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-18"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-19"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-20"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-21"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-05/2011-04-22"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-07"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-08"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-09"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-10"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-11"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-12"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-15"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-16"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-17"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-18"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-19"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-20"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-21"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-06/2011-04-22"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-12/2011-04-15"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-12/2011-04-16"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-12/2011-04-17"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-12/2011-04-18"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-12/2011-04-19"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-12/2011-04-20"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-12/2011-04-21"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-12/2011-04-22"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertTrue(timeline.isOvershadowed(Intervals.of("2011-04-15/2011-04-21"), "0", new OvershadowableInteger("0", 0, 1))); Assert.assertFalse(timeline.isOvershadowed(Intervals.of("2011-04-21/2011-04-22"), "0", new OvershadowableInteger("0", 0, 1))); } @Test public void testOvershadowedByReference() { add("2019-01-01/2019-01-02", "0", makeNumbered("0", 0, 0)); add("2019-01-01/2019-01-02", "0", makeNumbered("0", 1, 0)); add("2019-01-01/2019-01-02", "0", makeNumbered("0", 2, 0)); add("2019-01-01/2019-01-02", "0", makeNumberedOverwriting("0", 0, 1, 0, 3, 1, 2)); add("2019-01-01/2019-01-02", "0", makeNumberedOverwriting("0", 1, 1, 0, 3, 1, 2)); Assert.assertEquals( ImmutableSet.of( makeTimelineObjectHolder( "2019-01-01/2019-01-02", "0", ImmutableList.of(makeNumbered("0", 0, 0), makeNumbered("0", 1, 0), makeNumbered("0", 2, 0)) ) ), timeline.findFullyOvershadowed() ); } @Test public void testOvershadowedByReferenceChain() { // 2019-01-01/2019-01-02 add("2019-01-01/2019-01-02", "0", makeNumbered("0", 0, 0)); add("2019-01-01/2019-01-02", "0", makeNumbered("0", 1, 0)); add("2019-01-01/2019-01-02", "0", makeNumbered("0", 2, 0)); // 2019-01-02/2019-01-03 add("2019-01-02/2019-01-03", "0", makeNumbered("0", 0, 0)); add("2019-01-02/2019-01-03", "0", makeNumbered("0", 1, 0)); // Overwrite 2019-01-01/2019-01-02 add("2019-01-01/2019-01-02", "0", makeNumberedOverwriting("0", 0, 1, 0, 3, 1, 2)); add("2019-01-01/2019-01-02", "0", makeNumberedOverwriting("0", 1, 1, 0, 3, 1, 2)); // Overwrite 2019-01-01/2019-01-02 add("2019-01-01/2019-01-02", "0", makeNumberedOverwriting("0", 2, 2, 0, 3, 2, 2)); add("2019-01-01/2019-01-02", "0", makeNumberedOverwriting("0", 3, 2, 0, 3, 2, 2)); Assert.assertEquals( ImmutableSet.of( makeTimelineObjectHolder( "2019-01-01/2019-01-02", "0", ImmutableList.of( makeNumbered("0", 0, 0), makeNumbered("0", 1, 0), makeNumbered("0", 2, 0), makeNumberedOverwriting("0", 0, 1, 0, 3, 1, 2), makeNumberedOverwriting("0", 1, 1, 0, 3, 1, 2) ) ) ), timeline.findFullyOvershadowed() ); } @Test public void testOvershadowedByReferenceAndThenVersion() { // 2019-01-01/2019-01-02 add("2019-01-01/2019-01-02", "0", makeNumbered("0", 0, 0)); add("2019-01-01/2019-01-02", "0", makeNumbered("0", 1, 0)); add("2019-01-01/2019-01-02", "0", makeNumbered("0", 2, 0)); // 2019-01-02/2019-01-03 add("2019-01-02/2019-01-03", "0", makeNumbered("0", 0, 0)); add("2019-01-02/2019-01-03", "0", makeNumbered("0", 1, 0)); // Overwrite 2019-01-01/2019-01-02 add("2019-01-01/2019-01-02", "0", makeNumberedOverwriting("0", 0, 1, 0, 3, 1, 2)); add("2019-01-01/2019-01-02", "0", makeNumberedOverwriting("0", 1, 1, 0, 3, 1, 2)); // Overwrite 2019-01-01/2019-01-02 add("2019-01-01/2019-01-02", "1", makeNumbered("1", 0, 0)); add("2019-01-01/2019-01-02", "1", makeNumbered("1", 1, 0)); Assert.assertEquals( ImmutableSet.of( makeTimelineObjectHolder( "2019-01-01/2019-01-02", "0", ImmutableList.of( makeNumbered("0", 0, 0), makeNumbered("0", 1, 0), makeNumbered("0", 2, 0), makeNumberedOverwriting("0", 0, 1, 0, 3, 1, 2), makeNumberedOverwriting("0", 1, 1, 0, 3, 1, 2) ) ) ), timeline.findFullyOvershadowed() ); } @Test public void testOvershadowedByVersionAndThenReference() { // 2019-01-01/2019-01-02 add("2019-01-01/2019-01-02", "0", makeNumbered("0", 0, 0)); add("2019-01-01/2019-01-02", "0", makeNumbered("0", 1, 0)); add("2019-01-01/2019-01-02", "0", makeNumbered("0", 2, 0)); // 2019-01-02/2019-01-03 add("2019-01-02/2019-01-03", "0", makeNumbered("0", 0, 0)); add("2019-01-02/2019-01-03", "0", makeNumbered("0", 1, 0)); // Overwrite 2019-01-01/2019-01-02 add("2019-01-01/2019-01-02", "1", makeNumbered("1", 0, 0)); add("2019-01-01/2019-01-02", "1", makeNumbered("1", 1, 0)); // Overwrite 2019-01-01/2019-01-02 add("2019-01-01/2019-01-02", "1", makeNumberedOverwriting("1", 0, 1, 0, 2, 1, 3)); add("2019-01-01/2019-01-02", "1", makeNumberedOverwriting("1", 1, 1, 0, 2, 1, 3)); add("2019-01-01/2019-01-02", "1", makeNumberedOverwriting("1", 2, 1, 0, 2, 1, 3)); Assert.assertEquals( ImmutableSet.of( makeTimelineObjectHolder( "2019-01-01/2019-01-02", "0", ImmutableList.of( makeNumbered("0", 0, 0), makeNumbered("0", 1, 0), makeNumbered("0", 2, 0) ) ), makeTimelineObjectHolder( "2019-01-01/2019-01-02", "1", ImmutableList.of( makeNumbered("1", 0, 0), makeNumbered("1", 1, 0) ) ) ), timeline.findFullyOvershadowed() ); } @Test public void testFallbackOnMissingSegment() { final Interval interval = Intervals.of("2019-01-01/2019-01-02"); add(interval, "0", makeNumbered("0", 0, 0)); add(interval, "0", makeNumbered("0", 1, 0)); add(interval, "0", makeNumbered("0", 2, 0)); // Overwrite 2019-01-01/2019-01-02 add(interval, "1", makeNumbered("1", 0, 0)); add(interval, "1", makeNumbered("1", 1, 0)); // Overwrite 2019-01-01/2019-01-02 add("2019-01-01/2019-01-02", "1", makeNumberedOverwriting("1", 0, 1, 0, 2, 1, 3)); add("2019-01-01/2019-01-02", "1", makeNumberedOverwriting("1", 1, 1, 0, 2, 1, 3)); add("2019-01-01/2019-01-02", "1", makeNumberedOverwriting("1", 2, 1, 0, 2, 1, 3)); timeline.remove( interval, "1", makeNumberedOverwriting("1", 2, 1, 0, 2, 1, 3) ); final List> holders = timeline.lookup(interval); Assert.assertEquals( ImmutableList.of( new TimelineObjectHolder<>( interval, "1", new PartitionHolder<>( ImmutableList.of( makeNumbered("1", 0, 0), makeNumbered("1", 1, 0), makeNumberedOverwriting("1", 0, 1, 0, 2, 1, 3), makeNumberedOverwriting("1", 1, 1, 0, 2, 1, 3) ) ) ) ), holders ); } @Test public void testAddSameChunkToFullAtomicUpdateGroup() { final Interval interval = Intervals.of("2019-01-01/2019-01-02"); add(interval, "0", makeNumbered("0", 0, 0)); add(interval, "0", makeNumberedOverwriting("0", 0, 0, 0, 1, 1, 1)); add(interval, "0", makeNumbered("0", 0, 1)); final Set> overshadowed = timeline.findFullyOvershadowed(); Assert.assertEquals( ImmutableSet.of( new TimelineObjectHolder<>( interval, "0", new PartitionHolder<>(ImmutableList.of(makeNumbered("0", 0, 1))) ) ), overshadowed ); } @Test public void testOvershadowMultipleStandbyAtomicUpdateGroup() { final Interval interval = Intervals.of("2019-01-01/2019-01-02"); add(interval, "0", makeNumberedOverwriting("0", 0, 0, 0, 1, 1, 2)); add(interval, "0", makeNumberedOverwriting("0", 1, 0, 0, 1, 2, 2)); add(interval, "0", makeNumberedOverwriting("0", 2, 0, 0, 1, 3, 2)); // <-- full atomicUpdateGroup add(interval, "0", makeNumberedOverwriting("0", 3, 1, 0, 1, 3, 2)); // <-- full atomicUpdateGroup final Set> overshadowed = timeline.findFullyOvershadowed(); Assert.assertEquals( ImmutableSet.of( new TimelineObjectHolder<>( interval, "0", new PartitionHolder<>( ImmutableList.of( makeNumberedOverwriting("0", 0, 0, 0, 1, 1, 2), makeNumberedOverwriting("0", 1, 0, 0, 1, 2, 2) ) ) ) ), overshadowed ); } @Test public void testIsOvershadowedForOverwritingSegments() { final Interval interval = Intervals.of("2019-01-01/2019-01-02"); add(interval, "0", makeNumberedOverwriting("0", 0, 0, 5, 10, 10, 1)); for (int i = 0; i < 5; i++) { Assert.assertTrue(timeline.isOvershadowed(interval, "0", makeNumbered("0", i + 5, 0).getObject())); } Assert.assertFalse(timeline.isOvershadowed(interval, "0", makeNumbered("0", 4, 0).getObject())); Assert.assertFalse(timeline.isOvershadowed(interval, "0", makeNumbered("0", 11, 0).getObject())); Assert.assertTrue(timeline.isOvershadowed(interval, "0", makeNumberedOverwriting("0", 1, 0, 5, 6, 5, 2).getObject())); Assert.assertTrue(timeline.isOvershadowed(interval, "0", makeNumberedOverwriting("0", 1, 0, 7, 8, 5, 2).getObject())); Assert.assertTrue(timeline.isOvershadowed(interval, "0", makeNumberedOverwriting("0", 1, 0, 8, 10, 5, 2).getObject())); Assert.assertFalse(timeline.isOvershadowed(interval, "0", makeNumberedOverwriting("0", 1, 0, 5, 10, 12, 2).getObject())); Assert.assertFalse(timeline.isOvershadowed(interval, "0", makeNumberedOverwriting("0", 1, 0, 4, 15, 12, 2).getObject())); } @Test public void testIterateAllObjects() { add("2011-01-01/2011-01-10", "1", 1); add("2011-01-01/2011-01-10", "2", 3); Collection overshadowableIntegers = timeline.iterateAllObjects(); Assert.assertEquals(2, overshadowableIntegers.size()); // Tests that the "iteration" size of the returned collection is 2 (the "reported" size from size() method may be // deceptive). Assert.assertEquals(2, Lists.newArrayList(overshadowableIntegers.iterator()).size()); } } src/test/java/tagline/testutil/note/NoteUtil.java package tagline.testutil.note; import static tagline.logic.parser.note.NoteCliSyntax.PREFIX_CONTENT; import static tagline.logic.parser.note.NoteCliSyntax.PREFIX_TAG; import static tagline.logic.parser.note.NoteCliSyntax.PREFIX_TITLE; import tagline.logic.commands.note.CreateNoteCommand; import tagline.model.note.Note; import tagline.model.tag.Tag; /** * A utility class for Note. */ public class NoteUtil { /** * Returns an add command string for adding the {@code note}. */ public static String getCreateCommand(Note note) { return CreateNoteCommand.COMMAND_WORD + " " + getNoteDetails(note); } /** * Returns the part of command string for the given {@code person}'s details. */ public static String getNoteDetails(Note note) { StringBuilder sb = new StringBuilder(); sb.append(PREFIX_TITLE + note.getTitle().value + " "); sb.append(PREFIX_CONTENT + note.getContent().value + " "); for (Tag tag : note.getTags()) { sb.append(PREFIX_TAG + tag.toString() + " "); } return sb.toString(); } } package data.databaseImpl; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.ServiceUnavailableException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * Lavet af */ public class DefaultDatabaseImpl { //move to config private static final String databaseUrl = "jdbc:mysql://kreditsystem-database.czir2ycmcwhq.us-east-2.rds.amazonaws.com"; private static final String databaseUsername = "kreditsystem"; private static final String databasePassword = ""; public Connection getConnection() { try { Class.forName("com.mysql.driver"); return DriverManager.getConnection(databaseUrl, databaseUsername, databasePassword); } catch (ClassNotFoundException e) { throw new InternalServerErrorException("Mysql driver class not found: "+e); } catch (SQLException e) { throw new ServiceUnavailableException("Database connection error: "+e); } } } package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import seedu.address.commons.core.Messages; import seedu.address.logic.CommandHistory; import seedu.address.model.Model; import seedu.address.model.participant.FindingParticipantPredicate; /** * Lists all freshmen in the address book to the user. */ public class ListParticipantCommand extends Command { public static final String COMMAND_WORD = "list_f"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Lists all freshmen"; public static final String MESSAGE_SUCCESS = "Listed all freshmen"; private final FindingParticipantPredicate predicate; public ListParticipantCommand(FindingParticipantPredicate predicate) { this.predicate = predicate; } @Override public CommandResult execute(Model model, CommandHistory history) { requireNonNull(model); model.updateFilteredParticipantList(predicate); return new CommandResult( String.format(Messages.MESSAGE_PERSONS_LISTED_OVERVIEW, model.getFilteredParticipantList().size())); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof ListParticipantCommand // instanceof handles nulls && predicate.equals(((ListParticipantCommand) other).predicate)); // state check } } /** Return true if ch can be part of an operator. */ private boolean isSpecial(char ch) { switch (ch) { case '!': case '%': case '&': case '*': case '?': case '+': case '-': case ':': case '<': case '=': case '>': case '^': case '|': case '~': case '@': return true; default: return false; } }commandfamily-mifareclassic/src/main/java/com/taptrack/tcmptappy2/commandfamilies/mifareclassic/commands/GetMifareClassicLibraryVersionCommand.java package com.taptrack.tcmptappy2.commandfamilies.mifareclassic.commands; import androidx.annotation.NonNull; import com.taptrack.tcmptappy2.MalformedPayloadException; import com.taptrack.tcmptappy2.commandfamilies.mifareclassic.AbstractMifareClassicMessage; /** * Command for requesting that the Tappy respond with the version of the * Type 4 library supported on this device. */ public class GetMifareClassicLibraryVersionCommand extends AbstractMifareClassicMessage { public static final byte COMMAND_CODE = (byte) 0xFF; public GetMifareClassicLibraryVersionCommand() { } @Override public void parsePayload(@NonNull byte[] payload) throws MalformedPayloadException { } @NonNull @Override public byte[] getPayload() { return new byte[0]; } @Override public byte getCommandCode() { return COMMAND_CODE; } } package br.com.financecontrol.entity; import org.hibernate.annotations.GenericGenerator; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; @lombok.Getter @lombok.Setter @lombok.NoArgsConstructor @lombok.EqualsAndHashCode @lombok.AllArgsConstructor @lombok.Builder @Entity @Table(name = "account") public class Account implements Serializable { private static final long serialVersionUID = 2017880951855917024L; @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") private String id; public static AccountBuilder builder() { return new AccountBuilder(); } } ec_pdm/src/main/java/com/gyf/ec/service/EcStatisticsService.java package com.gyf.ec.service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSONObject; import com.gohuinuo.common.base.ServiceMybatis; import com.gyf.ec.mapper.EcSkuCostPriceLogMapper; import com.gyf.ec.mapper.EcStatisticsMapper; import com.gyf.ec.mapper.EcSuppliersComPriceLogMapper; import com.gyf.ec.model.EcSkuCostPriceLog; import com.gyf.ec.model.EcStatistics; import com.gyf.ec.model.EcStatisticsBySku; import com.gyf.ec.model.EcStatisticsBySupp; import com.gyf.ec.model.EcStatisticsUserOrType; import com.gyf.ec.model.EcSuppliersComPriceLog; @Service("ecStatisticsService") public class EcStatisticsService extends ServiceMybatis { @Resource private EcStatisticsMapper mapper; @Resource private EcSkuCostPriceLogMapper ecSkuCostPriceLogMapper; @Resource private EcSuppliersComPriceLogMapper ecSuppliersComPriceLogMapper; public JSONObject findEcStatistics(Map params) { JSONObject obj = new JSONObject(); String selectType = params.get("selectType") + ""; if("1".equals(selectType)) { obj.put("text", "每日新增任务数量"); } else if("2".equals(selectType)) { obj.put("text", "每日解决任务数量"); } List list = mapper.findEcStatistics(params); String[] dateTimeAry = new String[list.size()]; Integer[] numAry = new Integer[list.size()]; for(int i = 0; i < list.size(); i++) { EcStatistics es = list.get(i); dateTimeAry[i] = es.getDateTime(); numAry[i] = es.getNum(); } obj.put("dateTimeAry", dateTimeAry); obj.put("numAry", numAry); return obj; } public JSONObject findEcStatistics2(Map params) { JSONObject obj = new JSONObject(); String selectType = params.get("selectType") + ""; List list = new ArrayList(); if("1".equals(selectType)) { obj.put("text", "按人员查看任务量"); list = mapper.findEcStatisticsByUuser(params); } else if("2".equals(selectType)) { obj.put("text", "按任务类型查看任务量"); list = mapper.findEcStatisticsByTaskType(params); } //Long[] eidAry = new Long[list.size()]; //String[] snameAry = new String[list.size()]; //Integer[] numAry = new Integer[list.size()]; Object[] objAry = new Object[list.size()]; for(int i = 0; i < list.size(); i++) { Object[] objA = new Object[2]; EcStatisticsUserOrType es = list.get(i); //eidAry[i] = es.getEid(); //snameAry[i] = es.getSname(); //numAry[i] = es.getNum(); objA[0] = es.getSname(); objA[1] = es.getNum(); objAry[i] = objA; } //obj.put("eidAry", eidAry); //obj.put("snameAry", snameAry); //obj.put("numAry", numAry); obj.put("objAry", objAry); return obj; } public JSONObject findEcStatistics3(Map params) { JSONObject obj = new JSONObject(); String skus = params.get("skus") + ""; String[] skuAry = skus.split(","); Object[] objAry = new Object[skuAry.length]; int cnum = 0; for(int i = 0; i < skuAry.length; i++) { params.put("sku", skuAry[i].trim()); List list = mapper.findEcStatisticsBySuppliersCommodity(params); Double[] dAry = new Double[list.size()]; for(int j = 0; j < list.size(); j++) { EcStatisticsUserOrType esuot = list.get(j); dAry[j] = esuot.getPrice(); } if(cnum < list.size()) { cnum = list.size(); } Map map = new HashMap(); map.put("name", skuAry[i]); map.put("data", dAry); objAry[i] = map; } String[] textAry = new String[cnum]; for(int k = 1; k <= cnum; k++) { textAry[k-1] = k + ""; } obj.put("textAry", textAry); obj.put("objAry", objAry); obj.put("skuAry", skuAry); return obj; } /** * sku报表 * @param params * @return */ public List findEcStatisticsBySku(Map params) { List list = null; int order = Integer.parseInt(params.get("order")+""); if(order == 0) { // 最新一次价格比上一次高的价格,差距百分比最大的 list = mapper.findEcStatisticsBySku0(params); } else if(order == 1) { // 最新更新价格的SKU排在第一,依此类推 list = mapper.findEcStatisticsBySku1(params); } else if(order == 2) { // 按报价价格最高到最低排序 list = mapper.findEcStatisticsBySku2(params); } else if(order == 3) { // 按最新一次价格从低到高 list = mapper.findEcStatisticsBySku3(params); } else if(order == 4) { // 价格未更新时间降序,一直未更新SKU价格的SKU,从最近一次更新价格时间到当天间隔最久的在最上面 list = mapper.findEcStatisticsBySku4(params); } for(int i = 0; i < list.size(); i++) { EcStatisticsBySku esbs = list.get(i); params.put("skuId", esbs.getSkuId()); List elist = ecSkuCostPriceLogMapper.findEcSkuCostPriceLog(params); String costPriceList = ""; for(int j = 0; j < elist.size(); j++) { EcSkuCostPriceLog ecSkuCostPriceLog = elist.get(j); if(j == 0) { costPriceList = ecSkuCostPriceLog.getOldCostPrice(); } else { costPriceList +=","+ecSkuCostPriceLog.getOldCostPrice(); } } esbs.setCostPriceList(costPriceList); Double floatProportion = 0.0; if(esbs.getFloatPrice() != null && esbs.getFloatPrice() > 0 && esbs.getSecond() != null && esbs.getSecond() > 0) { BigDecimal bg = new BigDecimal(esbs.getFloatPrice()/esbs.getSecond()); floatProportion = bg.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue(); } esbs.setFloatProportion(floatProportion); } return list; } /** * 供应商报表 * @param params * @return */ public List findEcStatisticsBySupp(Map params) { List list = null; int order = Integer.parseInt(params.get("order")+""); if(order == 0) { // 最新一次价格比上一次高的价格,差距百分比最大的 list = mapper.findEcStatisticsBySupp0(params); } else if(order == 1) { // 最新更新价格的SKU排在第一,依此类推 list = mapper.findEcStatisticsBySupp1(params); } else if(order == 2) { // 按报价价格最高到最低排序 list = mapper.findEcStatisticsBySupp2(params); } else if(order == 3) { // 按最新一次价格从低到高 list = mapper.findEcStatisticsBySupp3(params); } else if(order == 4) { // 价格未更新时间降序,一直未更新SKU价格的SKU,从最近一次更新价格时间到当天间隔最久的在最上面 list = mapper.findEcStatisticsBySupp4(params); } for(int i = 0; i < list.size(); i++) { EcStatisticsBySupp esbs = list.get(i); params.put("skuId", esbs.getSkuId()); params.put("suppcomId", esbs.getSuppcomId()); List elist = ecSuppliersComPriceLogMapper.findEcSuppliersComPriceLog(params); String purchasePriceList = ""; for(int j = 0; j < elist.size(); j++) { EcSuppliersComPriceLog ecSuppliersComPriceLog = elist.get(j); if(j == 0) { purchasePriceList = ecSuppliersComPriceLog.getOldPurchasePrice(); } else { purchasePriceList +=","+ecSuppliersComPriceLog.getOldPurchasePrice(); } } esbs.setPurchasePriceList(purchasePriceList); Double floatProportion = 0.0; if(esbs.getFloatPrice() > 0 && esbs.getSecond() > 0) { BigDecimal bg = new BigDecimal(esbs.getFloatPrice()/esbs.getSecond()); floatProportion = bg.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue(); } esbs.setFloatProportion(floatProportion); } return list; } public List findMainPrice(Map params) { return mapper.findMainPrice(params); } } bushadie/bysj package cn.bushadie.sqltest; import cn.bushadie.project.system.competition.domain.Groupinfo; import cn.bushadie.project.system.competition.mapper.GroupMapper; import cn.bushadie.project.system.competition.mapper.GroupinfoMapper; import cn.bushadie.project.system.competition.service.GroupinfoService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; /** * @author jdmy * on 2019/3/3. **/ @SpringBootTest @RunWith( SpringRunner.class) @Transactional(rollbackFor = Exception.class) public class GroupinfoTest { @Autowired private GroupinfoService groupinfoService; @Autowired private GroupinfoMapper groupinfoMapper; @Test public void countMemberNumber(){ // System.out.println(groupinfoService.countMemberNumber(51L)); } @Test public void remainTeamNum(){ int num=0; try { num=groupinfoService.remainTeamNum(51L,1L); }catch(Exception e) { e.printStackTrace(); } System.out.println("num = "+num); try { num=groupinfoService.remainTeamNum(1L,51L); }catch(Exception e) { e.printStackTrace(); } System.out.println("num = "+num); } @Test public void changeLeaderId(){ groupinfoMapper.changeLeaderId(51L,2L); } @Test public void selectGroupinfoList(){ groupinfoMapper.selectGroupinfoList(new Groupinfo()); } } public class Test { public static void main(String[] args) throws NombreIncorrect { Titulaire x = new Prag("dupont"); Titulaire y = new Mcf("Durand"); Vacataire z = new Vacataire("Dubois"); Departement info = new Departement(); info.ajouter(z); info.ajouter(x); info.ajouter(y); System.out.println(info); System.out.println("nbheuresComp " + info.nbHeureCompAPayer()); System.out.println("total " + info.prixHcAPayer()); x.ajoutHeure(25); y.ajoutHeure(100); z.ajoutHeure(50); System.out.println(info); System.out.println("nbheuresComp " + info.nbHeureCompAPayer()); System.out.println("total " + info.prixHcAPayer()); x.ajoutHeure(320); y.ajoutHeure(296); z.ajoutHeure(50); System.out.println(info); System.out.println("nbheuresComp " + info.nbHeureCompAPayer()); System.out.println("total " + info.prixHcAPayer()); System.out.println("++++++++++++"); } } illmaren/DiscordBot /* * Copyright 2018 github.com/kaaz * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package emily.command.administrative; import emily.command.meta.ReactionType; import emily.command.meta.Reactions; import emily.command.meta.AbstractCommand; import emily.main.DiscordBot; import emily.util.Emojibet; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.entities.MessageChannel; import net.dv8tion.jda.core.entities.User; public class ReactionsCommand extends AbstractCommand { @Override public String getDescription() { return "Configure what reactions do to messages"; } @Override public String getCommand() { return "reactions"; } @Override public boolean isListed() { return false; } @Override public String[] getUsage() { return new String[]{ "reactions //settings for user placed reactions ", "reactions music //reactions for now playing message" }; } @Override public String[] getAliases() { return new String[]{"reaction", "r"}; } private String buildMessage() { String[] onoff = {Emojibet.OKE_SIGN, Emojibet.X}; StringBuilder sb = new StringBuilder(); int i = 0; for (ReactionType reactionType : ReactionType.values()) { sb.append("**").append(reactionType.getTitle()).append("** \n"); sb.append(reactionType.getDescription()).append("\n\n"); for (Reactions reactions : reactionType.getReactions()) { sb.append(onoff[++i % 2]).append(" | ").append(reactions.getEmote()).append(" | ").append(reactions.getDescription()).append("\n"); } sb.append("\n\n"); } return sb.toString(); } @Override public String execute(DiscordBot bot, String[] args, MessageChannel channel, User author, Message inputMessage) { return "The following :\n" + buildMessage(); } } package com.github.actar233.mbdpay; import com.github.actar233.mbdpay.exception.MbdPayException; import com.github.actar233.mbdpay.model.*; public class ClientTest { public static void main(String[] args) { MbdPayClient client = new MbdPayClient("", ""); aliPay(client); openid(client); wxH5(client); wxJsApi(client); searchOrder(client); refund(client); } private static void aliPay(MbdPayClient client) { try { AliPayResult result = client.aliPay(AliPayParams.builder() .url("") .amountTotal(1) .callbackUrl("") .description("") .outTradeNo("<可选:outTradeNo>") .build()); if (result.isSuccess()) { System.out.println("查询成功"); System.out.println(result); } else { System.out.println("查询失败"); System.out.println(result.getError()); } } catch (MbdPayException e) { System.out.println("请求异常"); e.printStackTrace(); } } private static void openid(MbdPayClient client){ System.out.println(client.openid("https://www.baidu.com")); } private static void wxH5(MbdPayClient client) { try { WxH5Result result = client.wxH5(WxH5Params.builder() .amountTotal(1) .description("") .channel("h5") .outTradeNo("<可选:outTradeNo>") .build()); if (result.isSuccess()) { System.out.println("查询成功"); System.out.println(result); } else { System.out.println("查询失败"); System.out.println(result.getError()); } } catch (MbdPayException e) { System.out.println("请求异常"); e.printStackTrace(); } } private static void wxJsApi(MbdPayClient client) { try { WxJsApiResult result = client.wxJsApi(WxJsApiParams.builder() .openid("") .amountTotal(1) .callbackUrl("") .description("") .outTradeNo("<可选:outTradeNo>") .build()); if (result.isSuccess()) { System.out.println("查询成功"); System.out.println(result); // 获取支付参数 System.out.println(result.getPayParams()); } else { System.out.println("查询失败"); System.out.println(result.getError()); } } catch (MbdPayException e) { System.out.println("请求异常"); e.printStackTrace(); } } private static void searchOrder(MbdPayClient client) { try { SearchOrderResult result = client.searchOrder(SearchOrderParams.builder() .outTradeNo("") .build()); if (result.isSuccess()) { System.out.println("查询成功"); System.out.println(result); } else { System.out.println("查询失败"); System.out.println(result.getError()); } } catch (MbdPayException e) { System.out.println("请求异常"); e.printStackTrace(); } } private static void refund(MbdPayClient client) { try { RefundResult result = client.refund(RefundParams.builder() .orderId("") .build()); if (result.isSuccess()) { System.out.println("查询成功"); System.out.println(result); } else { System.out.println("查询失败"); System.out.println(result.getError()); } } catch (MbdPayException e) { System.out.println("请求异常"); e.printStackTrace(); } } } package xyz.immortius.chunkbychunk.common.blocks; import net.minecraft.world.level.block.state.BlockState; import xyz.immortius.chunkbychunk.interop.ChunkByChunkConstants; /** * Spawns a chunk from the equivalent chunk in the source dimension (with configuration offset) */ public class SpawnChunkBlock extends BaseSpawnChunkBlock { public SpawnChunkBlock(Properties blockProperties) { super(blockProperties); } @Override public BlockState getTriggeredBlockState() { return ChunkByChunkConstants.triggeredSpawnChunkBlock().defaultBlockState(); } } package org.learn.open.service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import javassist.NotFoundException; import org.learn.open.api.UserInfoService; import org.learn.open.entity.UserInfo; import org.learn.open.mapper.UserInfoMapper; import org.learn.open.repository.UserInfoRepository; import org.learn.open.utils.BeanMapUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service(value="userinfoservice-0.0.1") public class UserInfoServiceImpl implements UserInfoService{ private static final String CACHE_KEY = "userInfo"; private static final String DEMO_CACHE_NAME = "demo"; @Autowired private UserInfoRepository userInfoRepository; @Autowired private UserInfoMapper userInfoMapper; @Cacheable(value=DEMO_CACHE_NAME,key="'userInfo_'+#username") public UserInfo findByUsername(String username) { // System.out.println("UserInfoServiceImpl.findByUsername()"); // return userInfoRepository.findByUsername(username); return BeanMapUtils.transMap2Bean(userInfoMapper.findByUsername(username), UserInfo.class); } @Override @CacheEvict(value = DEMO_CACHE_NAME,key = "'demoInfo_'+#id") public void delete(Long id) { userInfoRepository.delete(id); } @Override @CachePut(value = DEMO_CACHE_NAME,key = "'userInfo_'+#updated.getUid()") @Transactional(rollbackFor=Exception.class) public UserInfo update(UserInfo updated) throws NotFoundException { // TODO Auto-generated method stub UserInfo ui = userInfoRepository.findOne(updated.getUid()); if(ui==null){ throw new NotFoundException("not find "+updated.getUid()); } ui.setName(updated.getName()); ui.setState(updated.getState()); userInfoRepository.save(ui); // if(true){ // throw new NotFoundException("故意外抛异常测试事务"); // } return ui; } @Override @Cacheable(value=DEMO_CACHE_NAME,key="'userInfo_'+#id") public UserInfo findById(Long id) { // TODO Auto-generated method stub return userInfoRepository.findOne(id); } @Override @CacheEvict(value=DEMO_CACHE_NAME,key=CACHE_KEY) public UserInfo save(UserInfo userInfo) { // TODO Auto-generated method stub return userInfoRepository.save(userInfo); } @Override public PageInfo searchName(String username) { PageHelper.startPage(10, 1); return BeanMapUtils.transListMap2Bean(userInfoMapper.pageList(username), UserInfo.class); } } package core.framework.impl.validate.type; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * @author neo */ class DataTypeValidatorTest { @Test void validateObjectClass() { assertThatThrownBy(() -> new DataTypeValidator(String.class).validate()) .isInstanceOf(Error.class) .hasMessageContaining("class must be bean class"); assertThatThrownBy(() -> new DataTypeValidator(int.class).validate()) .isInstanceOf(Error.class) .hasMessageContaining("class must be bean class"); assertThatThrownBy(() -> new DataTypeValidator(TestEnum.class).validate()) .isInstanceOf(Error.class) .hasMessageContaining("class must be bean class"); } enum TestEnum { A } } src/main/java/com/plivo/api/PlivoClient.java package com.plivo.api; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.DeserializationConfig; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import com.plivo.api.util.Utils; import okhttp3.Credentials; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Protocol; import okhttp3.Response; import okhttp3.ResponseBody; import okhttp3.logging.HttpLoggingInterceptor; import okhttp3.logging.HttpLoggingInterceptor.Level; import okhttp3.ConnectionPool; import retrofit2.Retrofit; import retrofit2.converter.jackson.JacksonConverterFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ProtocolException; import java.text.SimpleDateFormat; import java.util.concurrent.TimeUnit; public class PlivoClient { private static SimpleModule simpleModule = new SimpleModule(); protected static String BASE_URL = "https://api.plivo.com/v1/"; protected static String VOICE_BASE_URL = "https://voice.plivo.com/v1/"; protected static String VOICE_FALLBACK1_URL = "https://voice-usw1.plivo.com/v1/"; protected static String VOICE_FALLBACK2_URL = "https://voice-use1.plivo.com/v1/"; protected static String CALLINSIGHTS_BASE_URL = "https://stats.plivo.com/v1/"; protected static String LOOKUP_BASE_URL = "https://lookup.plivo.com/v1/"; private static String version = "Unknown Version"; private boolean testing = false; private static ObjectMapper objectMapper = new ObjectMapper(); public void setTesting(boolean testing) { this.testing = testing; } public boolean isTesting() { return testing; } static { simpleModule.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer modifyEnumDeserializer(DeserializationConfig config, JavaType type, BeanDescription beanDesc, JsonDeserializer deserializer) { return new JsonDeserializer() { @Override public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { Class rawClass = (Class>) type.getRawClass(); return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase().replace("-", "_")); } }; } }); simpleModule.addSerializer(Enum.class, new StdSerializer(Enum.class) { @Override public void serialize(Enum value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeString(value.name().toLowerCase().replace("_", "-")); } }); } { try { InputStream inputStream = PlivoClient.class .getResource("version.txt") .openStream(); version = new BufferedReader(new InputStreamReader(inputStream)).readLine(); } catch (IOException ignored) { ignored.printStackTrace(); } objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); objectMapper.disable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS); objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); } private final Interceptor interceptor = new HttpLoggingInterceptor() .setLevel(Level.NONE); private final String authId; private final String authToken; private OkHttpClient httpClient; private Retrofit retrofit; private Retrofit voiceRetrofit; private Retrofit voiceFallback1Retrofit; private Retrofit voiceFallback2Retrofit; private Retrofit callInsightsRetrofit; private Retrofit lookupRetrofit; private PlivoAPIService apiService = null; private PlivoAPIService voiceApiService = null; private PlivoAPIService voiceFallback1Service = null; private PlivoAPIService voiceFallback2Service = null; private CallInsightsAPIService callInsightsAPIService = null; private LookupAPIService lookupAPIService = null; /** * Constructs a new PlivoClient instance. To set a proxy, timeout etc, you can pass in an OkHttpClient.Builder, on which you can set * the timeout and proxy using: * *


   *   new OkHttpClient.Builder()
   *   .proxy(proxy)
   *   .connectTimeout(1, TimeUnit.MINUTES);
   * 
* * @param authId * @param authToken * @param httpClientBuilder * @param baseUrl * @param simpleModule */ public PlivoClient(String authId, String authToken, OkHttpClient.Builder httpClientBuilder, final String baseUrl, final SimpleModule simpleModule) { if (!(Utils.isAccountIdValid(authId) || Utils.isSubaccountIdValid(authId))) { throw new IllegalArgumentException("invalid account ID"); } this.authId = authId; this.authToken = Token; this.objectMapper.registerModule(simpleModule); httpClient = httpClientBuilder .addNetworkInterceptor(interceptor) .addInterceptor(chain -> chain.proceed( chain.request() .newBuilder() .addHeader("Authorization", Credentials.basic(getAuthId(), getAuthToken())) .addHeader("User-Agent", String.format("%s/%s (Implementation: %s %s %s, Specification: %s %s %s)", "plivo-java", version, Runtime.class.getPackage().getImplementationVendor(), Runtime.class.getPackage().getImplementationTitle(), Runtime.class.getPackage().getImplementationVersion(), Runtime.class.getPackage().getSpecificationVendor(), Runtime.class.getPackage().getSpecificationTitle(), Runtime.class.getPackage().getSpecificationVersion() )) .build() )) .connectionPool(new ConnectionPool(5, 5, TimeUnit.MINUTES)) .addNetworkInterceptor(chain -> { Response response; try { response = chain.proceed(chain.request()); } catch (ProtocolException protocolException) { // We return bodies for HTTP 204! response = new Response.Builder() .request(chain.request()) .code(204) .protocol(Protocol.HTTP_1_1) .body(ResponseBody.create(null, new byte[]{})) .build(); } return response; }).build(); retrofit = new Retrofit.Builder() .client(httpClient) .baseUrl(baseUrl) .addConverterFactory(JacksonConverterFactory.create(objectMapper)) .build(); this.apiService = retrofit.create(PlivoAPIService.class); voiceRetrofit = new Retrofit.Builder() .client(httpClient) .baseUrl((VOICE_BASE_URL)) .addConverterFactory(JacksonConverterFactory.create(objectMapper)) .build(); this.voiceApiService = voiceRetrofit.create(PlivoAPIService.class); voiceFallback1Retrofit = new Retrofit.Builder() .client(httpClient) .baseUrl((VOICE_FALLBACK1_URL)) .addConverterFactory(JacksonConverterFactory.create(objectMapper)) .build(); this.voiceFallback1Service = voiceFallback1Retrofit.create(PlivoAPIService.class); voiceFallback2Retrofit = new Retrofit.Builder() .client(httpClient) .baseUrl((VOICE_FALLBACK2_URL)) .addConverterFactory(JacksonConverterFactory.create(objectMapper)) .build(); this.voiceFallback2Service = voiceFallback2Retrofit.create(PlivoAPIService.class); callInsightsRetrofit = new Retrofit.Builder() .client(httpClient) .baseUrl((CALLINSIGHTS_BASE_URL)) .addConverterFactory(JacksonConverterFactory.create(objectMapper)) .build(); this.callInsightsAPIService = callInsightsRetrofit.create(CallInsightsAPIService.class); lookupRetrofit = new Retrofit.Builder() .client(httpClient) .baseUrl((LOOKUP_BASE_URL)) .addConverterFactory(JacksonConverterFactory.create(objectMapper)) .build(); this.lookupAPIService = lookupRetrofit.create(LookupAPIService.class); } /** * Constructs a new PlivoClient instance. To set a proxy, timeout etc, you can pass in an OkHttpClient.Builder, on which you can set * the timeout and proxy using: * *

   *   new OkHttpClient.Builder()
   *   .proxy(proxy)
   *   .connectTimeout(1, TimeUnit.MINUTES);
   * 
* * @param authId * @param authToken */ public PlivoClient(String authId, String authToken) { this(authId, authToken, new OkHttpClient.Builder(), BASE_URL, simpleModule); } /** * Constructs a new PlivoClient instance. To set a proxy, timeout etc, you can pass in an OkHttpClient.Builder, on which you can set * the timeout and proxy using: * *

   *   new OkHttpClient.Builder()
   *   .proxy(proxy)
   *   .connectTimeout(1, TimeUnit.MINUTES);
   * 
* * @param authId * @param authToken * @param httpClientBuilder */ public PlivoClient(String authId, String authToken, OkHttpClient.Builder httpClientBuilder) { this(authId, authToken, httpClientBuilder, BASE_URL, simpleModule); } public static ObjectMapper getObjectMapper() { return objectMapper; } Retrofit getRetrofit() { return retrofit; } public PlivoAPIService getApiService() { return apiService; } public PlivoAPIService getVoiceApiService(){ return voiceApiService; } public PlivoAPIService getVoiceFallback1Service(){ return voiceFallback1Service; } public PlivoAPIService getVoiceFallback2Service(){ return voiceFallback2Service; } public CallInsightsAPIService getCallInsightsAPIService() { return callInsightsAPIService; } public LookupAPIService getLookupAPIService() { return lookupAPIService; } void setApiService(PlivoAPIService apiService) { this.apiService = apiService; } public String getAuthId() { return authId; } public String getAuthToken() { return authToken; } } package com.rocksolidapps.movies.image; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; /** * @author Skała */ public interface BitmapTarget { void onBitmapLoaded(Bitmap bitmap); void onBitmapFailed(Drawable errorDrawable); void onPrepareLoad(Drawable placeHolderDrawable); } 1-10 package pes6j.servers; import pes6j.datablocks.UserInfo; public class HTTPFetchUserInfoThread extends Thread { public final static int FETCHED = 2; public final static int FETCHING = 1; public final static int IDLE = 0; String ip_address; String auth_url; UserInfo uInfo; int status; HTTPFetchUserInfoThread( String auth_url, String ip_address) { this.ip_address = ip_address; this.auth_url = auth_url; this.uInfo = null; this.status = IDLE; } public void run() { this.status = FETCHING; this.uInfo = Tools.getUserInfo( auth_url, ip_address ); this.status = FETCHED; } public UserInfo getUserInfo() { return( this.uInfo ); } public int getStatus() { return( this.status ); } } ses-app/ses-web-website/src/main/java/com/redescooter/ses/web/website/service/impl/base/SiteContactUsTraceServiceImpl.java package com.redescooter.ses.web.website.service.impl.base; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.redescooter.ses.web.website.dao.base.SiteContactUsTraceMapper; import com.redescooter.ses.web.website.dm.SiteContactUsTrace; import com.redescooter.ses.web.website.service.base.SiteContactUsTraceService; import org.springframework.stereotype.Service; import java.util.List; @Service public class SiteContactUsTraceServiceImpl extends ServiceImpl implements SiteContactUsTraceService { @Override public int updateBatch(List list) { return baseMapper.updateBatch(list); } @Override public int updateBatchSelective(List list) { return baseMapper.updateBatchSelective(list); } @Override public int batchInsert(List list) { return baseMapper.batchInsert(list); } @Override public int insertOrUpdate(SiteContactUsTrace record) { return baseMapper.insertOrUpdate(record); } @Override public int insertOrUpdateSelective(SiteContactUsTrace record) { return baseMapper.insertOrUpdateSelective(record); } } 0 package org.gooru.nucleus.handlers.libraries.processors.repositories.activejdbc.formatter; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Set; import org.javalite.activejdbc.LazyList; import org.javalite.activejdbc.Model; import org.javalite.activejdbc.ModelDelegate; import org.javalite.common.Convert; import org.postgresql.util.PGobject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.vertx.core.impl.StringEscapeUtils; /** * Created by ashish on 20/1/16. Simple Json formatter is not aware of any * parent child relationship and just assumes that formatter is needed to work * on the entity provided. The difference with AJ provided Model.toJson() is * difference in handling of "jsonb" field type in postgres */ class SimpleJsonFormatter implements JsonFormatter { private static final String JSONB_TYPE = "jsonb"; private static final int CAPACITY = 2048; private final String[] attributes; private final boolean pretty; private static final Logger LOGGER = LoggerFactory.getLogger(SimpleJsonFormatter.class); public SimpleJsonFormatter(boolean pretty, List attributes) { this.pretty = pretty; this.attributes = (attributes != null && !attributes.isEmpty()) ? lowerCased(attributes) : null; } @Override public String toJson(T model) { StringBuilder sb = new StringBuilder(CAPACITY); String indent = ""; modelToJson(model, sb, indent); return sb.toString(); } @Override public String toJson(LazyList modelList) { StringBuilder sb = new StringBuilder(CAPACITY); sb.append('['); if (pretty) { sb.append('\n'); } for (int i = 0; i < modelList.size(); i++) { if (i > 0) { sb.append(','); if (pretty) { sb.append('\n'); } } T model = modelList.get(i); modelToJson(model, sb, (pretty ? " " : "")); } if (pretty) { sb.append('\n'); } sb.append(']'); return sb.toString(); } private void modelToJson(T model, StringBuilder sb, String indent) { if (pretty) { sb.append(indent); } sb.append('{'); String[] names; if (this.attributes == null) { Set attributeNamesAll = ModelDelegate.attributeNames(model.getClass()); names = lowerCased(attributeNamesAll); } else { names = this.attributes; } for (int i = 0; i < names.length; i++) { if (i > 0) { sb.append(','); } if (pretty) { sb.append("\n ").append(indent); } String name = names[i]; sb.append('"').append(name).append("\":"); Object v = model.get(name); if (v == null) { sb.append("null"); } else if (v instanceof Number || v instanceof Boolean) { sb.append(v); } else if (v instanceof Date) { sb.append('"').append(Convert.toIsoString((Date) v)).append('"'); } else if (v instanceof PGobject && ((PGobject) v).getType().equalsIgnoreCase(JSONB_TYPE)) { sb.append(Convert.toString(v)); } else if (v instanceof String){ sb.append('"'); try { sb.append(StringEscapeUtils.escapeJava(String.valueOf(v))); } catch (Exception e) { LOGGER .warn("Failed to parse value of field '{}', will use default string without conversion ", name); sb.append(Convert.toString(v)); } sb.append('"'); } else { sb.append('"'); sb.append(Convert.toString(v)); sb.append('"'); } } if (pretty) { sb.append('\n').append(indent); } sb.append('}'); } private static String[] lowerCased(Collection collection) { String[] array = new String[collection.size()]; int i = 0; for (String elem : collection) { array[i++] = elem.toLowerCase(); } return array; } } package controllers; import models.DAOFactory; import models.Snippet; import models.SnippetDAO; import play.mvc.Result; import play.mvc.Controller; import play.twirl.api.Html; import util.ViewUtil; import views.html.snippetList; import java.util.List; /** * @author kevinholland */ public class Search extends Controller { public Result doSearch(String term) { SnippetDAO snippetDAO = DAOFactory.getSnippetDAO(); List snippets = snippetDAO.findWithLikeTitle(term); String html = String.format("

search: %s

", term); return ok(ViewUtil.applyToStructure(snippetList.apply(snippets, new Html(html)))); } } source/smnpo-message-starter/src/main/java/io/github/smnpo/message/rocketmq/ConsumerAutoConfiguration.java package io.github.smnpo.message.rocketmq; import com.aliyun.openservices.ons.api.Consumer; import com.aliyun.openservices.ons.api.MessageListener; import com.aliyun.openservices.ons.api.ONSFactory; import com.aliyun.openservices.ons.api.PropertyKeyConst; import io.github.smnpo.message.rocketmq.properties.ConsumerProperties; import io.github.smnpo.message.rocketmq.properties.ProducerProperties; import io.github.smnpo.message.rocketmq.runner.ConsumerRunner; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties; /** * @author: Ming.Zhao * @create: 2019-05-10 11:49 **/ @Slf4j @Configuration @EnableConfigurationProperties({ProducerProperties.class, ConsumerProperties.class}) @ConditionalOnProperty( prefix = "rocketmq.consumer", name = "id" ) public class ConsumerAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnBean(MessageListener.class) public Consumer consumer(ConsumerProperties consumerProperties) { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.ConsumerId, consumerProperties.getId()); properties.setProperty(PropertyKeyConst.AccessKey, consumerProperties.getAccessKey()); properties.setProperty(PropertyKeyConst.SecretKey, consumerProperties.getSecretKey()); properties.setProperty(PropertyKeyConst.ConsumeTimeout, String.valueOf(consumerProperties.getConsumerTimeout())); properties.setProperty(PropertyKeyConst.MaxReconsumeTimes, "2"); properties.setProperty(PropertyKeyConst.MessageModel, consumerProperties.getMessageModel()); return ONSFactory.createConsumer(properties); } @Bean public ConsumerRunner consumerRunner(ApplicationContext applicationContext) { ConsumerRunner consumerRunner = new ConsumerRunner(); consumerRunner.setApplicationContext(applicationContext); return consumerRunner; } } src/main/java/io/eion/security/passkeeper/service/DefaultSecureAccountStore.java package io.eion.security.passkeeper.service; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import io.eion.security.passkeeper.service.bean.SecureAccount; import io.eion.security.passkeeper.service.bean.SecureAccountRequest; import io.eion.security.passkeeper.service.exception.SecureAccountException; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * This class is used by DefaultSecureAccountService class so make it package local. *

* Created by vagrant on 9/14/16. */ @Service public class DefaultSecureAccountStore implements SecureAccountStore { private static final Logger logger = LoggerFactory.getLogger(DefaultSecureAccountStore.class); public static final String ACCOUNT_EXT = ".account"; @Value("${security.keystore.location}") private String keystoreLocation; @Autowired private Gson gson; @Override public void storeSecureAccount(final SecureAccount secureAccount) throws Exception { Assert.notNull(secureAccount); final String username = secureAccount.getUsername(); final File secureAccountFile = this.createSecureAccountFile(username); final Map secureAccountMap = this.loadSecureAccountMap(secureAccountFile); final String accountAlias = secureAccount.getAccountAlias(); secureAccountMap.put(accountAlias, secureAccount); this.saveSecureAccountFile(secureAccountFile, secureAccountMap); } @Override public void deleteSecureAccountStore(final String username) throws Exception { Assert.notNull(username); final File secureAccountFile = this.createSecureAccountFile(username); if (secureAccountFile.exists()) { final boolean delete = secureAccountFile.delete(); if (!delete) { throw new SecureAccountException("Secure account store for user is not deleted for some reason: " + username); } } } @Override public Optional getSecureAccount(final SecureAccountRequest secureAccountRequest) throws Exception { Assert.notNull(secureAccountRequest); final String username = secureAccountRequest.getUsername(); final File secureAccountFile = this.createSecureAccountFile(username); final Map secureAccountMap = this.loadSecureAccountMap(secureAccountFile); final SecureAccount secureAccount = secureAccountMap.get(secureAccountRequest.getAccountAlias()); return Optional.ofNullable(secureAccount); } @Override public void deleteSecureAccountPassword(final SecureAccountRequest secureAccountRequest) throws Exception { Assert.notNull(secureAccountRequest); final String username = secureAccountRequest.getUsername(); final File secureAccountFile = this.createSecureAccountFile(username); final Map secureAccountMap = this.loadSecureAccountMap(secureAccountFile); final SecureAccount removed = secureAccountMap.remove(secureAccountRequest.getAccountAlias()); logger.info("Removed secure account: {}", removed); this.saveSecureAccountFile(secureAccountFile, secureAccountMap); } private Map loadSecureAccountMap(final File secureAccountFile) throws Exception { Assert.notNull(secureAccountFile); Map secureAccountMap = new HashMap<>(); if (secureAccountFile.exists()) { try (final InputStream is = new FileSystemResource(secureAccountFile).getInputStream()) { final String secureAccountJSON = IOUtils.toString(is); if (!StringUtils.isEmpty(secureAccountJSON)) { Type mapType = new TypeToken>() { }.getType(); secureAccountMap = this.gson.fromJson(secureAccountJSON, mapType); } } } return secureAccountMap; } private void saveSecureAccountFile(final File secureAccountFile, final Map secureAccountMap) throws IOException { Assert.notNull(secureAccountFile); Assert.notNull(secureAccountMap); try (FileWriter fileWriter = new FileWriter(secureAccountFile)) { final String secureAccountJSON = this.gson.toJson(secureAccountMap); IOUtils.write(secureAccountJSON, fileWriter); fileWriter.flush(); } } private File createSecureAccountFile(final String username) { Assert.notNull(username); return new File(this.keystoreLocation, username + ACCOUNT_EXT); } } package seedu.zookeep.model.animal; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.zookeep.logic.commands.CommandTestUtil.VALID_FEED_TIME_EVENING; import static seedu.zookeep.logic.commands.CommandTestUtil.VALID_ID_BAILEY; import static seedu.zookeep.logic.commands.CommandTestUtil.VALID_MEDICAL_CONDITION_OBESE; import static seedu.zookeep.logic.commands.CommandTestUtil.VALID_NAME_BAILEY; import static seedu.zookeep.logic.commands.CommandTestUtil.VALID_SPECIES_BAILEY; import static seedu.zookeep.testutil.Assert.assertThrows; import static seedu.zookeep.testutil.TypicalAnimals.ARCHIE; import static seedu.zookeep.testutil.TypicalAnimals.BAILEY; import org.junit.jupiter.api.Test; import seedu.zookeep.testutil.AnimalBuilder; public class AnimalTest { @Test public void asObservableList_modifyList_throwsUnsupportedOperationException() { Animal animal = new AnimalBuilder().build(); assertThrows(UnsupportedOperationException.class, () -> animal.getMedicalConditions().remove(0)); } @Test public void isSameAnimal() { // same object -> returns true assertTrue(ARCHIE.isSameAnimal(ARCHIE)); // null -> returns false assertFalse(ARCHIE.isSameAnimal(null)); // different ID and species -> returns false Animal editedArchie = new AnimalBuilder(ARCHIE).withId(VALID_ID_BAILEY) .withSpecies(VALID_SPECIES_BAILEY).build(); assertFalse(ARCHIE.isSameAnimal(editedArchie)); // different name -> returns true editedArchie = new AnimalBuilder(ARCHIE).withName(VALID_NAME_BAILEY).build(); assertTrue(ARCHIE.isSameAnimal(editedArchie)); // same name, same ID, different attributes (medical conditions and feed times) -> returns true editedArchie = new AnimalBuilder(ARCHIE).withSpecies(VALID_SPECIES_BAILEY) .withMedicalConditions(VALID_MEDICAL_CONDITION_OBESE) .withFeedTimes(VALID_FEED_TIME_EVENING).build(); assertTrue(ARCHIE.isSameAnimal(editedArchie)); // same name, different ID, same attributes (medical conditions and feed times) -> returns false editedArchie = new AnimalBuilder(ARCHIE).withId(VALID_ID_BAILEY).build(); assertFalse(ARCHIE.isSameAnimal(editedArchie)); } @Test public void equals() { // same values -> returns true Animal archieCopy = new AnimalBuilder(ARCHIE).build(); assertTrue(ARCHIE.equals(archieCopy)); // same object -> returns true assertTrue(ARCHIE.equals(ARCHIE)); // null -> returns false assertFalse(ARCHIE.equals(null)); // different type -> returns false assertFalse(ARCHIE.equals(5)); // different animal -> returns false assertFalse(ARCHIE.equals(BAILEY)); // different name -> returns false Animal editedArchie = new AnimalBuilder(ARCHIE).withName(VALID_NAME_BAILEY).build(); assertFalse(ARCHIE.equals(editedArchie)); // different ID -> returns false editedArchie = new AnimalBuilder(ARCHIE).withId(VALID_ID_BAILEY).build(); assertFalse(ARCHIE.equals(editedArchie)); // different species -> returns false editedArchie = new AnimalBuilder(ARCHIE).withSpecies(VALID_SPECIES_BAILEY).build(); assertFalse(ARCHIE.equals(editedArchie)); // different medicalConditions -> returns false editedArchie = new AnimalBuilder(ARCHIE).withMedicalConditions(VALID_MEDICAL_CONDITION_OBESE).build(); assertFalse(ARCHIE.equals(editedArchie)); // different feedTimes -> returns false editedArchie = new AnimalBuilder(ARCHIE).withFeedTimes(VALID_FEED_TIME_EVENING).build(); assertFalse(ARCHIE.equals(editedArchie)); } @Test public void hashcode() { int archieHashCode = ARCHIE.hashCode(); // same values -> returns same hashcode Animal archieCopy = new AnimalBuilder(ARCHIE).build(); assertEquals(archieHashCode, archieCopy.hashCode()); // different name -> returns different hashcode Animal editedArchie = new AnimalBuilder(ARCHIE).withName(VALID_NAME_BAILEY).build(); assertNotEquals(archieHashCode, editedArchie.hashCode()); // different id -> returns different hashcode editedArchie = new AnimalBuilder(ARCHIE).withId(VALID_ID_BAILEY).build(); assertNotEquals(archieHashCode, editedArchie.hashCode()); // different species -> returns different hashcode editedArchie = new AnimalBuilder(ARCHIE).withSpecies(VALID_SPECIES_BAILEY).build(); assertNotEquals(archieHashCode, editedArchie.hashCode()); // different medicalConditions -> returns different hashcode editedArchie = new AnimalBuilder(ARCHIE).withMedicalConditions(VALID_MEDICAL_CONDITION_OBESE).build(); assertNotEquals(archieHashCode, editedArchie.hashCode()); // different feedTimes -> returns different hashcode editedArchie = new AnimalBuilder(ARCHIE).withFeedTimes(VALID_FEED_TIME_EVENING).build(); assertNotEquals(archieHashCode, editedArchie.hashCode()); } } package xyz.erupt.jpa.service; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.core.annotation.Order; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.stereotype.Service; import xyz.erupt.core.annotation.EruptDataSource; import xyz.erupt.core.config.EruptProp; import xyz.erupt.core.service.EruptApplication; import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceContext; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; /** * @author liyuepeng * @date 2020-01-13 */ @Service @Order public class EntityManagerService implements ApplicationRunner { @PersistenceContext private EntityManager entityManager; @Resource private EruptProp eruptProp; private Map entityManagerMap; @Override public void run(ApplicationArguments args) throws Exception { if (null != eruptProp.getDbs()) { //多数据源处理 entityManagerMap = new HashMap<>(); for (EruptProp.DB prop : eruptProp.getDbs()) { LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); { JpaProperties jpa = prop.getJpa(); HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(false); vendorAdapter.setDatabase(jpa.getDatabase()); vendorAdapter.setShowSql(jpa.isShowSql()); vendorAdapter.setDatabase(jpa.getDatabase()); vendorAdapter.setDatabasePlatform(jpa.getDatabasePlatform()); factory.setJpaVendorAdapter(vendorAdapter); } { factory.setDataSource(prop.getDatasource().initializeDataSourceBuilder().build()); factory.setPackagesToScan(EruptApplication.getScanPackage()); factory.afterPropertiesSet(); } entityManagerMap.put(prop.getDatasource().getName(), factory.getObject()); } } } //如果使用了@EruptDataSource多数据源,调用此方法必须手动关闭, close() public EntityManager getEntityManager(Class eruptClass) { EruptDataSource eruptDataSource = eruptClass.getAnnotation(EruptDataSource.class); if (null == eruptDataSource) { return entityManager; } else { return entityManagerMap.get(eruptDataSource.value()).createEntityManager(); } } public void getEntityManager(Class eruptClass, Consumer consumer) { EruptDataSource eruptDataSource = eruptClass.getAnnotation(EruptDataSource.class); if (null == eruptDataSource) { consumer.accept(entityManager); } else { EntityManager em = entityManagerMap.get(eruptDataSource.value()).createEntityManager(); try { em.getTransaction().begin(); consumer.accept(em); em.getTransaction().commit(); } catch (Exception e) { em.getTransaction().rollback(); } finally { if (em.isOpen()) { em.close(); } } } } } ebi-uniprot/uniprot-store1-10 package org.uniprot.store.config; public enum UniProtDataType { ARBA, CROSSREF, DISEASE, GENECENTRIC, HELP, KEYWORD, PIR_ID_MAPPING, LITERATURE, PROTEOME, PUBLICATION, SUBCELLLOCATION, SUGGEST, TAXONOMY, UNIPARC, UNIPROTKB, UNIREF, UNIRULE, UNIPARC_CROSSREF } helios/src/main/java/org/onereed/helios/SunInfoAdapter.java package org.onereed.helios; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import org.onereed.helios.common.TypedArrayAccessor; import org.onereed.helios.sun.SunEvent; import org.onereed.helios.sun.SunInfo; class SunInfoAdapter extends RecyclerView.Adapter { private static final int DATE_FORMAT_FLAGS = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL; static class SunEventViewHolder extends RecyclerView.ViewHolder { private final CardView cardView; private final TextView eventTimeView; SunEventViewHolder(CardView cardView) { super(cardView); this.cardView = cardView; this.eventTimeView = cardView.findViewById(R.id.eventTime); } } private SunInfo sunInfo = null; SunInfoAdapter() { setHasStableIds(true); } void acceptSunInfo(SunInfo newSunInfo) { sunInfo = newSunInfo; notifyDataSetChanged(); } @Override public long getItemId(int position) { return getSunEvent(position).getWeakId(); } @NonNull @Override public SunEventViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); CardView cardView = (CardView) layoutInflater.inflate(R.layout.sun_event, parent, false); return new SunEventViewHolder(cardView); } @Override public void onBindViewHolder(@NonNull SunEventViewHolder sunEventViewHolder, int position) { SunEvent sunEvent = getSunEvent(position); int typeOrdinal = sunEvent.getType().ordinal(); Context context = sunEventViewHolder.itemView.getContext(); TypedArrayAccessor typedArrayAccessor = TypedArrayAccessor.create(context.getResources(), typeOrdinal); int bgColor = typedArrayAccessor.getColor(R.array.sun_event_bg_colors); sunEventViewHolder.cardView.setCardBackgroundColor(bgColor); int iconId = typedArrayAccessor.getResourceId(R.array.sun_event_icons); sunEventViewHolder.eventTimeView.setCompoundDrawablesWithIntrinsicBounds(iconId, 0, 0, 0); long eventTimeMillis = sunEvent.getTime().toEpochMilli(); String timeText = DateUtils.formatDateTime(context, eventTimeMillis, DATE_FORMAT_FLAGS); int timeStyle = position == sunInfo.getClosestEventIndex() ? Typeface.BOLD : Typeface.NORMAL; sunEventViewHolder.eventTimeView.setText(timeText); sunEventViewHolder.eventTimeView.setTypeface(/* tf= */ null, timeStyle); sunEventViewHolder.cardView.setOnClickListener( view -> sendToLiberActivity(view.getContext(), typeOrdinal)); } @Override public int getItemCount() { return sunInfo == null ? 0 : sunInfo.getSunEvents().size(); } private SunEvent getSunEvent(int position) { return sunInfo.getSunEvents().get(position); } private static void sendToLiberActivity(Context context, int typeOrdinal) { Intent intent = new Intent(context, LiberActivity.class); intent.putExtra(IntentExtraTags.SUN_EVENT_TYPE, typeOrdinal); context.startActivity(intent); } } OopsConcepts/src/main/java/edu/prahlad/java/course2/oop/designPrinciples/favorCompositionOverInheritance/before_Inheritance/AutopilotCombustionEngineTruck.java0 package edu.prahlad.java.course2.oop.designPrinciples.favorCompositionOverInheritance.before_Inheritance; public class AutopilotCombustionEngineTruck extends CombustionEngineTruck{ } package com.demo.spring.dependency.inject; /** * @author on 2021/5/3 0:11 */ @FunctionalInterface public interface ObjectHolder { T getObject(); } package com.businessproject.demo.repository; import com.businessproject.demo.model.dbmodels.SaleRecord; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import java.time.ZonedDateTime; import java.util.List; public interface SaleRecordRepository extends MongoRepository { // Finds all sales records that are from the same sales representative List findAllBySalesRepId(String salesRepId); // Finds all sales records that are made in between a start date and end date @Query(value = "{'madeAt': {$gte :?0, $lte: ?1}}") List findSaleRecords(ZonedDateTime from, ZonedDateTime to); } uk-gov-mirror/hmcts.probate-submit-service0 package uk.gov.hmcts.probate.services.submit.model.v2.exception; public class CaseAlreadyExistsException extends RuntimeException { public CaseAlreadyExistsException(String identifier) { super("Case already exists for Identifier: " + identifier); } } /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.telephony.imsphone; import android.content.Context; import android.net.LinkProperties; import android.os.AsyncResult; import android.os.Handler; import android.os.Message; import android.os.RegistrantList; import android.sysprop.TelephonyProperties; import android.telephony.CallQuality; import android.telephony.NetworkScanRequest; import android.telephony.ServiceState; import android.telephony.SignalStrength; import android.telephony.ims.ImsReasonInfo; import android.util.Pair; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.telephony.Call; import com.android.internal.telephony.Connection; import com.android.internal.telephony.IccCard; import com.android.internal.telephony.IccPhoneBookInterfaceManager; import com.android.internal.telephony.MmiCode; import com.android.internal.telephony.OperatorInfo; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneConstants; import com.android.internal.telephony.PhoneNotifier; import com.android.internal.telephony.dataconnection.DataConnection; import com.android.internal.telephony.uicc.IccFileHandler; import com.android.telephony.Rlog; import java.util.ArrayList; import java.util.List; abstract class ImsPhoneBase extends Phone { private static final String LOG_TAG = "ImsPhoneBase"; private RegistrantList mRingbackRegistrants = new RegistrantList(); private RegistrantList mOnHoldRegistrants = new RegistrantList(); private RegistrantList mTtyModeReceivedRegistrants = new RegistrantList(); private PhoneConstants.State mState = PhoneConstants.State.IDLE; public ImsPhoneBase(String name, Context context, PhoneNotifier notifier, boolean unitTestMode) { super(name, notifier, context, new ImsPhoneCommandInterface(context), unitTestMode); } @Override public void migrateFrom(Phone from) { super.migrateFrom(from); migrate(mRingbackRegistrants, ((ImsPhoneBase)from).mRingbackRegistrants); } @Override public void registerForRingbackTone(Handler h, int what, Object obj) { mRingbackRegistrants.addUnique(h, what, obj); } @Override public void unregisterForRingbackTone(Handler h) { mRingbackRegistrants.remove(h); } @Override public void startRingbackTone() { AsyncResult result = new AsyncResult(null, Boolean.TRUE, null); mRingbackRegistrants.notifyRegistrants(result); } @Override public void stopRingbackTone() { AsyncResult result = new AsyncResult(null, Boolean.FALSE, null); mRingbackRegistrants.notifyRegistrants(result); } @Override public void registerForOnHoldTone(Handler h, int what, Object obj) { mOnHoldRegistrants.addUnique(h, what, obj); } @Override public void unregisterForOnHoldTone(Handler h) { mOnHoldRegistrants.remove(h); } /** * Signals all registrants that the remote hold tone should be started for a connection. * * @param cn The connection. */ @VisibleForTesting public void startOnHoldTone(Connection cn) { Pair result = new Pair(cn, Boolean.TRUE); mOnHoldRegistrants.notifyRegistrants(new AsyncResult(null, result, null)); } /** * Signals all registrants that the remote hold tone should be stopped for a connection. * * @param cn The connection. */ protected void stopOnHoldTone(Connection cn) { Pair result = new Pair(cn, Boolean.FALSE); mOnHoldRegistrants.notifyRegistrants(new AsyncResult(null, result, null)); } @Override public void registerForTtyModeReceived(Handler h, int what, Object obj){ mTtyModeReceivedRegistrants.addUnique(h, what, obj); } @Override public void unregisterForTtyModeReceived(Handler h) { mTtyModeReceivedRegistrants.remove(h); } public void onTtyModeReceived(int mode) { AsyncResult result = new AsyncResult(null, Integer.valueOf(mode), null); mTtyModeReceivedRegistrants.notifyRegistrants(result); } public void onCallQualityChanged(CallQuality callQuality, int callNetworkType) { mNotifier.notifyCallQualityChanged(this, callQuality, callNetworkType); } @Override public ServiceState getServiceState() { // FIXME: we may need to provide this when data connectivity is lost // or when server is down ServiceState s = new ServiceState(); s.setVoiceRegState(ServiceState.STATE_IN_SERVICE); return s; } @Override public PhoneConstants.State getState() { return mState; } @Override public int getPhoneType() { return PhoneConstants.PHONE_TYPE_IMS; } @Override public SignalStrength getSignalStrength() { return new SignalStrength(); } @Override public boolean getMessageWaitingIndicator() { return false; } @Override public List getPendingMmiCodes() { return new ArrayList(0); } @Override public PhoneConstants.DataState getDataConnectionState() { return PhoneConstants.DataState.DISCONNECTED; } @Override public DataActivityState getDataActivityState() { return DataActivityState.NONE; } /** * Notify any interested party of a Phone state change * {@link com.android.internal.telephony.PhoneConstants.State} */ public void notifyPhoneStateChanged() { mNotifier.notifyPhoneState(this); } /** * Notify registrants of a change in the call state. This notifies changes in * {@link com.android.internal.telephony.Call.State}. Use this when changes * in the precise call state are needed, else use notifyPhoneStateChanged. */ public void notifyPreciseCallStateChanged() { /* we'd love it if this was package-scoped*/ super.notifyPreciseCallStateChangedP(); } public void notifyDisconnect(Connection cn) { mDisconnectRegistrants.notifyResult(cn); } public void notifyImsReason(ImsReasonInfo imsReasonInfo) { mNotifier.notifyImsDisconnectCause(this, imsReasonInfo); } void notifyUnknownConnection() { mUnknownConnectionRegistrants.notifyResult(this); } public void notifySuppServiceFailed(SuppService code) { mSuppServiceFailedRegistrants.notifyResult(code); } void notifyServiceStateChanged(ServiceState ss) { super.notifyServiceStateChangedP(ss); } @Override public void notifyCallForwardingIndicator() { mNotifier.notifyCallForwardingChanged(this); } public boolean canDial() { int serviceState = getServiceState().getState(); Rlog.v(LOG_TAG, "canDial(): serviceState = " + serviceState); if (serviceState == ServiceState.STATE_POWER_OFF) return false; boolean disableCall = TelephonyProperties.disable_call().orElse(false); Rlog.v(LOG_TAG, "canDial(): disableCall = " + disableCall); if (disableCall) return false; Rlog.v(LOG_TAG, "canDial(): ringingCall: " + getRingingCall().getState()); Rlog.v(LOG_TAG, "canDial(): foregndCall: " + getForegroundCall().getState()); Rlog.v(LOG_TAG, "canDial(): backgndCall: " + getBackgroundCall().getState()); return !getRingingCall().isRinging() && (!getForegroundCall().getState().isAlive() || !getBackgroundCall().getState().isAlive()); } @Override public boolean handleInCallMmiCommands(String dialString) { return false; } boolean isInCall() { Call.State foregroundCallState = getForegroundCall().getState(); Call.State backgroundCallState = getBackgroundCall().getState(); Call.State ringingCallState = getRingingCall().getState(); return (foregroundCallState.isAlive() || backgroundCallState.isAlive() || ringingCallState.isAlive()); } @Override public boolean handlePinMmi(String dialString) { return false; } @Override public void sendUssdResponse(String ussdMessge) { } @Override public void registerForSuppServiceNotification( Handler h, int what, Object obj) { } @Override public void unregisterForSuppServiceNotification(Handler h) { } @Override public void setRadioPower(boolean power) { } @Override public String getVoiceMailNumber() { return null; } @Override public String getVoiceMailAlphaTag() { return null; } @Override public String getDeviceId() { return null; } @Override public String getDeviceSvn() { return null; } @Override public String getImei() { return null; } @Override public String getEsn() { Rlog.e(LOG_TAG, "[VoltePhone] getEsn() is a CDMA method"); return "0"; } @Override public String getMeid() { Rlog.e(LOG_TAG, "[VoltePhone] getMeid() is a CDMA method"); return "0"; } @Override public String getSubscriberId() { return null; } @Override public String getGroupIdLevel1() { return null; } @Override public String getGroupIdLevel2() { return null; } @Override public String getIccSerialNumber() { return null; } @Override public String getLine1AlphaTag() { return null; } @Override public boolean setLine1Number(String alphaTag, String number, Message onComplete) { // FIXME: what to reply for Volte? return false; } @Override public void setVoiceMailNumber(String alphaTag, String voiceMailNumber, Message onComplete) { // FIXME: what to reply for Volte? AsyncResult.forMessage(onComplete, null, null); onComplete.sendToTarget(); } @Override public void getCallForwardingOption(int commandInterfaceCFReason, Message onComplete) { } @Override public void getCallForwardingOption(int commandInterfaceCFReason, int serviceClass, Message onComplete) { } @Override public void setCallForwardingOption(int commandInterfaceCFAction, int commandInterfaceCFReason, String dialingNumber, int timerSeconds, Message onComplete) { } @Override public void setCallForwardingOption(int commandInterfaceCFAction, int commandInterfaceCFReason, String dialingNumber, int serviceClass, int timerSeconds, Message onComplete) { } @Override public void getOutgoingCallerIdDisplay(Message onComplete) { // FIXME: what to reply? AsyncResult.forMessage(onComplete, null, null); onComplete.sendToTarget(); } @Override public void setOutgoingCallerIdDisplay(int commandInterfaceCLIRMode, Message onComplete) { // FIXME: what's this for Volte? AsyncResult.forMessage(onComplete, null, null); onComplete.sendToTarget(); } @Override public void getCallWaiting(Message onComplete) { AsyncResult.forMessage(onComplete, null, null); onComplete.sendToTarget(); } @Override public void setCallWaiting(boolean enable, Message onComplete) { Rlog.e(LOG_TAG, "call waiting not supported"); } @Override public boolean getIccRecordsLoaded() { return false; } @Override public IccCard getIccCard() { return null; } @Override public void getAvailableNetworks(Message response) { } @Override public void startNetworkScan(NetworkScanRequest nsr, Message response) { } @Override public void stopNetworkScan(Message response) { } @Override public void setNetworkSelectionModeAutomatic(Message response) { } @Override public void selectNetworkManually(OperatorInfo network, boolean persistSelection, Message response) { } public List getCurrentDataConnectionList () { return null; } @Override public void updateServiceLocation() { } @Override public void enableLocationUpdates() { } @Override public void disableLocationUpdates() { } @Override public boolean getDataRoamingEnabled() { return false; } @Override public void setDataRoamingEnabled(boolean enable) { } @Override public boolean isUserDataEnabled() { return false; } public boolean enableDataConnectivity() { return false; } public boolean disableDataConnectivity() { return false; } @Override public boolean isDataAllowed(int apnType) { return false; } @Override public IccPhoneBookInterfaceManager getIccPhoneBookInterfaceManager(){ return null; } @Override public IccFileHandler getIccFileHandler(){ return null; } @Override public void activateCellBroadcastSms(int activate, Message response) { Rlog.e(LOG_TAG, "Error! This functionality is not implemented for Volte."); } @Override public void getCellBroadcastSmsConfig(Message response) { Rlog.e(LOG_TAG, "Error! This functionality is not implemented for Volte."); } @Override public void setCellBroadcastSmsConfig(int[] configValuesArray, Message response){ Rlog.e(LOG_TAG, "Error! This functionality is not implemented for Volte."); } //@Override @Override public boolean needsOtaServiceProvisioning() { // FIXME: what's this for Volte? return false; } //@Override @Override public LinkProperties getLinkProperties(String apnType) { // FIXME: what's this for Volte? return null; } @Override public void getCallBarring(String facility, String password, Message onComplete, int serviceClass) { } @Override public void setCallBarring(String facility, boolean lockState, String password, Message onComplete, int serviceClass) { } @Override protected void onUpdateIccAvailability() { } void updatePhoneState() { PhoneConstants.State oldState = mState; if (getRingingCall().isRinging()) { mState = PhoneConstants.State.RINGING; } else if (getForegroundCall().isIdle() && getBackgroundCall().isIdle()) { mState = PhoneConstants.State.IDLE; } else { mState = PhoneConstants.State.OFFHOOK; } if (mState != oldState) { Rlog.d(LOG_TAG, " ^^^ new phone state: " + mState); notifyPhoneStateChanged(); } } } 0 package com.phoegel.bridge.example; /** * 从 mysql 读取数据后转化为 txt 格式的文件类 */ public class MysqlToTxt extends TxtFile { @Override public void translate() { System.out.println("从 mysql 数据库读取数据"); super.translate(); } } src/android/FirebaseFileUploadPlugin.java package by.phaneendra.cordova.firebase; import android.app.ProgressDialog; import android.content.Context; import android.database.Cursor; import android.media.ExifInterface; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.util.Log; import android.widget.Toast; import by.phaneendra.cordova.support.CordovaMethod; import by.phaneendra.cordova.support.ReflectiveCordovaPlugin; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.common.util.concurrent.AbstractScheduledService; import android.content.Context; import com.google.firebase.FirebaseApp; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; import com.google.firebase.storage.FileDownloadTask; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnPausedListener; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageException; import com.google.firebase.storage.StorageMetadata; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.function.Consumer; import org.apache.cordova.CallbackContext; import org.apache.cordova.PluginResult; import org.json.JSONException; import org.json.JSONObject; import static java.util.concurrent.TimeUnit.MILLISECONDS; public class FirebaseFileUploadPlugin extends ReflectiveCordovaPlugin { @CordovaMethod public void uploadFile(String imagePath, String imageRefForUpload, final CallbackContext callbackContext) { ProgressDialog progressDialog = new ProgressDialog(cordova.getActivity()); progressDialog.setCancelable(false); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setMessage("Preparing to Upload..."); progressDialog.show(); Context context = cordova.getActivity().getApplicationContext(); FirebaseStorage firebaseStorage = FirebaseStorage.getInstance(); StorageReference storageReferenceProfilePic = firebaseStorage.getReference(); StorageReference imageRef = storageReferenceProfilePic.child(imageRefForUpload); try { imageRef.putFile(imagePath) .addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { imageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Uri uri) { progressDialog.dismiss(); String imageDownloadUrl = uri.toString(); JSONObject jErr = new JSONObject(); try{ jErr.accumulate("url",imageDownloadUrl); }catch(JSONException e){} callbackContext.success(jErr); } }); } }) .addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { progressDialog.dismiss(); Context context = cordova.getActivity().getApplicationContext(); Toast.makeText(context, "Image Upload Failed..."+exception.toString(), Toast.LENGTH_LONG).show(); JSONObject jErr = new JSONObject(); try{ jErr.accumulate("response","error"); }catch(JSONException e){} callbackContext.error(jErr); } }) .addOnProgressListener(new OnProgressListener() { @Override public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount(); progressDialog.setCancelable(false); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setMessage("Uploaded " + ((int) progress) + "%..."); } }); }catch(java.io.IOException e){ Log.d("image Error",e.toString()); } } }jonathannewman/pcore-java package com.puppet.pcore; import com.puppet.pcore.parser.Expression; import java.net.URI; /** * Provides the ability to parse and evaluate type expressions in String form. */ public interface TypeEvaluator { /** * Parses and evaluates a given {@code typeExpression} and makes it available under a given {@code name}. *

* If the expression_ evaluates to an {@code ObjectType} or a {@code TypeSet}, then that * the object is bound and returned. All other types will be bound using * a {@code TypeAlias} and the alias will be returned. * * @param name the name to use for the type * @param typeExpression the expression that evaluates to the type * @return the bound type or type alias. */ Type declareType(String name, String typeExpression); /** * Parses and evaluates a given {@code typeExpression} and makes it available under a given {@code name}. *

* If the expression_ evaluates to an {@code ObjectType} or a {@code TypeSet}, then that * the object is bound and returned. All other types will be bound using * a {@code TypeAlias} and the alias will be returned. * * @param name the name to use for the type * @param typeExpression the expression that evaluates to the type * @param nameAuthority the name authority for the given name * @return the bound type or type alias. */ Type declareType(String name, String typeExpression, URI nameAuthority); /** * Evaluates a given {@code expression} and makes it available under a given {@code name}. *

* If the expression_ evaluates to an {@code ObjectType} or a {@code TypeSet}, then that * the object is bound and returned. All other types will be bound using * a {@code TypeAlias} and the alias will be returned. * * @param name the name to use for the type * @param typeExpression the expression that evaluates to the type * @param nameAuthority the name authority to use for the declaration * @return the bound type or type alias. */ Type declareType(String name, Expression typeExpression, URI nameAuthority); /** * Resolves a literal expression. The expression may contain numbers, strings, boolean, * undef, array, hash, or type expressions. * * @param string the string to evaluate * @return the resulting object (hash, array, string, type, etc.) */ Object resolve(String string); /** * Resolves a parsed expression. * * @param expression the expression to evaluate * @return the resulting object (hash, array, string, type, etc.) */ Object resolve(Expression expression); /** * Resolves a type expression and returns the type. It's an error if the expression does not * resolve to a type. * * @param typeString the type expression to evaluate * @return the resulting type */ Type resolveType(String typeString); /** * Resolves a type expression and returns the type. It's an error if the expression does not * resolve to a type. * * @param typeExpression the type expression to evaluate * @return the resulting type */ Type resolveType(Expression typeExpression); } package com.example.library.util; import android.content.Context; import android.view.View; import com.example.library.holders.MaterialAboutItemViewHolder; import com.example.library.items.MaterialAboutActionItem; import com.example.library.items.MaterialAboutItem; import com.example.library.items.MaterialAboutTitleItem; import static com.example.library.util.DefaultViewTypeManager.ItemLayout.ACTION_LAYOUT; import static com.example.library.util.DefaultViewTypeManager.ItemLayout.TITLE_LAYOUT; import static com.example.library.util.DefaultViewTypeManager.ItemType.ACTION_ITEM; import static com.example.library.util.DefaultViewTypeManager.ItemType.TITLE_ITEM; public class DefaultViewTypeManager extends ViewTypeManager { public static final class ItemType { public static final int ACTION_ITEM = ViewTypeManager.ItemType.ACTION_ITEM; public static final int TITLE_ITEM = ViewTypeManager.ItemType.TITLE_ITEM; } public static final class ItemLayout { public static final int ACTION_LAYOUT = ViewTypeManager.ItemLayout.ACTION_LAYOUT; public static final int TITLE_LAYOUT = ViewTypeManager.ItemLayout.TITLE_LAYOUT; } public int getLayout(int itemType) { switch (itemType) { case ACTION_ITEM: return ACTION_LAYOUT; case TITLE_ITEM: return TITLE_LAYOUT; default: return -1; } } public MaterialAboutItemViewHolder getViewHolder(int itemType, View view) { switch (itemType) { case ACTION_ITEM: return MaterialAboutActionItem.getViewHolder(view); case TITLE_ITEM: return MaterialAboutTitleItem.getViewHolder(view); default: return null; } } public void setupItem(int itemType, MaterialAboutItemViewHolder holder, MaterialAboutItem item, Context context) { switch (itemType) { case ACTION_ITEM: MaterialAboutActionItem.setupItem((MaterialAboutActionItem.MaterialAboutActionItemViewHolder) holder, (MaterialAboutActionItem) item, context); break; case TITLE_ITEM: MaterialAboutTitleItem.setupItem((MaterialAboutTitleItem.MaterialAboutTitleItemViewHolder) holder, (MaterialAboutTitleItem) item, context); break; } } } 0 package com.sqa.chn.modules.access.service.impl; import com.sqa.chn.modules.access.entity.XiangMuXinXiBiao; import com.sqa.chn.modules.access.mapper.XiangMuXinXiBiaoMapper; import com.sqa.chn.modules.access.service.IXiangMuXinXiBiaoService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** *

* 项目信息表 服务实现类 *

* * @author GodMeowIceSun * @since 2021-08-06 */ @Service public class XiangMuXinXiBiaoServiceImpl extends ServiceImpl implements IXiangMuXinXiBiaoService { } /* * TaskUnifier * Copyright (c) 2013, * All rights reserved. */ package com.leclercb.taskunifier.plugin.toodledo.calls; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import com.leclercb.commons.api.utils.CheckUtils; import com.leclercb.taskunifier.api.models.Context; import com.leclercb.taskunifier.api.models.beans.ContextBean; import com.leclercb.taskunifier.api.synchronizer.exc.SynchronizerException; final class CallEditContext extends AbstractCallContext { public void editContext( ToodledoAccountInfo accountInfo, String accessToken, Context context) throws SynchronizerException { CheckUtils.isNotNull(accessToken); CheckUtils.isNotNull(context); if (context.getModelReferenceId("toodledo") == null) throw new IllegalArgumentException("You cannot edit a new context"); List params = new ArrayList(); params.add(new BasicNameValuePair("access_token", accessToken)); params.add(new BasicNameValuePair( "id", context.getModelReferenceId("toodledo"))); params.add(new BasicNameValuePair("name", context.getTitle())); params.add(new BasicNameValuePair("f", "xml")); String scheme = super.getScheme(accountInfo); String content = super.callGet(scheme, "/3/contexts/edit.php", params); ContextBean[] contexts = this.getResponseMessage( context, accountInfo, content); if (contexts.length != 1) throw new SynchronizerException(false, "Edition of context " + context.getModelId() + " has failed"); } } package org.glob3.mobile.generated; // // ICanvasUtils.cpp // G3MiOSSDK // // Created by on 07/05/14. // // // // ICanvasUtils.hpp // G3MiOSSDK // // Created by on 07/05/14. // // ///#include "ILogger.hpp" //class ICanvas; //class GFont; //class Vector2F; public enum VerticalAlignment { Top, Middle, Bottom; public int getValue() { return this.ordinal(); } public static VerticalAlignment forValue(int value) { return values()[value]; } } Repast/repast.simphony package repast.simphony.scenario; import java.io.File; import repast.simphony.engine.environment.ControllerAction; import com.thoughtworks.xstream.XStream; public class DefaultActionLoader extends ObjectActionLoader { public DefaultActionLoader(File file, Object contextID, Class actionClass, String actionRoot) { super(file, contextID, actionClass, actionRoot); } /** * Override this method if you need to prepare the XStream before using it. * * @param xstream * the XStream that will be used for reading in the descriptor */ protected void prepare(XStream xstream) { // do nothing } @Override protected ControllerAction createAction(T data, Scenario scenario) { return data; } protected ClassLoader getClassLoader() { return dataClass.getClassLoader(); } } class FBY { } class Db0sS4td { public static void XAiM (String[] Z3wjiz) throws Fdzjppbwd { if ( true.T) false.w(); int[] g = !----cjPIvT3VW()[ true.zwP2IAjupb()] = !null.whb77v2; x DePhOqb6xWDDU; boolean pyL; int[] M1F8VgDpJqLyAJ; int fcTqtH7RoOT31 = yBYS.ru35Zunazf() = --!false[ new void[ -PerxqMRu0lHx().VPBes].Og()]; ; boolean KOuOCGjP; } public static void vJovYKzU4gNL1 (String[] I) { return; void zZNA8avPm; Pst[] V6 = false[ --w[ 54739.Ilcm3P20MhZl]]; _qjJbTM0 xhWkTq = ( !!false.IiLNEzdRWiVnnE())._w_bZMED() = null[ -( new y6OKxsScjkMa[ new ux_().U0TOsB9psPjnZd][ !false[ 241.J7LaCty()]])[ new void[ -this[ false.KeJ]].HtTZUaYCCDz_6u()]]; { !false.W4NY00YMbeQmV(); -!false.J5l5dsYSnfB0P2; int kpLsqq410xRHMZ; if ( new int[ j_X3RFETKHw_1().Zfdwlwc()].ym3ELb43I) -new a().P1; { -new Zc5y0LxppaGDI[ -this.DaL][ !-!!this[ false.Mz0TLaW88U3c]]; } int Ti10; if ( true.AJffdJgo4l1A8()) 9.TFYPclXghF5TEK; void W5A5Y; int BBI; int[] ROk8Fj153fnIh; int[][] nQjMXXp_UzENH; { void[] VXP; } hC2E202v9glZcU[][][] yFPEdMRsYT; return; void xYrEYNqAXy7; ybXkkM1z jGsEtuYd; return; if ( -!81318.lzfSePkEkTR) if ( !-Z7yH()[ null.wQ0o]) { while ( ( this.R372Njt14f()).Q()) !zQZenxhup0cGha._vDakfOQVWMnjH(); } int[][][][] oB2vakRSSkX9; } boolean[][] ewMVnDoLVu = false.Nq67q5() = !!!new boolean[ new C().IPSTtl()][ -EMgr6p[ new Z().gCENc]]; int yyP1wYe = --false.kYJdyFErlhHyf5 = wTrXL8z2lNqs[ null[ -( true.eyxv0qzUzKmT).DXBxamrtarVJ9]]; if ( null.rECj()) if ( -false.Hg6JhA5XR) while ( new void[ -true.Oyba9t3lSa].J()) { ; }else { null.P; } void[] zxt4C9VKQ5; { { ; } { while ( !new _pa1().Inpz8OXHH()) ; } { void[] VK9Vzbo13LWdCY; } boolean[] SuLKU6oXBAl5W; if ( null.Xnc) if ( !( null.gjGDsiL1jbAZ()).eDQ4X()) ; -d.pJX9s; ; !-new T3WcgKD3FCzL().y0L(); boolean _IhH; int[] enq; true[ !jBDsJUuK().eaOsSRWNrmr]; int[] dqhn9AQjpRqg; { int Z0kl6bPNTOdXWX; } ( -k6qmRxJHrtyNfD[ !!-!!QeE().aiAs3KxMUA2()]).WiJ_VsU(); boolean[][][] HdkWt; if ( ---true.nj8n5YOm) if ( new iy3EZxfzlA[ wFpgeIhVA4X.r()][ !( ---!wevLnA0y9Y().iF56g())[ -null[ !!!-DqmYIPsLE()[ !!new UMz7VwU_K().LozvT6Fk2VxJ]]]]) if ( !---new gcMTp_Wlk()[ -this.JsW()]) while ( !!true[ ---!-false[ null[ new k9k0CokVS3Kms().EGKGIdphYOHa]]]) return; } while ( -new gP1sqmpIP4Maf().n_La4gt86Lu) while ( 6.h53Cx()) while ( TM5y2F2tkEO.PP7HEX()) { while ( ( false.Eabg1llbi()).iC()) !true.qq5m6(); } 352794567.Nsaxoavti1(); return; if ( -true[ true.K6igbTotCYV()]) while ( 0.S()) while ( !true.dUziml1kW()) ; d7[] gqK1BPd6hGG7x; ----new void[ !this.yV()].v5_gC(); boolean[] WpXQhJ1WCsBlk = new boolean[ !!null.CcBka].Hl3PhpC; } public boolean Y1gWBjRBQa; public int[] HGdOl; public a39IcF e; } class q9Q { public z5 oKha94vf82qZ6 () throws _ { ; return !-aSTEA2()[ -pPLieKy39().ss6()]; ( !( false.qWz2sV8Wms5()).Mj2BeP()).U_nMYZrXJLtp_R(); !new JZ3iNXku()[ -!new void[ !!!-new void[ !-!new zXNVtNeKx()[ this[ null.dUD4qEFELFI()]]].ajp993cnFuNT][ true.RiGjg()]]; void[][] hx; int[] cNc5 = l61e.wJPkweJN0ZS(); int ZyRhFYK = --!-!true.H4mDIh7sDRoGO() = -xQnG7_c.Xn7eQ; void xOaSvCg_yJ; W[] woSIIZhkDdd; !!( false.layPMCqN).m(); void UGYCoi9Z = !-this.ELBs_dGTt6bwPQ = this.Tuy5KeZqVOZ3; jiBxk[][] DNJ5ey3bK = !new int[ QX9WpWXD().NF0qGwXoDS3P()].yjdOcz6MDbnxs() = --!-new oLR[ !--false.XZqLmmR4H].gMb_xuDsikJnii; M_tS0U l1y2HGv; boolean[][][][] Vv; { { int U; } boolean YU8yMN4OG; ; } { BCF4SKL5ePHP[] RvtDCuRrj; nZZ_W5RCH4N rj2n2xC; void[][][][][][][][] STr; if ( Kbfnkm().kyJ_G_0E4F) ; boolean pdnLzPbm8u; return; return; while ( hhXOY7().W39qcmBLawb25) while ( !!40573.UQF) return; return; while ( !q().T) return; return; ; int[] OuS; { int[] mUk5; } void ledSJ; ; boolean ZMFusp; } new amJnsi().r0qg(); } } class H { public static void kE (String[] qHHlyxO2cX) { boolean yGdsXLFRf = new DwDgyP[ 202[ !-!MVz_X8uk1i().GTJ033mRxE9aSf()]].v2C0Q7zuwGAuZP() = this[ !--!( true.WdLol4YR)[ ( ( true.s_7o8t0m8Slna()).A0B2xyaUyd())[ 4.oE]]]; while ( !-!new f[ !false.QftbB36tykRS].O9OOX07A6Bx()) if ( -null[ O[ new QWrjl8i_V8().UqIZg]]) while ( !-!96.jtMmcVkF()) ; void[][][] bT8; int O4OakXV1qm7Yp2; while ( !!this[ --!new HiKxN0TdVcTJ().O]) { int[][][][][][] coEut; } { return; boolean[][] TZEfJqhl3RS7L7; if ( -!818.hUZCTkqu8Kx()) ; void[][][][][] WD4vo; void[] vLuFF0; void _F9PmIxruQE; -null.EB43; while ( new Ng().sB_tXtcjUuvzRZ()) { int BC; } } int RS = !true[ false.ZdQmE()] = new i_gC3Yz31sehrO().YShZPGzvP6; new boolean[ !!true.oPcXe36()].FpbPgUJgV; boolean[][] CRLYWAmH4hNH1 = null.ozlNRROUOD4() = ( !ZzmDlNbugloWPw()[ new boolean[ true[ this.FR6()]][ !( new xNl().U21zpCs()).gw6]]).ZDg0MG2; { int[][][][] XhGpd4B; void[][] XJuQ0pD6qFT; boolean[][] qkAWRb; ; { return; } while ( -pD0DGP().HWIu0Pmiggt5e()) if ( this[ !-!----!!-new O().yQqH]) { void zmm_z3; } while ( --!( ( ueiJOEYT6[ !false.y1U2oGT]).r6y)[ !true.A]) { ; } void[][] rhqQ0oYGfz; boolean[][][][][][][][] hKo2mFUtWjV; } _SVY8ZFLtUsm BfP6SN53V4qJ1 = wPpt.AY7lPWw3ijiu = --true[ new F4KFpEQR1pJ().juZu025eRtSM]; while ( -wys3_8vq1XBLiP[ -this.Qa4()]) return; boolean[][][][] yYAeKjE; } public void[][][] LvOUDH4; public static void WAB7sti22RWf5 (String[] lSJbhC9) throws UqDwoUSq { return true.QkB(); ; int Y5mSpt_31mK = ----!-!461.HGdgjVcTan(); c1ZO zVwo; LSYnnAm9IO[] xSto; if ( !true.naiC4U()) if ( null.VVwDWtbwBI5()) -new int[ -!!true.WiJfXj()][ true.ght9hs8VN8bWG]; bCKX[] A = !false.BMucn_CgmZtY3(); void[] YcI; while ( false.BrRblkIyr6d()) return; boolean ygUCMUJLs5; !this[ 3950289[ -!new mKyr()[ false.z()]]]; void[][] Y; int _8qTNPoCC5q0Ou; boolean th5fKFNzYa = JalDB0iZti()[ !m9Lw21DEQEjvnN[ this.zgxySvGe5]]; } public boolean mJ () { tWG5BVj4St[] uH; { ; 933392132._q; int vt; int ilKe_tg; while ( -( new sd_Di().TyqT8tSE).agAhIdJ7) { void[] IsygaTRvAkTm9x; } OfU8f_vn0kZ34 GGbf; boolean[] wi2m3Ocofrj; void kCF8bEjadTJe; boolean uei5Kd6pZ8; while ( -!-!!!-new rX8HWZzX3YtM()[ -true.f]) ; --!-this.OdScqVOgjA; !0[ 83.IcdH6xxeLOiA5]; void[] jf; void[][] kKB0xGZLEz; ; v0crKdnOD[] NAJgCMnDu; } void SmX2bz0 = ( -OjMl[ new void[ ( --!!-!-AApx0DzBR6nz[ !false.ekWANi])[ true[ !!Ofz.eww29nAVwx6wr()]]].i4()])[ -!new ZfAmeBw8DZnVI()[ !!true.r2ugEmHn1]] = this.Fgc(); return new void[ !null.W7()].cpS1NYRJfd8Kbu; ; int[][] CrLoXrQh5gp; } public static void yqnJAM (String[] DWBCe2vR9E) throws ob { return; int D3NEQ66; ; void[] xm2j5VKNH = NA_()[ this[ -( !!true.b8Pxsf66OolyXi())[ QjPyjTSV9A[ new Dg6ebR().dE()]]]] = !--!new int[ -false[ 3._yH()]][ !-!-true.Al_P3QcUYFE4Ws]; boolean P0l = ---new ReO_tG2yIosRP().qIBgLaTYmiSsj(); void[][] ft23PJ = -new au5rhBVBj()[ cR0OA().ChJs4awI9Ur] = !-true.T9KmkZOCe(); ; o89sactaKWsJ5r oLcc4PAk5Mboc; ; int[] sXYuc_ZYlwrXv; return -!this.sk_SiNZQi_f(); return ( null.Od())[ 1250494.xjYD5kmsIFRyv]; } public UWhX_8A9exsbQ Ry () throws bVvAtowhsic { int LaGsS = !-n7m()[ null.FZnm()]; } public static void G844yN8Y2kPh (String[] dIs9uLFQhwMa) throws cncTzNBVH_TXy { if ( !true.zhTwsk6NN()) -( !!new r1().brAQJ0Ba).wWnv7GAq();else { X2_8Bsz5dRNCL OuTO5zlHGi1; } V1weU_x6x8SaKI[][][][] tM = ( --new wFcf_HpdoaUT6[ -new boolean[ -!45931950.K3n()][ ( this.vFRa_SNPc).Pszu23pE8Xr0JS()]][ -new int[ -309.a()].gNZNent634a8G()]).Tr6Y2G = !!!-bcHvx[ !-!new WtG38kJGkOW()[ -new m7PUv()[ 2931.HuNW]]]; !2142.X(); boolean PyCaGJFV9nQ = null.PnO() = !!this.Lpkqk4; ; int WLjN_2Ua9n = this.shagWlK0cm4W; } public static void yL (String[] UBGbeX) { if ( null[ !--true.msFaTiuY()]) return; if ( true.TkJ) -new int[ !true[ !--true[ !new void[ null.Hs][ -!--( L2wD18().hFbxCfwt()).UrM]]]][ -new ne_6YulW().rL];else return; { while ( !!-kvm[ !-OQrHeH34.a5H_0o]) while ( -this[ !-Ssy4SYzNgQRVym.uVaDKYtly]) while ( false.Npvwg9V()) return; boolean[][][] R; return; void[][][] AuO3TK21kyxWAZ; boolean HFiW3PUWPNZkbh; boolean[][] mJm1OEQR7A1; { void ZBTYq7WEW6pov; } FoV29 OwqdmLZ; if ( -!!zNqj7uoV1NTDdo()[ --!!( --new t()[ new FQITBnGSl51QW().W5i_Vp7]).Nu72X573mgcpf]) while ( 48.wdMRHQ()) if ( true.AW9CV()) { return; } { while ( ( -----!this[ 2324.fyuByin()])[ -bt7BbOHFK5._Az2]) if ( new n78[ !new int[ !!!new void[ -!!this.UUEW73e()][ --new sGDNa3T()[ !W().rLN8_0dA]]].WGp0Pi][ -_WFLD5QUekDaP.Yni()]) return; } boolean rcZn2TEe; zpfMEPzqm qRSEinex2; boolean[] NPU; int EU84g3FLg2Fam; ; R W6hC; false.chyN5ODaLw(); int Z6; boolean _7k1ud; } return null[ --!( -new boolean[ !!true.eFJ()].DVEk)[ --!new EQGX3bRttwD()[ !!oeN9mfDFeYpUTx[ --!!( false.FYw7MM9HOd)[ new void[ true[ this.WwaYK3qw()]].lyy0qk73lr4]]]]]; while ( false[ -null.wQ2Wr8sXSGWe()]) ; AUp PmA05y5RvZ = --T39bSeS1zuH.rYH0WgZvC7I = -!-1.WS5Fg2YFzvw; { return; pa2kgUIJXcaLV rIsBwKM0t; { --!new int[ new qcVE()[ NW.qozHvDsi6()]].OWseZ(); } if ( !false[ !-false.ey]) { if ( this.o7JicW()) { return; } } ; return; void[] BVz6gH7HoEWLN; void[] kc; int[] S; return; } ( !-!-true.uwrVzRkbI9Lfeu()).KblTEpvvx49HqF; X4Ew8i oW; ; int EOM_XzMAfk7guc; } public void KQGuodx; public rwr1oa LNSx (boolean[][] uq8gdqede, int[] kqWziJ, boolean OT8sl8GW) { f0nHkWoC[] r23F1m47VXe = -( !-!!!( false.LJGqbaA).XGB9b9FP_4Z5L()).RrOtqXYJk(); boolean[] vnHMnzXzqn_ = false.hBncg0_JsxH() = true.ws0WVlQmhvwA; while ( 924214.BvJTD) while ( true[ new v1MpgQ().gFXp8nb2]) ; int TAb = new o0XkES2fcM().GrTIm; ; while ( false.QT()) ; void[] IMml_uCk; RDHPrNTnB[] nLH; while ( pDzES1o003[ 755252854.jxJO()]) { ; } void ShA06kAWEuPF = -false.k0Z2jo() = -!!new L()[ !9697[ this.cgNb()]]; void hq = false.E6d() = this.DtUg(); void[][] eER_Lz; RF8_ Bmvrh9dO; void[][] x7M8HKosXuuaHf; boolean DCNRKQ; ; ; !79.riAHS4op0s1; pm5AExMsgFNvBz u = true.H2nYNLY = true.X53jv(); } public gzuMJMlDLv2a t3nrVije7Vf (S_ftzWXvTSz[] cggx_AffG, void n5TP1YtmBa) { ; } public static void V3MIqns (String[] m9G) { int[] r2X; boolean W9e9; return dL6BFlwmBT().CFLOqfQMLi6PX1; int[] mj_; void[][][][][][] f7cetep_ezK4 = 82[ lH.m0bQlW2i7BPQA]; } } class X9wySv { } class NnOEI { public boolean[] UpIJKuyC9XhN7N; public boolean YEcKAU8k_S7SwM () throws r { return; return this.Rg4k9ThG4Ey; int[] A0t = ( this.L289g69QU20jFg())[ this[ false[ this.IRxCAWP_cI5JsS]]]; Flh0YtOCnFu d; void kXKZfQ8 = false.UBKfrSJ3; void DL98UbgmtI9c; qX4Z5mjN[][] Rf4eNrSozXG7 = !50128408.TG; if ( 526.ycp0_v7ar2TgE3) ;else ; while ( -!-!this[ !!!this.Tr1]) ; boolean[] q = new boolean[ null[ -this.Op_28Ra7n_c()]][ true.GPWCcn0XF8W]; boolean CQdAjJi7V; boolean[] kwnc; if ( !new int[ !( --zfYUQqiN.iEeBg5)[ !-OLtAOcT().Dog2YI]][ true.A6ScJPkgCfTD()]) while ( -true[ Zz()[ -null.Vrf9U2_zMXlc_f]]) if ( 338.Qhd()) if ( !!!!Ga607SwZSBND7.F_1BRK) if ( !null.inCdtd5Bm) { void[] XtGqQP9; }else !LdL1zR().qFcGeEt(); } public int R (PKZ e_jEmxPSA, void[][][][] Db, P7NYveGlW yBrHd7oeP, QsFly i4fQmu, void IBZHS, void[][] Ko) throws ED3dnGjAL2P_SX { void P = !-!!YFivHvp()[ !!!true.D01Jf8ps3343Q]; while ( -!3[ !true.aYCF()]) new void[ !new HzSY2eV8().u].Khod_9wTeY; return; } public boolean[][] aosWkvoe (int XRKiDTtytWY, boolean lGLkt) { while ( this[ -!!this[ -322976[ !Y1Ap4b()[ !true.XYScU]]]]) return; boolean[] cFU3yZMIb07vx; } public VjxO2AX_IdSa[] vSDAb6w8DS (hG3fP3GjiEF1Zz[][][][][] Yigcu1rHXfZ, LobC[][][] U38X_Mlht, gxz1A[][] AoFZ4a, boolean[] cswpAXb0eyEgN) throws DyDutFNZMl { PEwYwGqe[] f3i4MRZGKlRSxv = new void[ -false.enO7WuYU2o()].A9WSr(); Q1h9nopWTCyI0 otyyTWx0y9a4o = true.uD45PrpdJpa = -null[ new void[ !new mS().kcx6tRLKazbs()].BpPV_EVBVjlIw()]; if ( this[ true.X_E()]) ; { EWrpu13LFZ5Tn aOewsJTEZkV; while ( new J18f31nCZruzX().w9Iz()) if ( 61013287.Bo) -false[ w427bd3lUxGo8()[ -null.Szm1zG9MkZePKR]]; new boolean[ null[ null[ IZ.wd]]][ -os().qAbNcQV]; void[] HMM8; while ( -false.J) while ( this._E96y) !!pkSwKI[ null.uVAKW8()]; OSD4[] x556WPtS8sKS; kNSDwLECh47EJc Lj3vuZQrBua; void ZwDswrKvs8xC; if ( ( -!!!this.dc6zs5TWXA6Ec)[ -true.ehuewJ()]) return; ; { boolean[][][] hdfy; } boolean TEJHfN4NN; gG4hZm0eSF[] hD24K; } if ( this[ -true[ -new boolean[ ( o2jo0()[ !new boolean[ null.gmOKU51XB33rH()].rL_])[ true.cc8Rhvz]].j8A]]) return;else { while ( new S7UsP[ !( !null.Sn48N8_eeoW())[ !!-!zlXzMJw().h]].bx5DkeMbWLFm()) ; } if ( new WqSucHlWpk9Z().EpB) { boolean cHdZdc85xYTow; } boolean[] HD8ENT = new PsU().Mt() = 1570765.rqGxa1NMmW; return; return rn().R; void o6VgBEIU; return; if ( !!-new g8Nmg().ixL) { if ( -false.KE2ysv_yrOef()) if ( -new g().AMc5kM()) return; }else -!-true.LEsTbB4_h_3Fx(); boolean C1UBPhOWu = !-r[ --42.W3Lj7QS0YKqU5]; ; void[][][] oBlc3V5b5 = !true[ !new void[ B2vfqvk.ITcxC][ null._()]]; boolean[] txZ60Cs3 = !false.Yb2z() = !new UQxqXRhPZOco().OG8AvVt; int AH7mfH4zwxy2Q = !!null.t2EV2BlggsIE = !new ZPLP9qdrbQ176w().f(); } public static void cXU5bYXxy56 (String[] twfqVx9aba0s) throws rDYuc0Z5XEz { if ( !( -( u58aoI().zZ778SdEPEf()).xugR_Q4ix6MnkO).Tk1AXw5yn) if ( !new int[ null.bQy()].o_4I9xfJY) ; P Yfh23B4RZdT; { void[] pDixbk; while ( ( --Ll3X_oQS4KKB.KzejyG3q()).SKjaCbCTeG_()) if ( -036.X1QDCEYQKWOuu) while ( -this[ this.hblPhHd4BiB]) -false.wwxggJoM2; while ( -!-001308518.G5qNBnxrbz()) { if ( 9516.op_wHmo6X8fqPZ) if ( !!tqetNddFm9g1().dwlq_d) new y1v().Md3bP5H7erq8; } while ( !xnEl5.FZ868aF) return; { _6[][][] s0; } boolean[][][][] TfSgu6yle; return; y_FJyl1[][][] tPDCseUrH4O; while ( new twzFjpmDiJ8NI[ -!!--!-!new void[ VvCeGOHT[ new mVamzuwCT15lEM()._BsK4nfAxX8k]][ new bZkz4FxEEvOmo[ !!false.iXtokue1o()][ this[ ( new void[ null.j1sJlrY][ r48O9jh42W.wIrjG_PdUYZe()])[ !!this.yKHmtY46l]]]]].n7R04nWE) ; if ( -!-( -true.nb4SrujJ8nD0()).ul) !this.pyjZ3RLOe; if ( this[ !8167.YKE()]) if ( false.stmFMaim52tE()) ; } return; tHA[][][] ae = Yu6vAde().h535Kj8F_n(); { boolean[][] jQMuUslkFQw3FG; if ( !new cWmi().lW7C) ; void[][][] S1t4Egho; int[] oxPD3bR; dLJvcU QcZ; while ( !!false.CmPDHZ71BJ()) ; { { boolean jVXfx; } } { ; } if ( !new F9XOW()._C7W()) if ( 8701.SYjGPMjqxCwLZv) new int[ 54196.Wrpmz].L10z; if ( false.mtx5bqmqnw8V) if ( new void[ new nY().MRmH0B].RzaGD7Qnb7r) ; { { gqB0jjPcnmR3 _FbI5_xyHaDC9; } } while ( true.Y55DH7D) while ( iz0SgQiQv().BIEsbX2kTILr()) ; if ( wVUn75YNVQU.SQQ()) if ( -( tss86c2XE20.O1dbPxXU8Qn).zmRndvymadCy) if ( new boolean[ this.kBwMGOLG()].BD_Hm5797LZ()) ; boolean[][][][] zaBn; return; int pEchDcA; ; return; void[][] yK0bJHgj6Tppd; ECyq1 Xeh9bebRB554uA; } this.fvHgmdw_Z7(); void[] mhl6AA7mrglJ; boolean c0sZULhIhg4 = ( -_IWm6f4qTLK7w.HaBGNvP4H5()).IqdMXBH6a(); { int[] o3yQ; while ( null.sSq1bBldnU) return; int LLju43; return; } d orP = !false.HbL = -new cKcv_()[ new BCGLg3().pL6]; boolean rxD2 = new bNe[ null.dHiXqv].TC4a0n; int I; boolean[][][][] H8NNdmq = e3YOIk6a.sL3JFuDeD9Dq = -this[ new sHch38dn[ new int[ EjswzmEmIBM.Kkqp7k()].K76j()].pD]; int OW = rbZQvvbZKYAq().v = null[ HsGUTLY().d8cVDKJW]; if ( -!!false[ !null.fbnxViC()]) while ( new YfwI2ViPDgM().wiLhO8sUz) { boolean[][] nnPUUkmTHzhUj0; }else { while ( CAL6Vt84fcPT5.b03BywpqsI8T()) return; } ; return; return; ; } } class SR1hkigDm_kYos { public static void tl_H1g (String[] wOjBRM) { while ( false[ !!true[ -84721.ecB1a()]]) { void V20jMu0rn; } false.lBMReaZ2(); void[][][][] b; boolean[] Ng8aAa = !!-this.NnTZpUgREMAH; { return; ; return; { while ( 1.oFCT) if ( this.qFYkz) while ( !null.f8fH_vS()) return; } boolean[] B; x7lxJh[] k0IP_; int BGEN2s0ym; { void[][] PHyDS; } int[] lQyhVL; boolean lp; ; return; JCOvDpUmGI[] OrbvY5MD; { void[][] cB8D; } while ( -null.NZ7GBDcZPO()) while ( ( new tlYy7oU2IJOW6z[ new void[ !false.mtHEbuNOmQAobW()][ ( !01264373.rEq).JkajdLO0oviS]][ true.Mg()]).MFT) true.OwHRX(); GIxAXJ4RRui eBx2mVuIVAn; if ( --!!-this.TG0So()) return; int EoovZp9_5c; if ( ---new q4qw()[ false[ ( -true.C9LD0b1Vy())[ new X4ox()._o]]]) ; boolean B; } int TrVxJ = 4705.WLZ6eTDcugyTmH; return false.rK(); while ( false.d3J()) return; void FJZJEEi4qZuMI = null.HaUVPKjrnJMgFV() = -null.t67tKACNZG(); return; while ( null[ ( this.MurfHoyH8c())[ !-null.BIHPzZOg9TOIs()]]) ; null.MfO(); boolean[][][] L_F7Ff = --true.yEp1mH89() = null[ -true.B3fBuICJ_d6()]; int[][] dsGXhiwpVfrqAW = new boolean[ -!---!-tGBfB()[ this.MO()]].KVEI0mxZ7MWYH = null.F; if ( new K8S1Pwkcgw3WJj().K74) ;else ; return; } } chrisGerken/grauthor package com.gerken.xaa.mpe.editor; import com.gerken.xaa.mpe.core.AbstractFormPage; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.IManagedForm; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.ui.forms.widgets.TableWrapData; import org.eclipse.ui.forms.widgets.TableWrapLayout; import org.w3c.dom.Node; public class GroupPage extends AbstractFormPage { GroupTreeSection sectionGroupTreeSection; GroupDetailsSection sectionGroupDetailsSection; GroupTextSection sectionGroupTextSection; public static String PAGE_ID = "GROUP"; public GroupPage(FormEditor editor) { super(editor, PAGE_ID, "Groups"); } protected String getHelpResource() { return "/com.gerken.xaa.mpe/html/guide/mp_editor/Group.htm"; //$NON-NLS-1$ } protected void createFormContent(IManagedForm managedForm) { super.createFormContent(managedForm); ScrolledForm form = managedForm.getForm(); FormToolkit toolkit = managedForm.getToolkit(); form.setText("Group"); fillBody(managedForm, toolkit); // PlatformUI.getWorkbench().getHelpSystem().setHelp(form.getBody(), "com.gerken.xaa.mpe.Xaa.Group_page"); } private void fillBody(IManagedForm managedForm, FormToolkit toolkit) { Composite body = managedForm.getForm().getBody(); TableWrapLayout layout = new TableWrapLayout(); layout.bottomMargin = 10; layout.topMargin = 5; layout.leftMargin = 10; layout.rightMargin = 10; layout.numColumns = 2; layout.horizontalSpacing = 10; body.setLayout(layout); Composite column; // Populate column 1 column = toolkit.createComposite(body); layout = new TableWrapLayout(); layout.verticalSpacing = 20; column.setLayout(layout); column.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB)); sectionGroupTreeSection = new GroupTreeSection(this,column); managedForm.addPart(sectionGroupTreeSection); // Populate column 3 column = toolkit.createComposite(body); layout = new TableWrapLayout(); layout.verticalSpacing = 20; column.setLayout(layout); column.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB)); sectionGroupDetailsSection = new GroupDetailsSection(this,column); managedForm.addPart(sectionGroupDetailsSection); sectionGroupTextSection = new GroupTextSection(this,column); managedForm.addPart(sectionGroupTextSection); } public GroupTreeSection getGroupTreeSection() { return sectionGroupTreeSection; } public GroupDetailsSection getGroupDetailsSection() { return sectionGroupDetailsSection; } public GroupTextSection getGroupTextSection() { return sectionGroupTextSection; } public void markStale() { if (sectionGroupTreeSection != null) { sectionGroupTreeSection.markStale(); } if (sectionGroupDetailsSection != null) { sectionGroupDetailsSection.markStale(); } if (sectionGroupTextSection != null) { sectionGroupTextSection.markStale(); } } public void setSelection(Node node) { sectionGroupTreeSection.setSelection(node); } } 1-10 /** * Copyright (c) Dell Inc., or its subsidiaries. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 */ package io.pravega.segmentstore.storage.rolling; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import io.pravega.common.io.ByteBufferOutputStream; import io.pravega.common.util.ByteArraySegment; import io.pravega.segmentstore.storage.SegmentHandle; import io.pravega.segmentstore.storage.SegmentRollingPolicy; import java.nio.charset.Charset; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Map; import java.util.StringTokenizer; import lombok.val; /** * Serializes and deserializes RollingSegmentHandles. */ final class HandleSerializer { //region Serialization Constants. private static final Charset ENCODING = Charsets.UTF_8; private static final String KEY_POLICY_MAX_SIZE = "maxsize"; private static final String KEY_CONCAT = "concat"; private static final String KEY_VALUE_SEPARATOR = "="; private static final String SEPARATOR = "&"; private static final String CONCAT_SEPARATOR = "@"; //endregion //region Serialization /** * Deserializes the given byte array into a RollingSegmentHandle. * * @param serialization The byte array to deserialize. * @param headerHandle The SegmentHandle for the Header file. * @return A new instance of the RollingSegmentHandle class. */ static RollingSegmentHandle deserialize(byte[] serialization, SegmentHandle headerHandle) { StringTokenizer st = new StringTokenizer(new String(serialization, ENCODING), SEPARATOR, false); Preconditions.checkArgument(st.hasMoreTokens(), "No separators in serialization."); SegmentRollingPolicy policy = null; OffsetAdjuster om = new OffsetAdjuster(); long lastOffset = 0; ArrayList segmentChunks = new ArrayList<>(); while (st.hasMoreTokens()) { val entry = parse(st.nextToken()); if (entry.getKey().equalsIgnoreCase(KEY_POLICY_MAX_SIZE)) { // Rolling policy entry: only check if we don't have it set yet. if (policy == null) { Preconditions.checkArgument(isValidLong(entry.getValue()), "Invalid entry value for '%s'.", entry); policy = new SegmentRollingPolicy(Long.parseLong(entry.getValue())); } } else if (entry.getKey().equalsIgnoreCase(KEY_CONCAT)) { // Concat entry header. This contains information about an upcoming concat. val concatInfo = parseConcat(entry.getValue()); om.set(concatInfo.getKey(), concatInfo.getValue()); } else { // Regular offset->file entry. Preconditions.checkArgument(isValidLong(entry.getKey()), "Invalid key value for '%s'.", entry); long offset = om.adjustOffset(Long.parseLong(entry.getKey())); SegmentChunk s = new SegmentChunk(entry.getValue(), offset); Preconditions.checkArgument(lastOffset <= s.getStartOffset(), "SegmentChunk Entry '%s' has out-of-order offset (previous=%s).", s, lastOffset); segmentChunks.add(s); lastOffset = s.getStartOffset(); } } RollingSegmentHandle h = new RollingSegmentHandle(headerHandle, policy, segmentChunks); h.setHeaderLength(serialization.length); return h; } /** * Serializes an entire RollingSegmentHandle into a new ByteArraySegment. * * @param handle The RollingSegmentHandle to serialize. * @return A ByteArraySegment with the serialization. */ static ByteArraySegment serialize(RollingSegmentHandle handle) { try (ByteBufferOutputStream os = new ByteBufferOutputStream()) { //1. Policy Max Size. os.write(combine(KEY_POLICY_MAX_SIZE, Long.toString(handle.getRollingPolicy().getMaxLength()))); //2. Chunks. handle.chunks().forEach(chunk -> os.write(serializeChunk(chunk))); return os.getData(); } } /** * Serializes a single SegmentChunk. * * @param segmentChunk The SegmentChunk to serialize. * @return A byte array containing the serialization. */ static byte[] serializeChunk(SegmentChunk segmentChunk) { return combine(Long.toString(segmentChunk.getStartOffset()), segmentChunk.getName()); } /** * Serializes an entry that indicates a number of SegmentChunks are concatenated at a specified offset. * * @param chunkCount The number of SegmentChunks to concat. * @param concatOffset The concat offset. * @return A byte array containing the serialization. */ static byte[] serializeConcat(int chunkCount, long concatOffset) { return combine(KEY_CONCAT, chunkCount + CONCAT_SEPARATOR + concatOffset); } private static byte[] combine(String key, String value) { return (key + KEY_VALUE_SEPARATOR + value + SEPARATOR).getBytes(ENCODING); } private static Map.Entry parse(String entry) { int sp = entry.indexOf(KEY_VALUE_SEPARATOR); Preconditions.checkArgument(sp > 0 && sp < entry.length() - 1, "Header entry '%s' is invalid.", entry); String key = entry.substring(0, sp); String value = entry.substring(sp + KEY_VALUE_SEPARATOR.length()); Preconditions.checkArgument(!Strings.isNullOrEmpty(key), "Missing entry key for '%s'.", entry); Preconditions.checkArgument(!Strings.isNullOrEmpty(value), "Missing entry value for '%s'.", entry); return new AbstractMap.SimpleImmutableEntry<>(key, value); } private static Map.Entry parseConcat(String concat) { int pos = concat.indexOf(CONCAT_SEPARATOR); Preconditions.checkArgument(pos > 0 && pos < concat.length() - 1, "%s value '%s' is invalid.", KEY_CONCAT, concat); String count = concat.substring(0, pos); String offset = concat.substring(pos + CONCAT_SEPARATOR.length()); try { val result = new AbstractMap.SimpleImmutableEntry(Long.parseLong(offset), Integer.parseInt(count)); Preconditions.checkArgument(result.getKey() >= 0 && result.getValue() >= 0, "%s value '%s' is invalid.", KEY_CONCAT, concat); return result; } catch (NumberFormatException nfe) { throw new IllegalArgumentException(String.format("%s value '%s' is invalid.", KEY_CONCAT, concat), nfe); } } private static boolean isValidLong(String s) { try { Long.parseLong(s); return true; } catch (NumberFormatException nfe) { return false; } } ///endregion //region OffsetAdjuster /** * Helps adjust offsets when deserializing SegmentChunks from the Header. */ private static class OffsetAdjuster { private long offsetAdjustment; private int remainingCount; private int originalCount; /** * Sets the given offset adjustment. * * @param offsetAdjustment The offset adjustment. * @param count The number of times to apply the offset adjustment (counted by the number of calls to adjustOffset()). */ void set(long offsetAdjustment, int count) { this.offsetAdjustment = offsetAdjustment; this.remainingCount = count; this.originalCount = count; } /** * Adjusts the given offset, if necessary. The offset will be adjusted by the amount specified by the last call * to set() if this method hasn't been called more than the specified number of times. * * @param offset The offset to adjust. * @return The adjusted offset. */ long adjustOffset(long offset) { if (offset != 0 && this.remainingCount == this.originalCount) { // We haven't done any adjustments, yet we encountered an unexpected offset: reset. set(0, 0); } else if (this.remainingCount > 0) { this.remainingCount--; offset += this.offsetAdjustment; } return offset; } } //endregion } /******************************************************************************* * Copyright (C) 2005-2014 Alfresco Software Limited. * * This file is part of Alfresco Mobile for Android. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.alfresco.mobile.android.platform.utils; import static android.provider.Settings.System.AIRPLANE_MODE_ON; import android.content.ContentResolver; import android.content.Context; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.provider.Settings; import android.telephony.TelephonyManager; /** * Utility class to manage connectivity. * * @author */ public final class ConnectivityUtils { private ConnectivityUtils() { } public static boolean isAirplaneModeOn(Context context) { ContentResolver contentResolver = context.getContentResolver(); return Settings.System.getInt(contentResolver, AIRPLANE_MODE_ON, 0) != 0; } public static boolean hasPermission(Context context, String permission) { return context.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED; } public static boolean hasInternetAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { return true; } return false; } public static boolean isWifiAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (wifiInfo != null && wifiInfo.isConnected()) { return true; } return false; } public static boolean isMobileNetworkAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mobileInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (mobileInfo != null && mobileInfo.isConnected()) { return true; } return false; } public static boolean hasNetwork(Context context) { return ConnectivityUtils.hasInternetAvailable(context); } public static boolean hasMobileConnectivity(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mobileInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); return (mobileInfo != null); } public static long getAverageSpeed(Context context) { try { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mobileInfo = cm.getActiveNetworkInfo(); int type = mobileInfo.getType(); int subType = mobileInfo.getSubtype(); if (mobileInfo.getType() == ConnectivityManager.TYPE_WIFI) { return 500 * 1024; } else if (type == ConnectivityManager.TYPE_MOBILE) { switch (subType) { case TelephonyManager.NETWORK_TYPE_1xRTT: return 50 * 1024; // ~ 50-100 kbps case TelephonyManager.NETWORK_TYPE_CDMA: return 14 * 1024; // ~ 14-64 kbps case TelephonyManager.NETWORK_TYPE_EDGE: return 50 * 1024; // ~ 50-100 kbps case TelephonyManager.NETWORK_TYPE_EVDO_0: return 200 * 1024; // ~ 400-1000 kbps case TelephonyManager.NETWORK_TYPE_EVDO_A: return 300 * 1024; // ~ 600-1400 kbps case TelephonyManager.NETWORK_TYPE_GPRS: return 80 * 1024; // ~ 100 kbps case TelephonyManager.NETWORK_TYPE_HSDPA: return 1000 * 1024; // ~ 2-14 Mbps case TelephonyManager.NETWORK_TYPE_HSPA: return 600 * 1024; // ~ 700-1700 kbps case TelephonyManager.NETWORK_TYPE_HSUPA: return 1000 * 1024; // ~ 1-23 Mbps case TelephonyManager.NETWORK_TYPE_UMTS: return 350 * 1024; // ~ 400-7000 kbps case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11 return 800 * 1024; // ~ 1-2 Mbps case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9 return 1000 * 1024; // ~ 5 Mbps case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13 return 1000 * 1024; // ~ 10-20 Mbps case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8 return 25 * 1024; // ~25 kbps case TelephonyManager.NETWORK_TYPE_LTE: // API level 11 return 1000 * 1024; // ~ 10+ Mbps // Unknown case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return 125 * 1024; } } } catch (Exception e) { // DO Nothing } return 125 * 1024; } } /* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.0. You may not use this file * except in compliance with the Zeebe Community License 1.0. */ package io.zeebe.engine.util; import io.zeebe.logstreams.log.LoggedEvent; import io.zeebe.msgpack.UnpackedObject; import io.zeebe.protocol.impl.record.RecordMetadata; import io.zeebe.protocol.impl.record.value.deployment.DeploymentRecord; import io.zeebe.protocol.impl.record.value.error.ErrorRecord; import io.zeebe.protocol.impl.record.value.job.JobRecord; import io.zeebe.protocol.impl.record.value.timer.TimerRecord; import io.zeebe.protocol.impl.record.value.workflowinstance.WorkflowInstanceRecord; import io.zeebe.protocol.record.RecordType; import io.zeebe.protocol.record.ValueType; import io.zeebe.protocol.record.intent.Intent; import io.zeebe.util.ReflectUtil; import io.zeebe.util.buffer.BufferUtil; import org.agrona.DirectBuffer; public final class Records { public static DeploymentRecord asDeploymentRecord(final LoggedEvent event) { return readValueAs(event, DeploymentRecord.class); } public static JobRecord asJobRecord(final LoggedEvent event) { return readValueAs(event, JobRecord.class); } protected static T readValueAs( final LoggedEvent event, final Class valueClass) { final DirectBuffer copy = BufferUtil.cloneBuffer( event.getValueBuffer(), event.getValueOffset(), event.getValueLength()); final T valuePojo = ReflectUtil.newInstance(valueClass); valuePojo.wrap(copy); return valuePojo; } public static boolean isDeploymentRecord(final LoggedEvent event) { return isRecordOfType(event, ValueType.DEPLOYMENT); } public static boolean isJobRecord(final LoggedEvent event) { return isRecordOfType(event, ValueType.JOB); } public static boolean isIncidentRecord(final LoggedEvent event) { return isRecordOfType(event, ValueType.INCIDENT); } public static boolean isWorkflowInstanceRecord(final LoggedEvent event) { return isRecordOfType(event, ValueType.WORKFLOW_INSTANCE); } public static boolean isMessageRecord(final LoggedEvent event) { return isRecordOfType(event, ValueType.MESSAGE); } public static boolean isMessageSubscriptionRecord(final LoggedEvent event) { return isRecordOfType(event, ValueType.MESSAGE_SUBSCRIPTION); } public static boolean isMessageStartEventSubscriptionRecord(final LoggedEvent event) { return isRecordOfType(event, ValueType.MESSAGE_START_EVENT_SUBSCRIPTION); } public static boolean isWorkflowInstanceSubscriptionRecord(final LoggedEvent event) { return isRecordOfType(event, ValueType.WORKFLOW_INSTANCE_SUBSCRIPTION); } public static boolean isTimerRecord(final LoggedEvent event) { return isRecordOfType(event, ValueType.TIMER); } public static boolean isWorkflowInstanceCreationRecord(final LoggedEvent event) { return isRecordOfType(event, ValueType.WORKFLOW_INSTANCE_CREATION); } public static boolean isErrorRecord(final LoggedEvent event) { return isRecordOfType(event, ValueType.ERROR); } public static boolean hasIntent(final LoggedEvent event, final Intent intent) { if (event == null) { return false; } final RecordMetadata metadata = getMetadata(event); return metadata.getIntent() == intent; } private static RecordMetadata getMetadata(final LoggedEvent event) { final RecordMetadata metadata = new RecordMetadata(); event.readMetadata(metadata); return metadata; } public static boolean isRejection(final LoggedEvent event) { final RecordMetadata metadata = getMetadata(event); return metadata.getRecordType() == RecordType.COMMAND_REJECTION; } public static boolean isRejection( final LoggedEvent event, final ValueType valueType, final Intent intent) { return isRejection(event) && isRecordOfType(event, valueType) && hasIntent(event, intent); } public static boolean isEvent(final LoggedEvent event) { final RecordMetadata metadata = getMetadata(event); return metadata.getRecordType() == RecordType.EVENT; } public static boolean isEvent( final LoggedEvent event, final ValueType valueType, final Intent intent) { return isEvent(event) && isRecordOfType(event, valueType) && hasIntent(event, intent); } public static boolean isCommand(final LoggedEvent event) { final RecordMetadata metadata = getMetadata(event); return metadata.getRecordType() == RecordType.COMMAND; } public static boolean isCommand( final LoggedEvent event, final ValueType valueType, final Intent intent) { return isCommand(event) && isRecordOfType(event, valueType) && hasIntent(event, intent); } public static boolean isRecordOfType(final LoggedEvent event, final ValueType type) { if (event == null) { return false; } final RecordMetadata metadata = getMetadata(event); return metadata.getValueType() == type; } public static WorkflowInstanceRecord workflowInstance(final int instanceKey) { final WorkflowInstanceRecord event = new WorkflowInstanceRecord(); event.setWorkflowInstanceKey(instanceKey); return event; } public static ErrorRecord error(final int instanceKey, final long pos) { final ErrorRecord event = new ErrorRecord(); event.initErrorRecord(new Exception("expected"), pos); event.setWorkflowInstanceKey(instanceKey); return event; } public static JobRecord job(final int instanceKey) { final JobRecord event = new JobRecord(); event.setWorkflowInstanceKey(instanceKey); return event; } public static TimerRecord timer(final int instanceKey) { final TimerRecord event = new TimerRecord(); event .setWorkflowInstanceKey(instanceKey) .setElementInstanceKey(instanceKey) .setDueDate(1245) .setTargetElementId(BufferUtil.wrapString("foo")) .setRepetitions(0) .setWorkflowKey(1); return event; } } package com.thiyagu_7.adventofcode.year2020.day19; import org.junit.Test; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static com.thiyagu_7.adventofcode.FileUtils.readFile; import static org.junit.Assert.*; public class SolutionDay19Test { private static final String FILE_PATH_SAMPLE_RULES = "/year2020/day19/sample-input-rules.txt"; private static final String FILE_PATH_SAMPLE_MESSAGES = "/year2020/day19/sample-input-messages.txt"; private static final String FILE_PATH_SAMPLE_RULES2 = "/year2020/day19/sample-input-rules-part2.txt"; private static final String FILE_PATH_SAMPLE_MESSAGES2 = "/year2020/day19/sample-input-messages-part2.txt"; private static final String FILE_PATH_RULES = "/year2020/day19/input-rules.txt"; private static final String FILE_PATH_MESSAGES = "/year2020/day19/input-messages.txt"; private SolutionDay19 solutionDay19 = new SolutionDay19(); @Test public void part1_simple_test() { assertEquals(2, solutionDay19.part1(readRules(readFile(FILE_PATH_SAMPLE_RULES)), readFile(FILE_PATH_SAMPLE_MESSAGES))); } @Test public void test_part1() { assertEquals(241, solutionDay19.part1(readRules(readFile(FILE_PATH_RULES)), readFile(FILE_PATH_MESSAGES))); } @Test public void part2_simple_test() { //old // assertEquals(3, solutionDay19.part1(readRules(readFile(FILE_PATH_SAMPLE_RULES2)), readFile(FILE_PATH_SAMPLE_MESSAGES2))); //after updating rules assertEquals(12, solutionDay19.part2(readRules(readFile(FILE_PATH_SAMPLE_RULES2)), readFile(FILE_PATH_SAMPLE_MESSAGES2))); } @Test public void test_part2() { assertEquals(424, solutionDay19.part2(readRules(readFile(FILE_PATH_RULES)), readFile(FILE_PATH_MESSAGES))); } private Map readRules(List lines) { return lines.stream() .map(line -> line.split(":")) .collect(Collectors.toMap(p -> p[0], p -> p[1].trim())); } }0 /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache POI" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact . * * 5. Products derived from this software may not be called "Apache", * "Apache POI", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . */ package org.apache.poi.poifs.storage; import java.io.*; import java.util.*; import org.apache.poi.poifs.common.POIFSConstants; /** * Storage for documents that are too small to use regular * DocumentBlocks for their data * * @author (mjohnson at apache dot org) */ public class SmallDocumentBlock implements BlockWritable, ListManagedBlock { private byte[] _data; private static final byte _default_fill = ( byte ) 0xff; private static final int _block_size = 64; private static final int _blocks_per_big_block = POIFSConstants.BIG_BLOCK_SIZE / _block_size; private SmallDocumentBlock(final byte [] data, final int index) { this(); System.arraycopy(data, index * _block_size, _data, 0, _block_size); } private SmallDocumentBlock() { _data = new byte[ _block_size ]; } /** * convert a single long array into an array of SmallDocumentBlock * instances * * @param array the byte array to be converted * @param size the intended size of the array (which may be smaller) * * @return an array of SmallDocumentBlock instances, filled from * the array */ public static SmallDocumentBlock [] convert(final byte [] array, final int size) { SmallDocumentBlock[] rval = new SmallDocumentBlock[ (size + _block_size - 1) / _block_size ]; int offset = 0; for (int k = 0; k < rval.length; k++) { rval[ k ] = new SmallDocumentBlock(); if (offset < array.length) { int length = Math.min(_block_size, array.length - offset); System.arraycopy(array, offset, rval[ k ]._data, 0, length); if (length != _block_size) { Arrays.fill(rval[ k ]._data, length, _block_size, _default_fill); } } else { Arrays.fill(rval[ k ]._data, _default_fill); } offset += _block_size; } return rval; } /** * fill out a List of SmallDocumentBlocks so that it fully occupies * a set of big blocks * * @param blocks the List to be filled out * * @return number of big blocks the list encompasses */ public static int fill(final List blocks) { int count = blocks.size(); int big_block_count = (count + _blocks_per_big_block - 1) / _blocks_per_big_block; int full_count = big_block_count * _blocks_per_big_block; for (; count < full_count; count++) { blocks.add(makeEmptySmallDocumentBlock()); } return big_block_count; } /** * Factory for creating SmallDocumentBlocks from DocumentBlocks * * @param store the original DocumentBlocks * @param size the total document size * * @return an array of new SmallDocumentBlocks instances * * @exception IOException on errors reading from the DocumentBlocks * @exception ArrayIndexOutOfBoundsException if, somehow, the store * contains less data than size indicates */ public static SmallDocumentBlock [] convert(final BlockWritable [] store, final int size) throws IOException, ArrayIndexOutOfBoundsException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); for (int j = 0; j < store.length; j++) { store[ j ].writeBlocks(stream); } byte[] data = stream.toByteArray(); SmallDocumentBlock[] rval = new SmallDocumentBlock[ convertToBlockCount(size) ]; for (int index = 0; index < rval.length; index++) { rval[ index ] = new SmallDocumentBlock(data, index); } return rval; } /** * create a list of SmallDocumentBlock's from raw data * * @param blocks the raw data containing the SmallDocumentBlock * data * * @return a List of SmallDocumentBlock's extracted from the input * * @exception IOException */ public static List extract(ListManagedBlock [] blocks) throws IOException { List sdbs = new ArrayList(); for (int j = 0; j < blocks.length; j++) { byte[] data = blocks[ j ].getData(); for (int k = 0; k < _blocks_per_big_block; k++) { sdbs.add(new SmallDocumentBlock(data, k)); } } return sdbs; } /** * read data from an array of SmallDocumentBlocks * * @param blocks the blocks to read from * @param buffer the buffer to write the data into * @param offset the offset into the array of blocks to read from */ public static void read(final BlockWritable [] blocks, final byte [] buffer, final int offset) { int firstBlockIndex = offset / _block_size; int firstBlockOffset = offset % _block_size; int lastBlockIndex = (offset + buffer.length - 1) / _block_size; if (firstBlockIndex == lastBlockIndex) { System.arraycopy( (( SmallDocumentBlock ) blocks[ firstBlockIndex ])._data, firstBlockOffset, buffer, 0, buffer.length); } else { int buffer_offset = 0; System.arraycopy( (( SmallDocumentBlock ) blocks[ firstBlockIndex ])._data, firstBlockOffset, buffer, buffer_offset, _block_size - firstBlockOffset); buffer_offset += _block_size - firstBlockOffset; for (int j = firstBlockIndex + 1; j < lastBlockIndex; j++) { System.arraycopy((( SmallDocumentBlock ) blocks[ j ])._data, 0, buffer, buffer_offset, _block_size); buffer_offset += _block_size; } System.arraycopy( (( SmallDocumentBlock ) blocks[ lastBlockIndex ])._data, 0, buffer, buffer_offset, buffer.length - buffer_offset); } } /** * Calculate the storage size of a set of SmallDocumentBlocks * * @param size number of SmallDocumentBlocks * * @return total size */ public static int calcSize(int size) { return size * _block_size; } private static SmallDocumentBlock makeEmptySmallDocumentBlock() { SmallDocumentBlock block = new SmallDocumentBlock(); Arrays.fill(block._data, _default_fill); return block; } private static int convertToBlockCount(final int size) { return (size + _block_size - 1) / _block_size; } /* ********** START implementation of BlockWritable ********** */ /** * Write the storage to an OutputStream * * @param stream the OutputStream to which the stored data should * be written * * @exception IOException on problems writing to the specified * stream */ public void writeBlocks(final OutputStream stream) throws IOException { stream.write(_data); } /* ********** END implementation of BlockWritable ********** */ /* ********** START implementation of ListManagedBlock ********** */ /** * Get the data from the block * * @return the block's data as a byte array * * @exception IOException if there is no data */ public byte [] getData() throws IOException { return _data; } /* ********** END implementation of ListManagedBlock ********** */ } // end public class SmallDocumentBlock package com.library.base.net; import android.os.Handler; import com.google.gson.Gson; /** * HTTP响应回调 * * @Author: jerome * @Date: 2017-09-20 */ class HttpResponseCallBack extends BaseHttpResponse { private static final Gson GSON = new Gson(); private final Class mClass; public HttpResponseCallBack(Class cls, HttpCallback callback, Handler handler) { super(callback, handler); mClass = cls; } @Override protected void onParseDataJson(String msg, String dataJson) { if (Void.class == mClass) { notifySuccess(null); return; } if (String.class == mClass) { notifySuccess((T) dataJson); return; } T data = GSON.fromJson(dataJson, mClass); if (data == null) { notifyFailure(ApiErrorCode.ERROR_EMPTY_DATA, msg); } else { notifySuccess(data); } } } anterostecnologia/anterosdbcpsrc/main/java/br/com/anteros/dbcp/AnterosDBCPPoolMXBean.java /* * Copyright (C) 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package br.com.anteros.dbcp; import javax.sql.DataSource; /** * The javax.management MBean for a AnterosDBCP pool instance. * * @author */ public interface AnterosDBCPPoolMXBean { /** * Get the number of currently idle connections in the pool. *

* The return value is extremely transient and is a point-in-time measurement. Therefore, due to a time * difference between invoking this method and {@link #getActiveConnections()}, it is possible for the sum * of idle plus active connections to be either less than or greater than the value returned by * {@link #getTotalConnections()}. * * @return the current number of idle connections in the pool */ int getIdleConnections(); /** * Get the number of currently active connections in the pool. *

* The return value is extremely transient and is a point-in-time measurement. Therefore, due to a time * difference between invoking this method and {@link #getIdleConnections()}, it is possible for the sum * of idle plus active connections to be either less than or greater than the value returned by * {@link #getTotalConnections()}. * * @return the current number of active (in-use) connections in the pool */ int getActiveConnections(); /** * Get the total number of connections currently in the pool. The return value is transient and is a * point-in-time measurement. * * @return the total number of connections in the pool */ int getTotalConnections(); /** * Get the number of threads awaiting connections from the pool. The return value is extremely transient and is * a point-in-time measurement. * * @return the number of threads awaiting a connection from the pool */ int getThreadsAwaitingConnection(); /** * Evict currently idle connections from the pool, and mark active (in-use) connections for eviction when they are * returned to the pool. */ void softEvictConnections(); /** * Suspend the pool. When the pool is suspended, threads calling {@link DataSource#getConnection()} will be * blocked with no timeout until the pool is resumed via the {@link #resumePool()} method. *
* This method has no effect unless the {@link AnterosDBCPConfig#setAllowPoolSuspension(boolean)} method or equivalent * property has been set to {@code true}. */ void suspendPool(); /** * Resume the pool. Enables connection borrowing to resume on a pool that has been suspended via the * {@link #suspendPool()} method. *
* This method has no effect unless the {@link AnterosDBCPConfig#setAllowPoolSuspension(boolean)} method or equivalent * property has been set to {@code true}. */ void resumePool(); } Kunduin/aspectj-design-pattern package nju.kunduin.visitoraspect; /** @author kunduin */ public class ConcreteVisitor {} /* Array-based Data Structure where N items are created in an array, and every Mth element is removed until only one element remains. It does this by keeping an element count over how many elements we have looped over. It will delete the element in the array if the elementCount is a multiple of M. When array length is less than M, it will sequentially loop over each item in the array as normal without deleting, until element count reaches a multiple of , when it will then delete the element. Therefore, the loop always results in one integer left over at the end. */ package com.company; import java.util.Iterator; import java.util.NoSuchElementException; public class Josephus implements Iterable { private int[] arr; private int count; private int element; @SuppressWarnings("unchecked") public Josephus(int N, int M ){ count = N; element = M; arr = new int[count]; } public boolean isEmpty(){ return count == 0; } @SuppressWarnings("unchecked") public void eliminate(){ if (isEmpty()) throw new NoSuchElementException("Underflow"); //create our initial array. for(int i = 0; i < count; i++){ arr[i] = i+1; } //tracker for how many elements we have looped over. int elementCount = 1; while(count != 1){ for(int j = 0; j < arr.length; j++){ //if elementCount is a multiple of M, delete the element in the array //we are currently looping over. if((elementCount) % element ==0){ arr[j] = 0; count--; } elementCount++; } //updates the array, removing eliminates integers so it is ready //for the next loop over. int insertPos = 0; int[] temp = new int[count]; for(int k = 0; k < arr.length; k++){ if(arr[k] != 0){ temp[insertPos++] = arr[k]; } } arr = temp; } } @Override public String toString(){ StringBuilder s = new StringBuilder(); for(int item: arr){ if (item != 0){ s.append(item); s.append(" "); } } return s.toString(); } @Override public Iterator iterator() { return new ArrayIterator(); } private class ArrayIterator implements Iterator{ private int i = 0; public boolean hasNext(){ return i < count;} public void remove(){throw new UnsupportedOperationException();} public Object next(){ if (!hasNext()) throw new NoSuchElementException(); return arr[i++]; } } }1-10 /** * Copyright (C) 2020 Sheedon. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sheedon.mqtt.retrofit; import androidx.annotation.Nullable; import com.google.gson.Gson; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.sheedon.mqtt.Request; import org.sheedon.mqtt.RequestBody; import org.sheedon.mqtt.ResponseBody; import org.sheedon.mqtt.retrofit.mqtt.BACKNAME; import org.sheedon.mqtt.retrofit.mqtt.Body; import org.sheedon.mqtt.retrofit.mqtt.DELAYMILLISECOND; import org.sheedon.mqtt.retrofit.mqtt.Field; import org.sheedon.mqtt.retrofit.mqtt.FormEncoded; import org.sheedon.mqtt.retrofit.mqtt.PAYLOAD; import org.sheedon.mqtt.retrofit.mqtt.Path; import org.sheedon.mqtt.retrofit.mqtt.QOS; import org.sheedon.mqtt.retrofit.mqtt.RETAINED; import org.sheedon.mqtt.retrofit.mqtt.TOPIC; import org.sheedon.mqtt.retrofit.mqtt.Theme; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * 服务方法 * * @Author: sheedon * @Email: .com * @Date: 2020/2/22 12:51 */ final class ServiceMethod { final org.sheedon.mqtt.MQTTFactory mqttFactory; final CallAdapter callAdapter; private final Converter responseConverter; private final ParameterHandler[] parameterHandlers; private final MqttMessage mqttMessage; private final BindCallback bindCallback; private final String topic; private final boolean isFormEncoded; private final Gson gson; ServiceMethod(Builder builder) { this.mqttFactory = builder.retrofit.mqttFactory(); this.gson = builder.retrofit.getGson(); this.callAdapter = builder.callAdapter; this.responseConverter = builder.responseConverter; this.parameterHandlers = builder.parameterHandlers; this.mqttMessage = builder.mqttMessage; this.bindCallback = builder.bindCallback; this.topic = builder.topic; this.isFormEncoded = builder.isFormEncoded; } Request toRequest(@Nullable Object... args) throws IOException { RequestBuilder requestBuilder = new RequestBuilder(topic, mqttMessage, bindCallback, isFormEncoded, gson); @SuppressWarnings("unchecked") // It is an error to invoke a method with the wrong arg types. ParameterHandler[] handlers = (ParameterHandler[]) parameterHandlers; int argumentCount = args != null ? args.length : 0; if (argumentCount != handlers.length) { throw new IllegalArgumentException("Argument count (" + argumentCount + ") doesn't match expected count (" + handlers.length + ")"); } for (int p = 0; p < argumentCount; p++) { handlers[p].apply(requestBuilder, args[p]); } return requestBuilder.build(); } T adapt(Call call) { return callAdapter.adapt(call); } T adapt(Observable call) { return callAdapter.adapt(call); } /** * Builds a method return value from an HTTP response body. */ R toResponse(ResponseBody body) throws IOException { return responseConverter.convert(body); } static final class Builder { final Retrofit retrofit; final Method method; final Annotation[] methodAnnotations; final Annotation[][] parameterAnnotationsArray; final Type[] parameterTypes; String topic; boolean isReplace; final String baseTopic; final MqttMessage mqttMessage; final BindCallback bindCallback; Type responseType; boolean gotPayload; boolean gotTheme; boolean gotPath; boolean gotQuery; boolean gotBody; boolean isFormEncoded; ParameterHandler[] parameterHandlers; Converter responseConverter; CallAdapter callAdapter; /** * 构造器,生成初始数据 * * @param retrofit 传入的Retrofit * @param method 方法 */ public Builder(Retrofit retrofit, Method method) { this.retrofit = retrofit; this.method = method; this.baseTopic = retrofit.baseTopic(); this.methodAnnotations = method.getAnnotations(); this.parameterTypes = method.getGenericParameterTypes(); this.parameterAnnotationsArray = method.getParameterAnnotations(); this.mqttMessage = new MqttMessage(); this.bindCallback = new BindCallback(); } public ServiceMethod build() { callAdapter = createCallAdapter(); responseType = callAdapter.responseType(); if (responseType == Response.class) { throw methodError("'" + Utils.getRawType(responseType).getName() + "' is not a valid response body type. Did you mean ResponseBody?"); } responseConverter = createResponseConverter(); for (Annotation annotation : methodAnnotations) { parseMethodAnnotation(annotation); } int parameterCount = parameterAnnotationsArray.length; parameterHandlers = new ParameterHandler[parameterCount]; for (int p = 0; p < parameterCount; p++) { Type parameterType = parameterTypes[p]; if (Utils.hasUnresolvableType(parameterType)) { throw parameterError(p, "Parameter type must not include a type variable or wildcard: %s", parameterType); } Annotation[] parameterAnnotations = parameterAnnotationsArray[p]; if (parameterAnnotations == null) { throw parameterError(p, "No Retrofit annotation found."); } parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations); } if ((topic == null || topic.equals("")) && (baseTopic == null || baseTopic.isEmpty())) { throw methodError("Missing topic."); } else if (topic == null || topic.equals("")) { topic = baseTopic; } else if(!isReplace){ topic = baseTopic + topic; } return new ServiceMethod<>(this); } private CallAdapter createCallAdapter() { Type returnType = method.getGenericReturnType(); if (Utils.hasUnresolvableType(returnType)) { throw methodError( "Method return type must not include a type variable or wildcard: %s", returnType); } if (returnType == void.class) { throw methodError("Service methods cannot return void."); } Annotation[] annotations = method.getAnnotations(); try { //noinspection unchecked return (CallAdapter) retrofit.callAdapter(returnType, annotations); } catch (RuntimeException e) { // Wide exception range because factories are user code. throw methodError(e, "Unable to create call adapter for %s", returnType); } } private Converter createResponseConverter() { Annotation[] annotations = method.getAnnotations(); try { return retrofit.responseBodyConverter(responseType, annotations); } catch (RuntimeException e) { // Wide exception range because factories are user code. throw methodError(e, "Unable to create converter for %s", responseType); } } //解析方法注解 private void parseMethodAnnotation(Annotation annotation) { if (annotation instanceof TOPIC) { topic = ((TOPIC) annotation).value(); isReplace = ((TOPIC) annotation).isReplace(); } else if (annotation instanceof PAYLOAD) { gotPayload = true; mqttMessage.setPayload(((PAYLOAD) annotation).value().getBytes()); } else if (annotation instanceof QOS) { mqttMessage.setQos(((QOS) annotation).value()); } else if (annotation instanceof RETAINED) { mqttMessage.setRetained(((RETAINED) annotation).value()); } else if (annotation instanceof DELAYMILLISECOND) { bindCallback.setDelayMilliSecond(((DELAYMILLISECOND) annotation).value()); } else if (annotation instanceof BACKNAME) { bindCallback.setBackName(((BACKNAME) annotation).value()); } else if (annotation instanceof FormEncoded) { isFormEncoded = true; } } private ParameterHandler parseParameter( int p, Type parameterType, Annotation[] annotations) { ParameterHandler result = null; for (Annotation annotation : annotations) { ParameterHandler annotationAction = parseParameterAnnotation( p, parameterType, annotations, annotation); if (annotationAction == null) { continue; } if (result != null) { throw parameterError(p, "Multiple Retrofit annotations found, only one allowed."); } result = annotationAction; } if (result == null) { throw parameterError(p, "No Retrofit annotation found."); } return result; } private ParameterHandler parseParameterAnnotation( int p, Type type, Annotation[] annotations, Annotation annotation) { if (annotation instanceof Theme) { if (gotTheme) { throw parameterError(p, "Multiple @Theme method annotations found."); } gotTheme = true; if (type == String.class) { return new ParameterHandler.RelativeTopic(); } else { throw parameterError(p, "@Theme must be String type."); } } else if (annotation instanceof Path) { if (gotQuery) { throw parameterError(p, "A @Path parameter must not come after a @Field."); } if (gotTheme) { throw parameterError(p, "@Path parameters may not be used with @Theme."); } gotPath = true; Path path = (Path) annotation; String name = path.value(); // validatePathName(p, name); Converter converter = retrofit.stringConverter(type, annotations); return new ParameterHandler.Path<>(name, converter, path.encoded()); } else if (annotation instanceof Field) { if (gotPayload) { throw parameterError(p, "@Field parameters cannot be used with @PAYLOAD."); } if (gotBody) { throw parameterError(p, "@Field parameters may not be used with @Body."); } if (!isFormEncoded) { throw parameterError(p, "@Field parameters may be used with @FormEncoded."); } Field field = (Field) annotation; String name = field.value(); boolean encoded = field.encoded(); Class rawParameterType = Utils.getRawType(type); gotQuery = true; if (Iterable.class.isAssignableFrom(rawParameterType)) { if (!(type instanceof ParameterizedType)) { throw parameterError(p, rawParameterType.getSimpleName() + " must include generic type (e.g., " + rawParameterType.getSimpleName() + ")"); } ParameterizedType parameterizedType = (ParameterizedType) type; Type iterableType = Utils.getParameterUpperBound(0, parameterizedType); Converter converter = retrofit.stringConverter(iterableType, annotations); return new ParameterHandler.Field<>(name, converter, encoded).iterable(); } else if (rawParameterType.isArray()) { Class arrayComponentType = boxIfPrimitive(rawParameterType.getComponentType()); Converter converter = retrofit.stringConverter(arrayComponentType, annotations); return new ParameterHandler.Field<>(name, converter, encoded).array(); } else { Converter converter = retrofit.stringConverter(type, annotations); return new ParameterHandler.Field<>(name, converter, encoded); } } else if (annotation instanceof Body) { if (gotPayload) { throw parameterError(p, "@Body parameters cannot be used with @PAYLOAD."); } if (gotBody) { throw parameterError(p, "@Body method annotations found."); } if (isFormEncoded) { throw parameterError(p, "@Body parameters cannot be used with @FormEncoded."); } Converter converter; try { converter = retrofit.requestBodyConverter(type, annotations, methodAnnotations); } catch (RuntimeException e) { // Wide exception range because factories are user code. throw parameterError(e, p, "Unable to create @Body converter for %s", type); } gotBody = true; return new ParameterHandler.Body<>(converter); } return null; // Not a Retrofit annotation. } private RuntimeException methodError(String message, Object... args) { return methodError(null, message, args); } private RuntimeException methodError(Throwable cause, String message, Object... args) { message = String.format(message, args); return new IllegalArgumentException(message + "\n for method " + method.getDeclaringClass().getSimpleName() + "." + method.getName(), cause); } private RuntimeException parameterError( Throwable cause, int p, String message, Object... args) { return methodError(cause, message + " (parameter #" + (p + 1) + ")", args); } private RuntimeException parameterError(int p, String message, Object... args) { return methodError(message + " (parameter #" + (p + 1) + ")", args); } } static Class boxIfPrimitive(Class type) { if (boolean.class == type) return Boolean.class; if (byte.class == type) return Byte.class; if (char.class == type) return Character.class; if (double.class == type) return Double.class; if (float.class == type) return Float.class; if (int.class == type) return Integer.class; if (long.class == type) return Long.class; if (short.class == type) return Short.class; return type; } } 1-10 package org.anddev.andengine.entity.particle.emitter; public class PointParticleEmitter extends BaseParticleEmitter { public PointParticleEmitter(float paramFloat1, float paramFloat2) { super(paramFloat1, paramFloat2); } public void getPositionOffset(float[] paramArrayOfFloat) { paramArrayOfFloat[0] = this.mCenterX; paramArrayOfFloat[1] = this.mCenterY; } } /* Location: C:\Users\Rodelle\Desktop\Attacknid\Tools\Attacknids-dex2jar.jar * Qualified Name: org.anddev.andengine.entity.particle.emitter.PointParticleEmitter * JD-Core Version: 0.7.0.1 *//* * Copyright (c) 2017 BlueCats. All rights reserved. * http://www.bluecats.com */ package com.bluecats.cattracker.helpers; import android.content.*; import android.database.sqlite.*; import android.util.*; import com.bluecats.cattracker.*; public class DatabaseHelper extends android.database.sqlite.SQLiteOpenHelper { private static final String TAG = "DatabaseHelper"; public static final String TABLE_BEACON_PAYLOAD = "BeaconPayload"; private static DatabaseHelper mSQLiteOpenHelper; private static boolean mPendingClearHelper = false; public static synchronized DatabaseHelper getInstance(Context context) { if (mPendingClearHelper) { mPendingClearHelper = false; if (mSQLiteOpenHelper != null) { try { mSQLiteOpenHelper.close(); } catch (Exception e) { Log.e(TAG, e.toString()); } mSQLiteOpenHelper = null; } } if (mSQLiteOpenHelper == null) { mSQLiteOpenHelper = new DatabaseHelper(context); } return mSQLiteOpenHelper; } public static synchronized void clear() { mPendingClearHelper = true; } private DatabaseHelper(Context context) { super(context, String.format("%s.SQLite.db", context.getPackageName()), null, CatTracker.SQLITE_DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { createDatabase(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { upgradeDatabase(db); } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { upgradeDatabase(db); } private void createDatabase(SQLiteDatabase db) { Log.d(TAG, "createDatabase"); db.beginTransaction(); try { createBeaconPayloadTable(db); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } private void upgradeDatabase(SQLiteDatabase db) { Log.d(TAG, "upgradeDatabase"); db.beginTransaction(); try { db.execSQL("DROP TABLE IF EXISTS " + TABLE_BEACON_PAYLOAD + ";"); db.setTransactionSuccessful(); } finally { db.endTransaction(); } createDatabase(db); } private void createBeaconPayloadTable(SQLiteDatabase db) { String beaconTable = "CREATE TABLE " + TABLE_BEACON_PAYLOAD + " ( " + "beaconPayloadID TEXT, " + "beaconIdentifier TEXT, " + "timestamp INTEGER, " + "beaconPayload TEXT" + ");"; db.execSQL(beaconTable); } } /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.net; import java.io.IOError; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.ServerSocketChannel; import java.security.MessageDigest; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.base.Function; import org.apache.log4j.Logger; import org.apache.cassandra.concurrent.JMXEnabledThreadPoolExecutor; import org.apache.cassandra.concurrent.StageManager; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.HintedHandOffManager; import org.apache.cassandra.io.util.DataOutputBuffer; import org.apache.cassandra.locator.ILatencySubscriber; import org.apache.cassandra.net.io.SerializerType; import org.apache.cassandra.net.sink.SinkManager; import org.apache.cassandra.service.ConsistencyChecker; import org.apache.cassandra.service.GCInspector; import org.apache.cassandra.service.QuorumResponseHandler; import org.apache.cassandra.service.StorageService; import org.apache.cassandra.utils.ExpiringMap; import org.apache.cassandra.utils.Pair; import org.apache.cassandra.utils.SimpleCondition; import org.cliffc.high_scale_lib.NonBlockingHashMap; public class MessagingService { private static int version_ = 1; //TODO: make this parameter dynamic somehow. Not sure if config is appropriate. private static SerializerType serializerType_ = SerializerType.BINARY; /** we preface every message with this number so the recipient can validate the sender is sane */ public static final int PROTOCOL_MAGIC = 0xCA552DFA; /* This records all the results mapped by message Id */ private static ExpiringMap callbacks; /* Lookup table for registering message handlers based on the verb. */ private static Map verbHandlers_; /* Thread pool to handle messages without a specialized stage */ private static ExecutorService defaultExecutor_; /* Thread pool to handle messaging write activities */ private static ExecutorService streamExecutor_; private static NonBlockingHashMap connectionManagers_ = new NonBlockingHashMap(); private static Logger logger_ = Logger.getLogger(MessagingService.class); private static int LOG_DROPPED_INTERVAL_IN_MS = 5000; public static final MessagingService instance = new MessagingService(); private SocketThread socketThread; private SimpleCondition listenGate; private static final Map droppedMessages = new EnumMap(StorageService.Verb.class); private final List subscribers = new ArrayList(); static { for (StorageService.Verb verb : StorageService.Verb.values()) droppedMessages.put(verb, new AtomicInteger()); } public Object clone() throws CloneNotSupportedException { //Prevents the singleton from being cloned throw new CloneNotSupportedException(); } protected MessagingService() { listenGate = new SimpleCondition(); verbHandlers_ = new HashMap(); Function, ?> timeoutReporter = new Function, Object>() { public Object apply(Pair pair) { CallbackInfo expiredCallbackInfo = pair.right; maybeAddLatency(expiredCallbackInfo.callback, expiredCallbackInfo.target, (double) DatabaseDescriptor.getRpcTimeout()); // hintlog v2 if (expiredCallbackInfo.shouldHint()) { // Trigger hints for expired mutation message. assert expiredCallbackInfo.message != null; scheduleMutationHint(expiredCallbackInfo.message, expiredCallbackInfo.target); } return null; } }; callbacks = new ExpiringMap((long) (1.1 * DatabaseDescriptor.getRpcTimeout()), timeoutReporter); defaultExecutor_ = new JMXEnabledThreadPoolExecutor("MISCELLANEOUS-POOL"); streamExecutor_ = new JMXEnabledThreadPoolExecutor("MESSAGE-STREAMING-POOL"); TimerTask logDropped = new TimerTask() { public void run() { logDroppedMessages(); } }; Timer timer = new Timer("DroppedMessagesLogger"); timer.schedule(logDropped, LOG_DROPPED_INTERVAL_IN_MS, LOG_DROPPED_INTERVAL_IN_MS); } private Future scheduleMutationHint(Message mutationMessage, InetAddress mutationTarget) { try { HintedHandOffManager.instance().storeHint(mutationTarget, null, mutationMessage.getMessageBody()); } catch (IOException e) { logger_.error("Unable to deserialize mutation when writting hint for: " + mutationTarget); } return null; } /** * Track latency information for the dynamic snitch * @param cb: the callback associated with this message -- this lets us know if it's a message type we're interested in * @param address: the host that replied to the message * @param latency */ public void maybeAddLatency(IMessageCallback cb, InetAddress address, double latency) { if (cb instanceof QuorumResponseHandler || cb instanceof AsyncResult || cb instanceof ConsistencyChecker.DigestResponseHandler) addLatency(address, latency); } public void addLatency(InetAddress address, double latency) { for (ILatencySubscriber subscriber : subscribers) subscriber.receiveTiming(address, latency); } public byte[] hash(String type, byte data[]) { byte result[]; try { MessageDigest messageDigest = MessageDigest.getInstance(type); result = messageDigest.digest(data); } catch (Exception e) { throw new RuntimeException(e); } return result; } /** called by failure detection code to notify that housekeeping should be performed on downed sockets. */ public void convict(InetAddress ep) { logger_.debug("Resetting pool for " + ep); getConnectionPool(ep).reset(); } /** * Listen on the specified port. * @param localEp InetAddress whose port to listen on. */ public void listen(InetAddress localEp) throws IOException { ServerSocketChannel serverChannel = ServerSocketChannel.open(); final ServerSocket ss = serverChannel.socket(); ss.setReuseAddress(true); ss.bind(new InetSocketAddress(localEp, DatabaseDescriptor.getStoragePort())); socketThread = new SocketThread(ss, "ACCEPT-" + localEp); socketThread.start(); listenGate.signalAll(); } public void waitUntilListening() { try { listenGate.await(); } catch (InterruptedException ie) { logger_.debug("await interrupted"); } } public static OutboundTcpConnectionPool getConnectionPool(InetAddress to) { OutboundTcpConnectionPool cp = connectionManagers_.get(to); if (cp == null) { connectionManagers_.putIfAbsent(to, new OutboundTcpConnectionPool(to)); cp = connectionManagers_.get(to); } return cp; } public static OutboundTcpConnection getConnection(InetAddress to, Message msg) { return getConnectionPool(to).getConnection(msg); } /** * Register a verb and the corresponding verb handler with the * Messaging Service. * @param verb * @param verbHandler handler for the specified verb */ public void registerVerbHandlers(StorageService.Verb verb, IVerbHandler verbHandler) { assert !verbHandlers_.containsKey(verb); verbHandlers_.put(verb, verbHandler); } /** * This method returns the verb handler associated with the registered * verb. If no handler has been registered then null is returned. * @param type for which the verb handler is sought * @return a reference to IVerbHandler which is the handler for the specified verb */ public IVerbHandler getVerbHandler(StorageService.Verb type) { return verbHandlers_.get(type); } private void addCallback(IMessageCallback cb, Message message, InetAddress to, boolean hintEnabled) { CallbackInfo previous; // If HH is enabled and this is a mutation message => store the message to track for potential hints. if (hintEnabled && message.getVerb() == StorageService.Verb.MUTATION) previous = callbacks.put(message.getMessageId(), new CallbackInfo(to, cb, message)); else previous = callbacks.put(message.getMessageId(), new CallbackInfo(to, cb)); assert previous == null; } /** * Send a message to a given endpoint. This method specifies a callback * which is invoked with the actual response. * @param message message to be sent. * @param to endpoint to which the message needs to be sent * @param cb callback interface which is used to pass the responses or * suggest that a timeout occurred to the invoker of the send(). * suggest that a timeout occurred to the invoker of the send(). * @return an reference to message id used to match with the result */ public String sendRR(Message message, InetAddress to, IAsyncCallback cb) { return sendRR(message,to,cb,DatabaseDescriptor.hintedHandoffEnabled()); } public String sendRR(Message message, InetAddress to, IAsyncCallback cb, boolean hintEnabled) { String messageId = message.getMessageId(); addCallback(cb, message, to,hintEnabled); sendOneWay(message, to); return messageId; } /** * Send a message to a given endpoint. This method adheres to the fire and forget * style messaging. * @param message messages to be sent. * @param to endpoint to which the message needs to be sent */ public void sendOneWay(Message message, InetAddress to) { // do local deliveries if ( message.getFrom().equals(to) ) { MessagingService.receive(message); return; } // message sinks are a testing hook Message processedMessage = SinkManager.processClientMessageSink(message); if (processedMessage == null) { return; } // get pooled connection (really, connection queue) OutboundTcpConnection connection = getConnection(to, message); // pack message with header in a bytebuffer byte[] data; try { DataOutputBuffer buffer = new DataOutputBuffer(); Message.serializer().serialize(message, buffer); data = buffer.getData(); } catch (IOException e) { throw new RuntimeException(e); } assert data.length > 0; ByteBuffer buffer = packIt(data , false); // write it connection.write(buffer); } public IAsyncResult sendRR(Message message, InetAddress to) { return sendRR(message,to,DatabaseDescriptor.hintedHandoffEnabled()); } public IAsyncResult sendRR(Message message, InetAddress to, boolean hintEnabled) { IAsyncResult iar = new AsyncResult(); addCallback(iar, message, to, hintEnabled); sendOneWay(message, to); return iar; } /** * Stream a file from source to destination. This is highly optimized * to not hold any of the contents of the file in memory. * @param file name of file to stream. * @param startPosition position inside the file * @param endPosition * @param to endpoint to which we need to stream the file. */ public void stream(String file, long startPosition, long endPosition, InetAddress from, InetAddress to) { /* Streaming asynchronously on streamExector_ threads. */ Runnable streamingTask = new FileStreamTask(file, startPosition, endPosition, from, to); streamExecutor_.execute(streamingTask); } public void register(ILatencySubscriber subcriber) { subscribers.add(subcriber); } /** blocks until the processing pools are empty and done. */ public static void waitFor() throws InterruptedException { while (!defaultExecutor_.isTerminated()) defaultExecutor_.awaitTermination(5, TimeUnit.SECONDS); while (!streamExecutor_.isTerminated()) streamExecutor_.awaitTermination(5, TimeUnit.SECONDS); } public static void shutdown() { logger_.info("Shutting down MessageService..."); try { instance.socketThread.close(); } catch (IOException e) { throw new IOError(e); } defaultExecutor_.shutdownNow(); streamExecutor_.shutdownNow(); callbacks.shutdown(); logger_.info("Shutdown complete (no further commands will be processed)"); } public static void receive(Message message) { message = SinkManager.processServerMessageSink(message); Runnable runnable = new MessageDeliveryTask(message); ExecutorService stage = StageManager.getStage(message.getMessageType()); if (stage == null) { if (logger_.isDebugEnabled()) logger_.debug("Running " + message.getMessageType() + " on default stage"); defaultExecutor_.execute(runnable); } else { stage.execute(runnable); } } public static CallbackInfo removeRegisteredCallback(String messageId) { return callbacks.remove(messageId); } public static long getRegisteredCallbackAge(String messageId) { return callbacks.getAge(messageId); } public static void validateMagic(int magic) throws IOException { if (magic != PROTOCOL_MAGIC) throw new IOException("invalid protocol header"); } public static int getBits(int x, int p, int n) { return x >>> (p + 1) - n & ~(-1 << n); } public static ByteBuffer packIt(byte[] bytes, boolean compress) { /* Setting up the protocol header. This is 4 bytes long represented as an integer. The first 2 bits indicate the serializer type. The 3rd bit indicates if compression is turned on or off. It is turned off by default. The 4th bit indicates if we are in streaming mode. It is turned off by default. The 5th-8th bits are reserved for future use. The next 8 bits indicate a version number. Remaining 15 bits are not used currently. */ int header = 0; // Setting up the serializer bit header |= serializerType_.ordinal(); // set compression bit. if (compress) header |= 4; // Setting up the version bit header |= (version_ << 8); ByteBuffer buffer = ByteBuffer.allocate(4 + 4 + 4 + bytes.length); buffer.putInt(PROTOCOL_MAGIC); buffer.putInt(header); buffer.putInt(bytes.length); buffer.put(bytes); buffer.flip(); return buffer; } public static ByteBuffer constructStreamHeader(boolean compress) { /* Setting up the protocol header. This is 4 bytes long represented as an integer. The first 2 bits indicate the serializer type. The 3rd bit indicates if compression is turned on or off. It is turned off by default. The 4th bit indicates if we are in streaming mode. It is turned off by default. The following 4 bits are reserved for future use. The next 8 bits indicate a version number. Remaining 15 bits are not used currently. */ int header = 0; // Setting up the serializer bit header |= serializerType_.ordinal(); // set compression bit. if ( compress ) header |= 4; // set streaming bit header |= 8; // Setting up the version bit header |= (version_ << 8); /* Finished the protocol header setup */ ByteBuffer buffer = ByteBuffer.allocate(4 + 4); buffer.putInt(PROTOCOL_MAGIC); buffer.putInt(header); buffer.flip(); return buffer; } public static int incrementDroppedMessages(StorageService.Verb verb) { return droppedMessages.get(verb).incrementAndGet(); } private static void logDroppedMessages() { boolean logTpstats = false; for (Map.Entry entry : droppedMessages.entrySet()) { AtomicInteger dropped = entry.getValue(); if (dropped.get() > 0) { logTpstats = true; logger_.warn(String.format("Dropped %s %s messages in the last %sms", dropped, entry.getKey(), LOG_DROPPED_INTERVAL_IN_MS)); } dropped.set(0); } if (logTpstats) GCInspector.instance.logStats(); } private class SocketThread extends Thread { private final ServerSocket server; SocketThread(ServerSocket server, String name) { super(name); this.server = server; } public void run() { while (true) { try { Socket socket = server.accept(); new IncomingTcpConnection(socket).start(); } catch (AsynchronousCloseException e) { // this happens when another thread calls close(). logger_.info("MessagingService shutting down server thread."); break; } catch (IOException e) { throw new RuntimeException(e); } catch (Throwable e) { logger_.error("Unexpected error ",e); } } } void close() throws IOException { server.close(); } } } SigmundGranaas/forgero package com.sigmundgranaas.forgero.core.toolpart.binding; import com.sigmundgranaas.forgero.core.toolpart.AbstractToolPart; import com.sigmundgranaas.forgero.core.toolpart.ForgeroToolPartTypes; public class Binding extends AbstractToolPart implements ToolPartBinding { public Binding(BindingState state) { super(state); } @Override public String getToolPartName() { return ForgeroToolPartTypes.BINDING.getName(); } @Override public ForgeroToolPartTypes getToolPartType() { return ForgeroToolPartTypes.BINDING; } } zhoutianling/AriaAria/src/main/java/com/arialyy/aria/core/download/AbsDownloadTarget.java1-10 /* * Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.arialyy.aria.core.download; import com.arialyy.aria.core.AriaManager; import com.arialyy.aria.core.command.normal.NormalCmdFactory; import com.arialyy.aria.core.inf.AbsEntity; import com.arialyy.aria.core.inf.AbsTarget; import com.arialyy.aria.core.inf.AbsTaskEntity; import com.arialyy.aria.util.CommonUtil; /** * Created by lyy on 2017/2/28. */ abstract class AbsDownloadTarget extends AbsTarget { static final int HTTP = 1; static final int FTP = 2; //HTTP任务组 static final int GROUP_HTTP = 3; //FTP文件夹 static final int GROUP_FTP_DIR = 4; /** * 设置的文件保存路径的临时变量 */ String mTempFilePath; /** * {@code true}强制下载,不考虑文件路径是否被占用 */ boolean forceDownload = false; /** * 将任务设置为最高优先级任务,最高优先级任务有以下特点: * 1、在下载队列中,有且只有一个最高优先级任务 * 2、最高优先级任务会一直存在,直到用户手动暂停或任务完成 * 3、任务调度器不会暂停最高优先级任务 * 4、用户手动暂停或任务完成后,第二次重新执行该任务,该命令将失效 * 5、如果下载队列中已经满了,则会停止队尾的任务,当高优先级任务完成后,该队尾任务将自动执行 * 6、把任务设置为最高优先级任务后,将自动执行任务,不需要重新调用start()启动任务 */ protected void setHighestPriority() { if (checkEntity()) { AriaManager.getInstance(AriaManager.APP) .setCmd(CommonUtil.createNormalCmd(mTaskEntity, NormalCmdFactory.TASK_HIGHEST_PRIORITY, checkTaskType())) .exe(); } } /** * 添加任务 */ public void add() { if (checkEntity()) { AriaManager.getInstance(AriaManager.APP) .setCmd(CommonUtil.createNormalCmd(mTaskEntity, NormalCmdFactory.TASK_CREATE, checkTaskType())) .exe(); } } /** * 获取任务文件大小 * * @return 文件大小 */ public long getFileSize() { return getSize(); } /** * 获取单位转换后的文件大小 * * @return 文件大小{@code xxx mb} */ public String getConvertFileSize() { return getConvertSize(); } /** * 设置target类型 * * @return {@link #HTTP}、{@link #FTP}、{@link #GROUP_HTTP}、{@link #GROUP_FTP_DIR} */ protected abstract int getTargetType(); } package ch.bemar.supercache.cache; import java.io.Serializable; public interface IEvictionPolicy { public boolean isEvictionCandidate(V object); } 10-100 /* Copyright Airship and Contributors */ package com.urbanairship.analytics; import com.urbanairship.Logger; import com.urbanairship.json.JsonMap; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; /** * A screen tracking event allows users to track an activity by associating a * screen identifier within an activity's onStart callback. */ class ScreenTrackingEvent extends Event { /** * The screen tracking type key. */ @NonNull static final String TYPE = "screen_tracking"; /** * The maximum screen tracking event identifier length. */ static final int SCREEN_TRACKING_EVENT_MAX_CHARACTERS = 255; /** * The screen key. */ @NonNull static final String SCREEN_KEY = "screen"; /** * The previous screen key. */ @NonNull static final String PREVIOUS_SCREEN_KEY = "previous_screen"; /** * The start time key. */ @NonNull static final String START_TIME_KEY = "entered_time"; /** * The stop time key. */ @NonNull static final String STOP_TIME_KEY = "exited_time"; /** * The duration key. */ @NonNull static final String DURATION_KEY = "duration"; private final String screen; private final long startTime; private final long stopTime; private final String previousScreen; /** * Constructor for creating a screen tracking event. * * @param screen The ID of the screen. * @param previousScreen The optional ID of the previously tracked screen. * @param startTime The screen tracking start time in milliseconds. * @param stopTime The screen tracking stop time in milliseconds. */ ScreenTrackingEvent(@NonNull String screen, @Nullable String previousScreen, long startTime, long stopTime) { this.screen = screen; this.startTime = startTime; this.stopTime = stopTime; this.previousScreen = previousScreen; } @Override public boolean isValid() { if (screen.length() > SCREEN_TRACKING_EVENT_MAX_CHARACTERS || screen.length() <= 0) { Logger.error("Screen identifier string must be between 1 and 255 characters long."); return false; } if (startTime > stopTime) { Logger.error("Screen tracking duration must be positive or zero."); return false; } return true; } @NonNull @Override public String getType() { return TYPE; } /** * @hide */ @NonNull @Override @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public final JsonMap getEventData() { return JsonMap.newBuilder() .put(SCREEN_KEY, screen) .put(START_TIME_KEY, Event.millisecondsToSecondsString(startTime)) .put(STOP_TIME_KEY, Event.millisecondsToSecondsString(stopTime)) .put(DURATION_KEY, Event.millisecondsToSecondsString(stopTime - startTime)) .put(PREVIOUS_SCREEN_KEY, previousScreen) .build(); } } package com.aimilin.utils; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; /** * List操作工具类 * * @author LiuJunGuang */ public class ListUtils { private ListUtils() { super(); } /** * 根据指定的大小拆分列表 * * @param list 需要拆分的列表 * @param size 每个子列表最大元素个数 * @param 任意类型数据 * @return 拆分之后的列表 */ public static List> split(List list, int size) { if (list == null || list.isEmpty()) return null; List> splitList = new LinkedList<>(); int listSize = list.size(); for (int i = 0; i < Math.ceil(listSize / Double.valueOf(size)); i++) { int end = (i + 1) * size > listSize ? listSize : (i + 1) * size; List subList = list.subList(i * size, end); splitList.add(subList); } return splitList; } /** * 将给定的字符串数据构建一个列表类型对象 * * @param params 字符串数组 * @return List 结果列表 */ public static List createList(String... params) { return array2List(params); } /** * 将给定的数据对象构建一个列表类型对象 * * @param params 字符串数组 * @param 任意类型 * @return List 结果列表 */ @SuppressWarnings("unchecked") public static List createList(S... params) { if (params == null) { return null; } List targets = new ArrayList<>(); for (S param : params) { targets.add(param); } return targets; } /** * 合并给定两个列表数据到一个新列表中,源列表始终会排在前面,不会影响源和目标数据列表 * * @param sources 源列表 * @param targets 目标列表 * @param 任意类型 * @return List 结果列表 */ public static List mergerList(List sources, List targets) { List results = new ArrayList<>(); if (sources != null && !sources.isEmpty()) { results.addAll(sources); } if (targets != null && !targets.isEmpty()) { results.addAll(targets); } return results; } /** * 将给定的列表合并成一个列表 * * @param sources 源列表 * @param 任意类型 * @return List 结果列表 */ public static List mergerList(List> sources) { List results = new ArrayList<>(); if (sources == null || sources.isEmpty()) { return results; } for (List source : sources) { if (source == null || source.isEmpty()) { continue; } results.addAll(source); } return results; } /** * 将字符串(以逗号分隔,如:A,B,C)解析成List * * @param str 参数 * @return 若未指定字符串则返回空列表 */ public static List str2List(String str) { return str2List(str, ","); } /** * 将字符串(以指定分隔符分隔,如:A,B,C)解析成List * * @param str 字符串参数 * @param separator 分隔符,若未给定则返回只包含指定字符串的列表 * @return 若未指定字符串则返回空列表 */ public static List str2List(String str, String separator) { String[] array = StringUtils.split(str, separator); if (ArrayUtils.isEmpty(array)) { return new ArrayList<>(); } return array2List(array); } /** * 将字符串列表对象转换成字符串数组对象,如果list为null或空列表,则返回null * * @param list 要转换的字符串列表对象 * @return 字符串数组 */ public static String[] list2Array(List list) { if (list == null || list.isEmpty()) { return null; } String[] strArray = new String[list.size()]; for (int i = 0; i < list.size(); i++) { strArray[i] = list.get(i); } return strArray; } /** * 将字符串数组转换成以逗号分隔的字符串 * * @param array 字符串数组 * @return 字符串 */ public static String array2Str(String[] array) { return array2Str(array, null); } /** * 以指定分隔符构建字符串 * * @param words 字符串数组 * @param separator 分隔符 * @return 拼接之后的字符串 */ public static String array2Str(String[] words, String separator) { if (ArrayUtils.isEmpty(words)) { return ""; } if (StringUtils.isEmpty(separator)) { separator = ","; } StringBuilder sb = new StringBuilder(); for (String word : words) { if (StringUtils.isEmpty(word)) { continue; } sb.append(word).append(separator); } return StringUtils.removeEnd(sb.toString(), separator); } /** * 将给定列表List转换成以逗号分隔的字符串 * * @param sources 列表 * @return 若未指定列表则返回空字符串,若返回null则表示格式化失败 */ public static String list2Str(List sources) { return list2Str(sources, ","); } /** * 将给定列表List转换成以指定分隔符分隔的字符串 * * @param sources 字符串参数列表 * @param separator 分隔符,若未指定默认以逗号代替 * @return 字符串 */ public static String list2Str(List sources, String separator) { return list2Str(sources, null, separator); } /** * List转换成列表 * * @param sources 列表 * @param prefix 前缀 * @param separator 分隔符 * @return 字符串 */ public static String list2Str(List sources, String prefix, String separator) { if (sources == null || sources.isEmpty()) return null; StringBuilder sb = new StringBuilder(); for (String string : sources) { if (prefix != null) { sb.append(prefix); } sb.append(string).append(separator); } return StringUtils.removeEnd(sb.toString(), separator); } /** * 将给定类型的对象列表转换成列表 * * @param array 数组 * @param 任意类型数据 * @return List 结果集 */ @SuppressWarnings("unchecked") public static List array2List(S... array) { List strList = new LinkedList<>(); if (array != null && array.length != 0) { for (S string : array) { strList.add(string); } } return strList; } /** * 字符串列表去重 * * @param sources 源列表 * @return List */ public static List unique(List sources) { if (sources == null || sources.isEmpty()) { return sources; } List targets = new ArrayList<>(); for (String source : sources) { if (StringUtils.isEmpty(source)) { continue; } if (targets.contains(source)) { continue; } targets.add(source); } return targets; } /** * 将字符串列表转换成大写字符串列表,同时过滤掉null及空字符串 * * @param strList 字符串列表 * @return List */ public static List toUpper(List strList) { List targets = new ArrayList<>(); for (String string : strList) { if (StringUtils.isNotBlank(string)) { targets.add(string.toUpperCase()); } } return targets; } /** * 将字符串列表转换成小写字符串列表,同时过滤掉null及空字符串 * * @param strList 字符串列表 * @return List */ public static List toLower(List strList) { List targets = new ArrayList<>(); for (String string : strList) { if (StringUtils.isNotBlank(string)) { targets.add(string.toLowerCase()); } } return targets; } /** * 计算指定列表的长度 * * @param lists 字符串集合 * @return 大小 */ public static int size(Collection lists) { return lists == null ? 0 : lists.size(); } /** * 判定集合为空 * * @param entityList List列表 * @return 是否为空,true 空 */ public static boolean isEmpty(Collection entityList) { return entityList == null || entityList.isEmpty(); } /** * 判定集合非空 * * @param entityList List列表 * @return 是否为空,true 不空 */ public static boolean isNotEmpty(Collection entityList) { return entityList != null && !entityList.isEmpty(); } /** * 列表排序,本排序方法是null值安全的 * * @param sources 源列表 * @param 任意类型 * @param comparer 比较器 */ public static void sortList(List sources, Comparator comparer) { if (isEmpty(sources) || comparer == null) { return; } Collections.sort(sources, comparer); } /** * 列表排序 * * @param 任意类型 * @param sources 源列表 */ public static > void sortList(List sources) { if (isEmpty(sources)) { return; } Collections.sort(sources); } /** * 列表求和 * * @param paramList 参数列表 * @return 长度 */ public static Integer sumList(int[] paramList) { if (paramList == null || paramList.length == 0) return 0; Integer sum = 0; for (Integer integer : paramList) { sum += integer; } return sum; } /** * 根据指定的大小拆分列表 * * @param list 需要拆分的列表 * @param size 每个子列表最大元素个数 * @param 任意类型数据 * @return 拆分之后的列表 */ public static List> splitList(List list, int size) { if (list == null || list.isEmpty()) return null; List> splitList = new LinkedList<>(); int listSize = list.size(); for (int i = 0; i < Math.ceil(listSize / Double.valueOf(size)); i++) { int end = (i + 1) * size > listSize ? listSize : (i + 1) * size; List subList = list.subList(i * size, end); splitList.add(subList); } return splitList; } /** * 过滤Map中指定的字段 * * @param list 列表 * @param key 待过滤的属性名称 * @param 任意类型 * @param 任意类型 * @return 过滤之后的属性值列表 */ @SuppressWarnings("unchecked") public static List filter(List> list, String key) { if (list == null || list.isEmpty()) return null; List result = new ArrayList<>(); for (Map map : list) { Object value = MapUtils.getObject(map, key); if (value != null) { result.add((V) value); } } return result; } /** * 将列表转换成Key - Map 形式,方便取值,如果key值不唯一,则将会覆盖原值,谨慎使用 * * @param list 数据源 * @param key 作为Key的属性名称 * @param 任意类型 * @return Map */ public static Map> keyMap(List> list, String key) { Map> result = new HashMap<>(); if (list == null || list.isEmpty()) return result; for (Map map : list) { String value = MapUtils.getString(map, key); if (StringUtils.isNotBlank(value)) { result.put(value, map); } } return result; } /** * 将列表转换成Key - List<Map<String,Object>> 形式,方便取值,如果key值重复则在列表中添加 * * @param list 数据源 * @param key 作为Key的属性名称 * @param 任意类型 * @return Map */ public static Map>> keyList(List> list, String key) { return keyList(list, key, null); } /** * 将列表转换成Key - List<Map<String,Object>> 形式,方便取值,如果key值重复则在列表中添加,如果Key值取不到或者为空则使用默认值 * * @param list 列表 * @param key 作为key 的属性名称 * @param defaultKey Key 的默认值 * @param 任意类型 * @return Map */ public static Map>> keyList(List> list, String key, String defaultKey) { Map>> result = new LinkedHashMap<>(); if (list == null || list.isEmpty()) return result; for (Map map : list) { String keyValue = MapUtils.getString(map, key, defaultKey); if (result.containsKey(keyValue)) { result.get(keyValue).add(map); } else { List> tempList = new ArrayList<>(); tempList.add(map); result.put(keyValue, tempList); } } return result; } } 0 package io.izzel.taboolib.util; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.util.Vector; import java.util.Objects; import java.util.StringJoiner; public class Quat { public static final double DBL_EPSILON = Double.longBitsToDouble(0x3cb0000000000000L); private final double x; private final double y; private final double z; private final double w; public Quat(double x, double y, double z, double w) { this.x = x; this.y = y; this.z = z; this.w = w; } public double x() { return x; } public double y() { return y; } public double z() { return z; } public double w() { return w; } public double length() { return Math.sqrt(lengthSquared()); } public double lengthSquared() { return x * x + y * y + z * z + w * w; } public Quat rotate(Quat vector) { return rotate(vector.x(), vector.y(), vector.z()); } public Quat rotate(double x, double y, double z) { final double length = length(); if (Math.abs(length) < DBL_EPSILON) { throw new ArithmeticException("Cannot rotate by zero"); } 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 Quat( pw * -nx + px * nw - py * nz + pz * ny, pw * -ny + py * nw - pz * nx + px * nz, pw * -nz + pz * nw - px * ny + py * nx, 0); } public Quat rotate2D(double angle, double aboutX, double aboutZ) { return rotate2D(angle, aboutX, aboutZ, 0, 0); } public Quat rotate2D(double angle, double aboutX, double aboutZ, double translateX, double translateZ) { angle = Math.toRadians(angle); double x = this.x - aboutX; double z = this.z - aboutZ; double cos = Math.cos(angle); double sin = Math.sin(angle); double x2 = x * cos - z * sin; double z2 = x * sin + z * cos; return new Quat(x2 + aboutX + translateX, this.y, z2 + aboutZ + translateZ, 0); } public Quat getMinimum(Quat v2) { return Quat.at(Math.min(this.x, v2.x), Math.min(this.y, v2.y), Math.min(this.z, v2.z)); } public Quat getMaximum(Quat v2) { return Quat.at(Math.max(this.x, v2.x), Math.max(this.y, v2.y), Math.max(this.z, v2.z)); } public Vector toVector() { return new Vector(x, y, z); } public Location toLocation(World world) { return new Location(world, x, y, z); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Quat)) return false; Quat quat = (Quat) o; return Double.compare(quat.x, x) == 0 && Double.compare(quat.y, y) == 0 && Double.compare(quat.z, z) == 0 && Double.compare(quat.w, w) == 0; } @Override public int hashCode() { return Objects.hash(x, y, z, w); } @Override public String toString() { return new StringJoiner(", ", Quat.class.getSimpleName() + "[", "]") .add("x=" + x) .add("y=" + y) .add("z=" + z) .add("w=" + w) .toString(); } public static Quat one() { return Quat.at(1, 1, 1); } public static Quat zero() { return Quat.at(0, 0, 0); } public static Quat at(Vector vector) { return Quat.at(vector.getX(), vector.getY(), vector.getZ(), 0); } public static Quat at(Location location) { return Quat.at(location.getX(), location.getY(), location.getZ()); } public static Quat at(double x, double y, double z) { return new Quat(x, y, z, 0); } public static Quat at(double x, double y, double z, double w) { return new Quat(x, y, z, w); } public static Quat radiansAxis(double angle, Vector vector) { return radiansAxis(angle, vector.getX(), vector.getY(), vector.getZ()); } public static Quat radiansAxis(double angle, double x, double y, double z) { final double halfAngle = angle / 2; final double q = Math.sin(halfAngle) / Math.sqrt(x * x + y * y + z * z); return new Quat(x * q, y * q, z * q, Math.cos(halfAngle)); } } 0 package com.wzw.ziweishopcity.order.vo; import com.wzw.ziweishopcity.order.entity.OrderEntity; import com.wzw.ziweishopcity.order.entity.OrderItemEntity; import lombok.Data; import java.math.BigDecimal; import java.util.List; @Data public class OrderCreateVo { private OrderEntity orderEntity; private List orderItemEntities; private BigDecimal finalPrice; } src/main/java/org/jscep/client/inspect/AbstractCertStoreInspector.java package org.jscep.client.inspect; import java.security.cert.CertSelector; import java.security.cert.CertStore; import java.security.cert.CertStoreException; import java.security.cert.Certificate; import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.Collection; import javax.security.auth.x500.X500Principal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class AbstractCertStoreInspector implements CertStoreInspector { /** * Logger. */ static final Logger LOGGER = LoggerFactory .getLogger(AbstractCertStoreInspector.class); protected final CertStore store; protected X509Certificate signer; protected X509Certificate recipient; protected X509Certificate issuer; public AbstractCertStoreInspector(CertStore store) { this.store = store; try { inspect(); } catch (CertStoreException e) { throw new RuntimeException(e); } } private void inspect() throws CertStoreException { Collection certs = store.getCertificates(null); LOGGER.debug("CertStore contains {} certificate(s):", certs.size()); int i = 0; for (Certificate cert : certs) { X509Certificate x509 = (X509Certificate) cert; LOGGER.debug("{}. '[dn={}; serial={}]'", new Object[] { ++i, x509.getSubjectDN(), x509.getSerialNumber() }); } LOGGER.debug("Looking for recipient entity"); recipient = selectCertificate(store, getRecipientSelectors()); LOGGER.debug("Using [dn={}; serial={}] for recipient entity", recipient.getSubjectDN(), recipient.getSerialNumber()); LOGGER.debug("Looking for message signing entity"); signer = selectCertificate(store, getSignerSelectors()); LOGGER.debug("Using [dn={}; serial={}] for message signing entity", signer.getSubjectDN(), signer.getSerialNumber()); LOGGER.debug("Looking for issuing entity"); issuer = selectCertificate(store, getIssuerSelectors(recipient.getIssuerX500Principal().getEncoded())); LOGGER.debug("Using [dn={}; serial={}] for issuing entity", issuer.getSubjectDN(), issuer.getSerialNumber()); } /** * Finds the certificate of the SCEP message object recipient. * * @param store * the certificate store to inspect. * @return the recipient's certificate. * @throws CertStoreException * if the CertStore cannot be inspected */ X509Certificate selectCertificate(final CertStore store, final Collection selectors) throws CertStoreException { for (CertSelector selector : selectors) { LOGGER.debug("Selecting certificate using {}", selector); Collection certs = store .getCertificates(selector); if (certs.size() > 0) { LOGGER.debug("Selected {} certificate(s) using {}", certs.size(), selector); return (X509Certificate) certs.iterator().next(); } else { LOGGER.debug("No certificates selected"); } } return (X509Certificate) store.getCertificates(null).iterator().next(); } protected abstract Collection getIssuerSelectors(byte[] issuerDN); protected abstract Collection getSignerSelectors(); protected abstract Collection getRecipientSelectors(); /** * {@inheritDoc} */ public final X509Certificate getSigner() { return signer; } /** * {@inheritDoc} */ public final X509Certificate getRecipient() { return recipient; } /** * {@inheritDoc} */ public final X509Certificate getIssuer() { return issuer; } } Amatofrancesco99/Progetto-F21 package cinema.controller.handlers; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.time.format.TextStyle; import java.util.HashMap; import java.util.Locale; import com.itextpdf.text.BadElementException; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.Image; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import cinema.model.cinema.PhysicalSeat; import cinema.model.cinema.util.RoomException; import cinema.model.reservation.Reservation; import cinema.controller.handlers.util.HandlerException; /** * Crea un report, in formato .pdf, contenente tutte le informazioni inerenti * alla prenotazione. * * @author * */ public class ReportHandler { /** * Nome del cinema. */ private String name; /** * E-mail del cinema. */ private String email; /** * Ubicazione del cinema. */ private String location; /** * URL del logo del cinema. */ private String logoURL; /** * Costruttore del gestore del report. * * @param name nome del cinema. * @param email e-mail del cinema. * @param location ubicazione del cinema. * @param logoURL URL del logo del cinema (iconfinder.com). */ public ReportHandler(String name, String email, String location, String logoURL) { this.name = name; this.email = email; this.location = location; this.logoURL = logoURL; } /** * Crea la ricevuta contenente i dati della prenotazione. * * @param reservation prenotazione della quale si vuole generare la ricevuta. * @throws HandlerException se vengono riscontrati errori nella creazione della * ricevuta di prenotazione. */ public void createReport(Reservation reservation) throws HandlerException { // Posizione in cui il report sarà salvato String FILE = "./savedReports/Reservation_" + Long.toString(reservation.getProgressive()) + ".pdf"; HashMap allFonts = createAllFonts(); // impostazione dei font che verranno utilizzati nel report try { Document document = createEmptyDocument(FILE); // Genera un documento vuoto document.open(); // Apre il documento addDocumentProperties(document, reservation); // Aggiunge le proprietà al documenti Image image = createReportLogoImage(); // Crea una nuova immagine con il logo del cinema Paragraph titleP = createReportTitleParagraph(allFonts); // Crea un paragrafo contenente il titolo del // cinema Paragraph infoCinemaP = createCinemaInfoParagraph(allFonts); // Crea un paragrafo contenente alcune // proprietà del cinema Paragraph filmP = createFilmTitleParagraph(allFonts, reservation); // Crea un paragrafo contenente il // titolo del // film associato alla prenotazioni Paragraph infoFilmP = createFilmPropertiesParagraph(allFonts, reservation); // Crea un paragrafo // contenente // alcune informazioni riassuntive sul // film che si vuole visionare // Crea un paragrafo con le informazioni della reservation Paragraph infoReservationP = createReservationPropertiesParagraph(allFonts, reservation); PdfPTable table = createEmptyTable(); // Genera una tabella insertFieldsIntoTable(table, reservation); // Aggiunge alla tabella i posti selezionati Paragraph totalP = createTotalParagraph(allFonts, reservation); // Crea un paragrafo con il totale della // prenotazione addAllInfoToDocument(document, image, titleP, infoCinemaP, filmP, infoFilmP, infoReservationP, table, totalP); // Aggiunge al documento tutte le informazioni precedentemente create document.close(); // Chiude del documento reservation.setReportLocation(FILE); // se tutto va bene aggiunge il report alla cartella contenente tutti i // report // emessi dal cinema } catch (Exception e) { throw new HandlerException("Si è verificato un problema nella generazione del report."); } } /** * Aggiugne al documento (report) tutte le informazioni e i paragrafi utili a * generarlo. * * @param document documento che formalmente rappresenta il nostro * report. * @param image immagine con il logo del cinema. * @param titleP paragrafo con il titolo del cinema. * @param infoCinemaP paragrafo che contiene le proprietà del cinema. * @param filmP paragrafo che contiene il titolo del film associato * alla prenotazione. * @param infoFilmP paragrafo che contiene le informazioni del film * associato alla prenotazione. * @param infoReservationP paragrafo che contiene le informazioni della * prenotazione. * @param table tabella che conterrà i posti associati alla * prenotazione. * @param totalP paragrafo che contiene il totale della prenotazione. * @throws DocumentException se si verificano problemi nella generazione del * documento. */ private void addAllInfoToDocument(Document document, Image image, Paragraph titleP, Paragraph infoCinemaP, Paragraph filmP, Paragraph infoFilmP, Paragraph infoReservationP, PdfPTable table, Paragraph totalP) throws DocumentException { document.add(image); document.add(titleP); document.add(infoCinemaP); document.add(filmP); document.add(infoFilmP); document.add(infoReservationP); document.add(table); document.add(totalP); } /** * Genera un paragrafo contenente il totale della prenotazione. * * @param allFonts HashMap che contiene tutti i font utili. * @param reservation prenotazione di cui si vuole creare il report. * @return il paragrafo che contiene il totale della prenotazione. */ private Paragraph createTotalParagraph(HashMap allFonts, Reservation reservation) { Paragraph totalP = new Paragraph("Totale " + String.format("%.02f", reservation.getTotal()) + " EUR", allFonts.get("subFont3")); totalP.setSpacingBefore(60); totalP.setAlignment(Element.ALIGN_RIGHT); totalP.setIndentationRight(55); return totalP; } /** * Aggiunge alla tabella i posti selezionati nella prenotazione. * * @param table tabella che conterrà i posti associati alla prenotazione. * @param reservation prenotazione di cui si vuole creare il report. * @throws RoomException se ci sono delle eccezioni generate dalla classe Room. */ private void insertFieldsIntoTable(PdfPTable table, Reservation reservation) throws RoomException { PdfPCell c1 = new PdfPCell(new Phrase("Posti prenotati scelti al momento dell'acquisto")); c1.setHorizontalAlignment(Element.ALIGN_CENTER); c1.setVerticalAlignment(Element.ALIGN_MIDDLE); c1.setMinimumHeight(30); table.addCell(c1); for (PhysicalSeat s : reservation.getSeats()) { String seatCoordinates = reservation.getProjection().getSeatCoordinates(s); if (seatCoordinates != null) { PdfPCell cSeat = new PdfPCell(new Phrase("Fila " + seatCoordinates.replaceAll("\\d", "") + ", Posto " + seatCoordinates.replaceAll("[\\D]", ""))); cSeat.setVerticalAlignment(Element.ALIGN_MIDDLE); cSeat.setMinimumHeight(20); table.addCell(cSeat); } } } /** * Crea una tabella vuota. * * @return una tabella vuota. */ private PdfPTable createEmptyTable() { PdfPTable table = new PdfPTable(1); table.setSpacingBefore(60); return table; } /** * Genera un paragrafo contenente alcune informazioni riassuntive sulla * prenotazione effettuata. * * @param allFonts HashMap che contiene tutti i font utili. * @param reservation prenotazione di cui si vuole creare il report. * @return il paragrafo che contiene le informazioni della prenotazione. */ private Paragraph createReservationPropertiesParagraph(HashMap allFonts, Reservation reservation) { String dayOfWeek = reservation.getProjection().getDateTime().getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ITALIAN); String month = reservation.getProjection().getDateTime().getMonth().getDisplayName(TextStyle.FULL, Locale.ITALIAN); Paragraph infoReservationP = new Paragraph("Prenotazione effettuata da " + reservation.getPurchaser().getName() + " " + reservation.getPurchaser().getSurname() + "\n" + "Sala " + reservation.getProjection().getRoom().getNumber() + " - " + dayOfWeek.toUpperCase().charAt(0) + dayOfWeek.substring(1) + " " + reservation.getProjection().getDateTime().getDayOfMonth() + " " + month.toUpperCase().charAt(0) + month.substring(1) + " " + reservation.getProjection().getDateTime().getYear() + " alle " + String.format("%02d", reservation.getProjection().getDateTime().getHour()) + ":" + String.format("%02d", reservation.getProjection().getDateTime().getMinute()), allFonts.get("subFont25")); infoReservationP.setSpacingBefore(30); return infoReservationP; } /** * Genera un paragrafo contente alcune informazioni riassuntive sul film. * * @param allFonts HashMap che contiene tutti i font utili. * @param reservation prenotazione di cui si vuole creare il report. * @return il paragrafo che contiene le informazioni del film associato alla * prenotazione. */ private Paragraph createFilmPropertiesParagraph(HashMap allFonts, Reservation reservation) { Paragraph infoFilmP = new Paragraph("Regista/i: " + reservation.getProjection().getMovie().getDirectors().toString().replaceAll("\\[", "").replaceAll( "\\]", "") + " Durata: " + reservation.getProjection().getMovie().getDuration() + " min." + " Rating film: " + reservation.getProjection().getMovie().getRating() + "/5", allFonts.get("subFont2")); return infoFilmP; } /** * Genera un paragrafo contenente il titolo del film. * * @param allFonts HashMap che contiene tutti i font utili. * @param reservation prenotazione di cui si vuole creare il report. * @return il paragrafo che contiene il titolo del film associato alla * prenotazione. */ private Paragraph createFilmTitleParagraph(HashMap allFonts, Reservation reservation) { Paragraph FilmP = new Paragraph("> " + reservation.getProjection().getMovie().getTitle(), allFonts.get("subFont")); FilmP.setSpacingBefore(40); return FilmP; } /** * Genera un paragrafo contenente alcune proprietà riassuntive del cinema. * * @param allFonts HashMap che contiene tutti i font utili. * @return il paragrafo che contiene le proprietà del cinema. */ private Paragraph createCinemaInfoParagraph(HashMap allFonts) { Paragraph infoCinemaP = new Paragraph(location + "\n" + email + "\n", allFonts.get("smallFont")); infoCinemaP.setSpacingBefore(10); infoCinemaP.setAlignment(Element.ALIGN_CENTER); return infoCinemaP; } /** * Genera un paragrafo contenente il titolo del report (nome del cinema). * * @param allFonts HashMap che contiene tutti i font utili. * @return il paragrafo con il titolo del cinema. */ private Paragraph createReportTitleParagraph(HashMap allFonts) { Paragraph titleP = new Paragraph(name + "\n", allFonts.get("catFont")); titleP.setSpacingBefore(80); titleP.setAlignment(Element.ALIGN_CENTER); return titleP; } /** * Crea una nuova immagine contenente il logo del cinema e setta le sue * dimensioni. * * @return l'immagine con il logo del cinema. * @throws BadElementException se l'immagine non viene generata nel modo * corretto. * @throws MalformedURLException se l'URL è malformato. * @throws IOException se l'immagine non viene generata con un input * corretto. */ private Image createReportLogoImage() throws BadElementException, MalformedURLException, IOException { String imageUrl = logoURL; Image image = Image.getInstance(new URL(imageUrl)); image.scalePercent(20f); image.setAbsolutePosition(250f, 715f); return image; } /** * Aggiunge i metadati al documento. * * @param document documento che formalmente rappresenta il nostro report. * @param reservation prenotazione di cui si vuole creare il report. */ private void addDocumentProperties(Document document, Reservation reservation) { document.addTitle("Prenotazione numero " + reservation.getProgressive()); document.addSubject("Using iText"); document.addKeywords("Java, PDF, iText"); document.addAuthor("Screaming Hairy Armadillo Team"); document.addCreator("Screaming Hairy Armadillo Team"); } /** * Crea un documento e lo apre in lettura. * * @param FILE si referisce al percorso relativo dove verrà salvato il report. * @return documento che formalmente rappresenta il nostro report. * @throws FileNotFoundException se si verificano errori nell'apertura del file * dove verrà salvato il report. * @throws DocumentException se si verificano problemi nella generazione del * documento. */ private Document createEmptyDocument(String FILE) throws FileNotFoundException, DocumentException { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(FILE)); return document; } /** * Genera tutti i font che verranno utilizzati nel report. * * @return allFonts HashMap che contiene tutti i font utili. */ private HashMap createAllFonts() { HashMap allFonts = new HashMap(); Font catFont = new Font(Font.FontFamily.HELVETICA, 33, Font.BOLD); Font subFont = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD); Font subFont2 = new Font(Font.FontFamily.HELVETICA, 14, Font.NORMAL); Font subFont25 = new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD); Font subFont3 = new Font(Font.FontFamily.HELVETICA, 16, Font.NORMAL); Font smallFont = new Font(Font.FontFamily.HELVETICA, 14, Font.ITALIC); allFonts.put("catFont", catFont); allFonts.put("subFont", subFont); allFonts.put("subFont2", subFont2); allFonts.put("subFont25", subFont25); allFonts.put("subFont3", subFont3); allFonts.put("smallFont", smallFont); return allFonts; } } src/test/java/ee/risk/util/TestSlugGenerator.java0 package ee.risk.util; import junit.framework.TestCase; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * This test ensures that slug generator works properly * * @author */ public class TestSlugGenerator extends TestCase { private List entities; private SlugGenerator generator; @Override public void setUp() { entities = new ArrayList(); generator = new SlugGenerator(entities); } public void testAddPlainToEmpty() { entities.clear(); String slug = generator.getSlug(Entity.EntityWithTitle(1, "Estonia")); assertEquals("estonia", slug); } public void testAddDashedStringToEmpty() { entities.clear(); String slug = generator.getSlug(Entity.EntityWithTitle(1, "South-Korea")); assertEquals("south-korea", slug); } public void testAddNumericToEmpty() { entities.clear(); String slug = generator.getSlug(Entity.EntityWithTitle(1, "10")); assertEquals("10", slug); } public void testAddDashedNumericToEmpty() { entities.clear(); String slug = generator.getSlug(Entity.EntityWithTitle(1, "-10")); assertEquals("-10", slug); } public void testAddDashedToEmpty() { entities.clear(); String slug = generator.getSlug(Entity.EntityWithTitle(1, "-")); assertEquals("-", slug); } public void testAddDashedMixedToEmpty() { entities.clear(); String slug = generator.getSlug(Entity.EntityWithTitle(1, "South-Korea 10")); assertEquals("south-korea-10", slug); } public void testAddPlainUnique() { entities.clear(); entities.add(Entity.EntityWithName(1, "latvia")); String slug = generator.getSlug(Entity.EntityWithTitle(2, "Estonia")); assertEquals("estonia", slug); } public void testAddDashedUnique() { entities.clear(); entities.add(Entity.EntityWithName(1, "latvia")); String slug = generator.getSlug(Entity.EntityWithTitle(2, "South-Korea")); assertEquals("south-korea", slug); } public void testAddNumericUnique() { entities.clear(); entities.add(Entity.EntityWithName(1, "latvia")); String slug = generator.getSlug(Entity.EntityWithTitle(2, "-10")); assertEquals("-10", slug); } public void testAddDashedMixedUnique() { entities.clear(); entities.add(Entity.EntityWithName(1, "latvia")); String slug = generator.getSlug(Entity.EntityWithTitle(2, "South-Korea 10")); assertEquals("south-korea-10", slug); } public void testAddPlainCollision() { entities.clear(); entities.add(Entity.EntityWithName(1, "latvia")); String slug = generator.getSlug(Entity.EntityWithTitle(2, "Latvia")); assertEquals("latvia-1", slug); } public void testAddDashedCollision() { entities.clear(); entities.add(Entity.EntityWithName(1, "south-korea")); String slug = generator.getSlug(Entity.EntityWithTitle(2, "South-Korea")); assertEquals("south-korea-1", slug); entities.add(Entity.EntityWithName(2, "south-korea-1")); slug = generator.getSlug(Entity.EntityWithTitle(3, "South-Korea")); assertEquals("south-korea-2", slug); } public void testAddDashCollision() { entities.clear(); entities.add(Entity.EntityWithName(1, "-")); String slug = generator.getSlug(Entity.EntityWithTitle(2, "-")); assertEquals("--1", slug); } public void testAddDashedNumericCollision() { entities.clear(); entities.add(Entity.EntityWithName(1, "-10")); String slug = generator.getSlug(Entity.EntityWithTitle(2, "-10")); assertEquals("-10-1", slug); } public void testUpdateNoChange() { entities.clear(); entities.add(Entity.EntityWithName(1, "estonia")); entities.add(Entity.EntityWithName(2, "estonia-1")); entities.add(Entity.EntityWithName(3, "south-korea")); String slug = generator.getSlug(Entity.EntityWithTitle(2, "Estonia")); assertEquals("estonia-1", slug); slug = generator.getSlug(Entity.EntityWithTitle(1, "Estonia")); assertEquals("estonia", slug); slug = generator.getSlug(Entity.EntityWithTitle(3, "South-Korea")); assertEquals("south-korea", slug); } public void testUpdateCollision() { entities.clear(); entities.add(Entity.EntityWithName(1, "estonia")); entities.add(Entity.EntityWithName(2, "estonia-1")); entities.add(Entity.EntityWithName(3, "south-korea")); String slug = generator.getSlug(Entity.EntityWithTitle(3, "Estonia")); assertEquals("estonia-2", slug); slug = generator.getSlug(Entity.EntityWithTitle(2, "Estonia")); assertEquals("estonia-1", slug); slug = generator.getSlug(Entity.EntityWithTitle(1, "Estonia")); assertEquals("estonia", slug); } public void testUpdateUnique() { entities.clear(); entities.add(Entity.EntityWithName(1, "estonia")); entities.add(Entity.EntityWithName(2, "estonia-1")); entities.add(Entity.EntityWithName(3, "south-korea")); String slug = generator.getSlug(Entity.EntityWithTitle(2, "Latvia")); assertEquals("latvia", slug); } public void testUpdateAlternatingFromLast() { entities.clear(); entities.add(Entity.EntityWithName(1, "estonia")); entities.add(Entity.EntityWithName(2, "estonia-1")); entities.add(Entity.EntityWithName(3, "south-korea")); String slug = generator.getSlug(Entity.EntityWithTitle(2, "South-Korea")); assertEquals("south-korea-1", slug); entities.set(1, Entity.EntityWithName(2, slug)); slug = generator.getSlug(Entity.EntityWithTitle(3, "Estonia")); assertEquals("estonia-1", slug); entities.set(2, Entity.EntityWithName(3, slug)); slug = generator.getSlug(Entity.EntityWithTitle(1, "South-Korea")); assertEquals("south-korea-2", slug); } public void testUpdateAlternatingMiddle() { entities.clear(); entities.add(Entity.EntityWithName(1, "estonia")); entities.add(Entity.EntityWithName(2, "estonia-1")); entities.add(Entity.EntityWithName(3, "south-korea")); String slug = generator.getSlug(Entity.EntityWithTitle(1, "South-Korea")); assertEquals("south-korea-1", slug); entities.set(0, Entity.EntityWithName(1, slug)); slug = generator.getSlug(Entity.EntityWithTitle(3, "Estonia")); assertEquals("estonia-2", slug); entities.set(2, Entity.EntityWithName(3, slug)); slug = generator.getSlug(Entity.EntityWithTitle(1, "South-Korea")); assertEquals("south-korea-1", slug); } } package synergynet3.cluster.fileshare.filetransfer.receiver; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smackx.filetransfer.FileTransferListener; import org.jivesoftware.smackx.filetransfer.FileTransferRequest; import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer; import synergynet3.cluster.fileshare.localfilecache.LocalFileCache; import synergynet3.cluster.fileshare.localfilecache.LocalFileCacheEntry; import synergynet3.cluster.fileshare.localfilecache.MD5Hash; /** * The Class FileReceiver. */ public class FileReceiver implements FileTransferListener { /** * The Interface FileReceiverDelegate. */ public static interface FileReceiverDelegate { /** * Error receiving file. * * @param hash * the hash */ void errorReceivingFile(MD5Hash hash); /** * New file added to cache. * * @param entry * the entry */ void newFileAddedToCache(LocalFileCacheEntry entry); } /** The Constant log. */ private static final Logger log = Logger.getLogger(FileReceiver.class.getName()); /** The cache. */ private LocalFileCache cache; /** The delegate. */ private FileReceiverDelegate delegate; /** The hash to device. */ private Map hashToDevice; /** * Instantiates a new file receiver. * * @param delegate * the delegate * @param cache * the cache */ public FileReceiver(FileReceiverDelegate delegate, LocalFileCache cache) { this.delegate = delegate; this.cache = cache; hashToDevice = new HashMap(); } /* * (non-Javadoc) * @see * org.jivesoftware.smackx.filetransfer.FileTransferListener#fileTransferRequest * (org.jivesoftware.smackx.filetransfer.FileTransferRequest) */ @Override public void fileTransferRequest(final FileTransferRequest request) { log.fine("Received file transfer request " + request); final String uniqueFileIdentifier = request.getDescription(); final MD5Hash hash = new MD5Hash(uniqueFileIdentifier); final File temporaryIncomingFile = getTemporaryFileToStoreIncomingTransfer(); log.fine("File " + request.getFileName() + " being saved as " + temporaryIncomingFile.getAbsolutePath()); final IncomingFileTransfer transfer = request.accept(); try { transfer.recieveFile(temporaryIncomingFile); FileTransferWorker fileTransferWorker = new FileTransferWorker(new FileTransferWorker.FileTransferWorkerDelegate() { @Override public void transferComplete() { fileTransferDidComplete(request.getFileName(), temporaryIncomingFile, hash, transfer); } }, transfer); fileTransferWorker.start(); } catch (XMPPException ex) { log.log(Level.SEVERE, null, ex); } } /** * Should receive file. * * @param id * the id * @param device * the device */ public void shouldReceiveFile(MD5Hash id, String device) { hashToDevice.put(id, device); } /** * Gets the temporary file to store incoming transfer. * * @return the temporary file to store incoming transfer */ private File getTemporaryFileToStoreIncomingTransfer() { try { File temporaryFile = File.createTempFile("mn_filexfer", "tmp"); temporaryFile.deleteOnExit(); return temporaryFile; } catch (IOException e) { log.log(Level.SEVERE, "Could not receive an incoming file transfer: couldn't create temporary file storage", e); } return null; } /** * File transfer did complete. * * @param fileName * the file name * @param fileLocation * the file location * @param hash * the hash * @param transfer * the transfer */ protected void fileTransferDidComplete(String fileName, File fileLocation, MD5Hash hash, IncomingFileTransfer transfer) { log.fine("File " + fileLocation.getAbsolutePath() + " with id " + hash + " received successfully."); String device = hashToDevice.get(hash); try { LocalFileCacheEntry entry = cache.addFileToCacheWithName(fileLocation, fileName, device); delegate.newFileAddedToCache(entry); } catch (FileNotFoundException e) { delegate.errorReceivingFile(hash); log.log(Level.SEVERE, "Could not add file " + hash + " to cache", e); } catch (IOException e) { delegate.errorReceivingFile(hash); log.log(Level.SEVERE, "Could not add file " + hash + " to cache", e); } } } arusinha/incubator-netbeans /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.bugtracking.api; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.util.Arrays; import java.util.Collection; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.event.ChangeListener; import org.netbeans.modules.bugtracking.TestIssue; import org.netbeans.modules.bugtracking.spi.IssueController; import org.netbeans.modules.bugtracking.spi.IssueProvider; import org.openide.util.HelpCtx; /** * * @author tomas */ public class APITestIssue extends TestIssue { static final String ID_1 = "1"; static final String ID_2 = "2"; static final String ID_SUB_3 = "3"; static final String ID_NEW = "1000"; static final String SUMMARY_SUF = " - summary"; static final String TOOLTIP_SUF = " - tooltip"; private final String id; private final boolean isNew; boolean wasOpened; boolean wasRefreshed; boolean wasClosedOnComment; String addedComment; String attachedPatchDesc; boolean idFinished; File attachedFile; private IssueController controller; private final APITestRepository repo; private String summary; private String description; private boolean isPatch; public APITestIssue(String id, APITestRepository repo) { this(id, repo, false); } public APITestIssue(String id, APITestRepository repo, boolean isNew) { this(id, repo, isNew, id + SUMMARY_SUF, null); } public APITestIssue(String id, APITestRepository repo, boolean isNew, String summary, String description) { this.id = id; this.isNew = isNew; this.repo = repo; this.summary = summary; this.description = description; } @Override public String getDisplayName() { return "Issue : " + id + getSummary(); } @Override public String getTooltip() { return id + TOOLTIP_SUF; } @Override public String getID() { return id; } @Override public String getSummary() { return summary; } @Override public String getDescription() { return description; } @Override public boolean isNew() { return isNew; } @Override public boolean refresh() { wasRefreshed = true; support.firePropertyChange(IssueProvider.EVENT_ISSUE_DATA_CHANGED, null, null); return true; } @Override public void addComment(String comment, boolean closeAsFixed) { wasClosedOnComment = closeAsFixed; addedComment = comment; } @Override public void attachFile(File file, String description, boolean isPatch) { this.attachedPatchDesc = description; this.attachedFile = file; this.isPatch = isPatch; } @Override public IssueController getController() { if(controller == null) { controller = new IssueController() { @Override public void opened() { wasOpened = true; } private JPanel panel; @Override public JComponent getComponent() { if(panel == null) { panel = new JPanel(); } return panel; } @Override public HelpCtx getHelpCtx() { return null; } @Override public void closed() { } @Override public boolean saveChanges() { return true; } @Override public boolean discardUnsavedChanges() { return true; } @Override public boolean isChanged() { return false; } @Override public void addPropertyChangeListener(PropertyChangeListener l) { } @Override public void removePropertyChangeListener(PropertyChangeListener l) { } }; } return controller; } private final PropertyChangeSupport support = new PropertyChangeSupport(this); @Override public void removePropertyChangeListener(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } @Override public void addPropertyChangeListener(PropertyChangeListener listener) { support.addPropertyChangeListener(listener); } @Override public Collection getSubtasks() { return Arrays.asList(new String[] {APITestIssue.ID_SUB_3}); } @Override public boolean isFinished() { return idFinished; } void discardOutgoing() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } boolean submit() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } package com.hortonworks.streamline.streams.catalog.topology.component.bundle.impl; public class HDFSSpoutBundleHintProvider extends AbstractHDFSBundleHintProvider { public static final String FIELD_NAME_HDFS_URI = "HdfsUri"; @Override protected String getFieldNameForFSUrl() { return FIELD_NAME_HDFS_URI; } } package com.devteam.module.settings; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import com.devteam.module.common.ClientInfo; import com.devteam.module.data.db.sample.EntityDB; import com.devteam.module.settings.currency.data.CurrencyData; import com.devteam.module.settings.location.data.LocationData; import com.devteam.module.settings.resource.data.ResourceData; public class ModuleUnitTest extends TestConfig { ClientInfo client = ClientInfo.DEFAULT; @BeforeEach public void setup() throws Exception { dbService.initDb(clientInfo, true); } @Test @Tag("integration") public void testAll() throws Exception { EntityDB.getInstance().getData(CurrencyData.class).assertAll(client); EntityDB.getInstance().getData(LocationData.class).assertAll(client); EntityDB.getInstance().getData(ResourceData.class).assertResourceEntity(); EntityDB.getInstance().getData(ResourceData.class).assertResourceType(); } @Test @Tag("unit") public void testCurrencyData() throws Exception { EntityDB.getInstance().getData(CurrencyData.class).assertAll(client); } @Test @Tag("unit") public void testLocationData() throws Exception { EntityDB.getInstance().getData(LocationData.class).assertAll(client); } @Test @Tag("unit") public void testResourceEntity() throws Exception { EntityDB.getInstance().getData(ResourceData.class).assertResourceEntity(); } @Test @Tag("unit") public void testResourceType() throws Exception { EntityDB.getInstance().getData(ResourceData.class).assertResourceType(); } @Test @Tag("unit") @Tag("fail") public void testResourceTagDelete() throws Exception { EntityDB.getInstance().getData(ResourceData.class).assertResourceTypeDelete(); } } package com.tylersuehr.socialtextview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.support.annotation.ColorInt; import android.support.annotation.IntDef; import android.support.v7.widget.AppCompatTextView; import android.text.SpannableString; import android.text.Spanned; import android.util.AttributeSet; import android.util.Patterns; import android.view.View; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.LOCAL_VARIABLE; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.CLASS; /** * Copyright © 2017 * * @author * @version 1.0 */ public class SocialTextView extends AppCompatTextView { /* Constants for social media flags */ private static final int HASHTAG = 1; private static final int MENTION = 2; private static final int PHONE = 4; private static final int URL = 8; private static final int EMAIL = 16; private static Pattern patternHashtag; private static Pattern patternMention; /* Mutable properties */ private boolean underlineEnabled; private int selectedColor; private int hashtagColor; private int mentionColor; private int phoneColor; private int emailColor; private int urlColor; private OnLinkClickListener linkClickListener; /* Stores enabled link modes */ private int flags; public SocialTextView(Context c) { this(c, null); } public SocialTextView(Context c, AttributeSet attrs) { this(c, attrs, 0); } public SocialTextView(Context c, AttributeSet attrs, int def) { super(c, attrs, def); // Set the link movement method by default setMovementMethod(AccurateMovementMethod.getInstance()); // Set XML attributes TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.SocialTextView); this.flags = a.getInt(R.styleable.SocialTextView_linkModes, -1); this.hashtagColor = a.getColor(R.styleable.SocialTextView_hashtagColor, Color.RED); this.mentionColor = a.getColor(R.styleable.SocialTextView_mentionColor, Color.RED); this.phoneColor = a.getColor(R.styleable.SocialTextView_phoneColor, Color.RED); this.emailColor = a.getColor(R.styleable.SocialTextView_emailColor, Color.RED); this.urlColor = a.getColor(R.styleable.SocialTextView_urlColor, Color.RED); this.selectedColor = a.getColor(R.styleable.SocialTextView_selectedColor, Color.LTGRAY); this.underlineEnabled = a.getBoolean(R.styleable.SocialTextView_underlineEnabled, false); if (a.hasValue(R.styleable.SocialTextView_android_text)) { setLinkText(a.getString(R.styleable.SocialTextView_android_text)); } if (a.hasValue(R.styleable.SocialTextView_android_hint)) { setLinkHint(a.getString(R.styleable.SocialTextView_android_hint)); } a.recycle(); } /** * Overridden to ensure that highlighted text is always transparent. */ @Override public void setHighlightColor(@ColorInt int color) { super.setHighlightColor(Color.TRANSPARENT); } public void setLinkText(String text) { setText(createSocialMediaSpan(text)); } public void appendLinkText(String text) { append(createSocialMediaSpan(text)); } public void setLinkHint(String textHint) { setHint(createSocialMediaSpan(textHint)); } public void setOnLinkClickListener(OnLinkClickListener linkClickListener) { this.linkClickListener = linkClickListener; } public OnLinkClickListener getOnLinkClickListener() { return linkClickListener; } /** * Creates a spannable string containing the touchable spans of each link item * for each enabled link mode in the given text. * * @param text Text * @return {@link SpannableString} */ private SpannableString createSocialMediaSpan(String text) { final Set items = collectLinkItemsFromText(text); final SpannableString textSpan = new SpannableString(text); // Create a span for each link item for (final LinkItem item : items) { textSpan.setSpan(new TouchableSpan(getColorByMode(item.mode), selectedColor, underlineEnabled) { @Override public void onClick(View widget) { // Trigger callback when span is touched if (linkClickListener != null) { linkClickListener.onLinkClicked(item.mode, item.matched); } } }, item.start, item.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return textSpan; } /** * Checks which flags are enable so that the appropriate link items can be * collected from each respective mode. * * @param text Text * @return Set of {@link LinkItem} */ private Set collectLinkItemsFromText(String text) { final Set items = new HashSet<>(); // Check for hashtag links, if possible if ((flags & HASHTAG) == HASHTAG) { collectLinkItems(HASHTAG, items, getHashtagPattern().matcher(text)); } // Check for mention links, if possible if ((flags & MENTION) == MENTION) { collectLinkItems(MENTION, items, getMentionPattern().matcher(text)); } // Check for phone links, if possible if ((flags & PHONE) == PHONE) { collectLinkItems(PHONE, items, Patterns.PHONE.matcher(text)); } // Check for url links, if possible if ((flags & URL) == URL) { collectLinkItems(URL, items, Patterns.WEB_URL.matcher(text)); } // Check for email links, if possible if ((flags & EMAIL) == EMAIL) { collectLinkItems(EMAIL, items, Patterns.EMAIL_ADDRESS.matcher(text)); } return items; } /** * Iterates through all the matches found by the given matcher and adds a new * {@link LinkItem} for each match into the given collection of link items. * * @param mode {@link LinkOptions} * @param items Collection of {@link LinkItem} * @param matcher {@link Matcher} */ private void collectLinkItems(@LinkOptions int mode, Collection items, Matcher matcher) { while (matcher.find()) { int matcherStart = matcher.start(); String matchedText = matcher.group(); if (matchedText.startsWith(" ")) { matcherStart += 1; matchedText = matchedText.substring(1); } items.add(new LinkItem( matchedText, matcherStart, matcher.end(), mode )); } } /** * Gets the corresponding color for a given mode. * * @param mode {@link #HASHTAG}, {@link #MENTION}, {@link #EMAIL}, {@link #PHONE}, {@link #URL} * @return Color */ private int getColorByMode(@LinkOptions int mode) { switch (mode) { case HASHTAG: return hashtagColor; case MENTION: return mentionColor; case PHONE: return phoneColor; case URL: return urlColor; case EMAIL: return emailColor; default: throw new IllegalArgumentException("Invalid mode!"); } } /** * Lazy loads the 'hashtag' regex pattern. * * @return {@link Pattern} */ private static Pattern getHashtagPattern() { if (patternHashtag == null) { patternHashtag = Pattern.compile("(?:^|\\s|$)#[\\p{L}0-9_]*"); } return patternHashtag; } /** * Lazy loads the 'mention' regex pattern. * * @return {@link Pattern} */ private static Pattern getMentionPattern() { if (patternMention == null) { patternMention = Pattern.compile("(?:^|\\s|$|[.])@[\\p{L}0-9_]*"); } return patternMention; } /** * Data structure to store information about a link. */ private final class LinkItem { private final String matched; private final int start; private final int end; private final int mode; private LinkItem(String matched, int start, int end, int mode) { this.matched = matched; this.start = start; this.end = end; this.mode = mode; } } @Retention(RetentionPolicy.SOURCE) @Target({PARAMETER, METHOD, LOCAL_VARIABLE, FIELD}) @IntDef(value = {HASHTAG, MENTION, PHONE, EMAIL, URL}) public @interface LinkOptions { } /** * Listener for link clicks in text view. */ public interface OnLinkClickListener { void onLinkClicked(int linkType, String matchedText); } }package ca.warp7.pathplotter.remote; import ca.warp7.frc2020.lib.trajectory.ChassisVelocity; import edu.wpi.first.networktables.ConnectionNotification; import edu.wpi.first.networktables.EntryNotification; import edu.wpi.first.networktables.NetworkTableEntry; import edu.wpi.first.networktables.NetworkTableInstance; import edu.wpi.first.wpilibj.geometry.Pose2d; import edu.wpi.first.wpilibj.geometry.Rotation2d; import edu.wpi.first.wpilibj.geometry.Transform2d; import edu.wpi.first.wpilibj.geometry.Translation2d; import javafx.application.Platform; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import static edu.wpi.first.networktables.EntryListenerFlags.*; import static edu.wpi.first.wpilibj.smartdashboard.SmartDashboard.getEntry; public class RemoteListener { private NetworkTableInstance nt = NetworkTableInstance.getDefault(); private List> connectionListeners = new ArrayList<>(); private List> entryListeners = new ArrayList<>(); private static class Entries { private NetworkTableEntry trajectoryTime = getEntry("Trajectory Time"); private NetworkTableEntry targetX = getEntry("Target X (m)"); private NetworkTableEntry targetY = getEntry("Target Y (m)"); private NetworkTableEntry targetAngle = getEntry("Target Angle (deg)"); private NetworkTableEntry robotX = getEntry("Robot X (m)"); private NetworkTableEntry robotY = getEntry("Robot Y (m)"); private NetworkTableEntry robotAngle = getEntry("Robot Angle (deg)"); private NetworkTableEntry errorX = getEntry("Error X (m)"); private NetworkTableEntry errorY = getEntry("Error Y (m)"); private NetworkTableEntry errorAngle = getEntry("Error Angle (deg)"); private NetworkTableEntry targetLinear = getEntry("Target Linear (m/s)"); private NetworkTableEntry targetAngular = getEntry("Target Angular (deg/s)"); private NetworkTableEntry correctedLinear = getEntry("Corrected Linear (m/s)"); private NetworkTableEntry correctedAngular = getEntry("Corrected Angular (deg/s)"); private NetworkTableEntry leftPIDError = getEntry("Left PID Error (m/s)"); private NetworkTableEntry rightPIDError = getEntry("Right PID Error (m/s)"); private MeasuredState toMeasuredState() { return new MeasuredState( trajectoryTime.getDouble(0.0), new Pose2d( new Translation2d( targetX.getDouble(0.0), targetY.getDouble(0.0) ), Rotation2d.fromDegrees(targetAngle.getDouble(0.0)) ), new Pose2d( new Translation2d( robotX.getDouble(0.0), robotY.getDouble(0.0) ), Rotation2d.fromDegrees(robotAngle.getDouble(0.0)) ), new Transform2d( new Translation2d( errorX.getDouble(0.0), errorY.getDouble(0.0) ), Rotation2d.fromDegrees(errorAngle.getDouble(0.0)) ), new ChassisVelocity( targetLinear.getDouble(0.0), Math.toRadians(targetAngular.getDouble(0.0)) ), new ChassisVelocity( correctedLinear.getDouble(0.0), Math.toRadians(correctedAngular.getDouble(0.0)) ), leftPIDError.getDouble(0.0), rightPIDError.getDouble(0.0) ); } } public RemoteListener() { nt.addConnectionListener(connectionNotification -> { Platform.runLater(() -> { for (var listener : connectionListeners) { listener.accept(connectionNotification); } }); }, true); nt.addEntryListener("", entryNotification -> { System.out.println("hi"); Platform.runLater(() -> { for (var listener : entryListeners) { listener.accept(entryNotification); } }); }, kImmediate | kNew | kDelete | kUpdate); nt.startClient(); nt.startDSClient(); } public void addConnectionListener(Consumer listener) { connectionListeners.add(listener); } } MODmaxM/OAworktarget/generated-sources/annotations/com/nju/oawork/model/entity/note/Attachment_.java package com.nju.oawork.model.entity.note; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor") @StaticMetamodel(Attachment.class) public abstract class Attachment_ { public static volatile SingularAttribute attachmentSize; public static volatile SingularAttribute attachmentType; public static volatile SingularAttribute attachmentShuffix; public static volatile SingularAttribute attachmentName; public static volatile SingularAttribute model; public static volatile SingularAttribute attachmentId; public static volatile SingularAttribute uploadTime; public static volatile SingularAttribute userId; public static volatile SingularAttribute attachmentPath; } 0 package cn.yxvk.myshop.plus.business.dto; import lombok.Data; import java.io.Serializable; /** * @author yangxiang * @date 2019/11/19 11:10 */ @Data public class LoginInfo implements Serializable { private static final long serialVersionUID = 2525522707084457877L; private String avatar; private String[] access; private String name; private String userId; } queue/src/main/java/org/killbill/bus/BusReaper.java /* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.bus; import org.killbill.bus.api.PersistentBusConfig; import org.killbill.bus.dao.BusEventModelDao; import org.killbill.clock.Clock; import org.killbill.queue.DBBackedQueue; import org.killbill.queue.DefaultReaper; public class BusReaper extends DefaultReaper { public BusReaper(final DBBackedQueue dao, final PersistentBusConfig config, final Clock clock) { super(dao, config, clock, "BusReaper"); } } /* * NOTICE * This software was produced for the office of the Director of National Intelligence (ODNI) * Intelligence Advanced Research Projects Activity (IARPA) ICArUS program, * BAA number IARPA-BAA-10-04, under contract 2009-0917826-016, and is subject * to the Rights in Data-General Clause 52.227-14, Alt. IV (DEC 2007). * * This software and data is provided strictly to support demonstrations of ICArUS challenge problems * and to assist in the development of cognitive-neuroscience architectures. It is not intended to be used * in operational systems or environments. * * Copyright (C) 2015 The MITRE Corporation. All Rights Reserved. * */ package org.mitre.icarus.cps.app.experiment.phase_1; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import javax.swing.JOptionPane; import javax.swing.JRadioButton; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.AttackPresentationTrialState; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.Task_1_ProbeTrialState; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.Task_2_ProbeTrialState; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.Task_3_ProbeTrialState; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.TrialState_Phase1; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.trial_part_states.ConfirmSettingsTrialPartState; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.trial_part_states.GroupCentersProbeTrialPartState; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.trial_part_states.GroupCirclesProbeTrialPartState; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.trial_part_states.GroupProbeTrialPartState; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.trial_part_states.ProbabilityProbeTrialPartState; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.trial_part_states.ShowScoreTrialPartState; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.trial_part_states.SurpriseProbeTrialPartState; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.trial_part_states.TroopSelectionMultiGroupTrialPartState; import org.mitre.icarus.cps.app.experiment.phase_1.trial_states.trial_part_states.GroupCirclesProbeTrialPartState.GroupCircleShape; import org.mitre.icarus.cps.app.util.ProbabilityUtils; import org.mitre.icarus.cps.app.widgets.WidgetConstants; import org.mitre.icarus.cps.app.widgets.ImageManager.IconSize; import org.mitre.icarus.cps.app.widgets.map.phase_1.MapConstants_Phase1; import org.mitre.icarus.cps.app.widgets.map.phase_1.MapPanelContainer; import org.mitre.icarus.cps.app.widgets.map.phase_1.MapPanelContainer.LayerType; import org.mitre.icarus.cps.app.widgets.map.phase_1.PlacemarkFactory.AttackLocationType; import org.mitre.icarus.cps.app.widgets.map.phase_1.objects.AttackLocationPlacemark; import org.mitre.icarus.cps.app.widgets.map.phase_1.objects.GroupCenterPlacemark; import org.mitre.icarus.cps.app.widgets.phase_1.ColorManager_Phase1; import org.mitre.icarus.cps.app.widgets.phase_1.ImageManager_Phase1; import org.mitre.icarus.cps.app.widgets.phase_1.experiment.GroupSelectionPanel; import org.mitre.icarus.cps.app.widgets.probability_entry.IProbabilityEntryContainer; import org.mitre.icarus.cps.exam.phase_1.response.trial_part_responses.GroupCirclesProbeResponse.GroupCircle; import org.mitre.icarus.cps.exam.phase_1.testing.AttackLocationPresentationTrial; import org.mitre.icarus.cps.exam.phase_1.testing.Task_1_2_3_PhaseBase; import org.mitre.icarus.cps.exam.phase_1.testing.Task_1_2_3_ProbeTrialBase; import org.mitre.icarus.cps.exam.phase_1.testing.Task_1_2_3_TrialBlockBase; import org.mitre.icarus.cps.exam.phase_1.testing.Task_1_ProbeTrial; import org.mitre.icarus.cps.exam.phase_1.testing.Task_2_ProbeTrial; import org.mitre.icarus.cps.exam.phase_1.testing.Task_3_Phase; import org.mitre.icarus.cps.exam.phase_1.testing.Task_3_ProbeTrial; import org.mitre.icarus.cps.exam.phase_1.testing.trial_part_probes.SurpriseReportProbe; import org.mitre.icarus.cps.experiment_core.event.ConditionEvent; import org.mitre.icarus.cps.experiment_core.event.SubjectActionEvent; import org.mitre.icarus.cps.experiment_core.gui.INavButtonPanel.ButtonType; import org.mitre.icarus.cps.experiment_core.subject_data.SubjectConditionData; import org.mitre.icarus.cps.feature_vector.phase_1.GridLocation2D; import org.mitre.icarus.cps.feature_vector.phase_1.GridSize; import org.mitre.icarus.cps.feature_vector.phase_1.GroupAttack; import org.mitre.icarus.cps.feature_vector.phase_1.GroupCenter; import org.mitre.icarus.cps.feature_vector.phase_1.GroupType; import org.mitre.icarus.cps.feature_vector.phase_1.Road; /** * Controller for Tasks 1, 2, and 3. * * @author CBONACETO * */ public class Task_1_2_3_Controller extends TaskController> implements ActionListener { /** The trial states for each trial in the task */ protected List trialStates; /** The trial state for the current trial */ protected TrialState_Phase1 currentTrialState; /** Whether we're at the beginning of a trial block */ protected boolean blockStart; /** The current trial block number */ protected int blockNum; /** The previous probability settings */ protected List previousSettings; /** The last attack location that was shown */ protected AttackLocationPlacemark prevAttackLocation; /** The probe trial attack location */ protected AttackLocationPlacemark probeAttackLocation; /** The group selection panel (used to select a group to send troops against) */ protected GroupSelectionPanel groupSelectionPanel; /** The group circles for each group (Task 2) */ protected ArrayList groupCircles; /** The group centers for each group (Task 3) */ protected ArrayList groupCenters; protected boolean warnIfCirclesOrCentersNotEdited = false; /* (non-Javadoc) * @see org.mitre.icarus.cps.experiment.phase_1.TaskController#initializeTaskController(org.mitre.icarus.cps.exam.phase_1.testing.TaskTestPhase, org.mitre.icarus.cps.gui.phase_1.experiment.ConditionPanel_Phase1) */ @Override public void initializeTask(Task_1_2_3_PhaseBase task) { this.task = task; if(groupSelectionPanel == null) { groupSelectionPanel = new GroupSelectionPanel("groups"); } //Show the S2 score for Tasks 1 - 3 showScore = true; //Show the map scale for Task 3 if(task instanceof Task_3_Phase) { conditionPanel.getMapPanel().setShowScale(true); } else { conditionPanel.getMapPanel().setShowScale(false); } locationsPresent.clear(); groupCenterGroupsPresent.clear(); //Create the trial states for each trial trialStates = new ArrayList(); if(task.getTrialBlocks() != null && !task.getTrialBlocks().isEmpty()) { int trialNum = 0; for(Task_1_2_3_TrialBlockBase trialBlock : task.getTrialBlocks()) { //Create the presentation trial states if(trialBlock.getGroupAttackPresentations() != null) { for(AttackLocationPresentationTrial attackPresentation : trialBlock.getGroupAttackPresentations()) { trialStates.add(new AttackPresentationTrialState(trialNum, attackPresentation)); locationsPresent.add(attackPresentation.getGroupAttack()); trialNum++; } } //Create the probe trial state if(trialBlock.getProbeTrial() != null) { if(trialBlock.getProbeTrial() instanceof Task_1_ProbeTrial) { ((Task_1_ProbeTrial)trialBlock.getProbeTrial()).setTrialResponse(null); trialStates.add(new Task_1_ProbeTrialState(trialNum, (Task_1_ProbeTrial)trialBlock.getProbeTrial(), exam.getNormalizationMode(), showScore)); } else if(trialBlock.getProbeTrial() instanceof Task_2_ProbeTrial) { ((Task_2_ProbeTrial)trialBlock.getProbeTrial()).setTrialResponse(null); trialStates.add(new Task_2_ProbeTrialState(trialNum, (Task_2_ProbeTrial)trialBlock.getProbeTrial(), exam.getNormalizationMode(), showScore)); } else if (trialBlock.getProbeTrial() instanceof Task_3_ProbeTrial) { Task_3_ProbeTrial task3ProbeTrial = (Task_3_ProbeTrial)trialBlock.getProbeTrial(); task3ProbeTrial.setTrialResponse(null); trialStates.add(new Task_3_ProbeTrialState(trialNum, task3ProbeTrial, exam.getNormalizationMode(), showScore)); groupCenterGroupsPresent.addAll(task3ProbeTrial.getGroupCentersProbe().getGroups()); } trialNum++; } } } locationsPresent.add(new GroupAttack(GroupType.Unknown)); } /* (non-Javadoc) * @see org.mitre.icarus.cps.experiment.phase_1.TaskController#getTaskWithResponseData() */ @Override public Task_1_2_3_PhaseBase getTaskWithResponseData() { ArrayList trialBlocks = task.getTrialBlocks(); int currentTrialBlock = -1; ArrayList attackPresentationTimes = null; if(trialBlocks != null && !trialBlocks.isEmpty()) { attackPresentationTimes = new ArrayList(); currentTrialBlock = 0; } if(trialStates != null && !trialStates.isEmpty()) { for(TrialState_Phase1 trialState : trialStates) { trialState.updateTrialResponseData(); if(currentTrialBlock >= 0 && currentTrialBlock < trialBlocks.size()) { if(trialState instanceof AttackPresentationTrialState) { attackPresentationTimes.add(trialState.getTrialTime_ms()); } else { trialBlocks.get(currentTrialBlock).setGroupAttackPresentationTimes_ms(attackPresentationTimes); attackPresentationTimes = new ArrayList(); currentTrialBlock++; } } } } return task; } /* (non-Javadoc) * @see org.mitre.icarus.cps.experiment_core.controller.IConditionController#startCondition(int, org.mitre.icarus.cps.experiment_core.controller.IExperimentController, org.mitre.icarus.cps.experiment_core.subject_data.SubjectConditionData) */ @Override public void startCondition(int firstTrial, IcarusExamController_Phase1 experimentController, SubjectConditionData subjectConditionData) { conditionRunning = true; this.examController = experimentController; if(examController != null) { examController.setNavButtonEnabled(ButtonType.Back, false); examController.setNavButtonEnabled(ButtonType.Next, false); } //Clear the map prevAttackLocation = null; probeAttackLocation = null; MapPanelContainer mapPanel = conditionPanel.getMapPanel(); mapPanel.resetMap(); if(task instanceof Task_3_Phase) { mapPanel.setLayerInstructionsEnabled(true); } else { mapPanel.setLayerInstructionsEnabled(false); } if(task instanceof Task_3_Phase) { //Add the roads layer and roads to the map for Task 3 mapPanel.setRoadLayerEnabled(true); mapPanel.setRoadsLegendItemVisible(true); if(((Task_3_Phase) task).getRoads() != null) { mapPanel.setRoads(((Task_3_Phase) task).getRoads()); } } //Add the SIGACTs layer and to the map and call it "Attacks" mapPanel.setSigactLayerEnabled(true); mapPanel.setSigactsLayerAndLegendName("Attacks"); //Add the SIGACTs legend items to the map for each group mapPanel.setSigactsLegendItemVisible(true); mapPanel.setSigactLocationsInLegend(locationsPresent); if(task instanceof Task_3_Phase) { //Add the group centers legend item to the map for Task 3 mapPanel.setGroupCentersLegendItemVisible(true); mapPanel.setGroupCenterGroupsForLegend(groupCenterGroupsPresent); mapPanel.setGroupCentersLayerAndLegendName("Centers"); } mapPanel.redrawMap(); //Clear the task input panel conditionPanel.setTaskInputPanelVisible(true); taskInputPanel.setAllSubPanelsVisible(false); conditionPanel.showTaskScreen(); //Load the first trial currentTrialState = null; currentTrialPart = null; blockStart = true; blockNum = 0; currentTrial = -1; trialPhase = -1; nextTrial(); } @Override protected void performCleanup() { if(taskInputPanel.getSurpriseEntryComponent() != null) { taskInputPanel.getSurpriseEntryComponent().removeButtonActionListener(this); } if(groupSelectionPanel != null) { groupSelectionPanel.removeButtonActionListener(this); } } /** * Go to the next trial or trial part in the task. */ protected void nextTrial() { if(!conditionRunning) { return; } examController.setNavButtonEnabled(ButtonType.Back, false); examController.setNavButtonEnabled(ButtonType.Next, false); long currentTime = System.currentTimeMillis(); //Save data, validate data, and perform clean-up from the previous trial part boolean responseValid = true; if(currentTrialPart != null) { currentTrialPart.setTrialPartTime_ms(currentTrialPart.getTrialPartTime_ms() + (currentTime - trialPartStartTime)); if(currentTrialPart instanceof GroupProbeTrialPartState) { if(taskInputPanel.getGroupProbeComponent() != null) { GroupProbeTrialPartState groupProbe = (GroupProbeTrialPartState)currentTrialPart; groupProbe.setInteractionTimes(taskInputPanel.getGroupProbeComponent().getInteractionTimes()); if(!adjustingNormalizedSettings) { groupProbe.setPreviousSettings(groupProbe.getCurrentSettings()); } groupProbe.setCurrentSettings(taskInputPanel.getGroupProbeComponent().getCurrentSettings()); if(groupProbe.getCurrentNormalizedSettings() == null || groupProbe.getCurrentNormalizedSettings().size() != groupProbe.getCurrentSettings().size()) { groupProbe.setCurrentNormalizedSettings( ProbabilityUtils.createDefaultInitialProbabilities(groupProbe.getCurrentSettings().size())); } ProbabilityUtils.normalizePercentProbabilities(groupProbe.getCurrentSettings(), groupProbe.getCurrentNormalizedSettings()); previousSettings = groupProbe.getCurrentNormalizedSettings(); } } else if(currentTrialPart instanceof TroopSelectionMultiGroupTrialPartState) { //Validate that a group was selected GroupType selectedGroup = groupSelectionPanel.getSelectedGroup(); if(selectedGroup == null) { responseValid = false; } else { TroopSelectionMultiGroupTrialPartState troopProbe = (TroopSelectionMultiGroupTrialPartState)currentTrialPart; troopProbe.setTroopSelectionGroup(groupSelectionPanel.getSelectedGroup()); GroupType responsibleGroup = ((Task_1_2_3_ProbeTrialBase)currentTrialState.getTrial()).getGroundTruth().getResponsibleGroup(); if(examController.getScoreComputer() != null) { currentTrialState.setScore_s2(examController.getScoreComputer().computeTroopAllocationScoreS2_SingleGroupAllocation( troopProbe.getTroopSelectionGroup(), responsibleGroup)); } } } else if(currentTrialPart instanceof GroupCirclesProbeTrialPartState) { //Warn if group circles haven't been edited and we haven't already shown a warning if(warnIfCirclesOrCentersNotEdited) { warnIfCirclesOrCentersNotEdited = false; boolean circlesEdited = false; for(GroupCircleShape groupCircle : groupCircles) { if(groupCircle.circle.isShapeEdited()) { circlesEdited = true; } groupCircle.circle.setShapeEdited(false); } if(!circlesEdited) { //Show warning message if(JOptionPane.showConfirmDialog(examController.getParentWindow(), "
You have not edited the group circles.
" + "Would you like to continue anyway?
", "", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.NO_OPTION) { responseValid = false; } } } if(responseValid) { conditionPanel.getMapPanel().setGroupCirclesLayerEditable(false); } } else if(currentTrialPart instanceof GroupCentersProbeTrialPartState) { //Warn if group centers haven't been edited and we haven't already shown a warning if(warnIfCirclesOrCentersNotEdited) { warnIfCirclesOrCentersNotEdited = false; boolean centersEdited = false; for(GroupCenterPlacemark groupCenter : groupCenters) { if(groupCenter.isShapeEdited()) { centersEdited = true; } groupCenter.setShapeEdited(false); } if(!centersEdited) { //Show warning message if(JOptionPane.showConfirmDialog(examController.getParentWindow(), "
You have not edited the group centers.
" + "Would you like to continue anyway?
", "", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.NO_OPTION) { responseValid = false; } } } if(responseValid) { //First validate that the group centers are on roads double radius = conditionPanel.getMapPanel().getPlacemarkSize_gridUnits()/2.d; GroupCentersProbeTrialPartState centersProbe = (GroupCentersProbeTrialPartState)currentTrialPart; ArrayList roads = ((Task_3_Phase) task).getRoads(); LinkedList invalidCenters = new LinkedList(); for(GroupCenterPlacemark center : centersProbe.getGroupCenters()) { boolean onRoad = false; for(Road road : roads) { GridLocation2D closestRoadPoint = road.getClosestPoint(center.getCenterLocation(), radius); if(closestRoadPoint != null) { //Make sure the group center is centered on the road if it was slightly off center.setCenterLocation(closestRoadPoint); onRoad = true; break; } } if(!onRoad) { invalidCenters.add(center); } } conditionPanel.getMapPanel().redrawMap(); if(!invalidCenters.isEmpty()) { //One or more group centers is not on a road StringBuilder sb = createTrialNumberString(currentTrial+1, trialPhase+1, currentTrialState.getNumTrialParts(), "Centers"); if(invalidCenters.size() == 1) { sb.append("Please position the group center for "); } else { sb.append("Please position group centers for "); } int index = 0; for(GroupCenterPlacemark center : invalidCenters) { sb.append(" Group " + center.getFeature().getGroup().getGroupNameFull() + ""); if(index < invalidCenters.size() - 1) { if(index == invalidCenters.size() - 2) { sb.append(", and"); } else { sb.append(", "); } } index++; } sb.append(" on a road."); conditionPanel.setInstructionBannerText(sb.toString()); responseValid = false; } else { conditionPanel.getMapPanel().setGroupCentersLayerEditable(false); } } } else if(currentTrialPart instanceof SurpriseProbeTrialPartState) { if(taskInputPanel.getSurpriseEntryComponent() != null) { //Validate that a surprise value was entered if(taskInputPanel.getSurpriseEntryComponent().getSelectedIndex() < 0) { //conditionPanel.setInstructionBannerText("Please indicate your surprise and click Next to continue."); responseValid = false; } else { SurpriseProbeTrialPartState surpriseProbe = (SurpriseProbeTrialPartState)currentTrialPart; surpriseProbe.setCurrentSurprise(taskInputPanel.getSurpriseEntryComponent().getSelectedIndex()); taskInputPanel.getSurpriseEntryComponent().setEnabled(false); } } } } if(!responseValid) { //Don't advance if the response wasn't valid examController.setNavButtonEnabled(ButtonType.Next, true); trialPartStartTime = currentTime; return; } //Advance the trial phase counter trialPhase++; trialPartStartTime = currentTime; //Advance the trial counter if we're at the first trial, the current trial doesn't have any trial parts, //or we're at the last trial part of the current trial. if(currentTrial == -1 || (currentTrialState != null && (currentTrialState.getTrialParts() == null || trialPhase >= currentTrialState.getTrialParts().size()))) { if(currentTrialState != null) { currentTrialState.setTrialTime_ms(currentTime - trialStartTime); } currentTrial++; trialStartTime = currentTime; trialPhase = 0; if(trialStates == null || currentTrial >= trialStates.size()) { //We're at the end of the task conditionRunning = false; if(taskInputPanel.getSurpriseEntryComponent() != null) { taskInputPanel.getSurpriseEntryComponent().removeButtonActionListener(this); } if(groupSelectionPanel != null) { groupSelectionPanel.removeButtonActionListener(this); } // Fire condition completed event fireConditionEvent(new ConditionEvent(ConditionEvent.CONDITION_COMPLETED, currentTrial, this)); return; } else { //Set the current trial currentTrialState = trialStates.get(currentTrial); currentTrialPart = null; } } //Fire a trial changed event super.setTrial(currentTrial, trialPhase, currentTrialState.getNumTrialParts()); //Show the current trial or trial part if(currentTrialState instanceof AttackPresentationTrialState) { GroupAttack groupAttack = ((AttackLocationPresentationTrial)currentTrialState.getTrial()).getGroupAttack(); if(blockStart) { //Reset the map and hide the task input panel at the beginning of a block MapPanelContainer mapPanel = conditionPanel.getMapPanel(); mapPanel.restoresLayerZOrder(); mapPanel.setGroupCirclesLayerEditable(false); mapPanel.setGroupCentersLayerEditable(false); //Make group circles/centers semi-transparent if(groupCenters != null && !groupCenters.isEmpty()) { for(GroupCenterPlacemark groupCenter : groupCenters) { groupCenter.setTransparency(0.7f); } } if(groupCircles != null && !groupCircles.isEmpty()) { for(GroupCircleShape groupCircle : groupCircles) { groupCircle.circle.setTransparency(0.7f); } } mapPanel.redrawMap(); probeAttackLocation = null; taskInputPanel.setAllSubPanelsVisible(false); StringBuilder sb = createTrialNumberString(currentTrial+1, trialPhase+1, currentTrialState.getNumTrialParts(), "Attack"); /*if(currentTrial > 0) { sb.append("A new attack block has begun, and an attack by Group " + groupAttack.getGroup().getGroupNameFull() + " has occured. Click Next to continue."); } else {*/ sb.append("An attack by Group " + groupAttack.getGroup().getGroupNameFull() + " has occured. Click Next to continue."); //} conditionPanel.setInstructionBannerText(sb.toString()); blockStart = false; blockNum++; } else { StringBuilder sb = createTrialNumberString(currentTrial+1, trialPhase+1, currentTrialState.getNumTrialParts(), "Attack"); sb.append("An attack by Group " + groupAttack.getGroup().getGroupNameFull() + " has occured. Click Next to continue."); conditionPanel.setInstructionBannerText(sb.toString()); } //Append the attack location appendAttackLocation(groupAttack, false); } else { blockStart = true; //Go to the next part of the probe trial conditionPanel.setTaskInputPanelVisible(true); currentTrialPart = currentTrialState.getTrialParts().get(trialPhase); if(currentTrialPart instanceof GroupProbeTrialPartState) { GroupProbeTrialPartState groupProbe = (GroupProbeTrialPartState)currentTrialPart; //Append the unknown attack location if(probeAttackLocation == null) { appendAttackLocation(new GroupAttack(GroupType.Unknown, groupProbe.getProbe().getAttackLocation()), true); probeAttackLocation = prevAttackLocation; } //Show the group probe showGroupProbe(true, groupProbe.getProbe().getGroups(), groupProbe.getCurrentSettings(), groupProbe.getPreviousSettings()); StringBuilder sb = createTrialNumberString(currentTrial+1, trialPhase+1, currentTrialState.getNumTrialParts(), "Group Probe"); sb.append("An attack by an unknown group (?) has occurred. " + "Indicate the probability that each group is responsible for the attack, and click Next to continue."); conditionPanel.setInstructionBannerText(sb.toString()); } else if(currentTrialPart instanceof TroopSelectionMultiGroupTrialPartState) { //Show the troop selection probe TroopSelectionMultiGroupTrialPartState troopProbe = (TroopSelectionMultiGroupTrialPartState)currentTrialPart; showTroopSelectionProbe(troopProbe.getProbe().getGroups(), previousSettings, true); if(!groupSelectionPanel.isButtonActionListenerPresent(this)) { groupSelectionPanel.addButtonActionListener(this); } StringBuilder sb = createTrialNumberString(currentTrial+1, trialPhase+1, currentTrialState.getNumTrialParts(), "Send Troops"); sb.append("Using the radio buttons, allocate troops to one of the groups, and click Next to continue."); conditionPanel.setInstructionBannerText(sb.toString()); } else if(currentTrialPart instanceof ConfirmSettingsTrialPartState) { //Confirm the normalized settings for the group probe adjustingNormalizedSettings = false; ConfirmSettingsTrialPartState confirmSettingsProbe = (ConfirmSettingsTrialPartState)currentTrialPart; StringBuilder sb = createTrialNumberString(currentTrial+1, trialPhase+1, currentTrialState.getNumTrialParts(), "Confirm Settings"); if(confirmSettingsProbe.getProbabiltyProbe() instanceof GroupProbeTrialPartState) { ProbabilityProbeTrialPartState groupProbe = confirmSettingsProbe.getProbabiltyProbe(); taskInputPanel.getGroupProbeComponent().setCurrentSettings(groupProbe.getCurrentNormalizedSettings()); taskInputPanel.getGroupProbeComponent().showConfirmedProbabilities(); sb.append("Your probabilities have been normalized to sum to 100%. Click Back to adjust them or click Next to continue."); } conditionPanel.setInstructionBannerText(sb.toString()); examController.setNavButtonEnabled(ButtonType.Back, true); } else if(currentTrialPart instanceof GroupCirclesProbeTrialPartState) { //Show the group circles probe //Un-highlight the previous location if(prevAttackLocation != null && prevAttackLocation.isHighlighted()) { prevAttackLocation.setShowMarker(false); prevAttackLocation.setHighlighted(false); } warnIfCirclesOrCentersNotEdited = true; taskInputPanel.getGroupProbeComponent().showConfirmedProbabilities(); GroupCirclesProbeTrialPartState circlesProbe = (GroupCirclesProbeTrialPartState)currentTrialPart; if(circlesProbe.getProbe() != null) { showGroupCirclesProbe(circlesProbe); } StringBuilder sb = createTrialNumberString(currentTrial+1, trialPhase+1, currentTrialState.getNumTrialParts(), "Circles"); sb.append("Indicate your judgment of each group's spread by drawing a circle that captures the 2-to-1 boundary of attack. " + "Each group�s circle should enclose an area containing 2/3 of the attacks by that group; " + "1/3 of the attacks will be outside the circle. To move a circle, click and drag the middle point. " + "To resize a circle, click and drag the edge. Circles may overlap, and their edge may be placed off the screen. " + "Click Next to continue when you are ready."); //sb.append("Draw the 2-to-1 circle boundary for each group by clicking and dragging each" + // " group circle. Mouse over a circle and click and drag the middle point to move the circle. Click and drag the circle " + // "edge to resize the circle."); conditionPanel.setInstructionBannerText(sb.toString()); } else if(currentTrialPart instanceof GroupCentersProbeTrialPartState) { //Show the group centers probe //showGroupProbe(); //Un-highlight the previous location if(prevAttackLocation != null && prevAttackLocation.isHighlighted()) { prevAttackLocation.setShowMarker(false); prevAttackLocation.setHighlighted(false); } warnIfCirclesOrCentersNotEdited = true; taskInputPanel.getGroupProbeComponent().showConfirmedProbabilities(); GroupCentersProbeTrialPartState centersProbe = (GroupCentersProbeTrialPartState)currentTrialPart; if(centersProbe.getProbe() != null) { showGroupCentersProbe(centersProbe); } StringBuilder sb = createTrialNumberString(currentTrial+1, trialPhase+1, currentTrialState.getNumTrialParts(), "Centers"); sb.append("Locate the center of gravity for each group by clicking and dragging each" + " group center. The group centers of gravity should be positioned on a road. " + "Click Next to continue when you are ready."); conditionPanel.setInstructionBannerText(sb.toString()); } else if(currentTrialPart instanceof SurpriseProbeTrialPartState) { //Stop editing any group circles or centers conditionPanel.getMapPanel().setGroupCirclesLayerEditable(false); conditionPanel.getMapPanel().setGroupCentersLayerEditable(false); //Show the group responsible for the attack SurpriseProbeTrialPartState surpriseProbe = (SurpriseProbeTrialPartState)currentTrialPart; GroupType group = null; if(surpriseProbe.getGroundTruth() != null && surpriseProbe.getGroundTruth().getResponsibleGroup() != null && probeAttackLocation != null) { group = surpriseProbe.getGroundTruth().getResponsibleGroup(); probeAttackLocation.setName(group.toString()); Color color = ColorManager_Phase1.getGroupCenterColor(group); probeAttackLocation.setBorderColor(color); probeAttackLocation.setForegroundColor(color); if(WidgetConstants.USE_GROUP_SYMBOLS) { probeAttackLocation.setMarkerIcon(ImageManager_Phase1.getGroupSymbolImage(group, IconSize.Small)); probeAttackLocation.setShowName(false); } conditionPanel.getMapPanel().redrawMap(); } //Show the surprise probe SurpriseReportProbe probe = surpriseProbe.getProbe(); if(probe != null) { taskInputPanel.configureSurpriseEntryComponent( probe.getMinSurpriseValue(), probe.getMaxSurpriseValue(), probe.getSurpriseValueIncrement()); if(!taskInputPanel.getSurpriseEntryComponent().isButtonActionListenerPresent(this)) { taskInputPanel.getSurpriseEntryComponent().addButtonActionListener(this); } showSurpriseProbe(true, true, true); } StringBuilder sb = createTrialNumberString(currentTrial+1, trialPhase+1, currentTrialState.getNumTrialParts(), "Surprise"); if(group != null) { sb.append("Group " + group.getGroupNameFull() + " was responsible for the attack. " + "Indicate your surprise below by selecting a radio button and click Next to continue."); } else { sb.append("Indicate your surprise below by selecting a radio button and click Next to continue."); } conditionPanel.setInstructionBannerText(sb.toString()); } else if(currentTrialPart instanceof ShowScoreTrialPartState) { //Show the score (S2) for the probe trial TrialState_Phase1 trial = ((ShowScoreTrialPartState)currentTrialPart).getTrial(); long score = 0; if(trial.getScore_s2() != null) { score = Math.round(trial.getScore_s2()); } StringBuilder sb = createTrialNumberString(currentTrial+1, trialPhase+1, currentTrialState.getNumTrialParts(), "Score"); sb.append("You received " + score + " out of 100 points on this trial for " + "allocating troops. Click Next to continue."); conditionPanel.setInstructionBannerText(sb.toString()); } } //Pause before allowing a next button press if(currentTrialPart instanceof GroupProbeTrialPartState) { if(!adjustingNormalizedSettings) { //Increase pause length when we start the probe trial pauseBeforeNextTrial(2000); } else { //Pause for the standard amount of time pauseBeforeNextTrial(); } } else if(currentTrialPart instanceof TroopSelectionMultiGroupTrialPartState) { //Disable next button until group is selected examController.setNavButtonEnabled(ButtonType.Next, false); } else if(currentTrialPart instanceof SurpriseProbeTrialPartState) { //Disable next button until surprise value is entered examController.setNavButtonEnabled(ButtonType.Next, false); } else { //Pause for the standard amount of time pauseBeforeNextTrial(); } } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() instanceof JRadioButton) { //IProbabilityEntryContainer troopComponent = taskInputPanel.getTroopAllocationMultiGroupComponent(); IProbabilityEntryContainer troopComponent = taskInputPanel.getPreviousTroopAllocationComponent(); List troopAllocations = troopComponent.getCurrentSettings(); GroupType selectedGroup = groupSelectionPanel.getSelectedGroup(); int selectedGroupIndex = -1; if(selectedGroup != null) { selectedGroupIndex = groupSelectionPanel.getGroups().indexOf(selectedGroup); } for(int i=0; i groups, List currentSettings, List previousSettings) { if(settingsChanged) { taskInputPanel.setGroupsForGroupProbeComponent(groups); taskInputPanel.getGroupProbeComponent().setCurrentSettings(currentSettings); taskInputPanel.getGroupProbeComponent().setPreviousSettings(previousSettings); } if(!adjustingNormalizedSettings) { //System.out.println("resetting interaction times"); taskInputPanel.getGroupProbeComponent().resetInteractionTimes(); } taskInputPanel.setGroupsForPreviousSettingsComponent(groups); taskInputPanel.getGroupProbeComponent().setTopTitle("your probabilities"); taskInputPanel.getGroupProbeComponent().showEditableProbabilities(); taskInputPanel.getGroupProbeComponent().setSumVisible(true); taskInputPanel.setSubPanelComponent(0, taskInputPanel.getGroupProbeComponent()); taskInputPanel.setSubPanelVisible(0, true); taskInputPanel.setSubPanelVisible(1, false); taskInputPanel.setSubPanelVisible(2, false); taskInputPanel.setSubPanelVisible(3, false); } protected void showTroopSelectionProbe(List groups, List previousSettings, boolean showPreviousSettings) { groupSelectionPanel.setGroups(groups); taskInputPanel.setSubPanelComponent(0, groupSelectionPanel, BorderLayout.CENTER); /*taskInputPanel.setGroupsForTroopAllocationMultiGroupComponent(groups); taskInputPanel.getTroopAllocationMultiGroupComponent().setCurrentSettings( CPSUtils.createProbabilities(groups.size(), 0)); taskInputPanel.getTroopAllocationMultiGroupComponent().showConfirmedProbabilities(); taskInputPanel.getTroopAllocationMultiGroupComponent().setSumVisible(false); taskInputPanel.setSubPanelComponent(1, taskInputPanel.getTroopAllocationMultiGroupComponent());*/ taskInputPanel.setGroupsForPreviousTroopAllocationComponent(groups); taskInputPanel.getPreviousTroopAllocationComponent().setCurrentSettings( ProbabilityUtils.createProbabilities(groups.size(), 0)); taskInputPanel.setSubPanelComponent(1, taskInputPanel.getPreviousTroopAllocationComponent()); if(showPreviousSettings) { taskInputPanel.getPreviousSettingsComponent().setTopTitle("your probabilities"); taskInputPanel.getPreviousSettingsComponent().setCurrentSettings(previousSettings); taskInputPanel.getPreviousSettingsComponent().showConfirmedProbabilities(); taskInputPanel.setSubPanelComponent(2, taskInputPanel.getPreviousSettingsComponent()); } taskInputPanel.setSubPanelVisible(0, true); taskInputPanel.setSubPanelVisible(1, true); taskInputPanel.setSubPanelVisible(2, showPreviousSettings); taskInputPanel.setSubPanelVisible(3, false); } protected void showGroupCirclesProbe(GroupCirclesProbeTrialPartState circlesProbe) { ArrayList groups = null; if(circlesProbe.getProbe() != null) { groups = circlesProbe.getProbe().getGroups(); } //Add the group circles layer MapPanelContainer mapPanel = conditionPanel.getMapPanel(); mapPanel.setGroupCirclesLayerEnabled(true); mapPanel.setGroupCirclesLayerEditable(true); //Add initial group circles for each group at the bottom of the map if(blockNum == 1) { if(groups != null && !groups.isEmpty()) { mapPanel.removeAllGroupCircles(); groupCircles = new ArrayList(groups.size()); GridSize gridSize = mapPanel.getGridSize(); double radius = gridSize.getGridWidth() / 20; double diameter = radius * 2; double spacing = 3; double xPos = (gridSize.getGridWidth() - (groups.size() * diameter + (groups.size() - 1) * spacing)) / 2 + radius; double yPos = radius + (spacing * 2); for(GroupType group : groups) { GroupCircle groupCircle = new GroupCircle(group, new GridLocation2D(xPos, yPos), (double)radius); groupCircles.add(new GroupCircleShape(group, mapPanel.addGroupCircle(groupCircle, true))); xPos += diameter + spacing; } } } else { //Clone the current group circles, and reset the edited state and edit time for each circle mapPanel.removeAllGroupCircles(); ArrayList groupCirclesCopy = new ArrayList(groupCircles.size()); for(GroupCircleShape groupCircle : groupCircles) { GroupCircle groupCircleCopy = new GroupCircle(groupCircle.getGroup(), new GridLocation2D(groupCircle.circle.getCenterLocation()), groupCircle.circle.getRadius()); groupCirclesCopy.add(new GroupCircleShape(groupCircle.getGroup(), mapPanel.addGroupCircle(groupCircleCopy, true))); //groupCircle.circle.setShapeEdited(false); //groupCircle.circle.setEditTime(0); //groupCircle.circle.setTransparency(1.f); } groupCircles = groupCirclesCopy; } circlesProbe.setGroupCircles(groupCircles); mapPanel.redrawMap(); } protected void showGroupCentersProbe(GroupCentersProbeTrialPartState centersProbe) { ArrayList groups = null; if(centersProbe.getProbe() != null) { groups = centersProbe.getProbe().getGroups(); } //Add the group centers layer and legend items MapPanelContainer mapPanel = conditionPanel.getMapPanel(); mapPanel.setGroupCentersLayerEnabled(true); mapPanel.setGroupCentersLayerEditable(true); //mapPanel.setGroupCentersLegendItemVisible(true); //mapPanel.setGroupCenterGroupsForLegend(groups); //Add initial group centers for each group at the bottom of the map if(blockNum == 1) { mapPanel.removeAllGroupCenters(); if(groups != null && !groups.isEmpty()) { groupCenters = new ArrayList(groups.size()); GridSize gridSize = mapPanel.getGridSize(); double diameter = (int)mapPanel.translateToGridUnits(MapConstants_Phase1.PLACEMARK_SIZE_PIXELS); double radius = diameter / 2; double spacing = 3; double xPos = (gridSize.getGridWidth() - (groups.size() * diameter + (groups.size() - 1) * spacing)) / 2 + radius; double yPos = radius + (spacing * 2); for(GroupType group : groups) { GroupCenter groupCenter = new GroupCenter(group, new GridLocation2D(xPos, yPos)); groupCenters.add(mapPanel.addGroupCenter(groupCenter, false, true)); xPos += diameter + spacing; } } } else { //Clone the current group centers, and reset the edited state and edit time for each center mapPanel.removeAllGroupCenters(); ArrayList groupCentersCopy = new ArrayList(groupCenters.size()); for(GroupCenterPlacemark groupCenter : groupCenters) { GroupCenter groupCenterCopy = new GroupCenter(groupCenter.getFeature().getGroup(), new GridLocation2D(groupCenter.getCenterLocation())); groupCentersCopy.add(mapPanel.addGroupCenter(groupCenterCopy, false, true)); //groupCenter.setShapeEdited(false); //groupCenter.setEditTime(0); //groupCenter.setTransparency(1.f); } groupCenters = groupCentersCopy; } centersProbe.setGroupCenters(groupCenters); mapPanel.redrawMap(); } protected void showSurpriseProbe(boolean showTroopAllocation, boolean showPreviousSettings, boolean showPreviousSettinsAsFinalSettings) { taskInputPanel.setSubPanelComponent(0, taskInputPanel.getSurpriseEntryComponent()); taskInputPanel.getSurpriseEntryComponent().setEnabled(true); if(showTroopAllocation) { /*taskInputPanel.getTroopAllocationMultiGroupComponent().showConfirmedProbabilities(); taskInputPanel.getTroopAllocationMultiGroupComponent().setSumVisible(false); taskInputPanel.setSubPanelComponent(1, taskInputPanel.getTroopAllocationMultiGroupComponent());*/ taskInputPanel.setSubPanelComponent(1, taskInputPanel.getPreviousTroopAllocationComponent()); } if(showPreviousSettings) { taskInputPanel.getPreviousSettingsComponent().setCurrentSettings(previousSettings); if(showPreviousSettinsAsFinalSettings) { taskInputPanel.getPreviousSettingsComponent().setTopTitle("your probabilities"); } else { taskInputPanel.getPreviousSettingsComponent().setTopTitle("your previous probabilities"); } taskInputPanel.getPreviousSettingsComponent().showConfirmedProbabilities(); taskInputPanel.setSubPanelComponent(2, taskInputPanel.getPreviousSettingsComponent()); } taskInputPanel.setSubPanelVisible(0, true); taskInputPanel.setSubPanelVisible(1, showTroopAllocation); taskInputPanel.setSubPanelVisible(2, showPreviousSettings); taskInputPanel.setSubPanelVisible(3, false); } }/* * Copyright 2011 . All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ package org.burstsort4j.benchmark; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Runs performance tests over several kinds of data for each of the * sort implementations, collecting run times and displaying the results. * * @author */ public class MacroBenchmark { /** * Creates a new instance of MacroBenchmark. */ private MacroBenchmark() { } /** * Command-line interface to benchmark driver. * * @param args command-line arguments. */ public static void main(String[] args) { DataGenerator[] generators = { DataGenerator.RANDOM, DataGenerator.REPEAT, DataGenerator.REPEAT_CYCLE, DataGenerator.PSEUDO_WORD, DataGenerator.GENOME, DataGenerator.SMALL_ALPHABET, DataGenerator.MEDIAN_OF_3_KILLER }; // limit to those that perform reasonably well with larger data sets SortRunner[] runners = { SortRunner.HEAP, SortRunner.INTRO, SortRunner.QUICK, SortRunner.QUICK_2_PIVOT, SortRunner.MULTIKEY }; // use data sizes larger than micro but not huge DataSize[] sizes = { DataSize.N_1000, DataSize.N_4000, DataSize.N_16000, DataSize.N_64000, DataSize.N_256000 }; if (args.length > 0) { // Parse the command line arguments. int i = 0; while (i < args.length) { if (args[i].equals("--data")) { i++; if (i >= args.length) { usage("Missing --data argument"); } Pattern p = Pattern.compile(args[i], Pattern.CASE_INSENSITIVE); List list = new ArrayList(); for (DataGenerator generator : generators) { Matcher m = p.matcher(generator.getDisplayName()); if (m.find()) { list.add(generator); } } generators = list.toArray(new DataGenerator[list.size()]); } else if (args[i].equals("--sort")) { i++; if (i >= args.length) { usage("Missing --sort argument"); } Pattern p = Pattern.compile(args[i], Pattern.CASE_INSENSITIVE); List list = new ArrayList(); for (SortRunner runner : runners) { Matcher m = p.matcher(runner.getDisplayName()); if (m.find()) { list.add(runner); } } runners = list.toArray(new SortRunner[list.size()]); } else if (args[i].equals("--list")) { System.out.println("Data sets"); for (DataGenerator generator : generators) { System.out.format("\t%s\n", generator.getDisplayName()); } System.out.println("Sorting algorithms"); for (SortRunner runner : runners) { System.out.format("\t%s\n", runner.getDisplayName()); } System.exit(0); } else if (args[i].equals("--help")) { usage(); } else { usage("Unrecognized option: " + args[i]); } i++; } } // Warm up the JVM so that the code (hopefully) gets compiled. System.out.println("Warming up the system, please wait..."); for (DataGenerator generator : generators) { String[] dataSet = generator.generate(DataSize.N_400); String[] input = new String[dataSet.length]; for (SortRunner runner : runners) { for (int i = 0; i < 1000; i++) { System.arraycopy(dataSet, 0, input, 0, input.length); runner.sort(input); } } } // Avoid recreating the input arrays over and over again. Map inputSets = new EnumMap(DataSize.class); for (DataSize size : DataSize.values()) { inputSets.put(size, new String[size.getValue()]); } // For each type of data set, and each data set size, and // each sort implementation, run the sort many times and // calculate an average. for (DataGenerator generator : generators) { System.out.format("%s...\n", generator.getDisplayName()); for (DataSize size : sizes) { // Must generate the data for each size since some // generators use it to form a pattern. final String[] dataSet = generator.generate(size); System.out.format("\t%s...\n", size.toString()); final String[] input = inputSets.get(size); for (final SortRunner runner : runners) { System.out.format("\t\t%-20s:\t", runner.getDisplayName()); final SortRunner func = runner; BenchmarkRunnable r = new BenchmarkRunnable() { @Override public void run(BenchmarkData b) { for (int i = 0; i < b.count(); i++) { b.stopTimer(); System.arraycopy(dataSet, 0, input, 0, input.length); b.startTimer(); func.sort(input); } } }; BenchmarkData bench = new BenchmarkData(r); BenchmarkResult result = bench.run(); System.out.format("%8d\t%10d ns/op\n", result.count(), result.nsPerOp()); } } } } /** * Display an error message and the usage information. */ private static void usage(String msg) { System.out.println(msg); usage(); } /** * Display the usage information. */ private static void usage() { System.out.println("Usage: MacroBenchmark [options]"); System.out.println("\t--data "); System.out.println("\t\tSelect the data set whose name matches the regular expression."); System.out.println("\t\tFor example, '--data random' would use only the random data set."); System.out.println("\t--help"); System.out.println("\t\tDisplay this usage information."); System.out.println("\t--list"); System.out.println("\t\tDisplay a list of the supported data sets and sorting algorithms."); System.out.println("\t--sort "); System.out.println("\t\tSelect the sort algorithms whose name matches the regular"); System.out.println("\t\texpression. For example, '--sort (comb|insert)' would run"); System.out.println("\t\tboth versions of the insertion and comb sort algorithms."); System.exit(0); } } z875479694h/SpringBoot-Shiro-JWT-Scaffoldingutil/src/main/java/xyz/hcworld/util/IpUtil.java package xyz.hcworld.util; import javax.servlet.http.HttpServletRequest; /** * ip获取类 * @ClassName: IpUtil * @Author: 张红尘 * @Date: 2021-05-06 * @Version: 1.0 */ public class IpUtil { /** * 未知ip */ private final static String UNKNOWN = "unknown"; /** * 解析Header的数据获取真实ip * @param request * @return */ public static String getIp(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } } package openfoodfacts.github.scrachx.openfood.models; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.util.ArrayList; import java.util.List; import openfoodfacts.github.scrachx.openfood.network.deserializers.LabelsWrapperDeserializer; /** * Created by Lobster on 03.03.18. */ @JsonDeserialize(using = LabelsWrapperDeserializer.class) public class LabelsWrapper { private List labels; public List